1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkSecondaryStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use ::git::{status::FileStatus, Restore};
77use code_context_menus::{
78 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
79 CompletionsMenu, ContextMenuOrigin,
80};
81use git::blame::GitBlame;
82use gpui::{
83 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
84 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
85 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
86 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
87 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
88 ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
89 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
90 WeakEntity, WeakFocusHandle, Window,
91};
92use highlight_matching_bracket::refresh_matching_bracket_highlights;
93use hover_popover::{hide_hover, HoverState};
94use indent_guides::ActiveIndentGuidesState;
95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
96pub use inline_completion::Direction;
97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
98pub use items::MAX_TAB_TITLE_LEN;
99use itertools::Itertools;
100use language::{
101 language_settings::{
102 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
103 },
104 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
105 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, DiskState,
106 EditPredictionsMode, EditPreview, HighlightedText, IndentKind, IndentSize, Language,
107 OffsetRangeExt, Point, Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
108};
109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
110use linked_editing_ranges::refresh_linked_ranges;
111use mouse_context_menu::MouseContextMenu;
112use persistence::DB;
113pub use proposed_changes_editor::{
114 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
115};
116use smallvec::smallvec;
117use std::iter::Peekable;
118use task::{ResolvedTask, TaskTemplate, TaskVariables};
119
120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
121pub use lsp::CompletionContext;
122use lsp::{
123 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
124 LanguageServerId, LanguageServerName,
125};
126
127use language::BufferSnapshot;
128use movement::TextLayoutDetails;
129pub use multi_buffer::{
130 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
131 ToOffset, ToPoint,
132};
133use multi_buffer::{
134 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
135 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
136};
137use project::{
138 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
139 project_settings::{GitGutterSetting, ProjectSettings},
140 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
141 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
142};
143use rand::prelude::*;
144use rpc::{proto::*, ErrorExt};
145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
146use selections_collection::{
147 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
148};
149use serde::{Deserialize, Serialize};
150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
151use smallvec::SmallVec;
152use snippet::Snippet;
153use std::{
154 any::TypeId,
155 borrow::Cow,
156 cell::RefCell,
157 cmp::{self, Ordering, Reverse},
158 mem,
159 num::NonZeroU32,
160 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
161 path::{Path, PathBuf},
162 rc::Rc,
163 sync::Arc,
164 time::{Duration, Instant},
165};
166pub use sum_tree::Bias;
167use sum_tree::TreeMap;
168use text::{BufferId, OffsetUtf16, Rope};
169use theme::{
170 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
171 ThemeColors, ThemeSettings,
172};
173use ui::{
174 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
175 Tooltip,
176};
177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
178use workspace::{
179 item::{ItemHandle, PreviewTabsSettings},
180 ItemId, RestoreOnStartupBehavior,
181};
182use workspace::{
183 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
184 WorkspaceSettings,
185};
186use workspace::{
187 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
188};
189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
190
191use crate::hover_links::{find_url, find_url_from_range};
192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
193
194pub const FILE_HEADER_HEIGHT: u32 = 2;
195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
199const MAX_LINE_LEN: usize = 1024;
200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
203#[doc(hidden)]
204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
205
206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
208
209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
211
212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
213 alt: true,
214 shift: true,
215 control: false,
216 platform: false,
217 function: false,
218};
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
221pub enum InlayId {
222 InlineCompletion(usize),
223 Hint(usize),
224}
225
226impl InlayId {
227 fn id(&self) -> usize {
228 match self {
229 Self::InlineCompletion(id) => *id,
230 Self::Hint(id) => *id,
231 }
232 }
233}
234
235enum DocumentHighlightRead {}
236enum DocumentHighlightWrite {}
237enum InputComposition {}
238enum SelectedTextHighlight {}
239
240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
241pub enum Navigated {
242 Yes,
243 No,
244}
245
246impl Navigated {
247 pub fn from_bool(yes: bool) -> Navigated {
248 if yes {
249 Navigated::Yes
250 } else {
251 Navigated::No
252 }
253 }
254}
255
256pub fn init_settings(cx: &mut App) {
257 EditorSettings::register(cx);
258}
259
260pub fn init(cx: &mut App) {
261 init_settings(cx);
262
263 workspace::register_project_item::<Editor>(cx);
264 workspace::FollowableViewRegistry::register::<Editor>(cx);
265 workspace::register_serializable_item::<Editor>(cx);
266
267 cx.observe_new(
268 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
269 workspace.register_action(Editor::new_file);
270 workspace.register_action(Editor::new_file_vertical);
271 workspace.register_action(Editor::new_file_horizontal);
272 workspace.register_action(Editor::cancel_language_server_work);
273 },
274 )
275 .detach();
276
277 cx.on_action(move |_: &workspace::NewFile, cx| {
278 let app_state = workspace::AppState::global(cx);
279 if let Some(app_state) = app_state.upgrade() {
280 workspace::open_new(
281 Default::default(),
282 app_state,
283 cx,
284 |workspace, window, cx| {
285 Editor::new_file(workspace, &Default::default(), window, cx)
286 },
287 )
288 .detach();
289 }
290 });
291 cx.on_action(move |_: &workspace::NewWindow, cx| {
292 let app_state = workspace::AppState::global(cx);
293 if let Some(app_state) = app_state.upgrade() {
294 workspace::open_new(
295 Default::default(),
296 app_state,
297 cx,
298 |workspace, window, cx| {
299 cx.activate(true);
300 Editor::new_file(workspace, &Default::default(), window, cx)
301 },
302 )
303 .detach();
304 }
305 });
306}
307
308pub struct SearchWithinRange;
309
310trait InvalidationRegion {
311 fn ranges(&self) -> &[Range<Anchor>];
312}
313
314#[derive(Clone, Debug, PartialEq)]
315pub enum SelectPhase {
316 Begin {
317 position: DisplayPoint,
318 add: bool,
319 click_count: usize,
320 },
321 BeginColumnar {
322 position: DisplayPoint,
323 reset: bool,
324 goal_column: u32,
325 },
326 Extend {
327 position: DisplayPoint,
328 click_count: usize,
329 },
330 Update {
331 position: DisplayPoint,
332 goal_column: u32,
333 scroll_delta: gpui::Point<f32>,
334 },
335 End,
336}
337
338#[derive(Clone, Debug)]
339pub enum SelectMode {
340 Character,
341 Word(Range<Anchor>),
342 Line(Range<Anchor>),
343 All,
344}
345
346#[derive(Copy, Clone, PartialEq, Eq, Debug)]
347pub enum EditorMode {
348 SingleLine { auto_width: bool },
349 AutoHeight { max_lines: usize },
350 Full,
351}
352
353#[derive(Copy, Clone, Debug)]
354pub enum SoftWrap {
355 /// Prefer not to wrap at all.
356 ///
357 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
358 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
359 GitDiff,
360 /// Prefer a single line generally, unless an overly long line is encountered.
361 None,
362 /// Soft wrap lines that exceed the editor width.
363 EditorWidth,
364 /// Soft wrap lines at the preferred line length.
365 Column(u32),
366 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
367 Bounded(u32),
368}
369
370#[derive(Clone)]
371pub struct EditorStyle {
372 pub background: Hsla,
373 pub local_player: PlayerColor,
374 pub text: TextStyle,
375 pub scrollbar_width: Pixels,
376 pub syntax: Arc<SyntaxTheme>,
377 pub status: StatusColors,
378 pub inlay_hints_style: HighlightStyle,
379 pub inline_completion_styles: InlineCompletionStyles,
380 pub unnecessary_code_fade: f32,
381}
382
383impl Default for EditorStyle {
384 fn default() -> Self {
385 Self {
386 background: Hsla::default(),
387 local_player: PlayerColor::default(),
388 text: TextStyle::default(),
389 scrollbar_width: Pixels::default(),
390 syntax: Default::default(),
391 // HACK: Status colors don't have a real default.
392 // We should look into removing the status colors from the editor
393 // style and retrieve them directly from the theme.
394 status: StatusColors::dark(),
395 inlay_hints_style: HighlightStyle::default(),
396 inline_completion_styles: InlineCompletionStyles {
397 insertion: HighlightStyle::default(),
398 whitespace: HighlightStyle::default(),
399 },
400 unnecessary_code_fade: Default::default(),
401 }
402 }
403}
404
405pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
406 let show_background = language_settings::language_settings(None, None, cx)
407 .inlay_hints
408 .show_background;
409
410 HighlightStyle {
411 color: Some(cx.theme().status().hint),
412 background_color: show_background.then(|| cx.theme().status().hint_background),
413 ..HighlightStyle::default()
414 }
415}
416
417pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
418 InlineCompletionStyles {
419 insertion: HighlightStyle {
420 color: Some(cx.theme().status().predictive),
421 ..HighlightStyle::default()
422 },
423 whitespace: HighlightStyle {
424 background_color: Some(cx.theme().status().created_background),
425 ..HighlightStyle::default()
426 },
427 }
428}
429
430type CompletionId = usize;
431
432pub(crate) enum EditDisplayMode {
433 TabAccept,
434 DiffPopover,
435 Inline,
436}
437
438enum InlineCompletion {
439 Edit {
440 edits: Vec<(Range<Anchor>, String)>,
441 edit_preview: Option<EditPreview>,
442 display_mode: EditDisplayMode,
443 snapshot: BufferSnapshot,
444 },
445 Move {
446 target: Anchor,
447 snapshot: BufferSnapshot,
448 },
449}
450
451struct InlineCompletionState {
452 inlay_ids: Vec<InlayId>,
453 completion: InlineCompletion,
454 completion_id: Option<SharedString>,
455 invalidation_range: Range<Anchor>,
456}
457
458enum EditPredictionSettings {
459 Disabled,
460 Enabled {
461 show_in_menu: bool,
462 preview_requires_modifier: bool,
463 },
464}
465
466enum InlineCompletionHighlight {}
467
468#[derive(Debug, Clone)]
469struct InlineDiagnostic {
470 message: SharedString,
471 group_id: usize,
472 is_primary: bool,
473 start: Point,
474 severity: DiagnosticSeverity,
475}
476
477pub enum MenuInlineCompletionsPolicy {
478 Never,
479 ByProvider,
480}
481
482pub enum EditPredictionPreview {
483 /// Modifier is not pressed
484 Inactive,
485 /// Modifier pressed
486 Active {
487 previous_scroll_position: Option<ScrollAnchor>,
488 },
489}
490
491#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
492struct EditorActionId(usize);
493
494impl EditorActionId {
495 pub fn post_inc(&mut self) -> Self {
496 let answer = self.0;
497
498 *self = Self(answer + 1);
499
500 Self(answer)
501 }
502}
503
504// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
505// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
506
507type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
508type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
509
510#[derive(Default)]
511struct ScrollbarMarkerState {
512 scrollbar_size: Size<Pixels>,
513 dirty: bool,
514 markers: Arc<[PaintQuad]>,
515 pending_refresh: Option<Task<Result<()>>>,
516}
517
518impl ScrollbarMarkerState {
519 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
520 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
521 }
522}
523
524#[derive(Clone, Debug)]
525struct RunnableTasks {
526 templates: Vec<(TaskSourceKind, TaskTemplate)>,
527 offset: multi_buffer::Anchor,
528 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
529 column: u32,
530 // Values of all named captures, including those starting with '_'
531 extra_variables: HashMap<String, String>,
532 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
533 context_range: Range<BufferOffset>,
534}
535
536impl RunnableTasks {
537 fn resolve<'a>(
538 &'a self,
539 cx: &'a task::TaskContext,
540 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
541 self.templates.iter().filter_map(|(kind, template)| {
542 template
543 .resolve_task(&kind.to_id_base(), cx)
544 .map(|task| (kind.clone(), task))
545 })
546 }
547}
548
549#[derive(Clone)]
550struct ResolvedTasks {
551 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
552 position: Anchor,
553}
554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
555struct BufferOffset(usize);
556
557// Addons allow storing per-editor state in other crates (e.g. Vim)
558pub trait Addon: 'static {
559 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
560
561 fn render_buffer_header_controls(
562 &self,
563 _: &ExcerptInfo,
564 _: &Window,
565 _: &App,
566 ) -> Option<AnyElement> {
567 None
568 }
569
570 fn to_any(&self) -> &dyn std::any::Any;
571}
572
573#[derive(Debug, Copy, Clone, PartialEq, Eq)]
574pub enum IsVimMode {
575 Yes,
576 No,
577}
578
579/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
580///
581/// See the [module level documentation](self) for more information.
582pub struct Editor {
583 focus_handle: FocusHandle,
584 last_focused_descendant: Option<WeakFocusHandle>,
585 /// The text buffer being edited
586 buffer: Entity<MultiBuffer>,
587 /// Map of how text in the buffer should be displayed.
588 /// Handles soft wraps, folds, fake inlay text insertions, etc.
589 pub display_map: Entity<DisplayMap>,
590 pub selections: SelectionsCollection,
591 pub scroll_manager: ScrollManager,
592 /// When inline assist editors are linked, they all render cursors because
593 /// typing enters text into each of them, even the ones that aren't focused.
594 pub(crate) show_cursor_when_unfocused: bool,
595 columnar_selection_tail: Option<Anchor>,
596 add_selections_state: Option<AddSelectionsState>,
597 select_next_state: Option<SelectNextState>,
598 select_prev_state: Option<SelectNextState>,
599 selection_history: SelectionHistory,
600 autoclose_regions: Vec<AutocloseRegion>,
601 snippet_stack: InvalidationStack<SnippetState>,
602 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
603 ime_transaction: Option<TransactionId>,
604 active_diagnostics: Option<ActiveDiagnosticGroup>,
605 show_inline_diagnostics: bool,
606 inline_diagnostics_update: Task<()>,
607 inline_diagnostics_enabled: bool,
608 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
609 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
610
611 // TODO: make this a access method
612 pub project: Option<Entity<Project>>,
613 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
614 completion_provider: Option<Box<dyn CompletionProvider>>,
615 collaboration_hub: Option<Box<dyn CollaborationHub>>,
616 blink_manager: Entity<BlinkManager>,
617 show_cursor_names: bool,
618 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
619 pub show_local_selections: bool,
620 mode: EditorMode,
621 show_breadcrumbs: bool,
622 show_gutter: bool,
623 show_scrollbars: bool,
624 show_line_numbers: Option<bool>,
625 use_relative_line_numbers: Option<bool>,
626 show_git_diff_gutter: Option<bool>,
627 show_code_actions: Option<bool>,
628 show_runnables: Option<bool>,
629 show_wrap_guides: Option<bool>,
630 show_indent_guides: Option<bool>,
631 placeholder_text: Option<Arc<str>>,
632 highlight_order: usize,
633 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
634 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
635 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
636 scrollbar_marker_state: ScrollbarMarkerState,
637 active_indent_guides_state: ActiveIndentGuidesState,
638 nav_history: Option<ItemNavHistory>,
639 context_menu: RefCell<Option<CodeContextMenu>>,
640 mouse_context_menu: Option<MouseContextMenu>,
641 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
642 signature_help_state: SignatureHelpState,
643 auto_signature_help: Option<bool>,
644 find_all_references_task_sources: Vec<Anchor>,
645 next_completion_id: CompletionId,
646 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
647 code_actions_task: Option<Task<Result<()>>>,
648 selection_highlight_task: Option<Task<()>>,
649 document_highlights_task: Option<Task<()>>,
650 linked_editing_range_task: Option<Task<Option<()>>>,
651 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
652 pending_rename: Option<RenameState>,
653 searchable: bool,
654 cursor_shape: CursorShape,
655 current_line_highlight: Option<CurrentLineHighlight>,
656 collapse_matches: bool,
657 autoindent_mode: Option<AutoindentMode>,
658 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
659 input_enabled: bool,
660 use_modal_editing: bool,
661 read_only: bool,
662 leader_peer_id: Option<PeerId>,
663 remote_id: Option<ViewId>,
664 hover_state: HoverState,
665 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
666 gutter_hovered: bool,
667 hovered_link_state: Option<HoveredLinkState>,
668 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
669 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
670 active_inline_completion: Option<InlineCompletionState>,
671 /// Used to prevent flickering as the user types while the menu is open
672 stale_inline_completion_in_menu: Option<InlineCompletionState>,
673 edit_prediction_settings: EditPredictionSettings,
674 inline_completions_hidden_for_vim_mode: bool,
675 show_inline_completions_override: Option<bool>,
676 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
677 edit_prediction_preview: EditPredictionPreview,
678 edit_prediction_indent_conflict: bool,
679 edit_prediction_requires_modifier_in_indent_conflict: bool,
680 inlay_hint_cache: InlayHintCache,
681 next_inlay_id: usize,
682 _subscriptions: Vec<Subscription>,
683 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
684 gutter_dimensions: GutterDimensions,
685 style: Option<EditorStyle>,
686 text_style_refinement: Option<TextStyleRefinement>,
687 next_editor_action_id: EditorActionId,
688 editor_actions:
689 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
690 use_autoclose: bool,
691 use_auto_surround: bool,
692 auto_replace_emoji_shortcode: bool,
693 show_git_blame_gutter: bool,
694 show_git_blame_inline: bool,
695 show_git_blame_inline_delay_task: Option<Task<()>>,
696 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
697 git_blame_inline_enabled: bool,
698 serialize_dirty_buffers: bool,
699 show_selection_menu: Option<bool>,
700 blame: Option<Entity<GitBlame>>,
701 blame_subscription: Option<Subscription>,
702 custom_context_menu: Option<
703 Box<
704 dyn 'static
705 + Fn(
706 &mut Self,
707 DisplayPoint,
708 &mut Window,
709 &mut Context<Self>,
710 ) -> Option<Entity<ui::ContextMenu>>,
711 >,
712 >,
713 last_bounds: Option<Bounds<Pixels>>,
714 last_position_map: Option<Rc<PositionMap>>,
715 expect_bounds_change: Option<Bounds<Pixels>>,
716 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
717 tasks_update_task: Option<Task<()>>,
718 in_project_search: bool,
719 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
720 breadcrumb_header: Option<String>,
721 focused_block: Option<FocusedBlock>,
722 next_scroll_position: NextScrollCursorCenterTopBottom,
723 addons: HashMap<TypeId, Box<dyn Addon>>,
724 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
725 load_diff_task: Option<Shared<Task<()>>>,
726 selection_mark_mode: bool,
727 toggle_fold_multiple_buffers: Task<()>,
728 _scroll_cursor_center_top_bottom_task: Task<()>,
729 serialize_selections: Task<()>,
730}
731
732#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
733enum NextScrollCursorCenterTopBottom {
734 #[default]
735 Center,
736 Top,
737 Bottom,
738}
739
740impl NextScrollCursorCenterTopBottom {
741 fn next(&self) -> Self {
742 match self {
743 Self::Center => Self::Top,
744 Self::Top => Self::Bottom,
745 Self::Bottom => Self::Center,
746 }
747 }
748}
749
750#[derive(Clone)]
751pub struct EditorSnapshot {
752 pub mode: EditorMode,
753 show_gutter: bool,
754 show_line_numbers: Option<bool>,
755 show_git_diff_gutter: Option<bool>,
756 show_code_actions: Option<bool>,
757 show_runnables: Option<bool>,
758 git_blame_gutter_max_author_length: Option<usize>,
759 pub display_snapshot: DisplaySnapshot,
760 pub placeholder_text: Option<Arc<str>>,
761 is_focused: bool,
762 scroll_anchor: ScrollAnchor,
763 ongoing_scroll: OngoingScroll,
764 current_line_highlight: CurrentLineHighlight,
765 gutter_hovered: bool,
766}
767
768const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
769
770#[derive(Default, Debug, Clone, Copy)]
771pub struct GutterDimensions {
772 pub left_padding: Pixels,
773 pub right_padding: Pixels,
774 pub width: Pixels,
775 pub margin: Pixels,
776 pub git_blame_entries_width: Option<Pixels>,
777}
778
779impl GutterDimensions {
780 /// The full width of the space taken up by the gutter.
781 pub fn full_width(&self) -> Pixels {
782 self.margin + self.width
783 }
784
785 /// The width of the space reserved for the fold indicators,
786 /// use alongside 'justify_end' and `gutter_width` to
787 /// right align content with the line numbers
788 pub fn fold_area_width(&self) -> Pixels {
789 self.margin + self.right_padding
790 }
791}
792
793#[derive(Debug)]
794pub struct RemoteSelection {
795 pub replica_id: ReplicaId,
796 pub selection: Selection<Anchor>,
797 pub cursor_shape: CursorShape,
798 pub peer_id: PeerId,
799 pub line_mode: bool,
800 pub participant_index: Option<ParticipantIndex>,
801 pub user_name: Option<SharedString>,
802}
803
804#[derive(Clone, Debug)]
805struct SelectionHistoryEntry {
806 selections: Arc<[Selection<Anchor>]>,
807 select_next_state: Option<SelectNextState>,
808 select_prev_state: Option<SelectNextState>,
809 add_selections_state: Option<AddSelectionsState>,
810}
811
812enum SelectionHistoryMode {
813 Normal,
814 Undoing,
815 Redoing,
816}
817
818#[derive(Clone, PartialEq, Eq, Hash)]
819struct HoveredCursor {
820 replica_id: u16,
821 selection_id: usize,
822}
823
824impl Default for SelectionHistoryMode {
825 fn default() -> Self {
826 Self::Normal
827 }
828}
829
830#[derive(Default)]
831struct SelectionHistory {
832 #[allow(clippy::type_complexity)]
833 selections_by_transaction:
834 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
835 mode: SelectionHistoryMode,
836 undo_stack: VecDeque<SelectionHistoryEntry>,
837 redo_stack: VecDeque<SelectionHistoryEntry>,
838}
839
840impl SelectionHistory {
841 fn insert_transaction(
842 &mut self,
843 transaction_id: TransactionId,
844 selections: Arc<[Selection<Anchor>]>,
845 ) {
846 self.selections_by_transaction
847 .insert(transaction_id, (selections, None));
848 }
849
850 #[allow(clippy::type_complexity)]
851 fn transaction(
852 &self,
853 transaction_id: TransactionId,
854 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
855 self.selections_by_transaction.get(&transaction_id)
856 }
857
858 #[allow(clippy::type_complexity)]
859 fn transaction_mut(
860 &mut self,
861 transaction_id: TransactionId,
862 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
863 self.selections_by_transaction.get_mut(&transaction_id)
864 }
865
866 fn push(&mut self, entry: SelectionHistoryEntry) {
867 if !entry.selections.is_empty() {
868 match self.mode {
869 SelectionHistoryMode::Normal => {
870 self.push_undo(entry);
871 self.redo_stack.clear();
872 }
873 SelectionHistoryMode::Undoing => self.push_redo(entry),
874 SelectionHistoryMode::Redoing => self.push_undo(entry),
875 }
876 }
877 }
878
879 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
880 if self
881 .undo_stack
882 .back()
883 .map_or(true, |e| e.selections != entry.selections)
884 {
885 self.undo_stack.push_back(entry);
886 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
887 self.undo_stack.pop_front();
888 }
889 }
890 }
891
892 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
893 if self
894 .redo_stack
895 .back()
896 .map_or(true, |e| e.selections != entry.selections)
897 {
898 self.redo_stack.push_back(entry);
899 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
900 self.redo_stack.pop_front();
901 }
902 }
903 }
904}
905
906struct RowHighlight {
907 index: usize,
908 range: Range<Anchor>,
909 color: Hsla,
910 should_autoscroll: bool,
911}
912
913#[derive(Clone, Debug)]
914struct AddSelectionsState {
915 above: bool,
916 stack: Vec<usize>,
917}
918
919#[derive(Clone)]
920struct SelectNextState {
921 query: AhoCorasick,
922 wordwise: bool,
923 done: bool,
924}
925
926impl std::fmt::Debug for SelectNextState {
927 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928 f.debug_struct(std::any::type_name::<Self>())
929 .field("wordwise", &self.wordwise)
930 .field("done", &self.done)
931 .finish()
932 }
933}
934
935#[derive(Debug)]
936struct AutocloseRegion {
937 selection_id: usize,
938 range: Range<Anchor>,
939 pair: BracketPair,
940}
941
942#[derive(Debug)]
943struct SnippetState {
944 ranges: Vec<Vec<Range<Anchor>>>,
945 active_index: usize,
946 choices: Vec<Option<Vec<String>>>,
947}
948
949#[doc(hidden)]
950pub struct RenameState {
951 pub range: Range<Anchor>,
952 pub old_name: Arc<str>,
953 pub editor: Entity<Editor>,
954 block_id: CustomBlockId,
955}
956
957struct InvalidationStack<T>(Vec<T>);
958
959struct RegisteredInlineCompletionProvider {
960 provider: Arc<dyn InlineCompletionProviderHandle>,
961 _subscription: Subscription,
962}
963
964#[derive(Debug)]
965struct ActiveDiagnosticGroup {
966 primary_range: Range<Anchor>,
967 primary_message: String,
968 group_id: usize,
969 blocks: HashMap<CustomBlockId, Diagnostic>,
970 is_valid: bool,
971}
972
973#[derive(Serialize, Deserialize, Clone, Debug)]
974pub struct ClipboardSelection {
975 /// The number of bytes in this selection.
976 pub len: usize,
977 /// Whether this was a full-line selection.
978 pub is_entire_line: bool,
979 /// The column where this selection originally started.
980 pub start_column: u32,
981}
982
983#[derive(Debug)]
984pub(crate) struct NavigationData {
985 cursor_anchor: Anchor,
986 cursor_position: Point,
987 scroll_anchor: ScrollAnchor,
988 scroll_top_row: u32,
989}
990
991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
992pub enum GotoDefinitionKind {
993 Symbol,
994 Declaration,
995 Type,
996 Implementation,
997}
998
999#[derive(Debug, Clone)]
1000enum InlayHintRefreshReason {
1001 Toggle(bool),
1002 SettingsChange(InlayHintSettings),
1003 NewLinesShown,
1004 BufferEdited(HashSet<Arc<Language>>),
1005 RefreshRequested,
1006 ExcerptsRemoved(Vec<ExcerptId>),
1007}
1008
1009impl InlayHintRefreshReason {
1010 fn description(&self) -> &'static str {
1011 match self {
1012 Self::Toggle(_) => "toggle",
1013 Self::SettingsChange(_) => "settings change",
1014 Self::NewLinesShown => "new lines shown",
1015 Self::BufferEdited(_) => "buffer edited",
1016 Self::RefreshRequested => "refresh requested",
1017 Self::ExcerptsRemoved(_) => "excerpts removed",
1018 }
1019 }
1020}
1021
1022pub enum FormatTarget {
1023 Buffers,
1024 Ranges(Vec<Range<MultiBufferPoint>>),
1025}
1026
1027pub(crate) struct FocusedBlock {
1028 id: BlockId,
1029 focus_handle: WeakFocusHandle,
1030}
1031
1032#[derive(Clone)]
1033enum JumpData {
1034 MultiBufferRow {
1035 row: MultiBufferRow,
1036 line_offset_from_top: u32,
1037 },
1038 MultiBufferPoint {
1039 excerpt_id: ExcerptId,
1040 position: Point,
1041 anchor: text::Anchor,
1042 line_offset_from_top: u32,
1043 },
1044}
1045
1046pub enum MultibufferSelectionMode {
1047 First,
1048 All,
1049}
1050
1051impl Editor {
1052 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1053 let buffer = cx.new(|cx| Buffer::local("", cx));
1054 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1055 Self::new(
1056 EditorMode::SingleLine { auto_width: false },
1057 buffer,
1058 None,
1059 false,
1060 window,
1061 cx,
1062 )
1063 }
1064
1065 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1066 let buffer = cx.new(|cx| Buffer::local("", cx));
1067 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1068 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1069 }
1070
1071 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1072 let buffer = cx.new(|cx| Buffer::local("", cx));
1073 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1074 Self::new(
1075 EditorMode::SingleLine { auto_width: true },
1076 buffer,
1077 None,
1078 false,
1079 window,
1080 cx,
1081 )
1082 }
1083
1084 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1085 let buffer = cx.new(|cx| Buffer::local("", cx));
1086 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1087 Self::new(
1088 EditorMode::AutoHeight { max_lines },
1089 buffer,
1090 None,
1091 false,
1092 window,
1093 cx,
1094 )
1095 }
1096
1097 pub fn for_buffer(
1098 buffer: Entity<Buffer>,
1099 project: Option<Entity<Project>>,
1100 window: &mut Window,
1101 cx: &mut Context<Self>,
1102 ) -> Self {
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1105 }
1106
1107 pub fn for_multibuffer(
1108 buffer: Entity<MultiBuffer>,
1109 project: Option<Entity<Project>>,
1110 show_excerpt_controls: bool,
1111 window: &mut Window,
1112 cx: &mut Context<Self>,
1113 ) -> Self {
1114 Self::new(
1115 EditorMode::Full,
1116 buffer,
1117 project,
1118 show_excerpt_controls,
1119 window,
1120 cx,
1121 )
1122 }
1123
1124 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1125 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1126 let mut clone = Self::new(
1127 self.mode,
1128 self.buffer.clone(),
1129 self.project.clone(),
1130 show_excerpt_controls,
1131 window,
1132 cx,
1133 );
1134 self.display_map.update(cx, |display_map, cx| {
1135 let snapshot = display_map.snapshot(cx);
1136 clone.display_map.update(cx, |display_map, cx| {
1137 display_map.set_state(&snapshot, cx);
1138 });
1139 });
1140 clone.selections.clone_state(&self.selections);
1141 clone.scroll_manager.clone_state(&self.scroll_manager);
1142 clone.searchable = self.searchable;
1143 clone
1144 }
1145
1146 pub fn new(
1147 mode: EditorMode,
1148 buffer: Entity<MultiBuffer>,
1149 project: Option<Entity<Project>>,
1150 show_excerpt_controls: bool,
1151 window: &mut Window,
1152 cx: &mut Context<Self>,
1153 ) -> Self {
1154 let style = window.text_style();
1155 let font_size = style.font_size.to_pixels(window.rem_size());
1156 let editor = cx.entity().downgrade();
1157 let fold_placeholder = FoldPlaceholder {
1158 constrain_width: true,
1159 render: Arc::new(move |fold_id, fold_range, cx| {
1160 let editor = editor.clone();
1161 div()
1162 .id(fold_id)
1163 .bg(cx.theme().colors().ghost_element_background)
1164 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1165 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1166 .rounded_sm()
1167 .size_full()
1168 .cursor_pointer()
1169 .child("⋯")
1170 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1171 .on_click(move |_, _window, cx| {
1172 editor
1173 .update(cx, |editor, cx| {
1174 editor.unfold_ranges(
1175 &[fold_range.start..fold_range.end],
1176 true,
1177 false,
1178 cx,
1179 );
1180 cx.stop_propagation();
1181 })
1182 .ok();
1183 })
1184 .into_any()
1185 }),
1186 merge_adjacent: true,
1187 ..Default::default()
1188 };
1189 let display_map = cx.new(|cx| {
1190 DisplayMap::new(
1191 buffer.clone(),
1192 style.font(),
1193 font_size,
1194 None,
1195 show_excerpt_controls,
1196 FILE_HEADER_HEIGHT,
1197 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1198 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1199 fold_placeholder,
1200 cx,
1201 )
1202 });
1203
1204 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1205
1206 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1207
1208 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1209 .then(|| language_settings::SoftWrap::None);
1210
1211 let mut project_subscriptions = Vec::new();
1212 if mode == EditorMode::Full {
1213 if let Some(project) = project.as_ref() {
1214 if buffer.read(cx).is_singleton() {
1215 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1216 cx.emit(EditorEvent::TitleChanged);
1217 }));
1218 }
1219 project_subscriptions.push(cx.subscribe_in(
1220 project,
1221 window,
1222 |editor, _, event, window, cx| {
1223 if let project::Event::RefreshInlayHints = event {
1224 editor
1225 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1226 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1227 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1228 let focus_handle = editor.focus_handle(cx);
1229 if focus_handle.is_focused(window) {
1230 let snapshot = buffer.read(cx).snapshot();
1231 for (range, snippet) in snippet_edits {
1232 let editor_range =
1233 language::range_from_lsp(*range).to_offset(&snapshot);
1234 editor
1235 .insert_snippet(
1236 &[editor_range],
1237 snippet.clone(),
1238 window,
1239 cx,
1240 )
1241 .ok();
1242 }
1243 }
1244 }
1245 }
1246 },
1247 ));
1248 if let Some(task_inventory) = project
1249 .read(cx)
1250 .task_store()
1251 .read(cx)
1252 .task_inventory()
1253 .cloned()
1254 {
1255 project_subscriptions.push(cx.observe_in(
1256 &task_inventory,
1257 window,
1258 |editor, _, window, cx| {
1259 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1260 },
1261 ));
1262 }
1263 }
1264 }
1265
1266 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1267
1268 let inlay_hint_settings =
1269 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1270 let focus_handle = cx.focus_handle();
1271 cx.on_focus(&focus_handle, window, Self::handle_focus)
1272 .detach();
1273 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1274 .detach();
1275 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1276 .detach();
1277 cx.on_blur(&focus_handle, window, Self::handle_blur)
1278 .detach();
1279
1280 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1281 Some(false)
1282 } else {
1283 None
1284 };
1285
1286 let mut code_action_providers = Vec::new();
1287 let mut load_uncommitted_diff = None;
1288 if let Some(project) = project.clone() {
1289 load_uncommitted_diff = Some(
1290 get_uncommitted_diff_for_buffer(
1291 &project,
1292 buffer.read(cx).all_buffers(),
1293 buffer.clone(),
1294 cx,
1295 )
1296 .shared(),
1297 );
1298 code_action_providers.push(Rc::new(project) as Rc<_>);
1299 }
1300
1301 let mut this = Self {
1302 focus_handle,
1303 show_cursor_when_unfocused: false,
1304 last_focused_descendant: None,
1305 buffer: buffer.clone(),
1306 display_map: display_map.clone(),
1307 selections,
1308 scroll_manager: ScrollManager::new(cx),
1309 columnar_selection_tail: None,
1310 add_selections_state: None,
1311 select_next_state: None,
1312 select_prev_state: None,
1313 selection_history: Default::default(),
1314 autoclose_regions: Default::default(),
1315 snippet_stack: Default::default(),
1316 select_larger_syntax_node_stack: Vec::new(),
1317 ime_transaction: Default::default(),
1318 active_diagnostics: None,
1319 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1320 inline_diagnostics_update: Task::ready(()),
1321 inline_diagnostics: Vec::new(),
1322 soft_wrap_mode_override,
1323 completion_provider: project.clone().map(|project| Box::new(project) as _),
1324 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1325 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1326 project,
1327 blink_manager: blink_manager.clone(),
1328 show_local_selections: true,
1329 show_scrollbars: true,
1330 mode,
1331 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1332 show_gutter: mode == EditorMode::Full,
1333 show_line_numbers: None,
1334 use_relative_line_numbers: None,
1335 show_git_diff_gutter: None,
1336 show_code_actions: None,
1337 show_runnables: None,
1338 show_wrap_guides: None,
1339 show_indent_guides,
1340 placeholder_text: None,
1341 highlight_order: 0,
1342 highlighted_rows: HashMap::default(),
1343 background_highlights: Default::default(),
1344 gutter_highlights: TreeMap::default(),
1345 scrollbar_marker_state: ScrollbarMarkerState::default(),
1346 active_indent_guides_state: ActiveIndentGuidesState::default(),
1347 nav_history: None,
1348 context_menu: RefCell::new(None),
1349 mouse_context_menu: None,
1350 completion_tasks: Default::default(),
1351 signature_help_state: SignatureHelpState::default(),
1352 auto_signature_help: None,
1353 find_all_references_task_sources: Vec::new(),
1354 next_completion_id: 0,
1355 next_inlay_id: 0,
1356 code_action_providers,
1357 available_code_actions: Default::default(),
1358 code_actions_task: Default::default(),
1359 selection_highlight_task: Default::default(),
1360 document_highlights_task: Default::default(),
1361 linked_editing_range_task: Default::default(),
1362 pending_rename: Default::default(),
1363 searchable: true,
1364 cursor_shape: EditorSettings::get_global(cx)
1365 .cursor_shape
1366 .unwrap_or_default(),
1367 current_line_highlight: None,
1368 autoindent_mode: Some(AutoindentMode::EachLine),
1369 collapse_matches: false,
1370 workspace: None,
1371 input_enabled: true,
1372 use_modal_editing: mode == EditorMode::Full,
1373 read_only: false,
1374 use_autoclose: true,
1375 use_auto_surround: true,
1376 auto_replace_emoji_shortcode: false,
1377 leader_peer_id: None,
1378 remote_id: None,
1379 hover_state: Default::default(),
1380 pending_mouse_down: None,
1381 hovered_link_state: Default::default(),
1382 edit_prediction_provider: None,
1383 active_inline_completion: None,
1384 stale_inline_completion_in_menu: None,
1385 edit_prediction_preview: EditPredictionPreview::Inactive,
1386 inline_diagnostics_enabled: mode == EditorMode::Full,
1387 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1388
1389 gutter_hovered: false,
1390 pixel_position_of_newest_cursor: None,
1391 last_bounds: None,
1392 last_position_map: None,
1393 expect_bounds_change: None,
1394 gutter_dimensions: GutterDimensions::default(),
1395 style: None,
1396 show_cursor_names: false,
1397 hovered_cursors: Default::default(),
1398 next_editor_action_id: EditorActionId::default(),
1399 editor_actions: Rc::default(),
1400 inline_completions_hidden_for_vim_mode: false,
1401 show_inline_completions_override: None,
1402 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1403 edit_prediction_settings: EditPredictionSettings::Disabled,
1404 edit_prediction_indent_conflict: false,
1405 edit_prediction_requires_modifier_in_indent_conflict: true,
1406 custom_context_menu: None,
1407 show_git_blame_gutter: false,
1408 show_git_blame_inline: false,
1409 show_selection_menu: None,
1410 show_git_blame_inline_delay_task: None,
1411 git_blame_inline_tooltip: None,
1412 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1413 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1414 .session
1415 .restore_unsaved_buffers,
1416 blame: None,
1417 blame_subscription: None,
1418 tasks: Default::default(),
1419 _subscriptions: vec![
1420 cx.observe(&buffer, Self::on_buffer_changed),
1421 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1422 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1423 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1424 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1425 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1426 cx.observe_window_activation(window, |editor, window, cx| {
1427 let active = window.is_window_active();
1428 editor.blink_manager.update(cx, |blink_manager, cx| {
1429 if active {
1430 blink_manager.enable(cx);
1431 } else {
1432 blink_manager.disable(cx);
1433 }
1434 });
1435 }),
1436 ],
1437 tasks_update_task: None,
1438 linked_edit_ranges: Default::default(),
1439 in_project_search: false,
1440 previous_search_ranges: None,
1441 breadcrumb_header: None,
1442 focused_block: None,
1443 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1444 addons: HashMap::default(),
1445 registered_buffers: HashMap::default(),
1446 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1447 selection_mark_mode: false,
1448 toggle_fold_multiple_buffers: Task::ready(()),
1449 serialize_selections: Task::ready(()),
1450 text_style_refinement: None,
1451 load_diff_task: load_uncommitted_diff,
1452 };
1453 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1454 this._subscriptions.extend(project_subscriptions);
1455
1456 this.end_selection(window, cx);
1457 this.scroll_manager.show_scrollbar(window, cx);
1458
1459 if mode == EditorMode::Full {
1460 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1461 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1462
1463 if this.git_blame_inline_enabled {
1464 this.git_blame_inline_enabled = true;
1465 this.start_git_blame_inline(false, window, cx);
1466 }
1467
1468 if let Some(buffer) = buffer.read(cx).as_singleton() {
1469 if let Some(project) = this.project.as_ref() {
1470 let handle = project.update(cx, |project, cx| {
1471 project.register_buffer_with_language_servers(&buffer, cx)
1472 });
1473 this.registered_buffers
1474 .insert(buffer.read(cx).remote_id(), handle);
1475 }
1476 }
1477 }
1478
1479 this.report_editor_event("Editor Opened", None, cx);
1480 this
1481 }
1482
1483 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1484 self.mouse_context_menu
1485 .as_ref()
1486 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1487 }
1488
1489 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1490 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1491 }
1492
1493 fn key_context_internal(
1494 &self,
1495 has_active_edit_prediction: bool,
1496 window: &Window,
1497 cx: &App,
1498 ) -> KeyContext {
1499 let mut key_context = KeyContext::new_with_defaults();
1500 key_context.add("Editor");
1501 let mode = match self.mode {
1502 EditorMode::SingleLine { .. } => "single_line",
1503 EditorMode::AutoHeight { .. } => "auto_height",
1504 EditorMode::Full => "full",
1505 };
1506
1507 if EditorSettings::jupyter_enabled(cx) {
1508 key_context.add("jupyter");
1509 }
1510
1511 key_context.set("mode", mode);
1512 if self.pending_rename.is_some() {
1513 key_context.add("renaming");
1514 }
1515
1516 match self.context_menu.borrow().as_ref() {
1517 Some(CodeContextMenu::Completions(_)) => {
1518 key_context.add("menu");
1519 key_context.add("showing_completions");
1520 }
1521 Some(CodeContextMenu::CodeActions(_)) => {
1522 key_context.add("menu");
1523 key_context.add("showing_code_actions")
1524 }
1525 None => {}
1526 }
1527
1528 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1529 if !self.focus_handle(cx).contains_focused(window, cx)
1530 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1531 {
1532 for addon in self.addons.values() {
1533 addon.extend_key_context(&mut key_context, cx)
1534 }
1535 }
1536
1537 if let Some(extension) = self
1538 .buffer
1539 .read(cx)
1540 .as_singleton()
1541 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1542 {
1543 key_context.set("extension", extension.to_string());
1544 }
1545
1546 if has_active_edit_prediction {
1547 if self.edit_prediction_in_conflict() {
1548 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1549 } else {
1550 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1551 key_context.add("copilot_suggestion");
1552 }
1553 }
1554
1555 if self.selection_mark_mode {
1556 key_context.add("selection_mode");
1557 }
1558
1559 key_context
1560 }
1561
1562 pub fn edit_prediction_in_conflict(&self) -> bool {
1563 if !self.show_edit_predictions_in_menu() {
1564 return false;
1565 }
1566
1567 let showing_completions = self
1568 .context_menu
1569 .borrow()
1570 .as_ref()
1571 .map_or(false, |context| {
1572 matches!(context, CodeContextMenu::Completions(_))
1573 });
1574
1575 showing_completions
1576 || self.edit_prediction_requires_modifier()
1577 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1578 // bindings to insert tab characters.
1579 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1580 }
1581
1582 pub fn accept_edit_prediction_keybind(
1583 &self,
1584 window: &Window,
1585 cx: &App,
1586 ) -> AcceptEditPredictionBinding {
1587 let key_context = self.key_context_internal(true, window, cx);
1588 let in_conflict = self.edit_prediction_in_conflict();
1589
1590 AcceptEditPredictionBinding(
1591 window
1592 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1593 .into_iter()
1594 .filter(|binding| {
1595 !in_conflict
1596 || binding
1597 .keystrokes()
1598 .first()
1599 .map_or(false, |keystroke| keystroke.modifiers.modified())
1600 })
1601 .rev()
1602 .min_by_key(|binding| {
1603 binding
1604 .keystrokes()
1605 .first()
1606 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1607 }),
1608 )
1609 }
1610
1611 pub fn new_file(
1612 workspace: &mut Workspace,
1613 _: &workspace::NewFile,
1614 window: &mut Window,
1615 cx: &mut Context<Workspace>,
1616 ) {
1617 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1618 "Failed to create buffer",
1619 window,
1620 cx,
1621 |e, _, _| match e.error_code() {
1622 ErrorCode::RemoteUpgradeRequired => Some(format!(
1623 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1624 e.error_tag("required").unwrap_or("the latest version")
1625 )),
1626 _ => None,
1627 },
1628 );
1629 }
1630
1631 pub fn new_in_workspace(
1632 workspace: &mut Workspace,
1633 window: &mut Window,
1634 cx: &mut Context<Workspace>,
1635 ) -> Task<Result<Entity<Editor>>> {
1636 let project = workspace.project().clone();
1637 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1638
1639 cx.spawn_in(window, |workspace, mut cx| async move {
1640 let buffer = create.await?;
1641 workspace.update_in(&mut cx, |workspace, window, cx| {
1642 let editor =
1643 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1644 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1645 editor
1646 })
1647 })
1648 }
1649
1650 fn new_file_vertical(
1651 workspace: &mut Workspace,
1652 _: &workspace::NewFileSplitVertical,
1653 window: &mut Window,
1654 cx: &mut Context<Workspace>,
1655 ) {
1656 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1657 }
1658
1659 fn new_file_horizontal(
1660 workspace: &mut Workspace,
1661 _: &workspace::NewFileSplitHorizontal,
1662 window: &mut Window,
1663 cx: &mut Context<Workspace>,
1664 ) {
1665 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1666 }
1667
1668 fn new_file_in_direction(
1669 workspace: &mut Workspace,
1670 direction: SplitDirection,
1671 window: &mut Window,
1672 cx: &mut Context<Workspace>,
1673 ) {
1674 let project = workspace.project().clone();
1675 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1676
1677 cx.spawn_in(window, |workspace, mut cx| async move {
1678 let buffer = create.await?;
1679 workspace.update_in(&mut cx, move |workspace, window, cx| {
1680 workspace.split_item(
1681 direction,
1682 Box::new(
1683 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1684 ),
1685 window,
1686 cx,
1687 )
1688 })?;
1689 anyhow::Ok(())
1690 })
1691 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1692 match e.error_code() {
1693 ErrorCode::RemoteUpgradeRequired => Some(format!(
1694 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1695 e.error_tag("required").unwrap_or("the latest version")
1696 )),
1697 _ => None,
1698 }
1699 });
1700 }
1701
1702 pub fn leader_peer_id(&self) -> Option<PeerId> {
1703 self.leader_peer_id
1704 }
1705
1706 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1707 &self.buffer
1708 }
1709
1710 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1711 self.workspace.as_ref()?.0.upgrade()
1712 }
1713
1714 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1715 self.buffer().read(cx).title(cx)
1716 }
1717
1718 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1719 let git_blame_gutter_max_author_length = self
1720 .render_git_blame_gutter(cx)
1721 .then(|| {
1722 if let Some(blame) = self.blame.as_ref() {
1723 let max_author_length =
1724 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1725 Some(max_author_length)
1726 } else {
1727 None
1728 }
1729 })
1730 .flatten();
1731
1732 EditorSnapshot {
1733 mode: self.mode,
1734 show_gutter: self.show_gutter,
1735 show_line_numbers: self.show_line_numbers,
1736 show_git_diff_gutter: self.show_git_diff_gutter,
1737 show_code_actions: self.show_code_actions,
1738 show_runnables: self.show_runnables,
1739 git_blame_gutter_max_author_length,
1740 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1741 scroll_anchor: self.scroll_manager.anchor(),
1742 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1743 placeholder_text: self.placeholder_text.clone(),
1744 is_focused: self.focus_handle.is_focused(window),
1745 current_line_highlight: self
1746 .current_line_highlight
1747 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1748 gutter_hovered: self.gutter_hovered,
1749 }
1750 }
1751
1752 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1753 self.buffer.read(cx).language_at(point, cx)
1754 }
1755
1756 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1757 self.buffer.read(cx).read(cx).file_at(point).cloned()
1758 }
1759
1760 pub fn active_excerpt(
1761 &self,
1762 cx: &App,
1763 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1764 self.buffer
1765 .read(cx)
1766 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1767 }
1768
1769 pub fn mode(&self) -> EditorMode {
1770 self.mode
1771 }
1772
1773 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1774 self.collaboration_hub.as_deref()
1775 }
1776
1777 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1778 self.collaboration_hub = Some(hub);
1779 }
1780
1781 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1782 self.in_project_search = in_project_search;
1783 }
1784
1785 pub fn set_custom_context_menu(
1786 &mut self,
1787 f: impl 'static
1788 + Fn(
1789 &mut Self,
1790 DisplayPoint,
1791 &mut Window,
1792 &mut Context<Self>,
1793 ) -> Option<Entity<ui::ContextMenu>>,
1794 ) {
1795 self.custom_context_menu = Some(Box::new(f))
1796 }
1797
1798 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1799 self.completion_provider = provider;
1800 }
1801
1802 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1803 self.semantics_provider.clone()
1804 }
1805
1806 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1807 self.semantics_provider = provider;
1808 }
1809
1810 pub fn set_edit_prediction_provider<T>(
1811 &mut self,
1812 provider: Option<Entity<T>>,
1813 window: &mut Window,
1814 cx: &mut Context<Self>,
1815 ) where
1816 T: EditPredictionProvider,
1817 {
1818 self.edit_prediction_provider =
1819 provider.map(|provider| RegisteredInlineCompletionProvider {
1820 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1821 if this.focus_handle.is_focused(window) {
1822 this.update_visible_inline_completion(window, cx);
1823 }
1824 }),
1825 provider: Arc::new(provider),
1826 });
1827 self.update_edit_prediction_settings(cx);
1828 self.refresh_inline_completion(false, false, window, cx);
1829 }
1830
1831 pub fn placeholder_text(&self) -> Option<&str> {
1832 self.placeholder_text.as_deref()
1833 }
1834
1835 pub fn set_placeholder_text(
1836 &mut self,
1837 placeholder_text: impl Into<Arc<str>>,
1838 cx: &mut Context<Self>,
1839 ) {
1840 let placeholder_text = Some(placeholder_text.into());
1841 if self.placeholder_text != placeholder_text {
1842 self.placeholder_text = placeholder_text;
1843 cx.notify();
1844 }
1845 }
1846
1847 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1848 self.cursor_shape = cursor_shape;
1849
1850 // Disrupt blink for immediate user feedback that the cursor shape has changed
1851 self.blink_manager.update(cx, BlinkManager::show_cursor);
1852
1853 cx.notify();
1854 }
1855
1856 pub fn set_current_line_highlight(
1857 &mut self,
1858 current_line_highlight: Option<CurrentLineHighlight>,
1859 ) {
1860 self.current_line_highlight = current_line_highlight;
1861 }
1862
1863 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1864 self.collapse_matches = collapse_matches;
1865 }
1866
1867 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1868 let buffers = self.buffer.read(cx).all_buffers();
1869 let Some(project) = self.project.as_ref() else {
1870 return;
1871 };
1872 project.update(cx, |project, cx| {
1873 for buffer in buffers {
1874 self.registered_buffers
1875 .entry(buffer.read(cx).remote_id())
1876 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1877 }
1878 })
1879 }
1880
1881 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1882 if self.collapse_matches {
1883 return range.start..range.start;
1884 }
1885 range.clone()
1886 }
1887
1888 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1889 if self.display_map.read(cx).clip_at_line_ends != clip {
1890 self.display_map
1891 .update(cx, |map, _| map.clip_at_line_ends = clip);
1892 }
1893 }
1894
1895 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1896 self.input_enabled = input_enabled;
1897 }
1898
1899 pub fn set_inline_completions_hidden_for_vim_mode(
1900 &mut self,
1901 hidden: bool,
1902 window: &mut Window,
1903 cx: &mut Context<Self>,
1904 ) {
1905 if hidden != self.inline_completions_hidden_for_vim_mode {
1906 self.inline_completions_hidden_for_vim_mode = hidden;
1907 if hidden {
1908 self.update_visible_inline_completion(window, cx);
1909 } else {
1910 self.refresh_inline_completion(true, false, window, cx);
1911 }
1912 }
1913 }
1914
1915 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1916 self.menu_inline_completions_policy = value;
1917 }
1918
1919 pub fn set_autoindent(&mut self, autoindent: bool) {
1920 if autoindent {
1921 self.autoindent_mode = Some(AutoindentMode::EachLine);
1922 } else {
1923 self.autoindent_mode = None;
1924 }
1925 }
1926
1927 pub fn read_only(&self, cx: &App) -> bool {
1928 self.read_only || self.buffer.read(cx).read_only()
1929 }
1930
1931 pub fn set_read_only(&mut self, read_only: bool) {
1932 self.read_only = read_only;
1933 }
1934
1935 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1936 self.use_autoclose = autoclose;
1937 }
1938
1939 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1940 self.use_auto_surround = auto_surround;
1941 }
1942
1943 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1944 self.auto_replace_emoji_shortcode = auto_replace;
1945 }
1946
1947 pub fn toggle_edit_predictions(
1948 &mut self,
1949 _: &ToggleEditPrediction,
1950 window: &mut Window,
1951 cx: &mut Context<Self>,
1952 ) {
1953 if self.show_inline_completions_override.is_some() {
1954 self.set_show_edit_predictions(None, window, cx);
1955 } else {
1956 let show_edit_predictions = !self.edit_predictions_enabled();
1957 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1958 }
1959 }
1960
1961 pub fn set_show_edit_predictions(
1962 &mut self,
1963 show_edit_predictions: Option<bool>,
1964 window: &mut Window,
1965 cx: &mut Context<Self>,
1966 ) {
1967 self.show_inline_completions_override = show_edit_predictions;
1968 self.update_edit_prediction_settings(cx);
1969
1970 if let Some(false) = show_edit_predictions {
1971 self.discard_inline_completion(false, cx);
1972 } else {
1973 self.refresh_inline_completion(false, true, window, cx);
1974 }
1975 }
1976
1977 fn inline_completions_disabled_in_scope(
1978 &self,
1979 buffer: &Entity<Buffer>,
1980 buffer_position: language::Anchor,
1981 cx: &App,
1982 ) -> bool {
1983 let snapshot = buffer.read(cx).snapshot();
1984 let settings = snapshot.settings_at(buffer_position, cx);
1985
1986 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1987 return false;
1988 };
1989
1990 scope.override_name().map_or(false, |scope_name| {
1991 settings
1992 .edit_predictions_disabled_in
1993 .iter()
1994 .any(|s| s == scope_name)
1995 })
1996 }
1997
1998 pub fn set_use_modal_editing(&mut self, to: bool) {
1999 self.use_modal_editing = to;
2000 }
2001
2002 pub fn use_modal_editing(&self) -> bool {
2003 self.use_modal_editing
2004 }
2005
2006 fn selections_did_change(
2007 &mut self,
2008 local: bool,
2009 old_cursor_position: &Anchor,
2010 show_completions: bool,
2011 window: &mut Window,
2012 cx: &mut Context<Self>,
2013 ) {
2014 window.invalidate_character_coordinates();
2015
2016 // Copy selections to primary selection buffer
2017 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2018 if local {
2019 let selections = self.selections.all::<usize>(cx);
2020 let buffer_handle = self.buffer.read(cx).read(cx);
2021
2022 let mut text = String::new();
2023 for (index, selection) in selections.iter().enumerate() {
2024 let text_for_selection = buffer_handle
2025 .text_for_range(selection.start..selection.end)
2026 .collect::<String>();
2027
2028 text.push_str(&text_for_selection);
2029 if index != selections.len() - 1 {
2030 text.push('\n');
2031 }
2032 }
2033
2034 if !text.is_empty() {
2035 cx.write_to_primary(ClipboardItem::new_string(text));
2036 }
2037 }
2038
2039 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2040 self.buffer.update(cx, |buffer, cx| {
2041 buffer.set_active_selections(
2042 &self.selections.disjoint_anchors(),
2043 self.selections.line_mode,
2044 self.cursor_shape,
2045 cx,
2046 )
2047 });
2048 }
2049 let display_map = self
2050 .display_map
2051 .update(cx, |display_map, cx| display_map.snapshot(cx));
2052 let buffer = &display_map.buffer_snapshot;
2053 self.add_selections_state = None;
2054 self.select_next_state = None;
2055 self.select_prev_state = None;
2056 self.select_larger_syntax_node_stack.clear();
2057 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2058 self.snippet_stack
2059 .invalidate(&self.selections.disjoint_anchors(), buffer);
2060 self.take_rename(false, window, cx);
2061
2062 let new_cursor_position = self.selections.newest_anchor().head();
2063
2064 self.push_to_nav_history(
2065 *old_cursor_position,
2066 Some(new_cursor_position.to_point(buffer)),
2067 cx,
2068 );
2069
2070 if local {
2071 let new_cursor_position = self.selections.newest_anchor().head();
2072 let mut context_menu = self.context_menu.borrow_mut();
2073 let completion_menu = match context_menu.as_ref() {
2074 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2075 _ => {
2076 *context_menu = None;
2077 None
2078 }
2079 };
2080 if let Some(buffer_id) = new_cursor_position.buffer_id {
2081 if !self.registered_buffers.contains_key(&buffer_id) {
2082 if let Some(project) = self.project.as_ref() {
2083 project.update(cx, |project, cx| {
2084 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2085 return;
2086 };
2087 self.registered_buffers.insert(
2088 buffer_id,
2089 project.register_buffer_with_language_servers(&buffer, cx),
2090 );
2091 })
2092 }
2093 }
2094 }
2095
2096 if let Some(completion_menu) = completion_menu {
2097 let cursor_position = new_cursor_position.to_offset(buffer);
2098 let (word_range, kind) =
2099 buffer.surrounding_word(completion_menu.initial_position, true);
2100 if kind == Some(CharKind::Word)
2101 && word_range.to_inclusive().contains(&cursor_position)
2102 {
2103 let mut completion_menu = completion_menu.clone();
2104 drop(context_menu);
2105
2106 let query = Self::completion_query(buffer, cursor_position);
2107 cx.spawn(move |this, mut cx| async move {
2108 completion_menu
2109 .filter(query.as_deref(), cx.background_executor().clone())
2110 .await;
2111
2112 this.update(&mut cx, |this, cx| {
2113 let mut context_menu = this.context_menu.borrow_mut();
2114 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2115 else {
2116 return;
2117 };
2118
2119 if menu.id > completion_menu.id {
2120 return;
2121 }
2122
2123 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2124 drop(context_menu);
2125 cx.notify();
2126 })
2127 })
2128 .detach();
2129
2130 if show_completions {
2131 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2132 }
2133 } else {
2134 drop(context_menu);
2135 self.hide_context_menu(window, cx);
2136 }
2137 } else {
2138 drop(context_menu);
2139 }
2140
2141 hide_hover(self, cx);
2142
2143 if old_cursor_position.to_display_point(&display_map).row()
2144 != new_cursor_position.to_display_point(&display_map).row()
2145 {
2146 self.available_code_actions.take();
2147 }
2148 self.refresh_code_actions(window, cx);
2149 self.refresh_document_highlights(cx);
2150 self.refresh_selected_text_highlights(window, cx);
2151 refresh_matching_bracket_highlights(self, window, cx);
2152 self.update_visible_inline_completion(window, cx);
2153 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2154 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2155 if self.git_blame_inline_enabled {
2156 self.start_inline_blame_timer(window, cx);
2157 }
2158 }
2159
2160 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2161 cx.emit(EditorEvent::SelectionsChanged { local });
2162
2163 let selections = &self.selections.disjoint;
2164 if selections.len() == 1 {
2165 cx.emit(SearchEvent::ActiveMatchChanged)
2166 }
2167 if local
2168 && self.is_singleton(cx)
2169 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2170 {
2171 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2172 let background_executor = cx.background_executor().clone();
2173 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2174 let snapshot = self.buffer().read(cx).snapshot(cx);
2175 let selections = selections.clone();
2176 self.serialize_selections = cx.background_spawn(async move {
2177 background_executor.timer(Duration::from_millis(100)).await;
2178 let selections = selections
2179 .iter()
2180 .map(|selection| {
2181 (
2182 selection.start.to_offset(&snapshot),
2183 selection.end.to_offset(&snapshot),
2184 )
2185 })
2186 .collect();
2187 DB.save_editor_selections(editor_id, workspace_id, selections)
2188 .await
2189 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2190 .log_err();
2191 });
2192 }
2193 }
2194
2195 cx.notify();
2196 }
2197
2198 pub fn change_selections<R>(
2199 &mut self,
2200 autoscroll: Option<Autoscroll>,
2201 window: &mut Window,
2202 cx: &mut Context<Self>,
2203 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2204 ) -> R {
2205 self.change_selections_inner(autoscroll, true, window, cx, change)
2206 }
2207
2208 fn change_selections_inner<R>(
2209 &mut self,
2210 autoscroll: Option<Autoscroll>,
2211 request_completions: bool,
2212 window: &mut Window,
2213 cx: &mut Context<Self>,
2214 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2215 ) -> R {
2216 let old_cursor_position = self.selections.newest_anchor().head();
2217 self.push_to_selection_history();
2218
2219 let (changed, result) = self.selections.change_with(cx, change);
2220
2221 if changed {
2222 if let Some(autoscroll) = autoscroll {
2223 self.request_autoscroll(autoscroll, cx);
2224 }
2225 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2226
2227 if self.should_open_signature_help_automatically(
2228 &old_cursor_position,
2229 self.signature_help_state.backspace_pressed(),
2230 cx,
2231 ) {
2232 self.show_signature_help(&ShowSignatureHelp, window, cx);
2233 }
2234 self.signature_help_state.set_backspace_pressed(false);
2235 }
2236
2237 result
2238 }
2239
2240 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2241 where
2242 I: IntoIterator<Item = (Range<S>, T)>,
2243 S: ToOffset,
2244 T: Into<Arc<str>>,
2245 {
2246 if self.read_only(cx) {
2247 return;
2248 }
2249
2250 self.buffer
2251 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2252 }
2253
2254 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2255 where
2256 I: IntoIterator<Item = (Range<S>, T)>,
2257 S: ToOffset,
2258 T: Into<Arc<str>>,
2259 {
2260 if self.read_only(cx) {
2261 return;
2262 }
2263
2264 self.buffer.update(cx, |buffer, cx| {
2265 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2266 });
2267 }
2268
2269 pub fn edit_with_block_indent<I, S, T>(
2270 &mut self,
2271 edits: I,
2272 original_start_columns: Vec<u32>,
2273 cx: &mut Context<Self>,
2274 ) where
2275 I: IntoIterator<Item = (Range<S>, T)>,
2276 S: ToOffset,
2277 T: Into<Arc<str>>,
2278 {
2279 if self.read_only(cx) {
2280 return;
2281 }
2282
2283 self.buffer.update(cx, |buffer, cx| {
2284 buffer.edit(
2285 edits,
2286 Some(AutoindentMode::Block {
2287 original_start_columns,
2288 }),
2289 cx,
2290 )
2291 });
2292 }
2293
2294 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2295 self.hide_context_menu(window, cx);
2296
2297 match phase {
2298 SelectPhase::Begin {
2299 position,
2300 add,
2301 click_count,
2302 } => self.begin_selection(position, add, click_count, window, cx),
2303 SelectPhase::BeginColumnar {
2304 position,
2305 goal_column,
2306 reset,
2307 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2308 SelectPhase::Extend {
2309 position,
2310 click_count,
2311 } => self.extend_selection(position, click_count, window, cx),
2312 SelectPhase::Update {
2313 position,
2314 goal_column,
2315 scroll_delta,
2316 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2317 SelectPhase::End => self.end_selection(window, cx),
2318 }
2319 }
2320
2321 fn extend_selection(
2322 &mut self,
2323 position: DisplayPoint,
2324 click_count: usize,
2325 window: &mut Window,
2326 cx: &mut Context<Self>,
2327 ) {
2328 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2329 let tail = self.selections.newest::<usize>(cx).tail();
2330 self.begin_selection(position, false, click_count, window, cx);
2331
2332 let position = position.to_offset(&display_map, Bias::Left);
2333 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2334
2335 let mut pending_selection = self
2336 .selections
2337 .pending_anchor()
2338 .expect("extend_selection not called with pending selection");
2339 if position >= tail {
2340 pending_selection.start = tail_anchor;
2341 } else {
2342 pending_selection.end = tail_anchor;
2343 pending_selection.reversed = true;
2344 }
2345
2346 let mut pending_mode = self.selections.pending_mode().unwrap();
2347 match &mut pending_mode {
2348 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2349 _ => {}
2350 }
2351
2352 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2353 s.set_pending(pending_selection, pending_mode)
2354 });
2355 }
2356
2357 fn begin_selection(
2358 &mut self,
2359 position: DisplayPoint,
2360 add: bool,
2361 click_count: usize,
2362 window: &mut Window,
2363 cx: &mut Context<Self>,
2364 ) {
2365 if !self.focus_handle.is_focused(window) {
2366 self.last_focused_descendant = None;
2367 window.focus(&self.focus_handle);
2368 }
2369
2370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2371 let buffer = &display_map.buffer_snapshot;
2372 let newest_selection = self.selections.newest_anchor().clone();
2373 let position = display_map.clip_point(position, Bias::Left);
2374
2375 let start;
2376 let end;
2377 let mode;
2378 let mut auto_scroll;
2379 match click_count {
2380 1 => {
2381 start = buffer.anchor_before(position.to_point(&display_map));
2382 end = start;
2383 mode = SelectMode::Character;
2384 auto_scroll = true;
2385 }
2386 2 => {
2387 let range = movement::surrounding_word(&display_map, position);
2388 start = buffer.anchor_before(range.start.to_point(&display_map));
2389 end = buffer.anchor_before(range.end.to_point(&display_map));
2390 mode = SelectMode::Word(start..end);
2391 auto_scroll = true;
2392 }
2393 3 => {
2394 let position = display_map
2395 .clip_point(position, Bias::Left)
2396 .to_point(&display_map);
2397 let line_start = display_map.prev_line_boundary(position).0;
2398 let next_line_start = buffer.clip_point(
2399 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2400 Bias::Left,
2401 );
2402 start = buffer.anchor_before(line_start);
2403 end = buffer.anchor_before(next_line_start);
2404 mode = SelectMode::Line(start..end);
2405 auto_scroll = true;
2406 }
2407 _ => {
2408 start = buffer.anchor_before(0);
2409 end = buffer.anchor_before(buffer.len());
2410 mode = SelectMode::All;
2411 auto_scroll = false;
2412 }
2413 }
2414 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2415
2416 let point_to_delete: Option<usize> = {
2417 let selected_points: Vec<Selection<Point>> =
2418 self.selections.disjoint_in_range(start..end, cx);
2419
2420 if !add || click_count > 1 {
2421 None
2422 } else if !selected_points.is_empty() {
2423 Some(selected_points[0].id)
2424 } else {
2425 let clicked_point_already_selected =
2426 self.selections.disjoint.iter().find(|selection| {
2427 selection.start.to_point(buffer) == start.to_point(buffer)
2428 || selection.end.to_point(buffer) == end.to_point(buffer)
2429 });
2430
2431 clicked_point_already_selected.map(|selection| selection.id)
2432 }
2433 };
2434
2435 let selections_count = self.selections.count();
2436
2437 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2438 if let Some(point_to_delete) = point_to_delete {
2439 s.delete(point_to_delete);
2440
2441 if selections_count == 1 {
2442 s.set_pending_anchor_range(start..end, mode);
2443 }
2444 } else {
2445 if !add {
2446 s.clear_disjoint();
2447 } else if click_count > 1 {
2448 s.delete(newest_selection.id)
2449 }
2450
2451 s.set_pending_anchor_range(start..end, mode);
2452 }
2453 });
2454 }
2455
2456 fn begin_columnar_selection(
2457 &mut self,
2458 position: DisplayPoint,
2459 goal_column: u32,
2460 reset: bool,
2461 window: &mut Window,
2462 cx: &mut Context<Self>,
2463 ) {
2464 if !self.focus_handle.is_focused(window) {
2465 self.last_focused_descendant = None;
2466 window.focus(&self.focus_handle);
2467 }
2468
2469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2470
2471 if reset {
2472 let pointer_position = display_map
2473 .buffer_snapshot
2474 .anchor_before(position.to_point(&display_map));
2475
2476 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2477 s.clear_disjoint();
2478 s.set_pending_anchor_range(
2479 pointer_position..pointer_position,
2480 SelectMode::Character,
2481 );
2482 });
2483 }
2484
2485 let tail = self.selections.newest::<Point>(cx).tail();
2486 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2487
2488 if !reset {
2489 self.select_columns(
2490 tail.to_display_point(&display_map),
2491 position,
2492 goal_column,
2493 &display_map,
2494 window,
2495 cx,
2496 );
2497 }
2498 }
2499
2500 fn update_selection(
2501 &mut self,
2502 position: DisplayPoint,
2503 goal_column: u32,
2504 scroll_delta: gpui::Point<f32>,
2505 window: &mut Window,
2506 cx: &mut Context<Self>,
2507 ) {
2508 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2509
2510 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2511 let tail = tail.to_display_point(&display_map);
2512 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2513 } else if let Some(mut pending) = self.selections.pending_anchor() {
2514 let buffer = self.buffer.read(cx).snapshot(cx);
2515 let head;
2516 let tail;
2517 let mode = self.selections.pending_mode().unwrap();
2518 match &mode {
2519 SelectMode::Character => {
2520 head = position.to_point(&display_map);
2521 tail = pending.tail().to_point(&buffer);
2522 }
2523 SelectMode::Word(original_range) => {
2524 let original_display_range = original_range.start.to_display_point(&display_map)
2525 ..original_range.end.to_display_point(&display_map);
2526 let original_buffer_range = original_display_range.start.to_point(&display_map)
2527 ..original_display_range.end.to_point(&display_map);
2528 if movement::is_inside_word(&display_map, position)
2529 || original_display_range.contains(&position)
2530 {
2531 let word_range = movement::surrounding_word(&display_map, position);
2532 if word_range.start < original_display_range.start {
2533 head = word_range.start.to_point(&display_map);
2534 } else {
2535 head = word_range.end.to_point(&display_map);
2536 }
2537 } else {
2538 head = position.to_point(&display_map);
2539 }
2540
2541 if head <= original_buffer_range.start {
2542 tail = original_buffer_range.end;
2543 } else {
2544 tail = original_buffer_range.start;
2545 }
2546 }
2547 SelectMode::Line(original_range) => {
2548 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2549
2550 let position = display_map
2551 .clip_point(position, Bias::Left)
2552 .to_point(&display_map);
2553 let line_start = display_map.prev_line_boundary(position).0;
2554 let next_line_start = buffer.clip_point(
2555 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2556 Bias::Left,
2557 );
2558
2559 if line_start < original_range.start {
2560 head = line_start
2561 } else {
2562 head = next_line_start
2563 }
2564
2565 if head <= original_range.start {
2566 tail = original_range.end;
2567 } else {
2568 tail = original_range.start;
2569 }
2570 }
2571 SelectMode::All => {
2572 return;
2573 }
2574 };
2575
2576 if head < tail {
2577 pending.start = buffer.anchor_before(head);
2578 pending.end = buffer.anchor_before(tail);
2579 pending.reversed = true;
2580 } else {
2581 pending.start = buffer.anchor_before(tail);
2582 pending.end = buffer.anchor_before(head);
2583 pending.reversed = false;
2584 }
2585
2586 self.change_selections(None, window, cx, |s| {
2587 s.set_pending(pending, mode);
2588 });
2589 } else {
2590 log::error!("update_selection dispatched with no pending selection");
2591 return;
2592 }
2593
2594 self.apply_scroll_delta(scroll_delta, window, cx);
2595 cx.notify();
2596 }
2597
2598 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2599 self.columnar_selection_tail.take();
2600 if self.selections.pending_anchor().is_some() {
2601 let selections = self.selections.all::<usize>(cx);
2602 self.change_selections(None, window, cx, |s| {
2603 s.select(selections);
2604 s.clear_pending();
2605 });
2606 }
2607 }
2608
2609 fn select_columns(
2610 &mut self,
2611 tail: DisplayPoint,
2612 head: DisplayPoint,
2613 goal_column: u32,
2614 display_map: &DisplaySnapshot,
2615 window: &mut Window,
2616 cx: &mut Context<Self>,
2617 ) {
2618 let start_row = cmp::min(tail.row(), head.row());
2619 let end_row = cmp::max(tail.row(), head.row());
2620 let start_column = cmp::min(tail.column(), goal_column);
2621 let end_column = cmp::max(tail.column(), goal_column);
2622 let reversed = start_column < tail.column();
2623
2624 let selection_ranges = (start_row.0..=end_row.0)
2625 .map(DisplayRow)
2626 .filter_map(|row| {
2627 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2628 let start = display_map
2629 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2630 .to_point(display_map);
2631 let end = display_map
2632 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2633 .to_point(display_map);
2634 if reversed {
2635 Some(end..start)
2636 } else {
2637 Some(start..end)
2638 }
2639 } else {
2640 None
2641 }
2642 })
2643 .collect::<Vec<_>>();
2644
2645 self.change_selections(None, window, cx, |s| {
2646 s.select_ranges(selection_ranges);
2647 });
2648 cx.notify();
2649 }
2650
2651 pub fn has_pending_nonempty_selection(&self) -> bool {
2652 let pending_nonempty_selection = match self.selections.pending_anchor() {
2653 Some(Selection { start, end, .. }) => start != end,
2654 None => false,
2655 };
2656
2657 pending_nonempty_selection
2658 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2659 }
2660
2661 pub fn has_pending_selection(&self) -> bool {
2662 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2663 }
2664
2665 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2666 self.selection_mark_mode = false;
2667
2668 if self.clear_expanded_diff_hunks(cx) {
2669 cx.notify();
2670 return;
2671 }
2672 if self.dismiss_menus_and_popups(true, window, cx) {
2673 return;
2674 }
2675
2676 if self.mode == EditorMode::Full
2677 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2678 {
2679 return;
2680 }
2681
2682 cx.propagate();
2683 }
2684
2685 pub fn dismiss_menus_and_popups(
2686 &mut self,
2687 is_user_requested: bool,
2688 window: &mut Window,
2689 cx: &mut Context<Self>,
2690 ) -> bool {
2691 if self.take_rename(false, window, cx).is_some() {
2692 return true;
2693 }
2694
2695 if hide_hover(self, cx) {
2696 return true;
2697 }
2698
2699 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2700 return true;
2701 }
2702
2703 if self.hide_context_menu(window, cx).is_some() {
2704 return true;
2705 }
2706
2707 if self.mouse_context_menu.take().is_some() {
2708 return true;
2709 }
2710
2711 if is_user_requested && self.discard_inline_completion(true, cx) {
2712 return true;
2713 }
2714
2715 if self.snippet_stack.pop().is_some() {
2716 return true;
2717 }
2718
2719 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2720 self.dismiss_diagnostics(cx);
2721 return true;
2722 }
2723
2724 false
2725 }
2726
2727 fn linked_editing_ranges_for(
2728 &self,
2729 selection: Range<text::Anchor>,
2730 cx: &App,
2731 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2732 if self.linked_edit_ranges.is_empty() {
2733 return None;
2734 }
2735 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2736 selection.end.buffer_id.and_then(|end_buffer_id| {
2737 if selection.start.buffer_id != Some(end_buffer_id) {
2738 return None;
2739 }
2740 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2741 let snapshot = buffer.read(cx).snapshot();
2742 self.linked_edit_ranges
2743 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2744 .map(|ranges| (ranges, snapshot, buffer))
2745 })?;
2746 use text::ToOffset as TO;
2747 // find offset from the start of current range to current cursor position
2748 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2749
2750 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2751 let start_difference = start_offset - start_byte_offset;
2752 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2753 let end_difference = end_offset - start_byte_offset;
2754 // Current range has associated linked ranges.
2755 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2756 for range in linked_ranges.iter() {
2757 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2758 let end_offset = start_offset + end_difference;
2759 let start_offset = start_offset + start_difference;
2760 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2761 continue;
2762 }
2763 if self.selections.disjoint_anchor_ranges().any(|s| {
2764 if s.start.buffer_id != selection.start.buffer_id
2765 || s.end.buffer_id != selection.end.buffer_id
2766 {
2767 return false;
2768 }
2769 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2770 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2771 }) {
2772 continue;
2773 }
2774 let start = buffer_snapshot.anchor_after(start_offset);
2775 let end = buffer_snapshot.anchor_after(end_offset);
2776 linked_edits
2777 .entry(buffer.clone())
2778 .or_default()
2779 .push(start..end);
2780 }
2781 Some(linked_edits)
2782 }
2783
2784 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2785 let text: Arc<str> = text.into();
2786
2787 if self.read_only(cx) {
2788 return;
2789 }
2790
2791 let selections = self.selections.all_adjusted(cx);
2792 let mut bracket_inserted = false;
2793 let mut edits = Vec::new();
2794 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2795 let mut new_selections = Vec::with_capacity(selections.len());
2796 let mut new_autoclose_regions = Vec::new();
2797 let snapshot = self.buffer.read(cx).read(cx);
2798
2799 for (selection, autoclose_region) in
2800 self.selections_with_autoclose_regions(selections, &snapshot)
2801 {
2802 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2803 // Determine if the inserted text matches the opening or closing
2804 // bracket of any of this language's bracket pairs.
2805 let mut bracket_pair = None;
2806 let mut is_bracket_pair_start = false;
2807 let mut is_bracket_pair_end = false;
2808 if !text.is_empty() {
2809 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2810 // and they are removing the character that triggered IME popup.
2811 for (pair, enabled) in scope.brackets() {
2812 if !pair.close && !pair.surround {
2813 continue;
2814 }
2815
2816 if enabled && pair.start.ends_with(text.as_ref()) {
2817 let prefix_len = pair.start.len() - text.len();
2818 let preceding_text_matches_prefix = prefix_len == 0
2819 || (selection.start.column >= (prefix_len as u32)
2820 && snapshot.contains_str_at(
2821 Point::new(
2822 selection.start.row,
2823 selection.start.column - (prefix_len as u32),
2824 ),
2825 &pair.start[..prefix_len],
2826 ));
2827 if preceding_text_matches_prefix {
2828 bracket_pair = Some(pair.clone());
2829 is_bracket_pair_start = true;
2830 break;
2831 }
2832 }
2833 if pair.end.as_str() == text.as_ref() {
2834 bracket_pair = Some(pair.clone());
2835 is_bracket_pair_end = true;
2836 break;
2837 }
2838 }
2839 }
2840
2841 if let Some(bracket_pair) = bracket_pair {
2842 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2843 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2844 let auto_surround =
2845 self.use_auto_surround && snapshot_settings.use_auto_surround;
2846 if selection.is_empty() {
2847 if is_bracket_pair_start {
2848 // If the inserted text is a suffix of an opening bracket and the
2849 // selection is preceded by the rest of the opening bracket, then
2850 // insert the closing bracket.
2851 let following_text_allows_autoclose = snapshot
2852 .chars_at(selection.start)
2853 .next()
2854 .map_or(true, |c| scope.should_autoclose_before(c));
2855
2856 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2857 && bracket_pair.start.len() == 1
2858 {
2859 let target = bracket_pair.start.chars().next().unwrap();
2860 let current_line_count = snapshot
2861 .reversed_chars_at(selection.start)
2862 .take_while(|&c| c != '\n')
2863 .filter(|&c| c == target)
2864 .count();
2865 current_line_count % 2 == 1
2866 } else {
2867 false
2868 };
2869
2870 if autoclose
2871 && bracket_pair.close
2872 && following_text_allows_autoclose
2873 && !is_closing_quote
2874 {
2875 let anchor = snapshot.anchor_before(selection.end);
2876 new_selections.push((selection.map(|_| anchor), text.len()));
2877 new_autoclose_regions.push((
2878 anchor,
2879 text.len(),
2880 selection.id,
2881 bracket_pair.clone(),
2882 ));
2883 edits.push((
2884 selection.range(),
2885 format!("{}{}", text, bracket_pair.end).into(),
2886 ));
2887 bracket_inserted = true;
2888 continue;
2889 }
2890 }
2891
2892 if let Some(region) = autoclose_region {
2893 // If the selection is followed by an auto-inserted closing bracket,
2894 // then don't insert that closing bracket again; just move the selection
2895 // past the closing bracket.
2896 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2897 && text.as_ref() == region.pair.end.as_str();
2898 if should_skip {
2899 let anchor = snapshot.anchor_after(selection.end);
2900 new_selections
2901 .push((selection.map(|_| anchor), region.pair.end.len()));
2902 continue;
2903 }
2904 }
2905
2906 let always_treat_brackets_as_autoclosed = snapshot
2907 .settings_at(selection.start, cx)
2908 .always_treat_brackets_as_autoclosed;
2909 if always_treat_brackets_as_autoclosed
2910 && is_bracket_pair_end
2911 && snapshot.contains_str_at(selection.end, text.as_ref())
2912 {
2913 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2914 // and the inserted text is a closing bracket and the selection is followed
2915 // by the closing bracket then move the selection past the closing bracket.
2916 let anchor = snapshot.anchor_after(selection.end);
2917 new_selections.push((selection.map(|_| anchor), text.len()));
2918 continue;
2919 }
2920 }
2921 // If an opening bracket is 1 character long and is typed while
2922 // text is selected, then surround that text with the bracket pair.
2923 else if auto_surround
2924 && bracket_pair.surround
2925 && is_bracket_pair_start
2926 && bracket_pair.start.chars().count() == 1
2927 {
2928 edits.push((selection.start..selection.start, text.clone()));
2929 edits.push((
2930 selection.end..selection.end,
2931 bracket_pair.end.as_str().into(),
2932 ));
2933 bracket_inserted = true;
2934 new_selections.push((
2935 Selection {
2936 id: selection.id,
2937 start: snapshot.anchor_after(selection.start),
2938 end: snapshot.anchor_before(selection.end),
2939 reversed: selection.reversed,
2940 goal: selection.goal,
2941 },
2942 0,
2943 ));
2944 continue;
2945 }
2946 }
2947 }
2948
2949 if self.auto_replace_emoji_shortcode
2950 && selection.is_empty()
2951 && text.as_ref().ends_with(':')
2952 {
2953 if let Some(possible_emoji_short_code) =
2954 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2955 {
2956 if !possible_emoji_short_code.is_empty() {
2957 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2958 let emoji_shortcode_start = Point::new(
2959 selection.start.row,
2960 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2961 );
2962
2963 // Remove shortcode from buffer
2964 edits.push((
2965 emoji_shortcode_start..selection.start,
2966 "".to_string().into(),
2967 ));
2968 new_selections.push((
2969 Selection {
2970 id: selection.id,
2971 start: snapshot.anchor_after(emoji_shortcode_start),
2972 end: snapshot.anchor_before(selection.start),
2973 reversed: selection.reversed,
2974 goal: selection.goal,
2975 },
2976 0,
2977 ));
2978
2979 // Insert emoji
2980 let selection_start_anchor = snapshot.anchor_after(selection.start);
2981 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2982 edits.push((selection.start..selection.end, emoji.to_string().into()));
2983
2984 continue;
2985 }
2986 }
2987 }
2988 }
2989
2990 // If not handling any auto-close operation, then just replace the selected
2991 // text with the given input and move the selection to the end of the
2992 // newly inserted text.
2993 let anchor = snapshot.anchor_after(selection.end);
2994 if !self.linked_edit_ranges.is_empty() {
2995 let start_anchor = snapshot.anchor_before(selection.start);
2996
2997 let is_word_char = text.chars().next().map_or(true, |char| {
2998 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2999 classifier.is_word(char)
3000 });
3001
3002 if is_word_char {
3003 if let Some(ranges) = self
3004 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3005 {
3006 for (buffer, edits) in ranges {
3007 linked_edits
3008 .entry(buffer.clone())
3009 .or_default()
3010 .extend(edits.into_iter().map(|range| (range, text.clone())));
3011 }
3012 }
3013 }
3014 }
3015
3016 new_selections.push((selection.map(|_| anchor), 0));
3017 edits.push((selection.start..selection.end, text.clone()));
3018 }
3019
3020 drop(snapshot);
3021
3022 self.transact(window, cx, |this, window, cx| {
3023 this.buffer.update(cx, |buffer, cx| {
3024 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3025 });
3026 for (buffer, edits) in linked_edits {
3027 buffer.update(cx, |buffer, cx| {
3028 let snapshot = buffer.snapshot();
3029 let edits = edits
3030 .into_iter()
3031 .map(|(range, text)| {
3032 use text::ToPoint as TP;
3033 let end_point = TP::to_point(&range.end, &snapshot);
3034 let start_point = TP::to_point(&range.start, &snapshot);
3035 (start_point..end_point, text)
3036 })
3037 .sorted_by_key(|(range, _)| range.start)
3038 .collect::<Vec<_>>();
3039 buffer.edit(edits, None, cx);
3040 })
3041 }
3042 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3043 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3044 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3045 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3046 .zip(new_selection_deltas)
3047 .map(|(selection, delta)| Selection {
3048 id: selection.id,
3049 start: selection.start + delta,
3050 end: selection.end + delta,
3051 reversed: selection.reversed,
3052 goal: SelectionGoal::None,
3053 })
3054 .collect::<Vec<_>>();
3055
3056 let mut i = 0;
3057 for (position, delta, selection_id, pair) in new_autoclose_regions {
3058 let position = position.to_offset(&map.buffer_snapshot) + delta;
3059 let start = map.buffer_snapshot.anchor_before(position);
3060 let end = map.buffer_snapshot.anchor_after(position);
3061 while let Some(existing_state) = this.autoclose_regions.get(i) {
3062 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3063 Ordering::Less => i += 1,
3064 Ordering::Greater => break,
3065 Ordering::Equal => {
3066 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3067 Ordering::Less => i += 1,
3068 Ordering::Equal => break,
3069 Ordering::Greater => break,
3070 }
3071 }
3072 }
3073 }
3074 this.autoclose_regions.insert(
3075 i,
3076 AutocloseRegion {
3077 selection_id,
3078 range: start..end,
3079 pair,
3080 },
3081 );
3082 }
3083
3084 let had_active_inline_completion = this.has_active_inline_completion();
3085 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3086 s.select(new_selections)
3087 });
3088
3089 if !bracket_inserted {
3090 if let Some(on_type_format_task) =
3091 this.trigger_on_type_formatting(text.to_string(), window, cx)
3092 {
3093 on_type_format_task.detach_and_log_err(cx);
3094 }
3095 }
3096
3097 let editor_settings = EditorSettings::get_global(cx);
3098 if bracket_inserted
3099 && (editor_settings.auto_signature_help
3100 || editor_settings.show_signature_help_after_edits)
3101 {
3102 this.show_signature_help(&ShowSignatureHelp, window, cx);
3103 }
3104
3105 let trigger_in_words =
3106 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3107 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3108 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3109 this.refresh_inline_completion(true, false, window, cx);
3110 });
3111 }
3112
3113 fn find_possible_emoji_shortcode_at_position(
3114 snapshot: &MultiBufferSnapshot,
3115 position: Point,
3116 ) -> Option<String> {
3117 let mut chars = Vec::new();
3118 let mut found_colon = false;
3119 for char in snapshot.reversed_chars_at(position).take(100) {
3120 // Found a possible emoji shortcode in the middle of the buffer
3121 if found_colon {
3122 if char.is_whitespace() {
3123 chars.reverse();
3124 return Some(chars.iter().collect());
3125 }
3126 // If the previous character is not a whitespace, we are in the middle of a word
3127 // and we only want to complete the shortcode if the word is made up of other emojis
3128 let mut containing_word = String::new();
3129 for ch in snapshot
3130 .reversed_chars_at(position)
3131 .skip(chars.len() + 1)
3132 .take(100)
3133 {
3134 if ch.is_whitespace() {
3135 break;
3136 }
3137 containing_word.push(ch);
3138 }
3139 let containing_word = containing_word.chars().rev().collect::<String>();
3140 if util::word_consists_of_emojis(containing_word.as_str()) {
3141 chars.reverse();
3142 return Some(chars.iter().collect());
3143 }
3144 }
3145
3146 if char.is_whitespace() || !char.is_ascii() {
3147 return None;
3148 }
3149 if char == ':' {
3150 found_colon = true;
3151 } else {
3152 chars.push(char);
3153 }
3154 }
3155 // Found a possible emoji shortcode at the beginning of the buffer
3156 chars.reverse();
3157 Some(chars.iter().collect())
3158 }
3159
3160 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3161 self.transact(window, cx, |this, window, cx| {
3162 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3163 let selections = this.selections.all::<usize>(cx);
3164 let multi_buffer = this.buffer.read(cx);
3165 let buffer = multi_buffer.snapshot(cx);
3166 selections
3167 .iter()
3168 .map(|selection| {
3169 let start_point = selection.start.to_point(&buffer);
3170 let mut indent =
3171 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3172 indent.len = cmp::min(indent.len, start_point.column);
3173 let start = selection.start;
3174 let end = selection.end;
3175 let selection_is_empty = start == end;
3176 let language_scope = buffer.language_scope_at(start);
3177 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3178 &language_scope
3179 {
3180 let insert_extra_newline =
3181 insert_extra_newline_brackets(&buffer, start..end, language)
3182 || insert_extra_newline_tree_sitter(&buffer, start..end);
3183
3184 // Comment extension on newline is allowed only for cursor selections
3185 let comment_delimiter = maybe!({
3186 if !selection_is_empty {
3187 return None;
3188 }
3189
3190 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3191 return None;
3192 }
3193
3194 let delimiters = language.line_comment_prefixes();
3195 let max_len_of_delimiter =
3196 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3197 let (snapshot, range) =
3198 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3199
3200 let mut index_of_first_non_whitespace = 0;
3201 let comment_candidate = snapshot
3202 .chars_for_range(range)
3203 .skip_while(|c| {
3204 let should_skip = c.is_whitespace();
3205 if should_skip {
3206 index_of_first_non_whitespace += 1;
3207 }
3208 should_skip
3209 })
3210 .take(max_len_of_delimiter)
3211 .collect::<String>();
3212 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3213 comment_candidate.starts_with(comment_prefix.as_ref())
3214 })?;
3215 let cursor_is_placed_after_comment_marker =
3216 index_of_first_non_whitespace + comment_prefix.len()
3217 <= start_point.column as usize;
3218 if cursor_is_placed_after_comment_marker {
3219 Some(comment_prefix.clone())
3220 } else {
3221 None
3222 }
3223 });
3224 (comment_delimiter, insert_extra_newline)
3225 } else {
3226 (None, false)
3227 };
3228
3229 let capacity_for_delimiter = comment_delimiter
3230 .as_deref()
3231 .map(str::len)
3232 .unwrap_or_default();
3233 let mut new_text =
3234 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3235 new_text.push('\n');
3236 new_text.extend(indent.chars());
3237 if let Some(delimiter) = &comment_delimiter {
3238 new_text.push_str(delimiter);
3239 }
3240 if insert_extra_newline {
3241 new_text = new_text.repeat(2);
3242 }
3243
3244 let anchor = buffer.anchor_after(end);
3245 let new_selection = selection.map(|_| anchor);
3246 (
3247 (start..end, new_text),
3248 (insert_extra_newline, new_selection),
3249 )
3250 })
3251 .unzip()
3252 };
3253
3254 this.edit_with_autoindent(edits, cx);
3255 let buffer = this.buffer.read(cx).snapshot(cx);
3256 let new_selections = selection_fixup_info
3257 .into_iter()
3258 .map(|(extra_newline_inserted, new_selection)| {
3259 let mut cursor = new_selection.end.to_point(&buffer);
3260 if extra_newline_inserted {
3261 cursor.row -= 1;
3262 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3263 }
3264 new_selection.map(|_| cursor)
3265 })
3266 .collect();
3267
3268 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3269 s.select(new_selections)
3270 });
3271 this.refresh_inline_completion(true, false, window, cx);
3272 });
3273 }
3274
3275 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3276 let buffer = self.buffer.read(cx);
3277 let snapshot = buffer.snapshot(cx);
3278
3279 let mut edits = Vec::new();
3280 let mut rows = Vec::new();
3281
3282 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3283 let cursor = selection.head();
3284 let row = cursor.row;
3285
3286 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3287
3288 let newline = "\n".to_string();
3289 edits.push((start_of_line..start_of_line, newline));
3290
3291 rows.push(row + rows_inserted as u32);
3292 }
3293
3294 self.transact(window, cx, |editor, window, cx| {
3295 editor.edit(edits, cx);
3296
3297 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3298 let mut index = 0;
3299 s.move_cursors_with(|map, _, _| {
3300 let row = rows[index];
3301 index += 1;
3302
3303 let point = Point::new(row, 0);
3304 let boundary = map.next_line_boundary(point).1;
3305 let clipped = map.clip_point(boundary, Bias::Left);
3306
3307 (clipped, SelectionGoal::None)
3308 });
3309 });
3310
3311 let mut indent_edits = Vec::new();
3312 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3313 for row in rows {
3314 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3315 for (row, indent) in indents {
3316 if indent.len == 0 {
3317 continue;
3318 }
3319
3320 let text = match indent.kind {
3321 IndentKind::Space => " ".repeat(indent.len as usize),
3322 IndentKind::Tab => "\t".repeat(indent.len as usize),
3323 };
3324 let point = Point::new(row.0, 0);
3325 indent_edits.push((point..point, text));
3326 }
3327 }
3328 editor.edit(indent_edits, cx);
3329 });
3330 }
3331
3332 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3333 let buffer = self.buffer.read(cx);
3334 let snapshot = buffer.snapshot(cx);
3335
3336 let mut edits = Vec::new();
3337 let mut rows = Vec::new();
3338 let mut rows_inserted = 0;
3339
3340 for selection in self.selections.all_adjusted(cx) {
3341 let cursor = selection.head();
3342 let row = cursor.row;
3343
3344 let point = Point::new(row + 1, 0);
3345 let start_of_line = snapshot.clip_point(point, Bias::Left);
3346
3347 let newline = "\n".to_string();
3348 edits.push((start_of_line..start_of_line, newline));
3349
3350 rows_inserted += 1;
3351 rows.push(row + rows_inserted);
3352 }
3353
3354 self.transact(window, cx, |editor, window, cx| {
3355 editor.edit(edits, cx);
3356
3357 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3358 let mut index = 0;
3359 s.move_cursors_with(|map, _, _| {
3360 let row = rows[index];
3361 index += 1;
3362
3363 let point = Point::new(row, 0);
3364 let boundary = map.next_line_boundary(point).1;
3365 let clipped = map.clip_point(boundary, Bias::Left);
3366
3367 (clipped, SelectionGoal::None)
3368 });
3369 });
3370
3371 let mut indent_edits = Vec::new();
3372 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3373 for row in rows {
3374 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3375 for (row, indent) in indents {
3376 if indent.len == 0 {
3377 continue;
3378 }
3379
3380 let text = match indent.kind {
3381 IndentKind::Space => " ".repeat(indent.len as usize),
3382 IndentKind::Tab => "\t".repeat(indent.len as usize),
3383 };
3384 let point = Point::new(row.0, 0);
3385 indent_edits.push((point..point, text));
3386 }
3387 }
3388 editor.edit(indent_edits, cx);
3389 });
3390 }
3391
3392 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3393 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3394 original_start_columns: Vec::new(),
3395 });
3396 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3397 }
3398
3399 fn insert_with_autoindent_mode(
3400 &mut self,
3401 text: &str,
3402 autoindent_mode: Option<AutoindentMode>,
3403 window: &mut Window,
3404 cx: &mut Context<Self>,
3405 ) {
3406 if self.read_only(cx) {
3407 return;
3408 }
3409
3410 let text: Arc<str> = text.into();
3411 self.transact(window, cx, |this, window, cx| {
3412 let old_selections = this.selections.all_adjusted(cx);
3413 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3414 let anchors = {
3415 let snapshot = buffer.read(cx);
3416 old_selections
3417 .iter()
3418 .map(|s| {
3419 let anchor = snapshot.anchor_after(s.head());
3420 s.map(|_| anchor)
3421 })
3422 .collect::<Vec<_>>()
3423 };
3424 buffer.edit(
3425 old_selections
3426 .iter()
3427 .map(|s| (s.start..s.end, text.clone())),
3428 autoindent_mode,
3429 cx,
3430 );
3431 anchors
3432 });
3433
3434 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3435 s.select_anchors(selection_anchors);
3436 });
3437
3438 cx.notify();
3439 });
3440 }
3441
3442 fn trigger_completion_on_input(
3443 &mut self,
3444 text: &str,
3445 trigger_in_words: bool,
3446 window: &mut Window,
3447 cx: &mut Context<Self>,
3448 ) {
3449 if self.is_completion_trigger(text, trigger_in_words, cx) {
3450 self.show_completions(
3451 &ShowCompletions {
3452 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3453 },
3454 window,
3455 cx,
3456 );
3457 } else {
3458 self.hide_context_menu(window, cx);
3459 }
3460 }
3461
3462 fn is_completion_trigger(
3463 &self,
3464 text: &str,
3465 trigger_in_words: bool,
3466 cx: &mut Context<Self>,
3467 ) -> bool {
3468 let position = self.selections.newest_anchor().head();
3469 let multibuffer = self.buffer.read(cx);
3470 let Some(buffer) = position
3471 .buffer_id
3472 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3473 else {
3474 return false;
3475 };
3476
3477 if let Some(completion_provider) = &self.completion_provider {
3478 completion_provider.is_completion_trigger(
3479 &buffer,
3480 position.text_anchor,
3481 text,
3482 trigger_in_words,
3483 cx,
3484 )
3485 } else {
3486 false
3487 }
3488 }
3489
3490 /// If any empty selections is touching the start of its innermost containing autoclose
3491 /// region, expand it to select the brackets.
3492 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3493 let selections = self.selections.all::<usize>(cx);
3494 let buffer = self.buffer.read(cx).read(cx);
3495 let new_selections = self
3496 .selections_with_autoclose_regions(selections, &buffer)
3497 .map(|(mut selection, region)| {
3498 if !selection.is_empty() {
3499 return selection;
3500 }
3501
3502 if let Some(region) = region {
3503 let mut range = region.range.to_offset(&buffer);
3504 if selection.start == range.start && range.start >= region.pair.start.len() {
3505 range.start -= region.pair.start.len();
3506 if buffer.contains_str_at(range.start, ®ion.pair.start)
3507 && buffer.contains_str_at(range.end, ®ion.pair.end)
3508 {
3509 range.end += region.pair.end.len();
3510 selection.start = range.start;
3511 selection.end = range.end;
3512
3513 return selection;
3514 }
3515 }
3516 }
3517
3518 let always_treat_brackets_as_autoclosed = buffer
3519 .settings_at(selection.start, cx)
3520 .always_treat_brackets_as_autoclosed;
3521
3522 if !always_treat_brackets_as_autoclosed {
3523 return selection;
3524 }
3525
3526 if let Some(scope) = buffer.language_scope_at(selection.start) {
3527 for (pair, enabled) in scope.brackets() {
3528 if !enabled || !pair.close {
3529 continue;
3530 }
3531
3532 if buffer.contains_str_at(selection.start, &pair.end) {
3533 let pair_start_len = pair.start.len();
3534 if buffer.contains_str_at(
3535 selection.start.saturating_sub(pair_start_len),
3536 &pair.start,
3537 ) {
3538 selection.start -= pair_start_len;
3539 selection.end += pair.end.len();
3540
3541 return selection;
3542 }
3543 }
3544 }
3545 }
3546
3547 selection
3548 })
3549 .collect();
3550
3551 drop(buffer);
3552 self.change_selections(None, window, cx, |selections| {
3553 selections.select(new_selections)
3554 });
3555 }
3556
3557 /// Iterate the given selections, and for each one, find the smallest surrounding
3558 /// autoclose region. This uses the ordering of the selections and the autoclose
3559 /// regions to avoid repeated comparisons.
3560 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3561 &'a self,
3562 selections: impl IntoIterator<Item = Selection<D>>,
3563 buffer: &'a MultiBufferSnapshot,
3564 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3565 let mut i = 0;
3566 let mut regions = self.autoclose_regions.as_slice();
3567 selections.into_iter().map(move |selection| {
3568 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3569
3570 let mut enclosing = None;
3571 while let Some(pair_state) = regions.get(i) {
3572 if pair_state.range.end.to_offset(buffer) < range.start {
3573 regions = ®ions[i + 1..];
3574 i = 0;
3575 } else if pair_state.range.start.to_offset(buffer) > range.end {
3576 break;
3577 } else {
3578 if pair_state.selection_id == selection.id {
3579 enclosing = Some(pair_state);
3580 }
3581 i += 1;
3582 }
3583 }
3584
3585 (selection, enclosing)
3586 })
3587 }
3588
3589 /// Remove any autoclose regions that no longer contain their selection.
3590 fn invalidate_autoclose_regions(
3591 &mut self,
3592 mut selections: &[Selection<Anchor>],
3593 buffer: &MultiBufferSnapshot,
3594 ) {
3595 self.autoclose_regions.retain(|state| {
3596 let mut i = 0;
3597 while let Some(selection) = selections.get(i) {
3598 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3599 selections = &selections[1..];
3600 continue;
3601 }
3602 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3603 break;
3604 }
3605 if selection.id == state.selection_id {
3606 return true;
3607 } else {
3608 i += 1;
3609 }
3610 }
3611 false
3612 });
3613 }
3614
3615 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3616 let offset = position.to_offset(buffer);
3617 let (word_range, kind) = buffer.surrounding_word(offset, true);
3618 if offset > word_range.start && kind == Some(CharKind::Word) {
3619 Some(
3620 buffer
3621 .text_for_range(word_range.start..offset)
3622 .collect::<String>(),
3623 )
3624 } else {
3625 None
3626 }
3627 }
3628
3629 pub fn toggle_inlay_hints(
3630 &mut self,
3631 _: &ToggleInlayHints,
3632 _: &mut Window,
3633 cx: &mut Context<Self>,
3634 ) {
3635 self.refresh_inlay_hints(
3636 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3637 cx,
3638 );
3639 }
3640
3641 pub fn inlay_hints_enabled(&self) -> bool {
3642 self.inlay_hint_cache.enabled
3643 }
3644
3645 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3646 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3647 return;
3648 }
3649
3650 let reason_description = reason.description();
3651 let ignore_debounce = matches!(
3652 reason,
3653 InlayHintRefreshReason::SettingsChange(_)
3654 | InlayHintRefreshReason::Toggle(_)
3655 | InlayHintRefreshReason::ExcerptsRemoved(_)
3656 );
3657 let (invalidate_cache, required_languages) = match reason {
3658 InlayHintRefreshReason::Toggle(enabled) => {
3659 self.inlay_hint_cache.enabled = enabled;
3660 if enabled {
3661 (InvalidationStrategy::RefreshRequested, None)
3662 } else {
3663 self.inlay_hint_cache.clear();
3664 self.splice_inlays(
3665 &self
3666 .visible_inlay_hints(cx)
3667 .iter()
3668 .map(|inlay| inlay.id)
3669 .collect::<Vec<InlayId>>(),
3670 Vec::new(),
3671 cx,
3672 );
3673 return;
3674 }
3675 }
3676 InlayHintRefreshReason::SettingsChange(new_settings) => {
3677 match self.inlay_hint_cache.update_settings(
3678 &self.buffer,
3679 new_settings,
3680 self.visible_inlay_hints(cx),
3681 cx,
3682 ) {
3683 ControlFlow::Break(Some(InlaySplice {
3684 to_remove,
3685 to_insert,
3686 })) => {
3687 self.splice_inlays(&to_remove, to_insert, cx);
3688 return;
3689 }
3690 ControlFlow::Break(None) => return,
3691 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3692 }
3693 }
3694 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3695 if let Some(InlaySplice {
3696 to_remove,
3697 to_insert,
3698 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3699 {
3700 self.splice_inlays(&to_remove, to_insert, cx);
3701 }
3702 return;
3703 }
3704 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3705 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3706 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3707 }
3708 InlayHintRefreshReason::RefreshRequested => {
3709 (InvalidationStrategy::RefreshRequested, None)
3710 }
3711 };
3712
3713 if let Some(InlaySplice {
3714 to_remove,
3715 to_insert,
3716 }) = self.inlay_hint_cache.spawn_hint_refresh(
3717 reason_description,
3718 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3719 invalidate_cache,
3720 ignore_debounce,
3721 cx,
3722 ) {
3723 self.splice_inlays(&to_remove, to_insert, cx);
3724 }
3725 }
3726
3727 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3728 self.display_map
3729 .read(cx)
3730 .current_inlays()
3731 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3732 .cloned()
3733 .collect()
3734 }
3735
3736 pub fn excerpts_for_inlay_hints_query(
3737 &self,
3738 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3739 cx: &mut Context<Editor>,
3740 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3741 let Some(project) = self.project.as_ref() else {
3742 return HashMap::default();
3743 };
3744 let project = project.read(cx);
3745 let multi_buffer = self.buffer().read(cx);
3746 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3747 let multi_buffer_visible_start = self
3748 .scroll_manager
3749 .anchor()
3750 .anchor
3751 .to_point(&multi_buffer_snapshot);
3752 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3753 multi_buffer_visible_start
3754 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3755 Bias::Left,
3756 );
3757 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3758 multi_buffer_snapshot
3759 .range_to_buffer_ranges(multi_buffer_visible_range)
3760 .into_iter()
3761 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3762 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3763 let buffer_file = project::File::from_dyn(buffer.file())?;
3764 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3765 let worktree_entry = buffer_worktree
3766 .read(cx)
3767 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3768 if worktree_entry.is_ignored {
3769 return None;
3770 }
3771
3772 let language = buffer.language()?;
3773 if let Some(restrict_to_languages) = restrict_to_languages {
3774 if !restrict_to_languages.contains(language) {
3775 return None;
3776 }
3777 }
3778 Some((
3779 excerpt_id,
3780 (
3781 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3782 buffer.version().clone(),
3783 excerpt_visible_range,
3784 ),
3785 ))
3786 })
3787 .collect()
3788 }
3789
3790 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3791 TextLayoutDetails {
3792 text_system: window.text_system().clone(),
3793 editor_style: self.style.clone().unwrap(),
3794 rem_size: window.rem_size(),
3795 scroll_anchor: self.scroll_manager.anchor(),
3796 visible_rows: self.visible_line_count(),
3797 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3798 }
3799 }
3800
3801 pub fn splice_inlays(
3802 &self,
3803 to_remove: &[InlayId],
3804 to_insert: Vec<Inlay>,
3805 cx: &mut Context<Self>,
3806 ) {
3807 self.display_map.update(cx, |display_map, cx| {
3808 display_map.splice_inlays(to_remove, to_insert, cx)
3809 });
3810 cx.notify();
3811 }
3812
3813 fn trigger_on_type_formatting(
3814 &self,
3815 input: String,
3816 window: &mut Window,
3817 cx: &mut Context<Self>,
3818 ) -> Option<Task<Result<()>>> {
3819 if input.len() != 1 {
3820 return None;
3821 }
3822
3823 let project = self.project.as_ref()?;
3824 let position = self.selections.newest_anchor().head();
3825 let (buffer, buffer_position) = self
3826 .buffer
3827 .read(cx)
3828 .text_anchor_for_position(position, cx)?;
3829
3830 let settings = language_settings::language_settings(
3831 buffer
3832 .read(cx)
3833 .language_at(buffer_position)
3834 .map(|l| l.name()),
3835 buffer.read(cx).file(),
3836 cx,
3837 );
3838 if !settings.use_on_type_format {
3839 return None;
3840 }
3841
3842 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3843 // hence we do LSP request & edit on host side only — add formats to host's history.
3844 let push_to_lsp_host_history = true;
3845 // If this is not the host, append its history with new edits.
3846 let push_to_client_history = project.read(cx).is_via_collab();
3847
3848 let on_type_formatting = project.update(cx, |project, cx| {
3849 project.on_type_format(
3850 buffer.clone(),
3851 buffer_position,
3852 input,
3853 push_to_lsp_host_history,
3854 cx,
3855 )
3856 });
3857 Some(cx.spawn_in(window, |editor, mut cx| async move {
3858 if let Some(transaction) = on_type_formatting.await? {
3859 if push_to_client_history {
3860 buffer
3861 .update(&mut cx, |buffer, _| {
3862 buffer.push_transaction(transaction, Instant::now());
3863 })
3864 .ok();
3865 }
3866 editor.update(&mut cx, |editor, cx| {
3867 editor.refresh_document_highlights(cx);
3868 })?;
3869 }
3870 Ok(())
3871 }))
3872 }
3873
3874 pub fn show_completions(
3875 &mut self,
3876 options: &ShowCompletions,
3877 window: &mut Window,
3878 cx: &mut Context<Self>,
3879 ) {
3880 if self.pending_rename.is_some() {
3881 return;
3882 }
3883
3884 let Some(provider) = self.completion_provider.as_ref() else {
3885 return;
3886 };
3887
3888 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3889 return;
3890 }
3891
3892 let position = self.selections.newest_anchor().head();
3893 if position.diff_base_anchor.is_some() {
3894 return;
3895 }
3896 let (buffer, buffer_position) =
3897 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3898 output
3899 } else {
3900 return;
3901 };
3902 let show_completion_documentation = buffer
3903 .read(cx)
3904 .snapshot()
3905 .settings_at(buffer_position, cx)
3906 .show_completion_documentation;
3907
3908 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3909
3910 let trigger_kind = match &options.trigger {
3911 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3912 CompletionTriggerKind::TRIGGER_CHARACTER
3913 }
3914 _ => CompletionTriggerKind::INVOKED,
3915 };
3916 let completion_context = CompletionContext {
3917 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3918 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3919 Some(String::from(trigger))
3920 } else {
3921 None
3922 }
3923 }),
3924 trigger_kind,
3925 };
3926 let completions =
3927 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3928 let sort_completions = provider.sort_completions();
3929
3930 let id = post_inc(&mut self.next_completion_id);
3931 let task = cx.spawn_in(window, |editor, mut cx| {
3932 async move {
3933 editor.update(&mut cx, |this, _| {
3934 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3935 })?;
3936 let completions = completions.await.log_err();
3937 let menu = if let Some(completions) = completions {
3938 let mut menu = CompletionsMenu::new(
3939 id,
3940 sort_completions,
3941 show_completion_documentation,
3942 position,
3943 buffer.clone(),
3944 completions.into(),
3945 );
3946
3947 menu.filter(query.as_deref(), cx.background_executor().clone())
3948 .await;
3949
3950 menu.visible().then_some(menu)
3951 } else {
3952 None
3953 };
3954
3955 editor.update_in(&mut cx, |editor, window, cx| {
3956 match editor.context_menu.borrow().as_ref() {
3957 None => {}
3958 Some(CodeContextMenu::Completions(prev_menu)) => {
3959 if prev_menu.id > id {
3960 return;
3961 }
3962 }
3963 _ => return,
3964 }
3965
3966 if editor.focus_handle.is_focused(window) && menu.is_some() {
3967 let mut menu = menu.unwrap();
3968 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3969
3970 *editor.context_menu.borrow_mut() =
3971 Some(CodeContextMenu::Completions(menu));
3972
3973 if editor.show_edit_predictions_in_menu() {
3974 editor.update_visible_inline_completion(window, cx);
3975 } else {
3976 editor.discard_inline_completion(false, cx);
3977 }
3978
3979 cx.notify();
3980 } else if editor.completion_tasks.len() <= 1 {
3981 // If there are no more completion tasks and the last menu was
3982 // empty, we should hide it.
3983 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3984 // If it was already hidden and we don't show inline
3985 // completions in the menu, we should also show the
3986 // inline-completion when available.
3987 if was_hidden && editor.show_edit_predictions_in_menu() {
3988 editor.update_visible_inline_completion(window, cx);
3989 }
3990 }
3991 })?;
3992
3993 Ok::<_, anyhow::Error>(())
3994 }
3995 .log_err()
3996 });
3997
3998 self.completion_tasks.push((id, task));
3999 }
4000
4001 pub fn confirm_completion(
4002 &mut self,
4003 action: &ConfirmCompletion,
4004 window: &mut Window,
4005 cx: &mut Context<Self>,
4006 ) -> Option<Task<Result<()>>> {
4007 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4008 }
4009
4010 pub fn compose_completion(
4011 &mut self,
4012 action: &ComposeCompletion,
4013 window: &mut Window,
4014 cx: &mut Context<Self>,
4015 ) -> Option<Task<Result<()>>> {
4016 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4017 }
4018
4019 fn do_completion(
4020 &mut self,
4021 item_ix: Option<usize>,
4022 intent: CompletionIntent,
4023 window: &mut Window,
4024 cx: &mut Context<Editor>,
4025 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4026 use language::ToOffset as _;
4027
4028 let completions_menu =
4029 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4030 menu
4031 } else {
4032 return None;
4033 };
4034
4035 let entries = completions_menu.entries.borrow();
4036 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4037 if self.show_edit_predictions_in_menu() {
4038 self.discard_inline_completion(true, cx);
4039 }
4040 let candidate_id = mat.candidate_id;
4041 drop(entries);
4042
4043 let buffer_handle = completions_menu.buffer;
4044 let completion = completions_menu
4045 .completions
4046 .borrow()
4047 .get(candidate_id)?
4048 .clone();
4049 cx.stop_propagation();
4050
4051 let snippet;
4052 let text;
4053
4054 if completion.is_snippet() {
4055 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4056 text = snippet.as_ref().unwrap().text.clone();
4057 } else {
4058 snippet = None;
4059 text = completion.new_text.clone();
4060 };
4061 let selections = self.selections.all::<usize>(cx);
4062 let buffer = buffer_handle.read(cx);
4063 let old_range = completion.old_range.to_offset(buffer);
4064 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4065
4066 let newest_selection = self.selections.newest_anchor();
4067 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4068 return None;
4069 }
4070
4071 let lookbehind = newest_selection
4072 .start
4073 .text_anchor
4074 .to_offset(buffer)
4075 .saturating_sub(old_range.start);
4076 let lookahead = old_range
4077 .end
4078 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4079 let mut common_prefix_len = old_text
4080 .bytes()
4081 .zip(text.bytes())
4082 .take_while(|(a, b)| a == b)
4083 .count();
4084
4085 let snapshot = self.buffer.read(cx).snapshot(cx);
4086 let mut range_to_replace: Option<Range<isize>> = None;
4087 let mut ranges = Vec::new();
4088 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4089 for selection in &selections {
4090 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4091 let start = selection.start.saturating_sub(lookbehind);
4092 let end = selection.end + lookahead;
4093 if selection.id == newest_selection.id {
4094 range_to_replace = Some(
4095 ((start + common_prefix_len) as isize - selection.start as isize)
4096 ..(end as isize - selection.start as isize),
4097 );
4098 }
4099 ranges.push(start + common_prefix_len..end);
4100 } else {
4101 common_prefix_len = 0;
4102 ranges.clear();
4103 ranges.extend(selections.iter().map(|s| {
4104 if s.id == newest_selection.id {
4105 range_to_replace = Some(
4106 old_range.start.to_offset_utf16(&snapshot).0 as isize
4107 - selection.start as isize
4108 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4109 - selection.start as isize,
4110 );
4111 old_range.clone()
4112 } else {
4113 s.start..s.end
4114 }
4115 }));
4116 break;
4117 }
4118 if !self.linked_edit_ranges.is_empty() {
4119 let start_anchor = snapshot.anchor_before(selection.head());
4120 let end_anchor = snapshot.anchor_after(selection.tail());
4121 if let Some(ranges) = self
4122 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4123 {
4124 for (buffer, edits) in ranges {
4125 linked_edits.entry(buffer.clone()).or_default().extend(
4126 edits
4127 .into_iter()
4128 .map(|range| (range, text[common_prefix_len..].to_owned())),
4129 );
4130 }
4131 }
4132 }
4133 }
4134 let text = &text[common_prefix_len..];
4135
4136 cx.emit(EditorEvent::InputHandled {
4137 utf16_range_to_replace: range_to_replace,
4138 text: text.into(),
4139 });
4140
4141 self.transact(window, cx, |this, window, cx| {
4142 if let Some(mut snippet) = snippet {
4143 snippet.text = text.to_string();
4144 for tabstop in snippet
4145 .tabstops
4146 .iter_mut()
4147 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4148 {
4149 tabstop.start -= common_prefix_len as isize;
4150 tabstop.end -= common_prefix_len as isize;
4151 }
4152
4153 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4154 } else {
4155 this.buffer.update(cx, |buffer, cx| {
4156 buffer.edit(
4157 ranges.iter().map(|range| (range.clone(), text)),
4158 this.autoindent_mode.clone(),
4159 cx,
4160 );
4161 });
4162 }
4163 for (buffer, edits) in linked_edits {
4164 buffer.update(cx, |buffer, cx| {
4165 let snapshot = buffer.snapshot();
4166 let edits = edits
4167 .into_iter()
4168 .map(|(range, text)| {
4169 use text::ToPoint as TP;
4170 let end_point = TP::to_point(&range.end, &snapshot);
4171 let start_point = TP::to_point(&range.start, &snapshot);
4172 (start_point..end_point, text)
4173 })
4174 .sorted_by_key(|(range, _)| range.start)
4175 .collect::<Vec<_>>();
4176 buffer.edit(edits, None, cx);
4177 })
4178 }
4179
4180 this.refresh_inline_completion(true, false, window, cx);
4181 });
4182
4183 let show_new_completions_on_confirm = completion
4184 .confirm
4185 .as_ref()
4186 .map_or(false, |confirm| confirm(intent, window, cx));
4187 if show_new_completions_on_confirm {
4188 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4189 }
4190
4191 let provider = self.completion_provider.as_ref()?;
4192 drop(completion);
4193 let apply_edits = provider.apply_additional_edits_for_completion(
4194 buffer_handle,
4195 completions_menu.completions.clone(),
4196 candidate_id,
4197 true,
4198 cx,
4199 );
4200
4201 let editor_settings = EditorSettings::get_global(cx);
4202 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4203 // After the code completion is finished, users often want to know what signatures are needed.
4204 // so we should automatically call signature_help
4205 self.show_signature_help(&ShowSignatureHelp, window, cx);
4206 }
4207
4208 Some(cx.foreground_executor().spawn(async move {
4209 apply_edits.await?;
4210 Ok(())
4211 }))
4212 }
4213
4214 pub fn toggle_code_actions(
4215 &mut self,
4216 action: &ToggleCodeActions,
4217 window: &mut Window,
4218 cx: &mut Context<Self>,
4219 ) {
4220 let mut context_menu = self.context_menu.borrow_mut();
4221 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4222 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4223 // Toggle if we're selecting the same one
4224 *context_menu = None;
4225 cx.notify();
4226 return;
4227 } else {
4228 // Otherwise, clear it and start a new one
4229 *context_menu = None;
4230 cx.notify();
4231 }
4232 }
4233 drop(context_menu);
4234 let snapshot = self.snapshot(window, cx);
4235 let deployed_from_indicator = action.deployed_from_indicator;
4236 let mut task = self.code_actions_task.take();
4237 let action = action.clone();
4238 cx.spawn_in(window, |editor, mut cx| async move {
4239 while let Some(prev_task) = task {
4240 prev_task.await.log_err();
4241 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4242 }
4243
4244 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4245 if editor.focus_handle.is_focused(window) {
4246 let multibuffer_point = action
4247 .deployed_from_indicator
4248 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4249 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4250 let (buffer, buffer_row) = snapshot
4251 .buffer_snapshot
4252 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4253 .and_then(|(buffer_snapshot, range)| {
4254 editor
4255 .buffer
4256 .read(cx)
4257 .buffer(buffer_snapshot.remote_id())
4258 .map(|buffer| (buffer, range.start.row))
4259 })?;
4260 let (_, code_actions) = editor
4261 .available_code_actions
4262 .clone()
4263 .and_then(|(location, code_actions)| {
4264 let snapshot = location.buffer.read(cx).snapshot();
4265 let point_range = location.range.to_point(&snapshot);
4266 let point_range = point_range.start.row..=point_range.end.row;
4267 if point_range.contains(&buffer_row) {
4268 Some((location, code_actions))
4269 } else {
4270 None
4271 }
4272 })
4273 .unzip();
4274 let buffer_id = buffer.read(cx).remote_id();
4275 let tasks = editor
4276 .tasks
4277 .get(&(buffer_id, buffer_row))
4278 .map(|t| Arc::new(t.to_owned()));
4279 if tasks.is_none() && code_actions.is_none() {
4280 return None;
4281 }
4282
4283 editor.completion_tasks.clear();
4284 editor.discard_inline_completion(false, cx);
4285 let task_context =
4286 tasks
4287 .as_ref()
4288 .zip(editor.project.clone())
4289 .map(|(tasks, project)| {
4290 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4291 });
4292
4293 Some(cx.spawn_in(window, |editor, mut cx| async move {
4294 let task_context = match task_context {
4295 Some(task_context) => task_context.await,
4296 None => None,
4297 };
4298 let resolved_tasks =
4299 tasks.zip(task_context).map(|(tasks, task_context)| {
4300 Rc::new(ResolvedTasks {
4301 templates: tasks.resolve(&task_context).collect(),
4302 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4303 multibuffer_point.row,
4304 tasks.column,
4305 )),
4306 })
4307 });
4308 let spawn_straight_away = resolved_tasks
4309 .as_ref()
4310 .map_or(false, |tasks| tasks.templates.len() == 1)
4311 && code_actions
4312 .as_ref()
4313 .map_or(true, |actions| actions.is_empty());
4314 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4315 *editor.context_menu.borrow_mut() =
4316 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4317 buffer,
4318 actions: CodeActionContents {
4319 tasks: resolved_tasks,
4320 actions: code_actions,
4321 },
4322 selected_item: Default::default(),
4323 scroll_handle: UniformListScrollHandle::default(),
4324 deployed_from_indicator,
4325 }));
4326 if spawn_straight_away {
4327 if let Some(task) = editor.confirm_code_action(
4328 &ConfirmCodeAction { item_ix: Some(0) },
4329 window,
4330 cx,
4331 ) {
4332 cx.notify();
4333 return task;
4334 }
4335 }
4336 cx.notify();
4337 Task::ready(Ok(()))
4338 }) {
4339 task.await
4340 } else {
4341 Ok(())
4342 }
4343 }))
4344 } else {
4345 Some(Task::ready(Ok(())))
4346 }
4347 })?;
4348 if let Some(task) = spawned_test_task {
4349 task.await?;
4350 }
4351
4352 Ok::<_, anyhow::Error>(())
4353 })
4354 .detach_and_log_err(cx);
4355 }
4356
4357 pub fn confirm_code_action(
4358 &mut self,
4359 action: &ConfirmCodeAction,
4360 window: &mut Window,
4361 cx: &mut Context<Self>,
4362 ) -> Option<Task<Result<()>>> {
4363 let actions_menu =
4364 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4365 menu
4366 } else {
4367 return None;
4368 };
4369 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4370 let action = actions_menu.actions.get(action_ix)?;
4371 let title = action.label();
4372 let buffer = actions_menu.buffer;
4373 let workspace = self.workspace()?;
4374
4375 match action {
4376 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4377 workspace.update(cx, |workspace, cx| {
4378 workspace::tasks::schedule_resolved_task(
4379 workspace,
4380 task_source_kind,
4381 resolved_task,
4382 false,
4383 cx,
4384 );
4385
4386 Some(Task::ready(Ok(())))
4387 })
4388 }
4389 CodeActionsItem::CodeAction {
4390 excerpt_id,
4391 action,
4392 provider,
4393 } => {
4394 let apply_code_action =
4395 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4396 let workspace = workspace.downgrade();
4397 Some(cx.spawn_in(window, |editor, cx| async move {
4398 let project_transaction = apply_code_action.await?;
4399 Self::open_project_transaction(
4400 &editor,
4401 workspace,
4402 project_transaction,
4403 title,
4404 cx,
4405 )
4406 .await
4407 }))
4408 }
4409 }
4410 }
4411
4412 pub async fn open_project_transaction(
4413 this: &WeakEntity<Editor>,
4414 workspace: WeakEntity<Workspace>,
4415 transaction: ProjectTransaction,
4416 title: String,
4417 mut cx: AsyncWindowContext,
4418 ) -> Result<()> {
4419 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4420 cx.update(|_, cx| {
4421 entries.sort_unstable_by_key(|(buffer, _)| {
4422 buffer.read(cx).file().map(|f| f.path().clone())
4423 });
4424 })?;
4425
4426 // If the project transaction's edits are all contained within this editor, then
4427 // avoid opening a new editor to display them.
4428
4429 if let Some((buffer, transaction)) = entries.first() {
4430 if entries.len() == 1 {
4431 let excerpt = this.update(&mut cx, |editor, cx| {
4432 editor
4433 .buffer()
4434 .read(cx)
4435 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4436 })?;
4437 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4438 if excerpted_buffer == *buffer {
4439 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4440 let excerpt_range = excerpt_range.to_offset(buffer);
4441 buffer
4442 .edited_ranges_for_transaction::<usize>(transaction)
4443 .all(|range| {
4444 excerpt_range.start <= range.start
4445 && excerpt_range.end >= range.end
4446 })
4447 })?;
4448
4449 if all_edits_within_excerpt {
4450 return Ok(());
4451 }
4452 }
4453 }
4454 }
4455 } else {
4456 return Ok(());
4457 }
4458
4459 let mut ranges_to_highlight = Vec::new();
4460 let excerpt_buffer = cx.new(|cx| {
4461 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4462 for (buffer_handle, transaction) in &entries {
4463 let buffer = buffer_handle.read(cx);
4464 ranges_to_highlight.extend(
4465 multibuffer.push_excerpts_with_context_lines(
4466 buffer_handle.clone(),
4467 buffer
4468 .edited_ranges_for_transaction::<usize>(transaction)
4469 .collect(),
4470 DEFAULT_MULTIBUFFER_CONTEXT,
4471 cx,
4472 ),
4473 );
4474 }
4475 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4476 multibuffer
4477 })?;
4478
4479 workspace.update_in(&mut cx, |workspace, window, cx| {
4480 let project = workspace.project().clone();
4481 let editor = cx
4482 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4483 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4484 editor.update(cx, |editor, cx| {
4485 editor.highlight_background::<Self>(
4486 &ranges_to_highlight,
4487 |theme| theme.editor_highlighted_line_background,
4488 cx,
4489 );
4490 });
4491 })?;
4492
4493 Ok(())
4494 }
4495
4496 pub fn clear_code_action_providers(&mut self) {
4497 self.code_action_providers.clear();
4498 self.available_code_actions.take();
4499 }
4500
4501 pub fn add_code_action_provider(
4502 &mut self,
4503 provider: Rc<dyn CodeActionProvider>,
4504 window: &mut Window,
4505 cx: &mut Context<Self>,
4506 ) {
4507 if self
4508 .code_action_providers
4509 .iter()
4510 .any(|existing_provider| existing_provider.id() == provider.id())
4511 {
4512 return;
4513 }
4514
4515 self.code_action_providers.push(provider);
4516 self.refresh_code_actions(window, cx);
4517 }
4518
4519 pub fn remove_code_action_provider(
4520 &mut self,
4521 id: Arc<str>,
4522 window: &mut Window,
4523 cx: &mut Context<Self>,
4524 ) {
4525 self.code_action_providers
4526 .retain(|provider| provider.id() != id);
4527 self.refresh_code_actions(window, cx);
4528 }
4529
4530 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4531 let buffer = self.buffer.read(cx);
4532 let newest_selection = self.selections.newest_anchor().clone();
4533 if newest_selection.head().diff_base_anchor.is_some() {
4534 return None;
4535 }
4536 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4537 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4538 if start_buffer != end_buffer {
4539 return None;
4540 }
4541
4542 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4543 cx.background_executor()
4544 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4545 .await;
4546
4547 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4548 let providers = this.code_action_providers.clone();
4549 let tasks = this
4550 .code_action_providers
4551 .iter()
4552 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4553 .collect::<Vec<_>>();
4554 (providers, tasks)
4555 })?;
4556
4557 let mut actions = Vec::new();
4558 for (provider, provider_actions) in
4559 providers.into_iter().zip(future::join_all(tasks).await)
4560 {
4561 if let Some(provider_actions) = provider_actions.log_err() {
4562 actions.extend(provider_actions.into_iter().map(|action| {
4563 AvailableCodeAction {
4564 excerpt_id: newest_selection.start.excerpt_id,
4565 action,
4566 provider: provider.clone(),
4567 }
4568 }));
4569 }
4570 }
4571
4572 this.update(&mut cx, |this, cx| {
4573 this.available_code_actions = if actions.is_empty() {
4574 None
4575 } else {
4576 Some((
4577 Location {
4578 buffer: start_buffer,
4579 range: start..end,
4580 },
4581 actions.into(),
4582 ))
4583 };
4584 cx.notify();
4585 })
4586 }));
4587 None
4588 }
4589
4590 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4591 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4592 self.show_git_blame_inline = false;
4593
4594 self.show_git_blame_inline_delay_task =
4595 Some(cx.spawn_in(window, |this, mut cx| async move {
4596 cx.background_executor().timer(delay).await;
4597
4598 this.update(&mut cx, |this, cx| {
4599 this.show_git_blame_inline = true;
4600 cx.notify();
4601 })
4602 .log_err();
4603 }));
4604 }
4605 }
4606
4607 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4608 if self.pending_rename.is_some() {
4609 return None;
4610 }
4611
4612 let provider = self.semantics_provider.clone()?;
4613 let buffer = self.buffer.read(cx);
4614 let newest_selection = self.selections.newest_anchor().clone();
4615 let cursor_position = newest_selection.head();
4616 let (cursor_buffer, cursor_buffer_position) =
4617 buffer.text_anchor_for_position(cursor_position, cx)?;
4618 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4619 if cursor_buffer != tail_buffer {
4620 return None;
4621 }
4622 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4623 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4624 cx.background_executor()
4625 .timer(Duration::from_millis(debounce))
4626 .await;
4627
4628 let highlights = if let Some(highlights) = cx
4629 .update(|cx| {
4630 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4631 })
4632 .ok()
4633 .flatten()
4634 {
4635 highlights.await.log_err()
4636 } else {
4637 None
4638 };
4639
4640 if let Some(highlights) = highlights {
4641 this.update(&mut cx, |this, cx| {
4642 if this.pending_rename.is_some() {
4643 return;
4644 }
4645
4646 let buffer_id = cursor_position.buffer_id;
4647 let buffer = this.buffer.read(cx);
4648 if !buffer
4649 .text_anchor_for_position(cursor_position, cx)
4650 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4651 {
4652 return;
4653 }
4654
4655 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4656 let mut write_ranges = Vec::new();
4657 let mut read_ranges = Vec::new();
4658 for highlight in highlights {
4659 for (excerpt_id, excerpt_range) in
4660 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4661 {
4662 let start = highlight
4663 .range
4664 .start
4665 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4666 let end = highlight
4667 .range
4668 .end
4669 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4670 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4671 continue;
4672 }
4673
4674 let range = Anchor {
4675 buffer_id,
4676 excerpt_id,
4677 text_anchor: start,
4678 diff_base_anchor: None,
4679 }..Anchor {
4680 buffer_id,
4681 excerpt_id,
4682 text_anchor: end,
4683 diff_base_anchor: None,
4684 };
4685 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4686 write_ranges.push(range);
4687 } else {
4688 read_ranges.push(range);
4689 }
4690 }
4691 }
4692
4693 this.highlight_background::<DocumentHighlightRead>(
4694 &read_ranges,
4695 |theme| theme.editor_document_highlight_read_background,
4696 cx,
4697 );
4698 this.highlight_background::<DocumentHighlightWrite>(
4699 &write_ranges,
4700 |theme| theme.editor_document_highlight_write_background,
4701 cx,
4702 );
4703 cx.notify();
4704 })
4705 .log_err();
4706 }
4707 }));
4708 None
4709 }
4710
4711 pub fn refresh_selected_text_highlights(
4712 &mut self,
4713 window: &mut Window,
4714 cx: &mut Context<Editor>,
4715 ) {
4716 self.selection_highlight_task.take();
4717 if !EditorSettings::get_global(cx).selection_highlight {
4718 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4719 return;
4720 }
4721 if self.selections.count() != 1 || self.selections.line_mode {
4722 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4723 return;
4724 }
4725 let selection = self.selections.newest::<Point>(cx);
4726 if selection.is_empty() || selection.start.row != selection.end.row {
4727 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4728 return;
4729 }
4730 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4731 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4732 cx.background_executor()
4733 .timer(Duration::from_millis(debounce))
4734 .await;
4735 let Some(Some(matches_task)) = editor
4736 .update_in(&mut cx, |editor, _, cx| {
4737 if editor.selections.count() != 1 || editor.selections.line_mode {
4738 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4739 return None;
4740 }
4741 let selection = editor.selections.newest::<Point>(cx);
4742 if selection.is_empty() || selection.start.row != selection.end.row {
4743 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4744 return None;
4745 }
4746 let buffer = editor.buffer().read(cx).snapshot(cx);
4747 let query = buffer.text_for_range(selection.range()).collect::<String>();
4748 if query.trim().is_empty() {
4749 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4750 return None;
4751 }
4752 Some(cx.background_spawn(async move {
4753 let mut ranges = Vec::new();
4754 let selection_anchors = selection.range().to_anchors(&buffer);
4755 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4756 for (search_buffer, search_range, excerpt_id) in
4757 buffer.range_to_buffer_ranges(range)
4758 {
4759 ranges.extend(
4760 project::search::SearchQuery::text(
4761 query.clone(),
4762 false,
4763 false,
4764 false,
4765 Default::default(),
4766 Default::default(),
4767 None,
4768 )
4769 .unwrap()
4770 .search(search_buffer, Some(search_range.clone()))
4771 .await
4772 .into_iter()
4773 .filter_map(
4774 |match_range| {
4775 let start = search_buffer.anchor_after(
4776 search_range.start + match_range.start,
4777 );
4778 let end = search_buffer.anchor_before(
4779 search_range.start + match_range.end,
4780 );
4781 let range = Anchor::range_in_buffer(
4782 excerpt_id,
4783 search_buffer.remote_id(),
4784 start..end,
4785 );
4786 (range != selection_anchors).then_some(range)
4787 },
4788 ),
4789 );
4790 }
4791 }
4792 ranges
4793 }))
4794 })
4795 .log_err()
4796 else {
4797 return;
4798 };
4799 let matches = matches_task.await;
4800 editor
4801 .update_in(&mut cx, |editor, _, cx| {
4802 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4803 if !matches.is_empty() {
4804 editor.highlight_background::<SelectedTextHighlight>(
4805 &matches,
4806 |theme| theme.editor_document_highlight_bracket_background,
4807 cx,
4808 )
4809 }
4810 })
4811 .log_err();
4812 }));
4813 }
4814
4815 pub fn refresh_inline_completion(
4816 &mut self,
4817 debounce: bool,
4818 user_requested: bool,
4819 window: &mut Window,
4820 cx: &mut Context<Self>,
4821 ) -> Option<()> {
4822 let provider = self.edit_prediction_provider()?;
4823 let cursor = self.selections.newest_anchor().head();
4824 let (buffer, cursor_buffer_position) =
4825 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4826
4827 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4828 self.discard_inline_completion(false, cx);
4829 return None;
4830 }
4831
4832 if !user_requested
4833 && (!self.should_show_edit_predictions()
4834 || !self.is_focused(window)
4835 || buffer.read(cx).is_empty())
4836 {
4837 self.discard_inline_completion(false, cx);
4838 return None;
4839 }
4840
4841 self.update_visible_inline_completion(window, cx);
4842 provider.refresh(
4843 self.project.clone(),
4844 buffer,
4845 cursor_buffer_position,
4846 debounce,
4847 cx,
4848 );
4849 Some(())
4850 }
4851
4852 fn show_edit_predictions_in_menu(&self) -> bool {
4853 match self.edit_prediction_settings {
4854 EditPredictionSettings::Disabled => false,
4855 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4856 }
4857 }
4858
4859 pub fn edit_predictions_enabled(&self) -> bool {
4860 match self.edit_prediction_settings {
4861 EditPredictionSettings::Disabled => false,
4862 EditPredictionSettings::Enabled { .. } => true,
4863 }
4864 }
4865
4866 fn edit_prediction_requires_modifier(&self) -> bool {
4867 match self.edit_prediction_settings {
4868 EditPredictionSettings::Disabled => false,
4869 EditPredictionSettings::Enabled {
4870 preview_requires_modifier,
4871 ..
4872 } => preview_requires_modifier,
4873 }
4874 }
4875
4876 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4877 if self.edit_prediction_provider.is_none() {
4878 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4879 } else {
4880 let selection = self.selections.newest_anchor();
4881 let cursor = selection.head();
4882
4883 if let Some((buffer, cursor_buffer_position)) =
4884 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4885 {
4886 self.edit_prediction_settings =
4887 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
4888 }
4889 }
4890 }
4891
4892 fn edit_prediction_settings_at_position(
4893 &self,
4894 buffer: &Entity<Buffer>,
4895 buffer_position: language::Anchor,
4896 cx: &App,
4897 ) -> EditPredictionSettings {
4898 if self.mode != EditorMode::Full
4899 || !self.show_inline_completions_override.unwrap_or(true)
4900 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4901 {
4902 return EditPredictionSettings::Disabled;
4903 }
4904
4905 let buffer = buffer.read(cx);
4906
4907 let file = buffer.file();
4908
4909 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4910 return EditPredictionSettings::Disabled;
4911 };
4912
4913 let by_provider = matches!(
4914 self.menu_inline_completions_policy,
4915 MenuInlineCompletionsPolicy::ByProvider
4916 );
4917
4918 let show_in_menu = by_provider
4919 && self
4920 .edit_prediction_provider
4921 .as_ref()
4922 .map_or(false, |provider| {
4923 provider.provider.show_completions_in_menu()
4924 });
4925
4926 let preview_requires_modifier =
4927 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4928
4929 EditPredictionSettings::Enabled {
4930 show_in_menu,
4931 preview_requires_modifier,
4932 }
4933 }
4934
4935 fn should_show_edit_predictions(&self) -> bool {
4936 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4937 }
4938
4939 pub fn edit_prediction_preview_is_active(&self) -> bool {
4940 matches!(
4941 self.edit_prediction_preview,
4942 EditPredictionPreview::Active { .. }
4943 )
4944 }
4945
4946 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
4947 let cursor = self.selections.newest_anchor().head();
4948 if let Some((buffer, cursor_position)) =
4949 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4950 {
4951 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
4952 } else {
4953 false
4954 }
4955 }
4956
4957 fn edit_predictions_enabled_in_buffer(
4958 &self,
4959 buffer: &Entity<Buffer>,
4960 buffer_position: language::Anchor,
4961 cx: &App,
4962 ) -> bool {
4963 maybe!({
4964 let provider = self.edit_prediction_provider()?;
4965 if !provider.is_enabled(&buffer, buffer_position, cx) {
4966 return Some(false);
4967 }
4968 let buffer = buffer.read(cx);
4969 let Some(file) = buffer.file() else {
4970 return Some(true);
4971 };
4972 let settings = all_language_settings(Some(file), cx);
4973 Some(settings.inline_completions_enabled_for_path(file.path()))
4974 })
4975 .unwrap_or(false)
4976 }
4977
4978 fn cycle_inline_completion(
4979 &mut self,
4980 direction: Direction,
4981 window: &mut Window,
4982 cx: &mut Context<Self>,
4983 ) -> Option<()> {
4984 let provider = self.edit_prediction_provider()?;
4985 let cursor = self.selections.newest_anchor().head();
4986 let (buffer, cursor_buffer_position) =
4987 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4988 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
4989 return None;
4990 }
4991
4992 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4993 self.update_visible_inline_completion(window, cx);
4994
4995 Some(())
4996 }
4997
4998 pub fn show_inline_completion(
4999 &mut self,
5000 _: &ShowEditPrediction,
5001 window: &mut Window,
5002 cx: &mut Context<Self>,
5003 ) {
5004 if !self.has_active_inline_completion() {
5005 self.refresh_inline_completion(false, true, window, cx);
5006 return;
5007 }
5008
5009 self.update_visible_inline_completion(window, cx);
5010 }
5011
5012 pub fn display_cursor_names(
5013 &mut self,
5014 _: &DisplayCursorNames,
5015 window: &mut Window,
5016 cx: &mut Context<Self>,
5017 ) {
5018 self.show_cursor_names(window, cx);
5019 }
5020
5021 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5022 self.show_cursor_names = true;
5023 cx.notify();
5024 cx.spawn_in(window, |this, mut cx| async move {
5025 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5026 this.update(&mut cx, |this, cx| {
5027 this.show_cursor_names = false;
5028 cx.notify()
5029 })
5030 .ok()
5031 })
5032 .detach();
5033 }
5034
5035 pub fn next_edit_prediction(
5036 &mut self,
5037 _: &NextEditPrediction,
5038 window: &mut Window,
5039 cx: &mut Context<Self>,
5040 ) {
5041 if self.has_active_inline_completion() {
5042 self.cycle_inline_completion(Direction::Next, window, cx);
5043 } else {
5044 let is_copilot_disabled = self
5045 .refresh_inline_completion(false, true, window, cx)
5046 .is_none();
5047 if is_copilot_disabled {
5048 cx.propagate();
5049 }
5050 }
5051 }
5052
5053 pub fn previous_edit_prediction(
5054 &mut self,
5055 _: &PreviousEditPrediction,
5056 window: &mut Window,
5057 cx: &mut Context<Self>,
5058 ) {
5059 if self.has_active_inline_completion() {
5060 self.cycle_inline_completion(Direction::Prev, window, cx);
5061 } else {
5062 let is_copilot_disabled = self
5063 .refresh_inline_completion(false, true, window, cx)
5064 .is_none();
5065 if is_copilot_disabled {
5066 cx.propagate();
5067 }
5068 }
5069 }
5070
5071 pub fn accept_edit_prediction(
5072 &mut self,
5073 _: &AcceptEditPrediction,
5074 window: &mut Window,
5075 cx: &mut Context<Self>,
5076 ) {
5077 if self.show_edit_predictions_in_menu() {
5078 self.hide_context_menu(window, cx);
5079 }
5080
5081 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5082 return;
5083 };
5084
5085 self.report_inline_completion_event(
5086 active_inline_completion.completion_id.clone(),
5087 true,
5088 cx,
5089 );
5090
5091 match &active_inline_completion.completion {
5092 InlineCompletion::Move { target, .. } => {
5093 let target = *target;
5094
5095 if let Some(position_map) = &self.last_position_map {
5096 if position_map
5097 .visible_row_range
5098 .contains(&target.to_display_point(&position_map.snapshot).row())
5099 || !self.edit_prediction_requires_modifier()
5100 {
5101 self.unfold_ranges(&[target..target], true, false, cx);
5102 // Note that this is also done in vim's handler of the Tab action.
5103 self.change_selections(
5104 Some(Autoscroll::newest()),
5105 window,
5106 cx,
5107 |selections| {
5108 selections.select_anchor_ranges([target..target]);
5109 },
5110 );
5111 self.clear_row_highlights::<EditPredictionPreview>();
5112
5113 self.edit_prediction_preview = EditPredictionPreview::Active {
5114 previous_scroll_position: None,
5115 };
5116 } else {
5117 self.edit_prediction_preview = EditPredictionPreview::Active {
5118 previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
5119 };
5120 self.highlight_rows::<EditPredictionPreview>(
5121 target..target,
5122 cx.theme().colors().editor_highlighted_line_background,
5123 true,
5124 cx,
5125 );
5126 self.request_autoscroll(Autoscroll::fit(), cx);
5127 }
5128 }
5129 }
5130 InlineCompletion::Edit { edits, .. } => {
5131 if let Some(provider) = self.edit_prediction_provider() {
5132 provider.accept(cx);
5133 }
5134
5135 let snapshot = self.buffer.read(cx).snapshot(cx);
5136 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5137
5138 self.buffer.update(cx, |buffer, cx| {
5139 buffer.edit(edits.iter().cloned(), None, cx)
5140 });
5141
5142 self.change_selections(None, window, cx, |s| {
5143 s.select_anchor_ranges([last_edit_end..last_edit_end])
5144 });
5145
5146 self.update_visible_inline_completion(window, cx);
5147 if self.active_inline_completion.is_none() {
5148 self.refresh_inline_completion(true, true, window, cx);
5149 }
5150
5151 cx.notify();
5152 }
5153 }
5154
5155 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5156 }
5157
5158 pub fn accept_partial_inline_completion(
5159 &mut self,
5160 _: &AcceptPartialEditPrediction,
5161 window: &mut Window,
5162 cx: &mut Context<Self>,
5163 ) {
5164 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5165 return;
5166 };
5167 if self.selections.count() != 1 {
5168 return;
5169 }
5170
5171 self.report_inline_completion_event(
5172 active_inline_completion.completion_id.clone(),
5173 true,
5174 cx,
5175 );
5176
5177 match &active_inline_completion.completion {
5178 InlineCompletion::Move { target, .. } => {
5179 let target = *target;
5180 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5181 selections.select_anchor_ranges([target..target]);
5182 });
5183 }
5184 InlineCompletion::Edit { edits, .. } => {
5185 // Find an insertion that starts at the cursor position.
5186 let snapshot = self.buffer.read(cx).snapshot(cx);
5187 let cursor_offset = self.selections.newest::<usize>(cx).head();
5188 let insertion = edits.iter().find_map(|(range, text)| {
5189 let range = range.to_offset(&snapshot);
5190 if range.is_empty() && range.start == cursor_offset {
5191 Some(text)
5192 } else {
5193 None
5194 }
5195 });
5196
5197 if let Some(text) = insertion {
5198 let mut partial_completion = text
5199 .chars()
5200 .by_ref()
5201 .take_while(|c| c.is_alphabetic())
5202 .collect::<String>();
5203 if partial_completion.is_empty() {
5204 partial_completion = text
5205 .chars()
5206 .by_ref()
5207 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5208 .collect::<String>();
5209 }
5210
5211 cx.emit(EditorEvent::InputHandled {
5212 utf16_range_to_replace: None,
5213 text: partial_completion.clone().into(),
5214 });
5215
5216 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5217
5218 self.refresh_inline_completion(true, true, window, cx);
5219 cx.notify();
5220 } else {
5221 self.accept_edit_prediction(&Default::default(), window, cx);
5222 }
5223 }
5224 }
5225 }
5226
5227 fn discard_inline_completion(
5228 &mut self,
5229 should_report_inline_completion_event: bool,
5230 cx: &mut Context<Self>,
5231 ) -> bool {
5232 if should_report_inline_completion_event {
5233 let completion_id = self
5234 .active_inline_completion
5235 .as_ref()
5236 .and_then(|active_completion| active_completion.completion_id.clone());
5237
5238 self.report_inline_completion_event(completion_id, false, cx);
5239 }
5240
5241 if let Some(provider) = self.edit_prediction_provider() {
5242 provider.discard(cx);
5243 }
5244
5245 self.take_active_inline_completion(cx)
5246 }
5247
5248 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5249 let Some(provider) = self.edit_prediction_provider() else {
5250 return;
5251 };
5252
5253 let Some((_, buffer, _)) = self
5254 .buffer
5255 .read(cx)
5256 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5257 else {
5258 return;
5259 };
5260
5261 let extension = buffer
5262 .read(cx)
5263 .file()
5264 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5265
5266 let event_type = match accepted {
5267 true => "Edit Prediction Accepted",
5268 false => "Edit Prediction Discarded",
5269 };
5270 telemetry::event!(
5271 event_type,
5272 provider = provider.name(),
5273 prediction_id = id,
5274 suggestion_accepted = accepted,
5275 file_extension = extension,
5276 );
5277 }
5278
5279 pub fn has_active_inline_completion(&self) -> bool {
5280 self.active_inline_completion.is_some()
5281 }
5282
5283 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5284 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5285 return false;
5286 };
5287
5288 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5289 self.clear_highlights::<InlineCompletionHighlight>(cx);
5290 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5291 true
5292 }
5293
5294 /// Returns true when we're displaying the edit prediction popover below the cursor
5295 /// like we are not previewing and the LSP autocomplete menu is visible
5296 /// or we are in `when_holding_modifier` mode.
5297 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5298 if self.edit_prediction_preview_is_active()
5299 || !self.show_edit_predictions_in_menu()
5300 || !self.edit_predictions_enabled()
5301 {
5302 return false;
5303 }
5304
5305 if self.has_visible_completions_menu() {
5306 return true;
5307 }
5308
5309 has_completion && self.edit_prediction_requires_modifier()
5310 }
5311
5312 fn handle_modifiers_changed(
5313 &mut self,
5314 modifiers: Modifiers,
5315 position_map: &PositionMap,
5316 window: &mut Window,
5317 cx: &mut Context<Self>,
5318 ) {
5319 if self.show_edit_predictions_in_menu() {
5320 self.update_edit_prediction_preview(&modifiers, window, cx);
5321 }
5322
5323 self.update_selection_mode(&modifiers, position_map, window, cx);
5324
5325 let mouse_position = window.mouse_position();
5326 if !position_map.text_hitbox.is_hovered(window) {
5327 return;
5328 }
5329
5330 self.update_hovered_link(
5331 position_map.point_for_position(mouse_position),
5332 &position_map.snapshot,
5333 modifiers,
5334 window,
5335 cx,
5336 )
5337 }
5338
5339 fn update_selection_mode(
5340 &mut self,
5341 modifiers: &Modifiers,
5342 position_map: &PositionMap,
5343 window: &mut Window,
5344 cx: &mut Context<Self>,
5345 ) {
5346 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5347 return;
5348 }
5349
5350 let mouse_position = window.mouse_position();
5351 let point_for_position = position_map.point_for_position(mouse_position);
5352 let position = point_for_position.previous_valid;
5353
5354 self.select(
5355 SelectPhase::BeginColumnar {
5356 position,
5357 reset: false,
5358 goal_column: point_for_position.exact_unclipped.column(),
5359 },
5360 window,
5361 cx,
5362 );
5363 }
5364
5365 fn update_edit_prediction_preview(
5366 &mut self,
5367 modifiers: &Modifiers,
5368 window: &mut Window,
5369 cx: &mut Context<Self>,
5370 ) {
5371 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5372 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5373 return;
5374 };
5375
5376 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5377 if matches!(
5378 self.edit_prediction_preview,
5379 EditPredictionPreview::Inactive
5380 ) {
5381 self.edit_prediction_preview = EditPredictionPreview::Active {
5382 previous_scroll_position: None,
5383 };
5384
5385 self.update_visible_inline_completion(window, cx);
5386 cx.notify();
5387 }
5388 } else if let EditPredictionPreview::Active {
5389 previous_scroll_position,
5390 } = self.edit_prediction_preview
5391 {
5392 if let (Some(previous_scroll_position), Some(position_map)) =
5393 (previous_scroll_position, self.last_position_map.as_ref())
5394 {
5395 self.set_scroll_position(
5396 previous_scroll_position
5397 .scroll_position(&position_map.snapshot.display_snapshot),
5398 window,
5399 cx,
5400 );
5401 }
5402
5403 self.edit_prediction_preview = EditPredictionPreview::Inactive;
5404 self.clear_row_highlights::<EditPredictionPreview>();
5405 self.update_visible_inline_completion(window, cx);
5406 cx.notify();
5407 }
5408 }
5409
5410 fn update_visible_inline_completion(
5411 &mut self,
5412 _window: &mut Window,
5413 cx: &mut Context<Self>,
5414 ) -> Option<()> {
5415 let selection = self.selections.newest_anchor();
5416 let cursor = selection.head();
5417 let multibuffer = self.buffer.read(cx).snapshot(cx);
5418 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5419 let excerpt_id = cursor.excerpt_id;
5420
5421 let show_in_menu = self.show_edit_predictions_in_menu();
5422 let completions_menu_has_precedence = !show_in_menu
5423 && (self.context_menu.borrow().is_some()
5424 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5425
5426 if completions_menu_has_precedence
5427 || !offset_selection.is_empty()
5428 || self
5429 .active_inline_completion
5430 .as_ref()
5431 .map_or(false, |completion| {
5432 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5433 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5434 !invalidation_range.contains(&offset_selection.head())
5435 })
5436 {
5437 self.discard_inline_completion(false, cx);
5438 return None;
5439 }
5440
5441 self.take_active_inline_completion(cx);
5442 let Some(provider) = self.edit_prediction_provider() else {
5443 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5444 return None;
5445 };
5446
5447 let (buffer, cursor_buffer_position) =
5448 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5449
5450 self.edit_prediction_settings =
5451 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5452
5453 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5454
5455 if self.edit_prediction_indent_conflict {
5456 let cursor_point = cursor.to_point(&multibuffer);
5457
5458 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5459
5460 if let Some((_, indent)) = indents.iter().next() {
5461 if indent.len == cursor_point.column {
5462 self.edit_prediction_indent_conflict = false;
5463 }
5464 }
5465 }
5466
5467 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5468 let edits = inline_completion
5469 .edits
5470 .into_iter()
5471 .flat_map(|(range, new_text)| {
5472 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5473 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5474 Some((start..end, new_text))
5475 })
5476 .collect::<Vec<_>>();
5477 if edits.is_empty() {
5478 return None;
5479 }
5480
5481 let first_edit_start = edits.first().unwrap().0.start;
5482 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5483 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5484
5485 let last_edit_end = edits.last().unwrap().0.end;
5486 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5487 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5488
5489 let cursor_row = cursor.to_point(&multibuffer).row;
5490
5491 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5492
5493 let mut inlay_ids = Vec::new();
5494 let invalidation_row_range;
5495 let move_invalidation_row_range = if cursor_row < edit_start_row {
5496 Some(cursor_row..edit_end_row)
5497 } else if cursor_row > edit_end_row {
5498 Some(edit_start_row..cursor_row)
5499 } else {
5500 None
5501 };
5502 let is_move =
5503 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5504 let completion = if is_move {
5505 invalidation_row_range =
5506 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5507 let target = first_edit_start;
5508 InlineCompletion::Move { target, snapshot }
5509 } else {
5510 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5511 && !self.inline_completions_hidden_for_vim_mode;
5512
5513 if show_completions_in_buffer {
5514 if edits
5515 .iter()
5516 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5517 {
5518 let mut inlays = Vec::new();
5519 for (range, new_text) in &edits {
5520 let inlay = Inlay::inline_completion(
5521 post_inc(&mut self.next_inlay_id),
5522 range.start,
5523 new_text.as_str(),
5524 );
5525 inlay_ids.push(inlay.id);
5526 inlays.push(inlay);
5527 }
5528
5529 self.splice_inlays(&[], inlays, cx);
5530 } else {
5531 let background_color = cx.theme().status().deleted_background;
5532 self.highlight_text::<InlineCompletionHighlight>(
5533 edits.iter().map(|(range, _)| range.clone()).collect(),
5534 HighlightStyle {
5535 background_color: Some(background_color),
5536 ..Default::default()
5537 },
5538 cx,
5539 );
5540 }
5541 }
5542
5543 invalidation_row_range = edit_start_row..edit_end_row;
5544
5545 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5546 if provider.show_tab_accept_marker() {
5547 EditDisplayMode::TabAccept
5548 } else {
5549 EditDisplayMode::Inline
5550 }
5551 } else {
5552 EditDisplayMode::DiffPopover
5553 };
5554
5555 InlineCompletion::Edit {
5556 edits,
5557 edit_preview: inline_completion.edit_preview,
5558 display_mode,
5559 snapshot,
5560 }
5561 };
5562
5563 let invalidation_range = multibuffer
5564 .anchor_before(Point::new(invalidation_row_range.start, 0))
5565 ..multibuffer.anchor_after(Point::new(
5566 invalidation_row_range.end,
5567 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5568 ));
5569
5570 self.stale_inline_completion_in_menu = None;
5571 self.active_inline_completion = Some(InlineCompletionState {
5572 inlay_ids,
5573 completion,
5574 completion_id: inline_completion.id,
5575 invalidation_range,
5576 });
5577
5578 cx.notify();
5579
5580 Some(())
5581 }
5582
5583 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5584 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5585 }
5586
5587 fn render_code_actions_indicator(
5588 &self,
5589 _style: &EditorStyle,
5590 row: DisplayRow,
5591 is_active: bool,
5592 cx: &mut Context<Self>,
5593 ) -> Option<IconButton> {
5594 if self.available_code_actions.is_some() {
5595 Some(
5596 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5597 .shape(ui::IconButtonShape::Square)
5598 .icon_size(IconSize::XSmall)
5599 .icon_color(Color::Muted)
5600 .toggle_state(is_active)
5601 .tooltip({
5602 let focus_handle = self.focus_handle.clone();
5603 move |window, cx| {
5604 Tooltip::for_action_in(
5605 "Toggle Code Actions",
5606 &ToggleCodeActions {
5607 deployed_from_indicator: None,
5608 },
5609 &focus_handle,
5610 window,
5611 cx,
5612 )
5613 }
5614 })
5615 .on_click(cx.listener(move |editor, _e, window, cx| {
5616 window.focus(&editor.focus_handle(cx));
5617 editor.toggle_code_actions(
5618 &ToggleCodeActions {
5619 deployed_from_indicator: Some(row),
5620 },
5621 window,
5622 cx,
5623 );
5624 })),
5625 )
5626 } else {
5627 None
5628 }
5629 }
5630
5631 fn clear_tasks(&mut self) {
5632 self.tasks.clear()
5633 }
5634
5635 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5636 if self.tasks.insert(key, value).is_some() {
5637 // This case should hopefully be rare, but just in case...
5638 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5639 }
5640 }
5641
5642 fn build_tasks_context(
5643 project: &Entity<Project>,
5644 buffer: &Entity<Buffer>,
5645 buffer_row: u32,
5646 tasks: &Arc<RunnableTasks>,
5647 cx: &mut Context<Self>,
5648 ) -> Task<Option<task::TaskContext>> {
5649 let position = Point::new(buffer_row, tasks.column);
5650 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5651 let location = Location {
5652 buffer: buffer.clone(),
5653 range: range_start..range_start,
5654 };
5655 // Fill in the environmental variables from the tree-sitter captures
5656 let mut captured_task_variables = TaskVariables::default();
5657 for (capture_name, value) in tasks.extra_variables.clone() {
5658 captured_task_variables.insert(
5659 task::VariableName::Custom(capture_name.into()),
5660 value.clone(),
5661 );
5662 }
5663 project.update(cx, |project, cx| {
5664 project.task_store().update(cx, |task_store, cx| {
5665 task_store.task_context_for_location(captured_task_variables, location, cx)
5666 })
5667 })
5668 }
5669
5670 pub fn spawn_nearest_task(
5671 &mut self,
5672 action: &SpawnNearestTask,
5673 window: &mut Window,
5674 cx: &mut Context<Self>,
5675 ) {
5676 let Some((workspace, _)) = self.workspace.clone() else {
5677 return;
5678 };
5679 let Some(project) = self.project.clone() else {
5680 return;
5681 };
5682
5683 // Try to find a closest, enclosing node using tree-sitter that has a
5684 // task
5685 let Some((buffer, buffer_row, tasks)) = self
5686 .find_enclosing_node_task(cx)
5687 // Or find the task that's closest in row-distance.
5688 .or_else(|| self.find_closest_task(cx))
5689 else {
5690 return;
5691 };
5692
5693 let reveal_strategy = action.reveal;
5694 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5695 cx.spawn_in(window, |_, mut cx| async move {
5696 let context = task_context.await?;
5697 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5698
5699 let resolved = resolved_task.resolved.as_mut()?;
5700 resolved.reveal = reveal_strategy;
5701
5702 workspace
5703 .update(&mut cx, |workspace, cx| {
5704 workspace::tasks::schedule_resolved_task(
5705 workspace,
5706 task_source_kind,
5707 resolved_task,
5708 false,
5709 cx,
5710 );
5711 })
5712 .ok()
5713 })
5714 .detach();
5715 }
5716
5717 fn find_closest_task(
5718 &mut self,
5719 cx: &mut Context<Self>,
5720 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5721 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5722
5723 let ((buffer_id, row), tasks) = self
5724 .tasks
5725 .iter()
5726 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5727
5728 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5729 let tasks = Arc::new(tasks.to_owned());
5730 Some((buffer, *row, tasks))
5731 }
5732
5733 fn find_enclosing_node_task(
5734 &mut self,
5735 cx: &mut Context<Self>,
5736 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5737 let snapshot = self.buffer.read(cx).snapshot(cx);
5738 let offset = self.selections.newest::<usize>(cx).head();
5739 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5740 let buffer_id = excerpt.buffer().remote_id();
5741
5742 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5743 let mut cursor = layer.node().walk();
5744
5745 while cursor.goto_first_child_for_byte(offset).is_some() {
5746 if cursor.node().end_byte() == offset {
5747 cursor.goto_next_sibling();
5748 }
5749 }
5750
5751 // Ascend to the smallest ancestor that contains the range and has a task.
5752 loop {
5753 let node = cursor.node();
5754 let node_range = node.byte_range();
5755 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5756
5757 // Check if this node contains our offset
5758 if node_range.start <= offset && node_range.end >= offset {
5759 // If it contains offset, check for task
5760 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5761 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5762 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5763 }
5764 }
5765
5766 if !cursor.goto_parent() {
5767 break;
5768 }
5769 }
5770 None
5771 }
5772
5773 fn render_run_indicator(
5774 &self,
5775 _style: &EditorStyle,
5776 is_active: bool,
5777 row: DisplayRow,
5778 cx: &mut Context<Self>,
5779 ) -> IconButton {
5780 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5781 .shape(ui::IconButtonShape::Square)
5782 .icon_size(IconSize::XSmall)
5783 .icon_color(Color::Muted)
5784 .toggle_state(is_active)
5785 .on_click(cx.listener(move |editor, _e, window, cx| {
5786 window.focus(&editor.focus_handle(cx));
5787 editor.toggle_code_actions(
5788 &ToggleCodeActions {
5789 deployed_from_indicator: Some(row),
5790 },
5791 window,
5792 cx,
5793 );
5794 }))
5795 }
5796
5797 pub fn context_menu_visible(&self) -> bool {
5798 !self.edit_prediction_preview_is_active()
5799 && self
5800 .context_menu
5801 .borrow()
5802 .as_ref()
5803 .map_or(false, |menu| menu.visible())
5804 }
5805
5806 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5807 self.context_menu
5808 .borrow()
5809 .as_ref()
5810 .map(|menu| menu.origin())
5811 }
5812
5813 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5814 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5815
5816 #[allow(clippy::too_many_arguments)]
5817 fn render_edit_prediction_popover(
5818 &mut self,
5819 text_bounds: &Bounds<Pixels>,
5820 content_origin: gpui::Point<Pixels>,
5821 editor_snapshot: &EditorSnapshot,
5822 visible_row_range: Range<DisplayRow>,
5823 scroll_top: f32,
5824 scroll_bottom: f32,
5825 line_layouts: &[LineWithInvisibles],
5826 line_height: Pixels,
5827 scroll_pixel_position: gpui::Point<Pixels>,
5828 newest_selection_head: Option<DisplayPoint>,
5829 editor_width: Pixels,
5830 style: &EditorStyle,
5831 window: &mut Window,
5832 cx: &mut App,
5833 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5834 let active_inline_completion = self.active_inline_completion.as_ref()?;
5835
5836 if self.edit_prediction_visible_in_cursor_popover(true) {
5837 return None;
5838 }
5839
5840 match &active_inline_completion.completion {
5841 InlineCompletion::Move { target, .. } => {
5842 let target_display_point = target.to_display_point(editor_snapshot);
5843
5844 if self.edit_prediction_requires_modifier() {
5845 if !self.edit_prediction_preview_is_active() {
5846 return None;
5847 }
5848
5849 self.render_edit_prediction_modifier_jump_popover(
5850 text_bounds,
5851 content_origin,
5852 visible_row_range,
5853 line_layouts,
5854 line_height,
5855 scroll_pixel_position,
5856 newest_selection_head,
5857 target_display_point,
5858 window,
5859 cx,
5860 )
5861 } else {
5862 self.render_edit_prediction_eager_jump_popover(
5863 text_bounds,
5864 content_origin,
5865 editor_snapshot,
5866 visible_row_range,
5867 scroll_top,
5868 scroll_bottom,
5869 line_height,
5870 scroll_pixel_position,
5871 target_display_point,
5872 editor_width,
5873 window,
5874 cx,
5875 )
5876 }
5877 }
5878 InlineCompletion::Edit {
5879 display_mode: EditDisplayMode::Inline,
5880 ..
5881 } => None,
5882 InlineCompletion::Edit {
5883 display_mode: EditDisplayMode::TabAccept,
5884 edits,
5885 ..
5886 } => {
5887 let range = &edits.first()?.0;
5888 let target_display_point = range.end.to_display_point(editor_snapshot);
5889
5890 self.render_edit_prediction_end_of_line_popover(
5891 "Accept",
5892 editor_snapshot,
5893 visible_row_range,
5894 target_display_point,
5895 line_height,
5896 scroll_pixel_position,
5897 content_origin,
5898 editor_width,
5899 window,
5900 cx,
5901 )
5902 }
5903 InlineCompletion::Edit {
5904 edits,
5905 edit_preview,
5906 display_mode: EditDisplayMode::DiffPopover,
5907 snapshot,
5908 } => self.render_edit_prediction_diff_popover(
5909 text_bounds,
5910 content_origin,
5911 editor_snapshot,
5912 visible_row_range,
5913 line_layouts,
5914 line_height,
5915 scroll_pixel_position,
5916 newest_selection_head,
5917 editor_width,
5918 style,
5919 edits,
5920 edit_preview,
5921 snapshot,
5922 window,
5923 cx,
5924 ),
5925 }
5926 }
5927
5928 #[allow(clippy::too_many_arguments)]
5929 fn render_edit_prediction_modifier_jump_popover(
5930 &mut self,
5931 text_bounds: &Bounds<Pixels>,
5932 content_origin: gpui::Point<Pixels>,
5933 visible_row_range: Range<DisplayRow>,
5934 line_layouts: &[LineWithInvisibles],
5935 line_height: Pixels,
5936 scroll_pixel_position: gpui::Point<Pixels>,
5937 newest_selection_head: Option<DisplayPoint>,
5938 target_display_point: DisplayPoint,
5939 window: &mut Window,
5940 cx: &mut App,
5941 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5942 let scrolled_content_origin =
5943 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
5944
5945 const SCROLL_PADDING_Y: Pixels = px(12.);
5946
5947 if target_display_point.row() < visible_row_range.start {
5948 return self.render_edit_prediction_scroll_popover(
5949 |_| SCROLL_PADDING_Y,
5950 IconName::ArrowUp,
5951 visible_row_range,
5952 line_layouts,
5953 newest_selection_head,
5954 scrolled_content_origin,
5955 window,
5956 cx,
5957 );
5958 } else if target_display_point.row() >= visible_row_range.end {
5959 return self.render_edit_prediction_scroll_popover(
5960 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
5961 IconName::ArrowDown,
5962 visible_row_range,
5963 line_layouts,
5964 newest_selection_head,
5965 scrolled_content_origin,
5966 window,
5967 cx,
5968 );
5969 }
5970
5971 const POLE_WIDTH: Pixels = px(2.);
5972
5973 let mut element = v_flex()
5974 .items_end()
5975 .child(
5976 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
5977 .rounded_br(px(0.))
5978 .rounded_tr(px(0.))
5979 .border_r_2(),
5980 )
5981 .child(
5982 div()
5983 .w(POLE_WIDTH)
5984 .bg(Editor::edit_prediction_callout_popover_border_color(cx))
5985 .h(line_height),
5986 )
5987 .into_any();
5988
5989 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
5990
5991 let line_layout =
5992 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
5993 let target_column = target_display_point.column() as usize;
5994
5995 let target_x = line_layout.x_for_index(target_column);
5996 let target_y =
5997 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
5998
5999 let mut origin = scrolled_content_origin + point(target_x, target_y)
6000 - point(size.width - POLE_WIDTH, size.height - line_height);
6001
6002 origin.x = origin.x.max(content_origin.x);
6003
6004 element.prepaint_at(origin, window, cx);
6005
6006 Some((element, origin))
6007 }
6008
6009 #[allow(clippy::too_many_arguments)]
6010 fn render_edit_prediction_scroll_popover(
6011 &mut self,
6012 to_y: impl Fn(Size<Pixels>) -> Pixels,
6013 scroll_icon: IconName,
6014 visible_row_range: Range<DisplayRow>,
6015 line_layouts: &[LineWithInvisibles],
6016 newest_selection_head: Option<DisplayPoint>,
6017 scrolled_content_origin: gpui::Point<Pixels>,
6018 window: &mut Window,
6019 cx: &mut App,
6020 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6021 let mut element = self
6022 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6023 .into_any();
6024
6025 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6026
6027 let cursor = newest_selection_head?;
6028 let cursor_row_layout =
6029 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6030 let cursor_column = cursor.column() as usize;
6031
6032 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6033
6034 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6035
6036 element.prepaint_at(origin, window, cx);
6037 Some((element, origin))
6038 }
6039
6040 #[allow(clippy::too_many_arguments)]
6041 fn render_edit_prediction_eager_jump_popover(
6042 &mut self,
6043 text_bounds: &Bounds<Pixels>,
6044 content_origin: gpui::Point<Pixels>,
6045 editor_snapshot: &EditorSnapshot,
6046 visible_row_range: Range<DisplayRow>,
6047 scroll_top: f32,
6048 scroll_bottom: f32,
6049 line_height: Pixels,
6050 scroll_pixel_position: gpui::Point<Pixels>,
6051 target_display_point: DisplayPoint,
6052 editor_width: Pixels,
6053 window: &mut Window,
6054 cx: &mut App,
6055 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6056 if target_display_point.row().as_f32() < scroll_top {
6057 let mut element = self
6058 .render_edit_prediction_line_popover(
6059 "Jump to Edit",
6060 Some(IconName::ArrowUp),
6061 window,
6062 cx,
6063 )?
6064 .into_any();
6065
6066 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6067 let offset = point(
6068 (text_bounds.size.width - size.width) / 2.,
6069 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6070 );
6071
6072 let origin = text_bounds.origin + offset;
6073 element.prepaint_at(origin, window, cx);
6074 Some((element, origin))
6075 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6076 let mut element = self
6077 .render_edit_prediction_line_popover(
6078 "Jump to Edit",
6079 Some(IconName::ArrowDown),
6080 window,
6081 cx,
6082 )?
6083 .into_any();
6084
6085 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6086 let offset = point(
6087 (text_bounds.size.width - size.width) / 2.,
6088 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6089 );
6090
6091 let origin = text_bounds.origin + offset;
6092 element.prepaint_at(origin, window, cx);
6093 Some((element, origin))
6094 } else {
6095 self.render_edit_prediction_end_of_line_popover(
6096 "Jump to Edit",
6097 editor_snapshot,
6098 visible_row_range,
6099 target_display_point,
6100 line_height,
6101 scroll_pixel_position,
6102 content_origin,
6103 editor_width,
6104 window,
6105 cx,
6106 )
6107 }
6108 }
6109
6110 #[allow(clippy::too_many_arguments)]
6111 fn render_edit_prediction_end_of_line_popover(
6112 self: &mut Editor,
6113 label: &'static str,
6114 editor_snapshot: &EditorSnapshot,
6115 visible_row_range: Range<DisplayRow>,
6116 target_display_point: DisplayPoint,
6117 line_height: Pixels,
6118 scroll_pixel_position: gpui::Point<Pixels>,
6119 content_origin: gpui::Point<Pixels>,
6120 editor_width: Pixels,
6121 window: &mut Window,
6122 cx: &mut App,
6123 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6124 let target_line_end = DisplayPoint::new(
6125 target_display_point.row(),
6126 editor_snapshot.line_len(target_display_point.row()),
6127 );
6128
6129 let mut element = self
6130 .render_edit_prediction_line_popover(label, None, window, cx)?
6131 .into_any();
6132
6133 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6134
6135 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6136
6137 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6138 let mut origin = start_point
6139 + line_origin
6140 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6141 origin.x = origin.x.max(content_origin.x);
6142
6143 let max_x = content_origin.x + editor_width - size.width;
6144
6145 if origin.x > max_x {
6146 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6147
6148 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6149 origin.y += offset;
6150 IconName::ArrowUp
6151 } else {
6152 origin.y -= offset;
6153 IconName::ArrowDown
6154 };
6155
6156 element = self
6157 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6158 .into_any();
6159
6160 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6161
6162 origin.x = content_origin.x + editor_width - size.width - px(2.);
6163 }
6164
6165 element.prepaint_at(origin, window, cx);
6166 Some((element, origin))
6167 }
6168
6169 #[allow(clippy::too_many_arguments)]
6170 fn render_edit_prediction_diff_popover(
6171 self: &Editor,
6172 text_bounds: &Bounds<Pixels>,
6173 content_origin: gpui::Point<Pixels>,
6174 editor_snapshot: &EditorSnapshot,
6175 visible_row_range: Range<DisplayRow>,
6176 line_layouts: &[LineWithInvisibles],
6177 line_height: Pixels,
6178 scroll_pixel_position: gpui::Point<Pixels>,
6179 newest_selection_head: Option<DisplayPoint>,
6180 editor_width: Pixels,
6181 style: &EditorStyle,
6182 edits: &Vec<(Range<Anchor>, String)>,
6183 edit_preview: &Option<language::EditPreview>,
6184 snapshot: &language::BufferSnapshot,
6185 window: &mut Window,
6186 cx: &mut App,
6187 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6188 let edit_start = edits
6189 .first()
6190 .unwrap()
6191 .0
6192 .start
6193 .to_display_point(editor_snapshot);
6194 let edit_end = edits
6195 .last()
6196 .unwrap()
6197 .0
6198 .end
6199 .to_display_point(editor_snapshot);
6200
6201 let is_visible = visible_row_range.contains(&edit_start.row())
6202 || visible_row_range.contains(&edit_end.row());
6203 if !is_visible {
6204 return None;
6205 }
6206
6207 let highlighted_edits =
6208 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6209
6210 let styled_text = highlighted_edits.to_styled_text(&style.text);
6211 let line_count = highlighted_edits.text.lines().count();
6212
6213 const BORDER_WIDTH: Pixels = px(1.);
6214
6215 let mut element = h_flex()
6216 .items_start()
6217 .child(
6218 h_flex()
6219 .bg(cx.theme().colors().editor_background)
6220 .border(BORDER_WIDTH)
6221 .shadow_sm()
6222 .border_color(cx.theme().colors().border)
6223 .rounded_l_lg()
6224 .when(line_count > 1, |el| el.rounded_br_lg())
6225 .pr_1()
6226 .child(styled_text),
6227 )
6228 .child(
6229 h_flex()
6230 .h(line_height + BORDER_WIDTH * px(2.))
6231 .px_1p5()
6232 .gap_1()
6233 // Workaround: For some reason, there's a gap if we don't do this
6234 .ml(-BORDER_WIDTH)
6235 .shadow(smallvec![gpui::BoxShadow {
6236 color: gpui::black().opacity(0.05),
6237 offset: point(px(1.), px(1.)),
6238 blur_radius: px(2.),
6239 spread_radius: px(0.),
6240 }])
6241 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6242 .border(BORDER_WIDTH)
6243 .border_color(cx.theme().colors().border)
6244 .rounded_r_lg()
6245 .children(self.render_edit_prediction_accept_keybind(window, cx)),
6246 )
6247 .into_any();
6248
6249 let longest_row =
6250 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6251 let longest_line_width = if visible_row_range.contains(&longest_row) {
6252 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6253 } else {
6254 layout_line(
6255 longest_row,
6256 editor_snapshot,
6257 style,
6258 editor_width,
6259 |_| false,
6260 window,
6261 cx,
6262 )
6263 .width
6264 };
6265
6266 let viewport_bounds =
6267 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6268 right: -EditorElement::SCROLLBAR_WIDTH,
6269 ..Default::default()
6270 });
6271
6272 let x_after_longest =
6273 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6274 - scroll_pixel_position.x;
6275
6276 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6277
6278 // Fully visible if it can be displayed within the window (allow overlapping other
6279 // panes). However, this is only allowed if the popover starts within text_bounds.
6280 let can_position_to_the_right = x_after_longest < text_bounds.right()
6281 && x_after_longest + element_bounds.width < viewport_bounds.right();
6282
6283 let mut origin = if can_position_to_the_right {
6284 point(
6285 x_after_longest,
6286 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6287 - scroll_pixel_position.y,
6288 )
6289 } else {
6290 let cursor_row = newest_selection_head.map(|head| head.row());
6291 let above_edit = edit_start
6292 .row()
6293 .0
6294 .checked_sub(line_count as u32)
6295 .map(DisplayRow);
6296 let below_edit = Some(edit_end.row() + 1);
6297 let above_cursor =
6298 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6299 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6300
6301 // Place the edit popover adjacent to the edit if there is a location
6302 // available that is onscreen and does not obscure the cursor. Otherwise,
6303 // place it adjacent to the cursor.
6304 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6305 .into_iter()
6306 .flatten()
6307 .find(|&start_row| {
6308 let end_row = start_row + line_count as u32;
6309 visible_row_range.contains(&start_row)
6310 && visible_row_range.contains(&end_row)
6311 && cursor_row.map_or(true, |cursor_row| {
6312 !((start_row..end_row).contains(&cursor_row))
6313 })
6314 })?;
6315
6316 content_origin
6317 + point(
6318 -scroll_pixel_position.x,
6319 row_target.as_f32() * line_height - scroll_pixel_position.y,
6320 )
6321 };
6322
6323 origin.x -= BORDER_WIDTH;
6324
6325 window.defer_draw(element, origin, 1);
6326
6327 // Do not return an element, since it will already be drawn due to defer_draw.
6328 None
6329 }
6330
6331 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6332 px(30.)
6333 }
6334
6335 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6336 if self.read_only(cx) {
6337 cx.theme().players().read_only()
6338 } else {
6339 self.style.as_ref().unwrap().local_player
6340 }
6341 }
6342
6343 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
6344 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6345 let accept_keystroke = accept_binding.keystroke()?;
6346
6347 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6348
6349 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6350 Color::Accent
6351 } else {
6352 Color::Muted
6353 };
6354
6355 h_flex()
6356 .px_0p5()
6357 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6358 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6359 .text_size(TextSize::XSmall.rems(cx))
6360 .child(h_flex().children(ui::render_modifiers(
6361 &accept_keystroke.modifiers,
6362 PlatformStyle::platform(),
6363 Some(modifiers_color),
6364 Some(IconSize::XSmall.rems().into()),
6365 true,
6366 )))
6367 .when(is_platform_style_mac, |parent| {
6368 parent.child(accept_keystroke.key.clone())
6369 })
6370 .when(!is_platform_style_mac, |parent| {
6371 parent.child(
6372 Key::new(
6373 util::capitalize(&accept_keystroke.key),
6374 Some(Color::Default),
6375 )
6376 .size(Some(IconSize::XSmall.rems().into())),
6377 )
6378 })
6379 .into()
6380 }
6381
6382 fn render_edit_prediction_line_popover(
6383 &self,
6384 label: impl Into<SharedString>,
6385 icon: Option<IconName>,
6386 window: &mut Window,
6387 cx: &App,
6388 ) -> Option<Div> {
6389 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6390
6391 let result = h_flex()
6392 .py_0p5()
6393 .pl_1()
6394 .pr(padding_right)
6395 .gap_1()
6396 .rounded(px(6.))
6397 .border_1()
6398 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6399 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6400 .shadow_sm()
6401 .children(self.render_edit_prediction_accept_keybind(window, cx))
6402 .child(Label::new(label).size(LabelSize::Small))
6403 .when_some(icon, |element, icon| {
6404 element.child(
6405 div()
6406 .mt(px(1.5))
6407 .child(Icon::new(icon).size(IconSize::Small)),
6408 )
6409 });
6410
6411 Some(result)
6412 }
6413
6414 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6415 let accent_color = cx.theme().colors().text_accent;
6416 let editor_bg_color = cx.theme().colors().editor_background;
6417 editor_bg_color.blend(accent_color.opacity(0.1))
6418 }
6419
6420 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6421 let accent_color = cx.theme().colors().text_accent;
6422 let editor_bg_color = cx.theme().colors().editor_background;
6423 editor_bg_color.blend(accent_color.opacity(0.6))
6424 }
6425
6426 #[allow(clippy::too_many_arguments)]
6427 fn render_edit_prediction_cursor_popover(
6428 &self,
6429 min_width: Pixels,
6430 max_width: Pixels,
6431 cursor_point: Point,
6432 style: &EditorStyle,
6433 accept_keystroke: Option<&gpui::Keystroke>,
6434 _window: &Window,
6435 cx: &mut Context<Editor>,
6436 ) -> Option<AnyElement> {
6437 let provider = self.edit_prediction_provider.as_ref()?;
6438
6439 if provider.provider.needs_terms_acceptance(cx) {
6440 return Some(
6441 h_flex()
6442 .min_w(min_width)
6443 .flex_1()
6444 .px_2()
6445 .py_1()
6446 .gap_3()
6447 .elevation_2(cx)
6448 .hover(|style| style.bg(cx.theme().colors().element_hover))
6449 .id("accept-terms")
6450 .cursor_pointer()
6451 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6452 .on_click(cx.listener(|this, _event, window, cx| {
6453 cx.stop_propagation();
6454 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6455 window.dispatch_action(
6456 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6457 cx,
6458 );
6459 }))
6460 .child(
6461 h_flex()
6462 .flex_1()
6463 .gap_2()
6464 .child(Icon::new(IconName::ZedPredict))
6465 .child(Label::new("Accept Terms of Service"))
6466 .child(div().w_full())
6467 .child(
6468 Icon::new(IconName::ArrowUpRight)
6469 .color(Color::Muted)
6470 .size(IconSize::Small),
6471 )
6472 .into_any_element(),
6473 )
6474 .into_any(),
6475 );
6476 }
6477
6478 let is_refreshing = provider.provider.is_refreshing(cx);
6479
6480 fn pending_completion_container() -> Div {
6481 h_flex()
6482 .h_full()
6483 .flex_1()
6484 .gap_2()
6485 .child(Icon::new(IconName::ZedPredict))
6486 }
6487
6488 let completion = match &self.active_inline_completion {
6489 Some(completion) => match &completion.completion {
6490 InlineCompletion::Move {
6491 target, snapshot, ..
6492 } if !self.has_visible_completions_menu() => {
6493 use text::ToPoint as _;
6494
6495 return Some(
6496 h_flex()
6497 .px_2()
6498 .py_1()
6499 .gap_2()
6500 .elevation_2(cx)
6501 .border_color(cx.theme().colors().border)
6502 .rounded(px(6.))
6503 .rounded_tl(px(0.))
6504 .child(
6505 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6506 Icon::new(IconName::ZedPredictDown)
6507 } else {
6508 Icon::new(IconName::ZedPredictUp)
6509 },
6510 )
6511 .child(Label::new("Hold").size(LabelSize::Small))
6512 .child(h_flex().children(ui::render_modifiers(
6513 &accept_keystroke?.modifiers,
6514 PlatformStyle::platform(),
6515 Some(Color::Default),
6516 Some(IconSize::Small.rems().into()),
6517 false,
6518 )))
6519 .into_any(),
6520 );
6521 }
6522 _ => self.render_edit_prediction_cursor_popover_preview(
6523 completion,
6524 cursor_point,
6525 style,
6526 cx,
6527 )?,
6528 },
6529
6530 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6531 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6532 stale_completion,
6533 cursor_point,
6534 style,
6535 cx,
6536 )?,
6537
6538 None => {
6539 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6540 }
6541 },
6542
6543 None => pending_completion_container().child(Label::new("No Prediction")),
6544 };
6545
6546 let completion = if is_refreshing {
6547 completion
6548 .with_animation(
6549 "loading-completion",
6550 Animation::new(Duration::from_secs(2))
6551 .repeat()
6552 .with_easing(pulsating_between(0.4, 0.8)),
6553 |label, delta| label.opacity(delta),
6554 )
6555 .into_any_element()
6556 } else {
6557 completion.into_any_element()
6558 };
6559
6560 let has_completion = self.active_inline_completion.is_some();
6561
6562 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6563 Some(
6564 h_flex()
6565 .min_w(min_width)
6566 .max_w(max_width)
6567 .flex_1()
6568 .elevation_2(cx)
6569 .border_color(cx.theme().colors().border)
6570 .child(
6571 div()
6572 .flex_1()
6573 .py_1()
6574 .px_2()
6575 .overflow_hidden()
6576 .child(completion),
6577 )
6578 .when_some(accept_keystroke, |el, accept_keystroke| {
6579 if !accept_keystroke.modifiers.modified() {
6580 return el;
6581 }
6582
6583 el.child(
6584 h_flex()
6585 .h_full()
6586 .border_l_1()
6587 .rounded_r_lg()
6588 .border_color(cx.theme().colors().border)
6589 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6590 .gap_1()
6591 .py_1()
6592 .px_2()
6593 .child(
6594 h_flex()
6595 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6596 .when(is_platform_style_mac, |parent| parent.gap_1())
6597 .child(h_flex().children(ui::render_modifiers(
6598 &accept_keystroke.modifiers,
6599 PlatformStyle::platform(),
6600 Some(if !has_completion {
6601 Color::Muted
6602 } else {
6603 Color::Default
6604 }),
6605 None,
6606 false,
6607 ))),
6608 )
6609 .child(Label::new("Preview").into_any_element())
6610 .opacity(if has_completion { 1.0 } else { 0.4 }),
6611 )
6612 })
6613 .into_any(),
6614 )
6615 }
6616
6617 fn render_edit_prediction_cursor_popover_preview(
6618 &self,
6619 completion: &InlineCompletionState,
6620 cursor_point: Point,
6621 style: &EditorStyle,
6622 cx: &mut Context<Editor>,
6623 ) -> Option<Div> {
6624 use text::ToPoint as _;
6625
6626 fn render_relative_row_jump(
6627 prefix: impl Into<String>,
6628 current_row: u32,
6629 target_row: u32,
6630 ) -> Div {
6631 let (row_diff, arrow) = if target_row < current_row {
6632 (current_row - target_row, IconName::ArrowUp)
6633 } else {
6634 (target_row - current_row, IconName::ArrowDown)
6635 };
6636
6637 h_flex()
6638 .child(
6639 Label::new(format!("{}{}", prefix.into(), row_diff))
6640 .color(Color::Muted)
6641 .size(LabelSize::Small),
6642 )
6643 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6644 }
6645
6646 match &completion.completion {
6647 InlineCompletion::Move {
6648 target, snapshot, ..
6649 } => Some(
6650 h_flex()
6651 .px_2()
6652 .gap_2()
6653 .flex_1()
6654 .child(
6655 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6656 Icon::new(IconName::ZedPredictDown)
6657 } else {
6658 Icon::new(IconName::ZedPredictUp)
6659 },
6660 )
6661 .child(Label::new("Jump to Edit")),
6662 ),
6663
6664 InlineCompletion::Edit {
6665 edits,
6666 edit_preview,
6667 snapshot,
6668 display_mode: _,
6669 } => {
6670 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6671
6672 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6673 &snapshot,
6674 &edits,
6675 edit_preview.as_ref()?,
6676 true,
6677 cx,
6678 )
6679 .first_line_preview();
6680
6681 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6682 .with_highlights(&style.text, highlighted_edits.highlights);
6683
6684 let preview = h_flex()
6685 .gap_1()
6686 .min_w_16()
6687 .child(styled_text)
6688 .when(has_more_lines, |parent| parent.child("…"));
6689
6690 let left = if first_edit_row != cursor_point.row {
6691 render_relative_row_jump("", cursor_point.row, first_edit_row)
6692 .into_any_element()
6693 } else {
6694 Icon::new(IconName::ZedPredict).into_any_element()
6695 };
6696
6697 Some(
6698 h_flex()
6699 .h_full()
6700 .flex_1()
6701 .gap_2()
6702 .pr_1()
6703 .overflow_x_hidden()
6704 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6705 .child(left)
6706 .child(preview),
6707 )
6708 }
6709 }
6710 }
6711
6712 fn render_context_menu(
6713 &self,
6714 style: &EditorStyle,
6715 max_height_in_lines: u32,
6716 y_flipped: bool,
6717 window: &mut Window,
6718 cx: &mut Context<Editor>,
6719 ) -> Option<AnyElement> {
6720 let menu = self.context_menu.borrow();
6721 let menu = menu.as_ref()?;
6722 if !menu.visible() {
6723 return None;
6724 };
6725 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6726 }
6727
6728 fn render_context_menu_aside(
6729 &mut self,
6730 max_size: Size<Pixels>,
6731 window: &mut Window,
6732 cx: &mut Context<Editor>,
6733 ) -> Option<AnyElement> {
6734 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6735 if menu.visible() {
6736 menu.render_aside(self, max_size, window, cx)
6737 } else {
6738 None
6739 }
6740 })
6741 }
6742
6743 fn hide_context_menu(
6744 &mut self,
6745 window: &mut Window,
6746 cx: &mut Context<Self>,
6747 ) -> Option<CodeContextMenu> {
6748 cx.notify();
6749 self.completion_tasks.clear();
6750 let context_menu = self.context_menu.borrow_mut().take();
6751 self.stale_inline_completion_in_menu.take();
6752 self.update_visible_inline_completion(window, cx);
6753 context_menu
6754 }
6755
6756 fn show_snippet_choices(
6757 &mut self,
6758 choices: &Vec<String>,
6759 selection: Range<Anchor>,
6760 cx: &mut Context<Self>,
6761 ) {
6762 if selection.start.buffer_id.is_none() {
6763 return;
6764 }
6765 let buffer_id = selection.start.buffer_id.unwrap();
6766 let buffer = self.buffer().read(cx).buffer(buffer_id);
6767 let id = post_inc(&mut self.next_completion_id);
6768
6769 if let Some(buffer) = buffer {
6770 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6771 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6772 ));
6773 }
6774 }
6775
6776 pub fn insert_snippet(
6777 &mut self,
6778 insertion_ranges: &[Range<usize>],
6779 snippet: Snippet,
6780 window: &mut Window,
6781 cx: &mut Context<Self>,
6782 ) -> Result<()> {
6783 struct Tabstop<T> {
6784 is_end_tabstop: bool,
6785 ranges: Vec<Range<T>>,
6786 choices: Option<Vec<String>>,
6787 }
6788
6789 let tabstops = self.buffer.update(cx, |buffer, cx| {
6790 let snippet_text: Arc<str> = snippet.text.clone().into();
6791 buffer.edit(
6792 insertion_ranges
6793 .iter()
6794 .cloned()
6795 .map(|range| (range, snippet_text.clone())),
6796 Some(AutoindentMode::EachLine),
6797 cx,
6798 );
6799
6800 let snapshot = &*buffer.read(cx);
6801 let snippet = &snippet;
6802 snippet
6803 .tabstops
6804 .iter()
6805 .map(|tabstop| {
6806 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6807 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6808 });
6809 let mut tabstop_ranges = tabstop
6810 .ranges
6811 .iter()
6812 .flat_map(|tabstop_range| {
6813 let mut delta = 0_isize;
6814 insertion_ranges.iter().map(move |insertion_range| {
6815 let insertion_start = insertion_range.start as isize + delta;
6816 delta +=
6817 snippet.text.len() as isize - insertion_range.len() as isize;
6818
6819 let start = ((insertion_start + tabstop_range.start) as usize)
6820 .min(snapshot.len());
6821 let end = ((insertion_start + tabstop_range.end) as usize)
6822 .min(snapshot.len());
6823 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6824 })
6825 })
6826 .collect::<Vec<_>>();
6827 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6828
6829 Tabstop {
6830 is_end_tabstop,
6831 ranges: tabstop_ranges,
6832 choices: tabstop.choices.clone(),
6833 }
6834 })
6835 .collect::<Vec<_>>()
6836 });
6837 if let Some(tabstop) = tabstops.first() {
6838 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6839 s.select_ranges(tabstop.ranges.iter().cloned());
6840 });
6841
6842 if let Some(choices) = &tabstop.choices {
6843 if let Some(selection) = tabstop.ranges.first() {
6844 self.show_snippet_choices(choices, selection.clone(), cx)
6845 }
6846 }
6847
6848 // If we're already at the last tabstop and it's at the end of the snippet,
6849 // we're done, we don't need to keep the state around.
6850 if !tabstop.is_end_tabstop {
6851 let choices = tabstops
6852 .iter()
6853 .map(|tabstop| tabstop.choices.clone())
6854 .collect();
6855
6856 let ranges = tabstops
6857 .into_iter()
6858 .map(|tabstop| tabstop.ranges)
6859 .collect::<Vec<_>>();
6860
6861 self.snippet_stack.push(SnippetState {
6862 active_index: 0,
6863 ranges,
6864 choices,
6865 });
6866 }
6867
6868 // Check whether the just-entered snippet ends with an auto-closable bracket.
6869 if self.autoclose_regions.is_empty() {
6870 let snapshot = self.buffer.read(cx).snapshot(cx);
6871 for selection in &mut self.selections.all::<Point>(cx) {
6872 let selection_head = selection.head();
6873 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6874 continue;
6875 };
6876
6877 let mut bracket_pair = None;
6878 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6879 let prev_chars = snapshot
6880 .reversed_chars_at(selection_head)
6881 .collect::<String>();
6882 for (pair, enabled) in scope.brackets() {
6883 if enabled
6884 && pair.close
6885 && prev_chars.starts_with(pair.start.as_str())
6886 && next_chars.starts_with(pair.end.as_str())
6887 {
6888 bracket_pair = Some(pair.clone());
6889 break;
6890 }
6891 }
6892 if let Some(pair) = bracket_pair {
6893 let start = snapshot.anchor_after(selection_head);
6894 let end = snapshot.anchor_after(selection_head);
6895 self.autoclose_regions.push(AutocloseRegion {
6896 selection_id: selection.id,
6897 range: start..end,
6898 pair,
6899 });
6900 }
6901 }
6902 }
6903 }
6904 Ok(())
6905 }
6906
6907 pub fn move_to_next_snippet_tabstop(
6908 &mut self,
6909 window: &mut Window,
6910 cx: &mut Context<Self>,
6911 ) -> bool {
6912 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6913 }
6914
6915 pub fn move_to_prev_snippet_tabstop(
6916 &mut self,
6917 window: &mut Window,
6918 cx: &mut Context<Self>,
6919 ) -> bool {
6920 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6921 }
6922
6923 pub fn move_to_snippet_tabstop(
6924 &mut self,
6925 bias: Bias,
6926 window: &mut Window,
6927 cx: &mut Context<Self>,
6928 ) -> bool {
6929 if let Some(mut snippet) = self.snippet_stack.pop() {
6930 match bias {
6931 Bias::Left => {
6932 if snippet.active_index > 0 {
6933 snippet.active_index -= 1;
6934 } else {
6935 self.snippet_stack.push(snippet);
6936 return false;
6937 }
6938 }
6939 Bias::Right => {
6940 if snippet.active_index + 1 < snippet.ranges.len() {
6941 snippet.active_index += 1;
6942 } else {
6943 self.snippet_stack.push(snippet);
6944 return false;
6945 }
6946 }
6947 }
6948 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6949 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6950 s.select_anchor_ranges(current_ranges.iter().cloned())
6951 });
6952
6953 if let Some(choices) = &snippet.choices[snippet.active_index] {
6954 if let Some(selection) = current_ranges.first() {
6955 self.show_snippet_choices(&choices, selection.clone(), cx);
6956 }
6957 }
6958
6959 // If snippet state is not at the last tabstop, push it back on the stack
6960 if snippet.active_index + 1 < snippet.ranges.len() {
6961 self.snippet_stack.push(snippet);
6962 }
6963 return true;
6964 }
6965 }
6966
6967 false
6968 }
6969
6970 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6971 self.transact(window, cx, |this, window, cx| {
6972 this.select_all(&SelectAll, window, cx);
6973 this.insert("", window, cx);
6974 });
6975 }
6976
6977 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6978 self.transact(window, cx, |this, window, cx| {
6979 this.select_autoclose_pair(window, cx);
6980 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6981 if !this.linked_edit_ranges.is_empty() {
6982 let selections = this.selections.all::<MultiBufferPoint>(cx);
6983 let snapshot = this.buffer.read(cx).snapshot(cx);
6984
6985 for selection in selections.iter() {
6986 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6987 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6988 if selection_start.buffer_id != selection_end.buffer_id {
6989 continue;
6990 }
6991 if let Some(ranges) =
6992 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6993 {
6994 for (buffer, entries) in ranges {
6995 linked_ranges.entry(buffer).or_default().extend(entries);
6996 }
6997 }
6998 }
6999 }
7000
7001 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7002 if !this.selections.line_mode {
7003 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7004 for selection in &mut selections {
7005 if selection.is_empty() {
7006 let old_head = selection.head();
7007 let mut new_head =
7008 movement::left(&display_map, old_head.to_display_point(&display_map))
7009 .to_point(&display_map);
7010 if let Some((buffer, line_buffer_range)) = display_map
7011 .buffer_snapshot
7012 .buffer_line_for_row(MultiBufferRow(old_head.row))
7013 {
7014 let indent_size =
7015 buffer.indent_size_for_line(line_buffer_range.start.row);
7016 let indent_len = match indent_size.kind {
7017 IndentKind::Space => {
7018 buffer.settings_at(line_buffer_range.start, cx).tab_size
7019 }
7020 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7021 };
7022 if old_head.column <= indent_size.len && old_head.column > 0 {
7023 let indent_len = indent_len.get();
7024 new_head = cmp::min(
7025 new_head,
7026 MultiBufferPoint::new(
7027 old_head.row,
7028 ((old_head.column - 1) / indent_len) * indent_len,
7029 ),
7030 );
7031 }
7032 }
7033
7034 selection.set_head(new_head, SelectionGoal::None);
7035 }
7036 }
7037 }
7038
7039 this.signature_help_state.set_backspace_pressed(true);
7040 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7041 s.select(selections)
7042 });
7043 this.insert("", window, cx);
7044 let empty_str: Arc<str> = Arc::from("");
7045 for (buffer, edits) in linked_ranges {
7046 let snapshot = buffer.read(cx).snapshot();
7047 use text::ToPoint as TP;
7048
7049 let edits = edits
7050 .into_iter()
7051 .map(|range| {
7052 let end_point = TP::to_point(&range.end, &snapshot);
7053 let mut start_point = TP::to_point(&range.start, &snapshot);
7054
7055 if end_point == start_point {
7056 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7057 .saturating_sub(1);
7058 start_point =
7059 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7060 };
7061
7062 (start_point..end_point, empty_str.clone())
7063 })
7064 .sorted_by_key(|(range, _)| range.start)
7065 .collect::<Vec<_>>();
7066 buffer.update(cx, |this, cx| {
7067 this.edit(edits, None, cx);
7068 })
7069 }
7070 this.refresh_inline_completion(true, false, window, cx);
7071 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7072 });
7073 }
7074
7075 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7076 self.transact(window, cx, |this, window, cx| {
7077 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7078 let line_mode = s.line_mode;
7079 s.move_with(|map, selection| {
7080 if selection.is_empty() && !line_mode {
7081 let cursor = movement::right(map, selection.head());
7082 selection.end = cursor;
7083 selection.reversed = true;
7084 selection.goal = SelectionGoal::None;
7085 }
7086 })
7087 });
7088 this.insert("", window, cx);
7089 this.refresh_inline_completion(true, false, window, cx);
7090 });
7091 }
7092
7093 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
7094 if self.move_to_prev_snippet_tabstop(window, cx) {
7095 return;
7096 }
7097
7098 self.outdent(&Outdent, window, cx);
7099 }
7100
7101 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7102 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7103 return;
7104 }
7105
7106 let mut selections = self.selections.all_adjusted(cx);
7107 let buffer = self.buffer.read(cx);
7108 let snapshot = buffer.snapshot(cx);
7109 let rows_iter = selections.iter().map(|s| s.head().row);
7110 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7111
7112 let mut edits = Vec::new();
7113 let mut prev_edited_row = 0;
7114 let mut row_delta = 0;
7115 for selection in &mut selections {
7116 if selection.start.row != prev_edited_row {
7117 row_delta = 0;
7118 }
7119 prev_edited_row = selection.end.row;
7120
7121 // If the selection is non-empty, then increase the indentation of the selected lines.
7122 if !selection.is_empty() {
7123 row_delta =
7124 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7125 continue;
7126 }
7127
7128 // If the selection is empty and the cursor is in the leading whitespace before the
7129 // suggested indentation, then auto-indent the line.
7130 let cursor = selection.head();
7131 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7132 if let Some(suggested_indent) =
7133 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7134 {
7135 if cursor.column < suggested_indent.len
7136 && cursor.column <= current_indent.len
7137 && current_indent.len <= suggested_indent.len
7138 {
7139 selection.start = Point::new(cursor.row, suggested_indent.len);
7140 selection.end = selection.start;
7141 if row_delta == 0 {
7142 edits.extend(Buffer::edit_for_indent_size_adjustment(
7143 cursor.row,
7144 current_indent,
7145 suggested_indent,
7146 ));
7147 row_delta = suggested_indent.len - current_indent.len;
7148 }
7149 continue;
7150 }
7151 }
7152
7153 // Otherwise, insert a hard or soft tab.
7154 let settings = buffer.settings_at(cursor, cx);
7155 let tab_size = if settings.hard_tabs {
7156 IndentSize::tab()
7157 } else {
7158 let tab_size = settings.tab_size.get();
7159 let char_column = snapshot
7160 .text_for_range(Point::new(cursor.row, 0)..cursor)
7161 .flat_map(str::chars)
7162 .count()
7163 + row_delta as usize;
7164 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7165 IndentSize::spaces(chars_to_next_tab_stop)
7166 };
7167 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7168 selection.end = selection.start;
7169 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7170 row_delta += tab_size.len;
7171 }
7172
7173 self.transact(window, cx, |this, window, cx| {
7174 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7175 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7176 s.select(selections)
7177 });
7178 this.refresh_inline_completion(true, false, window, cx);
7179 });
7180 }
7181
7182 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7183 if self.read_only(cx) {
7184 return;
7185 }
7186 let mut selections = self.selections.all::<Point>(cx);
7187 let mut prev_edited_row = 0;
7188 let mut row_delta = 0;
7189 let mut edits = Vec::new();
7190 let buffer = self.buffer.read(cx);
7191 let snapshot = buffer.snapshot(cx);
7192 for selection in &mut selections {
7193 if selection.start.row != prev_edited_row {
7194 row_delta = 0;
7195 }
7196 prev_edited_row = selection.end.row;
7197
7198 row_delta =
7199 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7200 }
7201
7202 self.transact(window, cx, |this, window, cx| {
7203 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7204 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7205 s.select(selections)
7206 });
7207 });
7208 }
7209
7210 fn indent_selection(
7211 buffer: &MultiBuffer,
7212 snapshot: &MultiBufferSnapshot,
7213 selection: &mut Selection<Point>,
7214 edits: &mut Vec<(Range<Point>, String)>,
7215 delta_for_start_row: u32,
7216 cx: &App,
7217 ) -> u32 {
7218 let settings = buffer.settings_at(selection.start, cx);
7219 let tab_size = settings.tab_size.get();
7220 let indent_kind = if settings.hard_tabs {
7221 IndentKind::Tab
7222 } else {
7223 IndentKind::Space
7224 };
7225 let mut start_row = selection.start.row;
7226 let mut end_row = selection.end.row + 1;
7227
7228 // If a selection ends at the beginning of a line, don't indent
7229 // that last line.
7230 if selection.end.column == 0 && selection.end.row > selection.start.row {
7231 end_row -= 1;
7232 }
7233
7234 // Avoid re-indenting a row that has already been indented by a
7235 // previous selection, but still update this selection's column
7236 // to reflect that indentation.
7237 if delta_for_start_row > 0 {
7238 start_row += 1;
7239 selection.start.column += delta_for_start_row;
7240 if selection.end.row == selection.start.row {
7241 selection.end.column += delta_for_start_row;
7242 }
7243 }
7244
7245 let mut delta_for_end_row = 0;
7246 let has_multiple_rows = start_row + 1 != end_row;
7247 for row in start_row..end_row {
7248 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7249 let indent_delta = match (current_indent.kind, indent_kind) {
7250 (IndentKind::Space, IndentKind::Space) => {
7251 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7252 IndentSize::spaces(columns_to_next_tab_stop)
7253 }
7254 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7255 (_, IndentKind::Tab) => IndentSize::tab(),
7256 };
7257
7258 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7259 0
7260 } else {
7261 selection.start.column
7262 };
7263 let row_start = Point::new(row, start);
7264 edits.push((
7265 row_start..row_start,
7266 indent_delta.chars().collect::<String>(),
7267 ));
7268
7269 // Update this selection's endpoints to reflect the indentation.
7270 if row == selection.start.row {
7271 selection.start.column += indent_delta.len;
7272 }
7273 if row == selection.end.row {
7274 selection.end.column += indent_delta.len;
7275 delta_for_end_row = indent_delta.len;
7276 }
7277 }
7278
7279 if selection.start.row == selection.end.row {
7280 delta_for_start_row + delta_for_end_row
7281 } else {
7282 delta_for_end_row
7283 }
7284 }
7285
7286 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7287 if self.read_only(cx) {
7288 return;
7289 }
7290 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7291 let selections = self.selections.all::<Point>(cx);
7292 let mut deletion_ranges = Vec::new();
7293 let mut last_outdent = None;
7294 {
7295 let buffer = self.buffer.read(cx);
7296 let snapshot = buffer.snapshot(cx);
7297 for selection in &selections {
7298 let settings = buffer.settings_at(selection.start, cx);
7299 let tab_size = settings.tab_size.get();
7300 let mut rows = selection.spanned_rows(false, &display_map);
7301
7302 // Avoid re-outdenting a row that has already been outdented by a
7303 // previous selection.
7304 if let Some(last_row) = last_outdent {
7305 if last_row == rows.start {
7306 rows.start = rows.start.next_row();
7307 }
7308 }
7309 let has_multiple_rows = rows.len() > 1;
7310 for row in rows.iter_rows() {
7311 let indent_size = snapshot.indent_size_for_line(row);
7312 if indent_size.len > 0 {
7313 let deletion_len = match indent_size.kind {
7314 IndentKind::Space => {
7315 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7316 if columns_to_prev_tab_stop == 0 {
7317 tab_size
7318 } else {
7319 columns_to_prev_tab_stop
7320 }
7321 }
7322 IndentKind::Tab => 1,
7323 };
7324 let start = if has_multiple_rows
7325 || deletion_len > selection.start.column
7326 || indent_size.len < selection.start.column
7327 {
7328 0
7329 } else {
7330 selection.start.column - deletion_len
7331 };
7332 deletion_ranges.push(
7333 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7334 );
7335 last_outdent = Some(row);
7336 }
7337 }
7338 }
7339 }
7340
7341 self.transact(window, cx, |this, window, cx| {
7342 this.buffer.update(cx, |buffer, cx| {
7343 let empty_str: Arc<str> = Arc::default();
7344 buffer.edit(
7345 deletion_ranges
7346 .into_iter()
7347 .map(|range| (range, empty_str.clone())),
7348 None,
7349 cx,
7350 );
7351 });
7352 let selections = this.selections.all::<usize>(cx);
7353 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7354 s.select(selections)
7355 });
7356 });
7357 }
7358
7359 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7360 if self.read_only(cx) {
7361 return;
7362 }
7363 let selections = self
7364 .selections
7365 .all::<usize>(cx)
7366 .into_iter()
7367 .map(|s| s.range());
7368
7369 self.transact(window, cx, |this, window, cx| {
7370 this.buffer.update(cx, |buffer, cx| {
7371 buffer.autoindent_ranges(selections, cx);
7372 });
7373 let selections = this.selections.all::<usize>(cx);
7374 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7375 s.select(selections)
7376 });
7377 });
7378 }
7379
7380 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7381 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7382 let selections = self.selections.all::<Point>(cx);
7383
7384 let mut new_cursors = Vec::new();
7385 let mut edit_ranges = Vec::new();
7386 let mut selections = selections.iter().peekable();
7387 while let Some(selection) = selections.next() {
7388 let mut rows = selection.spanned_rows(false, &display_map);
7389 let goal_display_column = selection.head().to_display_point(&display_map).column();
7390
7391 // Accumulate contiguous regions of rows that we want to delete.
7392 while let Some(next_selection) = selections.peek() {
7393 let next_rows = next_selection.spanned_rows(false, &display_map);
7394 if next_rows.start <= rows.end {
7395 rows.end = next_rows.end;
7396 selections.next().unwrap();
7397 } else {
7398 break;
7399 }
7400 }
7401
7402 let buffer = &display_map.buffer_snapshot;
7403 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7404 let edit_end;
7405 let cursor_buffer_row;
7406 if buffer.max_point().row >= rows.end.0 {
7407 // If there's a line after the range, delete the \n from the end of the row range
7408 // and position the cursor on the next line.
7409 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7410 cursor_buffer_row = rows.end;
7411 } else {
7412 // If there isn't a line after the range, delete the \n from the line before the
7413 // start of the row range and position the cursor there.
7414 edit_start = edit_start.saturating_sub(1);
7415 edit_end = buffer.len();
7416 cursor_buffer_row = rows.start.previous_row();
7417 }
7418
7419 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7420 *cursor.column_mut() =
7421 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7422
7423 new_cursors.push((
7424 selection.id,
7425 buffer.anchor_after(cursor.to_point(&display_map)),
7426 ));
7427 edit_ranges.push(edit_start..edit_end);
7428 }
7429
7430 self.transact(window, cx, |this, window, cx| {
7431 let buffer = this.buffer.update(cx, |buffer, cx| {
7432 let empty_str: Arc<str> = Arc::default();
7433 buffer.edit(
7434 edit_ranges
7435 .into_iter()
7436 .map(|range| (range, empty_str.clone())),
7437 None,
7438 cx,
7439 );
7440 buffer.snapshot(cx)
7441 });
7442 let new_selections = new_cursors
7443 .into_iter()
7444 .map(|(id, cursor)| {
7445 let cursor = cursor.to_point(&buffer);
7446 Selection {
7447 id,
7448 start: cursor,
7449 end: cursor,
7450 reversed: false,
7451 goal: SelectionGoal::None,
7452 }
7453 })
7454 .collect();
7455
7456 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7457 s.select(new_selections);
7458 });
7459 });
7460 }
7461
7462 pub fn join_lines_impl(
7463 &mut self,
7464 insert_whitespace: bool,
7465 window: &mut Window,
7466 cx: &mut Context<Self>,
7467 ) {
7468 if self.read_only(cx) {
7469 return;
7470 }
7471 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7472 for selection in self.selections.all::<Point>(cx) {
7473 let start = MultiBufferRow(selection.start.row);
7474 // Treat single line selections as if they include the next line. Otherwise this action
7475 // would do nothing for single line selections individual cursors.
7476 let end = if selection.start.row == selection.end.row {
7477 MultiBufferRow(selection.start.row + 1)
7478 } else {
7479 MultiBufferRow(selection.end.row)
7480 };
7481
7482 if let Some(last_row_range) = row_ranges.last_mut() {
7483 if start <= last_row_range.end {
7484 last_row_range.end = end;
7485 continue;
7486 }
7487 }
7488 row_ranges.push(start..end);
7489 }
7490
7491 let snapshot = self.buffer.read(cx).snapshot(cx);
7492 let mut cursor_positions = Vec::new();
7493 for row_range in &row_ranges {
7494 let anchor = snapshot.anchor_before(Point::new(
7495 row_range.end.previous_row().0,
7496 snapshot.line_len(row_range.end.previous_row()),
7497 ));
7498 cursor_positions.push(anchor..anchor);
7499 }
7500
7501 self.transact(window, cx, |this, window, cx| {
7502 for row_range in row_ranges.into_iter().rev() {
7503 for row in row_range.iter_rows().rev() {
7504 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7505 let next_line_row = row.next_row();
7506 let indent = snapshot.indent_size_for_line(next_line_row);
7507 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7508
7509 let replace =
7510 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7511 " "
7512 } else {
7513 ""
7514 };
7515
7516 this.buffer.update(cx, |buffer, cx| {
7517 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7518 });
7519 }
7520 }
7521
7522 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7523 s.select_anchor_ranges(cursor_positions)
7524 });
7525 });
7526 }
7527
7528 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7529 self.join_lines_impl(true, window, cx);
7530 }
7531
7532 pub fn sort_lines_case_sensitive(
7533 &mut self,
7534 _: &SortLinesCaseSensitive,
7535 window: &mut Window,
7536 cx: &mut Context<Self>,
7537 ) {
7538 self.manipulate_lines(window, cx, |lines| lines.sort())
7539 }
7540
7541 pub fn sort_lines_case_insensitive(
7542 &mut self,
7543 _: &SortLinesCaseInsensitive,
7544 window: &mut Window,
7545 cx: &mut Context<Self>,
7546 ) {
7547 self.manipulate_lines(window, cx, |lines| {
7548 lines.sort_by_key(|line| line.to_lowercase())
7549 })
7550 }
7551
7552 pub fn unique_lines_case_insensitive(
7553 &mut self,
7554 _: &UniqueLinesCaseInsensitive,
7555 window: &mut Window,
7556 cx: &mut Context<Self>,
7557 ) {
7558 self.manipulate_lines(window, cx, |lines| {
7559 let mut seen = HashSet::default();
7560 lines.retain(|line| seen.insert(line.to_lowercase()));
7561 })
7562 }
7563
7564 pub fn unique_lines_case_sensitive(
7565 &mut self,
7566 _: &UniqueLinesCaseSensitive,
7567 window: &mut Window,
7568 cx: &mut Context<Self>,
7569 ) {
7570 self.manipulate_lines(window, cx, |lines| {
7571 let mut seen = HashSet::default();
7572 lines.retain(|line| seen.insert(*line));
7573 })
7574 }
7575
7576 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7577 let Some(project) = self.project.clone() else {
7578 return;
7579 };
7580 self.reload(project, window, cx)
7581 .detach_and_notify_err(window, cx);
7582 }
7583
7584 pub fn restore_file(
7585 &mut self,
7586 _: &::git::RestoreFile,
7587 window: &mut Window,
7588 cx: &mut Context<Self>,
7589 ) {
7590 let mut buffer_ids = HashSet::default();
7591 let snapshot = self.buffer().read(cx).snapshot(cx);
7592 for selection in self.selections.all::<usize>(cx) {
7593 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7594 }
7595
7596 let buffer = self.buffer().read(cx);
7597 let ranges = buffer_ids
7598 .into_iter()
7599 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7600 .collect::<Vec<_>>();
7601
7602 self.restore_hunks_in_ranges(ranges, window, cx);
7603 }
7604
7605 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7606 let selections = self
7607 .selections
7608 .all(cx)
7609 .into_iter()
7610 .map(|s| s.range())
7611 .collect();
7612 self.restore_hunks_in_ranges(selections, window, cx);
7613 }
7614
7615 fn restore_hunks_in_ranges(
7616 &mut self,
7617 ranges: Vec<Range<Point>>,
7618 window: &mut Window,
7619 cx: &mut Context<Editor>,
7620 ) {
7621 let mut revert_changes = HashMap::default();
7622 let snapshot = self.buffer.read(cx).snapshot(cx);
7623 let Some(project) = &self.project else {
7624 return;
7625 };
7626
7627 let chunk_by = self
7628 .snapshot(window, cx)
7629 .hunks_for_ranges(ranges.into_iter())
7630 .into_iter()
7631 .chunk_by(|hunk| hunk.buffer_id);
7632 for (buffer_id, hunks) in &chunk_by {
7633 let hunks = hunks.collect::<Vec<_>>();
7634 for hunk in &hunks {
7635 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7636 }
7637 Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
7638 }
7639 drop(chunk_by);
7640 if !revert_changes.is_empty() {
7641 self.transact(window, cx, |editor, window, cx| {
7642 editor.revert(revert_changes, window, cx);
7643 });
7644 }
7645 }
7646
7647 pub fn open_active_item_in_terminal(
7648 &mut self,
7649 _: &OpenInTerminal,
7650 window: &mut Window,
7651 cx: &mut Context<Self>,
7652 ) {
7653 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7654 let project_path = buffer.read(cx).project_path(cx)?;
7655 let project = self.project.as_ref()?.read(cx);
7656 let entry = project.entry_for_path(&project_path, cx)?;
7657 let parent = match &entry.canonical_path {
7658 Some(canonical_path) => canonical_path.to_path_buf(),
7659 None => project.absolute_path(&project_path, cx)?,
7660 }
7661 .parent()?
7662 .to_path_buf();
7663 Some(parent)
7664 }) {
7665 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7666 }
7667 }
7668
7669 pub fn prepare_restore_change(
7670 &self,
7671 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7672 hunk: &MultiBufferDiffHunk,
7673 cx: &mut App,
7674 ) -> Option<()> {
7675 let buffer = self.buffer.read(cx);
7676 let diff = buffer.diff_for(hunk.buffer_id)?;
7677 let buffer = buffer.buffer(hunk.buffer_id)?;
7678 let buffer = buffer.read(cx);
7679 let original_text = diff
7680 .read(cx)
7681 .base_text()
7682 .as_ref()?
7683 .as_rope()
7684 .slice(hunk.diff_base_byte_range.clone());
7685 let buffer_snapshot = buffer.snapshot();
7686 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7687 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7688 probe
7689 .0
7690 .start
7691 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7692 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7693 }) {
7694 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7695 Some(())
7696 } else {
7697 None
7698 }
7699 }
7700
7701 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7702 self.manipulate_lines(window, cx, |lines| lines.reverse())
7703 }
7704
7705 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7706 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7707 }
7708
7709 fn manipulate_lines<Fn>(
7710 &mut self,
7711 window: &mut Window,
7712 cx: &mut Context<Self>,
7713 mut callback: Fn,
7714 ) where
7715 Fn: FnMut(&mut Vec<&str>),
7716 {
7717 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7718 let buffer = self.buffer.read(cx).snapshot(cx);
7719
7720 let mut edits = Vec::new();
7721
7722 let selections = self.selections.all::<Point>(cx);
7723 let mut selections = selections.iter().peekable();
7724 let mut contiguous_row_selections = Vec::new();
7725 let mut new_selections = Vec::new();
7726 let mut added_lines = 0;
7727 let mut removed_lines = 0;
7728
7729 while let Some(selection) = selections.next() {
7730 let (start_row, end_row) = consume_contiguous_rows(
7731 &mut contiguous_row_selections,
7732 selection,
7733 &display_map,
7734 &mut selections,
7735 );
7736
7737 let start_point = Point::new(start_row.0, 0);
7738 let end_point = Point::new(
7739 end_row.previous_row().0,
7740 buffer.line_len(end_row.previous_row()),
7741 );
7742 let text = buffer
7743 .text_for_range(start_point..end_point)
7744 .collect::<String>();
7745
7746 let mut lines = text.split('\n').collect_vec();
7747
7748 let lines_before = lines.len();
7749 callback(&mut lines);
7750 let lines_after = lines.len();
7751
7752 edits.push((start_point..end_point, lines.join("\n")));
7753
7754 // Selections must change based on added and removed line count
7755 let start_row =
7756 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7757 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7758 new_selections.push(Selection {
7759 id: selection.id,
7760 start: start_row,
7761 end: end_row,
7762 goal: SelectionGoal::None,
7763 reversed: selection.reversed,
7764 });
7765
7766 if lines_after > lines_before {
7767 added_lines += lines_after - lines_before;
7768 } else if lines_before > lines_after {
7769 removed_lines += lines_before - lines_after;
7770 }
7771 }
7772
7773 self.transact(window, cx, |this, window, cx| {
7774 let buffer = this.buffer.update(cx, |buffer, cx| {
7775 buffer.edit(edits, None, cx);
7776 buffer.snapshot(cx)
7777 });
7778
7779 // Recalculate offsets on newly edited buffer
7780 let new_selections = new_selections
7781 .iter()
7782 .map(|s| {
7783 let start_point = Point::new(s.start.0, 0);
7784 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7785 Selection {
7786 id: s.id,
7787 start: buffer.point_to_offset(start_point),
7788 end: buffer.point_to_offset(end_point),
7789 goal: s.goal,
7790 reversed: s.reversed,
7791 }
7792 })
7793 .collect();
7794
7795 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7796 s.select(new_selections);
7797 });
7798
7799 this.request_autoscroll(Autoscroll::fit(), cx);
7800 });
7801 }
7802
7803 pub fn convert_to_upper_case(
7804 &mut self,
7805 _: &ConvertToUpperCase,
7806 window: &mut Window,
7807 cx: &mut Context<Self>,
7808 ) {
7809 self.manipulate_text(window, cx, |text| text.to_uppercase())
7810 }
7811
7812 pub fn convert_to_lower_case(
7813 &mut self,
7814 _: &ConvertToLowerCase,
7815 window: &mut Window,
7816 cx: &mut Context<Self>,
7817 ) {
7818 self.manipulate_text(window, cx, |text| text.to_lowercase())
7819 }
7820
7821 pub fn convert_to_title_case(
7822 &mut self,
7823 _: &ConvertToTitleCase,
7824 window: &mut Window,
7825 cx: &mut Context<Self>,
7826 ) {
7827 self.manipulate_text(window, cx, |text| {
7828 text.split('\n')
7829 .map(|line| line.to_case(Case::Title))
7830 .join("\n")
7831 })
7832 }
7833
7834 pub fn convert_to_snake_case(
7835 &mut self,
7836 _: &ConvertToSnakeCase,
7837 window: &mut Window,
7838 cx: &mut Context<Self>,
7839 ) {
7840 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7841 }
7842
7843 pub fn convert_to_kebab_case(
7844 &mut self,
7845 _: &ConvertToKebabCase,
7846 window: &mut Window,
7847 cx: &mut Context<Self>,
7848 ) {
7849 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7850 }
7851
7852 pub fn convert_to_upper_camel_case(
7853 &mut self,
7854 _: &ConvertToUpperCamelCase,
7855 window: &mut Window,
7856 cx: &mut Context<Self>,
7857 ) {
7858 self.manipulate_text(window, cx, |text| {
7859 text.split('\n')
7860 .map(|line| line.to_case(Case::UpperCamel))
7861 .join("\n")
7862 })
7863 }
7864
7865 pub fn convert_to_lower_camel_case(
7866 &mut self,
7867 _: &ConvertToLowerCamelCase,
7868 window: &mut Window,
7869 cx: &mut Context<Self>,
7870 ) {
7871 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7872 }
7873
7874 pub fn convert_to_opposite_case(
7875 &mut self,
7876 _: &ConvertToOppositeCase,
7877 window: &mut Window,
7878 cx: &mut Context<Self>,
7879 ) {
7880 self.manipulate_text(window, cx, |text| {
7881 text.chars()
7882 .fold(String::with_capacity(text.len()), |mut t, c| {
7883 if c.is_uppercase() {
7884 t.extend(c.to_lowercase());
7885 } else {
7886 t.extend(c.to_uppercase());
7887 }
7888 t
7889 })
7890 })
7891 }
7892
7893 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7894 where
7895 Fn: FnMut(&str) -> String,
7896 {
7897 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7898 let buffer = self.buffer.read(cx).snapshot(cx);
7899
7900 let mut new_selections = Vec::new();
7901 let mut edits = Vec::new();
7902 let mut selection_adjustment = 0i32;
7903
7904 for selection in self.selections.all::<usize>(cx) {
7905 let selection_is_empty = selection.is_empty();
7906
7907 let (start, end) = if selection_is_empty {
7908 let word_range = movement::surrounding_word(
7909 &display_map,
7910 selection.start.to_display_point(&display_map),
7911 );
7912 let start = word_range.start.to_offset(&display_map, Bias::Left);
7913 let end = word_range.end.to_offset(&display_map, Bias::Left);
7914 (start, end)
7915 } else {
7916 (selection.start, selection.end)
7917 };
7918
7919 let text = buffer.text_for_range(start..end).collect::<String>();
7920 let old_length = text.len() as i32;
7921 let text = callback(&text);
7922
7923 new_selections.push(Selection {
7924 start: (start as i32 - selection_adjustment) as usize,
7925 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
7926 goal: SelectionGoal::None,
7927 ..selection
7928 });
7929
7930 selection_adjustment += old_length - text.len() as i32;
7931
7932 edits.push((start..end, text));
7933 }
7934
7935 self.transact(window, cx, |this, window, cx| {
7936 this.buffer.update(cx, |buffer, cx| {
7937 buffer.edit(edits, None, cx);
7938 });
7939
7940 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7941 s.select(new_selections);
7942 });
7943
7944 this.request_autoscroll(Autoscroll::fit(), cx);
7945 });
7946 }
7947
7948 pub fn duplicate(
7949 &mut self,
7950 upwards: bool,
7951 whole_lines: bool,
7952 window: &mut Window,
7953 cx: &mut Context<Self>,
7954 ) {
7955 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7956 let buffer = &display_map.buffer_snapshot;
7957 let selections = self.selections.all::<Point>(cx);
7958
7959 let mut edits = Vec::new();
7960 let mut selections_iter = selections.iter().peekable();
7961 while let Some(selection) = selections_iter.next() {
7962 let mut rows = selection.spanned_rows(false, &display_map);
7963 // duplicate line-wise
7964 if whole_lines || selection.start == selection.end {
7965 // Avoid duplicating the same lines twice.
7966 while let Some(next_selection) = selections_iter.peek() {
7967 let next_rows = next_selection.spanned_rows(false, &display_map);
7968 if next_rows.start < rows.end {
7969 rows.end = next_rows.end;
7970 selections_iter.next().unwrap();
7971 } else {
7972 break;
7973 }
7974 }
7975
7976 // Copy the text from the selected row region and splice it either at the start
7977 // or end of the region.
7978 let start = Point::new(rows.start.0, 0);
7979 let end = Point::new(
7980 rows.end.previous_row().0,
7981 buffer.line_len(rows.end.previous_row()),
7982 );
7983 let text = buffer
7984 .text_for_range(start..end)
7985 .chain(Some("\n"))
7986 .collect::<String>();
7987 let insert_location = if upwards {
7988 Point::new(rows.end.0, 0)
7989 } else {
7990 start
7991 };
7992 edits.push((insert_location..insert_location, text));
7993 } else {
7994 // duplicate character-wise
7995 let start = selection.start;
7996 let end = selection.end;
7997 let text = buffer.text_for_range(start..end).collect::<String>();
7998 edits.push((selection.end..selection.end, text));
7999 }
8000 }
8001
8002 self.transact(window, cx, |this, _, cx| {
8003 this.buffer.update(cx, |buffer, cx| {
8004 buffer.edit(edits, None, cx);
8005 });
8006
8007 this.request_autoscroll(Autoscroll::fit(), cx);
8008 });
8009 }
8010
8011 pub fn duplicate_line_up(
8012 &mut self,
8013 _: &DuplicateLineUp,
8014 window: &mut Window,
8015 cx: &mut Context<Self>,
8016 ) {
8017 self.duplicate(true, true, window, cx);
8018 }
8019
8020 pub fn duplicate_line_down(
8021 &mut self,
8022 _: &DuplicateLineDown,
8023 window: &mut Window,
8024 cx: &mut Context<Self>,
8025 ) {
8026 self.duplicate(false, true, window, cx);
8027 }
8028
8029 pub fn duplicate_selection(
8030 &mut self,
8031 _: &DuplicateSelection,
8032 window: &mut Window,
8033 cx: &mut Context<Self>,
8034 ) {
8035 self.duplicate(false, false, window, cx);
8036 }
8037
8038 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8039 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8040 let buffer = self.buffer.read(cx).snapshot(cx);
8041
8042 let mut edits = Vec::new();
8043 let mut unfold_ranges = Vec::new();
8044 let mut refold_creases = Vec::new();
8045
8046 let selections = self.selections.all::<Point>(cx);
8047 let mut selections = selections.iter().peekable();
8048 let mut contiguous_row_selections = Vec::new();
8049 let mut new_selections = Vec::new();
8050
8051 while let Some(selection) = selections.next() {
8052 // Find all the selections that span a contiguous row range
8053 let (start_row, end_row) = consume_contiguous_rows(
8054 &mut contiguous_row_selections,
8055 selection,
8056 &display_map,
8057 &mut selections,
8058 );
8059
8060 // Move the text spanned by the row range to be before the line preceding the row range
8061 if start_row.0 > 0 {
8062 let range_to_move = Point::new(
8063 start_row.previous_row().0,
8064 buffer.line_len(start_row.previous_row()),
8065 )
8066 ..Point::new(
8067 end_row.previous_row().0,
8068 buffer.line_len(end_row.previous_row()),
8069 );
8070 let insertion_point = display_map
8071 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8072 .0;
8073
8074 // Don't move lines across excerpts
8075 if buffer
8076 .excerpt_containing(insertion_point..range_to_move.end)
8077 .is_some()
8078 {
8079 let text = buffer
8080 .text_for_range(range_to_move.clone())
8081 .flat_map(|s| s.chars())
8082 .skip(1)
8083 .chain(['\n'])
8084 .collect::<String>();
8085
8086 edits.push((
8087 buffer.anchor_after(range_to_move.start)
8088 ..buffer.anchor_before(range_to_move.end),
8089 String::new(),
8090 ));
8091 let insertion_anchor = buffer.anchor_after(insertion_point);
8092 edits.push((insertion_anchor..insertion_anchor, text));
8093
8094 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8095
8096 // Move selections up
8097 new_selections.extend(contiguous_row_selections.drain(..).map(
8098 |mut selection| {
8099 selection.start.row -= row_delta;
8100 selection.end.row -= row_delta;
8101 selection
8102 },
8103 ));
8104
8105 // Move folds up
8106 unfold_ranges.push(range_to_move.clone());
8107 for fold in display_map.folds_in_range(
8108 buffer.anchor_before(range_to_move.start)
8109 ..buffer.anchor_after(range_to_move.end),
8110 ) {
8111 let mut start = fold.range.start.to_point(&buffer);
8112 let mut end = fold.range.end.to_point(&buffer);
8113 start.row -= row_delta;
8114 end.row -= row_delta;
8115 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8116 }
8117 }
8118 }
8119
8120 // If we didn't move line(s), preserve the existing selections
8121 new_selections.append(&mut contiguous_row_selections);
8122 }
8123
8124 self.transact(window, cx, |this, window, cx| {
8125 this.unfold_ranges(&unfold_ranges, true, true, cx);
8126 this.buffer.update(cx, |buffer, cx| {
8127 for (range, text) in edits {
8128 buffer.edit([(range, text)], None, cx);
8129 }
8130 });
8131 this.fold_creases(refold_creases, true, window, cx);
8132 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8133 s.select(new_selections);
8134 })
8135 });
8136 }
8137
8138 pub fn move_line_down(
8139 &mut self,
8140 _: &MoveLineDown,
8141 window: &mut Window,
8142 cx: &mut Context<Self>,
8143 ) {
8144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8145 let buffer = self.buffer.read(cx).snapshot(cx);
8146
8147 let mut edits = Vec::new();
8148 let mut unfold_ranges = Vec::new();
8149 let mut refold_creases = Vec::new();
8150
8151 let selections = self.selections.all::<Point>(cx);
8152 let mut selections = selections.iter().peekable();
8153 let mut contiguous_row_selections = Vec::new();
8154 let mut new_selections = Vec::new();
8155
8156 while let Some(selection) = selections.next() {
8157 // Find all the selections that span a contiguous row range
8158 let (start_row, end_row) = consume_contiguous_rows(
8159 &mut contiguous_row_selections,
8160 selection,
8161 &display_map,
8162 &mut selections,
8163 );
8164
8165 // Move the text spanned by the row range to be after the last line of the row range
8166 if end_row.0 <= buffer.max_point().row {
8167 let range_to_move =
8168 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8169 let insertion_point = display_map
8170 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8171 .0;
8172
8173 // Don't move lines across excerpt boundaries
8174 if buffer
8175 .excerpt_containing(range_to_move.start..insertion_point)
8176 .is_some()
8177 {
8178 let mut text = String::from("\n");
8179 text.extend(buffer.text_for_range(range_to_move.clone()));
8180 text.pop(); // Drop trailing newline
8181 edits.push((
8182 buffer.anchor_after(range_to_move.start)
8183 ..buffer.anchor_before(range_to_move.end),
8184 String::new(),
8185 ));
8186 let insertion_anchor = buffer.anchor_after(insertion_point);
8187 edits.push((insertion_anchor..insertion_anchor, text));
8188
8189 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8190
8191 // Move selections down
8192 new_selections.extend(contiguous_row_selections.drain(..).map(
8193 |mut selection| {
8194 selection.start.row += row_delta;
8195 selection.end.row += row_delta;
8196 selection
8197 },
8198 ));
8199
8200 // Move folds down
8201 unfold_ranges.push(range_to_move.clone());
8202 for fold in display_map.folds_in_range(
8203 buffer.anchor_before(range_to_move.start)
8204 ..buffer.anchor_after(range_to_move.end),
8205 ) {
8206 let mut start = fold.range.start.to_point(&buffer);
8207 let mut end = fold.range.end.to_point(&buffer);
8208 start.row += row_delta;
8209 end.row += row_delta;
8210 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8211 }
8212 }
8213 }
8214
8215 // If we didn't move line(s), preserve the existing selections
8216 new_selections.append(&mut contiguous_row_selections);
8217 }
8218
8219 self.transact(window, cx, |this, window, cx| {
8220 this.unfold_ranges(&unfold_ranges, true, true, cx);
8221 this.buffer.update(cx, |buffer, cx| {
8222 for (range, text) in edits {
8223 buffer.edit([(range, text)], None, cx);
8224 }
8225 });
8226 this.fold_creases(refold_creases, true, window, cx);
8227 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8228 s.select(new_selections)
8229 });
8230 });
8231 }
8232
8233 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8234 let text_layout_details = &self.text_layout_details(window);
8235 self.transact(window, cx, |this, window, cx| {
8236 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8237 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8238 let line_mode = s.line_mode;
8239 s.move_with(|display_map, selection| {
8240 if !selection.is_empty() || line_mode {
8241 return;
8242 }
8243
8244 let mut head = selection.head();
8245 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8246 if head.column() == display_map.line_len(head.row()) {
8247 transpose_offset = display_map
8248 .buffer_snapshot
8249 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8250 }
8251
8252 if transpose_offset == 0 {
8253 return;
8254 }
8255
8256 *head.column_mut() += 1;
8257 head = display_map.clip_point(head, Bias::Right);
8258 let goal = SelectionGoal::HorizontalPosition(
8259 display_map
8260 .x_for_display_point(head, text_layout_details)
8261 .into(),
8262 );
8263 selection.collapse_to(head, goal);
8264
8265 let transpose_start = display_map
8266 .buffer_snapshot
8267 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8268 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8269 let transpose_end = display_map
8270 .buffer_snapshot
8271 .clip_offset(transpose_offset + 1, Bias::Right);
8272 if let Some(ch) =
8273 display_map.buffer_snapshot.chars_at(transpose_start).next()
8274 {
8275 edits.push((transpose_start..transpose_offset, String::new()));
8276 edits.push((transpose_end..transpose_end, ch.to_string()));
8277 }
8278 }
8279 });
8280 edits
8281 });
8282 this.buffer
8283 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8284 let selections = this.selections.all::<usize>(cx);
8285 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8286 s.select(selections);
8287 });
8288 });
8289 }
8290
8291 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8292 self.rewrap_impl(IsVimMode::No, cx)
8293 }
8294
8295 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8296 let buffer = self.buffer.read(cx).snapshot(cx);
8297 let selections = self.selections.all::<Point>(cx);
8298 let mut selections = selections.iter().peekable();
8299
8300 let mut edits = Vec::new();
8301 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8302
8303 while let Some(selection) = selections.next() {
8304 let mut start_row = selection.start.row;
8305 let mut end_row = selection.end.row;
8306
8307 // Skip selections that overlap with a range that has already been rewrapped.
8308 let selection_range = start_row..end_row;
8309 if rewrapped_row_ranges
8310 .iter()
8311 .any(|range| range.overlaps(&selection_range))
8312 {
8313 continue;
8314 }
8315
8316 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
8317
8318 // Since not all lines in the selection may be at the same indent
8319 // level, choose the indent size that is the most common between all
8320 // of the lines.
8321 //
8322 // If there is a tie, we use the deepest indent.
8323 let (indent_size, indent_end) = {
8324 let mut indent_size_occurrences = HashMap::default();
8325 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8326
8327 for row in start_row..=end_row {
8328 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8329 rows_by_indent_size.entry(indent).or_default().push(row);
8330 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8331 }
8332
8333 let indent_size = indent_size_occurrences
8334 .into_iter()
8335 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8336 .map(|(indent, _)| indent)
8337 .unwrap_or_default();
8338 let row = rows_by_indent_size[&indent_size][0];
8339 let indent_end = Point::new(row, indent_size.len);
8340
8341 (indent_size, indent_end)
8342 };
8343
8344 let mut line_prefix = indent_size.chars().collect::<String>();
8345
8346 let mut inside_comment = false;
8347 if let Some(comment_prefix) =
8348 buffer
8349 .language_scope_at(selection.head())
8350 .and_then(|language| {
8351 language
8352 .line_comment_prefixes()
8353 .iter()
8354 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8355 .cloned()
8356 })
8357 {
8358 line_prefix.push_str(&comment_prefix);
8359 inside_comment = true;
8360 }
8361
8362 let language_settings = buffer.settings_at(selection.head(), cx);
8363 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8364 RewrapBehavior::InComments => inside_comment,
8365 RewrapBehavior::InSelections => !selection.is_empty(),
8366 RewrapBehavior::Anywhere => true,
8367 };
8368
8369 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8370 if !should_rewrap {
8371 continue;
8372 }
8373
8374 if selection.is_empty() {
8375 'expand_upwards: while start_row > 0 {
8376 let prev_row = start_row - 1;
8377 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8378 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8379 {
8380 start_row = prev_row;
8381 } else {
8382 break 'expand_upwards;
8383 }
8384 }
8385
8386 'expand_downwards: while end_row < buffer.max_point().row {
8387 let next_row = end_row + 1;
8388 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8389 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8390 {
8391 end_row = next_row;
8392 } else {
8393 break 'expand_downwards;
8394 }
8395 }
8396 }
8397
8398 let start = Point::new(start_row, 0);
8399 let start_offset = start.to_offset(&buffer);
8400 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8401 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8402 let Some(lines_without_prefixes) = selection_text
8403 .lines()
8404 .map(|line| {
8405 line.strip_prefix(&line_prefix)
8406 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8407 .ok_or_else(|| {
8408 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8409 })
8410 })
8411 .collect::<Result<Vec<_>, _>>()
8412 .log_err()
8413 else {
8414 continue;
8415 };
8416
8417 let wrap_column = buffer
8418 .settings_at(Point::new(start_row, 0), cx)
8419 .preferred_line_length as usize;
8420 let wrapped_text = wrap_with_prefix(
8421 line_prefix,
8422 lines_without_prefixes.join(" "),
8423 wrap_column,
8424 tab_size,
8425 );
8426
8427 // TODO: should always use char-based diff while still supporting cursor behavior that
8428 // matches vim.
8429 let mut diff_options = DiffOptions::default();
8430 if is_vim_mode == IsVimMode::Yes {
8431 diff_options.max_word_diff_len = 0;
8432 diff_options.max_word_diff_line_count = 0;
8433 } else {
8434 diff_options.max_word_diff_len = usize::MAX;
8435 diff_options.max_word_diff_line_count = usize::MAX;
8436 }
8437
8438 for (old_range, new_text) in
8439 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8440 {
8441 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8442 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8443 edits.push((edit_start..edit_end, new_text));
8444 }
8445
8446 rewrapped_row_ranges.push(start_row..=end_row);
8447 }
8448
8449 self.buffer
8450 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8451 }
8452
8453 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8454 let mut text = String::new();
8455 let buffer = self.buffer.read(cx).snapshot(cx);
8456 let mut selections = self.selections.all::<Point>(cx);
8457 let mut clipboard_selections = Vec::with_capacity(selections.len());
8458 {
8459 let max_point = buffer.max_point();
8460 let mut is_first = true;
8461 for selection in &mut selections {
8462 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8463 if is_entire_line {
8464 selection.start = Point::new(selection.start.row, 0);
8465 if !selection.is_empty() && selection.end.column == 0 {
8466 selection.end = cmp::min(max_point, selection.end);
8467 } else {
8468 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8469 }
8470 selection.goal = SelectionGoal::None;
8471 }
8472 if is_first {
8473 is_first = false;
8474 } else {
8475 text += "\n";
8476 }
8477 let mut len = 0;
8478 for chunk in buffer.text_for_range(selection.start..selection.end) {
8479 text.push_str(chunk);
8480 len += chunk.len();
8481 }
8482 clipboard_selections.push(ClipboardSelection {
8483 len,
8484 is_entire_line,
8485 start_column: selection.start.column,
8486 });
8487 }
8488 }
8489
8490 self.transact(window, cx, |this, window, cx| {
8491 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8492 s.select(selections);
8493 });
8494 this.insert("", window, cx);
8495 });
8496 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8497 }
8498
8499 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8500 let item = self.cut_common(window, cx);
8501 cx.write_to_clipboard(item);
8502 }
8503
8504 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8505 self.change_selections(None, window, cx, |s| {
8506 s.move_with(|snapshot, sel| {
8507 if sel.is_empty() {
8508 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8509 }
8510 });
8511 });
8512 let item = self.cut_common(window, cx);
8513 cx.set_global(KillRing(item))
8514 }
8515
8516 pub fn kill_ring_yank(
8517 &mut self,
8518 _: &KillRingYank,
8519 window: &mut Window,
8520 cx: &mut Context<Self>,
8521 ) {
8522 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8523 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8524 (kill_ring.text().to_string(), kill_ring.metadata_json())
8525 } else {
8526 return;
8527 }
8528 } else {
8529 return;
8530 };
8531 self.do_paste(&text, metadata, false, window, cx);
8532 }
8533
8534 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8535 let selections = self.selections.all::<Point>(cx);
8536 let buffer = self.buffer.read(cx).read(cx);
8537 let mut text = String::new();
8538
8539 let mut clipboard_selections = Vec::with_capacity(selections.len());
8540 {
8541 let max_point = buffer.max_point();
8542 let mut is_first = true;
8543 for selection in selections.iter() {
8544 let mut start = selection.start;
8545 let mut end = selection.end;
8546 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8547 if is_entire_line {
8548 start = Point::new(start.row, 0);
8549 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8550 }
8551 if is_first {
8552 is_first = false;
8553 } else {
8554 text += "\n";
8555 }
8556 let mut len = 0;
8557 for chunk in buffer.text_for_range(start..end) {
8558 text.push_str(chunk);
8559 len += chunk.len();
8560 }
8561 clipboard_selections.push(ClipboardSelection {
8562 len,
8563 is_entire_line,
8564 start_column: start.column,
8565 });
8566 }
8567 }
8568
8569 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8570 text,
8571 clipboard_selections,
8572 ));
8573 }
8574
8575 pub fn do_paste(
8576 &mut self,
8577 text: &String,
8578 clipboard_selections: Option<Vec<ClipboardSelection>>,
8579 handle_entire_lines: bool,
8580 window: &mut Window,
8581 cx: &mut Context<Self>,
8582 ) {
8583 if self.read_only(cx) {
8584 return;
8585 }
8586
8587 let clipboard_text = Cow::Borrowed(text);
8588
8589 self.transact(window, cx, |this, window, cx| {
8590 if let Some(mut clipboard_selections) = clipboard_selections {
8591 let old_selections = this.selections.all::<usize>(cx);
8592 let all_selections_were_entire_line =
8593 clipboard_selections.iter().all(|s| s.is_entire_line);
8594 let first_selection_start_column =
8595 clipboard_selections.first().map(|s| s.start_column);
8596 if clipboard_selections.len() != old_selections.len() {
8597 clipboard_selections.drain(..);
8598 }
8599 let cursor_offset = this.selections.last::<usize>(cx).head();
8600 let mut auto_indent_on_paste = true;
8601
8602 this.buffer.update(cx, |buffer, cx| {
8603 let snapshot = buffer.read(cx);
8604 auto_indent_on_paste =
8605 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8606
8607 let mut start_offset = 0;
8608 let mut edits = Vec::new();
8609 let mut original_start_columns = Vec::new();
8610 for (ix, selection) in old_selections.iter().enumerate() {
8611 let to_insert;
8612 let entire_line;
8613 let original_start_column;
8614 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8615 let end_offset = start_offset + clipboard_selection.len;
8616 to_insert = &clipboard_text[start_offset..end_offset];
8617 entire_line = clipboard_selection.is_entire_line;
8618 start_offset = end_offset + 1;
8619 original_start_column = Some(clipboard_selection.start_column);
8620 } else {
8621 to_insert = clipboard_text.as_str();
8622 entire_line = all_selections_were_entire_line;
8623 original_start_column = first_selection_start_column
8624 }
8625
8626 // If the corresponding selection was empty when this slice of the
8627 // clipboard text was written, then the entire line containing the
8628 // selection was copied. If this selection is also currently empty,
8629 // then paste the line before the current line of the buffer.
8630 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8631 let column = selection.start.to_point(&snapshot).column as usize;
8632 let line_start = selection.start - column;
8633 line_start..line_start
8634 } else {
8635 selection.range()
8636 };
8637
8638 edits.push((range, to_insert));
8639 original_start_columns.extend(original_start_column);
8640 }
8641 drop(snapshot);
8642
8643 buffer.edit(
8644 edits,
8645 if auto_indent_on_paste {
8646 Some(AutoindentMode::Block {
8647 original_start_columns,
8648 })
8649 } else {
8650 None
8651 },
8652 cx,
8653 );
8654 });
8655
8656 let selections = this.selections.all::<usize>(cx);
8657 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8658 s.select(selections)
8659 });
8660 } else {
8661 this.insert(&clipboard_text, window, cx);
8662 }
8663 });
8664 }
8665
8666 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8667 if let Some(item) = cx.read_from_clipboard() {
8668 let entries = item.entries();
8669
8670 match entries.first() {
8671 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8672 // of all the pasted entries.
8673 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8674 .do_paste(
8675 clipboard_string.text(),
8676 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8677 true,
8678 window,
8679 cx,
8680 ),
8681 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8682 }
8683 }
8684 }
8685
8686 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8687 if self.read_only(cx) {
8688 return;
8689 }
8690
8691 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8692 if let Some((selections, _)) =
8693 self.selection_history.transaction(transaction_id).cloned()
8694 {
8695 self.change_selections(None, window, cx, |s| {
8696 s.select_anchors(selections.to_vec());
8697 });
8698 }
8699 self.request_autoscroll(Autoscroll::fit(), cx);
8700 self.unmark_text(window, cx);
8701 self.refresh_inline_completion(true, false, window, cx);
8702 cx.emit(EditorEvent::Edited { transaction_id });
8703 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8704 }
8705 }
8706
8707 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8708 if self.read_only(cx) {
8709 return;
8710 }
8711
8712 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8713 if let Some((_, Some(selections))) =
8714 self.selection_history.transaction(transaction_id).cloned()
8715 {
8716 self.change_selections(None, window, cx, |s| {
8717 s.select_anchors(selections.to_vec());
8718 });
8719 }
8720 self.request_autoscroll(Autoscroll::fit(), cx);
8721 self.unmark_text(window, cx);
8722 self.refresh_inline_completion(true, false, window, cx);
8723 cx.emit(EditorEvent::Edited { transaction_id });
8724 }
8725 }
8726
8727 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8728 self.buffer
8729 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8730 }
8731
8732 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8733 self.buffer
8734 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8735 }
8736
8737 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8738 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8739 let line_mode = s.line_mode;
8740 s.move_with(|map, selection| {
8741 let cursor = if selection.is_empty() && !line_mode {
8742 movement::left(map, selection.start)
8743 } else {
8744 selection.start
8745 };
8746 selection.collapse_to(cursor, SelectionGoal::None);
8747 });
8748 })
8749 }
8750
8751 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8752 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8753 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8754 })
8755 }
8756
8757 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8758 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8759 let line_mode = s.line_mode;
8760 s.move_with(|map, selection| {
8761 let cursor = if selection.is_empty() && !line_mode {
8762 movement::right(map, selection.end)
8763 } else {
8764 selection.end
8765 };
8766 selection.collapse_to(cursor, SelectionGoal::None)
8767 });
8768 })
8769 }
8770
8771 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8773 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8774 })
8775 }
8776
8777 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8778 if self.take_rename(true, window, cx).is_some() {
8779 return;
8780 }
8781
8782 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8783 cx.propagate();
8784 return;
8785 }
8786
8787 let text_layout_details = &self.text_layout_details(window);
8788 let selection_count = self.selections.count();
8789 let first_selection = self.selections.first_anchor();
8790
8791 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8792 let line_mode = s.line_mode;
8793 s.move_with(|map, selection| {
8794 if !selection.is_empty() && !line_mode {
8795 selection.goal = SelectionGoal::None;
8796 }
8797 let (cursor, goal) = movement::up(
8798 map,
8799 selection.start,
8800 selection.goal,
8801 false,
8802 text_layout_details,
8803 );
8804 selection.collapse_to(cursor, goal);
8805 });
8806 });
8807
8808 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8809 {
8810 cx.propagate();
8811 }
8812 }
8813
8814 pub fn move_up_by_lines(
8815 &mut self,
8816 action: &MoveUpByLines,
8817 window: &mut Window,
8818 cx: &mut Context<Self>,
8819 ) {
8820 if self.take_rename(true, window, cx).is_some() {
8821 return;
8822 }
8823
8824 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8825 cx.propagate();
8826 return;
8827 }
8828
8829 let text_layout_details = &self.text_layout_details(window);
8830
8831 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8832 let line_mode = s.line_mode;
8833 s.move_with(|map, selection| {
8834 if !selection.is_empty() && !line_mode {
8835 selection.goal = SelectionGoal::None;
8836 }
8837 let (cursor, goal) = movement::up_by_rows(
8838 map,
8839 selection.start,
8840 action.lines,
8841 selection.goal,
8842 false,
8843 text_layout_details,
8844 );
8845 selection.collapse_to(cursor, goal);
8846 });
8847 })
8848 }
8849
8850 pub fn move_down_by_lines(
8851 &mut self,
8852 action: &MoveDownByLines,
8853 window: &mut Window,
8854 cx: &mut Context<Self>,
8855 ) {
8856 if self.take_rename(true, window, cx).is_some() {
8857 return;
8858 }
8859
8860 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8861 cx.propagate();
8862 return;
8863 }
8864
8865 let text_layout_details = &self.text_layout_details(window);
8866
8867 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8868 let line_mode = s.line_mode;
8869 s.move_with(|map, selection| {
8870 if !selection.is_empty() && !line_mode {
8871 selection.goal = SelectionGoal::None;
8872 }
8873 let (cursor, goal) = movement::down_by_rows(
8874 map,
8875 selection.start,
8876 action.lines,
8877 selection.goal,
8878 false,
8879 text_layout_details,
8880 );
8881 selection.collapse_to(cursor, goal);
8882 });
8883 })
8884 }
8885
8886 pub fn select_down_by_lines(
8887 &mut self,
8888 action: &SelectDownByLines,
8889 window: &mut Window,
8890 cx: &mut Context<Self>,
8891 ) {
8892 let text_layout_details = &self.text_layout_details(window);
8893 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8894 s.move_heads_with(|map, head, goal| {
8895 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8896 })
8897 })
8898 }
8899
8900 pub fn select_up_by_lines(
8901 &mut self,
8902 action: &SelectUpByLines,
8903 window: &mut Window,
8904 cx: &mut Context<Self>,
8905 ) {
8906 let text_layout_details = &self.text_layout_details(window);
8907 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8908 s.move_heads_with(|map, head, goal| {
8909 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8910 })
8911 })
8912 }
8913
8914 pub fn select_page_up(
8915 &mut self,
8916 _: &SelectPageUp,
8917 window: &mut Window,
8918 cx: &mut Context<Self>,
8919 ) {
8920 let Some(row_count) = self.visible_row_count() else {
8921 return;
8922 };
8923
8924 let text_layout_details = &self.text_layout_details(window);
8925
8926 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8927 s.move_heads_with(|map, head, goal| {
8928 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8929 })
8930 })
8931 }
8932
8933 pub fn move_page_up(
8934 &mut self,
8935 action: &MovePageUp,
8936 window: &mut Window,
8937 cx: &mut Context<Self>,
8938 ) {
8939 if self.take_rename(true, window, cx).is_some() {
8940 return;
8941 }
8942
8943 if self
8944 .context_menu
8945 .borrow_mut()
8946 .as_mut()
8947 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8948 .unwrap_or(false)
8949 {
8950 return;
8951 }
8952
8953 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8954 cx.propagate();
8955 return;
8956 }
8957
8958 let Some(row_count) = self.visible_row_count() else {
8959 return;
8960 };
8961
8962 let autoscroll = if action.center_cursor {
8963 Autoscroll::center()
8964 } else {
8965 Autoscroll::fit()
8966 };
8967
8968 let text_layout_details = &self.text_layout_details(window);
8969
8970 self.change_selections(Some(autoscroll), window, cx, |s| {
8971 let line_mode = s.line_mode;
8972 s.move_with(|map, selection| {
8973 if !selection.is_empty() && !line_mode {
8974 selection.goal = SelectionGoal::None;
8975 }
8976 let (cursor, goal) = movement::up_by_rows(
8977 map,
8978 selection.end,
8979 row_count,
8980 selection.goal,
8981 false,
8982 text_layout_details,
8983 );
8984 selection.collapse_to(cursor, goal);
8985 });
8986 });
8987 }
8988
8989 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8990 let text_layout_details = &self.text_layout_details(window);
8991 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8992 s.move_heads_with(|map, head, goal| {
8993 movement::up(map, head, goal, false, text_layout_details)
8994 })
8995 })
8996 }
8997
8998 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8999 self.take_rename(true, window, cx);
9000
9001 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9002 cx.propagate();
9003 return;
9004 }
9005
9006 let text_layout_details = &self.text_layout_details(window);
9007 let selection_count = self.selections.count();
9008 let first_selection = self.selections.first_anchor();
9009
9010 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9011 let line_mode = s.line_mode;
9012 s.move_with(|map, selection| {
9013 if !selection.is_empty() && !line_mode {
9014 selection.goal = SelectionGoal::None;
9015 }
9016 let (cursor, goal) = movement::down(
9017 map,
9018 selection.end,
9019 selection.goal,
9020 false,
9021 text_layout_details,
9022 );
9023 selection.collapse_to(cursor, goal);
9024 });
9025 });
9026
9027 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9028 {
9029 cx.propagate();
9030 }
9031 }
9032
9033 pub fn select_page_down(
9034 &mut self,
9035 _: &SelectPageDown,
9036 window: &mut Window,
9037 cx: &mut Context<Self>,
9038 ) {
9039 let Some(row_count) = self.visible_row_count() else {
9040 return;
9041 };
9042
9043 let text_layout_details = &self.text_layout_details(window);
9044
9045 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9046 s.move_heads_with(|map, head, goal| {
9047 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9048 })
9049 })
9050 }
9051
9052 pub fn move_page_down(
9053 &mut self,
9054 action: &MovePageDown,
9055 window: &mut Window,
9056 cx: &mut Context<Self>,
9057 ) {
9058 if self.take_rename(true, window, cx).is_some() {
9059 return;
9060 }
9061
9062 if self
9063 .context_menu
9064 .borrow_mut()
9065 .as_mut()
9066 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9067 .unwrap_or(false)
9068 {
9069 return;
9070 }
9071
9072 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9073 cx.propagate();
9074 return;
9075 }
9076
9077 let Some(row_count) = self.visible_row_count() else {
9078 return;
9079 };
9080
9081 let autoscroll = if action.center_cursor {
9082 Autoscroll::center()
9083 } else {
9084 Autoscroll::fit()
9085 };
9086
9087 let text_layout_details = &self.text_layout_details(window);
9088 self.change_selections(Some(autoscroll), window, cx, |s| {
9089 let line_mode = s.line_mode;
9090 s.move_with(|map, selection| {
9091 if !selection.is_empty() && !line_mode {
9092 selection.goal = SelectionGoal::None;
9093 }
9094 let (cursor, goal) = movement::down_by_rows(
9095 map,
9096 selection.end,
9097 row_count,
9098 selection.goal,
9099 false,
9100 text_layout_details,
9101 );
9102 selection.collapse_to(cursor, goal);
9103 });
9104 });
9105 }
9106
9107 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9108 let text_layout_details = &self.text_layout_details(window);
9109 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9110 s.move_heads_with(|map, head, goal| {
9111 movement::down(map, head, goal, false, text_layout_details)
9112 })
9113 });
9114 }
9115
9116 pub fn context_menu_first(
9117 &mut self,
9118 _: &ContextMenuFirst,
9119 _window: &mut Window,
9120 cx: &mut Context<Self>,
9121 ) {
9122 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9123 context_menu.select_first(self.completion_provider.as_deref(), cx);
9124 }
9125 }
9126
9127 pub fn context_menu_prev(
9128 &mut self,
9129 _: &ContextMenuPrev,
9130 _window: &mut Window,
9131 cx: &mut Context<Self>,
9132 ) {
9133 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9134 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9135 }
9136 }
9137
9138 pub fn context_menu_next(
9139 &mut self,
9140 _: &ContextMenuNext,
9141 _window: &mut Window,
9142 cx: &mut Context<Self>,
9143 ) {
9144 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9145 context_menu.select_next(self.completion_provider.as_deref(), cx);
9146 }
9147 }
9148
9149 pub fn context_menu_last(
9150 &mut self,
9151 _: &ContextMenuLast,
9152 _window: &mut Window,
9153 cx: &mut Context<Self>,
9154 ) {
9155 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9156 context_menu.select_last(self.completion_provider.as_deref(), cx);
9157 }
9158 }
9159
9160 pub fn move_to_previous_word_start(
9161 &mut self,
9162 _: &MoveToPreviousWordStart,
9163 window: &mut Window,
9164 cx: &mut Context<Self>,
9165 ) {
9166 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9167 s.move_cursors_with(|map, head, _| {
9168 (
9169 movement::previous_word_start(map, head),
9170 SelectionGoal::None,
9171 )
9172 });
9173 })
9174 }
9175
9176 pub fn move_to_previous_subword_start(
9177 &mut self,
9178 _: &MoveToPreviousSubwordStart,
9179 window: &mut Window,
9180 cx: &mut Context<Self>,
9181 ) {
9182 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9183 s.move_cursors_with(|map, head, _| {
9184 (
9185 movement::previous_subword_start(map, head),
9186 SelectionGoal::None,
9187 )
9188 });
9189 })
9190 }
9191
9192 pub fn select_to_previous_word_start(
9193 &mut self,
9194 _: &SelectToPreviousWordStart,
9195 window: &mut Window,
9196 cx: &mut Context<Self>,
9197 ) {
9198 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9199 s.move_heads_with(|map, head, _| {
9200 (
9201 movement::previous_word_start(map, head),
9202 SelectionGoal::None,
9203 )
9204 });
9205 })
9206 }
9207
9208 pub fn select_to_previous_subword_start(
9209 &mut self,
9210 _: &SelectToPreviousSubwordStart,
9211 window: &mut Window,
9212 cx: &mut Context<Self>,
9213 ) {
9214 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9215 s.move_heads_with(|map, head, _| {
9216 (
9217 movement::previous_subword_start(map, head),
9218 SelectionGoal::None,
9219 )
9220 });
9221 })
9222 }
9223
9224 pub fn delete_to_previous_word_start(
9225 &mut self,
9226 action: &DeleteToPreviousWordStart,
9227 window: &mut Window,
9228 cx: &mut Context<Self>,
9229 ) {
9230 self.transact(window, cx, |this, window, cx| {
9231 this.select_autoclose_pair(window, cx);
9232 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9233 let line_mode = s.line_mode;
9234 s.move_with(|map, selection| {
9235 if selection.is_empty() && !line_mode {
9236 let cursor = if action.ignore_newlines {
9237 movement::previous_word_start(map, selection.head())
9238 } else {
9239 movement::previous_word_start_or_newline(map, selection.head())
9240 };
9241 selection.set_head(cursor, SelectionGoal::None);
9242 }
9243 });
9244 });
9245 this.insert("", window, cx);
9246 });
9247 }
9248
9249 pub fn delete_to_previous_subword_start(
9250 &mut self,
9251 _: &DeleteToPreviousSubwordStart,
9252 window: &mut Window,
9253 cx: &mut Context<Self>,
9254 ) {
9255 self.transact(window, cx, |this, window, cx| {
9256 this.select_autoclose_pair(window, cx);
9257 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9258 let line_mode = s.line_mode;
9259 s.move_with(|map, selection| {
9260 if selection.is_empty() && !line_mode {
9261 let cursor = movement::previous_subword_start(map, selection.head());
9262 selection.set_head(cursor, SelectionGoal::None);
9263 }
9264 });
9265 });
9266 this.insert("", window, cx);
9267 });
9268 }
9269
9270 pub fn move_to_next_word_end(
9271 &mut self,
9272 _: &MoveToNextWordEnd,
9273 window: &mut Window,
9274 cx: &mut Context<Self>,
9275 ) {
9276 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9277 s.move_cursors_with(|map, head, _| {
9278 (movement::next_word_end(map, head), SelectionGoal::None)
9279 });
9280 })
9281 }
9282
9283 pub fn move_to_next_subword_end(
9284 &mut self,
9285 _: &MoveToNextSubwordEnd,
9286 window: &mut Window,
9287 cx: &mut Context<Self>,
9288 ) {
9289 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9290 s.move_cursors_with(|map, head, _| {
9291 (movement::next_subword_end(map, head), SelectionGoal::None)
9292 });
9293 })
9294 }
9295
9296 pub fn select_to_next_word_end(
9297 &mut self,
9298 _: &SelectToNextWordEnd,
9299 window: &mut Window,
9300 cx: &mut Context<Self>,
9301 ) {
9302 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9303 s.move_heads_with(|map, head, _| {
9304 (movement::next_word_end(map, head), SelectionGoal::None)
9305 });
9306 })
9307 }
9308
9309 pub fn select_to_next_subword_end(
9310 &mut self,
9311 _: &SelectToNextSubwordEnd,
9312 window: &mut Window,
9313 cx: &mut Context<Self>,
9314 ) {
9315 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9316 s.move_heads_with(|map, head, _| {
9317 (movement::next_subword_end(map, head), SelectionGoal::None)
9318 });
9319 })
9320 }
9321
9322 pub fn delete_to_next_word_end(
9323 &mut self,
9324 action: &DeleteToNextWordEnd,
9325 window: &mut Window,
9326 cx: &mut Context<Self>,
9327 ) {
9328 self.transact(window, cx, |this, window, cx| {
9329 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9330 let line_mode = s.line_mode;
9331 s.move_with(|map, selection| {
9332 if selection.is_empty() && !line_mode {
9333 let cursor = if action.ignore_newlines {
9334 movement::next_word_end(map, selection.head())
9335 } else {
9336 movement::next_word_end_or_newline(map, selection.head())
9337 };
9338 selection.set_head(cursor, SelectionGoal::None);
9339 }
9340 });
9341 });
9342 this.insert("", window, cx);
9343 });
9344 }
9345
9346 pub fn delete_to_next_subword_end(
9347 &mut self,
9348 _: &DeleteToNextSubwordEnd,
9349 window: &mut Window,
9350 cx: &mut Context<Self>,
9351 ) {
9352 self.transact(window, cx, |this, window, cx| {
9353 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9354 s.move_with(|map, selection| {
9355 if selection.is_empty() {
9356 let cursor = movement::next_subword_end(map, selection.head());
9357 selection.set_head(cursor, SelectionGoal::None);
9358 }
9359 });
9360 });
9361 this.insert("", window, cx);
9362 });
9363 }
9364
9365 pub fn move_to_beginning_of_line(
9366 &mut self,
9367 action: &MoveToBeginningOfLine,
9368 window: &mut Window,
9369 cx: &mut Context<Self>,
9370 ) {
9371 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9372 s.move_cursors_with(|map, head, _| {
9373 (
9374 movement::indented_line_beginning(
9375 map,
9376 head,
9377 action.stop_at_soft_wraps,
9378 action.stop_at_indent,
9379 ),
9380 SelectionGoal::None,
9381 )
9382 });
9383 })
9384 }
9385
9386 pub fn select_to_beginning_of_line(
9387 &mut self,
9388 action: &SelectToBeginningOfLine,
9389 window: &mut Window,
9390 cx: &mut Context<Self>,
9391 ) {
9392 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9393 s.move_heads_with(|map, head, _| {
9394 (
9395 movement::indented_line_beginning(
9396 map,
9397 head,
9398 action.stop_at_soft_wraps,
9399 action.stop_at_indent,
9400 ),
9401 SelectionGoal::None,
9402 )
9403 });
9404 });
9405 }
9406
9407 pub fn delete_to_beginning_of_line(
9408 &mut self,
9409 _: &DeleteToBeginningOfLine,
9410 window: &mut Window,
9411 cx: &mut Context<Self>,
9412 ) {
9413 self.transact(window, cx, |this, window, cx| {
9414 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9415 s.move_with(|_, selection| {
9416 selection.reversed = true;
9417 });
9418 });
9419
9420 this.select_to_beginning_of_line(
9421 &SelectToBeginningOfLine {
9422 stop_at_soft_wraps: false,
9423 stop_at_indent: false,
9424 },
9425 window,
9426 cx,
9427 );
9428 this.backspace(&Backspace, window, cx);
9429 });
9430 }
9431
9432 pub fn move_to_end_of_line(
9433 &mut self,
9434 action: &MoveToEndOfLine,
9435 window: &mut Window,
9436 cx: &mut Context<Self>,
9437 ) {
9438 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9439 s.move_cursors_with(|map, head, _| {
9440 (
9441 movement::line_end(map, head, action.stop_at_soft_wraps),
9442 SelectionGoal::None,
9443 )
9444 });
9445 })
9446 }
9447
9448 pub fn select_to_end_of_line(
9449 &mut self,
9450 action: &SelectToEndOfLine,
9451 window: &mut Window,
9452 cx: &mut Context<Self>,
9453 ) {
9454 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9455 s.move_heads_with(|map, head, _| {
9456 (
9457 movement::line_end(map, head, action.stop_at_soft_wraps),
9458 SelectionGoal::None,
9459 )
9460 });
9461 })
9462 }
9463
9464 pub fn delete_to_end_of_line(
9465 &mut self,
9466 _: &DeleteToEndOfLine,
9467 window: &mut Window,
9468 cx: &mut Context<Self>,
9469 ) {
9470 self.transact(window, cx, |this, window, cx| {
9471 this.select_to_end_of_line(
9472 &SelectToEndOfLine {
9473 stop_at_soft_wraps: false,
9474 },
9475 window,
9476 cx,
9477 );
9478 this.delete(&Delete, window, cx);
9479 });
9480 }
9481
9482 pub fn cut_to_end_of_line(
9483 &mut self,
9484 _: &CutToEndOfLine,
9485 window: &mut Window,
9486 cx: &mut Context<Self>,
9487 ) {
9488 self.transact(window, cx, |this, window, cx| {
9489 this.select_to_end_of_line(
9490 &SelectToEndOfLine {
9491 stop_at_soft_wraps: false,
9492 },
9493 window,
9494 cx,
9495 );
9496 this.cut(&Cut, window, cx);
9497 });
9498 }
9499
9500 pub fn move_to_start_of_paragraph(
9501 &mut self,
9502 _: &MoveToStartOfParagraph,
9503 window: &mut Window,
9504 cx: &mut Context<Self>,
9505 ) {
9506 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9507 cx.propagate();
9508 return;
9509 }
9510
9511 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9512 s.move_with(|map, selection| {
9513 selection.collapse_to(
9514 movement::start_of_paragraph(map, selection.head(), 1),
9515 SelectionGoal::None,
9516 )
9517 });
9518 })
9519 }
9520
9521 pub fn move_to_end_of_paragraph(
9522 &mut self,
9523 _: &MoveToEndOfParagraph,
9524 window: &mut Window,
9525 cx: &mut Context<Self>,
9526 ) {
9527 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9528 cx.propagate();
9529 return;
9530 }
9531
9532 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9533 s.move_with(|map, selection| {
9534 selection.collapse_to(
9535 movement::end_of_paragraph(map, selection.head(), 1),
9536 SelectionGoal::None,
9537 )
9538 });
9539 })
9540 }
9541
9542 pub fn select_to_start_of_paragraph(
9543 &mut self,
9544 _: &SelectToStartOfParagraph,
9545 window: &mut Window,
9546 cx: &mut Context<Self>,
9547 ) {
9548 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9549 cx.propagate();
9550 return;
9551 }
9552
9553 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9554 s.move_heads_with(|map, head, _| {
9555 (
9556 movement::start_of_paragraph(map, head, 1),
9557 SelectionGoal::None,
9558 )
9559 });
9560 })
9561 }
9562
9563 pub fn select_to_end_of_paragraph(
9564 &mut self,
9565 _: &SelectToEndOfParagraph,
9566 window: &mut Window,
9567 cx: &mut Context<Self>,
9568 ) {
9569 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9570 cx.propagate();
9571 return;
9572 }
9573
9574 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9575 s.move_heads_with(|map, head, _| {
9576 (
9577 movement::end_of_paragraph(map, head, 1),
9578 SelectionGoal::None,
9579 )
9580 });
9581 })
9582 }
9583
9584 pub fn move_to_start_of_excerpt(
9585 &mut self,
9586 _: &MoveToStartOfExcerpt,
9587 window: &mut Window,
9588 cx: &mut Context<Self>,
9589 ) {
9590 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9591 cx.propagate();
9592 return;
9593 }
9594
9595 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9596 s.move_with(|map, selection| {
9597 selection.collapse_to(
9598 movement::start_of_excerpt(
9599 map,
9600 selection.head(),
9601 workspace::searchable::Direction::Prev,
9602 ),
9603 SelectionGoal::None,
9604 )
9605 });
9606 })
9607 }
9608
9609 pub fn move_to_end_of_excerpt(
9610 &mut self,
9611 _: &MoveToEndOfExcerpt,
9612 window: &mut Window,
9613 cx: &mut Context<Self>,
9614 ) {
9615 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9616 cx.propagate();
9617 return;
9618 }
9619
9620 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9621 s.move_with(|map, selection| {
9622 selection.collapse_to(
9623 movement::end_of_excerpt(
9624 map,
9625 selection.head(),
9626 workspace::searchable::Direction::Next,
9627 ),
9628 SelectionGoal::None,
9629 )
9630 });
9631 })
9632 }
9633
9634 pub fn select_to_start_of_excerpt(
9635 &mut self,
9636 _: &SelectToStartOfExcerpt,
9637 window: &mut Window,
9638 cx: &mut Context<Self>,
9639 ) {
9640 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9641 cx.propagate();
9642 return;
9643 }
9644
9645 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9646 s.move_heads_with(|map, head, _| {
9647 (
9648 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9649 SelectionGoal::None,
9650 )
9651 });
9652 })
9653 }
9654
9655 pub fn select_to_end_of_excerpt(
9656 &mut self,
9657 _: &SelectToEndOfExcerpt,
9658 window: &mut Window,
9659 cx: &mut Context<Self>,
9660 ) {
9661 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9662 cx.propagate();
9663 return;
9664 }
9665
9666 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9667 s.move_heads_with(|map, head, _| {
9668 (
9669 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9670 SelectionGoal::None,
9671 )
9672 });
9673 })
9674 }
9675
9676 pub fn move_to_beginning(
9677 &mut self,
9678 _: &MoveToBeginning,
9679 window: &mut Window,
9680 cx: &mut Context<Self>,
9681 ) {
9682 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9683 cx.propagate();
9684 return;
9685 }
9686
9687 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9688 s.select_ranges(vec![0..0]);
9689 });
9690 }
9691
9692 pub fn select_to_beginning(
9693 &mut self,
9694 _: &SelectToBeginning,
9695 window: &mut Window,
9696 cx: &mut Context<Self>,
9697 ) {
9698 let mut selection = self.selections.last::<Point>(cx);
9699 selection.set_head(Point::zero(), SelectionGoal::None);
9700
9701 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9702 s.select(vec![selection]);
9703 });
9704 }
9705
9706 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9707 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9708 cx.propagate();
9709 return;
9710 }
9711
9712 let cursor = self.buffer.read(cx).read(cx).len();
9713 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9714 s.select_ranges(vec![cursor..cursor])
9715 });
9716 }
9717
9718 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9719 self.nav_history = nav_history;
9720 }
9721
9722 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9723 self.nav_history.as_ref()
9724 }
9725
9726 fn push_to_nav_history(
9727 &mut self,
9728 cursor_anchor: Anchor,
9729 new_position: Option<Point>,
9730 cx: &mut Context<Self>,
9731 ) {
9732 if let Some(nav_history) = self.nav_history.as_mut() {
9733 let buffer = self.buffer.read(cx).read(cx);
9734 let cursor_position = cursor_anchor.to_point(&buffer);
9735 let scroll_state = self.scroll_manager.anchor();
9736 let scroll_top_row = scroll_state.top_row(&buffer);
9737 drop(buffer);
9738
9739 if let Some(new_position) = new_position {
9740 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9741 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9742 return;
9743 }
9744 }
9745
9746 nav_history.push(
9747 Some(NavigationData {
9748 cursor_anchor,
9749 cursor_position,
9750 scroll_anchor: scroll_state,
9751 scroll_top_row,
9752 }),
9753 cx,
9754 );
9755 }
9756 }
9757
9758 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9759 let buffer = self.buffer.read(cx).snapshot(cx);
9760 let mut selection = self.selections.first::<usize>(cx);
9761 selection.set_head(buffer.len(), SelectionGoal::None);
9762 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9763 s.select(vec![selection]);
9764 });
9765 }
9766
9767 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9768 let end = self.buffer.read(cx).read(cx).len();
9769 self.change_selections(None, window, cx, |s| {
9770 s.select_ranges(vec![0..end]);
9771 });
9772 }
9773
9774 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9775 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9776 let mut selections = self.selections.all::<Point>(cx);
9777 let max_point = display_map.buffer_snapshot.max_point();
9778 for selection in &mut selections {
9779 let rows = selection.spanned_rows(true, &display_map);
9780 selection.start = Point::new(rows.start.0, 0);
9781 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9782 selection.reversed = false;
9783 }
9784 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9785 s.select(selections);
9786 });
9787 }
9788
9789 pub fn split_selection_into_lines(
9790 &mut self,
9791 _: &SplitSelectionIntoLines,
9792 window: &mut Window,
9793 cx: &mut Context<Self>,
9794 ) {
9795 let selections = self
9796 .selections
9797 .all::<Point>(cx)
9798 .into_iter()
9799 .map(|selection| selection.start..selection.end)
9800 .collect::<Vec<_>>();
9801 self.unfold_ranges(&selections, true, true, cx);
9802
9803 let mut new_selection_ranges = Vec::new();
9804 {
9805 let buffer = self.buffer.read(cx).read(cx);
9806 for selection in selections {
9807 for row in selection.start.row..selection.end.row {
9808 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9809 new_selection_ranges.push(cursor..cursor);
9810 }
9811
9812 let is_multiline_selection = selection.start.row != selection.end.row;
9813 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9814 // so this action feels more ergonomic when paired with other selection operations
9815 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9816 if !should_skip_last {
9817 new_selection_ranges.push(selection.end..selection.end);
9818 }
9819 }
9820 }
9821 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9822 s.select_ranges(new_selection_ranges);
9823 });
9824 }
9825
9826 pub fn add_selection_above(
9827 &mut self,
9828 _: &AddSelectionAbove,
9829 window: &mut Window,
9830 cx: &mut Context<Self>,
9831 ) {
9832 self.add_selection(true, window, cx);
9833 }
9834
9835 pub fn add_selection_below(
9836 &mut self,
9837 _: &AddSelectionBelow,
9838 window: &mut Window,
9839 cx: &mut Context<Self>,
9840 ) {
9841 self.add_selection(false, window, cx);
9842 }
9843
9844 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9845 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9846 let mut selections = self.selections.all::<Point>(cx);
9847 let text_layout_details = self.text_layout_details(window);
9848 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9849 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9850 let range = oldest_selection.display_range(&display_map).sorted();
9851
9852 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9853 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9854 let positions = start_x.min(end_x)..start_x.max(end_x);
9855
9856 selections.clear();
9857 let mut stack = Vec::new();
9858 for row in range.start.row().0..=range.end.row().0 {
9859 if let Some(selection) = self.selections.build_columnar_selection(
9860 &display_map,
9861 DisplayRow(row),
9862 &positions,
9863 oldest_selection.reversed,
9864 &text_layout_details,
9865 ) {
9866 stack.push(selection.id);
9867 selections.push(selection);
9868 }
9869 }
9870
9871 if above {
9872 stack.reverse();
9873 }
9874
9875 AddSelectionsState { above, stack }
9876 });
9877
9878 let last_added_selection = *state.stack.last().unwrap();
9879 let mut new_selections = Vec::new();
9880 if above == state.above {
9881 let end_row = if above {
9882 DisplayRow(0)
9883 } else {
9884 display_map.max_point().row()
9885 };
9886
9887 'outer: for selection in selections {
9888 if selection.id == last_added_selection {
9889 let range = selection.display_range(&display_map).sorted();
9890 debug_assert_eq!(range.start.row(), range.end.row());
9891 let mut row = range.start.row();
9892 let positions =
9893 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9894 px(start)..px(end)
9895 } else {
9896 let start_x =
9897 display_map.x_for_display_point(range.start, &text_layout_details);
9898 let end_x =
9899 display_map.x_for_display_point(range.end, &text_layout_details);
9900 start_x.min(end_x)..start_x.max(end_x)
9901 };
9902
9903 while row != end_row {
9904 if above {
9905 row.0 -= 1;
9906 } else {
9907 row.0 += 1;
9908 }
9909
9910 if let Some(new_selection) = self.selections.build_columnar_selection(
9911 &display_map,
9912 row,
9913 &positions,
9914 selection.reversed,
9915 &text_layout_details,
9916 ) {
9917 state.stack.push(new_selection.id);
9918 if above {
9919 new_selections.push(new_selection);
9920 new_selections.push(selection);
9921 } else {
9922 new_selections.push(selection);
9923 new_selections.push(new_selection);
9924 }
9925
9926 continue 'outer;
9927 }
9928 }
9929 }
9930
9931 new_selections.push(selection);
9932 }
9933 } else {
9934 new_selections = selections;
9935 new_selections.retain(|s| s.id != last_added_selection);
9936 state.stack.pop();
9937 }
9938
9939 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9940 s.select(new_selections);
9941 });
9942 if state.stack.len() > 1 {
9943 self.add_selections_state = Some(state);
9944 }
9945 }
9946
9947 pub fn select_next_match_internal(
9948 &mut self,
9949 display_map: &DisplaySnapshot,
9950 replace_newest: bool,
9951 autoscroll: Option<Autoscroll>,
9952 window: &mut Window,
9953 cx: &mut Context<Self>,
9954 ) -> Result<()> {
9955 fn select_next_match_ranges(
9956 this: &mut Editor,
9957 range: Range<usize>,
9958 replace_newest: bool,
9959 auto_scroll: Option<Autoscroll>,
9960 window: &mut Window,
9961 cx: &mut Context<Editor>,
9962 ) {
9963 this.unfold_ranges(&[range.clone()], false, true, cx);
9964 this.change_selections(auto_scroll, window, cx, |s| {
9965 if replace_newest {
9966 s.delete(s.newest_anchor().id);
9967 }
9968 s.insert_range(range.clone());
9969 });
9970 }
9971
9972 let buffer = &display_map.buffer_snapshot;
9973 let mut selections = self.selections.all::<usize>(cx);
9974 if let Some(mut select_next_state) = self.select_next_state.take() {
9975 let query = &select_next_state.query;
9976 if !select_next_state.done {
9977 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9978 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9979 let mut next_selected_range = None;
9980
9981 let bytes_after_last_selection =
9982 buffer.bytes_in_range(last_selection.end..buffer.len());
9983 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
9984 let query_matches = query
9985 .stream_find_iter(bytes_after_last_selection)
9986 .map(|result| (last_selection.end, result))
9987 .chain(
9988 query
9989 .stream_find_iter(bytes_before_first_selection)
9990 .map(|result| (0, result)),
9991 );
9992
9993 for (start_offset, query_match) in query_matches {
9994 let query_match = query_match.unwrap(); // can only fail due to I/O
9995 let offset_range =
9996 start_offset + query_match.start()..start_offset + query_match.end();
9997 let display_range = offset_range.start.to_display_point(display_map)
9998 ..offset_range.end.to_display_point(display_map);
9999
10000 if !select_next_state.wordwise
10001 || (!movement::is_inside_word(display_map, display_range.start)
10002 && !movement::is_inside_word(display_map, display_range.end))
10003 {
10004 // TODO: This is n^2, because we might check all the selections
10005 if !selections
10006 .iter()
10007 .any(|selection| selection.range().overlaps(&offset_range))
10008 {
10009 next_selected_range = Some(offset_range);
10010 break;
10011 }
10012 }
10013 }
10014
10015 if let Some(next_selected_range) = next_selected_range {
10016 select_next_match_ranges(
10017 self,
10018 next_selected_range,
10019 replace_newest,
10020 autoscroll,
10021 window,
10022 cx,
10023 );
10024 } else {
10025 select_next_state.done = true;
10026 }
10027 }
10028
10029 self.select_next_state = Some(select_next_state);
10030 } else {
10031 let mut only_carets = true;
10032 let mut same_text_selected = true;
10033 let mut selected_text = None;
10034
10035 let mut selections_iter = selections.iter().peekable();
10036 while let Some(selection) = selections_iter.next() {
10037 if selection.start != selection.end {
10038 only_carets = false;
10039 }
10040
10041 if same_text_selected {
10042 if selected_text.is_none() {
10043 selected_text =
10044 Some(buffer.text_for_range(selection.range()).collect::<String>());
10045 }
10046
10047 if let Some(next_selection) = selections_iter.peek() {
10048 if next_selection.range().len() == selection.range().len() {
10049 let next_selected_text = buffer
10050 .text_for_range(next_selection.range())
10051 .collect::<String>();
10052 if Some(next_selected_text) != selected_text {
10053 same_text_selected = false;
10054 selected_text = None;
10055 }
10056 } else {
10057 same_text_selected = false;
10058 selected_text = None;
10059 }
10060 }
10061 }
10062 }
10063
10064 if only_carets {
10065 for selection in &mut selections {
10066 let word_range = movement::surrounding_word(
10067 display_map,
10068 selection.start.to_display_point(display_map),
10069 );
10070 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10071 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10072 selection.goal = SelectionGoal::None;
10073 selection.reversed = false;
10074 select_next_match_ranges(
10075 self,
10076 selection.start..selection.end,
10077 replace_newest,
10078 autoscroll,
10079 window,
10080 cx,
10081 );
10082 }
10083
10084 if selections.len() == 1 {
10085 let selection = selections
10086 .last()
10087 .expect("ensured that there's only one selection");
10088 let query = buffer
10089 .text_for_range(selection.start..selection.end)
10090 .collect::<String>();
10091 let is_empty = query.is_empty();
10092 let select_state = SelectNextState {
10093 query: AhoCorasick::new(&[query])?,
10094 wordwise: true,
10095 done: is_empty,
10096 };
10097 self.select_next_state = Some(select_state);
10098 } else {
10099 self.select_next_state = None;
10100 }
10101 } else if let Some(selected_text) = selected_text {
10102 self.select_next_state = Some(SelectNextState {
10103 query: AhoCorasick::new(&[selected_text])?,
10104 wordwise: false,
10105 done: false,
10106 });
10107 self.select_next_match_internal(
10108 display_map,
10109 replace_newest,
10110 autoscroll,
10111 window,
10112 cx,
10113 )?;
10114 }
10115 }
10116 Ok(())
10117 }
10118
10119 pub fn select_all_matches(
10120 &mut self,
10121 _action: &SelectAllMatches,
10122 window: &mut Window,
10123 cx: &mut Context<Self>,
10124 ) -> Result<()> {
10125 self.push_to_selection_history();
10126 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10127
10128 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10129 let Some(select_next_state) = self.select_next_state.as_mut() else {
10130 return Ok(());
10131 };
10132 if select_next_state.done {
10133 return Ok(());
10134 }
10135
10136 let mut new_selections = self.selections.all::<usize>(cx);
10137
10138 let buffer = &display_map.buffer_snapshot;
10139 let query_matches = select_next_state
10140 .query
10141 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10142
10143 for query_match in query_matches {
10144 let query_match = query_match.unwrap(); // can only fail due to I/O
10145 let offset_range = query_match.start()..query_match.end();
10146 let display_range = offset_range.start.to_display_point(&display_map)
10147 ..offset_range.end.to_display_point(&display_map);
10148
10149 if !select_next_state.wordwise
10150 || (!movement::is_inside_word(&display_map, display_range.start)
10151 && !movement::is_inside_word(&display_map, display_range.end))
10152 {
10153 self.selections.change_with(cx, |selections| {
10154 new_selections.push(Selection {
10155 id: selections.new_selection_id(),
10156 start: offset_range.start,
10157 end: offset_range.end,
10158 reversed: false,
10159 goal: SelectionGoal::None,
10160 });
10161 });
10162 }
10163 }
10164
10165 new_selections.sort_by_key(|selection| selection.start);
10166 let mut ix = 0;
10167 while ix + 1 < new_selections.len() {
10168 let current_selection = &new_selections[ix];
10169 let next_selection = &new_selections[ix + 1];
10170 if current_selection.range().overlaps(&next_selection.range()) {
10171 if current_selection.id < next_selection.id {
10172 new_selections.remove(ix + 1);
10173 } else {
10174 new_selections.remove(ix);
10175 }
10176 } else {
10177 ix += 1;
10178 }
10179 }
10180
10181 let reversed = self.selections.oldest::<usize>(cx).reversed;
10182
10183 for selection in new_selections.iter_mut() {
10184 selection.reversed = reversed;
10185 }
10186
10187 select_next_state.done = true;
10188 self.unfold_ranges(
10189 &new_selections
10190 .iter()
10191 .map(|selection| selection.range())
10192 .collect::<Vec<_>>(),
10193 false,
10194 false,
10195 cx,
10196 );
10197 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10198 selections.select(new_selections)
10199 });
10200
10201 Ok(())
10202 }
10203
10204 pub fn select_next(
10205 &mut self,
10206 action: &SelectNext,
10207 window: &mut Window,
10208 cx: &mut Context<Self>,
10209 ) -> Result<()> {
10210 self.push_to_selection_history();
10211 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10212 self.select_next_match_internal(
10213 &display_map,
10214 action.replace_newest,
10215 Some(Autoscroll::newest()),
10216 window,
10217 cx,
10218 )?;
10219 Ok(())
10220 }
10221
10222 pub fn select_previous(
10223 &mut self,
10224 action: &SelectPrevious,
10225 window: &mut Window,
10226 cx: &mut Context<Self>,
10227 ) -> Result<()> {
10228 self.push_to_selection_history();
10229 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10230 let buffer = &display_map.buffer_snapshot;
10231 let mut selections = self.selections.all::<usize>(cx);
10232 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10233 let query = &select_prev_state.query;
10234 if !select_prev_state.done {
10235 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10236 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10237 let mut next_selected_range = None;
10238 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10239 let bytes_before_last_selection =
10240 buffer.reversed_bytes_in_range(0..last_selection.start);
10241 let bytes_after_first_selection =
10242 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10243 let query_matches = query
10244 .stream_find_iter(bytes_before_last_selection)
10245 .map(|result| (last_selection.start, result))
10246 .chain(
10247 query
10248 .stream_find_iter(bytes_after_first_selection)
10249 .map(|result| (buffer.len(), result)),
10250 );
10251 for (end_offset, query_match) in query_matches {
10252 let query_match = query_match.unwrap(); // can only fail due to I/O
10253 let offset_range =
10254 end_offset - query_match.end()..end_offset - query_match.start();
10255 let display_range = offset_range.start.to_display_point(&display_map)
10256 ..offset_range.end.to_display_point(&display_map);
10257
10258 if !select_prev_state.wordwise
10259 || (!movement::is_inside_word(&display_map, display_range.start)
10260 && !movement::is_inside_word(&display_map, display_range.end))
10261 {
10262 next_selected_range = Some(offset_range);
10263 break;
10264 }
10265 }
10266
10267 if let Some(next_selected_range) = next_selected_range {
10268 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10269 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10270 if action.replace_newest {
10271 s.delete(s.newest_anchor().id);
10272 }
10273 s.insert_range(next_selected_range);
10274 });
10275 } else {
10276 select_prev_state.done = true;
10277 }
10278 }
10279
10280 self.select_prev_state = Some(select_prev_state);
10281 } else {
10282 let mut only_carets = true;
10283 let mut same_text_selected = true;
10284 let mut selected_text = None;
10285
10286 let mut selections_iter = selections.iter().peekable();
10287 while let Some(selection) = selections_iter.next() {
10288 if selection.start != selection.end {
10289 only_carets = false;
10290 }
10291
10292 if same_text_selected {
10293 if selected_text.is_none() {
10294 selected_text =
10295 Some(buffer.text_for_range(selection.range()).collect::<String>());
10296 }
10297
10298 if let Some(next_selection) = selections_iter.peek() {
10299 if next_selection.range().len() == selection.range().len() {
10300 let next_selected_text = buffer
10301 .text_for_range(next_selection.range())
10302 .collect::<String>();
10303 if Some(next_selected_text) != selected_text {
10304 same_text_selected = false;
10305 selected_text = None;
10306 }
10307 } else {
10308 same_text_selected = false;
10309 selected_text = None;
10310 }
10311 }
10312 }
10313 }
10314
10315 if only_carets {
10316 for selection in &mut selections {
10317 let word_range = movement::surrounding_word(
10318 &display_map,
10319 selection.start.to_display_point(&display_map),
10320 );
10321 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10322 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10323 selection.goal = SelectionGoal::None;
10324 selection.reversed = false;
10325 }
10326 if selections.len() == 1 {
10327 let selection = selections
10328 .last()
10329 .expect("ensured that there's only one selection");
10330 let query = buffer
10331 .text_for_range(selection.start..selection.end)
10332 .collect::<String>();
10333 let is_empty = query.is_empty();
10334 let select_state = SelectNextState {
10335 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10336 wordwise: true,
10337 done: is_empty,
10338 };
10339 self.select_prev_state = Some(select_state);
10340 } else {
10341 self.select_prev_state = None;
10342 }
10343
10344 self.unfold_ranges(
10345 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10346 false,
10347 true,
10348 cx,
10349 );
10350 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10351 s.select(selections);
10352 });
10353 } else if let Some(selected_text) = selected_text {
10354 self.select_prev_state = Some(SelectNextState {
10355 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10356 wordwise: false,
10357 done: false,
10358 });
10359 self.select_previous(action, window, cx)?;
10360 }
10361 }
10362 Ok(())
10363 }
10364
10365 pub fn toggle_comments(
10366 &mut self,
10367 action: &ToggleComments,
10368 window: &mut Window,
10369 cx: &mut Context<Self>,
10370 ) {
10371 if self.read_only(cx) {
10372 return;
10373 }
10374 let text_layout_details = &self.text_layout_details(window);
10375 self.transact(window, cx, |this, window, cx| {
10376 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10377 let mut edits = Vec::new();
10378 let mut selection_edit_ranges = Vec::new();
10379 let mut last_toggled_row = None;
10380 let snapshot = this.buffer.read(cx).read(cx);
10381 let empty_str: Arc<str> = Arc::default();
10382 let mut suffixes_inserted = Vec::new();
10383 let ignore_indent = action.ignore_indent;
10384
10385 fn comment_prefix_range(
10386 snapshot: &MultiBufferSnapshot,
10387 row: MultiBufferRow,
10388 comment_prefix: &str,
10389 comment_prefix_whitespace: &str,
10390 ignore_indent: bool,
10391 ) -> Range<Point> {
10392 let indent_size = if ignore_indent {
10393 0
10394 } else {
10395 snapshot.indent_size_for_line(row).len
10396 };
10397
10398 let start = Point::new(row.0, indent_size);
10399
10400 let mut line_bytes = snapshot
10401 .bytes_in_range(start..snapshot.max_point())
10402 .flatten()
10403 .copied();
10404
10405 // If this line currently begins with the line comment prefix, then record
10406 // the range containing the prefix.
10407 if line_bytes
10408 .by_ref()
10409 .take(comment_prefix.len())
10410 .eq(comment_prefix.bytes())
10411 {
10412 // Include any whitespace that matches the comment prefix.
10413 let matching_whitespace_len = line_bytes
10414 .zip(comment_prefix_whitespace.bytes())
10415 .take_while(|(a, b)| a == b)
10416 .count() as u32;
10417 let end = Point::new(
10418 start.row,
10419 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10420 );
10421 start..end
10422 } else {
10423 start..start
10424 }
10425 }
10426
10427 fn comment_suffix_range(
10428 snapshot: &MultiBufferSnapshot,
10429 row: MultiBufferRow,
10430 comment_suffix: &str,
10431 comment_suffix_has_leading_space: bool,
10432 ) -> Range<Point> {
10433 let end = Point::new(row.0, snapshot.line_len(row));
10434 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10435
10436 let mut line_end_bytes = snapshot
10437 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10438 .flatten()
10439 .copied();
10440
10441 let leading_space_len = if suffix_start_column > 0
10442 && line_end_bytes.next() == Some(b' ')
10443 && comment_suffix_has_leading_space
10444 {
10445 1
10446 } else {
10447 0
10448 };
10449
10450 // If this line currently begins with the line comment prefix, then record
10451 // the range containing the prefix.
10452 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10453 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10454 start..end
10455 } else {
10456 end..end
10457 }
10458 }
10459
10460 // TODO: Handle selections that cross excerpts
10461 for selection in &mut selections {
10462 let start_column = snapshot
10463 .indent_size_for_line(MultiBufferRow(selection.start.row))
10464 .len;
10465 let language = if let Some(language) =
10466 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10467 {
10468 language
10469 } else {
10470 continue;
10471 };
10472
10473 selection_edit_ranges.clear();
10474
10475 // If multiple selections contain a given row, avoid processing that
10476 // row more than once.
10477 let mut start_row = MultiBufferRow(selection.start.row);
10478 if last_toggled_row == Some(start_row) {
10479 start_row = start_row.next_row();
10480 }
10481 let end_row =
10482 if selection.end.row > selection.start.row && selection.end.column == 0 {
10483 MultiBufferRow(selection.end.row - 1)
10484 } else {
10485 MultiBufferRow(selection.end.row)
10486 };
10487 last_toggled_row = Some(end_row);
10488
10489 if start_row > end_row {
10490 continue;
10491 }
10492
10493 // If the language has line comments, toggle those.
10494 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10495
10496 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10497 if ignore_indent {
10498 full_comment_prefixes = full_comment_prefixes
10499 .into_iter()
10500 .map(|s| Arc::from(s.trim_end()))
10501 .collect();
10502 }
10503
10504 if !full_comment_prefixes.is_empty() {
10505 let first_prefix = full_comment_prefixes
10506 .first()
10507 .expect("prefixes is non-empty");
10508 let prefix_trimmed_lengths = full_comment_prefixes
10509 .iter()
10510 .map(|p| p.trim_end_matches(' ').len())
10511 .collect::<SmallVec<[usize; 4]>>();
10512
10513 let mut all_selection_lines_are_comments = true;
10514
10515 for row in start_row.0..=end_row.0 {
10516 let row = MultiBufferRow(row);
10517 if start_row < end_row && snapshot.is_line_blank(row) {
10518 continue;
10519 }
10520
10521 let prefix_range = full_comment_prefixes
10522 .iter()
10523 .zip(prefix_trimmed_lengths.iter().copied())
10524 .map(|(prefix, trimmed_prefix_len)| {
10525 comment_prefix_range(
10526 snapshot.deref(),
10527 row,
10528 &prefix[..trimmed_prefix_len],
10529 &prefix[trimmed_prefix_len..],
10530 ignore_indent,
10531 )
10532 })
10533 .max_by_key(|range| range.end.column - range.start.column)
10534 .expect("prefixes is non-empty");
10535
10536 if prefix_range.is_empty() {
10537 all_selection_lines_are_comments = false;
10538 }
10539
10540 selection_edit_ranges.push(prefix_range);
10541 }
10542
10543 if all_selection_lines_are_comments {
10544 edits.extend(
10545 selection_edit_ranges
10546 .iter()
10547 .cloned()
10548 .map(|range| (range, empty_str.clone())),
10549 );
10550 } else {
10551 let min_column = selection_edit_ranges
10552 .iter()
10553 .map(|range| range.start.column)
10554 .min()
10555 .unwrap_or(0);
10556 edits.extend(selection_edit_ranges.iter().map(|range| {
10557 let position = Point::new(range.start.row, min_column);
10558 (position..position, first_prefix.clone())
10559 }));
10560 }
10561 } else if let Some((full_comment_prefix, comment_suffix)) =
10562 language.block_comment_delimiters()
10563 {
10564 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10565 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10566 let prefix_range = comment_prefix_range(
10567 snapshot.deref(),
10568 start_row,
10569 comment_prefix,
10570 comment_prefix_whitespace,
10571 ignore_indent,
10572 );
10573 let suffix_range = comment_suffix_range(
10574 snapshot.deref(),
10575 end_row,
10576 comment_suffix.trim_start_matches(' '),
10577 comment_suffix.starts_with(' '),
10578 );
10579
10580 if prefix_range.is_empty() || suffix_range.is_empty() {
10581 edits.push((
10582 prefix_range.start..prefix_range.start,
10583 full_comment_prefix.clone(),
10584 ));
10585 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10586 suffixes_inserted.push((end_row, comment_suffix.len()));
10587 } else {
10588 edits.push((prefix_range, empty_str.clone()));
10589 edits.push((suffix_range, empty_str.clone()));
10590 }
10591 } else {
10592 continue;
10593 }
10594 }
10595
10596 drop(snapshot);
10597 this.buffer.update(cx, |buffer, cx| {
10598 buffer.edit(edits, None, cx);
10599 });
10600
10601 // Adjust selections so that they end before any comment suffixes that
10602 // were inserted.
10603 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10604 let mut selections = this.selections.all::<Point>(cx);
10605 let snapshot = this.buffer.read(cx).read(cx);
10606 for selection in &mut selections {
10607 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10608 match row.cmp(&MultiBufferRow(selection.end.row)) {
10609 Ordering::Less => {
10610 suffixes_inserted.next();
10611 continue;
10612 }
10613 Ordering::Greater => break,
10614 Ordering::Equal => {
10615 if selection.end.column == snapshot.line_len(row) {
10616 if selection.is_empty() {
10617 selection.start.column -= suffix_len as u32;
10618 }
10619 selection.end.column -= suffix_len as u32;
10620 }
10621 break;
10622 }
10623 }
10624 }
10625 }
10626
10627 drop(snapshot);
10628 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10629 s.select(selections)
10630 });
10631
10632 let selections = this.selections.all::<Point>(cx);
10633 let selections_on_single_row = selections.windows(2).all(|selections| {
10634 selections[0].start.row == selections[1].start.row
10635 && selections[0].end.row == selections[1].end.row
10636 && selections[0].start.row == selections[0].end.row
10637 });
10638 let selections_selecting = selections
10639 .iter()
10640 .any(|selection| selection.start != selection.end);
10641 let advance_downwards = action.advance_downwards
10642 && selections_on_single_row
10643 && !selections_selecting
10644 && !matches!(this.mode, EditorMode::SingleLine { .. });
10645
10646 if advance_downwards {
10647 let snapshot = this.buffer.read(cx).snapshot(cx);
10648
10649 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10650 s.move_cursors_with(|display_snapshot, display_point, _| {
10651 let mut point = display_point.to_point(display_snapshot);
10652 point.row += 1;
10653 point = snapshot.clip_point(point, Bias::Left);
10654 let display_point = point.to_display_point(display_snapshot);
10655 let goal = SelectionGoal::HorizontalPosition(
10656 display_snapshot
10657 .x_for_display_point(display_point, text_layout_details)
10658 .into(),
10659 );
10660 (display_point, goal)
10661 })
10662 });
10663 }
10664 });
10665 }
10666
10667 pub fn select_enclosing_symbol(
10668 &mut self,
10669 _: &SelectEnclosingSymbol,
10670 window: &mut Window,
10671 cx: &mut Context<Self>,
10672 ) {
10673 let buffer = self.buffer.read(cx).snapshot(cx);
10674 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10675
10676 fn update_selection(
10677 selection: &Selection<usize>,
10678 buffer_snap: &MultiBufferSnapshot,
10679 ) -> Option<Selection<usize>> {
10680 let cursor = selection.head();
10681 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10682 for symbol in symbols.iter().rev() {
10683 let start = symbol.range.start.to_offset(buffer_snap);
10684 let end = symbol.range.end.to_offset(buffer_snap);
10685 let new_range = start..end;
10686 if start < selection.start || end > selection.end {
10687 return Some(Selection {
10688 id: selection.id,
10689 start: new_range.start,
10690 end: new_range.end,
10691 goal: SelectionGoal::None,
10692 reversed: selection.reversed,
10693 });
10694 }
10695 }
10696 None
10697 }
10698
10699 let mut selected_larger_symbol = false;
10700 let new_selections = old_selections
10701 .iter()
10702 .map(|selection| match update_selection(selection, &buffer) {
10703 Some(new_selection) => {
10704 if new_selection.range() != selection.range() {
10705 selected_larger_symbol = true;
10706 }
10707 new_selection
10708 }
10709 None => selection.clone(),
10710 })
10711 .collect::<Vec<_>>();
10712
10713 if selected_larger_symbol {
10714 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10715 s.select(new_selections);
10716 });
10717 }
10718 }
10719
10720 pub fn select_larger_syntax_node(
10721 &mut self,
10722 _: &SelectLargerSyntaxNode,
10723 window: &mut Window,
10724 cx: &mut Context<Self>,
10725 ) {
10726 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10727 let buffer = self.buffer.read(cx).snapshot(cx);
10728 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10729
10730 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10731 let mut selected_larger_node = false;
10732 let new_selections = old_selections
10733 .iter()
10734 .map(|selection| {
10735 let old_range = selection.start..selection.end;
10736 let mut new_range = old_range.clone();
10737 let mut new_node = None;
10738 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10739 {
10740 new_node = Some(node);
10741 new_range = match containing_range {
10742 MultiOrSingleBufferOffsetRange::Single(_) => break,
10743 MultiOrSingleBufferOffsetRange::Multi(range) => range,
10744 };
10745 if !display_map.intersects_fold(new_range.start)
10746 && !display_map.intersects_fold(new_range.end)
10747 {
10748 break;
10749 }
10750 }
10751
10752 if let Some(node) = new_node {
10753 // Log the ancestor, to support using this action as a way to explore TreeSitter
10754 // nodes. Parent and grandparent are also logged because this operation will not
10755 // visit nodes that have the same range as their parent.
10756 log::info!("Node: {node:?}");
10757 let parent = node.parent();
10758 log::info!("Parent: {parent:?}");
10759 let grandparent = parent.and_then(|x| x.parent());
10760 log::info!("Grandparent: {grandparent:?}");
10761 }
10762
10763 selected_larger_node |= new_range != old_range;
10764 Selection {
10765 id: selection.id,
10766 start: new_range.start,
10767 end: new_range.end,
10768 goal: SelectionGoal::None,
10769 reversed: selection.reversed,
10770 }
10771 })
10772 .collect::<Vec<_>>();
10773
10774 if selected_larger_node {
10775 stack.push(old_selections);
10776 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10777 s.select(new_selections);
10778 });
10779 }
10780 self.select_larger_syntax_node_stack = stack;
10781 }
10782
10783 pub fn select_smaller_syntax_node(
10784 &mut self,
10785 _: &SelectSmallerSyntaxNode,
10786 window: &mut Window,
10787 cx: &mut Context<Self>,
10788 ) {
10789 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10790 if let Some(selections) = stack.pop() {
10791 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10792 s.select(selections.to_vec());
10793 });
10794 }
10795 self.select_larger_syntax_node_stack = stack;
10796 }
10797
10798 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10799 if !EditorSettings::get_global(cx).gutter.runnables {
10800 self.clear_tasks();
10801 return Task::ready(());
10802 }
10803 let project = self.project.as_ref().map(Entity::downgrade);
10804 cx.spawn_in(window, |this, mut cx| async move {
10805 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10806 let Some(project) = project.and_then(|p| p.upgrade()) else {
10807 return;
10808 };
10809 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10810 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10811 }) else {
10812 return;
10813 };
10814
10815 let hide_runnables = project
10816 .update(&mut cx, |project, cx| {
10817 // Do not display any test indicators in non-dev server remote projects.
10818 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10819 })
10820 .unwrap_or(true);
10821 if hide_runnables {
10822 return;
10823 }
10824 let new_rows =
10825 cx.background_spawn({
10826 let snapshot = display_snapshot.clone();
10827 async move {
10828 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10829 }
10830 })
10831 .await;
10832
10833 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10834 this.update(&mut cx, |this, _| {
10835 this.clear_tasks();
10836 for (key, value) in rows {
10837 this.insert_tasks(key, value);
10838 }
10839 })
10840 .ok();
10841 })
10842 }
10843 fn fetch_runnable_ranges(
10844 snapshot: &DisplaySnapshot,
10845 range: Range<Anchor>,
10846 ) -> Vec<language::RunnableRange> {
10847 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10848 }
10849
10850 fn runnable_rows(
10851 project: Entity<Project>,
10852 snapshot: DisplaySnapshot,
10853 runnable_ranges: Vec<RunnableRange>,
10854 mut cx: AsyncWindowContext,
10855 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10856 runnable_ranges
10857 .into_iter()
10858 .filter_map(|mut runnable| {
10859 let tasks = cx
10860 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10861 .ok()?;
10862 if tasks.is_empty() {
10863 return None;
10864 }
10865
10866 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10867
10868 let row = snapshot
10869 .buffer_snapshot
10870 .buffer_line_for_row(MultiBufferRow(point.row))?
10871 .1
10872 .start
10873 .row;
10874
10875 let context_range =
10876 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10877 Some((
10878 (runnable.buffer_id, row),
10879 RunnableTasks {
10880 templates: tasks,
10881 offset: snapshot
10882 .buffer_snapshot
10883 .anchor_before(runnable.run_range.start),
10884 context_range,
10885 column: point.column,
10886 extra_variables: runnable.extra_captures,
10887 },
10888 ))
10889 })
10890 .collect()
10891 }
10892
10893 fn templates_with_tags(
10894 project: &Entity<Project>,
10895 runnable: &mut Runnable,
10896 cx: &mut App,
10897 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10898 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10899 let (worktree_id, file) = project
10900 .buffer_for_id(runnable.buffer, cx)
10901 .and_then(|buffer| buffer.read(cx).file())
10902 .map(|file| (file.worktree_id(cx), file.clone()))
10903 .unzip();
10904
10905 (
10906 project.task_store().read(cx).task_inventory().cloned(),
10907 worktree_id,
10908 file,
10909 )
10910 });
10911
10912 let tags = mem::take(&mut runnable.tags);
10913 let mut tags: Vec<_> = tags
10914 .into_iter()
10915 .flat_map(|tag| {
10916 let tag = tag.0.clone();
10917 inventory
10918 .as_ref()
10919 .into_iter()
10920 .flat_map(|inventory| {
10921 inventory.read(cx).list_tasks(
10922 file.clone(),
10923 Some(runnable.language.clone()),
10924 worktree_id,
10925 cx,
10926 )
10927 })
10928 .filter(move |(_, template)| {
10929 template.tags.iter().any(|source_tag| source_tag == &tag)
10930 })
10931 })
10932 .sorted_by_key(|(kind, _)| kind.to_owned())
10933 .collect();
10934 if let Some((leading_tag_source, _)) = tags.first() {
10935 // Strongest source wins; if we have worktree tag binding, prefer that to
10936 // global and language bindings;
10937 // if we have a global binding, prefer that to language binding.
10938 let first_mismatch = tags
10939 .iter()
10940 .position(|(tag_source, _)| tag_source != leading_tag_source);
10941 if let Some(index) = first_mismatch {
10942 tags.truncate(index);
10943 }
10944 }
10945
10946 tags
10947 }
10948
10949 pub fn move_to_enclosing_bracket(
10950 &mut self,
10951 _: &MoveToEnclosingBracket,
10952 window: &mut Window,
10953 cx: &mut Context<Self>,
10954 ) {
10955 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10956 s.move_offsets_with(|snapshot, selection| {
10957 let Some(enclosing_bracket_ranges) =
10958 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10959 else {
10960 return;
10961 };
10962
10963 let mut best_length = usize::MAX;
10964 let mut best_inside = false;
10965 let mut best_in_bracket_range = false;
10966 let mut best_destination = None;
10967 for (open, close) in enclosing_bracket_ranges {
10968 let close = close.to_inclusive();
10969 let length = close.end() - open.start;
10970 let inside = selection.start >= open.end && selection.end <= *close.start();
10971 let in_bracket_range = open.to_inclusive().contains(&selection.head())
10972 || close.contains(&selection.head());
10973
10974 // If best is next to a bracket and current isn't, skip
10975 if !in_bracket_range && best_in_bracket_range {
10976 continue;
10977 }
10978
10979 // Prefer smaller lengths unless best is inside and current isn't
10980 if length > best_length && (best_inside || !inside) {
10981 continue;
10982 }
10983
10984 best_length = length;
10985 best_inside = inside;
10986 best_in_bracket_range = in_bracket_range;
10987 best_destination = Some(
10988 if close.contains(&selection.start) && close.contains(&selection.end) {
10989 if inside {
10990 open.end
10991 } else {
10992 open.start
10993 }
10994 } else if inside {
10995 *close.start()
10996 } else {
10997 *close.end()
10998 },
10999 );
11000 }
11001
11002 if let Some(destination) = best_destination {
11003 selection.collapse_to(destination, SelectionGoal::None);
11004 }
11005 })
11006 });
11007 }
11008
11009 pub fn undo_selection(
11010 &mut self,
11011 _: &UndoSelection,
11012 window: &mut Window,
11013 cx: &mut Context<Self>,
11014 ) {
11015 self.end_selection(window, cx);
11016 self.selection_history.mode = SelectionHistoryMode::Undoing;
11017 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11018 self.change_selections(None, window, cx, |s| {
11019 s.select_anchors(entry.selections.to_vec())
11020 });
11021 self.select_next_state = entry.select_next_state;
11022 self.select_prev_state = entry.select_prev_state;
11023 self.add_selections_state = entry.add_selections_state;
11024 self.request_autoscroll(Autoscroll::newest(), cx);
11025 }
11026 self.selection_history.mode = SelectionHistoryMode::Normal;
11027 }
11028
11029 pub fn redo_selection(
11030 &mut self,
11031 _: &RedoSelection,
11032 window: &mut Window,
11033 cx: &mut Context<Self>,
11034 ) {
11035 self.end_selection(window, cx);
11036 self.selection_history.mode = SelectionHistoryMode::Redoing;
11037 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11038 self.change_selections(None, window, cx, |s| {
11039 s.select_anchors(entry.selections.to_vec())
11040 });
11041 self.select_next_state = entry.select_next_state;
11042 self.select_prev_state = entry.select_prev_state;
11043 self.add_selections_state = entry.add_selections_state;
11044 self.request_autoscroll(Autoscroll::newest(), cx);
11045 }
11046 self.selection_history.mode = SelectionHistoryMode::Normal;
11047 }
11048
11049 pub fn expand_excerpts(
11050 &mut self,
11051 action: &ExpandExcerpts,
11052 _: &mut Window,
11053 cx: &mut Context<Self>,
11054 ) {
11055 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11056 }
11057
11058 pub fn expand_excerpts_down(
11059 &mut self,
11060 action: &ExpandExcerptsDown,
11061 _: &mut Window,
11062 cx: &mut Context<Self>,
11063 ) {
11064 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11065 }
11066
11067 pub fn expand_excerpts_up(
11068 &mut self,
11069 action: &ExpandExcerptsUp,
11070 _: &mut Window,
11071 cx: &mut Context<Self>,
11072 ) {
11073 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11074 }
11075
11076 pub fn expand_excerpts_for_direction(
11077 &mut self,
11078 lines: u32,
11079 direction: ExpandExcerptDirection,
11080
11081 cx: &mut Context<Self>,
11082 ) {
11083 let selections = self.selections.disjoint_anchors();
11084
11085 let lines = if lines == 0 {
11086 EditorSettings::get_global(cx).expand_excerpt_lines
11087 } else {
11088 lines
11089 };
11090
11091 self.buffer.update(cx, |buffer, cx| {
11092 let snapshot = buffer.snapshot(cx);
11093 let mut excerpt_ids = selections
11094 .iter()
11095 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11096 .collect::<Vec<_>>();
11097 excerpt_ids.sort();
11098 excerpt_ids.dedup();
11099 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11100 })
11101 }
11102
11103 pub fn expand_excerpt(
11104 &mut self,
11105 excerpt: ExcerptId,
11106 direction: ExpandExcerptDirection,
11107 cx: &mut Context<Self>,
11108 ) {
11109 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11110 self.buffer.update(cx, |buffer, cx| {
11111 buffer.expand_excerpts([excerpt], lines, direction, cx)
11112 })
11113 }
11114
11115 pub fn go_to_singleton_buffer_point(
11116 &mut self,
11117 point: Point,
11118 window: &mut Window,
11119 cx: &mut Context<Self>,
11120 ) {
11121 self.go_to_singleton_buffer_range(point..point, window, cx);
11122 }
11123
11124 pub fn go_to_singleton_buffer_range(
11125 &mut self,
11126 range: Range<Point>,
11127 window: &mut Window,
11128 cx: &mut Context<Self>,
11129 ) {
11130 let multibuffer = self.buffer().read(cx);
11131 let Some(buffer) = multibuffer.as_singleton() else {
11132 return;
11133 };
11134 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11135 return;
11136 };
11137 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11138 return;
11139 };
11140 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11141 s.select_anchor_ranges([start..end])
11142 });
11143 }
11144
11145 fn go_to_diagnostic(
11146 &mut self,
11147 _: &GoToDiagnostic,
11148 window: &mut Window,
11149 cx: &mut Context<Self>,
11150 ) {
11151 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11152 }
11153
11154 fn go_to_prev_diagnostic(
11155 &mut self,
11156 _: &GoToPrevDiagnostic,
11157 window: &mut Window,
11158 cx: &mut Context<Self>,
11159 ) {
11160 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11161 }
11162
11163 pub fn go_to_diagnostic_impl(
11164 &mut self,
11165 direction: Direction,
11166 window: &mut Window,
11167 cx: &mut Context<Self>,
11168 ) {
11169 let buffer = self.buffer.read(cx).snapshot(cx);
11170 let selection = self.selections.newest::<usize>(cx);
11171
11172 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11173 if direction == Direction::Next {
11174 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11175 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11176 return;
11177 };
11178 self.activate_diagnostics(
11179 buffer_id,
11180 popover.local_diagnostic.diagnostic.group_id,
11181 window,
11182 cx,
11183 );
11184 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11185 let primary_range_start = active_diagnostics.primary_range.start;
11186 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11187 let mut new_selection = s.newest_anchor().clone();
11188 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11189 s.select_anchors(vec![new_selection.clone()]);
11190 });
11191 self.refresh_inline_completion(false, true, window, cx);
11192 }
11193 return;
11194 }
11195 }
11196
11197 let active_group_id = self
11198 .active_diagnostics
11199 .as_ref()
11200 .map(|active_group| active_group.group_id);
11201 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11202 active_diagnostics
11203 .primary_range
11204 .to_offset(&buffer)
11205 .to_inclusive()
11206 });
11207 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11208 if active_primary_range.contains(&selection.head()) {
11209 *active_primary_range.start()
11210 } else {
11211 selection.head()
11212 }
11213 } else {
11214 selection.head()
11215 };
11216
11217 let snapshot = self.snapshot(window, cx);
11218 let primary_diagnostics_before = buffer
11219 .diagnostics_in_range::<usize>(0..search_start)
11220 .filter(|entry| entry.diagnostic.is_primary)
11221 .filter(|entry| entry.range.start != entry.range.end)
11222 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11223 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11224 .collect::<Vec<_>>();
11225 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11226 primary_diagnostics_before
11227 .iter()
11228 .position(|entry| entry.diagnostic.group_id == active_group_id)
11229 });
11230
11231 let primary_diagnostics_after = buffer
11232 .diagnostics_in_range::<usize>(search_start..buffer.len())
11233 .filter(|entry| entry.diagnostic.is_primary)
11234 .filter(|entry| entry.range.start != entry.range.end)
11235 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11236 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11237 .collect::<Vec<_>>();
11238 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11239 primary_diagnostics_after
11240 .iter()
11241 .enumerate()
11242 .rev()
11243 .find_map(|(i, entry)| {
11244 if entry.diagnostic.group_id == active_group_id {
11245 Some(i)
11246 } else {
11247 None
11248 }
11249 })
11250 });
11251
11252 let next_primary_diagnostic = match direction {
11253 Direction::Prev => primary_diagnostics_before
11254 .iter()
11255 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11256 .rev()
11257 .next(),
11258 Direction::Next => primary_diagnostics_after
11259 .iter()
11260 .skip(
11261 last_same_group_diagnostic_after
11262 .map(|index| index + 1)
11263 .unwrap_or(0),
11264 )
11265 .next(),
11266 };
11267
11268 // Cycle around to the start of the buffer, potentially moving back to the start of
11269 // the currently active diagnostic.
11270 let cycle_around = || match direction {
11271 Direction::Prev => primary_diagnostics_after
11272 .iter()
11273 .rev()
11274 .chain(primary_diagnostics_before.iter().rev())
11275 .next(),
11276 Direction::Next => primary_diagnostics_before
11277 .iter()
11278 .chain(primary_diagnostics_after.iter())
11279 .next(),
11280 };
11281
11282 if let Some((primary_range, group_id)) = next_primary_diagnostic
11283 .or_else(cycle_around)
11284 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11285 {
11286 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11287 return;
11288 };
11289 self.activate_diagnostics(buffer_id, group_id, window, cx);
11290 if self.active_diagnostics.is_some() {
11291 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11292 s.select(vec![Selection {
11293 id: selection.id,
11294 start: primary_range.start,
11295 end: primary_range.start,
11296 reversed: false,
11297 goal: SelectionGoal::None,
11298 }]);
11299 });
11300 self.refresh_inline_completion(false, true, window, cx);
11301 }
11302 }
11303 }
11304
11305 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11306 let snapshot = self.snapshot(window, cx);
11307 let selection = self.selections.newest::<Point>(cx);
11308 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11309 }
11310
11311 fn go_to_hunk_after_position(
11312 &mut self,
11313 snapshot: &EditorSnapshot,
11314 position: Point,
11315 window: &mut Window,
11316 cx: &mut Context<Editor>,
11317 ) -> Option<MultiBufferDiffHunk> {
11318 let mut hunk = snapshot
11319 .buffer_snapshot
11320 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11321 .find(|hunk| hunk.row_range.start.0 > position.row);
11322 if hunk.is_none() {
11323 hunk = snapshot
11324 .buffer_snapshot
11325 .diff_hunks_in_range(Point::zero()..position)
11326 .find(|hunk| hunk.row_range.end.0 < position.row)
11327 }
11328 if let Some(hunk) = &hunk {
11329 let destination = Point::new(hunk.row_range.start.0, 0);
11330 self.unfold_ranges(&[destination..destination], false, false, cx);
11331 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11332 s.select_ranges(vec![destination..destination]);
11333 });
11334 }
11335
11336 hunk
11337 }
11338
11339 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11340 let snapshot = self.snapshot(window, cx);
11341 let selection = self.selections.newest::<Point>(cx);
11342 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11343 }
11344
11345 fn go_to_hunk_before_position(
11346 &mut self,
11347 snapshot: &EditorSnapshot,
11348 position: Point,
11349 window: &mut Window,
11350 cx: &mut Context<Editor>,
11351 ) -> Option<MultiBufferDiffHunk> {
11352 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11353 if hunk.is_none() {
11354 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11355 }
11356 if let Some(hunk) = &hunk {
11357 let destination = Point::new(hunk.row_range.start.0, 0);
11358 self.unfold_ranges(&[destination..destination], false, false, cx);
11359 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11360 s.select_ranges(vec![destination..destination]);
11361 });
11362 }
11363
11364 hunk
11365 }
11366
11367 pub fn go_to_definition(
11368 &mut self,
11369 _: &GoToDefinition,
11370 window: &mut Window,
11371 cx: &mut Context<Self>,
11372 ) -> Task<Result<Navigated>> {
11373 let definition =
11374 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11375 cx.spawn_in(window, |editor, mut cx| async move {
11376 if definition.await? == Navigated::Yes {
11377 return Ok(Navigated::Yes);
11378 }
11379 match editor.update_in(&mut cx, |editor, window, cx| {
11380 editor.find_all_references(&FindAllReferences, window, cx)
11381 })? {
11382 Some(references) => references.await,
11383 None => Ok(Navigated::No),
11384 }
11385 })
11386 }
11387
11388 pub fn go_to_declaration(
11389 &mut self,
11390 _: &GoToDeclaration,
11391 window: &mut Window,
11392 cx: &mut Context<Self>,
11393 ) -> Task<Result<Navigated>> {
11394 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11395 }
11396
11397 pub fn go_to_declaration_split(
11398 &mut self,
11399 _: &GoToDeclaration,
11400 window: &mut Window,
11401 cx: &mut Context<Self>,
11402 ) -> Task<Result<Navigated>> {
11403 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11404 }
11405
11406 pub fn go_to_implementation(
11407 &mut self,
11408 _: &GoToImplementation,
11409 window: &mut Window,
11410 cx: &mut Context<Self>,
11411 ) -> Task<Result<Navigated>> {
11412 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11413 }
11414
11415 pub fn go_to_implementation_split(
11416 &mut self,
11417 _: &GoToImplementationSplit,
11418 window: &mut Window,
11419 cx: &mut Context<Self>,
11420 ) -> Task<Result<Navigated>> {
11421 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11422 }
11423
11424 pub fn go_to_type_definition(
11425 &mut self,
11426 _: &GoToTypeDefinition,
11427 window: &mut Window,
11428 cx: &mut Context<Self>,
11429 ) -> Task<Result<Navigated>> {
11430 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11431 }
11432
11433 pub fn go_to_definition_split(
11434 &mut self,
11435 _: &GoToDefinitionSplit,
11436 window: &mut Window,
11437 cx: &mut Context<Self>,
11438 ) -> Task<Result<Navigated>> {
11439 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11440 }
11441
11442 pub fn go_to_type_definition_split(
11443 &mut self,
11444 _: &GoToTypeDefinitionSplit,
11445 window: &mut Window,
11446 cx: &mut Context<Self>,
11447 ) -> Task<Result<Navigated>> {
11448 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11449 }
11450
11451 fn go_to_definition_of_kind(
11452 &mut self,
11453 kind: GotoDefinitionKind,
11454 split: bool,
11455 window: &mut Window,
11456 cx: &mut Context<Self>,
11457 ) -> Task<Result<Navigated>> {
11458 let Some(provider) = self.semantics_provider.clone() else {
11459 return Task::ready(Ok(Navigated::No));
11460 };
11461 let head = self.selections.newest::<usize>(cx).head();
11462 let buffer = self.buffer.read(cx);
11463 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11464 text_anchor
11465 } else {
11466 return Task::ready(Ok(Navigated::No));
11467 };
11468
11469 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11470 return Task::ready(Ok(Navigated::No));
11471 };
11472
11473 cx.spawn_in(window, |editor, mut cx| async move {
11474 let definitions = definitions.await?;
11475 let navigated = editor
11476 .update_in(&mut cx, |editor, window, cx| {
11477 editor.navigate_to_hover_links(
11478 Some(kind),
11479 definitions
11480 .into_iter()
11481 .filter(|location| {
11482 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11483 })
11484 .map(HoverLink::Text)
11485 .collect::<Vec<_>>(),
11486 split,
11487 window,
11488 cx,
11489 )
11490 })?
11491 .await?;
11492 anyhow::Ok(navigated)
11493 })
11494 }
11495
11496 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11497 let selection = self.selections.newest_anchor();
11498 let head = selection.head();
11499 let tail = selection.tail();
11500
11501 let Some((buffer, start_position)) =
11502 self.buffer.read(cx).text_anchor_for_position(head, cx)
11503 else {
11504 return;
11505 };
11506
11507 let end_position = if head != tail {
11508 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11509 return;
11510 };
11511 Some(pos)
11512 } else {
11513 None
11514 };
11515
11516 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11517 let url = if let Some(end_pos) = end_position {
11518 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11519 } else {
11520 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11521 };
11522
11523 if let Some(url) = url {
11524 editor.update(&mut cx, |_, cx| {
11525 cx.open_url(&url);
11526 })
11527 } else {
11528 Ok(())
11529 }
11530 });
11531
11532 url_finder.detach();
11533 }
11534
11535 pub fn open_selected_filename(
11536 &mut self,
11537 _: &OpenSelectedFilename,
11538 window: &mut Window,
11539 cx: &mut Context<Self>,
11540 ) {
11541 let Some(workspace) = self.workspace() else {
11542 return;
11543 };
11544
11545 let position = self.selections.newest_anchor().head();
11546
11547 let Some((buffer, buffer_position)) =
11548 self.buffer.read(cx).text_anchor_for_position(position, cx)
11549 else {
11550 return;
11551 };
11552
11553 let project = self.project.clone();
11554
11555 cx.spawn_in(window, |_, mut cx| async move {
11556 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11557
11558 if let Some((_, path)) = result {
11559 workspace
11560 .update_in(&mut cx, |workspace, window, cx| {
11561 workspace.open_resolved_path(path, window, cx)
11562 })?
11563 .await?;
11564 }
11565 anyhow::Ok(())
11566 })
11567 .detach();
11568 }
11569
11570 pub(crate) fn navigate_to_hover_links(
11571 &mut self,
11572 kind: Option<GotoDefinitionKind>,
11573 mut definitions: Vec<HoverLink>,
11574 split: bool,
11575 window: &mut Window,
11576 cx: &mut Context<Editor>,
11577 ) -> Task<Result<Navigated>> {
11578 // If there is one definition, just open it directly
11579 if definitions.len() == 1 {
11580 let definition = definitions.pop().unwrap();
11581
11582 enum TargetTaskResult {
11583 Location(Option<Location>),
11584 AlreadyNavigated,
11585 }
11586
11587 let target_task = match definition {
11588 HoverLink::Text(link) => {
11589 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11590 }
11591 HoverLink::InlayHint(lsp_location, server_id) => {
11592 let computation =
11593 self.compute_target_location(lsp_location, server_id, window, cx);
11594 cx.background_spawn(async move {
11595 let location = computation.await?;
11596 Ok(TargetTaskResult::Location(location))
11597 })
11598 }
11599 HoverLink::Url(url) => {
11600 cx.open_url(&url);
11601 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11602 }
11603 HoverLink::File(path) => {
11604 if let Some(workspace) = self.workspace() {
11605 cx.spawn_in(window, |_, mut cx| async move {
11606 workspace
11607 .update_in(&mut cx, |workspace, window, cx| {
11608 workspace.open_resolved_path(path, window, cx)
11609 })?
11610 .await
11611 .map(|_| TargetTaskResult::AlreadyNavigated)
11612 })
11613 } else {
11614 Task::ready(Ok(TargetTaskResult::Location(None)))
11615 }
11616 }
11617 };
11618 cx.spawn_in(window, |editor, mut cx| async move {
11619 let target = match target_task.await.context("target resolution task")? {
11620 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11621 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11622 TargetTaskResult::Location(Some(target)) => target,
11623 };
11624
11625 editor.update_in(&mut cx, |editor, window, cx| {
11626 let Some(workspace) = editor.workspace() else {
11627 return Navigated::No;
11628 };
11629 let pane = workspace.read(cx).active_pane().clone();
11630
11631 let range = target.range.to_point(target.buffer.read(cx));
11632 let range = editor.range_for_match(&range);
11633 let range = collapse_multiline_range(range);
11634
11635 if !split
11636 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11637 {
11638 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11639 } else {
11640 window.defer(cx, move |window, cx| {
11641 let target_editor: Entity<Self> =
11642 workspace.update(cx, |workspace, cx| {
11643 let pane = if split {
11644 workspace.adjacent_pane(window, cx)
11645 } else {
11646 workspace.active_pane().clone()
11647 };
11648
11649 workspace.open_project_item(
11650 pane,
11651 target.buffer.clone(),
11652 true,
11653 true,
11654 window,
11655 cx,
11656 )
11657 });
11658 target_editor.update(cx, |target_editor, cx| {
11659 // When selecting a definition in a different buffer, disable the nav history
11660 // to avoid creating a history entry at the previous cursor location.
11661 pane.update(cx, |pane, _| pane.disable_history());
11662 target_editor.go_to_singleton_buffer_range(range, window, cx);
11663 pane.update(cx, |pane, _| pane.enable_history());
11664 });
11665 });
11666 }
11667 Navigated::Yes
11668 })
11669 })
11670 } else if !definitions.is_empty() {
11671 cx.spawn_in(window, |editor, mut cx| async move {
11672 let (title, location_tasks, workspace) = editor
11673 .update_in(&mut cx, |editor, window, cx| {
11674 let tab_kind = match kind {
11675 Some(GotoDefinitionKind::Implementation) => "Implementations",
11676 _ => "Definitions",
11677 };
11678 let title = definitions
11679 .iter()
11680 .find_map(|definition| match definition {
11681 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11682 let buffer = origin.buffer.read(cx);
11683 format!(
11684 "{} for {}",
11685 tab_kind,
11686 buffer
11687 .text_for_range(origin.range.clone())
11688 .collect::<String>()
11689 )
11690 }),
11691 HoverLink::InlayHint(_, _) => None,
11692 HoverLink::Url(_) => None,
11693 HoverLink::File(_) => None,
11694 })
11695 .unwrap_or(tab_kind.to_string());
11696 let location_tasks = definitions
11697 .into_iter()
11698 .map(|definition| match definition {
11699 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11700 HoverLink::InlayHint(lsp_location, server_id) => editor
11701 .compute_target_location(lsp_location, server_id, window, cx),
11702 HoverLink::Url(_) => Task::ready(Ok(None)),
11703 HoverLink::File(_) => Task::ready(Ok(None)),
11704 })
11705 .collect::<Vec<_>>();
11706 (title, location_tasks, editor.workspace().clone())
11707 })
11708 .context("location tasks preparation")?;
11709
11710 let locations = future::join_all(location_tasks)
11711 .await
11712 .into_iter()
11713 .filter_map(|location| location.transpose())
11714 .collect::<Result<_>>()
11715 .context("location tasks")?;
11716
11717 let Some(workspace) = workspace else {
11718 return Ok(Navigated::No);
11719 };
11720 let opened = workspace
11721 .update_in(&mut cx, |workspace, window, cx| {
11722 Self::open_locations_in_multibuffer(
11723 workspace,
11724 locations,
11725 title,
11726 split,
11727 MultibufferSelectionMode::First,
11728 window,
11729 cx,
11730 )
11731 })
11732 .ok();
11733
11734 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11735 })
11736 } else {
11737 Task::ready(Ok(Navigated::No))
11738 }
11739 }
11740
11741 fn compute_target_location(
11742 &self,
11743 lsp_location: lsp::Location,
11744 server_id: LanguageServerId,
11745 window: &mut Window,
11746 cx: &mut Context<Self>,
11747 ) -> Task<anyhow::Result<Option<Location>>> {
11748 let Some(project) = self.project.clone() else {
11749 return Task::ready(Ok(None));
11750 };
11751
11752 cx.spawn_in(window, move |editor, mut cx| async move {
11753 let location_task = editor.update(&mut cx, |_, cx| {
11754 project.update(cx, |project, cx| {
11755 let language_server_name = project
11756 .language_server_statuses(cx)
11757 .find(|(id, _)| server_id == *id)
11758 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11759 language_server_name.map(|language_server_name| {
11760 project.open_local_buffer_via_lsp(
11761 lsp_location.uri.clone(),
11762 server_id,
11763 language_server_name,
11764 cx,
11765 )
11766 })
11767 })
11768 })?;
11769 let location = match location_task {
11770 Some(task) => Some({
11771 let target_buffer_handle = task.await.context("open local buffer")?;
11772 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11773 let target_start = target_buffer
11774 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11775 let target_end = target_buffer
11776 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11777 target_buffer.anchor_after(target_start)
11778 ..target_buffer.anchor_before(target_end)
11779 })?;
11780 Location {
11781 buffer: target_buffer_handle,
11782 range,
11783 }
11784 }),
11785 None => None,
11786 };
11787 Ok(location)
11788 })
11789 }
11790
11791 pub fn find_all_references(
11792 &mut self,
11793 _: &FindAllReferences,
11794 window: &mut Window,
11795 cx: &mut Context<Self>,
11796 ) -> Option<Task<Result<Navigated>>> {
11797 let selection = self.selections.newest::<usize>(cx);
11798 let multi_buffer = self.buffer.read(cx);
11799 let head = selection.head();
11800
11801 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11802 let head_anchor = multi_buffer_snapshot.anchor_at(
11803 head,
11804 if head < selection.tail() {
11805 Bias::Right
11806 } else {
11807 Bias::Left
11808 },
11809 );
11810
11811 match self
11812 .find_all_references_task_sources
11813 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11814 {
11815 Ok(_) => {
11816 log::info!(
11817 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11818 );
11819 return None;
11820 }
11821 Err(i) => {
11822 self.find_all_references_task_sources.insert(i, head_anchor);
11823 }
11824 }
11825
11826 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11827 let workspace = self.workspace()?;
11828 let project = workspace.read(cx).project().clone();
11829 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11830 Some(cx.spawn_in(window, |editor, mut cx| async move {
11831 let _cleanup = defer({
11832 let mut cx = cx.clone();
11833 move || {
11834 let _ = editor.update(&mut cx, |editor, _| {
11835 if let Ok(i) =
11836 editor
11837 .find_all_references_task_sources
11838 .binary_search_by(|anchor| {
11839 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11840 })
11841 {
11842 editor.find_all_references_task_sources.remove(i);
11843 }
11844 });
11845 }
11846 });
11847
11848 let locations = references.await?;
11849 if locations.is_empty() {
11850 return anyhow::Ok(Navigated::No);
11851 }
11852
11853 workspace.update_in(&mut cx, |workspace, window, cx| {
11854 let title = locations
11855 .first()
11856 .as_ref()
11857 .map(|location| {
11858 let buffer = location.buffer.read(cx);
11859 format!(
11860 "References to `{}`",
11861 buffer
11862 .text_for_range(location.range.clone())
11863 .collect::<String>()
11864 )
11865 })
11866 .unwrap();
11867 Self::open_locations_in_multibuffer(
11868 workspace,
11869 locations,
11870 title,
11871 false,
11872 MultibufferSelectionMode::First,
11873 window,
11874 cx,
11875 );
11876 Navigated::Yes
11877 })
11878 }))
11879 }
11880
11881 /// Opens a multibuffer with the given project locations in it
11882 pub fn open_locations_in_multibuffer(
11883 workspace: &mut Workspace,
11884 mut locations: Vec<Location>,
11885 title: String,
11886 split: bool,
11887 multibuffer_selection_mode: MultibufferSelectionMode,
11888 window: &mut Window,
11889 cx: &mut Context<Workspace>,
11890 ) {
11891 // If there are multiple definitions, open them in a multibuffer
11892 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11893 let mut locations = locations.into_iter().peekable();
11894 let mut ranges = Vec::new();
11895 let capability = workspace.project().read(cx).capability();
11896
11897 let excerpt_buffer = cx.new(|cx| {
11898 let mut multibuffer = MultiBuffer::new(capability);
11899 while let Some(location) = locations.next() {
11900 let buffer = location.buffer.read(cx);
11901 let mut ranges_for_buffer = Vec::new();
11902 let range = location.range.to_offset(buffer);
11903 ranges_for_buffer.push(range.clone());
11904
11905 while let Some(next_location) = locations.peek() {
11906 if next_location.buffer == location.buffer {
11907 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11908 locations.next();
11909 } else {
11910 break;
11911 }
11912 }
11913
11914 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11915 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11916 location.buffer.clone(),
11917 ranges_for_buffer,
11918 DEFAULT_MULTIBUFFER_CONTEXT,
11919 cx,
11920 ))
11921 }
11922
11923 multibuffer.with_title(title)
11924 });
11925
11926 let editor = cx.new(|cx| {
11927 Editor::for_multibuffer(
11928 excerpt_buffer,
11929 Some(workspace.project().clone()),
11930 true,
11931 window,
11932 cx,
11933 )
11934 });
11935 editor.update(cx, |editor, cx| {
11936 match multibuffer_selection_mode {
11937 MultibufferSelectionMode::First => {
11938 if let Some(first_range) = ranges.first() {
11939 editor.change_selections(None, window, cx, |selections| {
11940 selections.clear_disjoint();
11941 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11942 });
11943 }
11944 editor.highlight_background::<Self>(
11945 &ranges,
11946 |theme| theme.editor_highlighted_line_background,
11947 cx,
11948 );
11949 }
11950 MultibufferSelectionMode::All => {
11951 editor.change_selections(None, window, cx, |selections| {
11952 selections.clear_disjoint();
11953 selections.select_anchor_ranges(ranges);
11954 });
11955 }
11956 }
11957 editor.register_buffers_with_language_servers(cx);
11958 });
11959
11960 let item = Box::new(editor);
11961 let item_id = item.item_id();
11962
11963 if split {
11964 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11965 } else {
11966 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11967 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11968 pane.close_current_preview_item(window, cx)
11969 } else {
11970 None
11971 }
11972 });
11973 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11974 }
11975 workspace.active_pane().update(cx, |pane, cx| {
11976 pane.set_preview_item_id(Some(item_id), cx);
11977 });
11978 }
11979
11980 pub fn rename(
11981 &mut self,
11982 _: &Rename,
11983 window: &mut Window,
11984 cx: &mut Context<Self>,
11985 ) -> Option<Task<Result<()>>> {
11986 use language::ToOffset as _;
11987
11988 let provider = self.semantics_provider.clone()?;
11989 let selection = self.selections.newest_anchor().clone();
11990 let (cursor_buffer, cursor_buffer_position) = self
11991 .buffer
11992 .read(cx)
11993 .text_anchor_for_position(selection.head(), cx)?;
11994 let (tail_buffer, cursor_buffer_position_end) = self
11995 .buffer
11996 .read(cx)
11997 .text_anchor_for_position(selection.tail(), cx)?;
11998 if tail_buffer != cursor_buffer {
11999 return None;
12000 }
12001
12002 let snapshot = cursor_buffer.read(cx).snapshot();
12003 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12004 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12005 let prepare_rename = provider
12006 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12007 .unwrap_or_else(|| Task::ready(Ok(None)));
12008 drop(snapshot);
12009
12010 Some(cx.spawn_in(window, |this, mut cx| async move {
12011 let rename_range = if let Some(range) = prepare_rename.await? {
12012 Some(range)
12013 } else {
12014 this.update(&mut cx, |this, cx| {
12015 let buffer = this.buffer.read(cx).snapshot(cx);
12016 let mut buffer_highlights = this
12017 .document_highlights_for_position(selection.head(), &buffer)
12018 .filter(|highlight| {
12019 highlight.start.excerpt_id == selection.head().excerpt_id
12020 && highlight.end.excerpt_id == selection.head().excerpt_id
12021 });
12022 buffer_highlights
12023 .next()
12024 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12025 })?
12026 };
12027 if let Some(rename_range) = rename_range {
12028 this.update_in(&mut cx, |this, window, cx| {
12029 let snapshot = cursor_buffer.read(cx).snapshot();
12030 let rename_buffer_range = rename_range.to_offset(&snapshot);
12031 let cursor_offset_in_rename_range =
12032 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12033 let cursor_offset_in_rename_range_end =
12034 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12035
12036 this.take_rename(false, window, cx);
12037 let buffer = this.buffer.read(cx).read(cx);
12038 let cursor_offset = selection.head().to_offset(&buffer);
12039 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12040 let rename_end = rename_start + rename_buffer_range.len();
12041 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12042 let mut old_highlight_id = None;
12043 let old_name: Arc<str> = buffer
12044 .chunks(rename_start..rename_end, true)
12045 .map(|chunk| {
12046 if old_highlight_id.is_none() {
12047 old_highlight_id = chunk.syntax_highlight_id;
12048 }
12049 chunk.text
12050 })
12051 .collect::<String>()
12052 .into();
12053
12054 drop(buffer);
12055
12056 // Position the selection in the rename editor so that it matches the current selection.
12057 this.show_local_selections = false;
12058 let rename_editor = cx.new(|cx| {
12059 let mut editor = Editor::single_line(window, cx);
12060 editor.buffer.update(cx, |buffer, cx| {
12061 buffer.edit([(0..0, old_name.clone())], None, cx)
12062 });
12063 let rename_selection_range = match cursor_offset_in_rename_range
12064 .cmp(&cursor_offset_in_rename_range_end)
12065 {
12066 Ordering::Equal => {
12067 editor.select_all(&SelectAll, window, cx);
12068 return editor;
12069 }
12070 Ordering::Less => {
12071 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12072 }
12073 Ordering::Greater => {
12074 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12075 }
12076 };
12077 if rename_selection_range.end > old_name.len() {
12078 editor.select_all(&SelectAll, window, cx);
12079 } else {
12080 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12081 s.select_ranges([rename_selection_range]);
12082 });
12083 }
12084 editor
12085 });
12086 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12087 if e == &EditorEvent::Focused {
12088 cx.emit(EditorEvent::FocusedIn)
12089 }
12090 })
12091 .detach();
12092
12093 let write_highlights =
12094 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12095 let read_highlights =
12096 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12097 let ranges = write_highlights
12098 .iter()
12099 .flat_map(|(_, ranges)| ranges.iter())
12100 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12101 .cloned()
12102 .collect();
12103
12104 this.highlight_text::<Rename>(
12105 ranges,
12106 HighlightStyle {
12107 fade_out: Some(0.6),
12108 ..Default::default()
12109 },
12110 cx,
12111 );
12112 let rename_focus_handle = rename_editor.focus_handle(cx);
12113 window.focus(&rename_focus_handle);
12114 let block_id = this.insert_blocks(
12115 [BlockProperties {
12116 style: BlockStyle::Flex,
12117 placement: BlockPlacement::Below(range.start),
12118 height: 1,
12119 render: Arc::new({
12120 let rename_editor = rename_editor.clone();
12121 move |cx: &mut BlockContext| {
12122 let mut text_style = cx.editor_style.text.clone();
12123 if let Some(highlight_style) = old_highlight_id
12124 .and_then(|h| h.style(&cx.editor_style.syntax))
12125 {
12126 text_style = text_style.highlight(highlight_style);
12127 }
12128 div()
12129 .block_mouse_down()
12130 .pl(cx.anchor_x)
12131 .child(EditorElement::new(
12132 &rename_editor,
12133 EditorStyle {
12134 background: cx.theme().system().transparent,
12135 local_player: cx.editor_style.local_player,
12136 text: text_style,
12137 scrollbar_width: cx.editor_style.scrollbar_width,
12138 syntax: cx.editor_style.syntax.clone(),
12139 status: cx.editor_style.status.clone(),
12140 inlay_hints_style: HighlightStyle {
12141 font_weight: Some(FontWeight::BOLD),
12142 ..make_inlay_hints_style(cx.app)
12143 },
12144 inline_completion_styles: make_suggestion_styles(
12145 cx.app,
12146 ),
12147 ..EditorStyle::default()
12148 },
12149 ))
12150 .into_any_element()
12151 }
12152 }),
12153 priority: 0,
12154 }],
12155 Some(Autoscroll::fit()),
12156 cx,
12157 )[0];
12158 this.pending_rename = Some(RenameState {
12159 range,
12160 old_name,
12161 editor: rename_editor,
12162 block_id,
12163 });
12164 })?;
12165 }
12166
12167 Ok(())
12168 }))
12169 }
12170
12171 pub fn confirm_rename(
12172 &mut self,
12173 _: &ConfirmRename,
12174 window: &mut Window,
12175 cx: &mut Context<Self>,
12176 ) -> Option<Task<Result<()>>> {
12177 let rename = self.take_rename(false, window, cx)?;
12178 let workspace = self.workspace()?.downgrade();
12179 let (buffer, start) = self
12180 .buffer
12181 .read(cx)
12182 .text_anchor_for_position(rename.range.start, cx)?;
12183 let (end_buffer, _) = self
12184 .buffer
12185 .read(cx)
12186 .text_anchor_for_position(rename.range.end, cx)?;
12187 if buffer != end_buffer {
12188 return None;
12189 }
12190
12191 let old_name = rename.old_name;
12192 let new_name = rename.editor.read(cx).text(cx);
12193
12194 let rename = self.semantics_provider.as_ref()?.perform_rename(
12195 &buffer,
12196 start,
12197 new_name.clone(),
12198 cx,
12199 )?;
12200
12201 Some(cx.spawn_in(window, |editor, mut cx| async move {
12202 let project_transaction = rename.await?;
12203 Self::open_project_transaction(
12204 &editor,
12205 workspace,
12206 project_transaction,
12207 format!("Rename: {} → {}", old_name, new_name),
12208 cx.clone(),
12209 )
12210 .await?;
12211
12212 editor.update(&mut cx, |editor, cx| {
12213 editor.refresh_document_highlights(cx);
12214 })?;
12215 Ok(())
12216 }))
12217 }
12218
12219 fn take_rename(
12220 &mut self,
12221 moving_cursor: bool,
12222 window: &mut Window,
12223 cx: &mut Context<Self>,
12224 ) -> Option<RenameState> {
12225 let rename = self.pending_rename.take()?;
12226 if rename.editor.focus_handle(cx).is_focused(window) {
12227 window.focus(&self.focus_handle);
12228 }
12229
12230 self.remove_blocks(
12231 [rename.block_id].into_iter().collect(),
12232 Some(Autoscroll::fit()),
12233 cx,
12234 );
12235 self.clear_highlights::<Rename>(cx);
12236 self.show_local_selections = true;
12237
12238 if moving_cursor {
12239 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12240 editor.selections.newest::<usize>(cx).head()
12241 });
12242
12243 // Update the selection to match the position of the selection inside
12244 // the rename editor.
12245 let snapshot = self.buffer.read(cx).read(cx);
12246 let rename_range = rename.range.to_offset(&snapshot);
12247 let cursor_in_editor = snapshot
12248 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12249 .min(rename_range.end);
12250 drop(snapshot);
12251
12252 self.change_selections(None, window, cx, |s| {
12253 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12254 });
12255 } else {
12256 self.refresh_document_highlights(cx);
12257 }
12258
12259 Some(rename)
12260 }
12261
12262 pub fn pending_rename(&self) -> Option<&RenameState> {
12263 self.pending_rename.as_ref()
12264 }
12265
12266 fn format(
12267 &mut self,
12268 _: &Format,
12269 window: &mut Window,
12270 cx: &mut Context<Self>,
12271 ) -> Option<Task<Result<()>>> {
12272 let project = match &self.project {
12273 Some(project) => project.clone(),
12274 None => return None,
12275 };
12276
12277 Some(self.perform_format(
12278 project,
12279 FormatTrigger::Manual,
12280 FormatTarget::Buffers,
12281 window,
12282 cx,
12283 ))
12284 }
12285
12286 fn format_selections(
12287 &mut self,
12288 _: &FormatSelections,
12289 window: &mut Window,
12290 cx: &mut Context<Self>,
12291 ) -> Option<Task<Result<()>>> {
12292 let project = match &self.project {
12293 Some(project) => project.clone(),
12294 None => return None,
12295 };
12296
12297 let ranges = self
12298 .selections
12299 .all_adjusted(cx)
12300 .into_iter()
12301 .map(|selection| selection.range())
12302 .collect_vec();
12303
12304 Some(self.perform_format(
12305 project,
12306 FormatTrigger::Manual,
12307 FormatTarget::Ranges(ranges),
12308 window,
12309 cx,
12310 ))
12311 }
12312
12313 fn perform_format(
12314 &mut self,
12315 project: Entity<Project>,
12316 trigger: FormatTrigger,
12317 target: FormatTarget,
12318 window: &mut Window,
12319 cx: &mut Context<Self>,
12320 ) -> Task<Result<()>> {
12321 let buffer = self.buffer.clone();
12322 let (buffers, target) = match target {
12323 FormatTarget::Buffers => {
12324 let mut buffers = buffer.read(cx).all_buffers();
12325 if trigger == FormatTrigger::Save {
12326 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12327 }
12328 (buffers, LspFormatTarget::Buffers)
12329 }
12330 FormatTarget::Ranges(selection_ranges) => {
12331 let multi_buffer = buffer.read(cx);
12332 let snapshot = multi_buffer.read(cx);
12333 let mut buffers = HashSet::default();
12334 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12335 BTreeMap::new();
12336 for selection_range in selection_ranges {
12337 for (buffer, buffer_range, _) in
12338 snapshot.range_to_buffer_ranges(selection_range)
12339 {
12340 let buffer_id = buffer.remote_id();
12341 let start = buffer.anchor_before(buffer_range.start);
12342 let end = buffer.anchor_after(buffer_range.end);
12343 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12344 buffer_id_to_ranges
12345 .entry(buffer_id)
12346 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12347 .or_insert_with(|| vec![start..end]);
12348 }
12349 }
12350 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12351 }
12352 };
12353
12354 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12355 let format = project.update(cx, |project, cx| {
12356 project.format(buffers, target, true, trigger, cx)
12357 });
12358
12359 cx.spawn_in(window, |_, mut cx| async move {
12360 let transaction = futures::select_biased! {
12361 () = timeout => {
12362 log::warn!("timed out waiting for formatting");
12363 None
12364 }
12365 transaction = format.log_err().fuse() => transaction,
12366 };
12367
12368 buffer
12369 .update(&mut cx, |buffer, cx| {
12370 if let Some(transaction) = transaction {
12371 if !buffer.is_singleton() {
12372 buffer.push_transaction(&transaction.0, cx);
12373 }
12374 }
12375
12376 cx.notify();
12377 })
12378 .ok();
12379
12380 Ok(())
12381 })
12382 }
12383
12384 fn restart_language_server(
12385 &mut self,
12386 _: &RestartLanguageServer,
12387 _: &mut Window,
12388 cx: &mut Context<Self>,
12389 ) {
12390 if let Some(project) = self.project.clone() {
12391 self.buffer.update(cx, |multi_buffer, cx| {
12392 project.update(cx, |project, cx| {
12393 project.restart_language_servers_for_buffers(
12394 multi_buffer.all_buffers().into_iter().collect(),
12395 cx,
12396 );
12397 });
12398 })
12399 }
12400 }
12401
12402 fn cancel_language_server_work(
12403 workspace: &mut Workspace,
12404 _: &actions::CancelLanguageServerWork,
12405 _: &mut Window,
12406 cx: &mut Context<Workspace>,
12407 ) {
12408 let project = workspace.project();
12409 let buffers = workspace
12410 .active_item(cx)
12411 .and_then(|item| item.act_as::<Editor>(cx))
12412 .map_or(HashSet::default(), |editor| {
12413 editor.read(cx).buffer.read(cx).all_buffers()
12414 });
12415 project.update(cx, |project, cx| {
12416 project.cancel_language_server_work_for_buffers(buffers, cx);
12417 });
12418 }
12419
12420 fn show_character_palette(
12421 &mut self,
12422 _: &ShowCharacterPalette,
12423 window: &mut Window,
12424 _: &mut Context<Self>,
12425 ) {
12426 window.show_character_palette();
12427 }
12428
12429 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12430 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12431 let buffer = self.buffer.read(cx).snapshot(cx);
12432 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12433 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12434 let is_valid = buffer
12435 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12436 .any(|entry| {
12437 entry.diagnostic.is_primary
12438 && !entry.range.is_empty()
12439 && entry.range.start == primary_range_start
12440 && entry.diagnostic.message == active_diagnostics.primary_message
12441 });
12442
12443 if is_valid != active_diagnostics.is_valid {
12444 active_diagnostics.is_valid = is_valid;
12445 let mut new_styles = HashMap::default();
12446 for (block_id, diagnostic) in &active_diagnostics.blocks {
12447 new_styles.insert(
12448 *block_id,
12449 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12450 );
12451 }
12452 self.display_map.update(cx, |display_map, _cx| {
12453 display_map.replace_blocks(new_styles)
12454 });
12455 }
12456 }
12457 }
12458
12459 fn activate_diagnostics(
12460 &mut self,
12461 buffer_id: BufferId,
12462 group_id: usize,
12463 window: &mut Window,
12464 cx: &mut Context<Self>,
12465 ) {
12466 self.dismiss_diagnostics(cx);
12467 let snapshot = self.snapshot(window, cx);
12468 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12469 let buffer = self.buffer.read(cx).snapshot(cx);
12470
12471 let mut primary_range = None;
12472 let mut primary_message = None;
12473 let diagnostic_group = buffer
12474 .diagnostic_group(buffer_id, group_id)
12475 .filter_map(|entry| {
12476 let start = entry.range.start;
12477 let end = entry.range.end;
12478 if snapshot.is_line_folded(MultiBufferRow(start.row))
12479 && (start.row == end.row
12480 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12481 {
12482 return None;
12483 }
12484 if entry.diagnostic.is_primary {
12485 primary_range = Some(entry.range.clone());
12486 primary_message = Some(entry.diagnostic.message.clone());
12487 }
12488 Some(entry)
12489 })
12490 .collect::<Vec<_>>();
12491 let primary_range = primary_range?;
12492 let primary_message = primary_message?;
12493
12494 let blocks = display_map
12495 .insert_blocks(
12496 diagnostic_group.iter().map(|entry| {
12497 let diagnostic = entry.diagnostic.clone();
12498 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12499 BlockProperties {
12500 style: BlockStyle::Fixed,
12501 placement: BlockPlacement::Below(
12502 buffer.anchor_after(entry.range.start),
12503 ),
12504 height: message_height,
12505 render: diagnostic_block_renderer(diagnostic, None, true, true),
12506 priority: 0,
12507 }
12508 }),
12509 cx,
12510 )
12511 .into_iter()
12512 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12513 .collect();
12514
12515 Some(ActiveDiagnosticGroup {
12516 primary_range: buffer.anchor_before(primary_range.start)
12517 ..buffer.anchor_after(primary_range.end),
12518 primary_message,
12519 group_id,
12520 blocks,
12521 is_valid: true,
12522 })
12523 });
12524 }
12525
12526 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12527 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12528 self.display_map.update(cx, |display_map, cx| {
12529 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12530 });
12531 cx.notify();
12532 }
12533 }
12534
12535 /// Disable inline diagnostics rendering for this editor.
12536 pub fn disable_inline_diagnostics(&mut self) {
12537 self.inline_diagnostics_enabled = false;
12538 self.inline_diagnostics_update = Task::ready(());
12539 self.inline_diagnostics.clear();
12540 }
12541
12542 pub fn inline_diagnostics_enabled(&self) -> bool {
12543 self.inline_diagnostics_enabled
12544 }
12545
12546 pub fn show_inline_diagnostics(&self) -> bool {
12547 self.show_inline_diagnostics
12548 }
12549
12550 pub fn toggle_inline_diagnostics(
12551 &mut self,
12552 _: &ToggleInlineDiagnostics,
12553 window: &mut Window,
12554 cx: &mut Context<'_, Editor>,
12555 ) {
12556 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12557 self.refresh_inline_diagnostics(false, window, cx);
12558 }
12559
12560 fn refresh_inline_diagnostics(
12561 &mut self,
12562 debounce: bool,
12563 window: &mut Window,
12564 cx: &mut Context<Self>,
12565 ) {
12566 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12567 self.inline_diagnostics_update = Task::ready(());
12568 self.inline_diagnostics.clear();
12569 return;
12570 }
12571
12572 let debounce_ms = ProjectSettings::get_global(cx)
12573 .diagnostics
12574 .inline
12575 .update_debounce_ms;
12576 let debounce = if debounce && debounce_ms > 0 {
12577 Some(Duration::from_millis(debounce_ms))
12578 } else {
12579 None
12580 };
12581 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12582 if let Some(debounce) = debounce {
12583 cx.background_executor().timer(debounce).await;
12584 }
12585 let Some(snapshot) = editor
12586 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12587 .ok()
12588 else {
12589 return;
12590 };
12591
12592 let new_inline_diagnostics = cx
12593 .background_spawn(async move {
12594 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12595 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12596 let message = diagnostic_entry
12597 .diagnostic
12598 .message
12599 .split_once('\n')
12600 .map(|(line, _)| line)
12601 .map(SharedString::new)
12602 .unwrap_or_else(|| {
12603 SharedString::from(diagnostic_entry.diagnostic.message)
12604 });
12605 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12606 let (Ok(i) | Err(i)) = inline_diagnostics
12607 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12608 inline_diagnostics.insert(
12609 i,
12610 (
12611 start_anchor,
12612 InlineDiagnostic {
12613 message,
12614 group_id: diagnostic_entry.diagnostic.group_id,
12615 start: diagnostic_entry.range.start.to_point(&snapshot),
12616 is_primary: diagnostic_entry.diagnostic.is_primary,
12617 severity: diagnostic_entry.diagnostic.severity,
12618 },
12619 ),
12620 );
12621 }
12622 inline_diagnostics
12623 })
12624 .await;
12625
12626 editor
12627 .update(&mut cx, |editor, cx| {
12628 editor.inline_diagnostics = new_inline_diagnostics;
12629 cx.notify();
12630 })
12631 .ok();
12632 });
12633 }
12634
12635 pub fn set_selections_from_remote(
12636 &mut self,
12637 selections: Vec<Selection<Anchor>>,
12638 pending_selection: Option<Selection<Anchor>>,
12639 window: &mut Window,
12640 cx: &mut Context<Self>,
12641 ) {
12642 let old_cursor_position = self.selections.newest_anchor().head();
12643 self.selections.change_with(cx, |s| {
12644 s.select_anchors(selections);
12645 if let Some(pending_selection) = pending_selection {
12646 s.set_pending(pending_selection, SelectMode::Character);
12647 } else {
12648 s.clear_pending();
12649 }
12650 });
12651 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12652 }
12653
12654 fn push_to_selection_history(&mut self) {
12655 self.selection_history.push(SelectionHistoryEntry {
12656 selections: self.selections.disjoint_anchors(),
12657 select_next_state: self.select_next_state.clone(),
12658 select_prev_state: self.select_prev_state.clone(),
12659 add_selections_state: self.add_selections_state.clone(),
12660 });
12661 }
12662
12663 pub fn transact(
12664 &mut self,
12665 window: &mut Window,
12666 cx: &mut Context<Self>,
12667 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12668 ) -> Option<TransactionId> {
12669 self.start_transaction_at(Instant::now(), window, cx);
12670 update(self, window, cx);
12671 self.end_transaction_at(Instant::now(), cx)
12672 }
12673
12674 pub fn start_transaction_at(
12675 &mut self,
12676 now: Instant,
12677 window: &mut Window,
12678 cx: &mut Context<Self>,
12679 ) {
12680 self.end_selection(window, cx);
12681 if let Some(tx_id) = self
12682 .buffer
12683 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12684 {
12685 self.selection_history
12686 .insert_transaction(tx_id, self.selections.disjoint_anchors());
12687 cx.emit(EditorEvent::TransactionBegun {
12688 transaction_id: tx_id,
12689 })
12690 }
12691 }
12692
12693 pub fn end_transaction_at(
12694 &mut self,
12695 now: Instant,
12696 cx: &mut Context<Self>,
12697 ) -> Option<TransactionId> {
12698 if let Some(transaction_id) = self
12699 .buffer
12700 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12701 {
12702 if let Some((_, end_selections)) =
12703 self.selection_history.transaction_mut(transaction_id)
12704 {
12705 *end_selections = Some(self.selections.disjoint_anchors());
12706 } else {
12707 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12708 }
12709
12710 cx.emit(EditorEvent::Edited { transaction_id });
12711 Some(transaction_id)
12712 } else {
12713 None
12714 }
12715 }
12716
12717 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12718 if self.selection_mark_mode {
12719 self.change_selections(None, window, cx, |s| {
12720 s.move_with(|_, sel| {
12721 sel.collapse_to(sel.head(), SelectionGoal::None);
12722 });
12723 })
12724 }
12725 self.selection_mark_mode = true;
12726 cx.notify();
12727 }
12728
12729 pub fn swap_selection_ends(
12730 &mut self,
12731 _: &actions::SwapSelectionEnds,
12732 window: &mut Window,
12733 cx: &mut Context<Self>,
12734 ) {
12735 self.change_selections(None, window, cx, |s| {
12736 s.move_with(|_, sel| {
12737 if sel.start != sel.end {
12738 sel.reversed = !sel.reversed
12739 }
12740 });
12741 });
12742 self.request_autoscroll(Autoscroll::newest(), cx);
12743 cx.notify();
12744 }
12745
12746 pub fn toggle_fold(
12747 &mut self,
12748 _: &actions::ToggleFold,
12749 window: &mut Window,
12750 cx: &mut Context<Self>,
12751 ) {
12752 if self.is_singleton(cx) {
12753 let selection = self.selections.newest::<Point>(cx);
12754
12755 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12756 let range = if selection.is_empty() {
12757 let point = selection.head().to_display_point(&display_map);
12758 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12759 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12760 .to_point(&display_map);
12761 start..end
12762 } else {
12763 selection.range()
12764 };
12765 if display_map.folds_in_range(range).next().is_some() {
12766 self.unfold_lines(&Default::default(), window, cx)
12767 } else {
12768 self.fold(&Default::default(), window, cx)
12769 }
12770 } else {
12771 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12772 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12773 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12774 .map(|(snapshot, _, _)| snapshot.remote_id())
12775 .collect();
12776
12777 for buffer_id in buffer_ids {
12778 if self.is_buffer_folded(buffer_id, cx) {
12779 self.unfold_buffer(buffer_id, cx);
12780 } else {
12781 self.fold_buffer(buffer_id, cx);
12782 }
12783 }
12784 }
12785 }
12786
12787 pub fn toggle_fold_recursive(
12788 &mut self,
12789 _: &actions::ToggleFoldRecursive,
12790 window: &mut Window,
12791 cx: &mut Context<Self>,
12792 ) {
12793 let selection = self.selections.newest::<Point>(cx);
12794
12795 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12796 let range = if selection.is_empty() {
12797 let point = selection.head().to_display_point(&display_map);
12798 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12799 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12800 .to_point(&display_map);
12801 start..end
12802 } else {
12803 selection.range()
12804 };
12805 if display_map.folds_in_range(range).next().is_some() {
12806 self.unfold_recursive(&Default::default(), window, cx)
12807 } else {
12808 self.fold_recursive(&Default::default(), window, cx)
12809 }
12810 }
12811
12812 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12813 if self.is_singleton(cx) {
12814 let mut to_fold = Vec::new();
12815 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12816 let selections = self.selections.all_adjusted(cx);
12817
12818 for selection in selections {
12819 let range = selection.range().sorted();
12820 let buffer_start_row = range.start.row;
12821
12822 if range.start.row != range.end.row {
12823 let mut found = false;
12824 let mut row = range.start.row;
12825 while row <= range.end.row {
12826 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12827 {
12828 found = true;
12829 row = crease.range().end.row + 1;
12830 to_fold.push(crease);
12831 } else {
12832 row += 1
12833 }
12834 }
12835 if found {
12836 continue;
12837 }
12838 }
12839
12840 for row in (0..=range.start.row).rev() {
12841 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12842 if crease.range().end.row >= buffer_start_row {
12843 to_fold.push(crease);
12844 if row <= range.start.row {
12845 break;
12846 }
12847 }
12848 }
12849 }
12850 }
12851
12852 self.fold_creases(to_fold, true, window, cx);
12853 } else {
12854 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12855
12856 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12857 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12858 .map(|(snapshot, _, _)| snapshot.remote_id())
12859 .collect();
12860 for buffer_id in buffer_ids {
12861 self.fold_buffer(buffer_id, cx);
12862 }
12863 }
12864 }
12865
12866 fn fold_at_level(
12867 &mut self,
12868 fold_at: &FoldAtLevel,
12869 window: &mut Window,
12870 cx: &mut Context<Self>,
12871 ) {
12872 if !self.buffer.read(cx).is_singleton() {
12873 return;
12874 }
12875
12876 let fold_at_level = fold_at.0;
12877 let snapshot = self.buffer.read(cx).snapshot(cx);
12878 let mut to_fold = Vec::new();
12879 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12880
12881 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12882 while start_row < end_row {
12883 match self
12884 .snapshot(window, cx)
12885 .crease_for_buffer_row(MultiBufferRow(start_row))
12886 {
12887 Some(crease) => {
12888 let nested_start_row = crease.range().start.row + 1;
12889 let nested_end_row = crease.range().end.row;
12890
12891 if current_level < fold_at_level {
12892 stack.push((nested_start_row, nested_end_row, current_level + 1));
12893 } else if current_level == fold_at_level {
12894 to_fold.push(crease);
12895 }
12896
12897 start_row = nested_end_row + 1;
12898 }
12899 None => start_row += 1,
12900 }
12901 }
12902 }
12903
12904 self.fold_creases(to_fold, true, window, cx);
12905 }
12906
12907 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12908 if self.buffer.read(cx).is_singleton() {
12909 let mut fold_ranges = Vec::new();
12910 let snapshot = self.buffer.read(cx).snapshot(cx);
12911
12912 for row in 0..snapshot.max_row().0 {
12913 if let Some(foldable_range) = self
12914 .snapshot(window, cx)
12915 .crease_for_buffer_row(MultiBufferRow(row))
12916 {
12917 fold_ranges.push(foldable_range);
12918 }
12919 }
12920
12921 self.fold_creases(fold_ranges, true, window, cx);
12922 } else {
12923 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12924 editor
12925 .update_in(&mut cx, |editor, _, cx| {
12926 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12927 editor.fold_buffer(buffer_id, cx);
12928 }
12929 })
12930 .ok();
12931 });
12932 }
12933 }
12934
12935 pub fn fold_function_bodies(
12936 &mut self,
12937 _: &actions::FoldFunctionBodies,
12938 window: &mut Window,
12939 cx: &mut Context<Self>,
12940 ) {
12941 let snapshot = self.buffer.read(cx).snapshot(cx);
12942
12943 let ranges = snapshot
12944 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12945 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12946 .collect::<Vec<_>>();
12947
12948 let creases = ranges
12949 .into_iter()
12950 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12951 .collect();
12952
12953 self.fold_creases(creases, true, window, cx);
12954 }
12955
12956 pub fn fold_recursive(
12957 &mut self,
12958 _: &actions::FoldRecursive,
12959 window: &mut Window,
12960 cx: &mut Context<Self>,
12961 ) {
12962 let mut to_fold = Vec::new();
12963 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12964 let selections = self.selections.all_adjusted(cx);
12965
12966 for selection in selections {
12967 let range = selection.range().sorted();
12968 let buffer_start_row = range.start.row;
12969
12970 if range.start.row != range.end.row {
12971 let mut found = false;
12972 for row in range.start.row..=range.end.row {
12973 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12974 found = true;
12975 to_fold.push(crease);
12976 }
12977 }
12978 if found {
12979 continue;
12980 }
12981 }
12982
12983 for row in (0..=range.start.row).rev() {
12984 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12985 if crease.range().end.row >= buffer_start_row {
12986 to_fold.push(crease);
12987 } else {
12988 break;
12989 }
12990 }
12991 }
12992 }
12993
12994 self.fold_creases(to_fold, true, window, cx);
12995 }
12996
12997 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12998 let buffer_row = fold_at.buffer_row;
12999 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13000
13001 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13002 let autoscroll = self
13003 .selections
13004 .all::<Point>(cx)
13005 .iter()
13006 .any(|selection| crease.range().overlaps(&selection.range()));
13007
13008 self.fold_creases(vec![crease], autoscroll, window, cx);
13009 }
13010 }
13011
13012 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13013 if self.is_singleton(cx) {
13014 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13015 let buffer = &display_map.buffer_snapshot;
13016 let selections = self.selections.all::<Point>(cx);
13017 let ranges = selections
13018 .iter()
13019 .map(|s| {
13020 let range = s.display_range(&display_map).sorted();
13021 let mut start = range.start.to_point(&display_map);
13022 let mut end = range.end.to_point(&display_map);
13023 start.column = 0;
13024 end.column = buffer.line_len(MultiBufferRow(end.row));
13025 start..end
13026 })
13027 .collect::<Vec<_>>();
13028
13029 self.unfold_ranges(&ranges, true, true, cx);
13030 } else {
13031 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13032 let buffer_ids: HashSet<_> = multi_buffer_snapshot
13033 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13034 .map(|(snapshot, _, _)| snapshot.remote_id())
13035 .collect();
13036 for buffer_id in buffer_ids {
13037 self.unfold_buffer(buffer_id, cx);
13038 }
13039 }
13040 }
13041
13042 pub fn unfold_recursive(
13043 &mut self,
13044 _: &UnfoldRecursive,
13045 _window: &mut Window,
13046 cx: &mut Context<Self>,
13047 ) {
13048 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13049 let selections = self.selections.all::<Point>(cx);
13050 let ranges = selections
13051 .iter()
13052 .map(|s| {
13053 let mut range = s.display_range(&display_map).sorted();
13054 *range.start.column_mut() = 0;
13055 *range.end.column_mut() = display_map.line_len(range.end.row());
13056 let start = range.start.to_point(&display_map);
13057 let end = range.end.to_point(&display_map);
13058 start..end
13059 })
13060 .collect::<Vec<_>>();
13061
13062 self.unfold_ranges(&ranges, true, true, cx);
13063 }
13064
13065 pub fn unfold_at(
13066 &mut self,
13067 unfold_at: &UnfoldAt,
13068 _window: &mut Window,
13069 cx: &mut Context<Self>,
13070 ) {
13071 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13072
13073 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13074 ..Point::new(
13075 unfold_at.buffer_row.0,
13076 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13077 );
13078
13079 let autoscroll = self
13080 .selections
13081 .all::<Point>(cx)
13082 .iter()
13083 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13084
13085 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13086 }
13087
13088 pub fn unfold_all(
13089 &mut self,
13090 _: &actions::UnfoldAll,
13091 _window: &mut Window,
13092 cx: &mut Context<Self>,
13093 ) {
13094 if self.buffer.read(cx).is_singleton() {
13095 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13096 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13097 } else {
13098 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13099 editor
13100 .update(&mut cx, |editor, cx| {
13101 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13102 editor.unfold_buffer(buffer_id, cx);
13103 }
13104 })
13105 .ok();
13106 });
13107 }
13108 }
13109
13110 pub fn fold_selected_ranges(
13111 &mut self,
13112 _: &FoldSelectedRanges,
13113 window: &mut Window,
13114 cx: &mut Context<Self>,
13115 ) {
13116 let selections = self.selections.all::<Point>(cx);
13117 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13118 let line_mode = self.selections.line_mode;
13119 let ranges = selections
13120 .into_iter()
13121 .map(|s| {
13122 if line_mode {
13123 let start = Point::new(s.start.row, 0);
13124 let end = Point::new(
13125 s.end.row,
13126 display_map
13127 .buffer_snapshot
13128 .line_len(MultiBufferRow(s.end.row)),
13129 );
13130 Crease::simple(start..end, display_map.fold_placeholder.clone())
13131 } else {
13132 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13133 }
13134 })
13135 .collect::<Vec<_>>();
13136 self.fold_creases(ranges, true, window, cx);
13137 }
13138
13139 pub fn fold_ranges<T: ToOffset + Clone>(
13140 &mut self,
13141 ranges: Vec<Range<T>>,
13142 auto_scroll: bool,
13143 window: &mut Window,
13144 cx: &mut Context<Self>,
13145 ) {
13146 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13147 let ranges = ranges
13148 .into_iter()
13149 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13150 .collect::<Vec<_>>();
13151 self.fold_creases(ranges, auto_scroll, window, cx);
13152 }
13153
13154 pub fn fold_creases<T: ToOffset + Clone>(
13155 &mut self,
13156 creases: Vec<Crease<T>>,
13157 auto_scroll: bool,
13158 window: &mut Window,
13159 cx: &mut Context<Self>,
13160 ) {
13161 if creases.is_empty() {
13162 return;
13163 }
13164
13165 let mut buffers_affected = HashSet::default();
13166 let multi_buffer = self.buffer().read(cx);
13167 for crease in &creases {
13168 if let Some((_, buffer, _)) =
13169 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13170 {
13171 buffers_affected.insert(buffer.read(cx).remote_id());
13172 };
13173 }
13174
13175 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13176
13177 if auto_scroll {
13178 self.request_autoscroll(Autoscroll::fit(), cx);
13179 }
13180
13181 cx.notify();
13182
13183 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13184 // Clear diagnostics block when folding a range that contains it.
13185 let snapshot = self.snapshot(window, cx);
13186 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13187 drop(snapshot);
13188 self.active_diagnostics = Some(active_diagnostics);
13189 self.dismiss_diagnostics(cx);
13190 } else {
13191 self.active_diagnostics = Some(active_diagnostics);
13192 }
13193 }
13194
13195 self.scrollbar_marker_state.dirty = true;
13196 }
13197
13198 /// Removes any folds whose ranges intersect any of the given ranges.
13199 pub fn unfold_ranges<T: ToOffset + Clone>(
13200 &mut self,
13201 ranges: &[Range<T>],
13202 inclusive: bool,
13203 auto_scroll: bool,
13204 cx: &mut Context<Self>,
13205 ) {
13206 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13207 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13208 });
13209 }
13210
13211 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13212 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13213 return;
13214 }
13215 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13216 self.display_map
13217 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13218 cx.emit(EditorEvent::BufferFoldToggled {
13219 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13220 folded: true,
13221 });
13222 cx.notify();
13223 }
13224
13225 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13226 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13227 return;
13228 }
13229 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13230 self.display_map.update(cx, |display_map, cx| {
13231 display_map.unfold_buffer(buffer_id, cx);
13232 });
13233 cx.emit(EditorEvent::BufferFoldToggled {
13234 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13235 folded: false,
13236 });
13237 cx.notify();
13238 }
13239
13240 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13241 self.display_map.read(cx).is_buffer_folded(buffer)
13242 }
13243
13244 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13245 self.display_map.read(cx).folded_buffers()
13246 }
13247
13248 /// Removes any folds with the given ranges.
13249 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13250 &mut self,
13251 ranges: &[Range<T>],
13252 type_id: TypeId,
13253 auto_scroll: bool,
13254 cx: &mut Context<Self>,
13255 ) {
13256 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13257 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13258 });
13259 }
13260
13261 fn remove_folds_with<T: ToOffset + Clone>(
13262 &mut self,
13263 ranges: &[Range<T>],
13264 auto_scroll: bool,
13265 cx: &mut Context<Self>,
13266 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13267 ) {
13268 if ranges.is_empty() {
13269 return;
13270 }
13271
13272 let mut buffers_affected = HashSet::default();
13273 let multi_buffer = self.buffer().read(cx);
13274 for range in ranges {
13275 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13276 buffers_affected.insert(buffer.read(cx).remote_id());
13277 };
13278 }
13279
13280 self.display_map.update(cx, update);
13281
13282 if auto_scroll {
13283 self.request_autoscroll(Autoscroll::fit(), cx);
13284 }
13285
13286 cx.notify();
13287 self.scrollbar_marker_state.dirty = true;
13288 self.active_indent_guides_state.dirty = true;
13289 }
13290
13291 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13292 self.display_map.read(cx).fold_placeholder.clone()
13293 }
13294
13295 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13296 self.buffer.update(cx, |buffer, cx| {
13297 buffer.set_all_diff_hunks_expanded(cx);
13298 });
13299 }
13300
13301 pub fn expand_all_diff_hunks(
13302 &mut self,
13303 _: &ExpandAllDiffHunks,
13304 _window: &mut Window,
13305 cx: &mut Context<Self>,
13306 ) {
13307 self.buffer.update(cx, |buffer, cx| {
13308 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13309 });
13310 }
13311
13312 pub fn toggle_selected_diff_hunks(
13313 &mut self,
13314 _: &ToggleSelectedDiffHunks,
13315 _window: &mut Window,
13316 cx: &mut Context<Self>,
13317 ) {
13318 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13319 self.toggle_diff_hunks_in_ranges(ranges, cx);
13320 }
13321
13322 pub fn diff_hunks_in_ranges<'a>(
13323 &'a self,
13324 ranges: &'a [Range<Anchor>],
13325 buffer: &'a MultiBufferSnapshot,
13326 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13327 ranges.iter().flat_map(move |range| {
13328 let end_excerpt_id = range.end.excerpt_id;
13329 let range = range.to_point(buffer);
13330 let mut peek_end = range.end;
13331 if range.end.row < buffer.max_row().0 {
13332 peek_end = Point::new(range.end.row + 1, 0);
13333 }
13334 buffer
13335 .diff_hunks_in_range(range.start..peek_end)
13336 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13337 })
13338 }
13339
13340 pub fn has_stageable_diff_hunks_in_ranges(
13341 &self,
13342 ranges: &[Range<Anchor>],
13343 snapshot: &MultiBufferSnapshot,
13344 ) -> bool {
13345 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13346 hunks.any(|hunk| hunk.secondary_status != DiffHunkSecondaryStatus::None)
13347 }
13348
13349 pub fn toggle_staged_selected_diff_hunks(
13350 &mut self,
13351 _: &::git::ToggleStaged,
13352 _window: &mut Window,
13353 cx: &mut Context<Self>,
13354 ) {
13355 let snapshot = self.buffer.read(cx).snapshot(cx);
13356 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13357 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13358 self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13359 }
13360
13361 pub fn stage_and_next(
13362 &mut self,
13363 _: &::git::StageAndNext,
13364 window: &mut Window,
13365 cx: &mut Context<Self>,
13366 ) {
13367 self.do_stage_or_unstage_and_next(true, window, cx);
13368 }
13369
13370 pub fn unstage_and_next(
13371 &mut self,
13372 _: &::git::UnstageAndNext,
13373 window: &mut Window,
13374 cx: &mut Context<Self>,
13375 ) {
13376 self.do_stage_or_unstage_and_next(false, window, cx);
13377 }
13378
13379 pub fn stage_or_unstage_diff_hunks(
13380 &mut self,
13381 stage: bool,
13382 ranges: &[Range<Anchor>],
13383 cx: &mut Context<Self>,
13384 ) {
13385 let snapshot = self.buffer.read(cx).snapshot(cx);
13386 let Some(project) = &self.project else {
13387 return;
13388 };
13389
13390 let chunk_by = self
13391 .diff_hunks_in_ranges(&ranges, &snapshot)
13392 .chunk_by(|hunk| hunk.buffer_id);
13393 for (buffer_id, hunks) in &chunk_by {
13394 Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13395 }
13396 }
13397
13398 fn do_stage_or_unstage_and_next(
13399 &mut self,
13400 stage: bool,
13401 window: &mut Window,
13402 cx: &mut Context<Self>,
13403 ) {
13404 let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13405 if ranges.iter().any(|range| range.start != range.end) {
13406 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13407 return;
13408 }
13409
13410 if !self.buffer().read(cx).is_singleton() {
13411 if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13412 if buffer.read(cx).is_empty() {
13413 let buffer = buffer.read(cx);
13414 let Some(file) = buffer.file() else {
13415 return;
13416 };
13417 let project_path = project::ProjectPath {
13418 worktree_id: file.worktree_id(cx),
13419 path: file.path().clone(),
13420 };
13421 let Some(project) = self.project.as_ref() else {
13422 return;
13423 };
13424 let project = project.read(cx);
13425
13426 let Some(repo) = project.git_store().read(cx).active_repository() else {
13427 return;
13428 };
13429
13430 repo.update(cx, |repo, cx| {
13431 let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13432 return;
13433 };
13434 let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13435 return;
13436 };
13437 if stage && status.status == FileStatus::Untracked {
13438 repo.stage_entries(vec![repo_path], cx)
13439 .detach_and_log_err(cx);
13440 return;
13441 }
13442 })
13443 }
13444 ranges = vec![multi_buffer::Anchor::range_in_buffer(
13445 excerpt_id,
13446 buffer.read(cx).remote_id(),
13447 range,
13448 )];
13449 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13450 let snapshot = self.buffer().read(cx).snapshot(cx);
13451 let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13452 if point.row < snapshot.max_row().0 {
13453 point.row += 1;
13454 point.column = 0;
13455 point = snapshot.clip_point(point, Bias::Right);
13456 self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13457 s.select_ranges([point..point]);
13458 })
13459 }
13460 return;
13461 }
13462 }
13463 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13464 self.go_to_next_hunk(&Default::default(), window, cx);
13465 }
13466
13467 fn do_stage_or_unstage(
13468 project: &Entity<Project>,
13469 stage: bool,
13470 buffer_id: BufferId,
13471 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13472 snapshot: &MultiBufferSnapshot,
13473 cx: &mut Context<Self>,
13474 ) {
13475 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13476 log::debug!("no buffer for id");
13477 return;
13478 };
13479 let buffer_snapshot = buffer.read(cx).snapshot();
13480 let Some((repo, path)) = project
13481 .read(cx)
13482 .repository_and_path_for_buffer_id(buffer_id, cx)
13483 else {
13484 log::debug!("no git repo for buffer id");
13485 return;
13486 };
13487 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13488 log::debug!("no diff for buffer id");
13489 return;
13490 };
13491
13492 let Some(new_index_text) = diff.new_secondary_text_for_stage_or_unstage(
13493 stage,
13494 hunks.filter_map(|hunk| {
13495 if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13496 return None;
13497 } else if !stage
13498 && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13499 {
13500 return None;
13501 }
13502 Some((hunk.buffer_range.clone(), hunk.diff_base_byte_range.clone()))
13503 }),
13504 &buffer_snapshot,
13505 cx,
13506 ) else {
13507 log::debug!("missing secondary diff or index text");
13508 return;
13509 };
13510 let new_index_text = if new_index_text.is_empty()
13511 && !stage
13512 && (diff.is_single_insertion
13513 || buffer_snapshot
13514 .file()
13515 .map_or(false, |file| file.disk_state() == DiskState::New))
13516 {
13517 log::debug!("removing from index");
13518 None
13519 } else {
13520 Some(new_index_text)
13521 };
13522 let buffer_store = project.read(cx).buffer_store().clone();
13523 buffer_store
13524 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13525 .detach_and_log_err(cx);
13526
13527 cx.background_spawn(
13528 repo.read(cx)
13529 .set_index_text(&path, new_index_text.map(|rope| rope.to_string()))
13530 .log_err(),
13531 )
13532 .detach();
13533 }
13534
13535 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13536 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13537 self.buffer
13538 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13539 }
13540
13541 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13542 self.buffer.update(cx, |buffer, cx| {
13543 let ranges = vec![Anchor::min()..Anchor::max()];
13544 if !buffer.all_diff_hunks_expanded()
13545 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13546 {
13547 buffer.collapse_diff_hunks(ranges, cx);
13548 true
13549 } else {
13550 false
13551 }
13552 })
13553 }
13554
13555 fn toggle_diff_hunks_in_ranges(
13556 &mut self,
13557 ranges: Vec<Range<Anchor>>,
13558 cx: &mut Context<'_, Editor>,
13559 ) {
13560 self.buffer.update(cx, |buffer, cx| {
13561 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13562 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13563 })
13564 }
13565
13566 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13567 self.buffer.update(cx, |buffer, cx| {
13568 let snapshot = buffer.snapshot(cx);
13569 let excerpt_id = range.end.excerpt_id;
13570 let point_range = range.to_point(&snapshot);
13571 let expand = !buffer.single_hunk_is_expanded(range, cx);
13572 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13573 })
13574 }
13575
13576 pub(crate) fn apply_all_diff_hunks(
13577 &mut self,
13578 _: &ApplyAllDiffHunks,
13579 window: &mut Window,
13580 cx: &mut Context<Self>,
13581 ) {
13582 let buffers = self.buffer.read(cx).all_buffers();
13583 for branch_buffer in buffers {
13584 branch_buffer.update(cx, |branch_buffer, cx| {
13585 branch_buffer.merge_into_base(Vec::new(), cx);
13586 });
13587 }
13588
13589 if let Some(project) = self.project.clone() {
13590 self.save(true, project, window, cx).detach_and_log_err(cx);
13591 }
13592 }
13593
13594 pub(crate) fn apply_selected_diff_hunks(
13595 &mut self,
13596 _: &ApplyDiffHunk,
13597 window: &mut Window,
13598 cx: &mut Context<Self>,
13599 ) {
13600 let snapshot = self.snapshot(window, cx);
13601 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13602 let mut ranges_by_buffer = HashMap::default();
13603 self.transact(window, cx, |editor, _window, cx| {
13604 for hunk in hunks {
13605 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13606 ranges_by_buffer
13607 .entry(buffer.clone())
13608 .or_insert_with(Vec::new)
13609 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13610 }
13611 }
13612
13613 for (buffer, ranges) in ranges_by_buffer {
13614 buffer.update(cx, |buffer, cx| {
13615 buffer.merge_into_base(ranges, cx);
13616 });
13617 }
13618 });
13619
13620 if let Some(project) = self.project.clone() {
13621 self.save(true, project, window, cx).detach_and_log_err(cx);
13622 }
13623 }
13624
13625 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13626 if hovered != self.gutter_hovered {
13627 self.gutter_hovered = hovered;
13628 cx.notify();
13629 }
13630 }
13631
13632 pub fn insert_blocks(
13633 &mut self,
13634 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13635 autoscroll: Option<Autoscroll>,
13636 cx: &mut Context<Self>,
13637 ) -> Vec<CustomBlockId> {
13638 let blocks = self
13639 .display_map
13640 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13641 if let Some(autoscroll) = autoscroll {
13642 self.request_autoscroll(autoscroll, cx);
13643 }
13644 cx.notify();
13645 blocks
13646 }
13647
13648 pub fn resize_blocks(
13649 &mut self,
13650 heights: HashMap<CustomBlockId, u32>,
13651 autoscroll: Option<Autoscroll>,
13652 cx: &mut Context<Self>,
13653 ) {
13654 self.display_map
13655 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13656 if let Some(autoscroll) = autoscroll {
13657 self.request_autoscroll(autoscroll, cx);
13658 }
13659 cx.notify();
13660 }
13661
13662 pub fn replace_blocks(
13663 &mut self,
13664 renderers: HashMap<CustomBlockId, RenderBlock>,
13665 autoscroll: Option<Autoscroll>,
13666 cx: &mut Context<Self>,
13667 ) {
13668 self.display_map
13669 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13670 if let Some(autoscroll) = autoscroll {
13671 self.request_autoscroll(autoscroll, cx);
13672 }
13673 cx.notify();
13674 }
13675
13676 pub fn remove_blocks(
13677 &mut self,
13678 block_ids: HashSet<CustomBlockId>,
13679 autoscroll: Option<Autoscroll>,
13680 cx: &mut Context<Self>,
13681 ) {
13682 self.display_map.update(cx, |display_map, cx| {
13683 display_map.remove_blocks(block_ids, cx)
13684 });
13685 if let Some(autoscroll) = autoscroll {
13686 self.request_autoscroll(autoscroll, cx);
13687 }
13688 cx.notify();
13689 }
13690
13691 pub fn row_for_block(
13692 &self,
13693 block_id: CustomBlockId,
13694 cx: &mut Context<Self>,
13695 ) -> Option<DisplayRow> {
13696 self.display_map
13697 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13698 }
13699
13700 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13701 self.focused_block = Some(focused_block);
13702 }
13703
13704 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13705 self.focused_block.take()
13706 }
13707
13708 pub fn insert_creases(
13709 &mut self,
13710 creases: impl IntoIterator<Item = Crease<Anchor>>,
13711 cx: &mut Context<Self>,
13712 ) -> Vec<CreaseId> {
13713 self.display_map
13714 .update(cx, |map, cx| map.insert_creases(creases, cx))
13715 }
13716
13717 pub fn remove_creases(
13718 &mut self,
13719 ids: impl IntoIterator<Item = CreaseId>,
13720 cx: &mut Context<Self>,
13721 ) {
13722 self.display_map
13723 .update(cx, |map, cx| map.remove_creases(ids, cx));
13724 }
13725
13726 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13727 self.display_map
13728 .update(cx, |map, cx| map.snapshot(cx))
13729 .longest_row()
13730 }
13731
13732 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13733 self.display_map
13734 .update(cx, |map, cx| map.snapshot(cx))
13735 .max_point()
13736 }
13737
13738 pub fn text(&self, cx: &App) -> String {
13739 self.buffer.read(cx).read(cx).text()
13740 }
13741
13742 pub fn is_empty(&self, cx: &App) -> bool {
13743 self.buffer.read(cx).read(cx).is_empty()
13744 }
13745
13746 pub fn text_option(&self, cx: &App) -> Option<String> {
13747 let text = self.text(cx);
13748 let text = text.trim();
13749
13750 if text.is_empty() {
13751 return None;
13752 }
13753
13754 Some(text.to_string())
13755 }
13756
13757 pub fn set_text(
13758 &mut self,
13759 text: impl Into<Arc<str>>,
13760 window: &mut Window,
13761 cx: &mut Context<Self>,
13762 ) {
13763 self.transact(window, cx, |this, _, cx| {
13764 this.buffer
13765 .read(cx)
13766 .as_singleton()
13767 .expect("you can only call set_text on editors for singleton buffers")
13768 .update(cx, |buffer, cx| buffer.set_text(text, cx));
13769 });
13770 }
13771
13772 pub fn display_text(&self, cx: &mut App) -> String {
13773 self.display_map
13774 .update(cx, |map, cx| map.snapshot(cx))
13775 .text()
13776 }
13777
13778 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13779 let mut wrap_guides = smallvec::smallvec![];
13780
13781 if self.show_wrap_guides == Some(false) {
13782 return wrap_guides;
13783 }
13784
13785 let settings = self.buffer.read(cx).settings_at(0, cx);
13786 if settings.show_wrap_guides {
13787 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13788 wrap_guides.push((soft_wrap as usize, true));
13789 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13790 wrap_guides.push((soft_wrap as usize, true));
13791 }
13792 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13793 }
13794
13795 wrap_guides
13796 }
13797
13798 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13799 let settings = self.buffer.read(cx).settings_at(0, cx);
13800 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13801 match mode {
13802 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13803 SoftWrap::None
13804 }
13805 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13806 language_settings::SoftWrap::PreferredLineLength => {
13807 SoftWrap::Column(settings.preferred_line_length)
13808 }
13809 language_settings::SoftWrap::Bounded => {
13810 SoftWrap::Bounded(settings.preferred_line_length)
13811 }
13812 }
13813 }
13814
13815 pub fn set_soft_wrap_mode(
13816 &mut self,
13817 mode: language_settings::SoftWrap,
13818
13819 cx: &mut Context<Self>,
13820 ) {
13821 self.soft_wrap_mode_override = Some(mode);
13822 cx.notify();
13823 }
13824
13825 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13826 self.text_style_refinement = Some(style);
13827 }
13828
13829 /// called by the Element so we know what style we were most recently rendered with.
13830 pub(crate) fn set_style(
13831 &mut self,
13832 style: EditorStyle,
13833 window: &mut Window,
13834 cx: &mut Context<Self>,
13835 ) {
13836 let rem_size = window.rem_size();
13837 self.display_map.update(cx, |map, cx| {
13838 map.set_font(
13839 style.text.font(),
13840 style.text.font_size.to_pixels(rem_size),
13841 cx,
13842 )
13843 });
13844 self.style = Some(style);
13845 }
13846
13847 pub fn style(&self) -> Option<&EditorStyle> {
13848 self.style.as_ref()
13849 }
13850
13851 // Called by the element. This method is not designed to be called outside of the editor
13852 // element's layout code because it does not notify when rewrapping is computed synchronously.
13853 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13854 self.display_map
13855 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13856 }
13857
13858 pub fn set_soft_wrap(&mut self) {
13859 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13860 }
13861
13862 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13863 if self.soft_wrap_mode_override.is_some() {
13864 self.soft_wrap_mode_override.take();
13865 } else {
13866 let soft_wrap = match self.soft_wrap_mode(cx) {
13867 SoftWrap::GitDiff => return,
13868 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13869 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13870 language_settings::SoftWrap::None
13871 }
13872 };
13873 self.soft_wrap_mode_override = Some(soft_wrap);
13874 }
13875 cx.notify();
13876 }
13877
13878 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13879 let Some(workspace) = self.workspace() else {
13880 return;
13881 };
13882 let fs = workspace.read(cx).app_state().fs.clone();
13883 let current_show = TabBarSettings::get_global(cx).show;
13884 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13885 setting.show = Some(!current_show);
13886 });
13887 }
13888
13889 pub fn toggle_indent_guides(
13890 &mut self,
13891 _: &ToggleIndentGuides,
13892 _: &mut Window,
13893 cx: &mut Context<Self>,
13894 ) {
13895 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13896 self.buffer
13897 .read(cx)
13898 .settings_at(0, cx)
13899 .indent_guides
13900 .enabled
13901 });
13902 self.show_indent_guides = Some(!currently_enabled);
13903 cx.notify();
13904 }
13905
13906 fn should_show_indent_guides(&self) -> Option<bool> {
13907 self.show_indent_guides
13908 }
13909
13910 pub fn toggle_line_numbers(
13911 &mut self,
13912 _: &ToggleLineNumbers,
13913 _: &mut Window,
13914 cx: &mut Context<Self>,
13915 ) {
13916 let mut editor_settings = EditorSettings::get_global(cx).clone();
13917 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13918 EditorSettings::override_global(editor_settings, cx);
13919 }
13920
13921 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13922 self.use_relative_line_numbers
13923 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13924 }
13925
13926 pub fn toggle_relative_line_numbers(
13927 &mut self,
13928 _: &ToggleRelativeLineNumbers,
13929 _: &mut Window,
13930 cx: &mut Context<Self>,
13931 ) {
13932 let is_relative = self.should_use_relative_line_numbers(cx);
13933 self.set_relative_line_number(Some(!is_relative), cx)
13934 }
13935
13936 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13937 self.use_relative_line_numbers = is_relative;
13938 cx.notify();
13939 }
13940
13941 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13942 self.show_gutter = show_gutter;
13943 cx.notify();
13944 }
13945
13946 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13947 self.show_scrollbars = show_scrollbars;
13948 cx.notify();
13949 }
13950
13951 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13952 self.show_line_numbers = Some(show_line_numbers);
13953 cx.notify();
13954 }
13955
13956 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13957 self.show_git_diff_gutter = Some(show_git_diff_gutter);
13958 cx.notify();
13959 }
13960
13961 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13962 self.show_code_actions = Some(show_code_actions);
13963 cx.notify();
13964 }
13965
13966 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13967 self.show_runnables = Some(show_runnables);
13968 cx.notify();
13969 }
13970
13971 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13972 if self.display_map.read(cx).masked != masked {
13973 self.display_map.update(cx, |map, _| map.masked = masked);
13974 }
13975 cx.notify()
13976 }
13977
13978 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13979 self.show_wrap_guides = Some(show_wrap_guides);
13980 cx.notify();
13981 }
13982
13983 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13984 self.show_indent_guides = Some(show_indent_guides);
13985 cx.notify();
13986 }
13987
13988 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13989 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13990 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13991 if let Some(dir) = file.abs_path(cx).parent() {
13992 return Some(dir.to_owned());
13993 }
13994 }
13995
13996 if let Some(project_path) = buffer.read(cx).project_path(cx) {
13997 return Some(project_path.path.to_path_buf());
13998 }
13999 }
14000
14001 None
14002 }
14003
14004 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14005 self.active_excerpt(cx)?
14006 .1
14007 .read(cx)
14008 .file()
14009 .and_then(|f| f.as_local())
14010 }
14011
14012 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14013 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14014 let buffer = buffer.read(cx);
14015 if let Some(project_path) = buffer.project_path(cx) {
14016 let project = self.project.as_ref()?.read(cx);
14017 project.absolute_path(&project_path, cx)
14018 } else {
14019 buffer
14020 .file()
14021 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14022 }
14023 })
14024 }
14025
14026 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14027 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14028 let project_path = buffer.read(cx).project_path(cx)?;
14029 let project = self.project.as_ref()?.read(cx);
14030 let entry = project.entry_for_path(&project_path, cx)?;
14031 let path = entry.path.to_path_buf();
14032 Some(path)
14033 })
14034 }
14035
14036 pub fn reveal_in_finder(
14037 &mut self,
14038 _: &RevealInFileManager,
14039 _window: &mut Window,
14040 cx: &mut Context<Self>,
14041 ) {
14042 if let Some(target) = self.target_file(cx) {
14043 cx.reveal_path(&target.abs_path(cx));
14044 }
14045 }
14046
14047 pub fn copy_path(
14048 &mut self,
14049 _: &zed_actions::workspace::CopyPath,
14050 _window: &mut Window,
14051 cx: &mut Context<Self>,
14052 ) {
14053 if let Some(path) = self.target_file_abs_path(cx) {
14054 if let Some(path) = path.to_str() {
14055 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14056 }
14057 }
14058 }
14059
14060 pub fn copy_relative_path(
14061 &mut self,
14062 _: &zed_actions::workspace::CopyRelativePath,
14063 _window: &mut Window,
14064 cx: &mut Context<Self>,
14065 ) {
14066 if let Some(path) = self.target_file_path(cx) {
14067 if let Some(path) = path.to_str() {
14068 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14069 }
14070 }
14071 }
14072
14073 pub fn copy_file_name_without_extension(
14074 &mut self,
14075 _: &CopyFileNameWithoutExtension,
14076 _: &mut Window,
14077 cx: &mut Context<Self>,
14078 ) {
14079 if let Some(file) = self.target_file(cx) {
14080 if let Some(file_stem) = file.path().file_stem() {
14081 if let Some(name) = file_stem.to_str() {
14082 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14083 }
14084 }
14085 }
14086 }
14087
14088 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14089 if let Some(file) = self.target_file(cx) {
14090 if let Some(file_name) = file.path().file_name() {
14091 if let Some(name) = file_name.to_str() {
14092 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14093 }
14094 }
14095 }
14096 }
14097
14098 pub fn toggle_git_blame(
14099 &mut self,
14100 _: &ToggleGitBlame,
14101 window: &mut Window,
14102 cx: &mut Context<Self>,
14103 ) {
14104 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14105
14106 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14107 self.start_git_blame(true, window, cx);
14108 }
14109
14110 cx.notify();
14111 }
14112
14113 pub fn toggle_git_blame_inline(
14114 &mut self,
14115 _: &ToggleGitBlameInline,
14116 window: &mut Window,
14117 cx: &mut Context<Self>,
14118 ) {
14119 self.toggle_git_blame_inline_internal(true, window, cx);
14120 cx.notify();
14121 }
14122
14123 pub fn git_blame_inline_enabled(&self) -> bool {
14124 self.git_blame_inline_enabled
14125 }
14126
14127 pub fn toggle_selection_menu(
14128 &mut self,
14129 _: &ToggleSelectionMenu,
14130 _: &mut Window,
14131 cx: &mut Context<Self>,
14132 ) {
14133 self.show_selection_menu = self
14134 .show_selection_menu
14135 .map(|show_selections_menu| !show_selections_menu)
14136 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14137
14138 cx.notify();
14139 }
14140
14141 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14142 self.show_selection_menu
14143 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14144 }
14145
14146 fn start_git_blame(
14147 &mut self,
14148 user_triggered: bool,
14149 window: &mut Window,
14150 cx: &mut Context<Self>,
14151 ) {
14152 if let Some(project) = self.project.as_ref() {
14153 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14154 return;
14155 };
14156
14157 if buffer.read(cx).file().is_none() {
14158 return;
14159 }
14160
14161 let focused = self.focus_handle(cx).contains_focused(window, cx);
14162
14163 let project = project.clone();
14164 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14165 self.blame_subscription =
14166 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14167 self.blame = Some(blame);
14168 }
14169 }
14170
14171 fn toggle_git_blame_inline_internal(
14172 &mut self,
14173 user_triggered: bool,
14174 window: &mut Window,
14175 cx: &mut Context<Self>,
14176 ) {
14177 if self.git_blame_inline_enabled {
14178 self.git_blame_inline_enabled = false;
14179 self.show_git_blame_inline = false;
14180 self.show_git_blame_inline_delay_task.take();
14181 } else {
14182 self.git_blame_inline_enabled = true;
14183 self.start_git_blame_inline(user_triggered, window, cx);
14184 }
14185
14186 cx.notify();
14187 }
14188
14189 fn start_git_blame_inline(
14190 &mut self,
14191 user_triggered: bool,
14192 window: &mut Window,
14193 cx: &mut Context<Self>,
14194 ) {
14195 self.start_git_blame(user_triggered, window, cx);
14196
14197 if ProjectSettings::get_global(cx)
14198 .git
14199 .inline_blame_delay()
14200 .is_some()
14201 {
14202 self.start_inline_blame_timer(window, cx);
14203 } else {
14204 self.show_git_blame_inline = true
14205 }
14206 }
14207
14208 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14209 self.blame.as_ref()
14210 }
14211
14212 pub fn show_git_blame_gutter(&self) -> bool {
14213 self.show_git_blame_gutter
14214 }
14215
14216 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14217 self.show_git_blame_gutter && self.has_blame_entries(cx)
14218 }
14219
14220 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14221 self.show_git_blame_inline
14222 && (self.focus_handle.is_focused(window)
14223 || self
14224 .git_blame_inline_tooltip
14225 .as_ref()
14226 .and_then(|t| t.upgrade())
14227 .is_some())
14228 && !self.newest_selection_head_on_empty_line(cx)
14229 && self.has_blame_entries(cx)
14230 }
14231
14232 fn has_blame_entries(&self, cx: &App) -> bool {
14233 self.blame()
14234 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14235 }
14236
14237 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14238 let cursor_anchor = self.selections.newest_anchor().head();
14239
14240 let snapshot = self.buffer.read(cx).snapshot(cx);
14241 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14242
14243 snapshot.line_len(buffer_row) == 0
14244 }
14245
14246 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14247 let buffer_and_selection = maybe!({
14248 let selection = self.selections.newest::<Point>(cx);
14249 let selection_range = selection.range();
14250
14251 let multi_buffer = self.buffer().read(cx);
14252 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14253 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14254
14255 let (buffer, range, _) = if selection.reversed {
14256 buffer_ranges.first()
14257 } else {
14258 buffer_ranges.last()
14259 }?;
14260
14261 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14262 ..text::ToPoint::to_point(&range.end, &buffer).row;
14263 Some((
14264 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14265 selection,
14266 ))
14267 });
14268
14269 let Some((buffer, selection)) = buffer_and_selection else {
14270 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14271 };
14272
14273 let Some(project) = self.project.as_ref() else {
14274 return Task::ready(Err(anyhow!("editor does not have project")));
14275 };
14276
14277 project.update(cx, |project, cx| {
14278 project.get_permalink_to_line(&buffer, selection, cx)
14279 })
14280 }
14281
14282 pub fn copy_permalink_to_line(
14283 &mut self,
14284 _: &CopyPermalinkToLine,
14285 window: &mut Window,
14286 cx: &mut Context<Self>,
14287 ) {
14288 let permalink_task = self.get_permalink_to_line(cx);
14289 let workspace = self.workspace();
14290
14291 cx.spawn_in(window, |_, mut cx| async move {
14292 match permalink_task.await {
14293 Ok(permalink) => {
14294 cx.update(|_, cx| {
14295 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14296 })
14297 .ok();
14298 }
14299 Err(err) => {
14300 let message = format!("Failed to copy permalink: {err}");
14301
14302 Err::<(), anyhow::Error>(err).log_err();
14303
14304 if let Some(workspace) = workspace {
14305 workspace
14306 .update_in(&mut cx, |workspace, _, cx| {
14307 struct CopyPermalinkToLine;
14308
14309 workspace.show_toast(
14310 Toast::new(
14311 NotificationId::unique::<CopyPermalinkToLine>(),
14312 message,
14313 ),
14314 cx,
14315 )
14316 })
14317 .ok();
14318 }
14319 }
14320 }
14321 })
14322 .detach();
14323 }
14324
14325 pub fn copy_file_location(
14326 &mut self,
14327 _: &CopyFileLocation,
14328 _: &mut Window,
14329 cx: &mut Context<Self>,
14330 ) {
14331 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14332 if let Some(file) = self.target_file(cx) {
14333 if let Some(path) = file.path().to_str() {
14334 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14335 }
14336 }
14337 }
14338
14339 pub fn open_permalink_to_line(
14340 &mut self,
14341 _: &OpenPermalinkToLine,
14342 window: &mut Window,
14343 cx: &mut Context<Self>,
14344 ) {
14345 let permalink_task = self.get_permalink_to_line(cx);
14346 let workspace = self.workspace();
14347
14348 cx.spawn_in(window, |_, mut cx| async move {
14349 match permalink_task.await {
14350 Ok(permalink) => {
14351 cx.update(|_, cx| {
14352 cx.open_url(permalink.as_ref());
14353 })
14354 .ok();
14355 }
14356 Err(err) => {
14357 let message = format!("Failed to open permalink: {err}");
14358
14359 Err::<(), anyhow::Error>(err).log_err();
14360
14361 if let Some(workspace) = workspace {
14362 workspace
14363 .update(&mut cx, |workspace, cx| {
14364 struct OpenPermalinkToLine;
14365
14366 workspace.show_toast(
14367 Toast::new(
14368 NotificationId::unique::<OpenPermalinkToLine>(),
14369 message,
14370 ),
14371 cx,
14372 )
14373 })
14374 .ok();
14375 }
14376 }
14377 }
14378 })
14379 .detach();
14380 }
14381
14382 pub fn insert_uuid_v4(
14383 &mut self,
14384 _: &InsertUuidV4,
14385 window: &mut Window,
14386 cx: &mut Context<Self>,
14387 ) {
14388 self.insert_uuid(UuidVersion::V4, window, cx);
14389 }
14390
14391 pub fn insert_uuid_v7(
14392 &mut self,
14393 _: &InsertUuidV7,
14394 window: &mut Window,
14395 cx: &mut Context<Self>,
14396 ) {
14397 self.insert_uuid(UuidVersion::V7, window, cx);
14398 }
14399
14400 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14401 self.transact(window, cx, |this, window, cx| {
14402 let edits = this
14403 .selections
14404 .all::<Point>(cx)
14405 .into_iter()
14406 .map(|selection| {
14407 let uuid = match version {
14408 UuidVersion::V4 => uuid::Uuid::new_v4(),
14409 UuidVersion::V7 => uuid::Uuid::now_v7(),
14410 };
14411
14412 (selection.range(), uuid.to_string())
14413 });
14414 this.edit(edits, cx);
14415 this.refresh_inline_completion(true, false, window, cx);
14416 });
14417 }
14418
14419 pub fn open_selections_in_multibuffer(
14420 &mut self,
14421 _: &OpenSelectionsInMultibuffer,
14422 window: &mut Window,
14423 cx: &mut Context<Self>,
14424 ) {
14425 let multibuffer = self.buffer.read(cx);
14426
14427 let Some(buffer) = multibuffer.as_singleton() else {
14428 return;
14429 };
14430
14431 let Some(workspace) = self.workspace() else {
14432 return;
14433 };
14434
14435 let locations = self
14436 .selections
14437 .disjoint_anchors()
14438 .iter()
14439 .map(|range| Location {
14440 buffer: buffer.clone(),
14441 range: range.start.text_anchor..range.end.text_anchor,
14442 })
14443 .collect::<Vec<_>>();
14444
14445 let title = multibuffer.title(cx).to_string();
14446
14447 cx.spawn_in(window, |_, mut cx| async move {
14448 workspace.update_in(&mut cx, |workspace, window, cx| {
14449 Self::open_locations_in_multibuffer(
14450 workspace,
14451 locations,
14452 format!("Selections for '{title}'"),
14453 false,
14454 MultibufferSelectionMode::All,
14455 window,
14456 cx,
14457 );
14458 })
14459 })
14460 .detach();
14461 }
14462
14463 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14464 /// last highlight added will be used.
14465 ///
14466 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14467 pub fn highlight_rows<T: 'static>(
14468 &mut self,
14469 range: Range<Anchor>,
14470 color: Hsla,
14471 should_autoscroll: bool,
14472 cx: &mut Context<Self>,
14473 ) {
14474 let snapshot = self.buffer().read(cx).snapshot(cx);
14475 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14476 let ix = row_highlights.binary_search_by(|highlight| {
14477 Ordering::Equal
14478 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14479 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14480 });
14481
14482 if let Err(mut ix) = ix {
14483 let index = post_inc(&mut self.highlight_order);
14484
14485 // If this range intersects with the preceding highlight, then merge it with
14486 // the preceding highlight. Otherwise insert a new highlight.
14487 let mut merged = false;
14488 if ix > 0 {
14489 let prev_highlight = &mut row_highlights[ix - 1];
14490 if prev_highlight
14491 .range
14492 .end
14493 .cmp(&range.start, &snapshot)
14494 .is_ge()
14495 {
14496 ix -= 1;
14497 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14498 prev_highlight.range.end = range.end;
14499 }
14500 merged = true;
14501 prev_highlight.index = index;
14502 prev_highlight.color = color;
14503 prev_highlight.should_autoscroll = should_autoscroll;
14504 }
14505 }
14506
14507 if !merged {
14508 row_highlights.insert(
14509 ix,
14510 RowHighlight {
14511 range: range.clone(),
14512 index,
14513 color,
14514 should_autoscroll,
14515 },
14516 );
14517 }
14518
14519 // If any of the following highlights intersect with this one, merge them.
14520 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14521 let highlight = &row_highlights[ix];
14522 if next_highlight
14523 .range
14524 .start
14525 .cmp(&highlight.range.end, &snapshot)
14526 .is_le()
14527 {
14528 if next_highlight
14529 .range
14530 .end
14531 .cmp(&highlight.range.end, &snapshot)
14532 .is_gt()
14533 {
14534 row_highlights[ix].range.end = next_highlight.range.end;
14535 }
14536 row_highlights.remove(ix + 1);
14537 } else {
14538 break;
14539 }
14540 }
14541 }
14542 }
14543
14544 /// Remove any highlighted row ranges of the given type that intersect the
14545 /// given ranges.
14546 pub fn remove_highlighted_rows<T: 'static>(
14547 &mut self,
14548 ranges_to_remove: Vec<Range<Anchor>>,
14549 cx: &mut Context<Self>,
14550 ) {
14551 let snapshot = self.buffer().read(cx).snapshot(cx);
14552 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14553 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14554 row_highlights.retain(|highlight| {
14555 while let Some(range_to_remove) = ranges_to_remove.peek() {
14556 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14557 Ordering::Less | Ordering::Equal => {
14558 ranges_to_remove.next();
14559 }
14560 Ordering::Greater => {
14561 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14562 Ordering::Less | Ordering::Equal => {
14563 return false;
14564 }
14565 Ordering::Greater => break,
14566 }
14567 }
14568 }
14569 }
14570
14571 true
14572 })
14573 }
14574
14575 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14576 pub fn clear_row_highlights<T: 'static>(&mut self) {
14577 self.highlighted_rows.remove(&TypeId::of::<T>());
14578 }
14579
14580 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14581 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14582 self.highlighted_rows
14583 .get(&TypeId::of::<T>())
14584 .map_or(&[] as &[_], |vec| vec.as_slice())
14585 .iter()
14586 .map(|highlight| (highlight.range.clone(), highlight.color))
14587 }
14588
14589 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14590 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14591 /// Allows to ignore certain kinds of highlights.
14592 pub fn highlighted_display_rows(
14593 &self,
14594 window: &mut Window,
14595 cx: &mut App,
14596 ) -> BTreeMap<DisplayRow, Background> {
14597 let snapshot = self.snapshot(window, cx);
14598 let mut used_highlight_orders = HashMap::default();
14599 self.highlighted_rows
14600 .iter()
14601 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14602 .fold(
14603 BTreeMap::<DisplayRow, Background>::new(),
14604 |mut unique_rows, highlight| {
14605 let start = highlight.range.start.to_display_point(&snapshot);
14606 let end = highlight.range.end.to_display_point(&snapshot);
14607 let start_row = start.row().0;
14608 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14609 && end.column() == 0
14610 {
14611 end.row().0.saturating_sub(1)
14612 } else {
14613 end.row().0
14614 };
14615 for row in start_row..=end_row {
14616 let used_index =
14617 used_highlight_orders.entry(row).or_insert(highlight.index);
14618 if highlight.index >= *used_index {
14619 *used_index = highlight.index;
14620 unique_rows.insert(DisplayRow(row), highlight.color.into());
14621 }
14622 }
14623 unique_rows
14624 },
14625 )
14626 }
14627
14628 pub fn highlighted_display_row_for_autoscroll(
14629 &self,
14630 snapshot: &DisplaySnapshot,
14631 ) -> Option<DisplayRow> {
14632 self.highlighted_rows
14633 .values()
14634 .flat_map(|highlighted_rows| highlighted_rows.iter())
14635 .filter_map(|highlight| {
14636 if highlight.should_autoscroll {
14637 Some(highlight.range.start.to_display_point(snapshot).row())
14638 } else {
14639 None
14640 }
14641 })
14642 .min()
14643 }
14644
14645 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14646 self.highlight_background::<SearchWithinRange>(
14647 ranges,
14648 |colors| colors.editor_document_highlight_read_background,
14649 cx,
14650 )
14651 }
14652
14653 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14654 self.breadcrumb_header = Some(new_header);
14655 }
14656
14657 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14658 self.clear_background_highlights::<SearchWithinRange>(cx);
14659 }
14660
14661 pub fn highlight_background<T: 'static>(
14662 &mut self,
14663 ranges: &[Range<Anchor>],
14664 color_fetcher: fn(&ThemeColors) -> Hsla,
14665 cx: &mut Context<Self>,
14666 ) {
14667 self.background_highlights
14668 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14669 self.scrollbar_marker_state.dirty = true;
14670 cx.notify();
14671 }
14672
14673 pub fn clear_background_highlights<T: 'static>(
14674 &mut self,
14675 cx: &mut Context<Self>,
14676 ) -> Option<BackgroundHighlight> {
14677 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14678 if !text_highlights.1.is_empty() {
14679 self.scrollbar_marker_state.dirty = true;
14680 cx.notify();
14681 }
14682 Some(text_highlights)
14683 }
14684
14685 pub fn highlight_gutter<T: 'static>(
14686 &mut self,
14687 ranges: &[Range<Anchor>],
14688 color_fetcher: fn(&App) -> Hsla,
14689 cx: &mut Context<Self>,
14690 ) {
14691 self.gutter_highlights
14692 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14693 cx.notify();
14694 }
14695
14696 pub fn clear_gutter_highlights<T: 'static>(
14697 &mut self,
14698 cx: &mut Context<Self>,
14699 ) -> Option<GutterHighlight> {
14700 cx.notify();
14701 self.gutter_highlights.remove(&TypeId::of::<T>())
14702 }
14703
14704 #[cfg(feature = "test-support")]
14705 pub fn all_text_background_highlights(
14706 &self,
14707 window: &mut Window,
14708 cx: &mut Context<Self>,
14709 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14710 let snapshot = self.snapshot(window, cx);
14711 let buffer = &snapshot.buffer_snapshot;
14712 let start = buffer.anchor_before(0);
14713 let end = buffer.anchor_after(buffer.len());
14714 let theme = cx.theme().colors();
14715 self.background_highlights_in_range(start..end, &snapshot, theme)
14716 }
14717
14718 #[cfg(feature = "test-support")]
14719 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14720 let snapshot = self.buffer().read(cx).snapshot(cx);
14721
14722 let highlights = self
14723 .background_highlights
14724 .get(&TypeId::of::<items::BufferSearchHighlights>());
14725
14726 if let Some((_color, ranges)) = highlights {
14727 ranges
14728 .iter()
14729 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14730 .collect_vec()
14731 } else {
14732 vec![]
14733 }
14734 }
14735
14736 fn document_highlights_for_position<'a>(
14737 &'a self,
14738 position: Anchor,
14739 buffer: &'a MultiBufferSnapshot,
14740 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14741 let read_highlights = self
14742 .background_highlights
14743 .get(&TypeId::of::<DocumentHighlightRead>())
14744 .map(|h| &h.1);
14745 let write_highlights = self
14746 .background_highlights
14747 .get(&TypeId::of::<DocumentHighlightWrite>())
14748 .map(|h| &h.1);
14749 let left_position = position.bias_left(buffer);
14750 let right_position = position.bias_right(buffer);
14751 read_highlights
14752 .into_iter()
14753 .chain(write_highlights)
14754 .flat_map(move |ranges| {
14755 let start_ix = match ranges.binary_search_by(|probe| {
14756 let cmp = probe.end.cmp(&left_position, buffer);
14757 if cmp.is_ge() {
14758 Ordering::Greater
14759 } else {
14760 Ordering::Less
14761 }
14762 }) {
14763 Ok(i) | Err(i) => i,
14764 };
14765
14766 ranges[start_ix..]
14767 .iter()
14768 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14769 })
14770 }
14771
14772 pub fn has_background_highlights<T: 'static>(&self) -> bool {
14773 self.background_highlights
14774 .get(&TypeId::of::<T>())
14775 .map_or(false, |(_, highlights)| !highlights.is_empty())
14776 }
14777
14778 pub fn background_highlights_in_range(
14779 &self,
14780 search_range: Range<Anchor>,
14781 display_snapshot: &DisplaySnapshot,
14782 theme: &ThemeColors,
14783 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14784 let mut results = Vec::new();
14785 for (color_fetcher, ranges) in self.background_highlights.values() {
14786 let color = color_fetcher(theme);
14787 let start_ix = match ranges.binary_search_by(|probe| {
14788 let cmp = probe
14789 .end
14790 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14791 if cmp.is_gt() {
14792 Ordering::Greater
14793 } else {
14794 Ordering::Less
14795 }
14796 }) {
14797 Ok(i) | Err(i) => i,
14798 };
14799 for range in &ranges[start_ix..] {
14800 if range
14801 .start
14802 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14803 .is_ge()
14804 {
14805 break;
14806 }
14807
14808 let start = range.start.to_display_point(display_snapshot);
14809 let end = range.end.to_display_point(display_snapshot);
14810 results.push((start..end, color))
14811 }
14812 }
14813 results
14814 }
14815
14816 pub fn background_highlight_row_ranges<T: 'static>(
14817 &self,
14818 search_range: Range<Anchor>,
14819 display_snapshot: &DisplaySnapshot,
14820 count: usize,
14821 ) -> Vec<RangeInclusive<DisplayPoint>> {
14822 let mut results = Vec::new();
14823 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14824 return vec![];
14825 };
14826
14827 let start_ix = match ranges.binary_search_by(|probe| {
14828 let cmp = probe
14829 .end
14830 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14831 if cmp.is_gt() {
14832 Ordering::Greater
14833 } else {
14834 Ordering::Less
14835 }
14836 }) {
14837 Ok(i) | Err(i) => i,
14838 };
14839 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14840 if let (Some(start_display), Some(end_display)) = (start, end) {
14841 results.push(
14842 start_display.to_display_point(display_snapshot)
14843 ..=end_display.to_display_point(display_snapshot),
14844 );
14845 }
14846 };
14847 let mut start_row: Option<Point> = None;
14848 let mut end_row: Option<Point> = None;
14849 if ranges.len() > count {
14850 return Vec::new();
14851 }
14852 for range in &ranges[start_ix..] {
14853 if range
14854 .start
14855 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14856 .is_ge()
14857 {
14858 break;
14859 }
14860 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14861 if let Some(current_row) = &end_row {
14862 if end.row == current_row.row {
14863 continue;
14864 }
14865 }
14866 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14867 if start_row.is_none() {
14868 assert_eq!(end_row, None);
14869 start_row = Some(start);
14870 end_row = Some(end);
14871 continue;
14872 }
14873 if let Some(current_end) = end_row.as_mut() {
14874 if start.row > current_end.row + 1 {
14875 push_region(start_row, end_row);
14876 start_row = Some(start);
14877 end_row = Some(end);
14878 } else {
14879 // Merge two hunks.
14880 *current_end = end;
14881 }
14882 } else {
14883 unreachable!();
14884 }
14885 }
14886 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14887 push_region(start_row, end_row);
14888 results
14889 }
14890
14891 pub fn gutter_highlights_in_range(
14892 &self,
14893 search_range: Range<Anchor>,
14894 display_snapshot: &DisplaySnapshot,
14895 cx: &App,
14896 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14897 let mut results = Vec::new();
14898 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14899 let color = color_fetcher(cx);
14900 let start_ix = match ranges.binary_search_by(|probe| {
14901 let cmp = probe
14902 .end
14903 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14904 if cmp.is_gt() {
14905 Ordering::Greater
14906 } else {
14907 Ordering::Less
14908 }
14909 }) {
14910 Ok(i) | Err(i) => i,
14911 };
14912 for range in &ranges[start_ix..] {
14913 if range
14914 .start
14915 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14916 .is_ge()
14917 {
14918 break;
14919 }
14920
14921 let start = range.start.to_display_point(display_snapshot);
14922 let end = range.end.to_display_point(display_snapshot);
14923 results.push((start..end, color))
14924 }
14925 }
14926 results
14927 }
14928
14929 /// Get the text ranges corresponding to the redaction query
14930 pub fn redacted_ranges(
14931 &self,
14932 search_range: Range<Anchor>,
14933 display_snapshot: &DisplaySnapshot,
14934 cx: &App,
14935 ) -> Vec<Range<DisplayPoint>> {
14936 display_snapshot
14937 .buffer_snapshot
14938 .redacted_ranges(search_range, |file| {
14939 if let Some(file) = file {
14940 file.is_private()
14941 && EditorSettings::get(
14942 Some(SettingsLocation {
14943 worktree_id: file.worktree_id(cx),
14944 path: file.path().as_ref(),
14945 }),
14946 cx,
14947 )
14948 .redact_private_values
14949 } else {
14950 false
14951 }
14952 })
14953 .map(|range| {
14954 range.start.to_display_point(display_snapshot)
14955 ..range.end.to_display_point(display_snapshot)
14956 })
14957 .collect()
14958 }
14959
14960 pub fn highlight_text<T: 'static>(
14961 &mut self,
14962 ranges: Vec<Range<Anchor>>,
14963 style: HighlightStyle,
14964 cx: &mut Context<Self>,
14965 ) {
14966 self.display_map.update(cx, |map, _| {
14967 map.highlight_text(TypeId::of::<T>(), ranges, style)
14968 });
14969 cx.notify();
14970 }
14971
14972 pub(crate) fn highlight_inlays<T: 'static>(
14973 &mut self,
14974 highlights: Vec<InlayHighlight>,
14975 style: HighlightStyle,
14976 cx: &mut Context<Self>,
14977 ) {
14978 self.display_map.update(cx, |map, _| {
14979 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14980 });
14981 cx.notify();
14982 }
14983
14984 pub fn text_highlights<'a, T: 'static>(
14985 &'a self,
14986 cx: &'a App,
14987 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14988 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14989 }
14990
14991 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14992 let cleared = self
14993 .display_map
14994 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14995 if cleared {
14996 cx.notify();
14997 }
14998 }
14999
15000 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15001 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15002 && self.focus_handle.is_focused(window)
15003 }
15004
15005 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15006 self.show_cursor_when_unfocused = is_enabled;
15007 cx.notify();
15008 }
15009
15010 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15011 cx.notify();
15012 }
15013
15014 fn on_buffer_event(
15015 &mut self,
15016 multibuffer: &Entity<MultiBuffer>,
15017 event: &multi_buffer::Event,
15018 window: &mut Window,
15019 cx: &mut Context<Self>,
15020 ) {
15021 match event {
15022 multi_buffer::Event::Edited {
15023 singleton_buffer_edited,
15024 edited_buffer: buffer_edited,
15025 } => {
15026 self.scrollbar_marker_state.dirty = true;
15027 self.active_indent_guides_state.dirty = true;
15028 self.refresh_active_diagnostics(cx);
15029 self.refresh_code_actions(window, cx);
15030 if self.has_active_inline_completion() {
15031 self.update_visible_inline_completion(window, cx);
15032 }
15033 if let Some(buffer) = buffer_edited {
15034 let buffer_id = buffer.read(cx).remote_id();
15035 if !self.registered_buffers.contains_key(&buffer_id) {
15036 if let Some(project) = self.project.as_ref() {
15037 project.update(cx, |project, cx| {
15038 self.registered_buffers.insert(
15039 buffer_id,
15040 project.register_buffer_with_language_servers(&buffer, cx),
15041 );
15042 })
15043 }
15044 }
15045 }
15046 cx.emit(EditorEvent::BufferEdited);
15047 cx.emit(SearchEvent::MatchesInvalidated);
15048 if *singleton_buffer_edited {
15049 if let Some(project) = &self.project {
15050 #[allow(clippy::mutable_key_type)]
15051 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15052 multibuffer
15053 .all_buffers()
15054 .into_iter()
15055 .filter_map(|buffer| {
15056 buffer.update(cx, |buffer, cx| {
15057 let language = buffer.language()?;
15058 let should_discard = project.update(cx, |project, cx| {
15059 project.is_local()
15060 && !project.has_language_servers_for(buffer, cx)
15061 });
15062 should_discard.not().then_some(language.clone())
15063 })
15064 })
15065 .collect::<HashSet<_>>()
15066 });
15067 if !languages_affected.is_empty() {
15068 self.refresh_inlay_hints(
15069 InlayHintRefreshReason::BufferEdited(languages_affected),
15070 cx,
15071 );
15072 }
15073 }
15074 }
15075
15076 let Some(project) = &self.project else { return };
15077 let (telemetry, is_via_ssh) = {
15078 let project = project.read(cx);
15079 let telemetry = project.client().telemetry().clone();
15080 let is_via_ssh = project.is_via_ssh();
15081 (telemetry, is_via_ssh)
15082 };
15083 refresh_linked_ranges(self, window, cx);
15084 telemetry.log_edit_event("editor", is_via_ssh);
15085 }
15086 multi_buffer::Event::ExcerptsAdded {
15087 buffer,
15088 predecessor,
15089 excerpts,
15090 } => {
15091 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15092 let buffer_id = buffer.read(cx).remote_id();
15093 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15094 if let Some(project) = &self.project {
15095 get_uncommitted_diff_for_buffer(
15096 project,
15097 [buffer.clone()],
15098 self.buffer.clone(),
15099 cx,
15100 )
15101 .detach();
15102 }
15103 }
15104 cx.emit(EditorEvent::ExcerptsAdded {
15105 buffer: buffer.clone(),
15106 predecessor: *predecessor,
15107 excerpts: excerpts.clone(),
15108 });
15109 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15110 }
15111 multi_buffer::Event::ExcerptsRemoved { ids } => {
15112 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15113 let buffer = self.buffer.read(cx);
15114 self.registered_buffers
15115 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15116 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15117 }
15118 multi_buffer::Event::ExcerptsEdited { ids } => {
15119 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15120 }
15121 multi_buffer::Event::ExcerptsExpanded { ids } => {
15122 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15123 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15124 }
15125 multi_buffer::Event::Reparsed(buffer_id) => {
15126 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15127
15128 cx.emit(EditorEvent::Reparsed(*buffer_id));
15129 }
15130 multi_buffer::Event::DiffHunksToggled => {
15131 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15132 }
15133 multi_buffer::Event::LanguageChanged(buffer_id) => {
15134 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15135 cx.emit(EditorEvent::Reparsed(*buffer_id));
15136 cx.notify();
15137 }
15138 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15139 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15140 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15141 cx.emit(EditorEvent::TitleChanged)
15142 }
15143 // multi_buffer::Event::DiffBaseChanged => {
15144 // self.scrollbar_marker_state.dirty = true;
15145 // cx.emit(EditorEvent::DiffBaseChanged);
15146 // cx.notify();
15147 // }
15148 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15149 multi_buffer::Event::DiagnosticsUpdated => {
15150 self.refresh_active_diagnostics(cx);
15151 self.refresh_inline_diagnostics(true, window, cx);
15152 self.scrollbar_marker_state.dirty = true;
15153 cx.notify();
15154 }
15155 _ => {}
15156 };
15157 }
15158
15159 fn on_display_map_changed(
15160 &mut self,
15161 _: Entity<DisplayMap>,
15162 _: &mut Window,
15163 cx: &mut Context<Self>,
15164 ) {
15165 cx.notify();
15166 }
15167
15168 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15169 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15170 self.update_edit_prediction_settings(cx);
15171 self.refresh_inline_completion(true, false, window, cx);
15172 self.refresh_inlay_hints(
15173 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15174 self.selections.newest_anchor().head(),
15175 &self.buffer.read(cx).snapshot(cx),
15176 cx,
15177 )),
15178 cx,
15179 );
15180
15181 let old_cursor_shape = self.cursor_shape;
15182
15183 {
15184 let editor_settings = EditorSettings::get_global(cx);
15185 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15186 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15187 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15188 }
15189
15190 if old_cursor_shape != self.cursor_shape {
15191 cx.emit(EditorEvent::CursorShapeChanged);
15192 }
15193
15194 let project_settings = ProjectSettings::get_global(cx);
15195 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15196
15197 if self.mode == EditorMode::Full {
15198 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15199 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15200 if self.show_inline_diagnostics != show_inline_diagnostics {
15201 self.show_inline_diagnostics = show_inline_diagnostics;
15202 self.refresh_inline_diagnostics(false, window, cx);
15203 }
15204
15205 if self.git_blame_inline_enabled != inline_blame_enabled {
15206 self.toggle_git_blame_inline_internal(false, window, cx);
15207 }
15208 }
15209
15210 cx.notify();
15211 }
15212
15213 pub fn set_searchable(&mut self, searchable: bool) {
15214 self.searchable = searchable;
15215 }
15216
15217 pub fn searchable(&self) -> bool {
15218 self.searchable
15219 }
15220
15221 fn open_proposed_changes_editor(
15222 &mut self,
15223 _: &OpenProposedChangesEditor,
15224 window: &mut Window,
15225 cx: &mut Context<Self>,
15226 ) {
15227 let Some(workspace) = self.workspace() else {
15228 cx.propagate();
15229 return;
15230 };
15231
15232 let selections = self.selections.all::<usize>(cx);
15233 let multi_buffer = self.buffer.read(cx);
15234 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15235 let mut new_selections_by_buffer = HashMap::default();
15236 for selection in selections {
15237 for (buffer, range, _) in
15238 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15239 {
15240 let mut range = range.to_point(buffer);
15241 range.start.column = 0;
15242 range.end.column = buffer.line_len(range.end.row);
15243 new_selections_by_buffer
15244 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15245 .or_insert(Vec::new())
15246 .push(range)
15247 }
15248 }
15249
15250 let proposed_changes_buffers = new_selections_by_buffer
15251 .into_iter()
15252 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15253 .collect::<Vec<_>>();
15254 let proposed_changes_editor = cx.new(|cx| {
15255 ProposedChangesEditor::new(
15256 "Proposed changes",
15257 proposed_changes_buffers,
15258 self.project.clone(),
15259 window,
15260 cx,
15261 )
15262 });
15263
15264 window.defer(cx, move |window, cx| {
15265 workspace.update(cx, |workspace, cx| {
15266 workspace.active_pane().update(cx, |pane, cx| {
15267 pane.add_item(
15268 Box::new(proposed_changes_editor),
15269 true,
15270 true,
15271 None,
15272 window,
15273 cx,
15274 );
15275 });
15276 });
15277 });
15278 }
15279
15280 pub fn open_excerpts_in_split(
15281 &mut self,
15282 _: &OpenExcerptsSplit,
15283 window: &mut Window,
15284 cx: &mut Context<Self>,
15285 ) {
15286 self.open_excerpts_common(None, true, window, cx)
15287 }
15288
15289 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15290 self.open_excerpts_common(None, false, window, cx)
15291 }
15292
15293 fn open_excerpts_common(
15294 &mut self,
15295 jump_data: Option<JumpData>,
15296 split: bool,
15297 window: &mut Window,
15298 cx: &mut Context<Self>,
15299 ) {
15300 let Some(workspace) = self.workspace() else {
15301 cx.propagate();
15302 return;
15303 };
15304
15305 if self.buffer.read(cx).is_singleton() {
15306 cx.propagate();
15307 return;
15308 }
15309
15310 let mut new_selections_by_buffer = HashMap::default();
15311 match &jump_data {
15312 Some(JumpData::MultiBufferPoint {
15313 excerpt_id,
15314 position,
15315 anchor,
15316 line_offset_from_top,
15317 }) => {
15318 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15319 if let Some(buffer) = multi_buffer_snapshot
15320 .buffer_id_for_excerpt(*excerpt_id)
15321 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15322 {
15323 let buffer_snapshot = buffer.read(cx).snapshot();
15324 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15325 language::ToPoint::to_point(anchor, &buffer_snapshot)
15326 } else {
15327 buffer_snapshot.clip_point(*position, Bias::Left)
15328 };
15329 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15330 new_selections_by_buffer.insert(
15331 buffer,
15332 (
15333 vec![jump_to_offset..jump_to_offset],
15334 Some(*line_offset_from_top),
15335 ),
15336 );
15337 }
15338 }
15339 Some(JumpData::MultiBufferRow {
15340 row,
15341 line_offset_from_top,
15342 }) => {
15343 let point = MultiBufferPoint::new(row.0, 0);
15344 if let Some((buffer, buffer_point, _)) =
15345 self.buffer.read(cx).point_to_buffer_point(point, cx)
15346 {
15347 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15348 new_selections_by_buffer
15349 .entry(buffer)
15350 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15351 .0
15352 .push(buffer_offset..buffer_offset)
15353 }
15354 }
15355 None => {
15356 let selections = self.selections.all::<usize>(cx);
15357 let multi_buffer = self.buffer.read(cx);
15358 for selection in selections {
15359 for (snapshot, range, _, anchor) in multi_buffer
15360 .snapshot(cx)
15361 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15362 {
15363 if let Some(anchor) = anchor {
15364 // selection is in a deleted hunk
15365 let Some(buffer_id) = anchor.buffer_id else {
15366 continue;
15367 };
15368 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15369 continue;
15370 };
15371 let offset = text::ToOffset::to_offset(
15372 &anchor.text_anchor,
15373 &buffer_handle.read(cx).snapshot(),
15374 );
15375 let range = offset..offset;
15376 new_selections_by_buffer
15377 .entry(buffer_handle)
15378 .or_insert((Vec::new(), None))
15379 .0
15380 .push(range)
15381 } else {
15382 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15383 else {
15384 continue;
15385 };
15386 new_selections_by_buffer
15387 .entry(buffer_handle)
15388 .or_insert((Vec::new(), None))
15389 .0
15390 .push(range)
15391 }
15392 }
15393 }
15394 }
15395 }
15396
15397 if new_selections_by_buffer.is_empty() {
15398 return;
15399 }
15400
15401 // We defer the pane interaction because we ourselves are a workspace item
15402 // and activating a new item causes the pane to call a method on us reentrantly,
15403 // which panics if we're on the stack.
15404 window.defer(cx, move |window, cx| {
15405 workspace.update(cx, |workspace, cx| {
15406 let pane = if split {
15407 workspace.adjacent_pane(window, cx)
15408 } else {
15409 workspace.active_pane().clone()
15410 };
15411
15412 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15413 let editor = buffer
15414 .read(cx)
15415 .file()
15416 .is_none()
15417 .then(|| {
15418 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15419 // so `workspace.open_project_item` will never find them, always opening a new editor.
15420 // Instead, we try to activate the existing editor in the pane first.
15421 let (editor, pane_item_index) =
15422 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15423 let editor = item.downcast::<Editor>()?;
15424 let singleton_buffer =
15425 editor.read(cx).buffer().read(cx).as_singleton()?;
15426 if singleton_buffer == buffer {
15427 Some((editor, i))
15428 } else {
15429 None
15430 }
15431 })?;
15432 pane.update(cx, |pane, cx| {
15433 pane.activate_item(pane_item_index, true, true, window, cx)
15434 });
15435 Some(editor)
15436 })
15437 .flatten()
15438 .unwrap_or_else(|| {
15439 workspace.open_project_item::<Self>(
15440 pane.clone(),
15441 buffer,
15442 true,
15443 true,
15444 window,
15445 cx,
15446 )
15447 });
15448
15449 editor.update(cx, |editor, cx| {
15450 let autoscroll = match scroll_offset {
15451 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15452 None => Autoscroll::newest(),
15453 };
15454 let nav_history = editor.nav_history.take();
15455 editor.change_selections(Some(autoscroll), window, cx, |s| {
15456 s.select_ranges(ranges);
15457 });
15458 editor.nav_history = nav_history;
15459 });
15460 }
15461 })
15462 });
15463 }
15464
15465 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15466 let snapshot = self.buffer.read(cx).read(cx);
15467 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15468 Some(
15469 ranges
15470 .iter()
15471 .map(move |range| {
15472 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15473 })
15474 .collect(),
15475 )
15476 }
15477
15478 fn selection_replacement_ranges(
15479 &self,
15480 range: Range<OffsetUtf16>,
15481 cx: &mut App,
15482 ) -> Vec<Range<OffsetUtf16>> {
15483 let selections = self.selections.all::<OffsetUtf16>(cx);
15484 let newest_selection = selections
15485 .iter()
15486 .max_by_key(|selection| selection.id)
15487 .unwrap();
15488 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15489 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15490 let snapshot = self.buffer.read(cx).read(cx);
15491 selections
15492 .into_iter()
15493 .map(|mut selection| {
15494 selection.start.0 =
15495 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15496 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15497 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15498 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15499 })
15500 .collect()
15501 }
15502
15503 fn report_editor_event(
15504 &self,
15505 event_type: &'static str,
15506 file_extension: Option<String>,
15507 cx: &App,
15508 ) {
15509 if cfg!(any(test, feature = "test-support")) {
15510 return;
15511 }
15512
15513 let Some(project) = &self.project else { return };
15514
15515 // If None, we are in a file without an extension
15516 let file = self
15517 .buffer
15518 .read(cx)
15519 .as_singleton()
15520 .and_then(|b| b.read(cx).file());
15521 let file_extension = file_extension.or(file
15522 .as_ref()
15523 .and_then(|file| Path::new(file.file_name(cx)).extension())
15524 .and_then(|e| e.to_str())
15525 .map(|a| a.to_string()));
15526
15527 let vim_mode = cx
15528 .global::<SettingsStore>()
15529 .raw_user_settings()
15530 .get("vim_mode")
15531 == Some(&serde_json::Value::Bool(true));
15532
15533 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15534 let copilot_enabled = edit_predictions_provider
15535 == language::language_settings::EditPredictionProvider::Copilot;
15536 let copilot_enabled_for_language = self
15537 .buffer
15538 .read(cx)
15539 .settings_at(0, cx)
15540 .show_edit_predictions;
15541
15542 let project = project.read(cx);
15543 telemetry::event!(
15544 event_type,
15545 file_extension,
15546 vim_mode,
15547 copilot_enabled,
15548 copilot_enabled_for_language,
15549 edit_predictions_provider,
15550 is_via_ssh = project.is_via_ssh(),
15551 );
15552 }
15553
15554 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15555 /// with each line being an array of {text, highlight} objects.
15556 fn copy_highlight_json(
15557 &mut self,
15558 _: &CopyHighlightJson,
15559 window: &mut Window,
15560 cx: &mut Context<Self>,
15561 ) {
15562 #[derive(Serialize)]
15563 struct Chunk<'a> {
15564 text: String,
15565 highlight: Option<&'a str>,
15566 }
15567
15568 let snapshot = self.buffer.read(cx).snapshot(cx);
15569 let range = self
15570 .selected_text_range(false, window, cx)
15571 .and_then(|selection| {
15572 if selection.range.is_empty() {
15573 None
15574 } else {
15575 Some(selection.range)
15576 }
15577 })
15578 .unwrap_or_else(|| 0..snapshot.len());
15579
15580 let chunks = snapshot.chunks(range, true);
15581 let mut lines = Vec::new();
15582 let mut line: VecDeque<Chunk> = VecDeque::new();
15583
15584 let Some(style) = self.style.as_ref() else {
15585 return;
15586 };
15587
15588 for chunk in chunks {
15589 let highlight = chunk
15590 .syntax_highlight_id
15591 .and_then(|id| id.name(&style.syntax));
15592 let mut chunk_lines = chunk.text.split('\n').peekable();
15593 while let Some(text) = chunk_lines.next() {
15594 let mut merged_with_last_token = false;
15595 if let Some(last_token) = line.back_mut() {
15596 if last_token.highlight == highlight {
15597 last_token.text.push_str(text);
15598 merged_with_last_token = true;
15599 }
15600 }
15601
15602 if !merged_with_last_token {
15603 line.push_back(Chunk {
15604 text: text.into(),
15605 highlight,
15606 });
15607 }
15608
15609 if chunk_lines.peek().is_some() {
15610 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15611 line.pop_front();
15612 }
15613 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15614 line.pop_back();
15615 }
15616
15617 lines.push(mem::take(&mut line));
15618 }
15619 }
15620 }
15621
15622 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15623 return;
15624 };
15625 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15626 }
15627
15628 pub fn open_context_menu(
15629 &mut self,
15630 _: &OpenContextMenu,
15631 window: &mut Window,
15632 cx: &mut Context<Self>,
15633 ) {
15634 self.request_autoscroll(Autoscroll::newest(), cx);
15635 let position = self.selections.newest_display(cx).start;
15636 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15637 }
15638
15639 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15640 &self.inlay_hint_cache
15641 }
15642
15643 pub fn replay_insert_event(
15644 &mut self,
15645 text: &str,
15646 relative_utf16_range: Option<Range<isize>>,
15647 window: &mut Window,
15648 cx: &mut Context<Self>,
15649 ) {
15650 if !self.input_enabled {
15651 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15652 return;
15653 }
15654 if let Some(relative_utf16_range) = relative_utf16_range {
15655 let selections = self.selections.all::<OffsetUtf16>(cx);
15656 self.change_selections(None, window, cx, |s| {
15657 let new_ranges = selections.into_iter().map(|range| {
15658 let start = OffsetUtf16(
15659 range
15660 .head()
15661 .0
15662 .saturating_add_signed(relative_utf16_range.start),
15663 );
15664 let end = OffsetUtf16(
15665 range
15666 .head()
15667 .0
15668 .saturating_add_signed(relative_utf16_range.end),
15669 );
15670 start..end
15671 });
15672 s.select_ranges(new_ranges);
15673 });
15674 }
15675
15676 self.handle_input(text, window, cx);
15677 }
15678
15679 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15680 let Some(provider) = self.semantics_provider.as_ref() else {
15681 return false;
15682 };
15683
15684 let mut supports = false;
15685 self.buffer().update(cx, |this, cx| {
15686 this.for_each_buffer(|buffer| {
15687 supports |= provider.supports_inlay_hints(buffer, cx);
15688 });
15689 });
15690
15691 supports
15692 }
15693
15694 pub fn is_focused(&self, window: &Window) -> bool {
15695 self.focus_handle.is_focused(window)
15696 }
15697
15698 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15699 cx.emit(EditorEvent::Focused);
15700
15701 if let Some(descendant) = self
15702 .last_focused_descendant
15703 .take()
15704 .and_then(|descendant| descendant.upgrade())
15705 {
15706 window.focus(&descendant);
15707 } else {
15708 if let Some(blame) = self.blame.as_ref() {
15709 blame.update(cx, GitBlame::focus)
15710 }
15711
15712 self.blink_manager.update(cx, BlinkManager::enable);
15713 self.show_cursor_names(window, cx);
15714 self.buffer.update(cx, |buffer, cx| {
15715 buffer.finalize_last_transaction(cx);
15716 if self.leader_peer_id.is_none() {
15717 buffer.set_active_selections(
15718 &self.selections.disjoint_anchors(),
15719 self.selections.line_mode,
15720 self.cursor_shape,
15721 cx,
15722 );
15723 }
15724 });
15725 }
15726 }
15727
15728 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15729 cx.emit(EditorEvent::FocusedIn)
15730 }
15731
15732 fn handle_focus_out(
15733 &mut self,
15734 event: FocusOutEvent,
15735 _window: &mut Window,
15736 _cx: &mut Context<Self>,
15737 ) {
15738 if event.blurred != self.focus_handle {
15739 self.last_focused_descendant = Some(event.blurred);
15740 }
15741 }
15742
15743 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15744 self.blink_manager.update(cx, BlinkManager::disable);
15745 self.buffer
15746 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15747
15748 if let Some(blame) = self.blame.as_ref() {
15749 blame.update(cx, GitBlame::blur)
15750 }
15751 if !self.hover_state.focused(window, cx) {
15752 hide_hover(self, cx);
15753 }
15754 if !self
15755 .context_menu
15756 .borrow()
15757 .as_ref()
15758 .is_some_and(|context_menu| context_menu.focused(window, cx))
15759 {
15760 self.hide_context_menu(window, cx);
15761 }
15762 self.discard_inline_completion(false, cx);
15763 cx.emit(EditorEvent::Blurred);
15764 cx.notify();
15765 }
15766
15767 pub fn register_action<A: Action>(
15768 &mut self,
15769 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15770 ) -> Subscription {
15771 let id = self.next_editor_action_id.post_inc();
15772 let listener = Arc::new(listener);
15773 self.editor_actions.borrow_mut().insert(
15774 id,
15775 Box::new(move |window, _| {
15776 let listener = listener.clone();
15777 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15778 let action = action.downcast_ref().unwrap();
15779 if phase == DispatchPhase::Bubble {
15780 listener(action, window, cx)
15781 }
15782 })
15783 }),
15784 );
15785
15786 let editor_actions = self.editor_actions.clone();
15787 Subscription::new(move || {
15788 editor_actions.borrow_mut().remove(&id);
15789 })
15790 }
15791
15792 pub fn file_header_size(&self) -> u32 {
15793 FILE_HEADER_HEIGHT
15794 }
15795
15796 pub fn revert(
15797 &mut self,
15798 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15799 window: &mut Window,
15800 cx: &mut Context<Self>,
15801 ) {
15802 self.buffer().update(cx, |multi_buffer, cx| {
15803 for (buffer_id, changes) in revert_changes {
15804 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15805 buffer.update(cx, |buffer, cx| {
15806 buffer.edit(
15807 changes.into_iter().map(|(range, text)| {
15808 (range, text.to_string().map(Arc::<str>::from))
15809 }),
15810 None,
15811 cx,
15812 );
15813 });
15814 }
15815 }
15816 });
15817 self.change_selections(None, window, cx, |selections| selections.refresh());
15818 }
15819
15820 pub fn to_pixel_point(
15821 &self,
15822 source: multi_buffer::Anchor,
15823 editor_snapshot: &EditorSnapshot,
15824 window: &mut Window,
15825 ) -> Option<gpui::Point<Pixels>> {
15826 let source_point = source.to_display_point(editor_snapshot);
15827 self.display_to_pixel_point(source_point, editor_snapshot, window)
15828 }
15829
15830 pub fn display_to_pixel_point(
15831 &self,
15832 source: DisplayPoint,
15833 editor_snapshot: &EditorSnapshot,
15834 window: &mut Window,
15835 ) -> Option<gpui::Point<Pixels>> {
15836 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15837 let text_layout_details = self.text_layout_details(window);
15838 let scroll_top = text_layout_details
15839 .scroll_anchor
15840 .scroll_position(editor_snapshot)
15841 .y;
15842
15843 if source.row().as_f32() < scroll_top.floor() {
15844 return None;
15845 }
15846 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15847 let source_y = line_height * (source.row().as_f32() - scroll_top);
15848 Some(gpui::Point::new(source_x, source_y))
15849 }
15850
15851 pub fn has_visible_completions_menu(&self) -> bool {
15852 !self.edit_prediction_preview_is_active()
15853 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15854 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15855 })
15856 }
15857
15858 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15859 self.addons
15860 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15861 }
15862
15863 pub fn unregister_addon<T: Addon>(&mut self) {
15864 self.addons.remove(&std::any::TypeId::of::<T>());
15865 }
15866
15867 pub fn addon<T: Addon>(&self) -> Option<&T> {
15868 let type_id = std::any::TypeId::of::<T>();
15869 self.addons
15870 .get(&type_id)
15871 .and_then(|item| item.to_any().downcast_ref::<T>())
15872 }
15873
15874 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15875 let text_layout_details = self.text_layout_details(window);
15876 let style = &text_layout_details.editor_style;
15877 let font_id = window.text_system().resolve_font(&style.text.font());
15878 let font_size = style.text.font_size.to_pixels(window.rem_size());
15879 let line_height = style.text.line_height_in_pixels(window.rem_size());
15880 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15881
15882 gpui::Size::new(em_width, line_height)
15883 }
15884
15885 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15886 self.load_diff_task.clone()
15887 }
15888
15889 fn read_selections_from_db(
15890 &mut self,
15891 item_id: u64,
15892 workspace_id: WorkspaceId,
15893 window: &mut Window,
15894 cx: &mut Context<Editor>,
15895 ) {
15896 if !self.is_singleton(cx)
15897 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15898 {
15899 return;
15900 }
15901 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15902 return;
15903 };
15904 if selections.is_empty() {
15905 return;
15906 }
15907
15908 let snapshot = self.buffer.read(cx).snapshot(cx);
15909 self.change_selections(None, window, cx, |s| {
15910 s.select_ranges(selections.into_iter().map(|(start, end)| {
15911 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15912 }));
15913 });
15914 }
15915}
15916
15917fn insert_extra_newline_brackets(
15918 buffer: &MultiBufferSnapshot,
15919 range: Range<usize>,
15920 language: &language::LanguageScope,
15921) -> bool {
15922 let leading_whitespace_len = buffer
15923 .reversed_chars_at(range.start)
15924 .take_while(|c| c.is_whitespace() && *c != '\n')
15925 .map(|c| c.len_utf8())
15926 .sum::<usize>();
15927 let trailing_whitespace_len = buffer
15928 .chars_at(range.end)
15929 .take_while(|c| c.is_whitespace() && *c != '\n')
15930 .map(|c| c.len_utf8())
15931 .sum::<usize>();
15932 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
15933
15934 language.brackets().any(|(pair, enabled)| {
15935 let pair_start = pair.start.trim_end();
15936 let pair_end = pair.end.trim_start();
15937
15938 enabled
15939 && pair.newline
15940 && buffer.contains_str_at(range.end, pair_end)
15941 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
15942 })
15943}
15944
15945fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
15946 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
15947 [(buffer, range, _)] => (*buffer, range.clone()),
15948 _ => return false,
15949 };
15950 let pair = {
15951 let mut result: Option<BracketMatch> = None;
15952
15953 for pair in buffer
15954 .all_bracket_ranges(range.clone())
15955 .filter(move |pair| {
15956 pair.open_range.start <= range.start && pair.close_range.end >= range.end
15957 })
15958 {
15959 let len = pair.close_range.end - pair.open_range.start;
15960
15961 if let Some(existing) = &result {
15962 let existing_len = existing.close_range.end - existing.open_range.start;
15963 if len > existing_len {
15964 continue;
15965 }
15966 }
15967
15968 result = Some(pair);
15969 }
15970
15971 result
15972 };
15973 let Some(pair) = pair else {
15974 return false;
15975 };
15976 pair.newline_only
15977 && buffer
15978 .chars_for_range(pair.open_range.end..range.start)
15979 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
15980 .all(|c| c.is_whitespace() && c != '\n')
15981}
15982
15983fn get_uncommitted_diff_for_buffer(
15984 project: &Entity<Project>,
15985 buffers: impl IntoIterator<Item = Entity<Buffer>>,
15986 buffer: Entity<MultiBuffer>,
15987 cx: &mut App,
15988) -> Task<()> {
15989 let mut tasks = Vec::new();
15990 project.update(cx, |project, cx| {
15991 for buffer in buffers {
15992 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15993 }
15994 });
15995 cx.spawn(|mut cx| async move {
15996 let diffs = futures::future::join_all(tasks).await;
15997 buffer
15998 .update(&mut cx, |buffer, cx| {
15999 for diff in diffs.into_iter().flatten() {
16000 buffer.add_diff(diff, cx);
16001 }
16002 })
16003 .ok();
16004 })
16005}
16006
16007fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16008 let tab_size = tab_size.get() as usize;
16009 let mut width = offset;
16010
16011 for ch in text.chars() {
16012 width += if ch == '\t' {
16013 tab_size - (width % tab_size)
16014 } else {
16015 1
16016 };
16017 }
16018
16019 width - offset
16020}
16021
16022#[cfg(test)]
16023mod tests {
16024 use super::*;
16025
16026 #[test]
16027 fn test_string_size_with_expanded_tabs() {
16028 let nz = |val| NonZeroU32::new(val).unwrap();
16029 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16030 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16031 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16032 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16033 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16034 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16035 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16036 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16037 }
16038}
16039
16040/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16041struct WordBreakingTokenizer<'a> {
16042 input: &'a str,
16043}
16044
16045impl<'a> WordBreakingTokenizer<'a> {
16046 fn new(input: &'a str) -> Self {
16047 Self { input }
16048 }
16049}
16050
16051fn is_char_ideographic(ch: char) -> bool {
16052 use unicode_script::Script::*;
16053 use unicode_script::UnicodeScript;
16054 matches!(ch.script(), Han | Tangut | Yi)
16055}
16056
16057fn is_grapheme_ideographic(text: &str) -> bool {
16058 text.chars().any(is_char_ideographic)
16059}
16060
16061fn is_grapheme_whitespace(text: &str) -> bool {
16062 text.chars().any(|x| x.is_whitespace())
16063}
16064
16065fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16066 text.chars().next().map_or(false, |ch| {
16067 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16068 })
16069}
16070
16071#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16072struct WordBreakToken<'a> {
16073 token: &'a str,
16074 grapheme_len: usize,
16075 is_whitespace: bool,
16076}
16077
16078impl<'a> Iterator for WordBreakingTokenizer<'a> {
16079 /// Yields a span, the count of graphemes in the token, and whether it was
16080 /// whitespace. Note that it also breaks at word boundaries.
16081 type Item = WordBreakToken<'a>;
16082
16083 fn next(&mut self) -> Option<Self::Item> {
16084 use unicode_segmentation::UnicodeSegmentation;
16085 if self.input.is_empty() {
16086 return None;
16087 }
16088
16089 let mut iter = self.input.graphemes(true).peekable();
16090 let mut offset = 0;
16091 let mut graphemes = 0;
16092 if let Some(first_grapheme) = iter.next() {
16093 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16094 offset += first_grapheme.len();
16095 graphemes += 1;
16096 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16097 if let Some(grapheme) = iter.peek().copied() {
16098 if should_stay_with_preceding_ideograph(grapheme) {
16099 offset += grapheme.len();
16100 graphemes += 1;
16101 }
16102 }
16103 } else {
16104 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16105 let mut next_word_bound = words.peek().copied();
16106 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16107 next_word_bound = words.next();
16108 }
16109 while let Some(grapheme) = iter.peek().copied() {
16110 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16111 break;
16112 };
16113 if is_grapheme_whitespace(grapheme) != is_whitespace {
16114 break;
16115 };
16116 offset += grapheme.len();
16117 graphemes += 1;
16118 iter.next();
16119 }
16120 }
16121 let token = &self.input[..offset];
16122 self.input = &self.input[offset..];
16123 if is_whitespace {
16124 Some(WordBreakToken {
16125 token: " ",
16126 grapheme_len: 1,
16127 is_whitespace: true,
16128 })
16129 } else {
16130 Some(WordBreakToken {
16131 token,
16132 grapheme_len: graphemes,
16133 is_whitespace: false,
16134 })
16135 }
16136 } else {
16137 None
16138 }
16139 }
16140}
16141
16142#[test]
16143fn test_word_breaking_tokenizer() {
16144 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16145 ("", &[]),
16146 (" ", &[(" ", 1, true)]),
16147 ("Ʒ", &[("Ʒ", 1, false)]),
16148 ("Ǽ", &[("Ǽ", 1, false)]),
16149 ("⋑", &[("⋑", 1, false)]),
16150 ("⋑⋑", &[("⋑⋑", 2, false)]),
16151 (
16152 "原理,进而",
16153 &[
16154 ("原", 1, false),
16155 ("理,", 2, false),
16156 ("进", 1, false),
16157 ("而", 1, false),
16158 ],
16159 ),
16160 (
16161 "hello world",
16162 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16163 ),
16164 (
16165 "hello, world",
16166 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16167 ),
16168 (
16169 " hello world",
16170 &[
16171 (" ", 1, true),
16172 ("hello", 5, false),
16173 (" ", 1, true),
16174 ("world", 5, false),
16175 ],
16176 ),
16177 (
16178 "这是什么 \n 钢笔",
16179 &[
16180 ("这", 1, false),
16181 ("是", 1, false),
16182 ("什", 1, false),
16183 ("么", 1, false),
16184 (" ", 1, true),
16185 ("钢", 1, false),
16186 ("笔", 1, false),
16187 ],
16188 ),
16189 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16190 ];
16191
16192 for (input, result) in tests {
16193 assert_eq!(
16194 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16195 result
16196 .iter()
16197 .copied()
16198 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16199 token,
16200 grapheme_len,
16201 is_whitespace,
16202 })
16203 .collect::<Vec<_>>()
16204 );
16205 }
16206}
16207
16208fn wrap_with_prefix(
16209 line_prefix: String,
16210 unwrapped_text: String,
16211 wrap_column: usize,
16212 tab_size: NonZeroU32,
16213) -> String {
16214 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16215 let mut wrapped_text = String::new();
16216 let mut current_line = line_prefix.clone();
16217
16218 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16219 let mut current_line_len = line_prefix_len;
16220 for WordBreakToken {
16221 token,
16222 grapheme_len,
16223 is_whitespace,
16224 } in tokenizer
16225 {
16226 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16227 wrapped_text.push_str(current_line.trim_end());
16228 wrapped_text.push('\n');
16229 current_line.truncate(line_prefix.len());
16230 current_line_len = line_prefix_len;
16231 if !is_whitespace {
16232 current_line.push_str(token);
16233 current_line_len += grapheme_len;
16234 }
16235 } else if !is_whitespace {
16236 current_line.push_str(token);
16237 current_line_len += grapheme_len;
16238 } else if current_line_len != line_prefix_len {
16239 current_line.push(' ');
16240 current_line_len += 1;
16241 }
16242 }
16243
16244 if !current_line.is_empty() {
16245 wrapped_text.push_str(¤t_line);
16246 }
16247 wrapped_text
16248}
16249
16250#[test]
16251fn test_wrap_with_prefix() {
16252 assert_eq!(
16253 wrap_with_prefix(
16254 "# ".to_string(),
16255 "abcdefg".to_string(),
16256 4,
16257 NonZeroU32::new(4).unwrap()
16258 ),
16259 "# abcdefg"
16260 );
16261 assert_eq!(
16262 wrap_with_prefix(
16263 "".to_string(),
16264 "\thello world".to_string(),
16265 8,
16266 NonZeroU32::new(4).unwrap()
16267 ),
16268 "hello\nworld"
16269 );
16270 assert_eq!(
16271 wrap_with_prefix(
16272 "// ".to_string(),
16273 "xx \nyy zz aa bb cc".to_string(),
16274 12,
16275 NonZeroU32::new(4).unwrap()
16276 ),
16277 "// xx yy zz\n// aa bb cc"
16278 );
16279 assert_eq!(
16280 wrap_with_prefix(
16281 String::new(),
16282 "这是什么 \n 钢笔".to_string(),
16283 3,
16284 NonZeroU32::new(4).unwrap()
16285 ),
16286 "这是什\n么 钢\n笔"
16287 );
16288}
16289
16290pub trait CollaborationHub {
16291 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16292 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16293 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16294}
16295
16296impl CollaborationHub for Entity<Project> {
16297 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16298 self.read(cx).collaborators()
16299 }
16300
16301 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16302 self.read(cx).user_store().read(cx).participant_indices()
16303 }
16304
16305 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16306 let this = self.read(cx);
16307 let user_ids = this.collaborators().values().map(|c| c.user_id);
16308 this.user_store().read_with(cx, |user_store, cx| {
16309 user_store.participant_names(user_ids, cx)
16310 })
16311 }
16312}
16313
16314pub trait SemanticsProvider {
16315 fn hover(
16316 &self,
16317 buffer: &Entity<Buffer>,
16318 position: text::Anchor,
16319 cx: &mut App,
16320 ) -> Option<Task<Vec<project::Hover>>>;
16321
16322 fn inlay_hints(
16323 &self,
16324 buffer_handle: Entity<Buffer>,
16325 range: Range<text::Anchor>,
16326 cx: &mut App,
16327 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16328
16329 fn resolve_inlay_hint(
16330 &self,
16331 hint: InlayHint,
16332 buffer_handle: Entity<Buffer>,
16333 server_id: LanguageServerId,
16334 cx: &mut App,
16335 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16336
16337 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16338
16339 fn document_highlights(
16340 &self,
16341 buffer: &Entity<Buffer>,
16342 position: text::Anchor,
16343 cx: &mut App,
16344 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16345
16346 fn definitions(
16347 &self,
16348 buffer: &Entity<Buffer>,
16349 position: text::Anchor,
16350 kind: GotoDefinitionKind,
16351 cx: &mut App,
16352 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16353
16354 fn range_for_rename(
16355 &self,
16356 buffer: &Entity<Buffer>,
16357 position: text::Anchor,
16358 cx: &mut App,
16359 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16360
16361 fn perform_rename(
16362 &self,
16363 buffer: &Entity<Buffer>,
16364 position: text::Anchor,
16365 new_name: String,
16366 cx: &mut App,
16367 ) -> Option<Task<Result<ProjectTransaction>>>;
16368}
16369
16370pub trait CompletionProvider {
16371 fn completions(
16372 &self,
16373 buffer: &Entity<Buffer>,
16374 buffer_position: text::Anchor,
16375 trigger: CompletionContext,
16376 window: &mut Window,
16377 cx: &mut Context<Editor>,
16378 ) -> Task<Result<Vec<Completion>>>;
16379
16380 fn resolve_completions(
16381 &self,
16382 buffer: Entity<Buffer>,
16383 completion_indices: Vec<usize>,
16384 completions: Rc<RefCell<Box<[Completion]>>>,
16385 cx: &mut Context<Editor>,
16386 ) -> Task<Result<bool>>;
16387
16388 fn apply_additional_edits_for_completion(
16389 &self,
16390 _buffer: Entity<Buffer>,
16391 _completions: Rc<RefCell<Box<[Completion]>>>,
16392 _completion_index: usize,
16393 _push_to_history: bool,
16394 _cx: &mut Context<Editor>,
16395 ) -> Task<Result<Option<language::Transaction>>> {
16396 Task::ready(Ok(None))
16397 }
16398
16399 fn is_completion_trigger(
16400 &self,
16401 buffer: &Entity<Buffer>,
16402 position: language::Anchor,
16403 text: &str,
16404 trigger_in_words: bool,
16405 cx: &mut Context<Editor>,
16406 ) -> bool;
16407
16408 fn sort_completions(&self) -> bool {
16409 true
16410 }
16411}
16412
16413pub trait CodeActionProvider {
16414 fn id(&self) -> Arc<str>;
16415
16416 fn code_actions(
16417 &self,
16418 buffer: &Entity<Buffer>,
16419 range: Range<text::Anchor>,
16420 window: &mut Window,
16421 cx: &mut App,
16422 ) -> Task<Result<Vec<CodeAction>>>;
16423
16424 fn apply_code_action(
16425 &self,
16426 buffer_handle: Entity<Buffer>,
16427 action: CodeAction,
16428 excerpt_id: ExcerptId,
16429 push_to_history: bool,
16430 window: &mut Window,
16431 cx: &mut App,
16432 ) -> Task<Result<ProjectTransaction>>;
16433}
16434
16435impl CodeActionProvider for Entity<Project> {
16436 fn id(&self) -> Arc<str> {
16437 "project".into()
16438 }
16439
16440 fn code_actions(
16441 &self,
16442 buffer: &Entity<Buffer>,
16443 range: Range<text::Anchor>,
16444 _window: &mut Window,
16445 cx: &mut App,
16446 ) -> Task<Result<Vec<CodeAction>>> {
16447 self.update(cx, |project, cx| {
16448 project.code_actions(buffer, range, None, cx)
16449 })
16450 }
16451
16452 fn apply_code_action(
16453 &self,
16454 buffer_handle: Entity<Buffer>,
16455 action: CodeAction,
16456 _excerpt_id: ExcerptId,
16457 push_to_history: bool,
16458 _window: &mut Window,
16459 cx: &mut App,
16460 ) -> Task<Result<ProjectTransaction>> {
16461 self.update(cx, |project, cx| {
16462 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16463 })
16464 }
16465}
16466
16467fn snippet_completions(
16468 project: &Project,
16469 buffer: &Entity<Buffer>,
16470 buffer_position: text::Anchor,
16471 cx: &mut App,
16472) -> Task<Result<Vec<Completion>>> {
16473 let language = buffer.read(cx).language_at(buffer_position);
16474 let language_name = language.as_ref().map(|language| language.lsp_id());
16475 let snippet_store = project.snippets().read(cx);
16476 let snippets = snippet_store.snippets_for(language_name, cx);
16477
16478 if snippets.is_empty() {
16479 return Task::ready(Ok(vec![]));
16480 }
16481 let snapshot = buffer.read(cx).text_snapshot();
16482 let chars: String = snapshot
16483 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16484 .collect();
16485
16486 let scope = language.map(|language| language.default_scope());
16487 let executor = cx.background_executor().clone();
16488
16489 cx.background_spawn(async move {
16490 let classifier = CharClassifier::new(scope).for_completion(true);
16491 let mut last_word = chars
16492 .chars()
16493 .take_while(|c| classifier.is_word(*c))
16494 .collect::<String>();
16495 last_word = last_word.chars().rev().collect();
16496
16497 if last_word.is_empty() {
16498 return Ok(vec![]);
16499 }
16500
16501 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16502 let to_lsp = |point: &text::Anchor| {
16503 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16504 point_to_lsp(end)
16505 };
16506 let lsp_end = to_lsp(&buffer_position);
16507
16508 let candidates = snippets
16509 .iter()
16510 .enumerate()
16511 .flat_map(|(ix, snippet)| {
16512 snippet
16513 .prefix
16514 .iter()
16515 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16516 })
16517 .collect::<Vec<StringMatchCandidate>>();
16518
16519 let mut matches = fuzzy::match_strings(
16520 &candidates,
16521 &last_word,
16522 last_word.chars().any(|c| c.is_uppercase()),
16523 100,
16524 &Default::default(),
16525 executor,
16526 )
16527 .await;
16528
16529 // Remove all candidates where the query's start does not match the start of any word in the candidate
16530 if let Some(query_start) = last_word.chars().next() {
16531 matches.retain(|string_match| {
16532 split_words(&string_match.string).any(|word| {
16533 // Check that the first codepoint of the word as lowercase matches the first
16534 // codepoint of the query as lowercase
16535 word.chars()
16536 .flat_map(|codepoint| codepoint.to_lowercase())
16537 .zip(query_start.to_lowercase())
16538 .all(|(word_cp, query_cp)| word_cp == query_cp)
16539 })
16540 });
16541 }
16542
16543 let matched_strings = matches
16544 .into_iter()
16545 .map(|m| m.string)
16546 .collect::<HashSet<_>>();
16547
16548 let result: Vec<Completion> = snippets
16549 .into_iter()
16550 .filter_map(|snippet| {
16551 let matching_prefix = snippet
16552 .prefix
16553 .iter()
16554 .find(|prefix| matched_strings.contains(*prefix))?;
16555 let start = as_offset - last_word.len();
16556 let start = snapshot.anchor_before(start);
16557 let range = start..buffer_position;
16558 let lsp_start = to_lsp(&start);
16559 let lsp_range = lsp::Range {
16560 start: lsp_start,
16561 end: lsp_end,
16562 };
16563 Some(Completion {
16564 old_range: range,
16565 new_text: snippet.body.clone(),
16566 resolved: false,
16567 label: CodeLabel {
16568 text: matching_prefix.clone(),
16569 runs: vec![],
16570 filter_range: 0..matching_prefix.len(),
16571 },
16572 server_id: LanguageServerId(usize::MAX),
16573 documentation: snippet
16574 .description
16575 .clone()
16576 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16577 lsp_completion: lsp::CompletionItem {
16578 label: snippet.prefix.first().unwrap().clone(),
16579 kind: Some(CompletionItemKind::SNIPPET),
16580 label_details: snippet.description.as_ref().map(|description| {
16581 lsp::CompletionItemLabelDetails {
16582 detail: Some(description.clone()),
16583 description: None,
16584 }
16585 }),
16586 insert_text_format: Some(InsertTextFormat::SNIPPET),
16587 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16588 lsp::InsertReplaceEdit {
16589 new_text: snippet.body.clone(),
16590 insert: lsp_range,
16591 replace: lsp_range,
16592 },
16593 )),
16594 filter_text: Some(snippet.body.clone()),
16595 sort_text: Some(char::MAX.to_string()),
16596 ..Default::default()
16597 },
16598 confirm: None,
16599 })
16600 })
16601 .collect();
16602
16603 Ok(result)
16604 })
16605}
16606
16607impl CompletionProvider for Entity<Project> {
16608 fn completions(
16609 &self,
16610 buffer: &Entity<Buffer>,
16611 buffer_position: text::Anchor,
16612 options: CompletionContext,
16613 _window: &mut Window,
16614 cx: &mut Context<Editor>,
16615 ) -> Task<Result<Vec<Completion>>> {
16616 self.update(cx, |project, cx| {
16617 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16618 let project_completions = project.completions(buffer, buffer_position, options, cx);
16619 cx.background_spawn(async move {
16620 let mut completions = project_completions.await?;
16621 let snippets_completions = snippets.await?;
16622 completions.extend(snippets_completions);
16623 Ok(completions)
16624 })
16625 })
16626 }
16627
16628 fn resolve_completions(
16629 &self,
16630 buffer: Entity<Buffer>,
16631 completion_indices: Vec<usize>,
16632 completions: Rc<RefCell<Box<[Completion]>>>,
16633 cx: &mut Context<Editor>,
16634 ) -> Task<Result<bool>> {
16635 self.update(cx, |project, cx| {
16636 project.lsp_store().update(cx, |lsp_store, cx| {
16637 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16638 })
16639 })
16640 }
16641
16642 fn apply_additional_edits_for_completion(
16643 &self,
16644 buffer: Entity<Buffer>,
16645 completions: Rc<RefCell<Box<[Completion]>>>,
16646 completion_index: usize,
16647 push_to_history: bool,
16648 cx: &mut Context<Editor>,
16649 ) -> Task<Result<Option<language::Transaction>>> {
16650 self.update(cx, |project, cx| {
16651 project.lsp_store().update(cx, |lsp_store, cx| {
16652 lsp_store.apply_additional_edits_for_completion(
16653 buffer,
16654 completions,
16655 completion_index,
16656 push_to_history,
16657 cx,
16658 )
16659 })
16660 })
16661 }
16662
16663 fn is_completion_trigger(
16664 &self,
16665 buffer: &Entity<Buffer>,
16666 position: language::Anchor,
16667 text: &str,
16668 trigger_in_words: bool,
16669 cx: &mut Context<Editor>,
16670 ) -> bool {
16671 let mut chars = text.chars();
16672 let char = if let Some(char) = chars.next() {
16673 char
16674 } else {
16675 return false;
16676 };
16677 if chars.next().is_some() {
16678 return false;
16679 }
16680
16681 let buffer = buffer.read(cx);
16682 let snapshot = buffer.snapshot();
16683 if !snapshot.settings_at(position, cx).show_completions_on_input {
16684 return false;
16685 }
16686 let classifier = snapshot.char_classifier_at(position).for_completion(true);
16687 if trigger_in_words && classifier.is_word(char) {
16688 return true;
16689 }
16690
16691 buffer.completion_triggers().contains(text)
16692 }
16693}
16694
16695impl SemanticsProvider for Entity<Project> {
16696 fn hover(
16697 &self,
16698 buffer: &Entity<Buffer>,
16699 position: text::Anchor,
16700 cx: &mut App,
16701 ) -> Option<Task<Vec<project::Hover>>> {
16702 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16703 }
16704
16705 fn document_highlights(
16706 &self,
16707 buffer: &Entity<Buffer>,
16708 position: text::Anchor,
16709 cx: &mut App,
16710 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16711 Some(self.update(cx, |project, cx| {
16712 project.document_highlights(buffer, position, cx)
16713 }))
16714 }
16715
16716 fn definitions(
16717 &self,
16718 buffer: &Entity<Buffer>,
16719 position: text::Anchor,
16720 kind: GotoDefinitionKind,
16721 cx: &mut App,
16722 ) -> Option<Task<Result<Vec<LocationLink>>>> {
16723 Some(self.update(cx, |project, cx| match kind {
16724 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16725 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16726 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16727 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16728 }))
16729 }
16730
16731 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16732 // TODO: make this work for remote projects
16733 self.update(cx, |this, cx| {
16734 buffer.update(cx, |buffer, cx| {
16735 this.any_language_server_supports_inlay_hints(buffer, cx)
16736 })
16737 })
16738 }
16739
16740 fn inlay_hints(
16741 &self,
16742 buffer_handle: Entity<Buffer>,
16743 range: Range<text::Anchor>,
16744 cx: &mut App,
16745 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16746 Some(self.update(cx, |project, cx| {
16747 project.inlay_hints(buffer_handle, range, cx)
16748 }))
16749 }
16750
16751 fn resolve_inlay_hint(
16752 &self,
16753 hint: InlayHint,
16754 buffer_handle: Entity<Buffer>,
16755 server_id: LanguageServerId,
16756 cx: &mut App,
16757 ) -> Option<Task<anyhow::Result<InlayHint>>> {
16758 Some(self.update(cx, |project, cx| {
16759 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16760 }))
16761 }
16762
16763 fn range_for_rename(
16764 &self,
16765 buffer: &Entity<Buffer>,
16766 position: text::Anchor,
16767 cx: &mut App,
16768 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16769 Some(self.update(cx, |project, cx| {
16770 let buffer = buffer.clone();
16771 let task = project.prepare_rename(buffer.clone(), position, cx);
16772 cx.spawn(|_, mut cx| async move {
16773 Ok(match task.await? {
16774 PrepareRenameResponse::Success(range) => Some(range),
16775 PrepareRenameResponse::InvalidPosition => None,
16776 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16777 // Fallback on using TreeSitter info to determine identifier range
16778 buffer.update(&mut cx, |buffer, _| {
16779 let snapshot = buffer.snapshot();
16780 let (range, kind) = snapshot.surrounding_word(position);
16781 if kind != Some(CharKind::Word) {
16782 return None;
16783 }
16784 Some(
16785 snapshot.anchor_before(range.start)
16786 ..snapshot.anchor_after(range.end),
16787 )
16788 })?
16789 }
16790 })
16791 })
16792 }))
16793 }
16794
16795 fn perform_rename(
16796 &self,
16797 buffer: &Entity<Buffer>,
16798 position: text::Anchor,
16799 new_name: String,
16800 cx: &mut App,
16801 ) -> Option<Task<Result<ProjectTransaction>>> {
16802 Some(self.update(cx, |project, cx| {
16803 project.perform_rename(buffer.clone(), position, new_name, cx)
16804 }))
16805 }
16806}
16807
16808fn inlay_hint_settings(
16809 location: Anchor,
16810 snapshot: &MultiBufferSnapshot,
16811 cx: &mut Context<Editor>,
16812) -> InlayHintSettings {
16813 let file = snapshot.file_at(location);
16814 let language = snapshot.language_at(location).map(|l| l.name());
16815 language_settings(language, file, cx).inlay_hints
16816}
16817
16818fn consume_contiguous_rows(
16819 contiguous_row_selections: &mut Vec<Selection<Point>>,
16820 selection: &Selection<Point>,
16821 display_map: &DisplaySnapshot,
16822 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16823) -> (MultiBufferRow, MultiBufferRow) {
16824 contiguous_row_selections.push(selection.clone());
16825 let start_row = MultiBufferRow(selection.start.row);
16826 let mut end_row = ending_row(selection, display_map);
16827
16828 while let Some(next_selection) = selections.peek() {
16829 if next_selection.start.row <= end_row.0 {
16830 end_row = ending_row(next_selection, display_map);
16831 contiguous_row_selections.push(selections.next().unwrap().clone());
16832 } else {
16833 break;
16834 }
16835 }
16836 (start_row, end_row)
16837}
16838
16839fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16840 if next_selection.end.column > 0 || next_selection.is_empty() {
16841 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16842 } else {
16843 MultiBufferRow(next_selection.end.row)
16844 }
16845}
16846
16847impl EditorSnapshot {
16848 pub fn remote_selections_in_range<'a>(
16849 &'a self,
16850 range: &'a Range<Anchor>,
16851 collaboration_hub: &dyn CollaborationHub,
16852 cx: &'a App,
16853 ) -> impl 'a + Iterator<Item = RemoteSelection> {
16854 let participant_names = collaboration_hub.user_names(cx);
16855 let participant_indices = collaboration_hub.user_participant_indices(cx);
16856 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16857 let collaborators_by_replica_id = collaborators_by_peer_id
16858 .iter()
16859 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16860 .collect::<HashMap<_, _>>();
16861 self.buffer_snapshot
16862 .selections_in_range(range, false)
16863 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16864 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16865 let participant_index = participant_indices.get(&collaborator.user_id).copied();
16866 let user_name = participant_names.get(&collaborator.user_id).cloned();
16867 Some(RemoteSelection {
16868 replica_id,
16869 selection,
16870 cursor_shape,
16871 line_mode,
16872 participant_index,
16873 peer_id: collaborator.peer_id,
16874 user_name,
16875 })
16876 })
16877 }
16878
16879 pub fn hunks_for_ranges(
16880 &self,
16881 ranges: impl Iterator<Item = Range<Point>>,
16882 ) -> Vec<MultiBufferDiffHunk> {
16883 let mut hunks = Vec::new();
16884 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16885 HashMap::default();
16886 for query_range in ranges {
16887 let query_rows =
16888 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16889 for hunk in self.buffer_snapshot.diff_hunks_in_range(
16890 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16891 ) {
16892 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16893 // when the caret is just above or just below the deleted hunk.
16894 let allow_adjacent = hunk.status().is_deleted();
16895 let related_to_selection = if allow_adjacent {
16896 hunk.row_range.overlaps(&query_rows)
16897 || hunk.row_range.start == query_rows.end
16898 || hunk.row_range.end == query_rows.start
16899 } else {
16900 hunk.row_range.overlaps(&query_rows)
16901 };
16902 if related_to_selection {
16903 if !processed_buffer_rows
16904 .entry(hunk.buffer_id)
16905 .or_default()
16906 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16907 {
16908 continue;
16909 }
16910 hunks.push(hunk);
16911 }
16912 }
16913 }
16914
16915 hunks
16916 }
16917
16918 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16919 self.display_snapshot.buffer_snapshot.language_at(position)
16920 }
16921
16922 pub fn is_focused(&self) -> bool {
16923 self.is_focused
16924 }
16925
16926 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16927 self.placeholder_text.as_ref()
16928 }
16929
16930 pub fn scroll_position(&self) -> gpui::Point<f32> {
16931 self.scroll_anchor.scroll_position(&self.display_snapshot)
16932 }
16933
16934 fn gutter_dimensions(
16935 &self,
16936 font_id: FontId,
16937 font_size: Pixels,
16938 max_line_number_width: Pixels,
16939 cx: &App,
16940 ) -> Option<GutterDimensions> {
16941 if !self.show_gutter {
16942 return None;
16943 }
16944
16945 let descent = cx.text_system().descent(font_id, font_size);
16946 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16947 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16948
16949 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16950 matches!(
16951 ProjectSettings::get_global(cx).git.git_gutter,
16952 Some(GitGutterSetting::TrackedFiles)
16953 )
16954 });
16955 let gutter_settings = EditorSettings::get_global(cx).gutter;
16956 let show_line_numbers = self
16957 .show_line_numbers
16958 .unwrap_or(gutter_settings.line_numbers);
16959 let line_gutter_width = if show_line_numbers {
16960 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16961 let min_width_for_number_on_gutter = em_advance * 4.0;
16962 max_line_number_width.max(min_width_for_number_on_gutter)
16963 } else {
16964 0.0.into()
16965 };
16966
16967 let show_code_actions = self
16968 .show_code_actions
16969 .unwrap_or(gutter_settings.code_actions);
16970
16971 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16972
16973 let git_blame_entries_width =
16974 self.git_blame_gutter_max_author_length
16975 .map(|max_author_length| {
16976 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16977
16978 /// The number of characters to dedicate to gaps and margins.
16979 const SPACING_WIDTH: usize = 4;
16980
16981 let max_char_count = max_author_length
16982 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16983 + ::git::SHORT_SHA_LENGTH
16984 + MAX_RELATIVE_TIMESTAMP.len()
16985 + SPACING_WIDTH;
16986
16987 em_advance * max_char_count
16988 });
16989
16990 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16991 left_padding += if show_code_actions || show_runnables {
16992 em_width * 3.0
16993 } else if show_git_gutter && show_line_numbers {
16994 em_width * 2.0
16995 } else if show_git_gutter || show_line_numbers {
16996 em_width
16997 } else {
16998 px(0.)
16999 };
17000
17001 let right_padding = if gutter_settings.folds && show_line_numbers {
17002 em_width * 4.0
17003 } else if gutter_settings.folds {
17004 em_width * 3.0
17005 } else if show_line_numbers {
17006 em_width
17007 } else {
17008 px(0.)
17009 };
17010
17011 Some(GutterDimensions {
17012 left_padding,
17013 right_padding,
17014 width: line_gutter_width + left_padding + right_padding,
17015 margin: -descent,
17016 git_blame_entries_width,
17017 })
17018 }
17019
17020 pub fn render_crease_toggle(
17021 &self,
17022 buffer_row: MultiBufferRow,
17023 row_contains_cursor: bool,
17024 editor: Entity<Editor>,
17025 window: &mut Window,
17026 cx: &mut App,
17027 ) -> Option<AnyElement> {
17028 let folded = self.is_line_folded(buffer_row);
17029 let mut is_foldable = false;
17030
17031 if let Some(crease) = self
17032 .crease_snapshot
17033 .query_row(buffer_row, &self.buffer_snapshot)
17034 {
17035 is_foldable = true;
17036 match crease {
17037 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17038 if let Some(render_toggle) = render_toggle {
17039 let toggle_callback =
17040 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17041 if folded {
17042 editor.update(cx, |editor, cx| {
17043 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17044 });
17045 } else {
17046 editor.update(cx, |editor, cx| {
17047 editor.unfold_at(
17048 &crate::UnfoldAt { buffer_row },
17049 window,
17050 cx,
17051 )
17052 });
17053 }
17054 });
17055 return Some((render_toggle)(
17056 buffer_row,
17057 folded,
17058 toggle_callback,
17059 window,
17060 cx,
17061 ));
17062 }
17063 }
17064 }
17065 }
17066
17067 is_foldable |= self.starts_indent(buffer_row);
17068
17069 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17070 Some(
17071 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17072 .toggle_state(folded)
17073 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17074 if folded {
17075 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17076 } else {
17077 this.fold_at(&FoldAt { buffer_row }, window, cx);
17078 }
17079 }))
17080 .into_any_element(),
17081 )
17082 } else {
17083 None
17084 }
17085 }
17086
17087 pub fn render_crease_trailer(
17088 &self,
17089 buffer_row: MultiBufferRow,
17090 window: &mut Window,
17091 cx: &mut App,
17092 ) -> Option<AnyElement> {
17093 let folded = self.is_line_folded(buffer_row);
17094 if let Crease::Inline { render_trailer, .. } = self
17095 .crease_snapshot
17096 .query_row(buffer_row, &self.buffer_snapshot)?
17097 {
17098 let render_trailer = render_trailer.as_ref()?;
17099 Some(render_trailer(buffer_row, folded, window, cx))
17100 } else {
17101 None
17102 }
17103 }
17104}
17105
17106impl Deref for EditorSnapshot {
17107 type Target = DisplaySnapshot;
17108
17109 fn deref(&self) -> &Self::Target {
17110 &self.display_snapshot
17111 }
17112}
17113
17114#[derive(Clone, Debug, PartialEq, Eq)]
17115pub enum EditorEvent {
17116 InputIgnored {
17117 text: Arc<str>,
17118 },
17119 InputHandled {
17120 utf16_range_to_replace: Option<Range<isize>>,
17121 text: Arc<str>,
17122 },
17123 ExcerptsAdded {
17124 buffer: Entity<Buffer>,
17125 predecessor: ExcerptId,
17126 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17127 },
17128 ExcerptsRemoved {
17129 ids: Vec<ExcerptId>,
17130 },
17131 BufferFoldToggled {
17132 ids: Vec<ExcerptId>,
17133 folded: bool,
17134 },
17135 ExcerptsEdited {
17136 ids: Vec<ExcerptId>,
17137 },
17138 ExcerptsExpanded {
17139 ids: Vec<ExcerptId>,
17140 },
17141 BufferEdited,
17142 Edited {
17143 transaction_id: clock::Lamport,
17144 },
17145 Reparsed(BufferId),
17146 Focused,
17147 FocusedIn,
17148 Blurred,
17149 DirtyChanged,
17150 Saved,
17151 TitleChanged,
17152 DiffBaseChanged,
17153 SelectionsChanged {
17154 local: bool,
17155 },
17156 ScrollPositionChanged {
17157 local: bool,
17158 autoscroll: bool,
17159 },
17160 Closed,
17161 TransactionUndone {
17162 transaction_id: clock::Lamport,
17163 },
17164 TransactionBegun {
17165 transaction_id: clock::Lamport,
17166 },
17167 Reloaded,
17168 CursorShapeChanged,
17169}
17170
17171impl EventEmitter<EditorEvent> for Editor {}
17172
17173impl Focusable for Editor {
17174 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17175 self.focus_handle.clone()
17176 }
17177}
17178
17179impl Render for Editor {
17180 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17181 let settings = ThemeSettings::get_global(cx);
17182
17183 let mut text_style = match self.mode {
17184 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17185 color: cx.theme().colors().editor_foreground,
17186 font_family: settings.ui_font.family.clone(),
17187 font_features: settings.ui_font.features.clone(),
17188 font_fallbacks: settings.ui_font.fallbacks.clone(),
17189 font_size: rems(0.875).into(),
17190 font_weight: settings.ui_font.weight,
17191 line_height: relative(settings.buffer_line_height.value()),
17192 ..Default::default()
17193 },
17194 EditorMode::Full => TextStyle {
17195 color: cx.theme().colors().editor_foreground,
17196 font_family: settings.buffer_font.family.clone(),
17197 font_features: settings.buffer_font.features.clone(),
17198 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17199 font_size: settings.buffer_font_size(cx).into(),
17200 font_weight: settings.buffer_font.weight,
17201 line_height: relative(settings.buffer_line_height.value()),
17202 ..Default::default()
17203 },
17204 };
17205 if let Some(text_style_refinement) = &self.text_style_refinement {
17206 text_style.refine(text_style_refinement)
17207 }
17208
17209 let background = match self.mode {
17210 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17211 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17212 EditorMode::Full => cx.theme().colors().editor_background,
17213 };
17214
17215 EditorElement::new(
17216 &cx.entity(),
17217 EditorStyle {
17218 background,
17219 local_player: cx.theme().players().local(),
17220 text: text_style,
17221 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17222 syntax: cx.theme().syntax().clone(),
17223 status: cx.theme().status().clone(),
17224 inlay_hints_style: make_inlay_hints_style(cx),
17225 inline_completion_styles: make_suggestion_styles(cx),
17226 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17227 },
17228 )
17229 }
17230}
17231
17232impl EntityInputHandler for Editor {
17233 fn text_for_range(
17234 &mut self,
17235 range_utf16: Range<usize>,
17236 adjusted_range: &mut Option<Range<usize>>,
17237 _: &mut Window,
17238 cx: &mut Context<Self>,
17239 ) -> Option<String> {
17240 let snapshot = self.buffer.read(cx).read(cx);
17241 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17242 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17243 if (start.0..end.0) != range_utf16 {
17244 adjusted_range.replace(start.0..end.0);
17245 }
17246 Some(snapshot.text_for_range(start..end).collect())
17247 }
17248
17249 fn selected_text_range(
17250 &mut self,
17251 ignore_disabled_input: bool,
17252 _: &mut Window,
17253 cx: &mut Context<Self>,
17254 ) -> Option<UTF16Selection> {
17255 // Prevent the IME menu from appearing when holding down an alphabetic key
17256 // while input is disabled.
17257 if !ignore_disabled_input && !self.input_enabled {
17258 return None;
17259 }
17260
17261 let selection = self.selections.newest::<OffsetUtf16>(cx);
17262 let range = selection.range();
17263
17264 Some(UTF16Selection {
17265 range: range.start.0..range.end.0,
17266 reversed: selection.reversed,
17267 })
17268 }
17269
17270 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17271 let snapshot = self.buffer.read(cx).read(cx);
17272 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17273 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17274 }
17275
17276 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17277 self.clear_highlights::<InputComposition>(cx);
17278 self.ime_transaction.take();
17279 }
17280
17281 fn replace_text_in_range(
17282 &mut self,
17283 range_utf16: Option<Range<usize>>,
17284 text: &str,
17285 window: &mut Window,
17286 cx: &mut Context<Self>,
17287 ) {
17288 if !self.input_enabled {
17289 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17290 return;
17291 }
17292
17293 self.transact(window, cx, |this, window, cx| {
17294 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17295 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17296 Some(this.selection_replacement_ranges(range_utf16, cx))
17297 } else {
17298 this.marked_text_ranges(cx)
17299 };
17300
17301 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17302 let newest_selection_id = this.selections.newest_anchor().id;
17303 this.selections
17304 .all::<OffsetUtf16>(cx)
17305 .iter()
17306 .zip(ranges_to_replace.iter())
17307 .find_map(|(selection, range)| {
17308 if selection.id == newest_selection_id {
17309 Some(
17310 (range.start.0 as isize - selection.head().0 as isize)
17311 ..(range.end.0 as isize - selection.head().0 as isize),
17312 )
17313 } else {
17314 None
17315 }
17316 })
17317 });
17318
17319 cx.emit(EditorEvent::InputHandled {
17320 utf16_range_to_replace: range_to_replace,
17321 text: text.into(),
17322 });
17323
17324 if let Some(new_selected_ranges) = new_selected_ranges {
17325 this.change_selections(None, window, cx, |selections| {
17326 selections.select_ranges(new_selected_ranges)
17327 });
17328 this.backspace(&Default::default(), window, cx);
17329 }
17330
17331 this.handle_input(text, window, cx);
17332 });
17333
17334 if let Some(transaction) = self.ime_transaction {
17335 self.buffer.update(cx, |buffer, cx| {
17336 buffer.group_until_transaction(transaction, cx);
17337 });
17338 }
17339
17340 self.unmark_text(window, cx);
17341 }
17342
17343 fn replace_and_mark_text_in_range(
17344 &mut self,
17345 range_utf16: Option<Range<usize>>,
17346 text: &str,
17347 new_selected_range_utf16: Option<Range<usize>>,
17348 window: &mut Window,
17349 cx: &mut Context<Self>,
17350 ) {
17351 if !self.input_enabled {
17352 return;
17353 }
17354
17355 let transaction = self.transact(window, cx, |this, window, cx| {
17356 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17357 let snapshot = this.buffer.read(cx).read(cx);
17358 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17359 for marked_range in &mut marked_ranges {
17360 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17361 marked_range.start.0 += relative_range_utf16.start;
17362 marked_range.start =
17363 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17364 marked_range.end =
17365 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17366 }
17367 }
17368 Some(marked_ranges)
17369 } else if let Some(range_utf16) = range_utf16 {
17370 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17371 Some(this.selection_replacement_ranges(range_utf16, cx))
17372 } else {
17373 None
17374 };
17375
17376 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17377 let newest_selection_id = this.selections.newest_anchor().id;
17378 this.selections
17379 .all::<OffsetUtf16>(cx)
17380 .iter()
17381 .zip(ranges_to_replace.iter())
17382 .find_map(|(selection, range)| {
17383 if selection.id == newest_selection_id {
17384 Some(
17385 (range.start.0 as isize - selection.head().0 as isize)
17386 ..(range.end.0 as isize - selection.head().0 as isize),
17387 )
17388 } else {
17389 None
17390 }
17391 })
17392 });
17393
17394 cx.emit(EditorEvent::InputHandled {
17395 utf16_range_to_replace: range_to_replace,
17396 text: text.into(),
17397 });
17398
17399 if let Some(ranges) = ranges_to_replace {
17400 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17401 }
17402
17403 let marked_ranges = {
17404 let snapshot = this.buffer.read(cx).read(cx);
17405 this.selections
17406 .disjoint_anchors()
17407 .iter()
17408 .map(|selection| {
17409 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17410 })
17411 .collect::<Vec<_>>()
17412 };
17413
17414 if text.is_empty() {
17415 this.unmark_text(window, cx);
17416 } else {
17417 this.highlight_text::<InputComposition>(
17418 marked_ranges.clone(),
17419 HighlightStyle {
17420 underline: Some(UnderlineStyle {
17421 thickness: px(1.),
17422 color: None,
17423 wavy: false,
17424 }),
17425 ..Default::default()
17426 },
17427 cx,
17428 );
17429 }
17430
17431 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17432 let use_autoclose = this.use_autoclose;
17433 let use_auto_surround = this.use_auto_surround;
17434 this.set_use_autoclose(false);
17435 this.set_use_auto_surround(false);
17436 this.handle_input(text, window, cx);
17437 this.set_use_autoclose(use_autoclose);
17438 this.set_use_auto_surround(use_auto_surround);
17439
17440 if let Some(new_selected_range) = new_selected_range_utf16 {
17441 let snapshot = this.buffer.read(cx).read(cx);
17442 let new_selected_ranges = marked_ranges
17443 .into_iter()
17444 .map(|marked_range| {
17445 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17446 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17447 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17448 snapshot.clip_offset_utf16(new_start, Bias::Left)
17449 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17450 })
17451 .collect::<Vec<_>>();
17452
17453 drop(snapshot);
17454 this.change_selections(None, window, cx, |selections| {
17455 selections.select_ranges(new_selected_ranges)
17456 });
17457 }
17458 });
17459
17460 self.ime_transaction = self.ime_transaction.or(transaction);
17461 if let Some(transaction) = self.ime_transaction {
17462 self.buffer.update(cx, |buffer, cx| {
17463 buffer.group_until_transaction(transaction, cx);
17464 });
17465 }
17466
17467 if self.text_highlights::<InputComposition>(cx).is_none() {
17468 self.ime_transaction.take();
17469 }
17470 }
17471
17472 fn bounds_for_range(
17473 &mut self,
17474 range_utf16: Range<usize>,
17475 element_bounds: gpui::Bounds<Pixels>,
17476 window: &mut Window,
17477 cx: &mut Context<Self>,
17478 ) -> Option<gpui::Bounds<Pixels>> {
17479 let text_layout_details = self.text_layout_details(window);
17480 let gpui::Size {
17481 width: em_width,
17482 height: line_height,
17483 } = self.character_size(window);
17484
17485 let snapshot = self.snapshot(window, cx);
17486 let scroll_position = snapshot.scroll_position();
17487 let scroll_left = scroll_position.x * em_width;
17488
17489 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17490 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17491 + self.gutter_dimensions.width
17492 + self.gutter_dimensions.margin;
17493 let y = line_height * (start.row().as_f32() - scroll_position.y);
17494
17495 Some(Bounds {
17496 origin: element_bounds.origin + point(x, y),
17497 size: size(em_width, line_height),
17498 })
17499 }
17500
17501 fn character_index_for_point(
17502 &mut self,
17503 point: gpui::Point<Pixels>,
17504 _window: &mut Window,
17505 _cx: &mut Context<Self>,
17506 ) -> Option<usize> {
17507 let position_map = self.last_position_map.as_ref()?;
17508 if !position_map.text_hitbox.contains(&point) {
17509 return None;
17510 }
17511 let display_point = position_map.point_for_position(point).previous_valid;
17512 let anchor = position_map
17513 .snapshot
17514 .display_point_to_anchor(display_point, Bias::Left);
17515 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17516 Some(utf16_offset.0)
17517 }
17518}
17519
17520trait SelectionExt {
17521 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17522 fn spanned_rows(
17523 &self,
17524 include_end_if_at_line_start: bool,
17525 map: &DisplaySnapshot,
17526 ) -> Range<MultiBufferRow>;
17527}
17528
17529impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17530 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17531 let start = self
17532 .start
17533 .to_point(&map.buffer_snapshot)
17534 .to_display_point(map);
17535 let end = self
17536 .end
17537 .to_point(&map.buffer_snapshot)
17538 .to_display_point(map);
17539 if self.reversed {
17540 end..start
17541 } else {
17542 start..end
17543 }
17544 }
17545
17546 fn spanned_rows(
17547 &self,
17548 include_end_if_at_line_start: bool,
17549 map: &DisplaySnapshot,
17550 ) -> Range<MultiBufferRow> {
17551 let start = self.start.to_point(&map.buffer_snapshot);
17552 let mut end = self.end.to_point(&map.buffer_snapshot);
17553 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17554 end.row -= 1;
17555 }
17556
17557 let buffer_start = map.prev_line_boundary(start).0;
17558 let buffer_end = map.next_line_boundary(end).0;
17559 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17560 }
17561}
17562
17563impl<T: InvalidationRegion> InvalidationStack<T> {
17564 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17565 where
17566 S: Clone + ToOffset,
17567 {
17568 while let Some(region) = self.last() {
17569 let all_selections_inside_invalidation_ranges =
17570 if selections.len() == region.ranges().len() {
17571 selections
17572 .iter()
17573 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17574 .all(|(selection, invalidation_range)| {
17575 let head = selection.head().to_offset(buffer);
17576 invalidation_range.start <= head && invalidation_range.end >= head
17577 })
17578 } else {
17579 false
17580 };
17581
17582 if all_selections_inside_invalidation_ranges {
17583 break;
17584 } else {
17585 self.pop();
17586 }
17587 }
17588 }
17589}
17590
17591impl<T> Default for InvalidationStack<T> {
17592 fn default() -> Self {
17593 Self(Default::default())
17594 }
17595}
17596
17597impl<T> Deref for InvalidationStack<T> {
17598 type Target = Vec<T>;
17599
17600 fn deref(&self) -> &Self::Target {
17601 &self.0
17602 }
17603}
17604
17605impl<T> DerefMut for InvalidationStack<T> {
17606 fn deref_mut(&mut self) -> &mut Self::Target {
17607 &mut self.0
17608 }
17609}
17610
17611impl InvalidationRegion for SnippetState {
17612 fn ranges(&self) -> &[Range<Anchor>] {
17613 &self.ranges[self.active_index]
17614 }
17615}
17616
17617pub fn diagnostic_block_renderer(
17618 diagnostic: Diagnostic,
17619 max_message_rows: Option<u8>,
17620 allow_closing: bool,
17621 _is_valid: bool,
17622) -> RenderBlock {
17623 let (text_without_backticks, code_ranges) =
17624 highlight_diagnostic_message(&diagnostic, max_message_rows);
17625
17626 Arc::new(move |cx: &mut BlockContext| {
17627 let group_id: SharedString = cx.block_id.to_string().into();
17628
17629 let mut text_style = cx.window.text_style().clone();
17630 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17631 let theme_settings = ThemeSettings::get_global(cx);
17632 text_style.font_family = theme_settings.buffer_font.family.clone();
17633 text_style.font_style = theme_settings.buffer_font.style;
17634 text_style.font_features = theme_settings.buffer_font.features.clone();
17635 text_style.font_weight = theme_settings.buffer_font.weight;
17636
17637 let multi_line_diagnostic = diagnostic.message.contains('\n');
17638
17639 let buttons = |diagnostic: &Diagnostic| {
17640 if multi_line_diagnostic {
17641 v_flex()
17642 } else {
17643 h_flex()
17644 }
17645 .when(allow_closing, |div| {
17646 div.children(diagnostic.is_primary.then(|| {
17647 IconButton::new("close-block", IconName::XCircle)
17648 .icon_color(Color::Muted)
17649 .size(ButtonSize::Compact)
17650 .style(ButtonStyle::Transparent)
17651 .visible_on_hover(group_id.clone())
17652 .on_click(move |_click, window, cx| {
17653 window.dispatch_action(Box::new(Cancel), cx)
17654 })
17655 .tooltip(|window, cx| {
17656 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17657 })
17658 }))
17659 })
17660 .child(
17661 IconButton::new("copy-block", IconName::Copy)
17662 .icon_color(Color::Muted)
17663 .size(ButtonSize::Compact)
17664 .style(ButtonStyle::Transparent)
17665 .visible_on_hover(group_id.clone())
17666 .on_click({
17667 let message = diagnostic.message.clone();
17668 move |_click, _, cx| {
17669 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17670 }
17671 })
17672 .tooltip(Tooltip::text("Copy diagnostic message")),
17673 )
17674 };
17675
17676 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17677 AvailableSpace::min_size(),
17678 cx.window,
17679 cx.app,
17680 );
17681
17682 h_flex()
17683 .id(cx.block_id)
17684 .group(group_id.clone())
17685 .relative()
17686 .size_full()
17687 .block_mouse_down()
17688 .pl(cx.gutter_dimensions.width)
17689 .w(cx.max_width - cx.gutter_dimensions.full_width())
17690 .child(
17691 div()
17692 .flex()
17693 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17694 .flex_shrink(),
17695 )
17696 .child(buttons(&diagnostic))
17697 .child(div().flex().flex_shrink_0().child(
17698 StyledText::new(text_without_backticks.clone()).with_highlights(
17699 &text_style,
17700 code_ranges.iter().map(|range| {
17701 (
17702 range.clone(),
17703 HighlightStyle {
17704 font_weight: Some(FontWeight::BOLD),
17705 ..Default::default()
17706 },
17707 )
17708 }),
17709 ),
17710 ))
17711 .into_any_element()
17712 })
17713}
17714
17715fn inline_completion_edit_text(
17716 current_snapshot: &BufferSnapshot,
17717 edits: &[(Range<Anchor>, String)],
17718 edit_preview: &EditPreview,
17719 include_deletions: bool,
17720 cx: &App,
17721) -> HighlightedText {
17722 let edits = edits
17723 .iter()
17724 .map(|(anchor, text)| {
17725 (
17726 anchor.start.text_anchor..anchor.end.text_anchor,
17727 text.clone(),
17728 )
17729 })
17730 .collect::<Vec<_>>();
17731
17732 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17733}
17734
17735pub fn highlight_diagnostic_message(
17736 diagnostic: &Diagnostic,
17737 mut max_message_rows: Option<u8>,
17738) -> (SharedString, Vec<Range<usize>>) {
17739 let mut text_without_backticks = String::new();
17740 let mut code_ranges = Vec::new();
17741
17742 if let Some(source) = &diagnostic.source {
17743 text_without_backticks.push_str(source);
17744 code_ranges.push(0..source.len());
17745 text_without_backticks.push_str(": ");
17746 }
17747
17748 let mut prev_offset = 0;
17749 let mut in_code_block = false;
17750 let has_row_limit = max_message_rows.is_some();
17751 let mut newline_indices = diagnostic
17752 .message
17753 .match_indices('\n')
17754 .filter(|_| has_row_limit)
17755 .map(|(ix, _)| ix)
17756 .fuse()
17757 .peekable();
17758
17759 for (quote_ix, _) in diagnostic
17760 .message
17761 .match_indices('`')
17762 .chain([(diagnostic.message.len(), "")])
17763 {
17764 let mut first_newline_ix = None;
17765 let mut last_newline_ix = None;
17766 while let Some(newline_ix) = newline_indices.peek() {
17767 if *newline_ix < quote_ix {
17768 if first_newline_ix.is_none() {
17769 first_newline_ix = Some(*newline_ix);
17770 }
17771 last_newline_ix = Some(*newline_ix);
17772
17773 if let Some(rows_left) = &mut max_message_rows {
17774 if *rows_left == 0 {
17775 break;
17776 } else {
17777 *rows_left -= 1;
17778 }
17779 }
17780 let _ = newline_indices.next();
17781 } else {
17782 break;
17783 }
17784 }
17785 let prev_len = text_without_backticks.len();
17786 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17787 text_without_backticks.push_str(new_text);
17788 if in_code_block {
17789 code_ranges.push(prev_len..text_without_backticks.len());
17790 }
17791 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17792 in_code_block = !in_code_block;
17793 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17794 text_without_backticks.push_str("...");
17795 break;
17796 }
17797 }
17798
17799 (text_without_backticks.into(), code_ranges)
17800}
17801
17802fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17803 match severity {
17804 DiagnosticSeverity::ERROR => colors.error,
17805 DiagnosticSeverity::WARNING => colors.warning,
17806 DiagnosticSeverity::INFORMATION => colors.info,
17807 DiagnosticSeverity::HINT => colors.info,
17808 _ => colors.ignored,
17809 }
17810}
17811
17812pub fn styled_runs_for_code_label<'a>(
17813 label: &'a CodeLabel,
17814 syntax_theme: &'a theme::SyntaxTheme,
17815) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17816 let fade_out = HighlightStyle {
17817 fade_out: Some(0.35),
17818 ..Default::default()
17819 };
17820
17821 let mut prev_end = label.filter_range.end;
17822 label
17823 .runs
17824 .iter()
17825 .enumerate()
17826 .flat_map(move |(ix, (range, highlight_id))| {
17827 let style = if let Some(style) = highlight_id.style(syntax_theme) {
17828 style
17829 } else {
17830 return Default::default();
17831 };
17832 let mut muted_style = style;
17833 muted_style.highlight(fade_out);
17834
17835 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17836 if range.start >= label.filter_range.end {
17837 if range.start > prev_end {
17838 runs.push((prev_end..range.start, fade_out));
17839 }
17840 runs.push((range.clone(), muted_style));
17841 } else if range.end <= label.filter_range.end {
17842 runs.push((range.clone(), style));
17843 } else {
17844 runs.push((range.start..label.filter_range.end, style));
17845 runs.push((label.filter_range.end..range.end, muted_style));
17846 }
17847 prev_end = cmp::max(prev_end, range.end);
17848
17849 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17850 runs.push((prev_end..label.text.len(), fade_out));
17851 }
17852
17853 runs
17854 })
17855}
17856
17857pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17858 let mut prev_index = 0;
17859 let mut prev_codepoint: Option<char> = None;
17860 text.char_indices()
17861 .chain([(text.len(), '\0')])
17862 .filter_map(move |(index, codepoint)| {
17863 let prev_codepoint = prev_codepoint.replace(codepoint)?;
17864 let is_boundary = index == text.len()
17865 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17866 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17867 if is_boundary {
17868 let chunk = &text[prev_index..index];
17869 prev_index = index;
17870 Some(chunk)
17871 } else {
17872 None
17873 }
17874 })
17875}
17876
17877pub trait RangeToAnchorExt: Sized {
17878 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17879
17880 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17881 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17882 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17883 }
17884}
17885
17886impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17887 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17888 let start_offset = self.start.to_offset(snapshot);
17889 let end_offset = self.end.to_offset(snapshot);
17890 if start_offset == end_offset {
17891 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17892 } else {
17893 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17894 }
17895 }
17896}
17897
17898pub trait RowExt {
17899 fn as_f32(&self) -> f32;
17900
17901 fn next_row(&self) -> Self;
17902
17903 fn previous_row(&self) -> Self;
17904
17905 fn minus(&self, other: Self) -> u32;
17906}
17907
17908impl RowExt for DisplayRow {
17909 fn as_f32(&self) -> f32 {
17910 self.0 as f32
17911 }
17912
17913 fn next_row(&self) -> Self {
17914 Self(self.0 + 1)
17915 }
17916
17917 fn previous_row(&self) -> Self {
17918 Self(self.0.saturating_sub(1))
17919 }
17920
17921 fn minus(&self, other: Self) -> u32 {
17922 self.0 - other.0
17923 }
17924}
17925
17926impl RowExt for MultiBufferRow {
17927 fn as_f32(&self) -> f32 {
17928 self.0 as f32
17929 }
17930
17931 fn next_row(&self) -> Self {
17932 Self(self.0 + 1)
17933 }
17934
17935 fn previous_row(&self) -> Self {
17936 Self(self.0.saturating_sub(1))
17937 }
17938
17939 fn minus(&self, other: Self) -> u32 {
17940 self.0 - other.0
17941 }
17942}
17943
17944trait RowRangeExt {
17945 type Row;
17946
17947 fn len(&self) -> usize;
17948
17949 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17950}
17951
17952impl RowRangeExt for Range<MultiBufferRow> {
17953 type Row = MultiBufferRow;
17954
17955 fn len(&self) -> usize {
17956 (self.end.0 - self.start.0) as usize
17957 }
17958
17959 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17960 (self.start.0..self.end.0).map(MultiBufferRow)
17961 }
17962}
17963
17964impl RowRangeExt for Range<DisplayRow> {
17965 type Row = DisplayRow;
17966
17967 fn len(&self) -> usize {
17968 (self.end.0 - self.start.0) as usize
17969 }
17970
17971 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17972 (self.start.0..self.end.0).map(DisplayRow)
17973 }
17974}
17975
17976/// If select range has more than one line, we
17977/// just point the cursor to range.start.
17978fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17979 if range.start.row == range.end.row {
17980 range
17981 } else {
17982 range.start..range.start
17983 }
17984}
17985pub struct KillRing(ClipboardItem);
17986impl Global for KillRing {}
17987
17988const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17989
17990fn all_edits_insertions_or_deletions(
17991 edits: &Vec<(Range<Anchor>, String)>,
17992 snapshot: &MultiBufferSnapshot,
17993) -> bool {
17994 let mut all_insertions = true;
17995 let mut all_deletions = true;
17996
17997 for (range, new_text) in edits.iter() {
17998 let range_is_empty = range.to_offset(&snapshot).is_empty();
17999 let text_is_empty = new_text.is_empty();
18000
18001 if range_is_empty != text_is_empty {
18002 if range_is_empty {
18003 all_deletions = false;
18004 } else {
18005 all_insertions = false;
18006 }
18007 } else {
18008 return false;
18009 }
18010
18011 if !all_insertions && !all_deletions {
18012 return false;
18013 }
18014 }
18015 all_insertions || all_deletions
18016}