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::DiffHunkStatus;
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, EditPredictionsMode,
106 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
107 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 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
124 InsertTextFormat, 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 CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
207pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
208pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
209
210pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
211pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
212
213const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
214 alt: true,
215 shift: true,
216 control: false,
217 platform: false,
218 function: false,
219};
220
221#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
222pub enum InlayId {
223 InlineCompletion(usize),
224 Hint(usize),
225}
226
227impl InlayId {
228 fn id(&self) -> usize {
229 match self {
230 Self::InlineCompletion(id) => *id,
231 Self::Hint(id) => *id,
232 }
233 }
234}
235
236enum DocumentHighlightRead {}
237enum DocumentHighlightWrite {}
238enum InputComposition {}
239enum SelectedTextHighlight {}
240
241#[derive(Debug, Copy, Clone, PartialEq, Eq)]
242pub enum Navigated {
243 Yes,
244 No,
245}
246
247impl Navigated {
248 pub fn from_bool(yes: bool) -> Navigated {
249 if yes {
250 Navigated::Yes
251 } else {
252 Navigated::No
253 }
254 }
255}
256
257#[derive(Debug, Clone, PartialEq, Eq)]
258enum DisplayDiffHunk {
259 Folded {
260 display_row: DisplayRow,
261 },
262 Unfolded {
263 diff_base_byte_range: Range<usize>,
264 display_row_range: Range<DisplayRow>,
265 multi_buffer_range: Range<Anchor>,
266 status: DiffHunkStatus,
267 },
268}
269
270pub fn init_settings(cx: &mut App) {
271 EditorSettings::register(cx);
272}
273
274pub fn init(cx: &mut App) {
275 init_settings(cx);
276
277 workspace::register_project_item::<Editor>(cx);
278 workspace::FollowableViewRegistry::register::<Editor>(cx);
279 workspace::register_serializable_item::<Editor>(cx);
280
281 cx.observe_new(
282 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
283 workspace.register_action(Editor::new_file);
284 workspace.register_action(Editor::new_file_vertical);
285 workspace.register_action(Editor::new_file_horizontal);
286 workspace.register_action(Editor::cancel_language_server_work);
287 },
288 )
289 .detach();
290
291 cx.on_action(move |_: &workspace::NewFile, 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 Editor::new_file(workspace, &Default::default(), window, cx)
300 },
301 )
302 .detach();
303 }
304 });
305 cx.on_action(move |_: &workspace::NewWindow, cx| {
306 let app_state = workspace::AppState::global(cx);
307 if let Some(app_state) = app_state.upgrade() {
308 workspace::open_new(
309 Default::default(),
310 app_state,
311 cx,
312 |workspace, window, cx| {
313 cx.activate(true);
314 Editor::new_file(workspace, &Default::default(), window, cx)
315 },
316 )
317 .detach();
318 }
319 });
320}
321
322pub struct SearchWithinRange;
323
324trait InvalidationRegion {
325 fn ranges(&self) -> &[Range<Anchor>];
326}
327
328#[derive(Clone, Debug, PartialEq)]
329pub enum SelectPhase {
330 Begin {
331 position: DisplayPoint,
332 add: bool,
333 click_count: usize,
334 },
335 BeginColumnar {
336 position: DisplayPoint,
337 reset: bool,
338 goal_column: u32,
339 },
340 Extend {
341 position: DisplayPoint,
342 click_count: usize,
343 },
344 Update {
345 position: DisplayPoint,
346 goal_column: u32,
347 scroll_delta: gpui::Point<f32>,
348 },
349 End,
350}
351
352#[derive(Clone, Debug)]
353pub enum SelectMode {
354 Character,
355 Word(Range<Anchor>),
356 Line(Range<Anchor>),
357 All,
358}
359
360#[derive(Copy, Clone, PartialEq, Eq, Debug)]
361pub enum EditorMode {
362 SingleLine { auto_width: bool },
363 AutoHeight { max_lines: usize },
364 Full,
365}
366
367#[derive(Copy, Clone, Debug)]
368pub enum SoftWrap {
369 /// Prefer not to wrap at all.
370 ///
371 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
372 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
373 GitDiff,
374 /// Prefer a single line generally, unless an overly long line is encountered.
375 None,
376 /// Soft wrap lines that exceed the editor width.
377 EditorWidth,
378 /// Soft wrap lines at the preferred line length.
379 Column(u32),
380 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
381 Bounded(u32),
382}
383
384#[derive(Clone)]
385pub struct EditorStyle {
386 pub background: Hsla,
387 pub local_player: PlayerColor,
388 pub text: TextStyle,
389 pub scrollbar_width: Pixels,
390 pub syntax: Arc<SyntaxTheme>,
391 pub status: StatusColors,
392 pub inlay_hints_style: HighlightStyle,
393 pub inline_completion_styles: InlineCompletionStyles,
394 pub unnecessary_code_fade: f32,
395}
396
397impl Default for EditorStyle {
398 fn default() -> Self {
399 Self {
400 background: Hsla::default(),
401 local_player: PlayerColor::default(),
402 text: TextStyle::default(),
403 scrollbar_width: Pixels::default(),
404 syntax: Default::default(),
405 // HACK: Status colors don't have a real default.
406 // We should look into removing the status colors from the editor
407 // style and retrieve them directly from the theme.
408 status: StatusColors::dark(),
409 inlay_hints_style: HighlightStyle::default(),
410 inline_completion_styles: InlineCompletionStyles {
411 insertion: HighlightStyle::default(),
412 whitespace: HighlightStyle::default(),
413 },
414 unnecessary_code_fade: Default::default(),
415 }
416 }
417}
418
419pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
420 let show_background = language_settings::language_settings(None, None, cx)
421 .inlay_hints
422 .show_background;
423
424 HighlightStyle {
425 color: Some(cx.theme().status().hint),
426 background_color: show_background.then(|| cx.theme().status().hint_background),
427 ..HighlightStyle::default()
428 }
429}
430
431pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
432 InlineCompletionStyles {
433 insertion: HighlightStyle {
434 color: Some(cx.theme().status().predictive),
435 ..HighlightStyle::default()
436 },
437 whitespace: HighlightStyle {
438 background_color: Some(cx.theme().status().created_background),
439 ..HighlightStyle::default()
440 },
441 }
442}
443
444type CompletionId = usize;
445
446pub(crate) enum EditDisplayMode {
447 TabAccept,
448 DiffPopover,
449 Inline,
450}
451
452enum InlineCompletion {
453 Edit {
454 edits: Vec<(Range<Anchor>, String)>,
455 edit_preview: Option<EditPreview>,
456 display_mode: EditDisplayMode,
457 snapshot: BufferSnapshot,
458 },
459 Move {
460 target: Anchor,
461 snapshot: BufferSnapshot,
462 },
463}
464
465struct InlineCompletionState {
466 inlay_ids: Vec<InlayId>,
467 completion: InlineCompletion,
468 completion_id: Option<SharedString>,
469 invalidation_range: Range<Anchor>,
470}
471
472enum EditPredictionSettings {
473 Disabled,
474 Enabled {
475 show_in_menu: bool,
476 preview_requires_modifier: bool,
477 },
478}
479
480enum InlineCompletionHighlight {}
481
482#[derive(Debug, Clone)]
483struct InlineDiagnostic {
484 message: SharedString,
485 group_id: usize,
486 is_primary: bool,
487 start: Point,
488 severity: DiagnosticSeverity,
489}
490
491pub enum MenuInlineCompletionsPolicy {
492 Never,
493 ByProvider,
494}
495
496pub enum EditPredictionPreview {
497 /// Modifier is not pressed
498 Inactive { released_too_fast: bool },
499 /// Modifier pressed
500 Active {
501 since: Instant,
502 previous_scroll_position: Option<ScrollAnchor>,
503 },
504}
505
506impl EditPredictionPreview {
507 pub fn released_too_fast(&self) -> bool {
508 match self {
509 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
510 EditPredictionPreview::Active { .. } => false,
511 }
512 }
513
514 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
515 if let EditPredictionPreview::Active {
516 previous_scroll_position,
517 ..
518 } = self
519 {
520 *previous_scroll_position = scroll_position;
521 }
522 }
523}
524
525#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
526struct EditorActionId(usize);
527
528impl EditorActionId {
529 pub fn post_inc(&mut self) -> Self {
530 let answer = self.0;
531
532 *self = Self(answer + 1);
533
534 Self(answer)
535 }
536}
537
538// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
539// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
540
541type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
542type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
543
544#[derive(Default)]
545struct ScrollbarMarkerState {
546 scrollbar_size: Size<Pixels>,
547 dirty: bool,
548 markers: Arc<[PaintQuad]>,
549 pending_refresh: Option<Task<Result<()>>>,
550}
551
552impl ScrollbarMarkerState {
553 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
554 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
555 }
556}
557
558#[derive(Clone, Debug)]
559struct RunnableTasks {
560 templates: Vec<(TaskSourceKind, TaskTemplate)>,
561 offset: multi_buffer::Anchor,
562 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
563 column: u32,
564 // Values of all named captures, including those starting with '_'
565 extra_variables: HashMap<String, String>,
566 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
567 context_range: Range<BufferOffset>,
568}
569
570impl RunnableTasks {
571 fn resolve<'a>(
572 &'a self,
573 cx: &'a task::TaskContext,
574 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
575 self.templates.iter().filter_map(|(kind, template)| {
576 template
577 .resolve_task(&kind.to_id_base(), cx)
578 .map(|task| (kind.clone(), task))
579 })
580 }
581}
582
583#[derive(Clone)]
584struct ResolvedTasks {
585 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
586 position: Anchor,
587}
588#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
589struct BufferOffset(usize);
590
591// Addons allow storing per-editor state in other crates (e.g. Vim)
592pub trait Addon: 'static {
593 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
594
595 fn render_buffer_header_controls(
596 &self,
597 _: &ExcerptInfo,
598 _: &Window,
599 _: &App,
600 ) -> Option<AnyElement> {
601 None
602 }
603
604 fn to_any(&self) -> &dyn std::any::Any;
605}
606
607#[derive(Debug, Copy, Clone, PartialEq, Eq)]
608pub enum IsVimMode {
609 Yes,
610 No,
611}
612
613/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
614///
615/// See the [module level documentation](self) for more information.
616pub struct Editor {
617 focus_handle: FocusHandle,
618 last_focused_descendant: Option<WeakFocusHandle>,
619 /// The text buffer being edited
620 buffer: Entity<MultiBuffer>,
621 /// Map of how text in the buffer should be displayed.
622 /// Handles soft wraps, folds, fake inlay text insertions, etc.
623 pub display_map: Entity<DisplayMap>,
624 pub selections: SelectionsCollection,
625 pub scroll_manager: ScrollManager,
626 /// When inline assist editors are linked, they all render cursors because
627 /// typing enters text into each of them, even the ones that aren't focused.
628 pub(crate) show_cursor_when_unfocused: bool,
629 columnar_selection_tail: Option<Anchor>,
630 add_selections_state: Option<AddSelectionsState>,
631 select_next_state: Option<SelectNextState>,
632 select_prev_state: Option<SelectNextState>,
633 selection_history: SelectionHistory,
634 autoclose_regions: Vec<AutocloseRegion>,
635 snippet_stack: InvalidationStack<SnippetState>,
636 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
637 ime_transaction: Option<TransactionId>,
638 active_diagnostics: Option<ActiveDiagnosticGroup>,
639 show_inline_diagnostics: bool,
640 inline_diagnostics_update: Task<()>,
641 inline_diagnostics_enabled: bool,
642 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
643 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
644
645 // TODO: make this a access method
646 pub project: Option<Entity<Project>>,
647 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
648 completion_provider: Option<Box<dyn CompletionProvider>>,
649 collaboration_hub: Option<Box<dyn CollaborationHub>>,
650 blink_manager: Entity<BlinkManager>,
651 show_cursor_names: bool,
652 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
653 pub show_local_selections: bool,
654 mode: EditorMode,
655 show_breadcrumbs: bool,
656 show_gutter: bool,
657 show_scrollbars: bool,
658 show_line_numbers: Option<bool>,
659 use_relative_line_numbers: Option<bool>,
660 show_git_diff_gutter: Option<bool>,
661 show_code_actions: Option<bool>,
662 show_runnables: Option<bool>,
663 show_wrap_guides: Option<bool>,
664 show_indent_guides: Option<bool>,
665 placeholder_text: Option<Arc<str>>,
666 highlight_order: usize,
667 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
668 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
669 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
670 scrollbar_marker_state: ScrollbarMarkerState,
671 active_indent_guides_state: ActiveIndentGuidesState,
672 nav_history: Option<ItemNavHistory>,
673 context_menu: RefCell<Option<CodeContextMenu>>,
674 mouse_context_menu: Option<MouseContextMenu>,
675 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
676 signature_help_state: SignatureHelpState,
677 auto_signature_help: Option<bool>,
678 find_all_references_task_sources: Vec<Anchor>,
679 next_completion_id: CompletionId,
680 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
681 code_actions_task: Option<Task<Result<()>>>,
682 selection_highlight_task: Option<Task<()>>,
683 document_highlights_task: Option<Task<()>>,
684 linked_editing_range_task: Option<Task<Option<()>>>,
685 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
686 pending_rename: Option<RenameState>,
687 searchable: bool,
688 cursor_shape: CursorShape,
689 current_line_highlight: Option<CurrentLineHighlight>,
690 collapse_matches: bool,
691 autoindent_mode: Option<AutoindentMode>,
692 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
693 input_enabled: bool,
694 use_modal_editing: bool,
695 read_only: bool,
696 leader_peer_id: Option<PeerId>,
697 remote_id: Option<ViewId>,
698 hover_state: HoverState,
699 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
700 gutter_hovered: bool,
701 hovered_link_state: Option<HoveredLinkState>,
702 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
703 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
704 active_inline_completion: Option<InlineCompletionState>,
705 /// Used to prevent flickering as the user types while the menu is open
706 stale_inline_completion_in_menu: Option<InlineCompletionState>,
707 edit_prediction_settings: EditPredictionSettings,
708 inline_completions_hidden_for_vim_mode: bool,
709 show_inline_completions_override: Option<bool>,
710 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
711 edit_prediction_preview: EditPredictionPreview,
712 edit_prediction_indent_conflict: bool,
713 edit_prediction_requires_modifier_in_indent_conflict: bool,
714 inlay_hint_cache: InlayHintCache,
715 next_inlay_id: usize,
716 _subscriptions: Vec<Subscription>,
717 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
718 gutter_dimensions: GutterDimensions,
719 style: Option<EditorStyle>,
720 text_style_refinement: Option<TextStyleRefinement>,
721 next_editor_action_id: EditorActionId,
722 editor_actions:
723 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
724 use_autoclose: bool,
725 use_auto_surround: bool,
726 auto_replace_emoji_shortcode: bool,
727 show_git_blame_gutter: bool,
728 show_git_blame_inline: bool,
729 show_git_blame_inline_delay_task: Option<Task<()>>,
730 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
731 git_blame_inline_enabled: bool,
732 serialize_dirty_buffers: bool,
733 show_selection_menu: Option<bool>,
734 blame: Option<Entity<GitBlame>>,
735 blame_subscription: Option<Subscription>,
736 custom_context_menu: Option<
737 Box<
738 dyn 'static
739 + Fn(
740 &mut Self,
741 DisplayPoint,
742 &mut Window,
743 &mut Context<Self>,
744 ) -> Option<Entity<ui::ContextMenu>>,
745 >,
746 >,
747 last_bounds: Option<Bounds<Pixels>>,
748 last_position_map: Option<Rc<PositionMap>>,
749 expect_bounds_change: Option<Bounds<Pixels>>,
750 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
751 tasks_update_task: Option<Task<()>>,
752 in_project_search: bool,
753 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
754 breadcrumb_header: Option<String>,
755 focused_block: Option<FocusedBlock>,
756 next_scroll_position: NextScrollCursorCenterTopBottom,
757 addons: HashMap<TypeId, Box<dyn Addon>>,
758 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
759 load_diff_task: Option<Shared<Task<()>>>,
760 selection_mark_mode: bool,
761 toggle_fold_multiple_buffers: Task<()>,
762 _scroll_cursor_center_top_bottom_task: Task<()>,
763 serialize_selections: Task<()>,
764}
765
766#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
767enum NextScrollCursorCenterTopBottom {
768 #[default]
769 Center,
770 Top,
771 Bottom,
772}
773
774impl NextScrollCursorCenterTopBottom {
775 fn next(&self) -> Self {
776 match self {
777 Self::Center => Self::Top,
778 Self::Top => Self::Bottom,
779 Self::Bottom => Self::Center,
780 }
781 }
782}
783
784#[derive(Clone)]
785pub struct EditorSnapshot {
786 pub mode: EditorMode,
787 show_gutter: bool,
788 show_line_numbers: Option<bool>,
789 show_git_diff_gutter: Option<bool>,
790 show_code_actions: Option<bool>,
791 show_runnables: Option<bool>,
792 git_blame_gutter_max_author_length: Option<usize>,
793 pub display_snapshot: DisplaySnapshot,
794 pub placeholder_text: Option<Arc<str>>,
795 is_focused: bool,
796 scroll_anchor: ScrollAnchor,
797 ongoing_scroll: OngoingScroll,
798 current_line_highlight: CurrentLineHighlight,
799 gutter_hovered: bool,
800}
801
802const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
803
804#[derive(Default, Debug, Clone, Copy)]
805pub struct GutterDimensions {
806 pub left_padding: Pixels,
807 pub right_padding: Pixels,
808 pub width: Pixels,
809 pub margin: Pixels,
810 pub git_blame_entries_width: Option<Pixels>,
811}
812
813impl GutterDimensions {
814 /// The full width of the space taken up by the gutter.
815 pub fn full_width(&self) -> Pixels {
816 self.margin + self.width
817 }
818
819 /// The width of the space reserved for the fold indicators,
820 /// use alongside 'justify_end' and `gutter_width` to
821 /// right align content with the line numbers
822 pub fn fold_area_width(&self) -> Pixels {
823 self.margin + self.right_padding
824 }
825}
826
827#[derive(Debug)]
828pub struct RemoteSelection {
829 pub replica_id: ReplicaId,
830 pub selection: Selection<Anchor>,
831 pub cursor_shape: CursorShape,
832 pub peer_id: PeerId,
833 pub line_mode: bool,
834 pub participant_index: Option<ParticipantIndex>,
835 pub user_name: Option<SharedString>,
836}
837
838#[derive(Clone, Debug)]
839struct SelectionHistoryEntry {
840 selections: Arc<[Selection<Anchor>]>,
841 select_next_state: Option<SelectNextState>,
842 select_prev_state: Option<SelectNextState>,
843 add_selections_state: Option<AddSelectionsState>,
844}
845
846enum SelectionHistoryMode {
847 Normal,
848 Undoing,
849 Redoing,
850}
851
852#[derive(Clone, PartialEq, Eq, Hash)]
853struct HoveredCursor {
854 replica_id: u16,
855 selection_id: usize,
856}
857
858impl Default for SelectionHistoryMode {
859 fn default() -> Self {
860 Self::Normal
861 }
862}
863
864#[derive(Default)]
865struct SelectionHistory {
866 #[allow(clippy::type_complexity)]
867 selections_by_transaction:
868 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
869 mode: SelectionHistoryMode,
870 undo_stack: VecDeque<SelectionHistoryEntry>,
871 redo_stack: VecDeque<SelectionHistoryEntry>,
872}
873
874impl SelectionHistory {
875 fn insert_transaction(
876 &mut self,
877 transaction_id: TransactionId,
878 selections: Arc<[Selection<Anchor>]>,
879 ) {
880 self.selections_by_transaction
881 .insert(transaction_id, (selections, None));
882 }
883
884 #[allow(clippy::type_complexity)]
885 fn transaction(
886 &self,
887 transaction_id: TransactionId,
888 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
889 self.selections_by_transaction.get(&transaction_id)
890 }
891
892 #[allow(clippy::type_complexity)]
893 fn transaction_mut(
894 &mut self,
895 transaction_id: TransactionId,
896 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
897 self.selections_by_transaction.get_mut(&transaction_id)
898 }
899
900 fn push(&mut self, entry: SelectionHistoryEntry) {
901 if !entry.selections.is_empty() {
902 match self.mode {
903 SelectionHistoryMode::Normal => {
904 self.push_undo(entry);
905 self.redo_stack.clear();
906 }
907 SelectionHistoryMode::Undoing => self.push_redo(entry),
908 SelectionHistoryMode::Redoing => self.push_undo(entry),
909 }
910 }
911 }
912
913 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
914 if self
915 .undo_stack
916 .back()
917 .map_or(true, |e| e.selections != entry.selections)
918 {
919 self.undo_stack.push_back(entry);
920 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
921 self.undo_stack.pop_front();
922 }
923 }
924 }
925
926 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
927 if self
928 .redo_stack
929 .back()
930 .map_or(true, |e| e.selections != entry.selections)
931 {
932 self.redo_stack.push_back(entry);
933 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
934 self.redo_stack.pop_front();
935 }
936 }
937 }
938}
939
940struct RowHighlight {
941 index: usize,
942 range: Range<Anchor>,
943 color: Hsla,
944 should_autoscroll: bool,
945}
946
947#[derive(Clone, Debug)]
948struct AddSelectionsState {
949 above: bool,
950 stack: Vec<usize>,
951}
952
953#[derive(Clone)]
954struct SelectNextState {
955 query: AhoCorasick,
956 wordwise: bool,
957 done: bool,
958}
959
960impl std::fmt::Debug for SelectNextState {
961 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
962 f.debug_struct(std::any::type_name::<Self>())
963 .field("wordwise", &self.wordwise)
964 .field("done", &self.done)
965 .finish()
966 }
967}
968
969#[derive(Debug)]
970struct AutocloseRegion {
971 selection_id: usize,
972 range: Range<Anchor>,
973 pair: BracketPair,
974}
975
976#[derive(Debug)]
977struct SnippetState {
978 ranges: Vec<Vec<Range<Anchor>>>,
979 active_index: usize,
980 choices: Vec<Option<Vec<String>>>,
981}
982
983#[doc(hidden)]
984pub struct RenameState {
985 pub range: Range<Anchor>,
986 pub old_name: Arc<str>,
987 pub editor: Entity<Editor>,
988 block_id: CustomBlockId,
989}
990
991struct InvalidationStack<T>(Vec<T>);
992
993struct RegisteredInlineCompletionProvider {
994 provider: Arc<dyn InlineCompletionProviderHandle>,
995 _subscription: Subscription,
996}
997
998#[derive(Debug, PartialEq, Eq)]
999struct ActiveDiagnosticGroup {
1000 primary_range: Range<Anchor>,
1001 primary_message: String,
1002 group_id: usize,
1003 blocks: HashMap<CustomBlockId, Diagnostic>,
1004 is_valid: bool,
1005}
1006
1007#[derive(Serialize, Deserialize, Clone, Debug)]
1008pub struct ClipboardSelection {
1009 /// The number of bytes in this selection.
1010 pub len: usize,
1011 /// Whether this was a full-line selection.
1012 pub is_entire_line: bool,
1013 /// The column where this selection originally started.
1014 pub start_column: u32,
1015}
1016
1017#[derive(Debug)]
1018pub(crate) struct NavigationData {
1019 cursor_anchor: Anchor,
1020 cursor_position: Point,
1021 scroll_anchor: ScrollAnchor,
1022 scroll_top_row: u32,
1023}
1024
1025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1026pub enum GotoDefinitionKind {
1027 Symbol,
1028 Declaration,
1029 Type,
1030 Implementation,
1031}
1032
1033#[derive(Debug, Clone)]
1034enum InlayHintRefreshReason {
1035 ModifiersChanged(bool),
1036 Toggle(bool),
1037 SettingsChange(InlayHintSettings),
1038 NewLinesShown,
1039 BufferEdited(HashSet<Arc<Language>>),
1040 RefreshRequested,
1041 ExcerptsRemoved(Vec<ExcerptId>),
1042}
1043
1044impl InlayHintRefreshReason {
1045 fn description(&self) -> &'static str {
1046 match self {
1047 Self::ModifiersChanged(_) => "modifiers changed",
1048 Self::Toggle(_) => "toggle",
1049 Self::SettingsChange(_) => "settings change",
1050 Self::NewLinesShown => "new lines shown",
1051 Self::BufferEdited(_) => "buffer edited",
1052 Self::RefreshRequested => "refresh requested",
1053 Self::ExcerptsRemoved(_) => "excerpts removed",
1054 }
1055 }
1056}
1057
1058pub enum FormatTarget {
1059 Buffers,
1060 Ranges(Vec<Range<MultiBufferPoint>>),
1061}
1062
1063pub(crate) struct FocusedBlock {
1064 id: BlockId,
1065 focus_handle: WeakFocusHandle,
1066}
1067
1068#[derive(Clone)]
1069enum JumpData {
1070 MultiBufferRow {
1071 row: MultiBufferRow,
1072 line_offset_from_top: u32,
1073 },
1074 MultiBufferPoint {
1075 excerpt_id: ExcerptId,
1076 position: Point,
1077 anchor: text::Anchor,
1078 line_offset_from_top: u32,
1079 },
1080}
1081
1082pub enum MultibufferSelectionMode {
1083 First,
1084 All,
1085}
1086
1087impl Editor {
1088 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1089 let buffer = cx.new(|cx| Buffer::local("", cx));
1090 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1091 Self::new(
1092 EditorMode::SingleLine { auto_width: false },
1093 buffer,
1094 None,
1095 false,
1096 window,
1097 cx,
1098 )
1099 }
1100
1101 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1102 let buffer = cx.new(|cx| Buffer::local("", cx));
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1105 }
1106
1107 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1108 let buffer = cx.new(|cx| Buffer::local("", cx));
1109 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1110 Self::new(
1111 EditorMode::SingleLine { auto_width: true },
1112 buffer,
1113 None,
1114 false,
1115 window,
1116 cx,
1117 )
1118 }
1119
1120 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1121 let buffer = cx.new(|cx| Buffer::local("", cx));
1122 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1123 Self::new(
1124 EditorMode::AutoHeight { max_lines },
1125 buffer,
1126 None,
1127 false,
1128 window,
1129 cx,
1130 )
1131 }
1132
1133 pub fn for_buffer(
1134 buffer: Entity<Buffer>,
1135 project: Option<Entity<Project>>,
1136 window: &mut Window,
1137 cx: &mut Context<Self>,
1138 ) -> Self {
1139 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1140 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1141 }
1142
1143 pub fn for_multibuffer(
1144 buffer: Entity<MultiBuffer>,
1145 project: Option<Entity<Project>>,
1146 show_excerpt_controls: bool,
1147 window: &mut Window,
1148 cx: &mut Context<Self>,
1149 ) -> Self {
1150 Self::new(
1151 EditorMode::Full,
1152 buffer,
1153 project,
1154 show_excerpt_controls,
1155 window,
1156 cx,
1157 )
1158 }
1159
1160 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1161 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1162 let mut clone = Self::new(
1163 self.mode,
1164 self.buffer.clone(),
1165 self.project.clone(),
1166 show_excerpt_controls,
1167 window,
1168 cx,
1169 );
1170 self.display_map.update(cx, |display_map, cx| {
1171 let snapshot = display_map.snapshot(cx);
1172 clone.display_map.update(cx, |display_map, cx| {
1173 display_map.set_state(&snapshot, cx);
1174 });
1175 });
1176 clone.selections.clone_state(&self.selections);
1177 clone.scroll_manager.clone_state(&self.scroll_manager);
1178 clone.searchable = self.searchable;
1179 clone
1180 }
1181
1182 pub fn new(
1183 mode: EditorMode,
1184 buffer: Entity<MultiBuffer>,
1185 project: Option<Entity<Project>>,
1186 show_excerpt_controls: bool,
1187 window: &mut Window,
1188 cx: &mut Context<Self>,
1189 ) -> Self {
1190 let style = window.text_style();
1191 let font_size = style.font_size.to_pixels(window.rem_size());
1192 let editor = cx.entity().downgrade();
1193 let fold_placeholder = FoldPlaceholder {
1194 constrain_width: true,
1195 render: Arc::new(move |fold_id, fold_range, cx| {
1196 let editor = editor.clone();
1197 div()
1198 .id(fold_id)
1199 .bg(cx.theme().colors().ghost_element_background)
1200 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1201 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1202 .rounded_sm()
1203 .size_full()
1204 .cursor_pointer()
1205 .child("⋯")
1206 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1207 .on_click(move |_, _window, cx| {
1208 editor
1209 .update(cx, |editor, cx| {
1210 editor.unfold_ranges(
1211 &[fold_range.start..fold_range.end],
1212 true,
1213 false,
1214 cx,
1215 );
1216 cx.stop_propagation();
1217 })
1218 .ok();
1219 })
1220 .into_any()
1221 }),
1222 merge_adjacent: true,
1223 ..Default::default()
1224 };
1225 let display_map = cx.new(|cx| {
1226 DisplayMap::new(
1227 buffer.clone(),
1228 style.font(),
1229 font_size,
1230 None,
1231 show_excerpt_controls,
1232 FILE_HEADER_HEIGHT,
1233 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1234 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1235 fold_placeholder,
1236 cx,
1237 )
1238 });
1239
1240 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1241
1242 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1243
1244 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1245 .then(|| language_settings::SoftWrap::None);
1246
1247 let mut project_subscriptions = Vec::new();
1248 if mode == EditorMode::Full {
1249 if let Some(project) = project.as_ref() {
1250 if buffer.read(cx).is_singleton() {
1251 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1252 cx.emit(EditorEvent::TitleChanged);
1253 }));
1254 }
1255 project_subscriptions.push(cx.subscribe_in(
1256 project,
1257 window,
1258 |editor, _, event, window, cx| {
1259 if let project::Event::RefreshInlayHints = event {
1260 editor
1261 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1262 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1263 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1264 let focus_handle = editor.focus_handle(cx);
1265 if focus_handle.is_focused(window) {
1266 let snapshot = buffer.read(cx).snapshot();
1267 for (range, snippet) in snippet_edits {
1268 let editor_range =
1269 language::range_from_lsp(*range).to_offset(&snapshot);
1270 editor
1271 .insert_snippet(
1272 &[editor_range],
1273 snippet.clone(),
1274 window,
1275 cx,
1276 )
1277 .ok();
1278 }
1279 }
1280 }
1281 }
1282 },
1283 ));
1284 if let Some(task_inventory) = project
1285 .read(cx)
1286 .task_store()
1287 .read(cx)
1288 .task_inventory()
1289 .cloned()
1290 {
1291 project_subscriptions.push(cx.observe_in(
1292 &task_inventory,
1293 window,
1294 |editor, _, window, cx| {
1295 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1296 },
1297 ));
1298 }
1299 }
1300 }
1301
1302 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1303
1304 let inlay_hint_settings =
1305 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1306 let focus_handle = cx.focus_handle();
1307 cx.on_focus(&focus_handle, window, Self::handle_focus)
1308 .detach();
1309 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1310 .detach();
1311 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1312 .detach();
1313 cx.on_blur(&focus_handle, window, Self::handle_blur)
1314 .detach();
1315
1316 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1317 Some(false)
1318 } else {
1319 None
1320 };
1321
1322 let mut code_action_providers = Vec::new();
1323 let mut load_uncommitted_diff = None;
1324 if let Some(project) = project.clone() {
1325 load_uncommitted_diff = Some(
1326 get_uncommitted_diff_for_buffer(
1327 &project,
1328 buffer.read(cx).all_buffers(),
1329 buffer.clone(),
1330 cx,
1331 )
1332 .shared(),
1333 );
1334 code_action_providers.push(Rc::new(project) as Rc<_>);
1335 }
1336
1337 let mut this = Self {
1338 focus_handle,
1339 show_cursor_when_unfocused: false,
1340 last_focused_descendant: None,
1341 buffer: buffer.clone(),
1342 display_map: display_map.clone(),
1343 selections,
1344 scroll_manager: ScrollManager::new(cx),
1345 columnar_selection_tail: None,
1346 add_selections_state: None,
1347 select_next_state: None,
1348 select_prev_state: None,
1349 selection_history: Default::default(),
1350 autoclose_regions: Default::default(),
1351 snippet_stack: Default::default(),
1352 select_larger_syntax_node_stack: Vec::new(),
1353 ime_transaction: Default::default(),
1354 active_diagnostics: None,
1355 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1356 inline_diagnostics_update: Task::ready(()),
1357 inline_diagnostics: Vec::new(),
1358 soft_wrap_mode_override,
1359 completion_provider: project.clone().map(|project| Box::new(project) as _),
1360 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1361 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1362 project,
1363 blink_manager: blink_manager.clone(),
1364 show_local_selections: true,
1365 show_scrollbars: true,
1366 mode,
1367 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1368 show_gutter: mode == EditorMode::Full,
1369 show_line_numbers: None,
1370 use_relative_line_numbers: None,
1371 show_git_diff_gutter: None,
1372 show_code_actions: None,
1373 show_runnables: None,
1374 show_wrap_guides: None,
1375 show_indent_guides,
1376 placeholder_text: None,
1377 highlight_order: 0,
1378 highlighted_rows: HashMap::default(),
1379 background_highlights: Default::default(),
1380 gutter_highlights: TreeMap::default(),
1381 scrollbar_marker_state: ScrollbarMarkerState::default(),
1382 active_indent_guides_state: ActiveIndentGuidesState::default(),
1383 nav_history: None,
1384 context_menu: RefCell::new(None),
1385 mouse_context_menu: None,
1386 completion_tasks: Default::default(),
1387 signature_help_state: SignatureHelpState::default(),
1388 auto_signature_help: None,
1389 find_all_references_task_sources: Vec::new(),
1390 next_completion_id: 0,
1391 next_inlay_id: 0,
1392 code_action_providers,
1393 available_code_actions: Default::default(),
1394 code_actions_task: Default::default(),
1395 selection_highlight_task: Default::default(),
1396 document_highlights_task: Default::default(),
1397 linked_editing_range_task: Default::default(),
1398 pending_rename: Default::default(),
1399 searchable: true,
1400 cursor_shape: EditorSettings::get_global(cx)
1401 .cursor_shape
1402 .unwrap_or_default(),
1403 current_line_highlight: None,
1404 autoindent_mode: Some(AutoindentMode::EachLine),
1405 collapse_matches: false,
1406 workspace: None,
1407 input_enabled: true,
1408 use_modal_editing: mode == EditorMode::Full,
1409 read_only: false,
1410 use_autoclose: true,
1411 use_auto_surround: true,
1412 auto_replace_emoji_shortcode: false,
1413 leader_peer_id: None,
1414 remote_id: None,
1415 hover_state: Default::default(),
1416 pending_mouse_down: None,
1417 hovered_link_state: Default::default(),
1418 edit_prediction_provider: None,
1419 active_inline_completion: None,
1420 stale_inline_completion_in_menu: None,
1421 edit_prediction_preview: EditPredictionPreview::Inactive {
1422 released_too_fast: false,
1423 },
1424 inline_diagnostics_enabled: mode == EditorMode::Full,
1425 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1426
1427 gutter_hovered: false,
1428 pixel_position_of_newest_cursor: None,
1429 last_bounds: None,
1430 last_position_map: None,
1431 expect_bounds_change: None,
1432 gutter_dimensions: GutterDimensions::default(),
1433 style: None,
1434 show_cursor_names: false,
1435 hovered_cursors: Default::default(),
1436 next_editor_action_id: EditorActionId::default(),
1437 editor_actions: Rc::default(),
1438 inline_completions_hidden_for_vim_mode: false,
1439 show_inline_completions_override: None,
1440 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1441 edit_prediction_settings: EditPredictionSettings::Disabled,
1442 edit_prediction_indent_conflict: false,
1443 edit_prediction_requires_modifier_in_indent_conflict: true,
1444 custom_context_menu: None,
1445 show_git_blame_gutter: false,
1446 show_git_blame_inline: false,
1447 show_selection_menu: None,
1448 show_git_blame_inline_delay_task: None,
1449 git_blame_inline_tooltip: None,
1450 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1451 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1452 .session
1453 .restore_unsaved_buffers,
1454 blame: None,
1455 blame_subscription: None,
1456 tasks: Default::default(),
1457 _subscriptions: vec![
1458 cx.observe(&buffer, Self::on_buffer_changed),
1459 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1460 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1461 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1462 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1463 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1464 cx.observe_window_activation(window, |editor, window, cx| {
1465 let active = window.is_window_active();
1466 editor.blink_manager.update(cx, |blink_manager, cx| {
1467 if active {
1468 blink_manager.enable(cx);
1469 } else {
1470 blink_manager.disable(cx);
1471 }
1472 });
1473 }),
1474 ],
1475 tasks_update_task: None,
1476 linked_edit_ranges: Default::default(),
1477 in_project_search: false,
1478 previous_search_ranges: None,
1479 breadcrumb_header: None,
1480 focused_block: None,
1481 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1482 addons: HashMap::default(),
1483 registered_buffers: HashMap::default(),
1484 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1485 selection_mark_mode: false,
1486 toggle_fold_multiple_buffers: Task::ready(()),
1487 serialize_selections: Task::ready(()),
1488 text_style_refinement: None,
1489 load_diff_task: load_uncommitted_diff,
1490 };
1491 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1492 this._subscriptions.extend(project_subscriptions);
1493
1494 this.end_selection(window, cx);
1495 this.scroll_manager.show_scrollbar(window, cx);
1496
1497 if mode == EditorMode::Full {
1498 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1499 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1500
1501 if this.git_blame_inline_enabled {
1502 this.git_blame_inline_enabled = true;
1503 this.start_git_blame_inline(false, window, cx);
1504 }
1505
1506 if let Some(buffer) = buffer.read(cx).as_singleton() {
1507 if let Some(project) = this.project.as_ref() {
1508 let handle = project.update(cx, |project, cx| {
1509 project.register_buffer_with_language_servers(&buffer, cx)
1510 });
1511 this.registered_buffers
1512 .insert(buffer.read(cx).remote_id(), handle);
1513 }
1514 }
1515 }
1516
1517 this.report_editor_event("Editor Opened", None, cx);
1518 this
1519 }
1520
1521 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1522 self.mouse_context_menu
1523 .as_ref()
1524 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1525 }
1526
1527 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1528 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1529 }
1530
1531 fn key_context_internal(
1532 &self,
1533 has_active_edit_prediction: bool,
1534 window: &Window,
1535 cx: &App,
1536 ) -> KeyContext {
1537 let mut key_context = KeyContext::new_with_defaults();
1538 key_context.add("Editor");
1539 let mode = match self.mode {
1540 EditorMode::SingleLine { .. } => "single_line",
1541 EditorMode::AutoHeight { .. } => "auto_height",
1542 EditorMode::Full => "full",
1543 };
1544
1545 if EditorSettings::jupyter_enabled(cx) {
1546 key_context.add("jupyter");
1547 }
1548
1549 key_context.set("mode", mode);
1550 if self.pending_rename.is_some() {
1551 key_context.add("renaming");
1552 }
1553
1554 match self.context_menu.borrow().as_ref() {
1555 Some(CodeContextMenu::Completions(_)) => {
1556 key_context.add("menu");
1557 key_context.add("showing_completions");
1558 }
1559 Some(CodeContextMenu::CodeActions(_)) => {
1560 key_context.add("menu");
1561 key_context.add("showing_code_actions")
1562 }
1563 None => {}
1564 }
1565
1566 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1567 if !self.focus_handle(cx).contains_focused(window, cx)
1568 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1569 {
1570 for addon in self.addons.values() {
1571 addon.extend_key_context(&mut key_context, cx)
1572 }
1573 }
1574
1575 if let Some(extension) = self
1576 .buffer
1577 .read(cx)
1578 .as_singleton()
1579 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1580 {
1581 key_context.set("extension", extension.to_string());
1582 }
1583
1584 if has_active_edit_prediction {
1585 if self.edit_prediction_in_conflict() {
1586 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1587 } else {
1588 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1589 key_context.add("copilot_suggestion");
1590 }
1591 }
1592
1593 if self.selection_mark_mode {
1594 key_context.add("selection_mode");
1595 }
1596
1597 key_context
1598 }
1599
1600 pub fn edit_prediction_in_conflict(&self) -> bool {
1601 if !self.show_edit_predictions_in_menu() {
1602 return false;
1603 }
1604
1605 let showing_completions = self
1606 .context_menu
1607 .borrow()
1608 .as_ref()
1609 .map_or(false, |context| {
1610 matches!(context, CodeContextMenu::Completions(_))
1611 });
1612
1613 showing_completions
1614 || self.edit_prediction_requires_modifier()
1615 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1616 // bindings to insert tab characters.
1617 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1618 }
1619
1620 pub fn accept_edit_prediction_keybind(
1621 &self,
1622 window: &Window,
1623 cx: &App,
1624 ) -> AcceptEditPredictionBinding {
1625 let key_context = self.key_context_internal(true, window, cx);
1626 let in_conflict = self.edit_prediction_in_conflict();
1627
1628 AcceptEditPredictionBinding(
1629 window
1630 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1631 .into_iter()
1632 .filter(|binding| {
1633 !in_conflict
1634 || binding
1635 .keystrokes()
1636 .first()
1637 .map_or(false, |keystroke| keystroke.modifiers.modified())
1638 })
1639 .rev()
1640 .min_by_key(|binding| {
1641 binding
1642 .keystrokes()
1643 .first()
1644 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1645 }),
1646 )
1647 }
1648
1649 pub fn new_file(
1650 workspace: &mut Workspace,
1651 _: &workspace::NewFile,
1652 window: &mut Window,
1653 cx: &mut Context<Workspace>,
1654 ) {
1655 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1656 "Failed to create buffer",
1657 window,
1658 cx,
1659 |e, _, _| match e.error_code() {
1660 ErrorCode::RemoteUpgradeRequired => Some(format!(
1661 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1662 e.error_tag("required").unwrap_or("the latest version")
1663 )),
1664 _ => None,
1665 },
1666 );
1667 }
1668
1669 pub fn new_in_workspace(
1670 workspace: &mut Workspace,
1671 window: &mut Window,
1672 cx: &mut Context<Workspace>,
1673 ) -> Task<Result<Entity<Editor>>> {
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, |workspace, window, cx| {
1680 let editor =
1681 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1682 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1683 editor
1684 })
1685 })
1686 }
1687
1688 fn new_file_vertical(
1689 workspace: &mut Workspace,
1690 _: &workspace::NewFileSplitVertical,
1691 window: &mut Window,
1692 cx: &mut Context<Workspace>,
1693 ) {
1694 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1695 }
1696
1697 fn new_file_horizontal(
1698 workspace: &mut Workspace,
1699 _: &workspace::NewFileSplitHorizontal,
1700 window: &mut Window,
1701 cx: &mut Context<Workspace>,
1702 ) {
1703 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1704 }
1705
1706 fn new_file_in_direction(
1707 workspace: &mut Workspace,
1708 direction: SplitDirection,
1709 window: &mut Window,
1710 cx: &mut Context<Workspace>,
1711 ) {
1712 let project = workspace.project().clone();
1713 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1714
1715 cx.spawn_in(window, |workspace, mut cx| async move {
1716 let buffer = create.await?;
1717 workspace.update_in(&mut cx, move |workspace, window, cx| {
1718 workspace.split_item(
1719 direction,
1720 Box::new(
1721 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1722 ),
1723 window,
1724 cx,
1725 )
1726 })?;
1727 anyhow::Ok(())
1728 })
1729 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1730 match e.error_code() {
1731 ErrorCode::RemoteUpgradeRequired => Some(format!(
1732 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1733 e.error_tag("required").unwrap_or("the latest version")
1734 )),
1735 _ => None,
1736 }
1737 });
1738 }
1739
1740 pub fn leader_peer_id(&self) -> Option<PeerId> {
1741 self.leader_peer_id
1742 }
1743
1744 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1745 &self.buffer
1746 }
1747
1748 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1749 self.workspace.as_ref()?.0.upgrade()
1750 }
1751
1752 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1753 self.buffer().read(cx).title(cx)
1754 }
1755
1756 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1757 let git_blame_gutter_max_author_length = self
1758 .render_git_blame_gutter(cx)
1759 .then(|| {
1760 if let Some(blame) = self.blame.as_ref() {
1761 let max_author_length =
1762 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1763 Some(max_author_length)
1764 } else {
1765 None
1766 }
1767 })
1768 .flatten();
1769
1770 EditorSnapshot {
1771 mode: self.mode,
1772 show_gutter: self.show_gutter,
1773 show_line_numbers: self.show_line_numbers,
1774 show_git_diff_gutter: self.show_git_diff_gutter,
1775 show_code_actions: self.show_code_actions,
1776 show_runnables: self.show_runnables,
1777 git_blame_gutter_max_author_length,
1778 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1779 scroll_anchor: self.scroll_manager.anchor(),
1780 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1781 placeholder_text: self.placeholder_text.clone(),
1782 is_focused: self.focus_handle.is_focused(window),
1783 current_line_highlight: self
1784 .current_line_highlight
1785 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1786 gutter_hovered: self.gutter_hovered,
1787 }
1788 }
1789
1790 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1791 self.buffer.read(cx).language_at(point, cx)
1792 }
1793
1794 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1795 self.buffer.read(cx).read(cx).file_at(point).cloned()
1796 }
1797
1798 pub fn active_excerpt(
1799 &self,
1800 cx: &App,
1801 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1802 self.buffer
1803 .read(cx)
1804 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1805 }
1806
1807 pub fn mode(&self) -> EditorMode {
1808 self.mode
1809 }
1810
1811 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1812 self.collaboration_hub.as_deref()
1813 }
1814
1815 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1816 self.collaboration_hub = Some(hub);
1817 }
1818
1819 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1820 self.in_project_search = in_project_search;
1821 }
1822
1823 pub fn set_custom_context_menu(
1824 &mut self,
1825 f: impl 'static
1826 + Fn(
1827 &mut Self,
1828 DisplayPoint,
1829 &mut Window,
1830 &mut Context<Self>,
1831 ) -> Option<Entity<ui::ContextMenu>>,
1832 ) {
1833 self.custom_context_menu = Some(Box::new(f))
1834 }
1835
1836 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1837 self.completion_provider = provider;
1838 }
1839
1840 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1841 self.semantics_provider.clone()
1842 }
1843
1844 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1845 self.semantics_provider = provider;
1846 }
1847
1848 pub fn set_edit_prediction_provider<T>(
1849 &mut self,
1850 provider: Option<Entity<T>>,
1851 window: &mut Window,
1852 cx: &mut Context<Self>,
1853 ) where
1854 T: EditPredictionProvider,
1855 {
1856 self.edit_prediction_provider =
1857 provider.map(|provider| RegisteredInlineCompletionProvider {
1858 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1859 if this.focus_handle.is_focused(window) {
1860 this.update_visible_inline_completion(window, cx);
1861 }
1862 }),
1863 provider: Arc::new(provider),
1864 });
1865 self.update_edit_prediction_settings(cx);
1866 self.refresh_inline_completion(false, false, window, cx);
1867 }
1868
1869 pub fn placeholder_text(&self) -> Option<&str> {
1870 self.placeholder_text.as_deref()
1871 }
1872
1873 pub fn set_placeholder_text(
1874 &mut self,
1875 placeholder_text: impl Into<Arc<str>>,
1876 cx: &mut Context<Self>,
1877 ) {
1878 let placeholder_text = Some(placeholder_text.into());
1879 if self.placeholder_text != placeholder_text {
1880 self.placeholder_text = placeholder_text;
1881 cx.notify();
1882 }
1883 }
1884
1885 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1886 self.cursor_shape = cursor_shape;
1887
1888 // Disrupt blink for immediate user feedback that the cursor shape has changed
1889 self.blink_manager.update(cx, BlinkManager::show_cursor);
1890
1891 cx.notify();
1892 }
1893
1894 pub fn set_current_line_highlight(
1895 &mut self,
1896 current_line_highlight: Option<CurrentLineHighlight>,
1897 ) {
1898 self.current_line_highlight = current_line_highlight;
1899 }
1900
1901 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1902 self.collapse_matches = collapse_matches;
1903 }
1904
1905 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1906 let buffers = self.buffer.read(cx).all_buffers();
1907 let Some(project) = self.project.as_ref() else {
1908 return;
1909 };
1910 project.update(cx, |project, cx| {
1911 for buffer in buffers {
1912 self.registered_buffers
1913 .entry(buffer.read(cx).remote_id())
1914 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1915 }
1916 })
1917 }
1918
1919 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1920 if self.collapse_matches {
1921 return range.start..range.start;
1922 }
1923 range.clone()
1924 }
1925
1926 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1927 if self.display_map.read(cx).clip_at_line_ends != clip {
1928 self.display_map
1929 .update(cx, |map, _| map.clip_at_line_ends = clip);
1930 }
1931 }
1932
1933 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1934 self.input_enabled = input_enabled;
1935 }
1936
1937 pub fn set_inline_completions_hidden_for_vim_mode(
1938 &mut self,
1939 hidden: bool,
1940 window: &mut Window,
1941 cx: &mut Context<Self>,
1942 ) {
1943 if hidden != self.inline_completions_hidden_for_vim_mode {
1944 self.inline_completions_hidden_for_vim_mode = hidden;
1945 if hidden {
1946 self.update_visible_inline_completion(window, cx);
1947 } else {
1948 self.refresh_inline_completion(true, false, window, cx);
1949 }
1950 }
1951 }
1952
1953 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1954 self.menu_inline_completions_policy = value;
1955 }
1956
1957 pub fn set_autoindent(&mut self, autoindent: bool) {
1958 if autoindent {
1959 self.autoindent_mode = Some(AutoindentMode::EachLine);
1960 } else {
1961 self.autoindent_mode = None;
1962 }
1963 }
1964
1965 pub fn read_only(&self, cx: &App) -> bool {
1966 self.read_only || self.buffer.read(cx).read_only()
1967 }
1968
1969 pub fn set_read_only(&mut self, read_only: bool) {
1970 self.read_only = read_only;
1971 }
1972
1973 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1974 self.use_autoclose = autoclose;
1975 }
1976
1977 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1978 self.use_auto_surround = auto_surround;
1979 }
1980
1981 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1982 self.auto_replace_emoji_shortcode = auto_replace;
1983 }
1984
1985 pub fn toggle_edit_predictions(
1986 &mut self,
1987 _: &ToggleEditPrediction,
1988 window: &mut Window,
1989 cx: &mut Context<Self>,
1990 ) {
1991 if self.show_inline_completions_override.is_some() {
1992 self.set_show_edit_predictions(None, window, cx);
1993 } else {
1994 let show_edit_predictions = !self.edit_predictions_enabled();
1995 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1996 }
1997 }
1998
1999 pub fn set_show_edit_predictions(
2000 &mut self,
2001 show_edit_predictions: Option<bool>,
2002 window: &mut Window,
2003 cx: &mut Context<Self>,
2004 ) {
2005 self.show_inline_completions_override = show_edit_predictions;
2006 self.update_edit_prediction_settings(cx);
2007
2008 if let Some(false) = show_edit_predictions {
2009 self.discard_inline_completion(false, cx);
2010 } else {
2011 self.refresh_inline_completion(false, true, window, cx);
2012 }
2013 }
2014
2015 fn inline_completions_disabled_in_scope(
2016 &self,
2017 buffer: &Entity<Buffer>,
2018 buffer_position: language::Anchor,
2019 cx: &App,
2020 ) -> bool {
2021 let snapshot = buffer.read(cx).snapshot();
2022 let settings = snapshot.settings_at(buffer_position, cx);
2023
2024 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2025 return false;
2026 };
2027
2028 scope.override_name().map_or(false, |scope_name| {
2029 settings
2030 .edit_predictions_disabled_in
2031 .iter()
2032 .any(|s| s == scope_name)
2033 })
2034 }
2035
2036 pub fn set_use_modal_editing(&mut self, to: bool) {
2037 self.use_modal_editing = to;
2038 }
2039
2040 pub fn use_modal_editing(&self) -> bool {
2041 self.use_modal_editing
2042 }
2043
2044 fn selections_did_change(
2045 &mut self,
2046 local: bool,
2047 old_cursor_position: &Anchor,
2048 show_completions: bool,
2049 window: &mut Window,
2050 cx: &mut Context<Self>,
2051 ) {
2052 window.invalidate_character_coordinates();
2053
2054 // Copy selections to primary selection buffer
2055 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2056 if local {
2057 let selections = self.selections.all::<usize>(cx);
2058 let buffer_handle = self.buffer.read(cx).read(cx);
2059
2060 let mut text = String::new();
2061 for (index, selection) in selections.iter().enumerate() {
2062 let text_for_selection = buffer_handle
2063 .text_for_range(selection.start..selection.end)
2064 .collect::<String>();
2065
2066 text.push_str(&text_for_selection);
2067 if index != selections.len() - 1 {
2068 text.push('\n');
2069 }
2070 }
2071
2072 if !text.is_empty() {
2073 cx.write_to_primary(ClipboardItem::new_string(text));
2074 }
2075 }
2076
2077 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2078 self.buffer.update(cx, |buffer, cx| {
2079 buffer.set_active_selections(
2080 &self.selections.disjoint_anchors(),
2081 self.selections.line_mode,
2082 self.cursor_shape,
2083 cx,
2084 )
2085 });
2086 }
2087 let display_map = self
2088 .display_map
2089 .update(cx, |display_map, cx| display_map.snapshot(cx));
2090 let buffer = &display_map.buffer_snapshot;
2091 self.add_selections_state = None;
2092 self.select_next_state = None;
2093 self.select_prev_state = None;
2094 self.select_larger_syntax_node_stack.clear();
2095 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2096 self.snippet_stack
2097 .invalidate(&self.selections.disjoint_anchors(), buffer);
2098 self.take_rename(false, window, cx);
2099
2100 let new_cursor_position = self.selections.newest_anchor().head();
2101
2102 self.push_to_nav_history(
2103 *old_cursor_position,
2104 Some(new_cursor_position.to_point(buffer)),
2105 cx,
2106 );
2107
2108 if local {
2109 let new_cursor_position = self.selections.newest_anchor().head();
2110 let mut context_menu = self.context_menu.borrow_mut();
2111 let completion_menu = match context_menu.as_ref() {
2112 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2113 _ => {
2114 *context_menu = None;
2115 None
2116 }
2117 };
2118 if let Some(buffer_id) = new_cursor_position.buffer_id {
2119 if !self.registered_buffers.contains_key(&buffer_id) {
2120 if let Some(project) = self.project.as_ref() {
2121 project.update(cx, |project, cx| {
2122 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2123 return;
2124 };
2125 self.registered_buffers.insert(
2126 buffer_id,
2127 project.register_buffer_with_language_servers(&buffer, cx),
2128 );
2129 })
2130 }
2131 }
2132 }
2133
2134 if let Some(completion_menu) = completion_menu {
2135 let cursor_position = new_cursor_position.to_offset(buffer);
2136 let (word_range, kind) =
2137 buffer.surrounding_word(completion_menu.initial_position, true);
2138 if kind == Some(CharKind::Word)
2139 && word_range.to_inclusive().contains(&cursor_position)
2140 {
2141 let mut completion_menu = completion_menu.clone();
2142 drop(context_menu);
2143
2144 let query = Self::completion_query(buffer, cursor_position);
2145 cx.spawn(move |this, mut cx| async move {
2146 completion_menu
2147 .filter(query.as_deref(), cx.background_executor().clone())
2148 .await;
2149
2150 this.update(&mut cx, |this, cx| {
2151 let mut context_menu = this.context_menu.borrow_mut();
2152 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2153 else {
2154 return;
2155 };
2156
2157 if menu.id > completion_menu.id {
2158 return;
2159 }
2160
2161 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2162 drop(context_menu);
2163 cx.notify();
2164 })
2165 })
2166 .detach();
2167
2168 if show_completions {
2169 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2170 }
2171 } else {
2172 drop(context_menu);
2173 self.hide_context_menu(window, cx);
2174 }
2175 } else {
2176 drop(context_menu);
2177 }
2178
2179 hide_hover(self, cx);
2180
2181 if old_cursor_position.to_display_point(&display_map).row()
2182 != new_cursor_position.to_display_point(&display_map).row()
2183 {
2184 self.available_code_actions.take();
2185 }
2186 self.refresh_code_actions(window, cx);
2187 self.refresh_document_highlights(cx);
2188 self.refresh_selected_text_highlights(window, cx);
2189 refresh_matching_bracket_highlights(self, window, cx);
2190 self.update_visible_inline_completion(window, cx);
2191 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2192 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2193 if self.git_blame_inline_enabled {
2194 self.start_inline_blame_timer(window, cx);
2195 }
2196 }
2197
2198 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2199 cx.emit(EditorEvent::SelectionsChanged { local });
2200
2201 let selections = &self.selections.disjoint;
2202 if selections.len() == 1 {
2203 cx.emit(SearchEvent::ActiveMatchChanged)
2204 }
2205 if local
2206 && self.is_singleton(cx)
2207 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2208 {
2209 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2210 let background_executor = cx.background_executor().clone();
2211 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2212 let snapshot = self.buffer().read(cx).snapshot(cx);
2213 let selections = selections.clone();
2214 self.serialize_selections = cx.background_spawn(async move {
2215 background_executor.timer(Duration::from_millis(100)).await;
2216 let selections = selections
2217 .iter()
2218 .map(|selection| {
2219 (
2220 selection.start.to_offset(&snapshot),
2221 selection.end.to_offset(&snapshot),
2222 )
2223 })
2224 .collect();
2225 DB.save_editor_selections(editor_id, workspace_id, selections)
2226 .await
2227 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2228 .log_err();
2229 });
2230 }
2231 }
2232
2233 cx.notify();
2234 }
2235
2236 pub fn change_selections<R>(
2237 &mut self,
2238 autoscroll: Option<Autoscroll>,
2239 window: &mut Window,
2240 cx: &mut Context<Self>,
2241 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2242 ) -> R {
2243 self.change_selections_inner(autoscroll, true, window, cx, change)
2244 }
2245
2246 fn change_selections_inner<R>(
2247 &mut self,
2248 autoscroll: Option<Autoscroll>,
2249 request_completions: bool,
2250 window: &mut Window,
2251 cx: &mut Context<Self>,
2252 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2253 ) -> R {
2254 let old_cursor_position = self.selections.newest_anchor().head();
2255 self.push_to_selection_history();
2256
2257 let (changed, result) = self.selections.change_with(cx, change);
2258
2259 if changed {
2260 if let Some(autoscroll) = autoscroll {
2261 self.request_autoscroll(autoscroll, cx);
2262 }
2263 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2264
2265 if self.should_open_signature_help_automatically(
2266 &old_cursor_position,
2267 self.signature_help_state.backspace_pressed(),
2268 cx,
2269 ) {
2270 self.show_signature_help(&ShowSignatureHelp, window, cx);
2271 }
2272 self.signature_help_state.set_backspace_pressed(false);
2273 }
2274
2275 result
2276 }
2277
2278 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2279 where
2280 I: IntoIterator<Item = (Range<S>, T)>,
2281 S: ToOffset,
2282 T: Into<Arc<str>>,
2283 {
2284 if self.read_only(cx) {
2285 return;
2286 }
2287
2288 self.buffer
2289 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2290 }
2291
2292 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2293 where
2294 I: IntoIterator<Item = (Range<S>, T)>,
2295 S: ToOffset,
2296 T: Into<Arc<str>>,
2297 {
2298 if self.read_only(cx) {
2299 return;
2300 }
2301
2302 self.buffer.update(cx, |buffer, cx| {
2303 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2304 });
2305 }
2306
2307 pub fn edit_with_block_indent<I, S, T>(
2308 &mut self,
2309 edits: I,
2310 original_start_columns: Vec<u32>,
2311 cx: &mut Context<Self>,
2312 ) where
2313 I: IntoIterator<Item = (Range<S>, T)>,
2314 S: ToOffset,
2315 T: Into<Arc<str>>,
2316 {
2317 if self.read_only(cx) {
2318 return;
2319 }
2320
2321 self.buffer.update(cx, |buffer, cx| {
2322 buffer.edit(
2323 edits,
2324 Some(AutoindentMode::Block {
2325 original_start_columns,
2326 }),
2327 cx,
2328 )
2329 });
2330 }
2331
2332 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2333 self.hide_context_menu(window, cx);
2334
2335 match phase {
2336 SelectPhase::Begin {
2337 position,
2338 add,
2339 click_count,
2340 } => self.begin_selection(position, add, click_count, window, cx),
2341 SelectPhase::BeginColumnar {
2342 position,
2343 goal_column,
2344 reset,
2345 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2346 SelectPhase::Extend {
2347 position,
2348 click_count,
2349 } => self.extend_selection(position, click_count, window, cx),
2350 SelectPhase::Update {
2351 position,
2352 goal_column,
2353 scroll_delta,
2354 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2355 SelectPhase::End => self.end_selection(window, cx),
2356 }
2357 }
2358
2359 fn extend_selection(
2360 &mut self,
2361 position: DisplayPoint,
2362 click_count: usize,
2363 window: &mut Window,
2364 cx: &mut Context<Self>,
2365 ) {
2366 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2367 let tail = self.selections.newest::<usize>(cx).tail();
2368 self.begin_selection(position, false, click_count, window, cx);
2369
2370 let position = position.to_offset(&display_map, Bias::Left);
2371 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2372
2373 let mut pending_selection = self
2374 .selections
2375 .pending_anchor()
2376 .expect("extend_selection not called with pending selection");
2377 if position >= tail {
2378 pending_selection.start = tail_anchor;
2379 } else {
2380 pending_selection.end = tail_anchor;
2381 pending_selection.reversed = true;
2382 }
2383
2384 let mut pending_mode = self.selections.pending_mode().unwrap();
2385 match &mut pending_mode {
2386 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2387 _ => {}
2388 }
2389
2390 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2391 s.set_pending(pending_selection, pending_mode)
2392 });
2393 }
2394
2395 fn begin_selection(
2396 &mut self,
2397 position: DisplayPoint,
2398 add: bool,
2399 click_count: usize,
2400 window: &mut Window,
2401 cx: &mut Context<Self>,
2402 ) {
2403 if !self.focus_handle.is_focused(window) {
2404 self.last_focused_descendant = None;
2405 window.focus(&self.focus_handle);
2406 }
2407
2408 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2409 let buffer = &display_map.buffer_snapshot;
2410 let newest_selection = self.selections.newest_anchor().clone();
2411 let position = display_map.clip_point(position, Bias::Left);
2412
2413 let start;
2414 let end;
2415 let mode;
2416 let mut auto_scroll;
2417 match click_count {
2418 1 => {
2419 start = buffer.anchor_before(position.to_point(&display_map));
2420 end = start;
2421 mode = SelectMode::Character;
2422 auto_scroll = true;
2423 }
2424 2 => {
2425 let range = movement::surrounding_word(&display_map, position);
2426 start = buffer.anchor_before(range.start.to_point(&display_map));
2427 end = buffer.anchor_before(range.end.to_point(&display_map));
2428 mode = SelectMode::Word(start..end);
2429 auto_scroll = true;
2430 }
2431 3 => {
2432 let position = display_map
2433 .clip_point(position, Bias::Left)
2434 .to_point(&display_map);
2435 let line_start = display_map.prev_line_boundary(position).0;
2436 let next_line_start = buffer.clip_point(
2437 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2438 Bias::Left,
2439 );
2440 start = buffer.anchor_before(line_start);
2441 end = buffer.anchor_before(next_line_start);
2442 mode = SelectMode::Line(start..end);
2443 auto_scroll = true;
2444 }
2445 _ => {
2446 start = buffer.anchor_before(0);
2447 end = buffer.anchor_before(buffer.len());
2448 mode = SelectMode::All;
2449 auto_scroll = false;
2450 }
2451 }
2452 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2453
2454 let point_to_delete: Option<usize> = {
2455 let selected_points: Vec<Selection<Point>> =
2456 self.selections.disjoint_in_range(start..end, cx);
2457
2458 if !add || click_count > 1 {
2459 None
2460 } else if !selected_points.is_empty() {
2461 Some(selected_points[0].id)
2462 } else {
2463 let clicked_point_already_selected =
2464 self.selections.disjoint.iter().find(|selection| {
2465 selection.start.to_point(buffer) == start.to_point(buffer)
2466 || selection.end.to_point(buffer) == end.to_point(buffer)
2467 });
2468
2469 clicked_point_already_selected.map(|selection| selection.id)
2470 }
2471 };
2472
2473 let selections_count = self.selections.count();
2474
2475 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2476 if let Some(point_to_delete) = point_to_delete {
2477 s.delete(point_to_delete);
2478
2479 if selections_count == 1 {
2480 s.set_pending_anchor_range(start..end, mode);
2481 }
2482 } else {
2483 if !add {
2484 s.clear_disjoint();
2485 } else if click_count > 1 {
2486 s.delete(newest_selection.id)
2487 }
2488
2489 s.set_pending_anchor_range(start..end, mode);
2490 }
2491 });
2492 }
2493
2494 fn begin_columnar_selection(
2495 &mut self,
2496 position: DisplayPoint,
2497 goal_column: u32,
2498 reset: bool,
2499 window: &mut Window,
2500 cx: &mut Context<Self>,
2501 ) {
2502 if !self.focus_handle.is_focused(window) {
2503 self.last_focused_descendant = None;
2504 window.focus(&self.focus_handle);
2505 }
2506
2507 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2508
2509 if reset {
2510 let pointer_position = display_map
2511 .buffer_snapshot
2512 .anchor_before(position.to_point(&display_map));
2513
2514 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2515 s.clear_disjoint();
2516 s.set_pending_anchor_range(
2517 pointer_position..pointer_position,
2518 SelectMode::Character,
2519 );
2520 });
2521 }
2522
2523 let tail = self.selections.newest::<Point>(cx).tail();
2524 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2525
2526 if !reset {
2527 self.select_columns(
2528 tail.to_display_point(&display_map),
2529 position,
2530 goal_column,
2531 &display_map,
2532 window,
2533 cx,
2534 );
2535 }
2536 }
2537
2538 fn update_selection(
2539 &mut self,
2540 position: DisplayPoint,
2541 goal_column: u32,
2542 scroll_delta: gpui::Point<f32>,
2543 window: &mut Window,
2544 cx: &mut Context<Self>,
2545 ) {
2546 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2547
2548 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2549 let tail = tail.to_display_point(&display_map);
2550 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2551 } else if let Some(mut pending) = self.selections.pending_anchor() {
2552 let buffer = self.buffer.read(cx).snapshot(cx);
2553 let head;
2554 let tail;
2555 let mode = self.selections.pending_mode().unwrap();
2556 match &mode {
2557 SelectMode::Character => {
2558 head = position.to_point(&display_map);
2559 tail = pending.tail().to_point(&buffer);
2560 }
2561 SelectMode::Word(original_range) => {
2562 let original_display_range = original_range.start.to_display_point(&display_map)
2563 ..original_range.end.to_display_point(&display_map);
2564 let original_buffer_range = original_display_range.start.to_point(&display_map)
2565 ..original_display_range.end.to_point(&display_map);
2566 if movement::is_inside_word(&display_map, position)
2567 || original_display_range.contains(&position)
2568 {
2569 let word_range = movement::surrounding_word(&display_map, position);
2570 if word_range.start < original_display_range.start {
2571 head = word_range.start.to_point(&display_map);
2572 } else {
2573 head = word_range.end.to_point(&display_map);
2574 }
2575 } else {
2576 head = position.to_point(&display_map);
2577 }
2578
2579 if head <= original_buffer_range.start {
2580 tail = original_buffer_range.end;
2581 } else {
2582 tail = original_buffer_range.start;
2583 }
2584 }
2585 SelectMode::Line(original_range) => {
2586 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2587
2588 let position = display_map
2589 .clip_point(position, Bias::Left)
2590 .to_point(&display_map);
2591 let line_start = display_map.prev_line_boundary(position).0;
2592 let next_line_start = buffer.clip_point(
2593 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2594 Bias::Left,
2595 );
2596
2597 if line_start < original_range.start {
2598 head = line_start
2599 } else {
2600 head = next_line_start
2601 }
2602
2603 if head <= original_range.start {
2604 tail = original_range.end;
2605 } else {
2606 tail = original_range.start;
2607 }
2608 }
2609 SelectMode::All => {
2610 return;
2611 }
2612 };
2613
2614 if head < tail {
2615 pending.start = buffer.anchor_before(head);
2616 pending.end = buffer.anchor_before(tail);
2617 pending.reversed = true;
2618 } else {
2619 pending.start = buffer.anchor_before(tail);
2620 pending.end = buffer.anchor_before(head);
2621 pending.reversed = false;
2622 }
2623
2624 self.change_selections(None, window, cx, |s| {
2625 s.set_pending(pending, mode);
2626 });
2627 } else {
2628 log::error!("update_selection dispatched with no pending selection");
2629 return;
2630 }
2631
2632 self.apply_scroll_delta(scroll_delta, window, cx);
2633 cx.notify();
2634 }
2635
2636 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2637 self.columnar_selection_tail.take();
2638 if self.selections.pending_anchor().is_some() {
2639 let selections = self.selections.all::<usize>(cx);
2640 self.change_selections(None, window, cx, |s| {
2641 s.select(selections);
2642 s.clear_pending();
2643 });
2644 }
2645 }
2646
2647 fn select_columns(
2648 &mut self,
2649 tail: DisplayPoint,
2650 head: DisplayPoint,
2651 goal_column: u32,
2652 display_map: &DisplaySnapshot,
2653 window: &mut Window,
2654 cx: &mut Context<Self>,
2655 ) {
2656 let start_row = cmp::min(tail.row(), head.row());
2657 let end_row = cmp::max(tail.row(), head.row());
2658 let start_column = cmp::min(tail.column(), goal_column);
2659 let end_column = cmp::max(tail.column(), goal_column);
2660 let reversed = start_column < tail.column();
2661
2662 let selection_ranges = (start_row.0..=end_row.0)
2663 .map(DisplayRow)
2664 .filter_map(|row| {
2665 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2666 let start = display_map
2667 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2668 .to_point(display_map);
2669 let end = display_map
2670 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2671 .to_point(display_map);
2672 if reversed {
2673 Some(end..start)
2674 } else {
2675 Some(start..end)
2676 }
2677 } else {
2678 None
2679 }
2680 })
2681 .collect::<Vec<_>>();
2682
2683 self.change_selections(None, window, cx, |s| {
2684 s.select_ranges(selection_ranges);
2685 });
2686 cx.notify();
2687 }
2688
2689 pub fn has_pending_nonempty_selection(&self) -> bool {
2690 let pending_nonempty_selection = match self.selections.pending_anchor() {
2691 Some(Selection { start, end, .. }) => start != end,
2692 None => false,
2693 };
2694
2695 pending_nonempty_selection
2696 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2697 }
2698
2699 pub fn has_pending_selection(&self) -> bool {
2700 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2701 }
2702
2703 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2704 self.selection_mark_mode = false;
2705
2706 if self.clear_expanded_diff_hunks(cx) {
2707 cx.notify();
2708 return;
2709 }
2710 if self.dismiss_menus_and_popups(true, window, cx) {
2711 return;
2712 }
2713
2714 if self.mode == EditorMode::Full
2715 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2716 {
2717 return;
2718 }
2719
2720 cx.propagate();
2721 }
2722
2723 pub fn dismiss_menus_and_popups(
2724 &mut self,
2725 is_user_requested: bool,
2726 window: &mut Window,
2727 cx: &mut Context<Self>,
2728 ) -> bool {
2729 if self.take_rename(false, window, cx).is_some() {
2730 return true;
2731 }
2732
2733 if hide_hover(self, cx) {
2734 return true;
2735 }
2736
2737 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2738 return true;
2739 }
2740
2741 if self.hide_context_menu(window, cx).is_some() {
2742 return true;
2743 }
2744
2745 if self.mouse_context_menu.take().is_some() {
2746 return true;
2747 }
2748
2749 if is_user_requested && self.discard_inline_completion(true, cx) {
2750 return true;
2751 }
2752
2753 if self.snippet_stack.pop().is_some() {
2754 return true;
2755 }
2756
2757 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2758 self.dismiss_diagnostics(cx);
2759 return true;
2760 }
2761
2762 false
2763 }
2764
2765 fn linked_editing_ranges_for(
2766 &self,
2767 selection: Range<text::Anchor>,
2768 cx: &App,
2769 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2770 if self.linked_edit_ranges.is_empty() {
2771 return None;
2772 }
2773 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2774 selection.end.buffer_id.and_then(|end_buffer_id| {
2775 if selection.start.buffer_id != Some(end_buffer_id) {
2776 return None;
2777 }
2778 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2779 let snapshot = buffer.read(cx).snapshot();
2780 self.linked_edit_ranges
2781 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2782 .map(|ranges| (ranges, snapshot, buffer))
2783 })?;
2784 use text::ToOffset as TO;
2785 // find offset from the start of current range to current cursor position
2786 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2787
2788 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2789 let start_difference = start_offset - start_byte_offset;
2790 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2791 let end_difference = end_offset - start_byte_offset;
2792 // Current range has associated linked ranges.
2793 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2794 for range in linked_ranges.iter() {
2795 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2796 let end_offset = start_offset + end_difference;
2797 let start_offset = start_offset + start_difference;
2798 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2799 continue;
2800 }
2801 if self.selections.disjoint_anchor_ranges().any(|s| {
2802 if s.start.buffer_id != selection.start.buffer_id
2803 || s.end.buffer_id != selection.end.buffer_id
2804 {
2805 return false;
2806 }
2807 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2808 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2809 }) {
2810 continue;
2811 }
2812 let start = buffer_snapshot.anchor_after(start_offset);
2813 let end = buffer_snapshot.anchor_after(end_offset);
2814 linked_edits
2815 .entry(buffer.clone())
2816 .or_default()
2817 .push(start..end);
2818 }
2819 Some(linked_edits)
2820 }
2821
2822 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2823 let text: Arc<str> = text.into();
2824
2825 if self.read_only(cx) {
2826 return;
2827 }
2828
2829 let selections = self.selections.all_adjusted(cx);
2830 let mut bracket_inserted = false;
2831 let mut edits = Vec::new();
2832 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2833 let mut new_selections = Vec::with_capacity(selections.len());
2834 let mut new_autoclose_regions = Vec::new();
2835 let snapshot = self.buffer.read(cx).read(cx);
2836
2837 for (selection, autoclose_region) in
2838 self.selections_with_autoclose_regions(selections, &snapshot)
2839 {
2840 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2841 // Determine if the inserted text matches the opening or closing
2842 // bracket of any of this language's bracket pairs.
2843 let mut bracket_pair = None;
2844 let mut is_bracket_pair_start = false;
2845 let mut is_bracket_pair_end = false;
2846 if !text.is_empty() {
2847 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2848 // and they are removing the character that triggered IME popup.
2849 for (pair, enabled) in scope.brackets() {
2850 if !pair.close && !pair.surround {
2851 continue;
2852 }
2853
2854 if enabled && pair.start.ends_with(text.as_ref()) {
2855 let prefix_len = pair.start.len() - text.len();
2856 let preceding_text_matches_prefix = prefix_len == 0
2857 || (selection.start.column >= (prefix_len as u32)
2858 && snapshot.contains_str_at(
2859 Point::new(
2860 selection.start.row,
2861 selection.start.column - (prefix_len as u32),
2862 ),
2863 &pair.start[..prefix_len],
2864 ));
2865 if preceding_text_matches_prefix {
2866 bracket_pair = Some(pair.clone());
2867 is_bracket_pair_start = true;
2868 break;
2869 }
2870 }
2871 if pair.end.as_str() == text.as_ref() {
2872 bracket_pair = Some(pair.clone());
2873 is_bracket_pair_end = true;
2874 break;
2875 }
2876 }
2877 }
2878
2879 if let Some(bracket_pair) = bracket_pair {
2880 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2881 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2882 let auto_surround =
2883 self.use_auto_surround && snapshot_settings.use_auto_surround;
2884 if selection.is_empty() {
2885 if is_bracket_pair_start {
2886 // If the inserted text is a suffix of an opening bracket and the
2887 // selection is preceded by the rest of the opening bracket, then
2888 // insert the closing bracket.
2889 let following_text_allows_autoclose = snapshot
2890 .chars_at(selection.start)
2891 .next()
2892 .map_or(true, |c| scope.should_autoclose_before(c));
2893
2894 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2895 && bracket_pair.start.len() == 1
2896 {
2897 let target = bracket_pair.start.chars().next().unwrap();
2898 let current_line_count = snapshot
2899 .reversed_chars_at(selection.start)
2900 .take_while(|&c| c != '\n')
2901 .filter(|&c| c == target)
2902 .count();
2903 current_line_count % 2 == 1
2904 } else {
2905 false
2906 };
2907
2908 if autoclose
2909 && bracket_pair.close
2910 && following_text_allows_autoclose
2911 && !is_closing_quote
2912 {
2913 let anchor = snapshot.anchor_before(selection.end);
2914 new_selections.push((selection.map(|_| anchor), text.len()));
2915 new_autoclose_regions.push((
2916 anchor,
2917 text.len(),
2918 selection.id,
2919 bracket_pair.clone(),
2920 ));
2921 edits.push((
2922 selection.range(),
2923 format!("{}{}", text, bracket_pair.end).into(),
2924 ));
2925 bracket_inserted = true;
2926 continue;
2927 }
2928 }
2929
2930 if let Some(region) = autoclose_region {
2931 // If the selection is followed by an auto-inserted closing bracket,
2932 // then don't insert that closing bracket again; just move the selection
2933 // past the closing bracket.
2934 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2935 && text.as_ref() == region.pair.end.as_str();
2936 if should_skip {
2937 let anchor = snapshot.anchor_after(selection.end);
2938 new_selections
2939 .push((selection.map(|_| anchor), region.pair.end.len()));
2940 continue;
2941 }
2942 }
2943
2944 let always_treat_brackets_as_autoclosed = snapshot
2945 .settings_at(selection.start, cx)
2946 .always_treat_brackets_as_autoclosed;
2947 if always_treat_brackets_as_autoclosed
2948 && is_bracket_pair_end
2949 && snapshot.contains_str_at(selection.end, text.as_ref())
2950 {
2951 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2952 // and the inserted text is a closing bracket and the selection is followed
2953 // by the closing bracket then move the selection past the closing bracket.
2954 let anchor = snapshot.anchor_after(selection.end);
2955 new_selections.push((selection.map(|_| anchor), text.len()));
2956 continue;
2957 }
2958 }
2959 // If an opening bracket is 1 character long and is typed while
2960 // text is selected, then surround that text with the bracket pair.
2961 else if auto_surround
2962 && bracket_pair.surround
2963 && is_bracket_pair_start
2964 && bracket_pair.start.chars().count() == 1
2965 {
2966 edits.push((selection.start..selection.start, text.clone()));
2967 edits.push((
2968 selection.end..selection.end,
2969 bracket_pair.end.as_str().into(),
2970 ));
2971 bracket_inserted = true;
2972 new_selections.push((
2973 Selection {
2974 id: selection.id,
2975 start: snapshot.anchor_after(selection.start),
2976 end: snapshot.anchor_before(selection.end),
2977 reversed: selection.reversed,
2978 goal: selection.goal,
2979 },
2980 0,
2981 ));
2982 continue;
2983 }
2984 }
2985 }
2986
2987 if self.auto_replace_emoji_shortcode
2988 && selection.is_empty()
2989 && text.as_ref().ends_with(':')
2990 {
2991 if let Some(possible_emoji_short_code) =
2992 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2993 {
2994 if !possible_emoji_short_code.is_empty() {
2995 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2996 let emoji_shortcode_start = Point::new(
2997 selection.start.row,
2998 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2999 );
3000
3001 // Remove shortcode from buffer
3002 edits.push((
3003 emoji_shortcode_start..selection.start,
3004 "".to_string().into(),
3005 ));
3006 new_selections.push((
3007 Selection {
3008 id: selection.id,
3009 start: snapshot.anchor_after(emoji_shortcode_start),
3010 end: snapshot.anchor_before(selection.start),
3011 reversed: selection.reversed,
3012 goal: selection.goal,
3013 },
3014 0,
3015 ));
3016
3017 // Insert emoji
3018 let selection_start_anchor = snapshot.anchor_after(selection.start);
3019 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3020 edits.push((selection.start..selection.end, emoji.to_string().into()));
3021
3022 continue;
3023 }
3024 }
3025 }
3026 }
3027
3028 // If not handling any auto-close operation, then just replace the selected
3029 // text with the given input and move the selection to the end of the
3030 // newly inserted text.
3031 let anchor = snapshot.anchor_after(selection.end);
3032 if !self.linked_edit_ranges.is_empty() {
3033 let start_anchor = snapshot.anchor_before(selection.start);
3034
3035 let is_word_char = text.chars().next().map_or(true, |char| {
3036 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3037 classifier.is_word(char)
3038 });
3039
3040 if is_word_char {
3041 if let Some(ranges) = self
3042 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3043 {
3044 for (buffer, edits) in ranges {
3045 linked_edits
3046 .entry(buffer.clone())
3047 .or_default()
3048 .extend(edits.into_iter().map(|range| (range, text.clone())));
3049 }
3050 }
3051 }
3052 }
3053
3054 new_selections.push((selection.map(|_| anchor), 0));
3055 edits.push((selection.start..selection.end, text.clone()));
3056 }
3057
3058 drop(snapshot);
3059
3060 self.transact(window, cx, |this, window, cx| {
3061 this.buffer.update(cx, |buffer, cx| {
3062 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3063 });
3064 for (buffer, edits) in linked_edits {
3065 buffer.update(cx, |buffer, cx| {
3066 let snapshot = buffer.snapshot();
3067 let edits = edits
3068 .into_iter()
3069 .map(|(range, text)| {
3070 use text::ToPoint as TP;
3071 let end_point = TP::to_point(&range.end, &snapshot);
3072 let start_point = TP::to_point(&range.start, &snapshot);
3073 (start_point..end_point, text)
3074 })
3075 .sorted_by_key(|(range, _)| range.start)
3076 .collect::<Vec<_>>();
3077 buffer.edit(edits, None, cx);
3078 })
3079 }
3080 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3081 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3082 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3083 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3084 .zip(new_selection_deltas)
3085 .map(|(selection, delta)| Selection {
3086 id: selection.id,
3087 start: selection.start + delta,
3088 end: selection.end + delta,
3089 reversed: selection.reversed,
3090 goal: SelectionGoal::None,
3091 })
3092 .collect::<Vec<_>>();
3093
3094 let mut i = 0;
3095 for (position, delta, selection_id, pair) in new_autoclose_regions {
3096 let position = position.to_offset(&map.buffer_snapshot) + delta;
3097 let start = map.buffer_snapshot.anchor_before(position);
3098 let end = map.buffer_snapshot.anchor_after(position);
3099 while let Some(existing_state) = this.autoclose_regions.get(i) {
3100 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3101 Ordering::Less => i += 1,
3102 Ordering::Greater => break,
3103 Ordering::Equal => {
3104 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3105 Ordering::Less => i += 1,
3106 Ordering::Equal => break,
3107 Ordering::Greater => break,
3108 }
3109 }
3110 }
3111 }
3112 this.autoclose_regions.insert(
3113 i,
3114 AutocloseRegion {
3115 selection_id,
3116 range: start..end,
3117 pair,
3118 },
3119 );
3120 }
3121
3122 let had_active_inline_completion = this.has_active_inline_completion();
3123 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3124 s.select(new_selections)
3125 });
3126
3127 if !bracket_inserted {
3128 if let Some(on_type_format_task) =
3129 this.trigger_on_type_formatting(text.to_string(), window, cx)
3130 {
3131 on_type_format_task.detach_and_log_err(cx);
3132 }
3133 }
3134
3135 let editor_settings = EditorSettings::get_global(cx);
3136 if bracket_inserted
3137 && (editor_settings.auto_signature_help
3138 || editor_settings.show_signature_help_after_edits)
3139 {
3140 this.show_signature_help(&ShowSignatureHelp, window, cx);
3141 }
3142
3143 let trigger_in_words =
3144 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3145 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3146 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3147 this.refresh_inline_completion(true, false, window, cx);
3148 });
3149 }
3150
3151 fn find_possible_emoji_shortcode_at_position(
3152 snapshot: &MultiBufferSnapshot,
3153 position: Point,
3154 ) -> Option<String> {
3155 let mut chars = Vec::new();
3156 let mut found_colon = false;
3157 for char in snapshot.reversed_chars_at(position).take(100) {
3158 // Found a possible emoji shortcode in the middle of the buffer
3159 if found_colon {
3160 if char.is_whitespace() {
3161 chars.reverse();
3162 return Some(chars.iter().collect());
3163 }
3164 // If the previous character is not a whitespace, we are in the middle of a word
3165 // and we only want to complete the shortcode if the word is made up of other emojis
3166 let mut containing_word = String::new();
3167 for ch in snapshot
3168 .reversed_chars_at(position)
3169 .skip(chars.len() + 1)
3170 .take(100)
3171 {
3172 if ch.is_whitespace() {
3173 break;
3174 }
3175 containing_word.push(ch);
3176 }
3177 let containing_word = containing_word.chars().rev().collect::<String>();
3178 if util::word_consists_of_emojis(containing_word.as_str()) {
3179 chars.reverse();
3180 return Some(chars.iter().collect());
3181 }
3182 }
3183
3184 if char.is_whitespace() || !char.is_ascii() {
3185 return None;
3186 }
3187 if char == ':' {
3188 found_colon = true;
3189 } else {
3190 chars.push(char);
3191 }
3192 }
3193 // Found a possible emoji shortcode at the beginning of the buffer
3194 chars.reverse();
3195 Some(chars.iter().collect())
3196 }
3197
3198 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3199 self.transact(window, cx, |this, window, cx| {
3200 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3201 let selections = this.selections.all::<usize>(cx);
3202 let multi_buffer = this.buffer.read(cx);
3203 let buffer = multi_buffer.snapshot(cx);
3204 selections
3205 .iter()
3206 .map(|selection| {
3207 let start_point = selection.start.to_point(&buffer);
3208 let mut indent =
3209 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3210 indent.len = cmp::min(indent.len, start_point.column);
3211 let start = selection.start;
3212 let end = selection.end;
3213 let selection_is_empty = start == end;
3214 let language_scope = buffer.language_scope_at(start);
3215 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3216 &language_scope
3217 {
3218 let insert_extra_newline =
3219 insert_extra_newline_brackets(&buffer, start..end, language)
3220 || insert_extra_newline_tree_sitter(&buffer, start..end);
3221
3222 // Comment extension on newline is allowed only for cursor selections
3223 let comment_delimiter = maybe!({
3224 if !selection_is_empty {
3225 return None;
3226 }
3227
3228 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3229 return None;
3230 }
3231
3232 let delimiters = language.line_comment_prefixes();
3233 let max_len_of_delimiter =
3234 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3235 let (snapshot, range) =
3236 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3237
3238 let mut index_of_first_non_whitespace = 0;
3239 let comment_candidate = snapshot
3240 .chars_for_range(range)
3241 .skip_while(|c| {
3242 let should_skip = c.is_whitespace();
3243 if should_skip {
3244 index_of_first_non_whitespace += 1;
3245 }
3246 should_skip
3247 })
3248 .take(max_len_of_delimiter)
3249 .collect::<String>();
3250 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3251 comment_candidate.starts_with(comment_prefix.as_ref())
3252 })?;
3253 let cursor_is_placed_after_comment_marker =
3254 index_of_first_non_whitespace + comment_prefix.len()
3255 <= start_point.column as usize;
3256 if cursor_is_placed_after_comment_marker {
3257 Some(comment_prefix.clone())
3258 } else {
3259 None
3260 }
3261 });
3262 (comment_delimiter, insert_extra_newline)
3263 } else {
3264 (None, false)
3265 };
3266
3267 let capacity_for_delimiter = comment_delimiter
3268 .as_deref()
3269 .map(str::len)
3270 .unwrap_or_default();
3271 let mut new_text =
3272 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3273 new_text.push('\n');
3274 new_text.extend(indent.chars());
3275 if let Some(delimiter) = &comment_delimiter {
3276 new_text.push_str(delimiter);
3277 }
3278 if insert_extra_newline {
3279 new_text = new_text.repeat(2);
3280 }
3281
3282 let anchor = buffer.anchor_after(end);
3283 let new_selection = selection.map(|_| anchor);
3284 (
3285 (start..end, new_text),
3286 (insert_extra_newline, new_selection),
3287 )
3288 })
3289 .unzip()
3290 };
3291
3292 this.edit_with_autoindent(edits, cx);
3293 let buffer = this.buffer.read(cx).snapshot(cx);
3294 let new_selections = selection_fixup_info
3295 .into_iter()
3296 .map(|(extra_newline_inserted, new_selection)| {
3297 let mut cursor = new_selection.end.to_point(&buffer);
3298 if extra_newline_inserted {
3299 cursor.row -= 1;
3300 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3301 }
3302 new_selection.map(|_| cursor)
3303 })
3304 .collect();
3305
3306 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3307 s.select(new_selections)
3308 });
3309 this.refresh_inline_completion(true, false, window, cx);
3310 });
3311 }
3312
3313 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3314 let buffer = self.buffer.read(cx);
3315 let snapshot = buffer.snapshot(cx);
3316
3317 let mut edits = Vec::new();
3318 let mut rows = Vec::new();
3319
3320 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3321 let cursor = selection.head();
3322 let row = cursor.row;
3323
3324 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3325
3326 let newline = "\n".to_string();
3327 edits.push((start_of_line..start_of_line, newline));
3328
3329 rows.push(row + rows_inserted as u32);
3330 }
3331
3332 self.transact(window, cx, |editor, window, cx| {
3333 editor.edit(edits, cx);
3334
3335 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3336 let mut index = 0;
3337 s.move_cursors_with(|map, _, _| {
3338 let row = rows[index];
3339 index += 1;
3340
3341 let point = Point::new(row, 0);
3342 let boundary = map.next_line_boundary(point).1;
3343 let clipped = map.clip_point(boundary, Bias::Left);
3344
3345 (clipped, SelectionGoal::None)
3346 });
3347 });
3348
3349 let mut indent_edits = Vec::new();
3350 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3351 for row in rows {
3352 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3353 for (row, indent) in indents {
3354 if indent.len == 0 {
3355 continue;
3356 }
3357
3358 let text = match indent.kind {
3359 IndentKind::Space => " ".repeat(indent.len as usize),
3360 IndentKind::Tab => "\t".repeat(indent.len as usize),
3361 };
3362 let point = Point::new(row.0, 0);
3363 indent_edits.push((point..point, text));
3364 }
3365 }
3366 editor.edit(indent_edits, cx);
3367 });
3368 }
3369
3370 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3371 let buffer = self.buffer.read(cx);
3372 let snapshot = buffer.snapshot(cx);
3373
3374 let mut edits = Vec::new();
3375 let mut rows = Vec::new();
3376 let mut rows_inserted = 0;
3377
3378 for selection in self.selections.all_adjusted(cx) {
3379 let cursor = selection.head();
3380 let row = cursor.row;
3381
3382 let point = Point::new(row + 1, 0);
3383 let start_of_line = snapshot.clip_point(point, Bias::Left);
3384
3385 let newline = "\n".to_string();
3386 edits.push((start_of_line..start_of_line, newline));
3387
3388 rows_inserted += 1;
3389 rows.push(row + rows_inserted);
3390 }
3391
3392 self.transact(window, cx, |editor, window, cx| {
3393 editor.edit(edits, cx);
3394
3395 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3396 let mut index = 0;
3397 s.move_cursors_with(|map, _, _| {
3398 let row = rows[index];
3399 index += 1;
3400
3401 let point = Point::new(row, 0);
3402 let boundary = map.next_line_boundary(point).1;
3403 let clipped = map.clip_point(boundary, Bias::Left);
3404
3405 (clipped, SelectionGoal::None)
3406 });
3407 });
3408
3409 let mut indent_edits = Vec::new();
3410 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3411 for row in rows {
3412 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3413 for (row, indent) in indents {
3414 if indent.len == 0 {
3415 continue;
3416 }
3417
3418 let text = match indent.kind {
3419 IndentKind::Space => " ".repeat(indent.len as usize),
3420 IndentKind::Tab => "\t".repeat(indent.len as usize),
3421 };
3422 let point = Point::new(row.0, 0);
3423 indent_edits.push((point..point, text));
3424 }
3425 }
3426 editor.edit(indent_edits, cx);
3427 });
3428 }
3429
3430 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3431 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3432 original_start_columns: Vec::new(),
3433 });
3434 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3435 }
3436
3437 fn insert_with_autoindent_mode(
3438 &mut self,
3439 text: &str,
3440 autoindent_mode: Option<AutoindentMode>,
3441 window: &mut Window,
3442 cx: &mut Context<Self>,
3443 ) {
3444 if self.read_only(cx) {
3445 return;
3446 }
3447
3448 let text: Arc<str> = text.into();
3449 self.transact(window, cx, |this, window, cx| {
3450 let old_selections = this.selections.all_adjusted(cx);
3451 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3452 let anchors = {
3453 let snapshot = buffer.read(cx);
3454 old_selections
3455 .iter()
3456 .map(|s| {
3457 let anchor = snapshot.anchor_after(s.head());
3458 s.map(|_| anchor)
3459 })
3460 .collect::<Vec<_>>()
3461 };
3462 buffer.edit(
3463 old_selections
3464 .iter()
3465 .map(|s| (s.start..s.end, text.clone())),
3466 autoindent_mode,
3467 cx,
3468 );
3469 anchors
3470 });
3471
3472 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3473 s.select_anchors(selection_anchors);
3474 });
3475
3476 cx.notify();
3477 });
3478 }
3479
3480 fn trigger_completion_on_input(
3481 &mut self,
3482 text: &str,
3483 trigger_in_words: bool,
3484 window: &mut Window,
3485 cx: &mut Context<Self>,
3486 ) {
3487 if self.is_completion_trigger(text, trigger_in_words, cx) {
3488 self.show_completions(
3489 &ShowCompletions {
3490 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3491 },
3492 window,
3493 cx,
3494 );
3495 } else {
3496 self.hide_context_menu(window, cx);
3497 }
3498 }
3499
3500 fn is_completion_trigger(
3501 &self,
3502 text: &str,
3503 trigger_in_words: bool,
3504 cx: &mut Context<Self>,
3505 ) -> bool {
3506 let position = self.selections.newest_anchor().head();
3507 let multibuffer = self.buffer.read(cx);
3508 let Some(buffer) = position
3509 .buffer_id
3510 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3511 else {
3512 return false;
3513 };
3514
3515 if let Some(completion_provider) = &self.completion_provider {
3516 completion_provider.is_completion_trigger(
3517 &buffer,
3518 position.text_anchor,
3519 text,
3520 trigger_in_words,
3521 cx,
3522 )
3523 } else {
3524 false
3525 }
3526 }
3527
3528 /// If any empty selections is touching the start of its innermost containing autoclose
3529 /// region, expand it to select the brackets.
3530 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3531 let selections = self.selections.all::<usize>(cx);
3532 let buffer = self.buffer.read(cx).read(cx);
3533 let new_selections = self
3534 .selections_with_autoclose_regions(selections, &buffer)
3535 .map(|(mut selection, region)| {
3536 if !selection.is_empty() {
3537 return selection;
3538 }
3539
3540 if let Some(region) = region {
3541 let mut range = region.range.to_offset(&buffer);
3542 if selection.start == range.start && range.start >= region.pair.start.len() {
3543 range.start -= region.pair.start.len();
3544 if buffer.contains_str_at(range.start, ®ion.pair.start)
3545 && buffer.contains_str_at(range.end, ®ion.pair.end)
3546 {
3547 range.end += region.pair.end.len();
3548 selection.start = range.start;
3549 selection.end = range.end;
3550
3551 return selection;
3552 }
3553 }
3554 }
3555
3556 let always_treat_brackets_as_autoclosed = buffer
3557 .settings_at(selection.start, cx)
3558 .always_treat_brackets_as_autoclosed;
3559
3560 if !always_treat_brackets_as_autoclosed {
3561 return selection;
3562 }
3563
3564 if let Some(scope) = buffer.language_scope_at(selection.start) {
3565 for (pair, enabled) in scope.brackets() {
3566 if !enabled || !pair.close {
3567 continue;
3568 }
3569
3570 if buffer.contains_str_at(selection.start, &pair.end) {
3571 let pair_start_len = pair.start.len();
3572 if buffer.contains_str_at(
3573 selection.start.saturating_sub(pair_start_len),
3574 &pair.start,
3575 ) {
3576 selection.start -= pair_start_len;
3577 selection.end += pair.end.len();
3578
3579 return selection;
3580 }
3581 }
3582 }
3583 }
3584
3585 selection
3586 })
3587 .collect();
3588
3589 drop(buffer);
3590 self.change_selections(None, window, cx, |selections| {
3591 selections.select(new_selections)
3592 });
3593 }
3594
3595 /// Iterate the given selections, and for each one, find the smallest surrounding
3596 /// autoclose region. This uses the ordering of the selections and the autoclose
3597 /// regions to avoid repeated comparisons.
3598 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3599 &'a self,
3600 selections: impl IntoIterator<Item = Selection<D>>,
3601 buffer: &'a MultiBufferSnapshot,
3602 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3603 let mut i = 0;
3604 let mut regions = self.autoclose_regions.as_slice();
3605 selections.into_iter().map(move |selection| {
3606 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3607
3608 let mut enclosing = None;
3609 while let Some(pair_state) = regions.get(i) {
3610 if pair_state.range.end.to_offset(buffer) < range.start {
3611 regions = ®ions[i + 1..];
3612 i = 0;
3613 } else if pair_state.range.start.to_offset(buffer) > range.end {
3614 break;
3615 } else {
3616 if pair_state.selection_id == selection.id {
3617 enclosing = Some(pair_state);
3618 }
3619 i += 1;
3620 }
3621 }
3622
3623 (selection, enclosing)
3624 })
3625 }
3626
3627 /// Remove any autoclose regions that no longer contain their selection.
3628 fn invalidate_autoclose_regions(
3629 &mut self,
3630 mut selections: &[Selection<Anchor>],
3631 buffer: &MultiBufferSnapshot,
3632 ) {
3633 self.autoclose_regions.retain(|state| {
3634 let mut i = 0;
3635 while let Some(selection) = selections.get(i) {
3636 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3637 selections = &selections[1..];
3638 continue;
3639 }
3640 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3641 break;
3642 }
3643 if selection.id == state.selection_id {
3644 return true;
3645 } else {
3646 i += 1;
3647 }
3648 }
3649 false
3650 });
3651 }
3652
3653 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3654 let offset = position.to_offset(buffer);
3655 let (word_range, kind) = buffer.surrounding_word(offset, true);
3656 if offset > word_range.start && kind == Some(CharKind::Word) {
3657 Some(
3658 buffer
3659 .text_for_range(word_range.start..offset)
3660 .collect::<String>(),
3661 )
3662 } else {
3663 None
3664 }
3665 }
3666
3667 pub fn toggle_inlay_hints(
3668 &mut self,
3669 _: &ToggleInlayHints,
3670 _: &mut Window,
3671 cx: &mut Context<Self>,
3672 ) {
3673 self.refresh_inlay_hints(
3674 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3675 cx,
3676 );
3677 }
3678
3679 pub fn inlay_hints_enabled(&self) -> bool {
3680 self.inlay_hint_cache.enabled
3681 }
3682
3683 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3684 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3685 return;
3686 }
3687
3688 let reason_description = reason.description();
3689 let ignore_debounce = matches!(
3690 reason,
3691 InlayHintRefreshReason::SettingsChange(_)
3692 | InlayHintRefreshReason::Toggle(_)
3693 | InlayHintRefreshReason::ExcerptsRemoved(_)
3694 );
3695 let (invalidate_cache, required_languages) = match reason {
3696 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3697 match self.inlay_hint_cache.modifiers_override(enabled) {
3698 Some(enabled) => {
3699 if enabled {
3700 (InvalidationStrategy::RefreshRequested, None)
3701 } else {
3702 self.splice_inlays(
3703 &self
3704 .visible_inlay_hints(cx)
3705 .iter()
3706 .map(|inlay| inlay.id)
3707 .collect::<Vec<InlayId>>(),
3708 Vec::new(),
3709 cx,
3710 );
3711 return;
3712 }
3713 }
3714 None => return,
3715 }
3716 }
3717 InlayHintRefreshReason::Toggle(enabled) => {
3718 if self.inlay_hint_cache.toggle(enabled) {
3719 if enabled {
3720 (InvalidationStrategy::RefreshRequested, None)
3721 } else {
3722 self.splice_inlays(
3723 &self
3724 .visible_inlay_hints(cx)
3725 .iter()
3726 .map(|inlay| inlay.id)
3727 .collect::<Vec<InlayId>>(),
3728 Vec::new(),
3729 cx,
3730 );
3731 return;
3732 }
3733 } else {
3734 return;
3735 }
3736 }
3737 InlayHintRefreshReason::SettingsChange(new_settings) => {
3738 match self.inlay_hint_cache.update_settings(
3739 &self.buffer,
3740 new_settings,
3741 self.visible_inlay_hints(cx),
3742 cx,
3743 ) {
3744 ControlFlow::Break(Some(InlaySplice {
3745 to_remove,
3746 to_insert,
3747 })) => {
3748 self.splice_inlays(&to_remove, to_insert, cx);
3749 return;
3750 }
3751 ControlFlow::Break(None) => return,
3752 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3753 }
3754 }
3755 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3756 if let Some(InlaySplice {
3757 to_remove,
3758 to_insert,
3759 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3760 {
3761 self.splice_inlays(&to_remove, to_insert, cx);
3762 }
3763 return;
3764 }
3765 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3766 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3767 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3768 }
3769 InlayHintRefreshReason::RefreshRequested => {
3770 (InvalidationStrategy::RefreshRequested, None)
3771 }
3772 };
3773
3774 if let Some(InlaySplice {
3775 to_remove,
3776 to_insert,
3777 }) = self.inlay_hint_cache.spawn_hint_refresh(
3778 reason_description,
3779 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3780 invalidate_cache,
3781 ignore_debounce,
3782 cx,
3783 ) {
3784 self.splice_inlays(&to_remove, to_insert, cx);
3785 }
3786 }
3787
3788 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3789 self.display_map
3790 .read(cx)
3791 .current_inlays()
3792 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3793 .cloned()
3794 .collect()
3795 }
3796
3797 pub fn excerpts_for_inlay_hints_query(
3798 &self,
3799 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3800 cx: &mut Context<Editor>,
3801 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3802 let Some(project) = self.project.as_ref() else {
3803 return HashMap::default();
3804 };
3805 let project = project.read(cx);
3806 let multi_buffer = self.buffer().read(cx);
3807 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3808 let multi_buffer_visible_start = self
3809 .scroll_manager
3810 .anchor()
3811 .anchor
3812 .to_point(&multi_buffer_snapshot);
3813 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3814 multi_buffer_visible_start
3815 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3816 Bias::Left,
3817 );
3818 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3819 multi_buffer_snapshot
3820 .range_to_buffer_ranges(multi_buffer_visible_range)
3821 .into_iter()
3822 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3823 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3824 let buffer_file = project::File::from_dyn(buffer.file())?;
3825 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3826 let worktree_entry = buffer_worktree
3827 .read(cx)
3828 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3829 if worktree_entry.is_ignored {
3830 return None;
3831 }
3832
3833 let language = buffer.language()?;
3834 if let Some(restrict_to_languages) = restrict_to_languages {
3835 if !restrict_to_languages.contains(language) {
3836 return None;
3837 }
3838 }
3839 Some((
3840 excerpt_id,
3841 (
3842 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3843 buffer.version().clone(),
3844 excerpt_visible_range,
3845 ),
3846 ))
3847 })
3848 .collect()
3849 }
3850
3851 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3852 TextLayoutDetails {
3853 text_system: window.text_system().clone(),
3854 editor_style: self.style.clone().unwrap(),
3855 rem_size: window.rem_size(),
3856 scroll_anchor: self.scroll_manager.anchor(),
3857 visible_rows: self.visible_line_count(),
3858 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3859 }
3860 }
3861
3862 pub fn splice_inlays(
3863 &self,
3864 to_remove: &[InlayId],
3865 to_insert: Vec<Inlay>,
3866 cx: &mut Context<Self>,
3867 ) {
3868 self.display_map.update(cx, |display_map, cx| {
3869 display_map.splice_inlays(to_remove, to_insert, cx)
3870 });
3871 cx.notify();
3872 }
3873
3874 fn trigger_on_type_formatting(
3875 &self,
3876 input: String,
3877 window: &mut Window,
3878 cx: &mut Context<Self>,
3879 ) -> Option<Task<Result<()>>> {
3880 if input.len() != 1 {
3881 return None;
3882 }
3883
3884 let project = self.project.as_ref()?;
3885 let position = self.selections.newest_anchor().head();
3886 let (buffer, buffer_position) = self
3887 .buffer
3888 .read(cx)
3889 .text_anchor_for_position(position, cx)?;
3890
3891 let settings = language_settings::language_settings(
3892 buffer
3893 .read(cx)
3894 .language_at(buffer_position)
3895 .map(|l| l.name()),
3896 buffer.read(cx).file(),
3897 cx,
3898 );
3899 if !settings.use_on_type_format {
3900 return None;
3901 }
3902
3903 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3904 // hence we do LSP request & edit on host side only — add formats to host's history.
3905 let push_to_lsp_host_history = true;
3906 // If this is not the host, append its history with new edits.
3907 let push_to_client_history = project.read(cx).is_via_collab();
3908
3909 let on_type_formatting = project.update(cx, |project, cx| {
3910 project.on_type_format(
3911 buffer.clone(),
3912 buffer_position,
3913 input,
3914 push_to_lsp_host_history,
3915 cx,
3916 )
3917 });
3918 Some(cx.spawn_in(window, |editor, mut cx| async move {
3919 if let Some(transaction) = on_type_formatting.await? {
3920 if push_to_client_history {
3921 buffer
3922 .update(&mut cx, |buffer, _| {
3923 buffer.push_transaction(transaction, Instant::now());
3924 })
3925 .ok();
3926 }
3927 editor.update(&mut cx, |editor, cx| {
3928 editor.refresh_document_highlights(cx);
3929 })?;
3930 }
3931 Ok(())
3932 }))
3933 }
3934
3935 pub fn show_completions(
3936 &mut self,
3937 options: &ShowCompletions,
3938 window: &mut Window,
3939 cx: &mut Context<Self>,
3940 ) {
3941 if self.pending_rename.is_some() {
3942 return;
3943 }
3944
3945 let Some(provider) = self.completion_provider.as_ref() else {
3946 return;
3947 };
3948
3949 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3950 return;
3951 }
3952
3953 let position = self.selections.newest_anchor().head();
3954 if position.diff_base_anchor.is_some() {
3955 return;
3956 }
3957 let (buffer, buffer_position) =
3958 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3959 output
3960 } else {
3961 return;
3962 };
3963 let show_completion_documentation = buffer
3964 .read(cx)
3965 .snapshot()
3966 .settings_at(buffer_position, cx)
3967 .show_completion_documentation;
3968
3969 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3970
3971 let trigger_kind = match &options.trigger {
3972 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3973 CompletionTriggerKind::TRIGGER_CHARACTER
3974 }
3975 _ => CompletionTriggerKind::INVOKED,
3976 };
3977 let completion_context = CompletionContext {
3978 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3979 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3980 Some(String::from(trigger))
3981 } else {
3982 None
3983 }
3984 }),
3985 trigger_kind,
3986 };
3987 let completions =
3988 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3989 let sort_completions = provider.sort_completions();
3990
3991 let id = post_inc(&mut self.next_completion_id);
3992 let task = cx.spawn_in(window, |editor, mut cx| {
3993 async move {
3994 editor.update(&mut cx, |this, _| {
3995 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3996 })?;
3997 let completions = completions.await.log_err();
3998 let menu = if let Some(completions) = completions {
3999 let mut menu = CompletionsMenu::new(
4000 id,
4001 sort_completions,
4002 show_completion_documentation,
4003 position,
4004 buffer.clone(),
4005 completions.into(),
4006 );
4007
4008 menu.filter(query.as_deref(), cx.background_executor().clone())
4009 .await;
4010
4011 menu.visible().then_some(menu)
4012 } else {
4013 None
4014 };
4015
4016 editor.update_in(&mut cx, |editor, window, cx| {
4017 match editor.context_menu.borrow().as_ref() {
4018 None => {}
4019 Some(CodeContextMenu::Completions(prev_menu)) => {
4020 if prev_menu.id > id {
4021 return;
4022 }
4023 }
4024 _ => return,
4025 }
4026
4027 if editor.focus_handle.is_focused(window) && menu.is_some() {
4028 let mut menu = menu.unwrap();
4029 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4030
4031 *editor.context_menu.borrow_mut() =
4032 Some(CodeContextMenu::Completions(menu));
4033
4034 if editor.show_edit_predictions_in_menu() {
4035 editor.update_visible_inline_completion(window, cx);
4036 } else {
4037 editor.discard_inline_completion(false, cx);
4038 }
4039
4040 cx.notify();
4041 } else if editor.completion_tasks.len() <= 1 {
4042 // If there are no more completion tasks and the last menu was
4043 // empty, we should hide it.
4044 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4045 // If it was already hidden and we don't show inline
4046 // completions in the menu, we should also show the
4047 // inline-completion when available.
4048 if was_hidden && editor.show_edit_predictions_in_menu() {
4049 editor.update_visible_inline_completion(window, cx);
4050 }
4051 }
4052 })?;
4053
4054 Ok::<_, anyhow::Error>(())
4055 }
4056 .log_err()
4057 });
4058
4059 self.completion_tasks.push((id, task));
4060 }
4061
4062 pub fn confirm_completion(
4063 &mut self,
4064 action: &ConfirmCompletion,
4065 window: &mut Window,
4066 cx: &mut Context<Self>,
4067 ) -> Option<Task<Result<()>>> {
4068 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4069 }
4070
4071 pub fn compose_completion(
4072 &mut self,
4073 action: &ComposeCompletion,
4074 window: &mut Window,
4075 cx: &mut Context<Self>,
4076 ) -> Option<Task<Result<()>>> {
4077 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4078 }
4079
4080 fn do_completion(
4081 &mut self,
4082 item_ix: Option<usize>,
4083 intent: CompletionIntent,
4084 window: &mut Window,
4085 cx: &mut Context<Editor>,
4086 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4087 use language::ToOffset as _;
4088
4089 let completions_menu =
4090 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4091 menu
4092 } else {
4093 return None;
4094 };
4095
4096 let entries = completions_menu.entries.borrow();
4097 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4098 if self.show_edit_predictions_in_menu() {
4099 self.discard_inline_completion(true, cx);
4100 }
4101 let candidate_id = mat.candidate_id;
4102 drop(entries);
4103
4104 let buffer_handle = completions_menu.buffer;
4105 let completion = completions_menu
4106 .completions
4107 .borrow()
4108 .get(candidate_id)?
4109 .clone();
4110 cx.stop_propagation();
4111
4112 let snippet;
4113 let text;
4114
4115 if completion.is_snippet() {
4116 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4117 text = snippet.as_ref().unwrap().text.clone();
4118 } else {
4119 snippet = None;
4120 text = completion.new_text.clone();
4121 };
4122 let selections = self.selections.all::<usize>(cx);
4123 let buffer = buffer_handle.read(cx);
4124 let old_range = completion.old_range.to_offset(buffer);
4125 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4126
4127 let newest_selection = self.selections.newest_anchor();
4128 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4129 return None;
4130 }
4131
4132 let lookbehind = newest_selection
4133 .start
4134 .text_anchor
4135 .to_offset(buffer)
4136 .saturating_sub(old_range.start);
4137 let lookahead = old_range
4138 .end
4139 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4140 let mut common_prefix_len = old_text
4141 .bytes()
4142 .zip(text.bytes())
4143 .take_while(|(a, b)| a == b)
4144 .count();
4145
4146 let snapshot = self.buffer.read(cx).snapshot(cx);
4147 let mut range_to_replace: Option<Range<isize>> = None;
4148 let mut ranges = Vec::new();
4149 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4150 for selection in &selections {
4151 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4152 let start = selection.start.saturating_sub(lookbehind);
4153 let end = selection.end + lookahead;
4154 if selection.id == newest_selection.id {
4155 range_to_replace = Some(
4156 ((start + common_prefix_len) as isize - selection.start as isize)
4157 ..(end as isize - selection.start as isize),
4158 );
4159 }
4160 ranges.push(start + common_prefix_len..end);
4161 } else {
4162 common_prefix_len = 0;
4163 ranges.clear();
4164 ranges.extend(selections.iter().map(|s| {
4165 if s.id == newest_selection.id {
4166 range_to_replace = Some(
4167 old_range.start.to_offset_utf16(&snapshot).0 as isize
4168 - selection.start as isize
4169 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4170 - selection.start as isize,
4171 );
4172 old_range.clone()
4173 } else {
4174 s.start..s.end
4175 }
4176 }));
4177 break;
4178 }
4179 if !self.linked_edit_ranges.is_empty() {
4180 let start_anchor = snapshot.anchor_before(selection.head());
4181 let end_anchor = snapshot.anchor_after(selection.tail());
4182 if let Some(ranges) = self
4183 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4184 {
4185 for (buffer, edits) in ranges {
4186 linked_edits.entry(buffer.clone()).or_default().extend(
4187 edits
4188 .into_iter()
4189 .map(|range| (range, text[common_prefix_len..].to_owned())),
4190 );
4191 }
4192 }
4193 }
4194 }
4195 let text = &text[common_prefix_len..];
4196
4197 cx.emit(EditorEvent::InputHandled {
4198 utf16_range_to_replace: range_to_replace,
4199 text: text.into(),
4200 });
4201
4202 self.transact(window, cx, |this, window, cx| {
4203 if let Some(mut snippet) = snippet {
4204 snippet.text = text.to_string();
4205 for tabstop in snippet
4206 .tabstops
4207 .iter_mut()
4208 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4209 {
4210 tabstop.start -= common_prefix_len as isize;
4211 tabstop.end -= common_prefix_len as isize;
4212 }
4213
4214 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4215 } else {
4216 this.buffer.update(cx, |buffer, cx| {
4217 buffer.edit(
4218 ranges.iter().map(|range| (range.clone(), text)),
4219 this.autoindent_mode.clone(),
4220 cx,
4221 );
4222 });
4223 }
4224 for (buffer, edits) in linked_edits {
4225 buffer.update(cx, |buffer, cx| {
4226 let snapshot = buffer.snapshot();
4227 let edits = edits
4228 .into_iter()
4229 .map(|(range, text)| {
4230 use text::ToPoint as TP;
4231 let end_point = TP::to_point(&range.end, &snapshot);
4232 let start_point = TP::to_point(&range.start, &snapshot);
4233 (start_point..end_point, text)
4234 })
4235 .sorted_by_key(|(range, _)| range.start)
4236 .collect::<Vec<_>>();
4237 buffer.edit(edits, None, cx);
4238 })
4239 }
4240
4241 this.refresh_inline_completion(true, false, window, cx);
4242 });
4243
4244 let show_new_completions_on_confirm = completion
4245 .confirm
4246 .as_ref()
4247 .map_or(false, |confirm| confirm(intent, window, cx));
4248 if show_new_completions_on_confirm {
4249 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4250 }
4251
4252 let provider = self.completion_provider.as_ref()?;
4253 drop(completion);
4254 let apply_edits = provider.apply_additional_edits_for_completion(
4255 buffer_handle,
4256 completions_menu.completions.clone(),
4257 candidate_id,
4258 true,
4259 cx,
4260 );
4261
4262 let editor_settings = EditorSettings::get_global(cx);
4263 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4264 // After the code completion is finished, users often want to know what signatures are needed.
4265 // so we should automatically call signature_help
4266 self.show_signature_help(&ShowSignatureHelp, window, cx);
4267 }
4268
4269 Some(cx.foreground_executor().spawn(async move {
4270 apply_edits.await?;
4271 Ok(())
4272 }))
4273 }
4274
4275 pub fn toggle_code_actions(
4276 &mut self,
4277 action: &ToggleCodeActions,
4278 window: &mut Window,
4279 cx: &mut Context<Self>,
4280 ) {
4281 let mut context_menu = self.context_menu.borrow_mut();
4282 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4283 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4284 // Toggle if we're selecting the same one
4285 *context_menu = None;
4286 cx.notify();
4287 return;
4288 } else {
4289 // Otherwise, clear it and start a new one
4290 *context_menu = None;
4291 cx.notify();
4292 }
4293 }
4294 drop(context_menu);
4295 let snapshot = self.snapshot(window, cx);
4296 let deployed_from_indicator = action.deployed_from_indicator;
4297 let mut task = self.code_actions_task.take();
4298 let action = action.clone();
4299 cx.spawn_in(window, |editor, mut cx| async move {
4300 while let Some(prev_task) = task {
4301 prev_task.await.log_err();
4302 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4303 }
4304
4305 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4306 if editor.focus_handle.is_focused(window) {
4307 let multibuffer_point = action
4308 .deployed_from_indicator
4309 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4310 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4311 let (buffer, buffer_row) = snapshot
4312 .buffer_snapshot
4313 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4314 .and_then(|(buffer_snapshot, range)| {
4315 editor
4316 .buffer
4317 .read(cx)
4318 .buffer(buffer_snapshot.remote_id())
4319 .map(|buffer| (buffer, range.start.row))
4320 })?;
4321 let (_, code_actions) = editor
4322 .available_code_actions
4323 .clone()
4324 .and_then(|(location, code_actions)| {
4325 let snapshot = location.buffer.read(cx).snapshot();
4326 let point_range = location.range.to_point(&snapshot);
4327 let point_range = point_range.start.row..=point_range.end.row;
4328 if point_range.contains(&buffer_row) {
4329 Some((location, code_actions))
4330 } else {
4331 None
4332 }
4333 })
4334 .unzip();
4335 let buffer_id = buffer.read(cx).remote_id();
4336 let tasks = editor
4337 .tasks
4338 .get(&(buffer_id, buffer_row))
4339 .map(|t| Arc::new(t.to_owned()));
4340 if tasks.is_none() && code_actions.is_none() {
4341 return None;
4342 }
4343
4344 editor.completion_tasks.clear();
4345 editor.discard_inline_completion(false, cx);
4346 let task_context =
4347 tasks
4348 .as_ref()
4349 .zip(editor.project.clone())
4350 .map(|(tasks, project)| {
4351 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4352 });
4353
4354 Some(cx.spawn_in(window, |editor, mut cx| async move {
4355 let task_context = match task_context {
4356 Some(task_context) => task_context.await,
4357 None => None,
4358 };
4359 let resolved_tasks =
4360 tasks.zip(task_context).map(|(tasks, task_context)| {
4361 Rc::new(ResolvedTasks {
4362 templates: tasks.resolve(&task_context).collect(),
4363 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4364 multibuffer_point.row,
4365 tasks.column,
4366 )),
4367 })
4368 });
4369 let spawn_straight_away = resolved_tasks
4370 .as_ref()
4371 .map_or(false, |tasks| tasks.templates.len() == 1)
4372 && code_actions
4373 .as_ref()
4374 .map_or(true, |actions| actions.is_empty());
4375 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4376 *editor.context_menu.borrow_mut() =
4377 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4378 buffer,
4379 actions: CodeActionContents {
4380 tasks: resolved_tasks,
4381 actions: code_actions,
4382 },
4383 selected_item: Default::default(),
4384 scroll_handle: UniformListScrollHandle::default(),
4385 deployed_from_indicator,
4386 }));
4387 if spawn_straight_away {
4388 if let Some(task) = editor.confirm_code_action(
4389 &ConfirmCodeAction { item_ix: Some(0) },
4390 window,
4391 cx,
4392 ) {
4393 cx.notify();
4394 return task;
4395 }
4396 }
4397 cx.notify();
4398 Task::ready(Ok(()))
4399 }) {
4400 task.await
4401 } else {
4402 Ok(())
4403 }
4404 }))
4405 } else {
4406 Some(Task::ready(Ok(())))
4407 }
4408 })?;
4409 if let Some(task) = spawned_test_task {
4410 task.await?;
4411 }
4412
4413 Ok::<_, anyhow::Error>(())
4414 })
4415 .detach_and_log_err(cx);
4416 }
4417
4418 pub fn confirm_code_action(
4419 &mut self,
4420 action: &ConfirmCodeAction,
4421 window: &mut Window,
4422 cx: &mut Context<Self>,
4423 ) -> Option<Task<Result<()>>> {
4424 let actions_menu =
4425 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4426 menu
4427 } else {
4428 return None;
4429 };
4430 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4431 let action = actions_menu.actions.get(action_ix)?;
4432 let title = action.label();
4433 let buffer = actions_menu.buffer;
4434 let workspace = self.workspace()?;
4435
4436 match action {
4437 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4438 workspace.update(cx, |workspace, cx| {
4439 workspace::tasks::schedule_resolved_task(
4440 workspace,
4441 task_source_kind,
4442 resolved_task,
4443 false,
4444 cx,
4445 );
4446
4447 Some(Task::ready(Ok(())))
4448 })
4449 }
4450 CodeActionsItem::CodeAction {
4451 excerpt_id,
4452 action,
4453 provider,
4454 } => {
4455 let apply_code_action =
4456 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4457 let workspace = workspace.downgrade();
4458 Some(cx.spawn_in(window, |editor, cx| async move {
4459 let project_transaction = apply_code_action.await?;
4460 Self::open_project_transaction(
4461 &editor,
4462 workspace,
4463 project_transaction,
4464 title,
4465 cx,
4466 )
4467 .await
4468 }))
4469 }
4470 }
4471 }
4472
4473 pub async fn open_project_transaction(
4474 this: &WeakEntity<Editor>,
4475 workspace: WeakEntity<Workspace>,
4476 transaction: ProjectTransaction,
4477 title: String,
4478 mut cx: AsyncWindowContext,
4479 ) -> Result<()> {
4480 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4481 cx.update(|_, cx| {
4482 entries.sort_unstable_by_key(|(buffer, _)| {
4483 buffer.read(cx).file().map(|f| f.path().clone())
4484 });
4485 })?;
4486
4487 // If the project transaction's edits are all contained within this editor, then
4488 // avoid opening a new editor to display them.
4489
4490 if let Some((buffer, transaction)) = entries.first() {
4491 if entries.len() == 1 {
4492 let excerpt = this.update(&mut cx, |editor, cx| {
4493 editor
4494 .buffer()
4495 .read(cx)
4496 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4497 })?;
4498 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4499 if excerpted_buffer == *buffer {
4500 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4501 let excerpt_range = excerpt_range.to_offset(buffer);
4502 buffer
4503 .edited_ranges_for_transaction::<usize>(transaction)
4504 .all(|range| {
4505 excerpt_range.start <= range.start
4506 && excerpt_range.end >= range.end
4507 })
4508 })?;
4509
4510 if all_edits_within_excerpt {
4511 return Ok(());
4512 }
4513 }
4514 }
4515 }
4516 } else {
4517 return Ok(());
4518 }
4519
4520 let mut ranges_to_highlight = Vec::new();
4521 let excerpt_buffer = cx.new(|cx| {
4522 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4523 for (buffer_handle, transaction) in &entries {
4524 let buffer = buffer_handle.read(cx);
4525 ranges_to_highlight.extend(
4526 multibuffer.push_excerpts_with_context_lines(
4527 buffer_handle.clone(),
4528 buffer
4529 .edited_ranges_for_transaction::<usize>(transaction)
4530 .collect(),
4531 DEFAULT_MULTIBUFFER_CONTEXT,
4532 cx,
4533 ),
4534 );
4535 }
4536 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4537 multibuffer
4538 })?;
4539
4540 workspace.update_in(&mut cx, |workspace, window, cx| {
4541 let project = workspace.project().clone();
4542 let editor = cx
4543 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4544 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4545 editor.update(cx, |editor, cx| {
4546 editor.highlight_background::<Self>(
4547 &ranges_to_highlight,
4548 |theme| theme.editor_highlighted_line_background,
4549 cx,
4550 );
4551 });
4552 })?;
4553
4554 Ok(())
4555 }
4556
4557 pub fn clear_code_action_providers(&mut self) {
4558 self.code_action_providers.clear();
4559 self.available_code_actions.take();
4560 }
4561
4562 pub fn add_code_action_provider(
4563 &mut self,
4564 provider: Rc<dyn CodeActionProvider>,
4565 window: &mut Window,
4566 cx: &mut Context<Self>,
4567 ) {
4568 if self
4569 .code_action_providers
4570 .iter()
4571 .any(|existing_provider| existing_provider.id() == provider.id())
4572 {
4573 return;
4574 }
4575
4576 self.code_action_providers.push(provider);
4577 self.refresh_code_actions(window, cx);
4578 }
4579
4580 pub fn remove_code_action_provider(
4581 &mut self,
4582 id: Arc<str>,
4583 window: &mut Window,
4584 cx: &mut Context<Self>,
4585 ) {
4586 self.code_action_providers
4587 .retain(|provider| provider.id() != id);
4588 self.refresh_code_actions(window, cx);
4589 }
4590
4591 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4592 let buffer = self.buffer.read(cx);
4593 let newest_selection = self.selections.newest_anchor().clone();
4594 if newest_selection.head().diff_base_anchor.is_some() {
4595 return None;
4596 }
4597 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4598 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4599 if start_buffer != end_buffer {
4600 return None;
4601 }
4602
4603 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4604 cx.background_executor()
4605 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4606 .await;
4607
4608 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4609 let providers = this.code_action_providers.clone();
4610 let tasks = this
4611 .code_action_providers
4612 .iter()
4613 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4614 .collect::<Vec<_>>();
4615 (providers, tasks)
4616 })?;
4617
4618 let mut actions = Vec::new();
4619 for (provider, provider_actions) in
4620 providers.into_iter().zip(future::join_all(tasks).await)
4621 {
4622 if let Some(provider_actions) = provider_actions.log_err() {
4623 actions.extend(provider_actions.into_iter().map(|action| {
4624 AvailableCodeAction {
4625 excerpt_id: newest_selection.start.excerpt_id,
4626 action,
4627 provider: provider.clone(),
4628 }
4629 }));
4630 }
4631 }
4632
4633 this.update(&mut cx, |this, cx| {
4634 this.available_code_actions = if actions.is_empty() {
4635 None
4636 } else {
4637 Some((
4638 Location {
4639 buffer: start_buffer,
4640 range: start..end,
4641 },
4642 actions.into(),
4643 ))
4644 };
4645 cx.notify();
4646 })
4647 }));
4648 None
4649 }
4650
4651 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4652 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4653 self.show_git_blame_inline = false;
4654
4655 self.show_git_blame_inline_delay_task =
4656 Some(cx.spawn_in(window, |this, mut cx| async move {
4657 cx.background_executor().timer(delay).await;
4658
4659 this.update(&mut cx, |this, cx| {
4660 this.show_git_blame_inline = true;
4661 cx.notify();
4662 })
4663 .log_err();
4664 }));
4665 }
4666 }
4667
4668 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4669 if self.pending_rename.is_some() {
4670 return None;
4671 }
4672
4673 let provider = self.semantics_provider.clone()?;
4674 let buffer = self.buffer.read(cx);
4675 let newest_selection = self.selections.newest_anchor().clone();
4676 let cursor_position = newest_selection.head();
4677 let (cursor_buffer, cursor_buffer_position) =
4678 buffer.text_anchor_for_position(cursor_position, cx)?;
4679 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4680 if cursor_buffer != tail_buffer {
4681 return None;
4682 }
4683 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4684 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4685 cx.background_executor()
4686 .timer(Duration::from_millis(debounce))
4687 .await;
4688
4689 let highlights = if let Some(highlights) = cx
4690 .update(|cx| {
4691 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4692 })
4693 .ok()
4694 .flatten()
4695 {
4696 highlights.await.log_err()
4697 } else {
4698 None
4699 };
4700
4701 if let Some(highlights) = highlights {
4702 this.update(&mut cx, |this, cx| {
4703 if this.pending_rename.is_some() {
4704 return;
4705 }
4706
4707 let buffer_id = cursor_position.buffer_id;
4708 let buffer = this.buffer.read(cx);
4709 if !buffer
4710 .text_anchor_for_position(cursor_position, cx)
4711 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4712 {
4713 return;
4714 }
4715
4716 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4717 let mut write_ranges = Vec::new();
4718 let mut read_ranges = Vec::new();
4719 for highlight in highlights {
4720 for (excerpt_id, excerpt_range) in
4721 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4722 {
4723 let start = highlight
4724 .range
4725 .start
4726 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4727 let end = highlight
4728 .range
4729 .end
4730 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4731 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4732 continue;
4733 }
4734
4735 let range = Anchor {
4736 buffer_id,
4737 excerpt_id,
4738 text_anchor: start,
4739 diff_base_anchor: None,
4740 }..Anchor {
4741 buffer_id,
4742 excerpt_id,
4743 text_anchor: end,
4744 diff_base_anchor: None,
4745 };
4746 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4747 write_ranges.push(range);
4748 } else {
4749 read_ranges.push(range);
4750 }
4751 }
4752 }
4753
4754 this.highlight_background::<DocumentHighlightRead>(
4755 &read_ranges,
4756 |theme| theme.editor_document_highlight_read_background,
4757 cx,
4758 );
4759 this.highlight_background::<DocumentHighlightWrite>(
4760 &write_ranges,
4761 |theme| theme.editor_document_highlight_write_background,
4762 cx,
4763 );
4764 cx.notify();
4765 })
4766 .log_err();
4767 }
4768 }));
4769 None
4770 }
4771
4772 pub fn refresh_selected_text_highlights(
4773 &mut self,
4774 window: &mut Window,
4775 cx: &mut Context<Editor>,
4776 ) {
4777 self.selection_highlight_task.take();
4778 if !EditorSettings::get_global(cx).selection_highlight {
4779 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4780 return;
4781 }
4782 if self.selections.count() != 1 || self.selections.line_mode {
4783 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4784 return;
4785 }
4786 let selection = self.selections.newest::<Point>(cx);
4787 if selection.is_empty() || selection.start.row != selection.end.row {
4788 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4789 return;
4790 }
4791 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4792 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4793 cx.background_executor()
4794 .timer(Duration::from_millis(debounce))
4795 .await;
4796 let Some(Some(matches_task)) = editor
4797 .update_in(&mut cx, |editor, _, cx| {
4798 if editor.selections.count() != 1 || editor.selections.line_mode {
4799 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4800 return None;
4801 }
4802 let selection = editor.selections.newest::<Point>(cx);
4803 if selection.is_empty() || selection.start.row != selection.end.row {
4804 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4805 return None;
4806 }
4807 let buffer = editor.buffer().read(cx).snapshot(cx);
4808 let query = buffer.text_for_range(selection.range()).collect::<String>();
4809 if query.trim().is_empty() {
4810 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4811 return None;
4812 }
4813 Some(cx.background_spawn(async move {
4814 let mut ranges = Vec::new();
4815 let selection_anchors = selection.range().to_anchors(&buffer);
4816 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4817 for (search_buffer, search_range, excerpt_id) in
4818 buffer.range_to_buffer_ranges(range)
4819 {
4820 ranges.extend(
4821 project::search::SearchQuery::text(
4822 query.clone(),
4823 false,
4824 false,
4825 false,
4826 Default::default(),
4827 Default::default(),
4828 None,
4829 )
4830 .unwrap()
4831 .search(search_buffer, Some(search_range.clone()))
4832 .await
4833 .into_iter()
4834 .filter_map(
4835 |match_range| {
4836 let start = search_buffer.anchor_after(
4837 search_range.start + match_range.start,
4838 );
4839 let end = search_buffer.anchor_before(
4840 search_range.start + match_range.end,
4841 );
4842 let range = Anchor::range_in_buffer(
4843 excerpt_id,
4844 search_buffer.remote_id(),
4845 start..end,
4846 );
4847 (range != selection_anchors).then_some(range)
4848 },
4849 ),
4850 );
4851 }
4852 }
4853 ranges
4854 }))
4855 })
4856 .log_err()
4857 else {
4858 return;
4859 };
4860 let matches = matches_task.await;
4861 editor
4862 .update_in(&mut cx, |editor, _, cx| {
4863 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4864 if !matches.is_empty() {
4865 editor.highlight_background::<SelectedTextHighlight>(
4866 &matches,
4867 |theme| theme.editor_document_highlight_bracket_background,
4868 cx,
4869 )
4870 }
4871 })
4872 .log_err();
4873 }));
4874 }
4875
4876 pub fn refresh_inline_completion(
4877 &mut self,
4878 debounce: bool,
4879 user_requested: bool,
4880 window: &mut Window,
4881 cx: &mut Context<Self>,
4882 ) -> Option<()> {
4883 let provider = self.edit_prediction_provider()?;
4884 let cursor = self.selections.newest_anchor().head();
4885 let (buffer, cursor_buffer_position) =
4886 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4887
4888 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4889 self.discard_inline_completion(false, cx);
4890 return None;
4891 }
4892
4893 if !user_requested
4894 && (!self.should_show_edit_predictions()
4895 || !self.is_focused(window)
4896 || buffer.read(cx).is_empty())
4897 {
4898 self.discard_inline_completion(false, cx);
4899 return None;
4900 }
4901
4902 self.update_visible_inline_completion(window, cx);
4903 provider.refresh(
4904 self.project.clone(),
4905 buffer,
4906 cursor_buffer_position,
4907 debounce,
4908 cx,
4909 );
4910 Some(())
4911 }
4912
4913 fn show_edit_predictions_in_menu(&self) -> bool {
4914 match self.edit_prediction_settings {
4915 EditPredictionSettings::Disabled => false,
4916 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4917 }
4918 }
4919
4920 pub fn edit_predictions_enabled(&self) -> bool {
4921 match self.edit_prediction_settings {
4922 EditPredictionSettings::Disabled => false,
4923 EditPredictionSettings::Enabled { .. } => true,
4924 }
4925 }
4926
4927 fn edit_prediction_requires_modifier(&self) -> bool {
4928 match self.edit_prediction_settings {
4929 EditPredictionSettings::Disabled => false,
4930 EditPredictionSettings::Enabled {
4931 preview_requires_modifier,
4932 ..
4933 } => preview_requires_modifier,
4934 }
4935 }
4936
4937 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4938 if self.edit_prediction_provider.is_none() {
4939 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4940 } else {
4941 let selection = self.selections.newest_anchor();
4942 let cursor = selection.head();
4943
4944 if let Some((buffer, cursor_buffer_position)) =
4945 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4946 {
4947 self.edit_prediction_settings =
4948 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
4949 }
4950 }
4951 }
4952
4953 fn edit_prediction_settings_at_position(
4954 &self,
4955 buffer: &Entity<Buffer>,
4956 buffer_position: language::Anchor,
4957 cx: &App,
4958 ) -> EditPredictionSettings {
4959 if self.mode != EditorMode::Full
4960 || !self.show_inline_completions_override.unwrap_or(true)
4961 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4962 {
4963 return EditPredictionSettings::Disabled;
4964 }
4965
4966 let buffer = buffer.read(cx);
4967
4968 let file = buffer.file();
4969
4970 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4971 return EditPredictionSettings::Disabled;
4972 };
4973
4974 let by_provider = matches!(
4975 self.menu_inline_completions_policy,
4976 MenuInlineCompletionsPolicy::ByProvider
4977 );
4978
4979 let show_in_menu = by_provider
4980 && self
4981 .edit_prediction_provider
4982 .as_ref()
4983 .map_or(false, |provider| {
4984 provider.provider.show_completions_in_menu()
4985 });
4986
4987 let preview_requires_modifier =
4988 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
4989
4990 EditPredictionSettings::Enabled {
4991 show_in_menu,
4992 preview_requires_modifier,
4993 }
4994 }
4995
4996 fn should_show_edit_predictions(&self) -> bool {
4997 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4998 }
4999
5000 pub fn edit_prediction_preview_is_active(&self) -> bool {
5001 matches!(
5002 self.edit_prediction_preview,
5003 EditPredictionPreview::Active { .. }
5004 )
5005 }
5006
5007 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5008 let cursor = self.selections.newest_anchor().head();
5009 if let Some((buffer, cursor_position)) =
5010 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5011 {
5012 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5013 } else {
5014 false
5015 }
5016 }
5017
5018 fn edit_predictions_enabled_in_buffer(
5019 &self,
5020 buffer: &Entity<Buffer>,
5021 buffer_position: language::Anchor,
5022 cx: &App,
5023 ) -> bool {
5024 maybe!({
5025 let provider = self.edit_prediction_provider()?;
5026 if !provider.is_enabled(&buffer, buffer_position, cx) {
5027 return Some(false);
5028 }
5029 let buffer = buffer.read(cx);
5030 let Some(file) = buffer.file() else {
5031 return Some(true);
5032 };
5033 let settings = all_language_settings(Some(file), cx);
5034 Some(settings.edit_predictions_enabled_for_file(file, cx))
5035 })
5036 .unwrap_or(false)
5037 }
5038
5039 fn cycle_inline_completion(
5040 &mut self,
5041 direction: Direction,
5042 window: &mut Window,
5043 cx: &mut Context<Self>,
5044 ) -> Option<()> {
5045 let provider = self.edit_prediction_provider()?;
5046 let cursor = self.selections.newest_anchor().head();
5047 let (buffer, cursor_buffer_position) =
5048 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5049 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5050 return None;
5051 }
5052
5053 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5054 self.update_visible_inline_completion(window, cx);
5055
5056 Some(())
5057 }
5058
5059 pub fn show_inline_completion(
5060 &mut self,
5061 _: &ShowEditPrediction,
5062 window: &mut Window,
5063 cx: &mut Context<Self>,
5064 ) {
5065 if !self.has_active_inline_completion() {
5066 self.refresh_inline_completion(false, true, window, cx);
5067 return;
5068 }
5069
5070 self.update_visible_inline_completion(window, cx);
5071 }
5072
5073 pub fn display_cursor_names(
5074 &mut self,
5075 _: &DisplayCursorNames,
5076 window: &mut Window,
5077 cx: &mut Context<Self>,
5078 ) {
5079 self.show_cursor_names(window, cx);
5080 }
5081
5082 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5083 self.show_cursor_names = true;
5084 cx.notify();
5085 cx.spawn_in(window, |this, mut cx| async move {
5086 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5087 this.update(&mut cx, |this, cx| {
5088 this.show_cursor_names = false;
5089 cx.notify()
5090 })
5091 .ok()
5092 })
5093 .detach();
5094 }
5095
5096 pub fn next_edit_prediction(
5097 &mut self,
5098 _: &NextEditPrediction,
5099 window: &mut Window,
5100 cx: &mut Context<Self>,
5101 ) {
5102 if self.has_active_inline_completion() {
5103 self.cycle_inline_completion(Direction::Next, window, cx);
5104 } else {
5105 let is_copilot_disabled = self
5106 .refresh_inline_completion(false, true, window, cx)
5107 .is_none();
5108 if is_copilot_disabled {
5109 cx.propagate();
5110 }
5111 }
5112 }
5113
5114 pub fn previous_edit_prediction(
5115 &mut self,
5116 _: &PreviousEditPrediction,
5117 window: &mut Window,
5118 cx: &mut Context<Self>,
5119 ) {
5120 if self.has_active_inline_completion() {
5121 self.cycle_inline_completion(Direction::Prev, window, cx);
5122 } else {
5123 let is_copilot_disabled = self
5124 .refresh_inline_completion(false, true, window, cx)
5125 .is_none();
5126 if is_copilot_disabled {
5127 cx.propagate();
5128 }
5129 }
5130 }
5131
5132 pub fn accept_edit_prediction(
5133 &mut self,
5134 _: &AcceptEditPrediction,
5135 window: &mut Window,
5136 cx: &mut Context<Self>,
5137 ) {
5138 if self.show_edit_predictions_in_menu() {
5139 self.hide_context_menu(window, cx);
5140 }
5141
5142 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5143 return;
5144 };
5145
5146 self.report_inline_completion_event(
5147 active_inline_completion.completion_id.clone(),
5148 true,
5149 cx,
5150 );
5151
5152 match &active_inline_completion.completion {
5153 InlineCompletion::Move { target, .. } => {
5154 let target = *target;
5155
5156 if let Some(position_map) = &self.last_position_map {
5157 if position_map
5158 .visible_row_range
5159 .contains(&target.to_display_point(&position_map.snapshot).row())
5160 || !self.edit_prediction_requires_modifier()
5161 {
5162 self.unfold_ranges(&[target..target], true, false, cx);
5163 // Note that this is also done in vim's handler of the Tab action.
5164 self.change_selections(
5165 Some(Autoscroll::newest()),
5166 window,
5167 cx,
5168 |selections| {
5169 selections.select_anchor_ranges([target..target]);
5170 },
5171 );
5172 self.clear_row_highlights::<EditPredictionPreview>();
5173
5174 self.edit_prediction_preview
5175 .set_previous_scroll_position(None);
5176 } else {
5177 self.edit_prediction_preview
5178 .set_previous_scroll_position(Some(
5179 position_map.snapshot.scroll_anchor,
5180 ));
5181
5182 self.highlight_rows::<EditPredictionPreview>(
5183 target..target,
5184 cx.theme().colors().editor_highlighted_line_background,
5185 true,
5186 cx,
5187 );
5188 self.request_autoscroll(Autoscroll::fit(), cx);
5189 }
5190 }
5191 }
5192 InlineCompletion::Edit { edits, .. } => {
5193 if let Some(provider) = self.edit_prediction_provider() {
5194 provider.accept(cx);
5195 }
5196
5197 let snapshot = self.buffer.read(cx).snapshot(cx);
5198 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5199
5200 self.buffer.update(cx, |buffer, cx| {
5201 buffer.edit(edits.iter().cloned(), None, cx)
5202 });
5203
5204 self.change_selections(None, window, cx, |s| {
5205 s.select_anchor_ranges([last_edit_end..last_edit_end])
5206 });
5207
5208 self.update_visible_inline_completion(window, cx);
5209 if self.active_inline_completion.is_none() {
5210 self.refresh_inline_completion(true, true, window, cx);
5211 }
5212
5213 cx.notify();
5214 }
5215 }
5216
5217 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5218 }
5219
5220 pub fn accept_partial_inline_completion(
5221 &mut self,
5222 _: &AcceptPartialEditPrediction,
5223 window: &mut Window,
5224 cx: &mut Context<Self>,
5225 ) {
5226 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5227 return;
5228 };
5229 if self.selections.count() != 1 {
5230 return;
5231 }
5232
5233 self.report_inline_completion_event(
5234 active_inline_completion.completion_id.clone(),
5235 true,
5236 cx,
5237 );
5238
5239 match &active_inline_completion.completion {
5240 InlineCompletion::Move { target, .. } => {
5241 let target = *target;
5242 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5243 selections.select_anchor_ranges([target..target]);
5244 });
5245 }
5246 InlineCompletion::Edit { edits, .. } => {
5247 // Find an insertion that starts at the cursor position.
5248 let snapshot = self.buffer.read(cx).snapshot(cx);
5249 let cursor_offset = self.selections.newest::<usize>(cx).head();
5250 let insertion = edits.iter().find_map(|(range, text)| {
5251 let range = range.to_offset(&snapshot);
5252 if range.is_empty() && range.start == cursor_offset {
5253 Some(text)
5254 } else {
5255 None
5256 }
5257 });
5258
5259 if let Some(text) = insertion {
5260 let mut partial_completion = text
5261 .chars()
5262 .by_ref()
5263 .take_while(|c| c.is_alphabetic())
5264 .collect::<String>();
5265 if partial_completion.is_empty() {
5266 partial_completion = text
5267 .chars()
5268 .by_ref()
5269 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5270 .collect::<String>();
5271 }
5272
5273 cx.emit(EditorEvent::InputHandled {
5274 utf16_range_to_replace: None,
5275 text: partial_completion.clone().into(),
5276 });
5277
5278 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5279
5280 self.refresh_inline_completion(true, true, window, cx);
5281 cx.notify();
5282 } else {
5283 self.accept_edit_prediction(&Default::default(), window, cx);
5284 }
5285 }
5286 }
5287 }
5288
5289 fn discard_inline_completion(
5290 &mut self,
5291 should_report_inline_completion_event: bool,
5292 cx: &mut Context<Self>,
5293 ) -> bool {
5294 if should_report_inline_completion_event {
5295 let completion_id = self
5296 .active_inline_completion
5297 .as_ref()
5298 .and_then(|active_completion| active_completion.completion_id.clone());
5299
5300 self.report_inline_completion_event(completion_id, false, cx);
5301 }
5302
5303 if let Some(provider) = self.edit_prediction_provider() {
5304 provider.discard(cx);
5305 }
5306
5307 self.take_active_inline_completion(cx)
5308 }
5309
5310 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5311 let Some(provider) = self.edit_prediction_provider() else {
5312 return;
5313 };
5314
5315 let Some((_, buffer, _)) = self
5316 .buffer
5317 .read(cx)
5318 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5319 else {
5320 return;
5321 };
5322
5323 let extension = buffer
5324 .read(cx)
5325 .file()
5326 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5327
5328 let event_type = match accepted {
5329 true => "Edit Prediction Accepted",
5330 false => "Edit Prediction Discarded",
5331 };
5332 telemetry::event!(
5333 event_type,
5334 provider = provider.name(),
5335 prediction_id = id,
5336 suggestion_accepted = accepted,
5337 file_extension = extension,
5338 );
5339 }
5340
5341 pub fn has_active_inline_completion(&self) -> bool {
5342 self.active_inline_completion.is_some()
5343 }
5344
5345 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5346 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5347 return false;
5348 };
5349
5350 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5351 self.clear_highlights::<InlineCompletionHighlight>(cx);
5352 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5353 true
5354 }
5355
5356 /// Returns true when we're displaying the edit prediction popover below the cursor
5357 /// like we are not previewing and the LSP autocomplete menu is visible
5358 /// or we are in `when_holding_modifier` mode.
5359 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5360 if self.edit_prediction_preview_is_active()
5361 || !self.show_edit_predictions_in_menu()
5362 || !self.edit_predictions_enabled()
5363 {
5364 return false;
5365 }
5366
5367 if self.has_visible_completions_menu() {
5368 return true;
5369 }
5370
5371 has_completion && self.edit_prediction_requires_modifier()
5372 }
5373
5374 fn handle_modifiers_changed(
5375 &mut self,
5376 modifiers: Modifiers,
5377 position_map: &PositionMap,
5378 window: &mut Window,
5379 cx: &mut Context<Self>,
5380 ) {
5381 if self.show_edit_predictions_in_menu() {
5382 self.update_edit_prediction_preview(&modifiers, window, cx);
5383 }
5384
5385 self.update_selection_mode(&modifiers, position_map, window, cx);
5386
5387 let mouse_position = window.mouse_position();
5388 if !position_map.text_hitbox.is_hovered(window) {
5389 return;
5390 }
5391
5392 self.update_hovered_link(
5393 position_map.point_for_position(mouse_position),
5394 &position_map.snapshot,
5395 modifiers,
5396 window,
5397 cx,
5398 )
5399 }
5400
5401 fn update_selection_mode(
5402 &mut self,
5403 modifiers: &Modifiers,
5404 position_map: &PositionMap,
5405 window: &mut Window,
5406 cx: &mut Context<Self>,
5407 ) {
5408 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5409 return;
5410 }
5411
5412 let mouse_position = window.mouse_position();
5413 let point_for_position = position_map.point_for_position(mouse_position);
5414 let position = point_for_position.previous_valid;
5415
5416 self.select(
5417 SelectPhase::BeginColumnar {
5418 position,
5419 reset: false,
5420 goal_column: point_for_position.exact_unclipped.column(),
5421 },
5422 window,
5423 cx,
5424 );
5425 }
5426
5427 fn update_edit_prediction_preview(
5428 &mut self,
5429 modifiers: &Modifiers,
5430 window: &mut Window,
5431 cx: &mut Context<Self>,
5432 ) {
5433 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5434 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5435 return;
5436 };
5437
5438 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5439 if matches!(
5440 self.edit_prediction_preview,
5441 EditPredictionPreview::Inactive { .. }
5442 ) {
5443 self.edit_prediction_preview = EditPredictionPreview::Active {
5444 previous_scroll_position: None,
5445 since: Instant::now(),
5446 };
5447
5448 self.update_visible_inline_completion(window, cx);
5449 cx.notify();
5450 }
5451 } else if let EditPredictionPreview::Active {
5452 previous_scroll_position,
5453 since,
5454 } = self.edit_prediction_preview
5455 {
5456 if let (Some(previous_scroll_position), Some(position_map)) =
5457 (previous_scroll_position, self.last_position_map.as_ref())
5458 {
5459 self.set_scroll_position(
5460 previous_scroll_position
5461 .scroll_position(&position_map.snapshot.display_snapshot),
5462 window,
5463 cx,
5464 );
5465 }
5466
5467 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5468 released_too_fast: since.elapsed() < Duration::from_millis(200),
5469 };
5470 self.clear_row_highlights::<EditPredictionPreview>();
5471 self.update_visible_inline_completion(window, cx);
5472 cx.notify();
5473 }
5474 }
5475
5476 fn update_visible_inline_completion(
5477 &mut self,
5478 _window: &mut Window,
5479 cx: &mut Context<Self>,
5480 ) -> Option<()> {
5481 let selection = self.selections.newest_anchor();
5482 let cursor = selection.head();
5483 let multibuffer = self.buffer.read(cx).snapshot(cx);
5484 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5485 let excerpt_id = cursor.excerpt_id;
5486
5487 let show_in_menu = self.show_edit_predictions_in_menu();
5488 let completions_menu_has_precedence = !show_in_menu
5489 && (self.context_menu.borrow().is_some()
5490 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5491
5492 if completions_menu_has_precedence
5493 || !offset_selection.is_empty()
5494 || self
5495 .active_inline_completion
5496 .as_ref()
5497 .map_or(false, |completion| {
5498 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5499 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5500 !invalidation_range.contains(&offset_selection.head())
5501 })
5502 {
5503 self.discard_inline_completion(false, cx);
5504 return None;
5505 }
5506
5507 self.take_active_inline_completion(cx);
5508 let Some(provider) = self.edit_prediction_provider() else {
5509 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5510 return None;
5511 };
5512
5513 let (buffer, cursor_buffer_position) =
5514 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5515
5516 self.edit_prediction_settings =
5517 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5518
5519 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5520
5521 if self.edit_prediction_indent_conflict {
5522 let cursor_point = cursor.to_point(&multibuffer);
5523
5524 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5525
5526 if let Some((_, indent)) = indents.iter().next() {
5527 if indent.len == cursor_point.column {
5528 self.edit_prediction_indent_conflict = false;
5529 }
5530 }
5531 }
5532
5533 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5534 let edits = inline_completion
5535 .edits
5536 .into_iter()
5537 .flat_map(|(range, new_text)| {
5538 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5539 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5540 Some((start..end, new_text))
5541 })
5542 .collect::<Vec<_>>();
5543 if edits.is_empty() {
5544 return None;
5545 }
5546
5547 let first_edit_start = edits.first().unwrap().0.start;
5548 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5549 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5550
5551 let last_edit_end = edits.last().unwrap().0.end;
5552 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5553 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5554
5555 let cursor_row = cursor.to_point(&multibuffer).row;
5556
5557 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5558
5559 let mut inlay_ids = Vec::new();
5560 let invalidation_row_range;
5561 let move_invalidation_row_range = if cursor_row < edit_start_row {
5562 Some(cursor_row..edit_end_row)
5563 } else if cursor_row > edit_end_row {
5564 Some(edit_start_row..cursor_row)
5565 } else {
5566 None
5567 };
5568 let is_move =
5569 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5570 let completion = if is_move {
5571 invalidation_row_range =
5572 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5573 let target = first_edit_start;
5574 InlineCompletion::Move { target, snapshot }
5575 } else {
5576 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5577 && !self.inline_completions_hidden_for_vim_mode;
5578
5579 if show_completions_in_buffer {
5580 if edits
5581 .iter()
5582 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5583 {
5584 let mut inlays = Vec::new();
5585 for (range, new_text) in &edits {
5586 let inlay = Inlay::inline_completion(
5587 post_inc(&mut self.next_inlay_id),
5588 range.start,
5589 new_text.as_str(),
5590 );
5591 inlay_ids.push(inlay.id);
5592 inlays.push(inlay);
5593 }
5594
5595 self.splice_inlays(&[], inlays, cx);
5596 } else {
5597 let background_color = cx.theme().status().deleted_background;
5598 self.highlight_text::<InlineCompletionHighlight>(
5599 edits.iter().map(|(range, _)| range.clone()).collect(),
5600 HighlightStyle {
5601 background_color: Some(background_color),
5602 ..Default::default()
5603 },
5604 cx,
5605 );
5606 }
5607 }
5608
5609 invalidation_row_range = edit_start_row..edit_end_row;
5610
5611 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5612 if provider.show_tab_accept_marker() {
5613 EditDisplayMode::TabAccept
5614 } else {
5615 EditDisplayMode::Inline
5616 }
5617 } else {
5618 EditDisplayMode::DiffPopover
5619 };
5620
5621 InlineCompletion::Edit {
5622 edits,
5623 edit_preview: inline_completion.edit_preview,
5624 display_mode,
5625 snapshot,
5626 }
5627 };
5628
5629 let invalidation_range = multibuffer
5630 .anchor_before(Point::new(invalidation_row_range.start, 0))
5631 ..multibuffer.anchor_after(Point::new(
5632 invalidation_row_range.end,
5633 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5634 ));
5635
5636 self.stale_inline_completion_in_menu = None;
5637 self.active_inline_completion = Some(InlineCompletionState {
5638 inlay_ids,
5639 completion,
5640 completion_id: inline_completion.id,
5641 invalidation_range,
5642 });
5643
5644 cx.notify();
5645
5646 Some(())
5647 }
5648
5649 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5650 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5651 }
5652
5653 fn render_code_actions_indicator(
5654 &self,
5655 _style: &EditorStyle,
5656 row: DisplayRow,
5657 is_active: bool,
5658 cx: &mut Context<Self>,
5659 ) -> Option<IconButton> {
5660 if self.available_code_actions.is_some() {
5661 Some(
5662 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5663 .shape(ui::IconButtonShape::Square)
5664 .icon_size(IconSize::XSmall)
5665 .icon_color(Color::Muted)
5666 .toggle_state(is_active)
5667 .tooltip({
5668 let focus_handle = self.focus_handle.clone();
5669 move |window, cx| {
5670 Tooltip::for_action_in(
5671 "Toggle Code Actions",
5672 &ToggleCodeActions {
5673 deployed_from_indicator: None,
5674 },
5675 &focus_handle,
5676 window,
5677 cx,
5678 )
5679 }
5680 })
5681 .on_click(cx.listener(move |editor, _e, window, cx| {
5682 window.focus(&editor.focus_handle(cx));
5683 editor.toggle_code_actions(
5684 &ToggleCodeActions {
5685 deployed_from_indicator: Some(row),
5686 },
5687 window,
5688 cx,
5689 );
5690 })),
5691 )
5692 } else {
5693 None
5694 }
5695 }
5696
5697 fn clear_tasks(&mut self) {
5698 self.tasks.clear()
5699 }
5700
5701 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5702 if self.tasks.insert(key, value).is_some() {
5703 // This case should hopefully be rare, but just in case...
5704 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5705 }
5706 }
5707
5708 fn build_tasks_context(
5709 project: &Entity<Project>,
5710 buffer: &Entity<Buffer>,
5711 buffer_row: u32,
5712 tasks: &Arc<RunnableTasks>,
5713 cx: &mut Context<Self>,
5714 ) -> Task<Option<task::TaskContext>> {
5715 let position = Point::new(buffer_row, tasks.column);
5716 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5717 let location = Location {
5718 buffer: buffer.clone(),
5719 range: range_start..range_start,
5720 };
5721 // Fill in the environmental variables from the tree-sitter captures
5722 let mut captured_task_variables = TaskVariables::default();
5723 for (capture_name, value) in tasks.extra_variables.clone() {
5724 captured_task_variables.insert(
5725 task::VariableName::Custom(capture_name.into()),
5726 value.clone(),
5727 );
5728 }
5729 project.update(cx, |project, cx| {
5730 project.task_store().update(cx, |task_store, cx| {
5731 task_store.task_context_for_location(captured_task_variables, location, cx)
5732 })
5733 })
5734 }
5735
5736 pub fn spawn_nearest_task(
5737 &mut self,
5738 action: &SpawnNearestTask,
5739 window: &mut Window,
5740 cx: &mut Context<Self>,
5741 ) {
5742 let Some((workspace, _)) = self.workspace.clone() else {
5743 return;
5744 };
5745 let Some(project) = self.project.clone() else {
5746 return;
5747 };
5748
5749 // Try to find a closest, enclosing node using tree-sitter that has a
5750 // task
5751 let Some((buffer, buffer_row, tasks)) = self
5752 .find_enclosing_node_task(cx)
5753 // Or find the task that's closest in row-distance.
5754 .or_else(|| self.find_closest_task(cx))
5755 else {
5756 return;
5757 };
5758
5759 let reveal_strategy = action.reveal;
5760 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5761 cx.spawn_in(window, |_, mut cx| async move {
5762 let context = task_context.await?;
5763 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5764
5765 let resolved = resolved_task.resolved.as_mut()?;
5766 resolved.reveal = reveal_strategy;
5767
5768 workspace
5769 .update(&mut cx, |workspace, cx| {
5770 workspace::tasks::schedule_resolved_task(
5771 workspace,
5772 task_source_kind,
5773 resolved_task,
5774 false,
5775 cx,
5776 );
5777 })
5778 .ok()
5779 })
5780 .detach();
5781 }
5782
5783 fn find_closest_task(
5784 &mut self,
5785 cx: &mut Context<Self>,
5786 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5787 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5788
5789 let ((buffer_id, row), tasks) = self
5790 .tasks
5791 .iter()
5792 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5793
5794 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5795 let tasks = Arc::new(tasks.to_owned());
5796 Some((buffer, *row, tasks))
5797 }
5798
5799 fn find_enclosing_node_task(
5800 &mut self,
5801 cx: &mut Context<Self>,
5802 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5803 let snapshot = self.buffer.read(cx).snapshot(cx);
5804 let offset = self.selections.newest::<usize>(cx).head();
5805 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5806 let buffer_id = excerpt.buffer().remote_id();
5807
5808 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5809 let mut cursor = layer.node().walk();
5810
5811 while cursor.goto_first_child_for_byte(offset).is_some() {
5812 if cursor.node().end_byte() == offset {
5813 cursor.goto_next_sibling();
5814 }
5815 }
5816
5817 // Ascend to the smallest ancestor that contains the range and has a task.
5818 loop {
5819 let node = cursor.node();
5820 let node_range = node.byte_range();
5821 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5822
5823 // Check if this node contains our offset
5824 if node_range.start <= offset && node_range.end >= offset {
5825 // If it contains offset, check for task
5826 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5827 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5828 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5829 }
5830 }
5831
5832 if !cursor.goto_parent() {
5833 break;
5834 }
5835 }
5836 None
5837 }
5838
5839 fn render_run_indicator(
5840 &self,
5841 _style: &EditorStyle,
5842 is_active: bool,
5843 row: DisplayRow,
5844 cx: &mut Context<Self>,
5845 ) -> IconButton {
5846 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5847 .shape(ui::IconButtonShape::Square)
5848 .icon_size(IconSize::XSmall)
5849 .icon_color(Color::Muted)
5850 .toggle_state(is_active)
5851 .on_click(cx.listener(move |editor, _e, window, cx| {
5852 window.focus(&editor.focus_handle(cx));
5853 editor.toggle_code_actions(
5854 &ToggleCodeActions {
5855 deployed_from_indicator: Some(row),
5856 },
5857 window,
5858 cx,
5859 );
5860 }))
5861 }
5862
5863 pub fn context_menu_visible(&self) -> bool {
5864 !self.edit_prediction_preview_is_active()
5865 && self
5866 .context_menu
5867 .borrow()
5868 .as_ref()
5869 .map_or(false, |menu| menu.visible())
5870 }
5871
5872 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5873 self.context_menu
5874 .borrow()
5875 .as_ref()
5876 .map(|menu| menu.origin())
5877 }
5878
5879 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5880 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5881
5882 #[allow(clippy::too_many_arguments)]
5883 fn render_edit_prediction_popover(
5884 &mut self,
5885 text_bounds: &Bounds<Pixels>,
5886 content_origin: gpui::Point<Pixels>,
5887 editor_snapshot: &EditorSnapshot,
5888 visible_row_range: Range<DisplayRow>,
5889 scroll_top: f32,
5890 scroll_bottom: f32,
5891 line_layouts: &[LineWithInvisibles],
5892 line_height: Pixels,
5893 scroll_pixel_position: gpui::Point<Pixels>,
5894 newest_selection_head: Option<DisplayPoint>,
5895 editor_width: Pixels,
5896 style: &EditorStyle,
5897 window: &mut Window,
5898 cx: &mut App,
5899 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5900 let active_inline_completion = self.active_inline_completion.as_ref()?;
5901
5902 if self.edit_prediction_visible_in_cursor_popover(true) {
5903 return None;
5904 }
5905
5906 match &active_inline_completion.completion {
5907 InlineCompletion::Move { target, .. } => {
5908 let target_display_point = target.to_display_point(editor_snapshot);
5909
5910 if self.edit_prediction_requires_modifier() {
5911 if !self.edit_prediction_preview_is_active() {
5912 return None;
5913 }
5914
5915 self.render_edit_prediction_modifier_jump_popover(
5916 text_bounds,
5917 content_origin,
5918 visible_row_range,
5919 line_layouts,
5920 line_height,
5921 scroll_pixel_position,
5922 newest_selection_head,
5923 target_display_point,
5924 window,
5925 cx,
5926 )
5927 } else {
5928 self.render_edit_prediction_eager_jump_popover(
5929 text_bounds,
5930 content_origin,
5931 editor_snapshot,
5932 visible_row_range,
5933 scroll_top,
5934 scroll_bottom,
5935 line_height,
5936 scroll_pixel_position,
5937 target_display_point,
5938 editor_width,
5939 window,
5940 cx,
5941 )
5942 }
5943 }
5944 InlineCompletion::Edit {
5945 display_mode: EditDisplayMode::Inline,
5946 ..
5947 } => None,
5948 InlineCompletion::Edit {
5949 display_mode: EditDisplayMode::TabAccept,
5950 edits,
5951 ..
5952 } => {
5953 let range = &edits.first()?.0;
5954 let target_display_point = range.end.to_display_point(editor_snapshot);
5955
5956 self.render_edit_prediction_end_of_line_popover(
5957 "Accept",
5958 editor_snapshot,
5959 visible_row_range,
5960 target_display_point,
5961 line_height,
5962 scroll_pixel_position,
5963 content_origin,
5964 editor_width,
5965 window,
5966 cx,
5967 )
5968 }
5969 InlineCompletion::Edit {
5970 edits,
5971 edit_preview,
5972 display_mode: EditDisplayMode::DiffPopover,
5973 snapshot,
5974 } => self.render_edit_prediction_diff_popover(
5975 text_bounds,
5976 content_origin,
5977 editor_snapshot,
5978 visible_row_range,
5979 line_layouts,
5980 line_height,
5981 scroll_pixel_position,
5982 newest_selection_head,
5983 editor_width,
5984 style,
5985 edits,
5986 edit_preview,
5987 snapshot,
5988 window,
5989 cx,
5990 ),
5991 }
5992 }
5993
5994 #[allow(clippy::too_many_arguments)]
5995 fn render_edit_prediction_modifier_jump_popover(
5996 &mut self,
5997 text_bounds: &Bounds<Pixels>,
5998 content_origin: gpui::Point<Pixels>,
5999 visible_row_range: Range<DisplayRow>,
6000 line_layouts: &[LineWithInvisibles],
6001 line_height: Pixels,
6002 scroll_pixel_position: gpui::Point<Pixels>,
6003 newest_selection_head: Option<DisplayPoint>,
6004 target_display_point: DisplayPoint,
6005 window: &mut Window,
6006 cx: &mut App,
6007 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6008 let scrolled_content_origin =
6009 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6010
6011 const SCROLL_PADDING_Y: Pixels = px(12.);
6012
6013 if target_display_point.row() < visible_row_range.start {
6014 return self.render_edit_prediction_scroll_popover(
6015 |_| SCROLL_PADDING_Y,
6016 IconName::ArrowUp,
6017 visible_row_range,
6018 line_layouts,
6019 newest_selection_head,
6020 scrolled_content_origin,
6021 window,
6022 cx,
6023 );
6024 } else if target_display_point.row() >= visible_row_range.end {
6025 return self.render_edit_prediction_scroll_popover(
6026 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6027 IconName::ArrowDown,
6028 visible_row_range,
6029 line_layouts,
6030 newest_selection_head,
6031 scrolled_content_origin,
6032 window,
6033 cx,
6034 );
6035 }
6036
6037 const POLE_WIDTH: Pixels = px(2.);
6038
6039 let line_layout =
6040 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6041 let target_column = target_display_point.column() as usize;
6042
6043 let target_x = line_layout.x_for_index(target_column);
6044 let target_y =
6045 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6046
6047 let flag_on_right = target_x < text_bounds.size.width / 2.;
6048
6049 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6050 border_color.l += 0.001;
6051
6052 let mut element = v_flex()
6053 .items_end()
6054 .when(flag_on_right, |el| el.items_start())
6055 .child(if flag_on_right {
6056 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6057 .rounded_bl(px(0.))
6058 .rounded_tl(px(0.))
6059 .border_l_2()
6060 .border_color(border_color)
6061 } else {
6062 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6063 .rounded_br(px(0.))
6064 .rounded_tr(px(0.))
6065 .border_r_2()
6066 .border_color(border_color)
6067 })
6068 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6069 .into_any();
6070
6071 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6072
6073 let mut origin = scrolled_content_origin + point(target_x, target_y)
6074 - point(
6075 if flag_on_right {
6076 POLE_WIDTH
6077 } else {
6078 size.width - POLE_WIDTH
6079 },
6080 size.height - line_height,
6081 );
6082
6083 origin.x = origin.x.max(content_origin.x);
6084
6085 element.prepaint_at(origin, window, cx);
6086
6087 Some((element, origin))
6088 }
6089
6090 #[allow(clippy::too_many_arguments)]
6091 fn render_edit_prediction_scroll_popover(
6092 &mut self,
6093 to_y: impl Fn(Size<Pixels>) -> Pixels,
6094 scroll_icon: IconName,
6095 visible_row_range: Range<DisplayRow>,
6096 line_layouts: &[LineWithInvisibles],
6097 newest_selection_head: Option<DisplayPoint>,
6098 scrolled_content_origin: gpui::Point<Pixels>,
6099 window: &mut Window,
6100 cx: &mut App,
6101 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6102 let mut element = self
6103 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6104 .into_any();
6105
6106 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6107
6108 let cursor = newest_selection_head?;
6109 let cursor_row_layout =
6110 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6111 let cursor_column = cursor.column() as usize;
6112
6113 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6114
6115 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6116
6117 element.prepaint_at(origin, window, cx);
6118 Some((element, origin))
6119 }
6120
6121 #[allow(clippy::too_many_arguments)]
6122 fn render_edit_prediction_eager_jump_popover(
6123 &mut self,
6124 text_bounds: &Bounds<Pixels>,
6125 content_origin: gpui::Point<Pixels>,
6126 editor_snapshot: &EditorSnapshot,
6127 visible_row_range: Range<DisplayRow>,
6128 scroll_top: f32,
6129 scroll_bottom: f32,
6130 line_height: Pixels,
6131 scroll_pixel_position: gpui::Point<Pixels>,
6132 target_display_point: DisplayPoint,
6133 editor_width: Pixels,
6134 window: &mut Window,
6135 cx: &mut App,
6136 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6137 if target_display_point.row().as_f32() < scroll_top {
6138 let mut element = self
6139 .render_edit_prediction_line_popover(
6140 "Jump to Edit",
6141 Some(IconName::ArrowUp),
6142 window,
6143 cx,
6144 )?
6145 .into_any();
6146
6147 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6148 let offset = point(
6149 (text_bounds.size.width - size.width) / 2.,
6150 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6151 );
6152
6153 let origin = text_bounds.origin + offset;
6154 element.prepaint_at(origin, window, cx);
6155 Some((element, origin))
6156 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6157 let mut element = self
6158 .render_edit_prediction_line_popover(
6159 "Jump to Edit",
6160 Some(IconName::ArrowDown),
6161 window,
6162 cx,
6163 )?
6164 .into_any();
6165
6166 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6167 let offset = point(
6168 (text_bounds.size.width - size.width) / 2.,
6169 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6170 );
6171
6172 let origin = text_bounds.origin + offset;
6173 element.prepaint_at(origin, window, cx);
6174 Some((element, origin))
6175 } else {
6176 self.render_edit_prediction_end_of_line_popover(
6177 "Jump to Edit",
6178 editor_snapshot,
6179 visible_row_range,
6180 target_display_point,
6181 line_height,
6182 scroll_pixel_position,
6183 content_origin,
6184 editor_width,
6185 window,
6186 cx,
6187 )
6188 }
6189 }
6190
6191 #[allow(clippy::too_many_arguments)]
6192 fn render_edit_prediction_end_of_line_popover(
6193 self: &mut Editor,
6194 label: &'static str,
6195 editor_snapshot: &EditorSnapshot,
6196 visible_row_range: Range<DisplayRow>,
6197 target_display_point: DisplayPoint,
6198 line_height: Pixels,
6199 scroll_pixel_position: gpui::Point<Pixels>,
6200 content_origin: gpui::Point<Pixels>,
6201 editor_width: Pixels,
6202 window: &mut Window,
6203 cx: &mut App,
6204 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6205 let target_line_end = DisplayPoint::new(
6206 target_display_point.row(),
6207 editor_snapshot.line_len(target_display_point.row()),
6208 );
6209
6210 let mut element = self
6211 .render_edit_prediction_line_popover(label, None, window, cx)?
6212 .into_any();
6213
6214 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6215
6216 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6217
6218 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6219 let mut origin = start_point
6220 + line_origin
6221 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6222 origin.x = origin.x.max(content_origin.x);
6223
6224 let max_x = content_origin.x + editor_width - size.width;
6225
6226 if origin.x > max_x {
6227 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6228
6229 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6230 origin.y += offset;
6231 IconName::ArrowUp
6232 } else {
6233 origin.y -= offset;
6234 IconName::ArrowDown
6235 };
6236
6237 element = self
6238 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6239 .into_any();
6240
6241 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6242
6243 origin.x = content_origin.x + editor_width - size.width - px(2.);
6244 }
6245
6246 element.prepaint_at(origin, window, cx);
6247 Some((element, origin))
6248 }
6249
6250 #[allow(clippy::too_many_arguments)]
6251 fn render_edit_prediction_diff_popover(
6252 self: &Editor,
6253 text_bounds: &Bounds<Pixels>,
6254 content_origin: gpui::Point<Pixels>,
6255 editor_snapshot: &EditorSnapshot,
6256 visible_row_range: Range<DisplayRow>,
6257 line_layouts: &[LineWithInvisibles],
6258 line_height: Pixels,
6259 scroll_pixel_position: gpui::Point<Pixels>,
6260 newest_selection_head: Option<DisplayPoint>,
6261 editor_width: Pixels,
6262 style: &EditorStyle,
6263 edits: &Vec<(Range<Anchor>, String)>,
6264 edit_preview: &Option<language::EditPreview>,
6265 snapshot: &language::BufferSnapshot,
6266 window: &mut Window,
6267 cx: &mut App,
6268 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6269 let edit_start = edits
6270 .first()
6271 .unwrap()
6272 .0
6273 .start
6274 .to_display_point(editor_snapshot);
6275 let edit_end = edits
6276 .last()
6277 .unwrap()
6278 .0
6279 .end
6280 .to_display_point(editor_snapshot);
6281
6282 let is_visible = visible_row_range.contains(&edit_start.row())
6283 || visible_row_range.contains(&edit_end.row());
6284 if !is_visible {
6285 return None;
6286 }
6287
6288 let highlighted_edits =
6289 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6290
6291 let styled_text = highlighted_edits.to_styled_text(&style.text);
6292 let line_count = highlighted_edits.text.lines().count();
6293
6294 const BORDER_WIDTH: Pixels = px(1.);
6295
6296 let mut element = h_flex()
6297 .items_start()
6298 .child(
6299 h_flex()
6300 .bg(cx.theme().colors().editor_background)
6301 .border(BORDER_WIDTH)
6302 .shadow_sm()
6303 .border_color(cx.theme().colors().border)
6304 .rounded_l_lg()
6305 .when(line_count > 1, |el| el.rounded_br_lg())
6306 .pr_1()
6307 .child(styled_text),
6308 )
6309 .child(
6310 h_flex()
6311 .h(line_height + BORDER_WIDTH * px(2.))
6312 .px_1p5()
6313 .gap_1()
6314 // Workaround: For some reason, there's a gap if we don't do this
6315 .ml(-BORDER_WIDTH)
6316 .shadow(smallvec![gpui::BoxShadow {
6317 color: gpui::black().opacity(0.05),
6318 offset: point(px(1.), px(1.)),
6319 blur_radius: px(2.),
6320 spread_radius: px(0.),
6321 }])
6322 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6323 .border(BORDER_WIDTH)
6324 .border_color(cx.theme().colors().border)
6325 .rounded_r_lg()
6326 .children(self.render_edit_prediction_accept_keybind(window, cx)),
6327 )
6328 .into_any();
6329
6330 let longest_row =
6331 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6332 let longest_line_width = if visible_row_range.contains(&longest_row) {
6333 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6334 } else {
6335 layout_line(
6336 longest_row,
6337 editor_snapshot,
6338 style,
6339 editor_width,
6340 |_| false,
6341 window,
6342 cx,
6343 )
6344 .width
6345 };
6346
6347 let viewport_bounds =
6348 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6349 right: -EditorElement::SCROLLBAR_WIDTH,
6350 ..Default::default()
6351 });
6352
6353 let x_after_longest =
6354 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6355 - scroll_pixel_position.x;
6356
6357 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6358
6359 // Fully visible if it can be displayed within the window (allow overlapping other
6360 // panes). However, this is only allowed if the popover starts within text_bounds.
6361 let can_position_to_the_right = x_after_longest < text_bounds.right()
6362 && x_after_longest + element_bounds.width < viewport_bounds.right();
6363
6364 let mut origin = if can_position_to_the_right {
6365 point(
6366 x_after_longest,
6367 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6368 - scroll_pixel_position.y,
6369 )
6370 } else {
6371 let cursor_row = newest_selection_head.map(|head| head.row());
6372 let above_edit = edit_start
6373 .row()
6374 .0
6375 .checked_sub(line_count as u32)
6376 .map(DisplayRow);
6377 let below_edit = Some(edit_end.row() + 1);
6378 let above_cursor =
6379 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6380 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6381
6382 // Place the edit popover adjacent to the edit if there is a location
6383 // available that is onscreen and does not obscure the cursor. Otherwise,
6384 // place it adjacent to the cursor.
6385 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6386 .into_iter()
6387 .flatten()
6388 .find(|&start_row| {
6389 let end_row = start_row + line_count as u32;
6390 visible_row_range.contains(&start_row)
6391 && visible_row_range.contains(&end_row)
6392 && cursor_row.map_or(true, |cursor_row| {
6393 !((start_row..end_row).contains(&cursor_row))
6394 })
6395 })?;
6396
6397 content_origin
6398 + point(
6399 -scroll_pixel_position.x,
6400 row_target.as_f32() * line_height - scroll_pixel_position.y,
6401 )
6402 };
6403
6404 origin.x -= BORDER_WIDTH;
6405
6406 window.defer_draw(element, origin, 1);
6407
6408 // Do not return an element, since it will already be drawn due to defer_draw.
6409 None
6410 }
6411
6412 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6413 px(30.)
6414 }
6415
6416 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6417 if self.read_only(cx) {
6418 cx.theme().players().read_only()
6419 } else {
6420 self.style.as_ref().unwrap().local_player
6421 }
6422 }
6423
6424 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
6425 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6426 let accept_keystroke = accept_binding.keystroke()?;
6427
6428 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6429
6430 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6431 Color::Accent
6432 } else {
6433 Color::Muted
6434 };
6435
6436 h_flex()
6437 .px_0p5()
6438 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6439 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6440 .text_size(TextSize::XSmall.rems(cx))
6441 .child(h_flex().children(ui::render_modifiers(
6442 &accept_keystroke.modifiers,
6443 PlatformStyle::platform(),
6444 Some(modifiers_color),
6445 Some(IconSize::XSmall.rems().into()),
6446 true,
6447 )))
6448 .when(is_platform_style_mac, |parent| {
6449 parent.child(accept_keystroke.key.clone())
6450 })
6451 .when(!is_platform_style_mac, |parent| {
6452 parent.child(
6453 Key::new(
6454 util::capitalize(&accept_keystroke.key),
6455 Some(Color::Default),
6456 )
6457 .size(Some(IconSize::XSmall.rems().into())),
6458 )
6459 })
6460 .into()
6461 }
6462
6463 fn render_edit_prediction_line_popover(
6464 &self,
6465 label: impl Into<SharedString>,
6466 icon: Option<IconName>,
6467 window: &mut Window,
6468 cx: &App,
6469 ) -> Option<Div> {
6470 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6471
6472 let result = h_flex()
6473 .py_0p5()
6474 .pl_1()
6475 .pr(padding_right)
6476 .gap_1()
6477 .rounded(px(6.))
6478 .border_1()
6479 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6480 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6481 .shadow_sm()
6482 .children(self.render_edit_prediction_accept_keybind(window, cx))
6483 .child(Label::new(label).size(LabelSize::Small))
6484 .when_some(icon, |element, icon| {
6485 element.child(
6486 div()
6487 .mt(px(1.5))
6488 .child(Icon::new(icon).size(IconSize::Small)),
6489 )
6490 });
6491
6492 Some(result)
6493 }
6494
6495 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6496 let accent_color = cx.theme().colors().text_accent;
6497 let editor_bg_color = cx.theme().colors().editor_background;
6498 editor_bg_color.blend(accent_color.opacity(0.1))
6499 }
6500
6501 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6502 let accent_color = cx.theme().colors().text_accent;
6503 let editor_bg_color = cx.theme().colors().editor_background;
6504 editor_bg_color.blend(accent_color.opacity(0.6))
6505 }
6506
6507 #[allow(clippy::too_many_arguments)]
6508 fn render_edit_prediction_cursor_popover(
6509 &self,
6510 min_width: Pixels,
6511 max_width: Pixels,
6512 cursor_point: Point,
6513 style: &EditorStyle,
6514 accept_keystroke: Option<&gpui::Keystroke>,
6515 _window: &Window,
6516 cx: &mut Context<Editor>,
6517 ) -> Option<AnyElement> {
6518 let provider = self.edit_prediction_provider.as_ref()?;
6519
6520 if provider.provider.needs_terms_acceptance(cx) {
6521 return Some(
6522 h_flex()
6523 .min_w(min_width)
6524 .flex_1()
6525 .px_2()
6526 .py_1()
6527 .gap_3()
6528 .elevation_2(cx)
6529 .hover(|style| style.bg(cx.theme().colors().element_hover))
6530 .id("accept-terms")
6531 .cursor_pointer()
6532 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6533 .on_click(cx.listener(|this, _event, window, cx| {
6534 cx.stop_propagation();
6535 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6536 window.dispatch_action(
6537 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6538 cx,
6539 );
6540 }))
6541 .child(
6542 h_flex()
6543 .flex_1()
6544 .gap_2()
6545 .child(Icon::new(IconName::ZedPredict))
6546 .child(Label::new("Accept Terms of Service"))
6547 .child(div().w_full())
6548 .child(
6549 Icon::new(IconName::ArrowUpRight)
6550 .color(Color::Muted)
6551 .size(IconSize::Small),
6552 )
6553 .into_any_element(),
6554 )
6555 .into_any(),
6556 );
6557 }
6558
6559 let is_refreshing = provider.provider.is_refreshing(cx);
6560
6561 fn pending_completion_container() -> Div {
6562 h_flex()
6563 .h_full()
6564 .flex_1()
6565 .gap_2()
6566 .child(Icon::new(IconName::ZedPredict))
6567 }
6568
6569 let completion = match &self.active_inline_completion {
6570 Some(prediction) => {
6571 if !self.has_visible_completions_menu() {
6572 const RADIUS: Pixels = px(6.);
6573 const BORDER_WIDTH: Pixels = px(1.);
6574
6575 return Some(
6576 h_flex()
6577 .elevation_2(cx)
6578 .border(BORDER_WIDTH)
6579 .border_color(cx.theme().colors().border)
6580 .rounded(RADIUS)
6581 .rounded_tl(px(0.))
6582 .overflow_hidden()
6583 .child(div().px_1p5().child(match &prediction.completion {
6584 InlineCompletion::Move { target, snapshot } => {
6585 use text::ToPoint as _;
6586 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6587 {
6588 Icon::new(IconName::ZedPredictDown)
6589 } else {
6590 Icon::new(IconName::ZedPredictUp)
6591 }
6592 }
6593 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6594 }))
6595 .child(
6596 h_flex()
6597 .gap_1()
6598 .py_1()
6599 .px_2()
6600 .rounded_r(RADIUS - BORDER_WIDTH)
6601 .border_l_1()
6602 .border_color(cx.theme().colors().border)
6603 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6604 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6605 el.child(
6606 Label::new("Hold")
6607 .size(LabelSize::Small)
6608 .line_height_style(LineHeightStyle::UiLabel),
6609 )
6610 })
6611 .child(h_flex().children(ui::render_modifiers(
6612 &accept_keystroke?.modifiers,
6613 PlatformStyle::platform(),
6614 Some(Color::Default),
6615 Some(IconSize::XSmall.rems().into()),
6616 false,
6617 ))),
6618 )
6619 .into_any(),
6620 );
6621 }
6622
6623 self.render_edit_prediction_cursor_popover_preview(
6624 prediction,
6625 cursor_point,
6626 style,
6627 cx,
6628 )?
6629 }
6630
6631 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6632 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6633 stale_completion,
6634 cursor_point,
6635 style,
6636 cx,
6637 )?,
6638
6639 None => {
6640 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6641 }
6642 },
6643
6644 None => pending_completion_container().child(Label::new("No Prediction")),
6645 };
6646
6647 let completion = if is_refreshing {
6648 completion
6649 .with_animation(
6650 "loading-completion",
6651 Animation::new(Duration::from_secs(2))
6652 .repeat()
6653 .with_easing(pulsating_between(0.4, 0.8)),
6654 |label, delta| label.opacity(delta),
6655 )
6656 .into_any_element()
6657 } else {
6658 completion.into_any_element()
6659 };
6660
6661 let has_completion = self.active_inline_completion.is_some();
6662
6663 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6664 Some(
6665 h_flex()
6666 .min_w(min_width)
6667 .max_w(max_width)
6668 .flex_1()
6669 .elevation_2(cx)
6670 .border_color(cx.theme().colors().border)
6671 .child(
6672 div()
6673 .flex_1()
6674 .py_1()
6675 .px_2()
6676 .overflow_hidden()
6677 .child(completion),
6678 )
6679 .when_some(accept_keystroke, |el, accept_keystroke| {
6680 if !accept_keystroke.modifiers.modified() {
6681 return el;
6682 }
6683
6684 el.child(
6685 h_flex()
6686 .h_full()
6687 .border_l_1()
6688 .rounded_r_lg()
6689 .border_color(cx.theme().colors().border)
6690 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6691 .gap_1()
6692 .py_1()
6693 .px_2()
6694 .child(
6695 h_flex()
6696 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6697 .when(is_platform_style_mac, |parent| parent.gap_1())
6698 .child(h_flex().children(ui::render_modifiers(
6699 &accept_keystroke.modifiers,
6700 PlatformStyle::platform(),
6701 Some(if !has_completion {
6702 Color::Muted
6703 } else {
6704 Color::Default
6705 }),
6706 None,
6707 false,
6708 ))),
6709 )
6710 .child(Label::new("Preview").into_any_element())
6711 .opacity(if has_completion { 1.0 } else { 0.4 }),
6712 )
6713 })
6714 .into_any(),
6715 )
6716 }
6717
6718 fn render_edit_prediction_cursor_popover_preview(
6719 &self,
6720 completion: &InlineCompletionState,
6721 cursor_point: Point,
6722 style: &EditorStyle,
6723 cx: &mut Context<Editor>,
6724 ) -> Option<Div> {
6725 use text::ToPoint as _;
6726
6727 fn render_relative_row_jump(
6728 prefix: impl Into<String>,
6729 current_row: u32,
6730 target_row: u32,
6731 ) -> Div {
6732 let (row_diff, arrow) = if target_row < current_row {
6733 (current_row - target_row, IconName::ArrowUp)
6734 } else {
6735 (target_row - current_row, IconName::ArrowDown)
6736 };
6737
6738 h_flex()
6739 .child(
6740 Label::new(format!("{}{}", prefix.into(), row_diff))
6741 .color(Color::Muted)
6742 .size(LabelSize::Small),
6743 )
6744 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6745 }
6746
6747 match &completion.completion {
6748 InlineCompletion::Move {
6749 target, snapshot, ..
6750 } => Some(
6751 h_flex()
6752 .px_2()
6753 .gap_2()
6754 .flex_1()
6755 .child(
6756 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6757 Icon::new(IconName::ZedPredictDown)
6758 } else {
6759 Icon::new(IconName::ZedPredictUp)
6760 },
6761 )
6762 .child(Label::new("Jump to Edit")),
6763 ),
6764
6765 InlineCompletion::Edit {
6766 edits,
6767 edit_preview,
6768 snapshot,
6769 display_mode: _,
6770 } => {
6771 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6772
6773 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6774 &snapshot,
6775 &edits,
6776 edit_preview.as_ref()?,
6777 true,
6778 cx,
6779 )
6780 .first_line_preview();
6781
6782 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6783 .with_highlights(&style.text, highlighted_edits.highlights);
6784
6785 let preview = h_flex()
6786 .gap_1()
6787 .min_w_16()
6788 .child(styled_text)
6789 .when(has_more_lines, |parent| parent.child("…"));
6790
6791 let left = if first_edit_row != cursor_point.row {
6792 render_relative_row_jump("", cursor_point.row, first_edit_row)
6793 .into_any_element()
6794 } else {
6795 Icon::new(IconName::ZedPredict).into_any_element()
6796 };
6797
6798 Some(
6799 h_flex()
6800 .h_full()
6801 .flex_1()
6802 .gap_2()
6803 .pr_1()
6804 .overflow_x_hidden()
6805 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6806 .child(left)
6807 .child(preview),
6808 )
6809 }
6810 }
6811 }
6812
6813 fn render_context_menu(
6814 &self,
6815 style: &EditorStyle,
6816 max_height_in_lines: u32,
6817 y_flipped: bool,
6818 window: &mut Window,
6819 cx: &mut Context<Editor>,
6820 ) -> Option<AnyElement> {
6821 let menu = self.context_menu.borrow();
6822 let menu = menu.as_ref()?;
6823 if !menu.visible() {
6824 return None;
6825 };
6826 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6827 }
6828
6829 fn render_context_menu_aside(
6830 &mut self,
6831 max_size: Size<Pixels>,
6832 window: &mut Window,
6833 cx: &mut Context<Editor>,
6834 ) -> Option<AnyElement> {
6835 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6836 if menu.visible() {
6837 menu.render_aside(self, max_size, window, cx)
6838 } else {
6839 None
6840 }
6841 })
6842 }
6843
6844 fn hide_context_menu(
6845 &mut self,
6846 window: &mut Window,
6847 cx: &mut Context<Self>,
6848 ) -> Option<CodeContextMenu> {
6849 cx.notify();
6850 self.completion_tasks.clear();
6851 let context_menu = self.context_menu.borrow_mut().take();
6852 self.stale_inline_completion_in_menu.take();
6853 self.update_visible_inline_completion(window, cx);
6854 context_menu
6855 }
6856
6857 fn show_snippet_choices(
6858 &mut self,
6859 choices: &Vec<String>,
6860 selection: Range<Anchor>,
6861 cx: &mut Context<Self>,
6862 ) {
6863 if selection.start.buffer_id.is_none() {
6864 return;
6865 }
6866 let buffer_id = selection.start.buffer_id.unwrap();
6867 let buffer = self.buffer().read(cx).buffer(buffer_id);
6868 let id = post_inc(&mut self.next_completion_id);
6869
6870 if let Some(buffer) = buffer {
6871 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6872 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6873 ));
6874 }
6875 }
6876
6877 pub fn insert_snippet(
6878 &mut self,
6879 insertion_ranges: &[Range<usize>],
6880 snippet: Snippet,
6881 window: &mut Window,
6882 cx: &mut Context<Self>,
6883 ) -> Result<()> {
6884 struct Tabstop<T> {
6885 is_end_tabstop: bool,
6886 ranges: Vec<Range<T>>,
6887 choices: Option<Vec<String>>,
6888 }
6889
6890 let tabstops = self.buffer.update(cx, |buffer, cx| {
6891 let snippet_text: Arc<str> = snippet.text.clone().into();
6892 buffer.edit(
6893 insertion_ranges
6894 .iter()
6895 .cloned()
6896 .map(|range| (range, snippet_text.clone())),
6897 Some(AutoindentMode::EachLine),
6898 cx,
6899 );
6900
6901 let snapshot = &*buffer.read(cx);
6902 let snippet = &snippet;
6903 snippet
6904 .tabstops
6905 .iter()
6906 .map(|tabstop| {
6907 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6908 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6909 });
6910 let mut tabstop_ranges = tabstop
6911 .ranges
6912 .iter()
6913 .flat_map(|tabstop_range| {
6914 let mut delta = 0_isize;
6915 insertion_ranges.iter().map(move |insertion_range| {
6916 let insertion_start = insertion_range.start as isize + delta;
6917 delta +=
6918 snippet.text.len() as isize - insertion_range.len() as isize;
6919
6920 let start = ((insertion_start + tabstop_range.start) as usize)
6921 .min(snapshot.len());
6922 let end = ((insertion_start + tabstop_range.end) as usize)
6923 .min(snapshot.len());
6924 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6925 })
6926 })
6927 .collect::<Vec<_>>();
6928 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6929
6930 Tabstop {
6931 is_end_tabstop,
6932 ranges: tabstop_ranges,
6933 choices: tabstop.choices.clone(),
6934 }
6935 })
6936 .collect::<Vec<_>>()
6937 });
6938 if let Some(tabstop) = tabstops.first() {
6939 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6940 s.select_ranges(tabstop.ranges.iter().cloned());
6941 });
6942
6943 if let Some(choices) = &tabstop.choices {
6944 if let Some(selection) = tabstop.ranges.first() {
6945 self.show_snippet_choices(choices, selection.clone(), cx)
6946 }
6947 }
6948
6949 // If we're already at the last tabstop and it's at the end of the snippet,
6950 // we're done, we don't need to keep the state around.
6951 if !tabstop.is_end_tabstop {
6952 let choices = tabstops
6953 .iter()
6954 .map(|tabstop| tabstop.choices.clone())
6955 .collect();
6956
6957 let ranges = tabstops
6958 .into_iter()
6959 .map(|tabstop| tabstop.ranges)
6960 .collect::<Vec<_>>();
6961
6962 self.snippet_stack.push(SnippetState {
6963 active_index: 0,
6964 ranges,
6965 choices,
6966 });
6967 }
6968
6969 // Check whether the just-entered snippet ends with an auto-closable bracket.
6970 if self.autoclose_regions.is_empty() {
6971 let snapshot = self.buffer.read(cx).snapshot(cx);
6972 for selection in &mut self.selections.all::<Point>(cx) {
6973 let selection_head = selection.head();
6974 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6975 continue;
6976 };
6977
6978 let mut bracket_pair = None;
6979 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6980 let prev_chars = snapshot
6981 .reversed_chars_at(selection_head)
6982 .collect::<String>();
6983 for (pair, enabled) in scope.brackets() {
6984 if enabled
6985 && pair.close
6986 && prev_chars.starts_with(pair.start.as_str())
6987 && next_chars.starts_with(pair.end.as_str())
6988 {
6989 bracket_pair = Some(pair.clone());
6990 break;
6991 }
6992 }
6993 if let Some(pair) = bracket_pair {
6994 let start = snapshot.anchor_after(selection_head);
6995 let end = snapshot.anchor_after(selection_head);
6996 self.autoclose_regions.push(AutocloseRegion {
6997 selection_id: selection.id,
6998 range: start..end,
6999 pair,
7000 });
7001 }
7002 }
7003 }
7004 }
7005 Ok(())
7006 }
7007
7008 pub fn move_to_next_snippet_tabstop(
7009 &mut self,
7010 window: &mut Window,
7011 cx: &mut Context<Self>,
7012 ) -> bool {
7013 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7014 }
7015
7016 pub fn move_to_prev_snippet_tabstop(
7017 &mut self,
7018 window: &mut Window,
7019 cx: &mut Context<Self>,
7020 ) -> bool {
7021 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7022 }
7023
7024 pub fn move_to_snippet_tabstop(
7025 &mut self,
7026 bias: Bias,
7027 window: &mut Window,
7028 cx: &mut Context<Self>,
7029 ) -> bool {
7030 if let Some(mut snippet) = self.snippet_stack.pop() {
7031 match bias {
7032 Bias::Left => {
7033 if snippet.active_index > 0 {
7034 snippet.active_index -= 1;
7035 } else {
7036 self.snippet_stack.push(snippet);
7037 return false;
7038 }
7039 }
7040 Bias::Right => {
7041 if snippet.active_index + 1 < snippet.ranges.len() {
7042 snippet.active_index += 1;
7043 } else {
7044 self.snippet_stack.push(snippet);
7045 return false;
7046 }
7047 }
7048 }
7049 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7050 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7051 s.select_anchor_ranges(current_ranges.iter().cloned())
7052 });
7053
7054 if let Some(choices) = &snippet.choices[snippet.active_index] {
7055 if let Some(selection) = current_ranges.first() {
7056 self.show_snippet_choices(&choices, selection.clone(), cx);
7057 }
7058 }
7059
7060 // If snippet state is not at the last tabstop, push it back on the stack
7061 if snippet.active_index + 1 < snippet.ranges.len() {
7062 self.snippet_stack.push(snippet);
7063 }
7064 return true;
7065 }
7066 }
7067
7068 false
7069 }
7070
7071 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7072 self.transact(window, cx, |this, window, cx| {
7073 this.select_all(&SelectAll, window, cx);
7074 this.insert("", window, cx);
7075 });
7076 }
7077
7078 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7079 self.transact(window, cx, |this, window, cx| {
7080 this.select_autoclose_pair(window, cx);
7081 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7082 if !this.linked_edit_ranges.is_empty() {
7083 let selections = this.selections.all::<MultiBufferPoint>(cx);
7084 let snapshot = this.buffer.read(cx).snapshot(cx);
7085
7086 for selection in selections.iter() {
7087 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7088 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7089 if selection_start.buffer_id != selection_end.buffer_id {
7090 continue;
7091 }
7092 if let Some(ranges) =
7093 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7094 {
7095 for (buffer, entries) in ranges {
7096 linked_ranges.entry(buffer).or_default().extend(entries);
7097 }
7098 }
7099 }
7100 }
7101
7102 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7103 if !this.selections.line_mode {
7104 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7105 for selection in &mut selections {
7106 if selection.is_empty() {
7107 let old_head = selection.head();
7108 let mut new_head =
7109 movement::left(&display_map, old_head.to_display_point(&display_map))
7110 .to_point(&display_map);
7111 if let Some((buffer, line_buffer_range)) = display_map
7112 .buffer_snapshot
7113 .buffer_line_for_row(MultiBufferRow(old_head.row))
7114 {
7115 let indent_size =
7116 buffer.indent_size_for_line(line_buffer_range.start.row);
7117 let indent_len = match indent_size.kind {
7118 IndentKind::Space => {
7119 buffer.settings_at(line_buffer_range.start, cx).tab_size
7120 }
7121 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7122 };
7123 if old_head.column <= indent_size.len && old_head.column > 0 {
7124 let indent_len = indent_len.get();
7125 new_head = cmp::min(
7126 new_head,
7127 MultiBufferPoint::new(
7128 old_head.row,
7129 ((old_head.column - 1) / indent_len) * indent_len,
7130 ),
7131 );
7132 }
7133 }
7134
7135 selection.set_head(new_head, SelectionGoal::None);
7136 }
7137 }
7138 }
7139
7140 this.signature_help_state.set_backspace_pressed(true);
7141 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7142 s.select(selections)
7143 });
7144 this.insert("", window, cx);
7145 let empty_str: Arc<str> = Arc::from("");
7146 for (buffer, edits) in linked_ranges {
7147 let snapshot = buffer.read(cx).snapshot();
7148 use text::ToPoint as TP;
7149
7150 let edits = edits
7151 .into_iter()
7152 .map(|range| {
7153 let end_point = TP::to_point(&range.end, &snapshot);
7154 let mut start_point = TP::to_point(&range.start, &snapshot);
7155
7156 if end_point == start_point {
7157 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7158 .saturating_sub(1);
7159 start_point =
7160 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7161 };
7162
7163 (start_point..end_point, empty_str.clone())
7164 })
7165 .sorted_by_key(|(range, _)| range.start)
7166 .collect::<Vec<_>>();
7167 buffer.update(cx, |this, cx| {
7168 this.edit(edits, None, cx);
7169 })
7170 }
7171 this.refresh_inline_completion(true, false, window, cx);
7172 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7173 });
7174 }
7175
7176 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7177 self.transact(window, cx, |this, window, cx| {
7178 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7179 let line_mode = s.line_mode;
7180 s.move_with(|map, selection| {
7181 if selection.is_empty() && !line_mode {
7182 let cursor = movement::right(map, selection.head());
7183 selection.end = cursor;
7184 selection.reversed = true;
7185 selection.goal = SelectionGoal::None;
7186 }
7187 })
7188 });
7189 this.insert("", window, cx);
7190 this.refresh_inline_completion(true, false, window, cx);
7191 });
7192 }
7193
7194 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
7195 if self.move_to_prev_snippet_tabstop(window, cx) {
7196 return;
7197 }
7198
7199 self.outdent(&Outdent, window, cx);
7200 }
7201
7202 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7203 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7204 return;
7205 }
7206
7207 let mut selections = self.selections.all_adjusted(cx);
7208 let buffer = self.buffer.read(cx);
7209 let snapshot = buffer.snapshot(cx);
7210 let rows_iter = selections.iter().map(|s| s.head().row);
7211 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7212
7213 let mut edits = Vec::new();
7214 let mut prev_edited_row = 0;
7215 let mut row_delta = 0;
7216 for selection in &mut selections {
7217 if selection.start.row != prev_edited_row {
7218 row_delta = 0;
7219 }
7220 prev_edited_row = selection.end.row;
7221
7222 // If the selection is non-empty, then increase the indentation of the selected lines.
7223 if !selection.is_empty() {
7224 row_delta =
7225 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7226 continue;
7227 }
7228
7229 // If the selection is empty and the cursor is in the leading whitespace before the
7230 // suggested indentation, then auto-indent the line.
7231 let cursor = selection.head();
7232 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7233 if let Some(suggested_indent) =
7234 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7235 {
7236 if cursor.column < suggested_indent.len
7237 && cursor.column <= current_indent.len
7238 && current_indent.len <= suggested_indent.len
7239 {
7240 selection.start = Point::new(cursor.row, suggested_indent.len);
7241 selection.end = selection.start;
7242 if row_delta == 0 {
7243 edits.extend(Buffer::edit_for_indent_size_adjustment(
7244 cursor.row,
7245 current_indent,
7246 suggested_indent,
7247 ));
7248 row_delta = suggested_indent.len - current_indent.len;
7249 }
7250 continue;
7251 }
7252 }
7253
7254 // Otherwise, insert a hard or soft tab.
7255 let settings = buffer.settings_at(cursor, cx);
7256 let tab_size = if settings.hard_tabs {
7257 IndentSize::tab()
7258 } else {
7259 let tab_size = settings.tab_size.get();
7260 let char_column = snapshot
7261 .text_for_range(Point::new(cursor.row, 0)..cursor)
7262 .flat_map(str::chars)
7263 .count()
7264 + row_delta as usize;
7265 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7266 IndentSize::spaces(chars_to_next_tab_stop)
7267 };
7268 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7269 selection.end = selection.start;
7270 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7271 row_delta += tab_size.len;
7272 }
7273
7274 self.transact(window, cx, |this, window, cx| {
7275 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7276 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7277 s.select(selections)
7278 });
7279 this.refresh_inline_completion(true, false, window, cx);
7280 });
7281 }
7282
7283 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7284 if self.read_only(cx) {
7285 return;
7286 }
7287 let mut selections = self.selections.all::<Point>(cx);
7288 let mut prev_edited_row = 0;
7289 let mut row_delta = 0;
7290 let mut edits = Vec::new();
7291 let buffer = self.buffer.read(cx);
7292 let snapshot = buffer.snapshot(cx);
7293 for selection in &mut selections {
7294 if selection.start.row != prev_edited_row {
7295 row_delta = 0;
7296 }
7297 prev_edited_row = selection.end.row;
7298
7299 row_delta =
7300 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7301 }
7302
7303 self.transact(window, cx, |this, window, cx| {
7304 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7305 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7306 s.select(selections)
7307 });
7308 });
7309 }
7310
7311 fn indent_selection(
7312 buffer: &MultiBuffer,
7313 snapshot: &MultiBufferSnapshot,
7314 selection: &mut Selection<Point>,
7315 edits: &mut Vec<(Range<Point>, String)>,
7316 delta_for_start_row: u32,
7317 cx: &App,
7318 ) -> u32 {
7319 let settings = buffer.settings_at(selection.start, cx);
7320 let tab_size = settings.tab_size.get();
7321 let indent_kind = if settings.hard_tabs {
7322 IndentKind::Tab
7323 } else {
7324 IndentKind::Space
7325 };
7326 let mut start_row = selection.start.row;
7327 let mut end_row = selection.end.row + 1;
7328
7329 // If a selection ends at the beginning of a line, don't indent
7330 // that last line.
7331 if selection.end.column == 0 && selection.end.row > selection.start.row {
7332 end_row -= 1;
7333 }
7334
7335 // Avoid re-indenting a row that has already been indented by a
7336 // previous selection, but still update this selection's column
7337 // to reflect that indentation.
7338 if delta_for_start_row > 0 {
7339 start_row += 1;
7340 selection.start.column += delta_for_start_row;
7341 if selection.end.row == selection.start.row {
7342 selection.end.column += delta_for_start_row;
7343 }
7344 }
7345
7346 let mut delta_for_end_row = 0;
7347 let has_multiple_rows = start_row + 1 != end_row;
7348 for row in start_row..end_row {
7349 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7350 let indent_delta = match (current_indent.kind, indent_kind) {
7351 (IndentKind::Space, IndentKind::Space) => {
7352 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7353 IndentSize::spaces(columns_to_next_tab_stop)
7354 }
7355 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7356 (_, IndentKind::Tab) => IndentSize::tab(),
7357 };
7358
7359 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7360 0
7361 } else {
7362 selection.start.column
7363 };
7364 let row_start = Point::new(row, start);
7365 edits.push((
7366 row_start..row_start,
7367 indent_delta.chars().collect::<String>(),
7368 ));
7369
7370 // Update this selection's endpoints to reflect the indentation.
7371 if row == selection.start.row {
7372 selection.start.column += indent_delta.len;
7373 }
7374 if row == selection.end.row {
7375 selection.end.column += indent_delta.len;
7376 delta_for_end_row = indent_delta.len;
7377 }
7378 }
7379
7380 if selection.start.row == selection.end.row {
7381 delta_for_start_row + delta_for_end_row
7382 } else {
7383 delta_for_end_row
7384 }
7385 }
7386
7387 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7388 if self.read_only(cx) {
7389 return;
7390 }
7391 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7392 let selections = self.selections.all::<Point>(cx);
7393 let mut deletion_ranges = Vec::new();
7394 let mut last_outdent = None;
7395 {
7396 let buffer = self.buffer.read(cx);
7397 let snapshot = buffer.snapshot(cx);
7398 for selection in &selections {
7399 let settings = buffer.settings_at(selection.start, cx);
7400 let tab_size = settings.tab_size.get();
7401 let mut rows = selection.spanned_rows(false, &display_map);
7402
7403 // Avoid re-outdenting a row that has already been outdented by a
7404 // previous selection.
7405 if let Some(last_row) = last_outdent {
7406 if last_row == rows.start {
7407 rows.start = rows.start.next_row();
7408 }
7409 }
7410 let has_multiple_rows = rows.len() > 1;
7411 for row in rows.iter_rows() {
7412 let indent_size = snapshot.indent_size_for_line(row);
7413 if indent_size.len > 0 {
7414 let deletion_len = match indent_size.kind {
7415 IndentKind::Space => {
7416 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7417 if columns_to_prev_tab_stop == 0 {
7418 tab_size
7419 } else {
7420 columns_to_prev_tab_stop
7421 }
7422 }
7423 IndentKind::Tab => 1,
7424 };
7425 let start = if has_multiple_rows
7426 || deletion_len > selection.start.column
7427 || indent_size.len < selection.start.column
7428 {
7429 0
7430 } else {
7431 selection.start.column - deletion_len
7432 };
7433 deletion_ranges.push(
7434 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7435 );
7436 last_outdent = Some(row);
7437 }
7438 }
7439 }
7440 }
7441
7442 self.transact(window, cx, |this, window, cx| {
7443 this.buffer.update(cx, |buffer, cx| {
7444 let empty_str: Arc<str> = Arc::default();
7445 buffer.edit(
7446 deletion_ranges
7447 .into_iter()
7448 .map(|range| (range, empty_str.clone())),
7449 None,
7450 cx,
7451 );
7452 });
7453 let selections = this.selections.all::<usize>(cx);
7454 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7455 s.select(selections)
7456 });
7457 });
7458 }
7459
7460 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7461 if self.read_only(cx) {
7462 return;
7463 }
7464 let selections = self
7465 .selections
7466 .all::<usize>(cx)
7467 .into_iter()
7468 .map(|s| s.range());
7469
7470 self.transact(window, cx, |this, window, cx| {
7471 this.buffer.update(cx, |buffer, cx| {
7472 buffer.autoindent_ranges(selections, cx);
7473 });
7474 let selections = this.selections.all::<usize>(cx);
7475 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7476 s.select(selections)
7477 });
7478 });
7479 }
7480
7481 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7482 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7483 let selections = self.selections.all::<Point>(cx);
7484
7485 let mut new_cursors = Vec::new();
7486 let mut edit_ranges = Vec::new();
7487 let mut selections = selections.iter().peekable();
7488 while let Some(selection) = selections.next() {
7489 let mut rows = selection.spanned_rows(false, &display_map);
7490 let goal_display_column = selection.head().to_display_point(&display_map).column();
7491
7492 // Accumulate contiguous regions of rows that we want to delete.
7493 while let Some(next_selection) = selections.peek() {
7494 let next_rows = next_selection.spanned_rows(false, &display_map);
7495 if next_rows.start <= rows.end {
7496 rows.end = next_rows.end;
7497 selections.next().unwrap();
7498 } else {
7499 break;
7500 }
7501 }
7502
7503 let buffer = &display_map.buffer_snapshot;
7504 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7505 let edit_end;
7506 let cursor_buffer_row;
7507 if buffer.max_point().row >= rows.end.0 {
7508 // If there's a line after the range, delete the \n from the end of the row range
7509 // and position the cursor on the next line.
7510 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7511 cursor_buffer_row = rows.end;
7512 } else {
7513 // If there isn't a line after the range, delete the \n from the line before the
7514 // start of the row range and position the cursor there.
7515 edit_start = edit_start.saturating_sub(1);
7516 edit_end = buffer.len();
7517 cursor_buffer_row = rows.start.previous_row();
7518 }
7519
7520 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7521 *cursor.column_mut() =
7522 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7523
7524 new_cursors.push((
7525 selection.id,
7526 buffer.anchor_after(cursor.to_point(&display_map)),
7527 ));
7528 edit_ranges.push(edit_start..edit_end);
7529 }
7530
7531 self.transact(window, cx, |this, window, cx| {
7532 let buffer = this.buffer.update(cx, |buffer, cx| {
7533 let empty_str: Arc<str> = Arc::default();
7534 buffer.edit(
7535 edit_ranges
7536 .into_iter()
7537 .map(|range| (range, empty_str.clone())),
7538 None,
7539 cx,
7540 );
7541 buffer.snapshot(cx)
7542 });
7543 let new_selections = new_cursors
7544 .into_iter()
7545 .map(|(id, cursor)| {
7546 let cursor = cursor.to_point(&buffer);
7547 Selection {
7548 id,
7549 start: cursor,
7550 end: cursor,
7551 reversed: false,
7552 goal: SelectionGoal::None,
7553 }
7554 })
7555 .collect();
7556
7557 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7558 s.select(new_selections);
7559 });
7560 });
7561 }
7562
7563 pub fn join_lines_impl(
7564 &mut self,
7565 insert_whitespace: bool,
7566 window: &mut Window,
7567 cx: &mut Context<Self>,
7568 ) {
7569 if self.read_only(cx) {
7570 return;
7571 }
7572 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7573 for selection in self.selections.all::<Point>(cx) {
7574 let start = MultiBufferRow(selection.start.row);
7575 // Treat single line selections as if they include the next line. Otherwise this action
7576 // would do nothing for single line selections individual cursors.
7577 let end = if selection.start.row == selection.end.row {
7578 MultiBufferRow(selection.start.row + 1)
7579 } else {
7580 MultiBufferRow(selection.end.row)
7581 };
7582
7583 if let Some(last_row_range) = row_ranges.last_mut() {
7584 if start <= last_row_range.end {
7585 last_row_range.end = end;
7586 continue;
7587 }
7588 }
7589 row_ranges.push(start..end);
7590 }
7591
7592 let snapshot = self.buffer.read(cx).snapshot(cx);
7593 let mut cursor_positions = Vec::new();
7594 for row_range in &row_ranges {
7595 let anchor = snapshot.anchor_before(Point::new(
7596 row_range.end.previous_row().0,
7597 snapshot.line_len(row_range.end.previous_row()),
7598 ));
7599 cursor_positions.push(anchor..anchor);
7600 }
7601
7602 self.transact(window, cx, |this, window, cx| {
7603 for row_range in row_ranges.into_iter().rev() {
7604 for row in row_range.iter_rows().rev() {
7605 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7606 let next_line_row = row.next_row();
7607 let indent = snapshot.indent_size_for_line(next_line_row);
7608 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7609
7610 let replace =
7611 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7612 " "
7613 } else {
7614 ""
7615 };
7616
7617 this.buffer.update(cx, |buffer, cx| {
7618 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7619 });
7620 }
7621 }
7622
7623 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7624 s.select_anchor_ranges(cursor_positions)
7625 });
7626 });
7627 }
7628
7629 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7630 self.join_lines_impl(true, window, cx);
7631 }
7632
7633 pub fn sort_lines_case_sensitive(
7634 &mut self,
7635 _: &SortLinesCaseSensitive,
7636 window: &mut Window,
7637 cx: &mut Context<Self>,
7638 ) {
7639 self.manipulate_lines(window, cx, |lines| lines.sort())
7640 }
7641
7642 pub fn sort_lines_case_insensitive(
7643 &mut self,
7644 _: &SortLinesCaseInsensitive,
7645 window: &mut Window,
7646 cx: &mut Context<Self>,
7647 ) {
7648 self.manipulate_lines(window, cx, |lines| {
7649 lines.sort_by_key(|line| line.to_lowercase())
7650 })
7651 }
7652
7653 pub fn unique_lines_case_insensitive(
7654 &mut self,
7655 _: &UniqueLinesCaseInsensitive,
7656 window: &mut Window,
7657 cx: &mut Context<Self>,
7658 ) {
7659 self.manipulate_lines(window, cx, |lines| {
7660 let mut seen = HashSet::default();
7661 lines.retain(|line| seen.insert(line.to_lowercase()));
7662 })
7663 }
7664
7665 pub fn unique_lines_case_sensitive(
7666 &mut self,
7667 _: &UniqueLinesCaseSensitive,
7668 window: &mut Window,
7669 cx: &mut Context<Self>,
7670 ) {
7671 self.manipulate_lines(window, cx, |lines| {
7672 let mut seen = HashSet::default();
7673 lines.retain(|line| seen.insert(*line));
7674 })
7675 }
7676
7677 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7678 let Some(project) = self.project.clone() else {
7679 return;
7680 };
7681 self.reload(project, window, cx)
7682 .detach_and_notify_err(window, cx);
7683 }
7684
7685 pub fn restore_file(
7686 &mut self,
7687 _: &::git::RestoreFile,
7688 window: &mut Window,
7689 cx: &mut Context<Self>,
7690 ) {
7691 let mut buffer_ids = HashSet::default();
7692 let snapshot = self.buffer().read(cx).snapshot(cx);
7693 for selection in self.selections.all::<usize>(cx) {
7694 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7695 }
7696
7697 let buffer = self.buffer().read(cx);
7698 let ranges = buffer_ids
7699 .into_iter()
7700 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7701 .collect::<Vec<_>>();
7702
7703 self.restore_hunks_in_ranges(ranges, window, cx);
7704 }
7705
7706 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7707 let selections = self
7708 .selections
7709 .all(cx)
7710 .into_iter()
7711 .map(|s| s.range())
7712 .collect();
7713 self.restore_hunks_in_ranges(selections, window, cx);
7714 }
7715
7716 fn restore_hunks_in_ranges(
7717 &mut self,
7718 ranges: Vec<Range<Point>>,
7719 window: &mut Window,
7720 cx: &mut Context<Editor>,
7721 ) {
7722 let mut revert_changes = HashMap::default();
7723 let chunk_by = self
7724 .snapshot(window, cx)
7725 .hunks_for_ranges(ranges)
7726 .into_iter()
7727 .chunk_by(|hunk| hunk.buffer_id);
7728 for (buffer_id, hunks) in &chunk_by {
7729 let hunks = hunks.collect::<Vec<_>>();
7730 for hunk in &hunks {
7731 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7732 }
7733 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), window, cx);
7734 }
7735 drop(chunk_by);
7736 if !revert_changes.is_empty() {
7737 self.transact(window, cx, |editor, window, cx| {
7738 editor.restore(revert_changes, window, cx);
7739 });
7740 }
7741 }
7742
7743 pub fn open_active_item_in_terminal(
7744 &mut self,
7745 _: &OpenInTerminal,
7746 window: &mut Window,
7747 cx: &mut Context<Self>,
7748 ) {
7749 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7750 let project_path = buffer.read(cx).project_path(cx)?;
7751 let project = self.project.as_ref()?.read(cx);
7752 let entry = project.entry_for_path(&project_path, cx)?;
7753 let parent = match &entry.canonical_path {
7754 Some(canonical_path) => canonical_path.to_path_buf(),
7755 None => project.absolute_path(&project_path, cx)?,
7756 }
7757 .parent()?
7758 .to_path_buf();
7759 Some(parent)
7760 }) {
7761 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7762 }
7763 }
7764
7765 pub fn prepare_restore_change(
7766 &self,
7767 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7768 hunk: &MultiBufferDiffHunk,
7769 cx: &mut App,
7770 ) -> Option<()> {
7771 let buffer = self.buffer.read(cx);
7772 let diff = buffer.diff_for(hunk.buffer_id)?;
7773 let buffer = buffer.buffer(hunk.buffer_id)?;
7774 let buffer = buffer.read(cx);
7775 let original_text = diff
7776 .read(cx)
7777 .base_text()
7778 .as_rope()
7779 .slice(hunk.diff_base_byte_range.clone());
7780 let buffer_snapshot = buffer.snapshot();
7781 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7782 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7783 probe
7784 .0
7785 .start
7786 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7787 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7788 }) {
7789 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7790 Some(())
7791 } else {
7792 None
7793 }
7794 }
7795
7796 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7797 self.manipulate_lines(window, cx, |lines| lines.reverse())
7798 }
7799
7800 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7801 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7802 }
7803
7804 fn manipulate_lines<Fn>(
7805 &mut self,
7806 window: &mut Window,
7807 cx: &mut Context<Self>,
7808 mut callback: Fn,
7809 ) where
7810 Fn: FnMut(&mut Vec<&str>),
7811 {
7812 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7813 let buffer = self.buffer.read(cx).snapshot(cx);
7814
7815 let mut edits = Vec::new();
7816
7817 let selections = self.selections.all::<Point>(cx);
7818 let mut selections = selections.iter().peekable();
7819 let mut contiguous_row_selections = Vec::new();
7820 let mut new_selections = Vec::new();
7821 let mut added_lines = 0;
7822 let mut removed_lines = 0;
7823
7824 while let Some(selection) = selections.next() {
7825 let (start_row, end_row) = consume_contiguous_rows(
7826 &mut contiguous_row_selections,
7827 selection,
7828 &display_map,
7829 &mut selections,
7830 );
7831
7832 let start_point = Point::new(start_row.0, 0);
7833 let end_point = Point::new(
7834 end_row.previous_row().0,
7835 buffer.line_len(end_row.previous_row()),
7836 );
7837 let text = buffer
7838 .text_for_range(start_point..end_point)
7839 .collect::<String>();
7840
7841 let mut lines = text.split('\n').collect_vec();
7842
7843 let lines_before = lines.len();
7844 callback(&mut lines);
7845 let lines_after = lines.len();
7846
7847 edits.push((start_point..end_point, lines.join("\n")));
7848
7849 // Selections must change based on added and removed line count
7850 let start_row =
7851 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7852 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7853 new_selections.push(Selection {
7854 id: selection.id,
7855 start: start_row,
7856 end: end_row,
7857 goal: SelectionGoal::None,
7858 reversed: selection.reversed,
7859 });
7860
7861 if lines_after > lines_before {
7862 added_lines += lines_after - lines_before;
7863 } else if lines_before > lines_after {
7864 removed_lines += lines_before - lines_after;
7865 }
7866 }
7867
7868 self.transact(window, cx, |this, window, cx| {
7869 let buffer = this.buffer.update(cx, |buffer, cx| {
7870 buffer.edit(edits, None, cx);
7871 buffer.snapshot(cx)
7872 });
7873
7874 // Recalculate offsets on newly edited buffer
7875 let new_selections = new_selections
7876 .iter()
7877 .map(|s| {
7878 let start_point = Point::new(s.start.0, 0);
7879 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7880 Selection {
7881 id: s.id,
7882 start: buffer.point_to_offset(start_point),
7883 end: buffer.point_to_offset(end_point),
7884 goal: s.goal,
7885 reversed: s.reversed,
7886 }
7887 })
7888 .collect();
7889
7890 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7891 s.select(new_selections);
7892 });
7893
7894 this.request_autoscroll(Autoscroll::fit(), cx);
7895 });
7896 }
7897
7898 pub fn convert_to_upper_case(
7899 &mut self,
7900 _: &ConvertToUpperCase,
7901 window: &mut Window,
7902 cx: &mut Context<Self>,
7903 ) {
7904 self.manipulate_text(window, cx, |text| text.to_uppercase())
7905 }
7906
7907 pub fn convert_to_lower_case(
7908 &mut self,
7909 _: &ConvertToLowerCase,
7910 window: &mut Window,
7911 cx: &mut Context<Self>,
7912 ) {
7913 self.manipulate_text(window, cx, |text| text.to_lowercase())
7914 }
7915
7916 pub fn convert_to_title_case(
7917 &mut self,
7918 _: &ConvertToTitleCase,
7919 window: &mut Window,
7920 cx: &mut Context<Self>,
7921 ) {
7922 self.manipulate_text(window, cx, |text| {
7923 text.split('\n')
7924 .map(|line| line.to_case(Case::Title))
7925 .join("\n")
7926 })
7927 }
7928
7929 pub fn convert_to_snake_case(
7930 &mut self,
7931 _: &ConvertToSnakeCase,
7932 window: &mut Window,
7933 cx: &mut Context<Self>,
7934 ) {
7935 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7936 }
7937
7938 pub fn convert_to_kebab_case(
7939 &mut self,
7940 _: &ConvertToKebabCase,
7941 window: &mut Window,
7942 cx: &mut Context<Self>,
7943 ) {
7944 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7945 }
7946
7947 pub fn convert_to_upper_camel_case(
7948 &mut self,
7949 _: &ConvertToUpperCamelCase,
7950 window: &mut Window,
7951 cx: &mut Context<Self>,
7952 ) {
7953 self.manipulate_text(window, cx, |text| {
7954 text.split('\n')
7955 .map(|line| line.to_case(Case::UpperCamel))
7956 .join("\n")
7957 })
7958 }
7959
7960 pub fn convert_to_lower_camel_case(
7961 &mut self,
7962 _: &ConvertToLowerCamelCase,
7963 window: &mut Window,
7964 cx: &mut Context<Self>,
7965 ) {
7966 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7967 }
7968
7969 pub fn convert_to_opposite_case(
7970 &mut self,
7971 _: &ConvertToOppositeCase,
7972 window: &mut Window,
7973 cx: &mut Context<Self>,
7974 ) {
7975 self.manipulate_text(window, cx, |text| {
7976 text.chars()
7977 .fold(String::with_capacity(text.len()), |mut t, c| {
7978 if c.is_uppercase() {
7979 t.extend(c.to_lowercase());
7980 } else {
7981 t.extend(c.to_uppercase());
7982 }
7983 t
7984 })
7985 })
7986 }
7987
7988 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7989 where
7990 Fn: FnMut(&str) -> String,
7991 {
7992 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7993 let buffer = self.buffer.read(cx).snapshot(cx);
7994
7995 let mut new_selections = Vec::new();
7996 let mut edits = Vec::new();
7997 let mut selection_adjustment = 0i32;
7998
7999 for selection in self.selections.all::<usize>(cx) {
8000 let selection_is_empty = selection.is_empty();
8001
8002 let (start, end) = if selection_is_empty {
8003 let word_range = movement::surrounding_word(
8004 &display_map,
8005 selection.start.to_display_point(&display_map),
8006 );
8007 let start = word_range.start.to_offset(&display_map, Bias::Left);
8008 let end = word_range.end.to_offset(&display_map, Bias::Left);
8009 (start, end)
8010 } else {
8011 (selection.start, selection.end)
8012 };
8013
8014 let text = buffer.text_for_range(start..end).collect::<String>();
8015 let old_length = text.len() as i32;
8016 let text = callback(&text);
8017
8018 new_selections.push(Selection {
8019 start: (start as i32 - selection_adjustment) as usize,
8020 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8021 goal: SelectionGoal::None,
8022 ..selection
8023 });
8024
8025 selection_adjustment += old_length - text.len() as i32;
8026
8027 edits.push((start..end, text));
8028 }
8029
8030 self.transact(window, cx, |this, window, cx| {
8031 this.buffer.update(cx, |buffer, cx| {
8032 buffer.edit(edits, None, cx);
8033 });
8034
8035 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8036 s.select(new_selections);
8037 });
8038
8039 this.request_autoscroll(Autoscroll::fit(), cx);
8040 });
8041 }
8042
8043 pub fn duplicate(
8044 &mut self,
8045 upwards: bool,
8046 whole_lines: bool,
8047 window: &mut Window,
8048 cx: &mut Context<Self>,
8049 ) {
8050 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8051 let buffer = &display_map.buffer_snapshot;
8052 let selections = self.selections.all::<Point>(cx);
8053
8054 let mut edits = Vec::new();
8055 let mut selections_iter = selections.iter().peekable();
8056 while let Some(selection) = selections_iter.next() {
8057 let mut rows = selection.spanned_rows(false, &display_map);
8058 // duplicate line-wise
8059 if whole_lines || selection.start == selection.end {
8060 // Avoid duplicating the same lines twice.
8061 while let Some(next_selection) = selections_iter.peek() {
8062 let next_rows = next_selection.spanned_rows(false, &display_map);
8063 if next_rows.start < rows.end {
8064 rows.end = next_rows.end;
8065 selections_iter.next().unwrap();
8066 } else {
8067 break;
8068 }
8069 }
8070
8071 // Copy the text from the selected row region and splice it either at the start
8072 // or end of the region.
8073 let start = Point::new(rows.start.0, 0);
8074 let end = Point::new(
8075 rows.end.previous_row().0,
8076 buffer.line_len(rows.end.previous_row()),
8077 );
8078 let text = buffer
8079 .text_for_range(start..end)
8080 .chain(Some("\n"))
8081 .collect::<String>();
8082 let insert_location = if upwards {
8083 Point::new(rows.end.0, 0)
8084 } else {
8085 start
8086 };
8087 edits.push((insert_location..insert_location, text));
8088 } else {
8089 // duplicate character-wise
8090 let start = selection.start;
8091 let end = selection.end;
8092 let text = buffer.text_for_range(start..end).collect::<String>();
8093 edits.push((selection.end..selection.end, text));
8094 }
8095 }
8096
8097 self.transact(window, cx, |this, _, cx| {
8098 this.buffer.update(cx, |buffer, cx| {
8099 buffer.edit(edits, None, cx);
8100 });
8101
8102 this.request_autoscroll(Autoscroll::fit(), cx);
8103 });
8104 }
8105
8106 pub fn duplicate_line_up(
8107 &mut self,
8108 _: &DuplicateLineUp,
8109 window: &mut Window,
8110 cx: &mut Context<Self>,
8111 ) {
8112 self.duplicate(true, true, window, cx);
8113 }
8114
8115 pub fn duplicate_line_down(
8116 &mut self,
8117 _: &DuplicateLineDown,
8118 window: &mut Window,
8119 cx: &mut Context<Self>,
8120 ) {
8121 self.duplicate(false, true, window, cx);
8122 }
8123
8124 pub fn duplicate_selection(
8125 &mut self,
8126 _: &DuplicateSelection,
8127 window: &mut Window,
8128 cx: &mut Context<Self>,
8129 ) {
8130 self.duplicate(false, false, window, cx);
8131 }
8132
8133 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8134 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8135 let buffer = self.buffer.read(cx).snapshot(cx);
8136
8137 let mut edits = Vec::new();
8138 let mut unfold_ranges = Vec::new();
8139 let mut refold_creases = Vec::new();
8140
8141 let selections = self.selections.all::<Point>(cx);
8142 let mut selections = selections.iter().peekable();
8143 let mut contiguous_row_selections = Vec::new();
8144 let mut new_selections = Vec::new();
8145
8146 while let Some(selection) = selections.next() {
8147 // Find all the selections that span a contiguous row range
8148 let (start_row, end_row) = consume_contiguous_rows(
8149 &mut contiguous_row_selections,
8150 selection,
8151 &display_map,
8152 &mut selections,
8153 );
8154
8155 // Move the text spanned by the row range to be before the line preceding the row range
8156 if start_row.0 > 0 {
8157 let range_to_move = Point::new(
8158 start_row.previous_row().0,
8159 buffer.line_len(start_row.previous_row()),
8160 )
8161 ..Point::new(
8162 end_row.previous_row().0,
8163 buffer.line_len(end_row.previous_row()),
8164 );
8165 let insertion_point = display_map
8166 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8167 .0;
8168
8169 // Don't move lines across excerpts
8170 if buffer
8171 .excerpt_containing(insertion_point..range_to_move.end)
8172 .is_some()
8173 {
8174 let text = buffer
8175 .text_for_range(range_to_move.clone())
8176 .flat_map(|s| s.chars())
8177 .skip(1)
8178 .chain(['\n'])
8179 .collect::<String>();
8180
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 = range_to_move.start.row - insertion_point.row + 1;
8190
8191 // Move selections up
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 up
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 move_line_down(
8234 &mut self,
8235 _: &MoveLineDown,
8236 window: &mut Window,
8237 cx: &mut Context<Self>,
8238 ) {
8239 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8240 let buffer = self.buffer.read(cx).snapshot(cx);
8241
8242 let mut edits = Vec::new();
8243 let mut unfold_ranges = Vec::new();
8244 let mut refold_creases = Vec::new();
8245
8246 let selections = self.selections.all::<Point>(cx);
8247 let mut selections = selections.iter().peekable();
8248 let mut contiguous_row_selections = Vec::new();
8249 let mut new_selections = Vec::new();
8250
8251 while let Some(selection) = selections.next() {
8252 // Find all the selections that span a contiguous row range
8253 let (start_row, end_row) = consume_contiguous_rows(
8254 &mut contiguous_row_selections,
8255 selection,
8256 &display_map,
8257 &mut selections,
8258 );
8259
8260 // Move the text spanned by the row range to be after the last line of the row range
8261 if end_row.0 <= buffer.max_point().row {
8262 let range_to_move =
8263 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8264 let insertion_point = display_map
8265 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8266 .0;
8267
8268 // Don't move lines across excerpt boundaries
8269 if buffer
8270 .excerpt_containing(range_to_move.start..insertion_point)
8271 .is_some()
8272 {
8273 let mut text = String::from("\n");
8274 text.extend(buffer.text_for_range(range_to_move.clone()));
8275 text.pop(); // Drop trailing newline
8276 edits.push((
8277 buffer.anchor_after(range_to_move.start)
8278 ..buffer.anchor_before(range_to_move.end),
8279 String::new(),
8280 ));
8281 let insertion_anchor = buffer.anchor_after(insertion_point);
8282 edits.push((insertion_anchor..insertion_anchor, text));
8283
8284 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8285
8286 // Move selections down
8287 new_selections.extend(contiguous_row_selections.drain(..).map(
8288 |mut selection| {
8289 selection.start.row += row_delta;
8290 selection.end.row += row_delta;
8291 selection
8292 },
8293 ));
8294
8295 // Move folds down
8296 unfold_ranges.push(range_to_move.clone());
8297 for fold in display_map.folds_in_range(
8298 buffer.anchor_before(range_to_move.start)
8299 ..buffer.anchor_after(range_to_move.end),
8300 ) {
8301 let mut start = fold.range.start.to_point(&buffer);
8302 let mut end = fold.range.end.to_point(&buffer);
8303 start.row += row_delta;
8304 end.row += row_delta;
8305 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8306 }
8307 }
8308 }
8309
8310 // If we didn't move line(s), preserve the existing selections
8311 new_selections.append(&mut contiguous_row_selections);
8312 }
8313
8314 self.transact(window, cx, |this, window, cx| {
8315 this.unfold_ranges(&unfold_ranges, true, true, cx);
8316 this.buffer.update(cx, |buffer, cx| {
8317 for (range, text) in edits {
8318 buffer.edit([(range, text)], None, cx);
8319 }
8320 });
8321 this.fold_creases(refold_creases, true, window, cx);
8322 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8323 s.select(new_selections)
8324 });
8325 });
8326 }
8327
8328 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8329 let text_layout_details = &self.text_layout_details(window);
8330 self.transact(window, cx, |this, window, cx| {
8331 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8332 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8333 let line_mode = s.line_mode;
8334 s.move_with(|display_map, selection| {
8335 if !selection.is_empty() || line_mode {
8336 return;
8337 }
8338
8339 let mut head = selection.head();
8340 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8341 if head.column() == display_map.line_len(head.row()) {
8342 transpose_offset = display_map
8343 .buffer_snapshot
8344 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8345 }
8346
8347 if transpose_offset == 0 {
8348 return;
8349 }
8350
8351 *head.column_mut() += 1;
8352 head = display_map.clip_point(head, Bias::Right);
8353 let goal = SelectionGoal::HorizontalPosition(
8354 display_map
8355 .x_for_display_point(head, text_layout_details)
8356 .into(),
8357 );
8358 selection.collapse_to(head, goal);
8359
8360 let transpose_start = display_map
8361 .buffer_snapshot
8362 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8363 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8364 let transpose_end = display_map
8365 .buffer_snapshot
8366 .clip_offset(transpose_offset + 1, Bias::Right);
8367 if let Some(ch) =
8368 display_map.buffer_snapshot.chars_at(transpose_start).next()
8369 {
8370 edits.push((transpose_start..transpose_offset, String::new()));
8371 edits.push((transpose_end..transpose_end, ch.to_string()));
8372 }
8373 }
8374 });
8375 edits
8376 });
8377 this.buffer
8378 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8379 let selections = this.selections.all::<usize>(cx);
8380 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8381 s.select(selections);
8382 });
8383 });
8384 }
8385
8386 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8387 self.rewrap_impl(IsVimMode::No, cx)
8388 }
8389
8390 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8391 let buffer = self.buffer.read(cx).snapshot(cx);
8392 let selections = self.selections.all::<Point>(cx);
8393 let mut selections = selections.iter().peekable();
8394
8395 let mut edits = Vec::new();
8396 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8397
8398 while let Some(selection) = selections.next() {
8399 let mut start_row = selection.start.row;
8400 let mut end_row = selection.end.row;
8401
8402 // Skip selections that overlap with a range that has already been rewrapped.
8403 let selection_range = start_row..end_row;
8404 if rewrapped_row_ranges
8405 .iter()
8406 .any(|range| range.overlaps(&selection_range))
8407 {
8408 continue;
8409 }
8410
8411 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
8412
8413 // Since not all lines in the selection may be at the same indent
8414 // level, choose the indent size that is the most common between all
8415 // of the lines.
8416 //
8417 // If there is a tie, we use the deepest indent.
8418 let (indent_size, indent_end) = {
8419 let mut indent_size_occurrences = HashMap::default();
8420 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8421
8422 for row in start_row..=end_row {
8423 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8424 rows_by_indent_size.entry(indent).or_default().push(row);
8425 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8426 }
8427
8428 let indent_size = indent_size_occurrences
8429 .into_iter()
8430 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8431 .map(|(indent, _)| indent)
8432 .unwrap_or_default();
8433 let row = rows_by_indent_size[&indent_size][0];
8434 let indent_end = Point::new(row, indent_size.len);
8435
8436 (indent_size, indent_end)
8437 };
8438
8439 let mut line_prefix = indent_size.chars().collect::<String>();
8440
8441 let mut inside_comment = false;
8442 if let Some(comment_prefix) =
8443 buffer
8444 .language_scope_at(selection.head())
8445 .and_then(|language| {
8446 language
8447 .line_comment_prefixes()
8448 .iter()
8449 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8450 .cloned()
8451 })
8452 {
8453 line_prefix.push_str(&comment_prefix);
8454 inside_comment = true;
8455 }
8456
8457 let language_settings = buffer.settings_at(selection.head(), cx);
8458 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8459 RewrapBehavior::InComments => inside_comment,
8460 RewrapBehavior::InSelections => !selection.is_empty(),
8461 RewrapBehavior::Anywhere => true,
8462 };
8463
8464 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8465 if !should_rewrap {
8466 continue;
8467 }
8468
8469 if selection.is_empty() {
8470 'expand_upwards: while start_row > 0 {
8471 let prev_row = start_row - 1;
8472 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8473 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8474 {
8475 start_row = prev_row;
8476 } else {
8477 break 'expand_upwards;
8478 }
8479 }
8480
8481 'expand_downwards: while end_row < buffer.max_point().row {
8482 let next_row = end_row + 1;
8483 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8484 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8485 {
8486 end_row = next_row;
8487 } else {
8488 break 'expand_downwards;
8489 }
8490 }
8491 }
8492
8493 let start = Point::new(start_row, 0);
8494 let start_offset = start.to_offset(&buffer);
8495 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8496 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8497 let Some(lines_without_prefixes) = selection_text
8498 .lines()
8499 .map(|line| {
8500 line.strip_prefix(&line_prefix)
8501 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8502 .ok_or_else(|| {
8503 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8504 })
8505 })
8506 .collect::<Result<Vec<_>, _>>()
8507 .log_err()
8508 else {
8509 continue;
8510 };
8511
8512 let wrap_column = buffer
8513 .settings_at(Point::new(start_row, 0), cx)
8514 .preferred_line_length as usize;
8515 let wrapped_text = wrap_with_prefix(
8516 line_prefix,
8517 lines_without_prefixes.join(" "),
8518 wrap_column,
8519 tab_size,
8520 );
8521
8522 // TODO: should always use char-based diff while still supporting cursor behavior that
8523 // matches vim.
8524 let mut diff_options = DiffOptions::default();
8525 if is_vim_mode == IsVimMode::Yes {
8526 diff_options.max_word_diff_len = 0;
8527 diff_options.max_word_diff_line_count = 0;
8528 } else {
8529 diff_options.max_word_diff_len = usize::MAX;
8530 diff_options.max_word_diff_line_count = usize::MAX;
8531 }
8532
8533 for (old_range, new_text) in
8534 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8535 {
8536 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8537 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8538 edits.push((edit_start..edit_end, new_text));
8539 }
8540
8541 rewrapped_row_ranges.push(start_row..=end_row);
8542 }
8543
8544 self.buffer
8545 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8546 }
8547
8548 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8549 let mut text = String::new();
8550 let buffer = self.buffer.read(cx).snapshot(cx);
8551 let mut selections = self.selections.all::<Point>(cx);
8552 let mut clipboard_selections = Vec::with_capacity(selections.len());
8553 {
8554 let max_point = buffer.max_point();
8555 let mut is_first = true;
8556 for selection in &mut selections {
8557 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8558 if is_entire_line {
8559 selection.start = Point::new(selection.start.row, 0);
8560 if !selection.is_empty() && selection.end.column == 0 {
8561 selection.end = cmp::min(max_point, selection.end);
8562 } else {
8563 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8564 }
8565 selection.goal = SelectionGoal::None;
8566 }
8567 if is_first {
8568 is_first = false;
8569 } else {
8570 text += "\n";
8571 }
8572 let mut len = 0;
8573 for chunk in buffer.text_for_range(selection.start..selection.end) {
8574 text.push_str(chunk);
8575 len += chunk.len();
8576 }
8577 clipboard_selections.push(ClipboardSelection {
8578 len,
8579 is_entire_line,
8580 start_column: selection.start.column,
8581 });
8582 }
8583 }
8584
8585 self.transact(window, cx, |this, window, cx| {
8586 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8587 s.select(selections);
8588 });
8589 this.insert("", window, cx);
8590 });
8591 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8592 }
8593
8594 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8595 let item = self.cut_common(window, cx);
8596 cx.write_to_clipboard(item);
8597 }
8598
8599 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8600 self.change_selections(None, window, cx, |s| {
8601 s.move_with(|snapshot, sel| {
8602 if sel.is_empty() {
8603 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8604 }
8605 });
8606 });
8607 let item = self.cut_common(window, cx);
8608 cx.set_global(KillRing(item))
8609 }
8610
8611 pub fn kill_ring_yank(
8612 &mut self,
8613 _: &KillRingYank,
8614 window: &mut Window,
8615 cx: &mut Context<Self>,
8616 ) {
8617 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8618 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8619 (kill_ring.text().to_string(), kill_ring.metadata_json())
8620 } else {
8621 return;
8622 }
8623 } else {
8624 return;
8625 };
8626 self.do_paste(&text, metadata, false, window, cx);
8627 }
8628
8629 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8630 let selections = self.selections.all::<Point>(cx);
8631 let buffer = self.buffer.read(cx).read(cx);
8632 let mut text = String::new();
8633
8634 let mut clipboard_selections = Vec::with_capacity(selections.len());
8635 {
8636 let max_point = buffer.max_point();
8637 let mut is_first = true;
8638 for selection in selections.iter() {
8639 let mut start = selection.start;
8640 let mut end = selection.end;
8641 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8642 if is_entire_line {
8643 start = Point::new(start.row, 0);
8644 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8645 }
8646 if is_first {
8647 is_first = false;
8648 } else {
8649 text += "\n";
8650 }
8651 let mut len = 0;
8652 for chunk in buffer.text_for_range(start..end) {
8653 text.push_str(chunk);
8654 len += chunk.len();
8655 }
8656 clipboard_selections.push(ClipboardSelection {
8657 len,
8658 is_entire_line,
8659 start_column: start.column,
8660 });
8661 }
8662 }
8663
8664 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8665 text,
8666 clipboard_selections,
8667 ));
8668 }
8669
8670 pub fn do_paste(
8671 &mut self,
8672 text: &String,
8673 clipboard_selections: Option<Vec<ClipboardSelection>>,
8674 handle_entire_lines: bool,
8675 window: &mut Window,
8676 cx: &mut Context<Self>,
8677 ) {
8678 if self.read_only(cx) {
8679 return;
8680 }
8681
8682 let clipboard_text = Cow::Borrowed(text);
8683
8684 self.transact(window, cx, |this, window, cx| {
8685 if let Some(mut clipboard_selections) = clipboard_selections {
8686 let old_selections = this.selections.all::<usize>(cx);
8687 let all_selections_were_entire_line =
8688 clipboard_selections.iter().all(|s| s.is_entire_line);
8689 let first_selection_start_column =
8690 clipboard_selections.first().map(|s| s.start_column);
8691 if clipboard_selections.len() != old_selections.len() {
8692 clipboard_selections.drain(..);
8693 }
8694 let cursor_offset = this.selections.last::<usize>(cx).head();
8695 let mut auto_indent_on_paste = true;
8696
8697 this.buffer.update(cx, |buffer, cx| {
8698 let snapshot = buffer.read(cx);
8699 auto_indent_on_paste =
8700 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8701
8702 let mut start_offset = 0;
8703 let mut edits = Vec::new();
8704 let mut original_start_columns = Vec::new();
8705 for (ix, selection) in old_selections.iter().enumerate() {
8706 let to_insert;
8707 let entire_line;
8708 let original_start_column;
8709 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8710 let end_offset = start_offset + clipboard_selection.len;
8711 to_insert = &clipboard_text[start_offset..end_offset];
8712 entire_line = clipboard_selection.is_entire_line;
8713 start_offset = end_offset + 1;
8714 original_start_column = Some(clipboard_selection.start_column);
8715 } else {
8716 to_insert = clipboard_text.as_str();
8717 entire_line = all_selections_were_entire_line;
8718 original_start_column = first_selection_start_column
8719 }
8720
8721 // If the corresponding selection was empty when this slice of the
8722 // clipboard text was written, then the entire line containing the
8723 // selection was copied. If this selection is also currently empty,
8724 // then paste the line before the current line of the buffer.
8725 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8726 let column = selection.start.to_point(&snapshot).column as usize;
8727 let line_start = selection.start - column;
8728 line_start..line_start
8729 } else {
8730 selection.range()
8731 };
8732
8733 edits.push((range, to_insert));
8734 original_start_columns.extend(original_start_column);
8735 }
8736 drop(snapshot);
8737
8738 buffer.edit(
8739 edits,
8740 if auto_indent_on_paste {
8741 Some(AutoindentMode::Block {
8742 original_start_columns,
8743 })
8744 } else {
8745 None
8746 },
8747 cx,
8748 );
8749 });
8750
8751 let selections = this.selections.all::<usize>(cx);
8752 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8753 s.select(selections)
8754 });
8755 } else {
8756 this.insert(&clipboard_text, window, cx);
8757 }
8758 });
8759 }
8760
8761 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8762 if let Some(item) = cx.read_from_clipboard() {
8763 let entries = item.entries();
8764
8765 match entries.first() {
8766 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8767 // of all the pasted entries.
8768 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8769 .do_paste(
8770 clipboard_string.text(),
8771 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8772 true,
8773 window,
8774 cx,
8775 ),
8776 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8777 }
8778 }
8779 }
8780
8781 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8782 if self.read_only(cx) {
8783 return;
8784 }
8785
8786 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8787 if let Some((selections, _)) =
8788 self.selection_history.transaction(transaction_id).cloned()
8789 {
8790 self.change_selections(None, window, cx, |s| {
8791 s.select_anchors(selections.to_vec());
8792 });
8793 } else {
8794 log::error!(
8795 "No entry in selection_history found for undo. \
8796 This may correspond to a bug where undo does not update the selection. \
8797 If this is occurring, please add details to \
8798 https://github.com/zed-industries/zed/issues/22692"
8799 );
8800 }
8801 self.request_autoscroll(Autoscroll::fit(), cx);
8802 self.unmark_text(window, cx);
8803 self.refresh_inline_completion(true, false, window, cx);
8804 cx.emit(EditorEvent::Edited { transaction_id });
8805 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8806 }
8807 }
8808
8809 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8810 if self.read_only(cx) {
8811 return;
8812 }
8813
8814 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8815 if let Some((_, Some(selections))) =
8816 self.selection_history.transaction(transaction_id).cloned()
8817 {
8818 self.change_selections(None, window, cx, |s| {
8819 s.select_anchors(selections.to_vec());
8820 });
8821 } else {
8822 log::error!(
8823 "No entry in selection_history found for redo. \
8824 This may correspond to a bug where undo does not update the selection. \
8825 If this is occurring, please add details to \
8826 https://github.com/zed-industries/zed/issues/22692"
8827 );
8828 }
8829 self.request_autoscroll(Autoscroll::fit(), cx);
8830 self.unmark_text(window, cx);
8831 self.refresh_inline_completion(true, false, window, cx);
8832 cx.emit(EditorEvent::Edited { transaction_id });
8833 }
8834 }
8835
8836 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8837 self.buffer
8838 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8839 }
8840
8841 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8842 self.buffer
8843 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8844 }
8845
8846 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8847 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8848 let line_mode = s.line_mode;
8849 s.move_with(|map, selection| {
8850 let cursor = if selection.is_empty() && !line_mode {
8851 movement::left(map, selection.start)
8852 } else {
8853 selection.start
8854 };
8855 selection.collapse_to(cursor, SelectionGoal::None);
8856 });
8857 })
8858 }
8859
8860 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8861 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8862 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8863 })
8864 }
8865
8866 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8867 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8868 let line_mode = s.line_mode;
8869 s.move_with(|map, selection| {
8870 let cursor = if selection.is_empty() && !line_mode {
8871 movement::right(map, selection.end)
8872 } else {
8873 selection.end
8874 };
8875 selection.collapse_to(cursor, SelectionGoal::None)
8876 });
8877 })
8878 }
8879
8880 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8881 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8882 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8883 })
8884 }
8885
8886 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8887 if self.take_rename(true, window, cx).is_some() {
8888 return;
8889 }
8890
8891 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8892 cx.propagate();
8893 return;
8894 }
8895
8896 let text_layout_details = &self.text_layout_details(window);
8897 let selection_count = self.selections.count();
8898 let first_selection = self.selections.first_anchor();
8899
8900 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8901 let line_mode = s.line_mode;
8902 s.move_with(|map, selection| {
8903 if !selection.is_empty() && !line_mode {
8904 selection.goal = SelectionGoal::None;
8905 }
8906 let (cursor, goal) = movement::up(
8907 map,
8908 selection.start,
8909 selection.goal,
8910 false,
8911 text_layout_details,
8912 );
8913 selection.collapse_to(cursor, goal);
8914 });
8915 });
8916
8917 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8918 {
8919 cx.propagate();
8920 }
8921 }
8922
8923 pub fn move_up_by_lines(
8924 &mut self,
8925 action: &MoveUpByLines,
8926 window: &mut Window,
8927 cx: &mut Context<Self>,
8928 ) {
8929 if self.take_rename(true, window, cx).is_some() {
8930 return;
8931 }
8932
8933 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8934 cx.propagate();
8935 return;
8936 }
8937
8938 let text_layout_details = &self.text_layout_details(window);
8939
8940 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8941 let line_mode = s.line_mode;
8942 s.move_with(|map, selection| {
8943 if !selection.is_empty() && !line_mode {
8944 selection.goal = SelectionGoal::None;
8945 }
8946 let (cursor, goal) = movement::up_by_rows(
8947 map,
8948 selection.start,
8949 action.lines,
8950 selection.goal,
8951 false,
8952 text_layout_details,
8953 );
8954 selection.collapse_to(cursor, goal);
8955 });
8956 })
8957 }
8958
8959 pub fn move_down_by_lines(
8960 &mut self,
8961 action: &MoveDownByLines,
8962 window: &mut Window,
8963 cx: &mut Context<Self>,
8964 ) {
8965 if self.take_rename(true, window, cx).is_some() {
8966 return;
8967 }
8968
8969 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8970 cx.propagate();
8971 return;
8972 }
8973
8974 let text_layout_details = &self.text_layout_details(window);
8975
8976 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8977 let line_mode = s.line_mode;
8978 s.move_with(|map, selection| {
8979 if !selection.is_empty() && !line_mode {
8980 selection.goal = SelectionGoal::None;
8981 }
8982 let (cursor, goal) = movement::down_by_rows(
8983 map,
8984 selection.start,
8985 action.lines,
8986 selection.goal,
8987 false,
8988 text_layout_details,
8989 );
8990 selection.collapse_to(cursor, goal);
8991 });
8992 })
8993 }
8994
8995 pub fn select_down_by_lines(
8996 &mut self,
8997 action: &SelectDownByLines,
8998 window: &mut Window,
8999 cx: &mut Context<Self>,
9000 ) {
9001 let text_layout_details = &self.text_layout_details(window);
9002 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9003 s.move_heads_with(|map, head, goal| {
9004 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9005 })
9006 })
9007 }
9008
9009 pub fn select_up_by_lines(
9010 &mut self,
9011 action: &SelectUpByLines,
9012 window: &mut Window,
9013 cx: &mut Context<Self>,
9014 ) {
9015 let text_layout_details = &self.text_layout_details(window);
9016 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9017 s.move_heads_with(|map, head, goal| {
9018 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9019 })
9020 })
9021 }
9022
9023 pub fn select_page_up(
9024 &mut self,
9025 _: &SelectPageUp,
9026 window: &mut Window,
9027 cx: &mut Context<Self>,
9028 ) {
9029 let Some(row_count) = self.visible_row_count() else {
9030 return;
9031 };
9032
9033 let text_layout_details = &self.text_layout_details(window);
9034
9035 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9036 s.move_heads_with(|map, head, goal| {
9037 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9038 })
9039 })
9040 }
9041
9042 pub fn move_page_up(
9043 &mut self,
9044 action: &MovePageUp,
9045 window: &mut Window,
9046 cx: &mut Context<Self>,
9047 ) {
9048 if self.take_rename(true, window, cx).is_some() {
9049 return;
9050 }
9051
9052 if self
9053 .context_menu
9054 .borrow_mut()
9055 .as_mut()
9056 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9057 .unwrap_or(false)
9058 {
9059 return;
9060 }
9061
9062 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9063 cx.propagate();
9064 return;
9065 }
9066
9067 let Some(row_count) = self.visible_row_count() else {
9068 return;
9069 };
9070
9071 let autoscroll = if action.center_cursor {
9072 Autoscroll::center()
9073 } else {
9074 Autoscroll::fit()
9075 };
9076
9077 let text_layout_details = &self.text_layout_details(window);
9078
9079 self.change_selections(Some(autoscroll), window, cx, |s| {
9080 let line_mode = s.line_mode;
9081 s.move_with(|map, selection| {
9082 if !selection.is_empty() && !line_mode {
9083 selection.goal = SelectionGoal::None;
9084 }
9085 let (cursor, goal) = movement::up_by_rows(
9086 map,
9087 selection.end,
9088 row_count,
9089 selection.goal,
9090 false,
9091 text_layout_details,
9092 );
9093 selection.collapse_to(cursor, goal);
9094 });
9095 });
9096 }
9097
9098 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9099 let text_layout_details = &self.text_layout_details(window);
9100 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9101 s.move_heads_with(|map, head, goal| {
9102 movement::up(map, head, goal, false, text_layout_details)
9103 })
9104 })
9105 }
9106
9107 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9108 self.take_rename(true, window, cx);
9109
9110 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9111 cx.propagate();
9112 return;
9113 }
9114
9115 let text_layout_details = &self.text_layout_details(window);
9116 let selection_count = self.selections.count();
9117 let first_selection = self.selections.first_anchor();
9118
9119 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9120 let line_mode = s.line_mode;
9121 s.move_with(|map, selection| {
9122 if !selection.is_empty() && !line_mode {
9123 selection.goal = SelectionGoal::None;
9124 }
9125 let (cursor, goal) = movement::down(
9126 map,
9127 selection.end,
9128 selection.goal,
9129 false,
9130 text_layout_details,
9131 );
9132 selection.collapse_to(cursor, goal);
9133 });
9134 });
9135
9136 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9137 {
9138 cx.propagate();
9139 }
9140 }
9141
9142 pub fn select_page_down(
9143 &mut self,
9144 _: &SelectPageDown,
9145 window: &mut Window,
9146 cx: &mut Context<Self>,
9147 ) {
9148 let Some(row_count) = self.visible_row_count() else {
9149 return;
9150 };
9151
9152 let text_layout_details = &self.text_layout_details(window);
9153
9154 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9155 s.move_heads_with(|map, head, goal| {
9156 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9157 })
9158 })
9159 }
9160
9161 pub fn move_page_down(
9162 &mut self,
9163 action: &MovePageDown,
9164 window: &mut Window,
9165 cx: &mut Context<Self>,
9166 ) {
9167 if self.take_rename(true, window, cx).is_some() {
9168 return;
9169 }
9170
9171 if self
9172 .context_menu
9173 .borrow_mut()
9174 .as_mut()
9175 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9176 .unwrap_or(false)
9177 {
9178 return;
9179 }
9180
9181 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9182 cx.propagate();
9183 return;
9184 }
9185
9186 let Some(row_count) = self.visible_row_count() else {
9187 return;
9188 };
9189
9190 let autoscroll = if action.center_cursor {
9191 Autoscroll::center()
9192 } else {
9193 Autoscroll::fit()
9194 };
9195
9196 let text_layout_details = &self.text_layout_details(window);
9197 self.change_selections(Some(autoscroll), window, cx, |s| {
9198 let line_mode = s.line_mode;
9199 s.move_with(|map, selection| {
9200 if !selection.is_empty() && !line_mode {
9201 selection.goal = SelectionGoal::None;
9202 }
9203 let (cursor, goal) = movement::down_by_rows(
9204 map,
9205 selection.end,
9206 row_count,
9207 selection.goal,
9208 false,
9209 text_layout_details,
9210 );
9211 selection.collapse_to(cursor, goal);
9212 });
9213 });
9214 }
9215
9216 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9217 let text_layout_details = &self.text_layout_details(window);
9218 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9219 s.move_heads_with(|map, head, goal| {
9220 movement::down(map, head, goal, false, text_layout_details)
9221 })
9222 });
9223 }
9224
9225 pub fn context_menu_first(
9226 &mut self,
9227 _: &ContextMenuFirst,
9228 _window: &mut Window,
9229 cx: &mut Context<Self>,
9230 ) {
9231 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9232 context_menu.select_first(self.completion_provider.as_deref(), cx);
9233 }
9234 }
9235
9236 pub fn context_menu_prev(
9237 &mut self,
9238 _: &ContextMenuPrev,
9239 _window: &mut Window,
9240 cx: &mut Context<Self>,
9241 ) {
9242 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9243 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9244 }
9245 }
9246
9247 pub fn context_menu_next(
9248 &mut self,
9249 _: &ContextMenuNext,
9250 _window: &mut Window,
9251 cx: &mut Context<Self>,
9252 ) {
9253 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9254 context_menu.select_next(self.completion_provider.as_deref(), cx);
9255 }
9256 }
9257
9258 pub fn context_menu_last(
9259 &mut self,
9260 _: &ContextMenuLast,
9261 _window: &mut Window,
9262 cx: &mut Context<Self>,
9263 ) {
9264 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9265 context_menu.select_last(self.completion_provider.as_deref(), cx);
9266 }
9267 }
9268
9269 pub fn move_to_previous_word_start(
9270 &mut self,
9271 _: &MoveToPreviousWordStart,
9272 window: &mut Window,
9273 cx: &mut Context<Self>,
9274 ) {
9275 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9276 s.move_cursors_with(|map, head, _| {
9277 (
9278 movement::previous_word_start(map, head),
9279 SelectionGoal::None,
9280 )
9281 });
9282 })
9283 }
9284
9285 pub fn move_to_previous_subword_start(
9286 &mut self,
9287 _: &MoveToPreviousSubwordStart,
9288 window: &mut Window,
9289 cx: &mut Context<Self>,
9290 ) {
9291 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9292 s.move_cursors_with(|map, head, _| {
9293 (
9294 movement::previous_subword_start(map, head),
9295 SelectionGoal::None,
9296 )
9297 });
9298 })
9299 }
9300
9301 pub fn select_to_previous_word_start(
9302 &mut self,
9303 _: &SelectToPreviousWordStart,
9304 window: &mut Window,
9305 cx: &mut Context<Self>,
9306 ) {
9307 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9308 s.move_heads_with(|map, head, _| {
9309 (
9310 movement::previous_word_start(map, head),
9311 SelectionGoal::None,
9312 )
9313 });
9314 })
9315 }
9316
9317 pub fn select_to_previous_subword_start(
9318 &mut self,
9319 _: &SelectToPreviousSubwordStart,
9320 window: &mut Window,
9321 cx: &mut Context<Self>,
9322 ) {
9323 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9324 s.move_heads_with(|map, head, _| {
9325 (
9326 movement::previous_subword_start(map, head),
9327 SelectionGoal::None,
9328 )
9329 });
9330 })
9331 }
9332
9333 pub fn delete_to_previous_word_start(
9334 &mut self,
9335 action: &DeleteToPreviousWordStart,
9336 window: &mut Window,
9337 cx: &mut Context<Self>,
9338 ) {
9339 self.transact(window, cx, |this, window, cx| {
9340 this.select_autoclose_pair(window, cx);
9341 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9342 let line_mode = s.line_mode;
9343 s.move_with(|map, selection| {
9344 if selection.is_empty() && !line_mode {
9345 let cursor = if action.ignore_newlines {
9346 movement::previous_word_start(map, selection.head())
9347 } else {
9348 movement::previous_word_start_or_newline(map, selection.head())
9349 };
9350 selection.set_head(cursor, SelectionGoal::None);
9351 }
9352 });
9353 });
9354 this.insert("", window, cx);
9355 });
9356 }
9357
9358 pub fn delete_to_previous_subword_start(
9359 &mut self,
9360 _: &DeleteToPreviousSubwordStart,
9361 window: &mut Window,
9362 cx: &mut Context<Self>,
9363 ) {
9364 self.transact(window, cx, |this, window, cx| {
9365 this.select_autoclose_pair(window, cx);
9366 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9367 let line_mode = s.line_mode;
9368 s.move_with(|map, selection| {
9369 if selection.is_empty() && !line_mode {
9370 let cursor = movement::previous_subword_start(map, selection.head());
9371 selection.set_head(cursor, SelectionGoal::None);
9372 }
9373 });
9374 });
9375 this.insert("", window, cx);
9376 });
9377 }
9378
9379 pub fn move_to_next_word_end(
9380 &mut self,
9381 _: &MoveToNextWordEnd,
9382 window: &mut Window,
9383 cx: &mut Context<Self>,
9384 ) {
9385 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9386 s.move_cursors_with(|map, head, _| {
9387 (movement::next_word_end(map, head), SelectionGoal::None)
9388 });
9389 })
9390 }
9391
9392 pub fn move_to_next_subword_end(
9393 &mut self,
9394 _: &MoveToNextSubwordEnd,
9395 window: &mut Window,
9396 cx: &mut Context<Self>,
9397 ) {
9398 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9399 s.move_cursors_with(|map, head, _| {
9400 (movement::next_subword_end(map, head), SelectionGoal::None)
9401 });
9402 })
9403 }
9404
9405 pub fn select_to_next_word_end(
9406 &mut self,
9407 _: &SelectToNextWordEnd,
9408 window: &mut Window,
9409 cx: &mut Context<Self>,
9410 ) {
9411 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9412 s.move_heads_with(|map, head, _| {
9413 (movement::next_word_end(map, head), SelectionGoal::None)
9414 });
9415 })
9416 }
9417
9418 pub fn select_to_next_subword_end(
9419 &mut self,
9420 _: &SelectToNextSubwordEnd,
9421 window: &mut Window,
9422 cx: &mut Context<Self>,
9423 ) {
9424 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9425 s.move_heads_with(|map, head, _| {
9426 (movement::next_subword_end(map, head), SelectionGoal::None)
9427 });
9428 })
9429 }
9430
9431 pub fn delete_to_next_word_end(
9432 &mut self,
9433 action: &DeleteToNextWordEnd,
9434 window: &mut Window,
9435 cx: &mut Context<Self>,
9436 ) {
9437 self.transact(window, cx, |this, window, cx| {
9438 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9439 let line_mode = s.line_mode;
9440 s.move_with(|map, selection| {
9441 if selection.is_empty() && !line_mode {
9442 let cursor = if action.ignore_newlines {
9443 movement::next_word_end(map, selection.head())
9444 } else {
9445 movement::next_word_end_or_newline(map, selection.head())
9446 };
9447 selection.set_head(cursor, SelectionGoal::None);
9448 }
9449 });
9450 });
9451 this.insert("", window, cx);
9452 });
9453 }
9454
9455 pub fn delete_to_next_subword_end(
9456 &mut self,
9457 _: &DeleteToNextSubwordEnd,
9458 window: &mut Window,
9459 cx: &mut Context<Self>,
9460 ) {
9461 self.transact(window, cx, |this, window, cx| {
9462 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9463 s.move_with(|map, selection| {
9464 if selection.is_empty() {
9465 let cursor = movement::next_subword_end(map, selection.head());
9466 selection.set_head(cursor, SelectionGoal::None);
9467 }
9468 });
9469 });
9470 this.insert("", window, cx);
9471 });
9472 }
9473
9474 pub fn move_to_beginning_of_line(
9475 &mut self,
9476 action: &MoveToBeginningOfLine,
9477 window: &mut Window,
9478 cx: &mut Context<Self>,
9479 ) {
9480 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9481 s.move_cursors_with(|map, head, _| {
9482 (
9483 movement::indented_line_beginning(
9484 map,
9485 head,
9486 action.stop_at_soft_wraps,
9487 action.stop_at_indent,
9488 ),
9489 SelectionGoal::None,
9490 )
9491 });
9492 })
9493 }
9494
9495 pub fn select_to_beginning_of_line(
9496 &mut self,
9497 action: &SelectToBeginningOfLine,
9498 window: &mut Window,
9499 cx: &mut Context<Self>,
9500 ) {
9501 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9502 s.move_heads_with(|map, head, _| {
9503 (
9504 movement::indented_line_beginning(
9505 map,
9506 head,
9507 action.stop_at_soft_wraps,
9508 action.stop_at_indent,
9509 ),
9510 SelectionGoal::None,
9511 )
9512 });
9513 });
9514 }
9515
9516 pub fn delete_to_beginning_of_line(
9517 &mut self,
9518 _: &DeleteToBeginningOfLine,
9519 window: &mut Window,
9520 cx: &mut Context<Self>,
9521 ) {
9522 self.transact(window, cx, |this, window, cx| {
9523 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9524 s.move_with(|_, selection| {
9525 selection.reversed = true;
9526 });
9527 });
9528
9529 this.select_to_beginning_of_line(
9530 &SelectToBeginningOfLine {
9531 stop_at_soft_wraps: false,
9532 stop_at_indent: false,
9533 },
9534 window,
9535 cx,
9536 );
9537 this.backspace(&Backspace, window, cx);
9538 });
9539 }
9540
9541 pub fn move_to_end_of_line(
9542 &mut self,
9543 action: &MoveToEndOfLine,
9544 window: &mut Window,
9545 cx: &mut Context<Self>,
9546 ) {
9547 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9548 s.move_cursors_with(|map, head, _| {
9549 (
9550 movement::line_end(map, head, action.stop_at_soft_wraps),
9551 SelectionGoal::None,
9552 )
9553 });
9554 })
9555 }
9556
9557 pub fn select_to_end_of_line(
9558 &mut self,
9559 action: &SelectToEndOfLine,
9560 window: &mut Window,
9561 cx: &mut Context<Self>,
9562 ) {
9563 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9564 s.move_heads_with(|map, head, _| {
9565 (
9566 movement::line_end(map, head, action.stop_at_soft_wraps),
9567 SelectionGoal::None,
9568 )
9569 });
9570 })
9571 }
9572
9573 pub fn delete_to_end_of_line(
9574 &mut self,
9575 _: &DeleteToEndOfLine,
9576 window: &mut Window,
9577 cx: &mut Context<Self>,
9578 ) {
9579 self.transact(window, cx, |this, window, cx| {
9580 this.select_to_end_of_line(
9581 &SelectToEndOfLine {
9582 stop_at_soft_wraps: false,
9583 },
9584 window,
9585 cx,
9586 );
9587 this.delete(&Delete, window, cx);
9588 });
9589 }
9590
9591 pub fn cut_to_end_of_line(
9592 &mut self,
9593 _: &CutToEndOfLine,
9594 window: &mut Window,
9595 cx: &mut Context<Self>,
9596 ) {
9597 self.transact(window, cx, |this, window, cx| {
9598 this.select_to_end_of_line(
9599 &SelectToEndOfLine {
9600 stop_at_soft_wraps: false,
9601 },
9602 window,
9603 cx,
9604 );
9605 this.cut(&Cut, window, cx);
9606 });
9607 }
9608
9609 pub fn move_to_start_of_paragraph(
9610 &mut self,
9611 _: &MoveToStartOfParagraph,
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::start_of_paragraph(map, selection.head(), 1),
9624 SelectionGoal::None,
9625 )
9626 });
9627 })
9628 }
9629
9630 pub fn move_to_end_of_paragraph(
9631 &mut self,
9632 _: &MoveToEndOfParagraph,
9633 window: &mut Window,
9634 cx: &mut Context<Self>,
9635 ) {
9636 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9637 cx.propagate();
9638 return;
9639 }
9640
9641 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9642 s.move_with(|map, selection| {
9643 selection.collapse_to(
9644 movement::end_of_paragraph(map, selection.head(), 1),
9645 SelectionGoal::None,
9646 )
9647 });
9648 })
9649 }
9650
9651 pub fn select_to_start_of_paragraph(
9652 &mut self,
9653 _: &SelectToStartOfParagraph,
9654 window: &mut Window,
9655 cx: &mut Context<Self>,
9656 ) {
9657 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9658 cx.propagate();
9659 return;
9660 }
9661
9662 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9663 s.move_heads_with(|map, head, _| {
9664 (
9665 movement::start_of_paragraph(map, head, 1),
9666 SelectionGoal::None,
9667 )
9668 });
9669 })
9670 }
9671
9672 pub fn select_to_end_of_paragraph(
9673 &mut self,
9674 _: &SelectToEndOfParagraph,
9675 window: &mut Window,
9676 cx: &mut Context<Self>,
9677 ) {
9678 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9679 cx.propagate();
9680 return;
9681 }
9682
9683 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9684 s.move_heads_with(|map, head, _| {
9685 (
9686 movement::end_of_paragraph(map, head, 1),
9687 SelectionGoal::None,
9688 )
9689 });
9690 })
9691 }
9692
9693 pub fn move_to_start_of_excerpt(
9694 &mut self,
9695 _: &MoveToStartOfExcerpt,
9696 window: &mut Window,
9697 cx: &mut Context<Self>,
9698 ) {
9699 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9700 cx.propagate();
9701 return;
9702 }
9703
9704 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9705 s.move_with(|map, selection| {
9706 selection.collapse_to(
9707 movement::start_of_excerpt(
9708 map,
9709 selection.head(),
9710 workspace::searchable::Direction::Prev,
9711 ),
9712 SelectionGoal::None,
9713 )
9714 });
9715 })
9716 }
9717
9718 pub fn move_to_end_of_excerpt(
9719 &mut self,
9720 _: &MoveToEndOfExcerpt,
9721 window: &mut Window,
9722 cx: &mut Context<Self>,
9723 ) {
9724 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9725 cx.propagate();
9726 return;
9727 }
9728
9729 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9730 s.move_with(|map, selection| {
9731 selection.collapse_to(
9732 movement::end_of_excerpt(
9733 map,
9734 selection.head(),
9735 workspace::searchable::Direction::Next,
9736 ),
9737 SelectionGoal::None,
9738 )
9739 });
9740 })
9741 }
9742
9743 pub fn select_to_start_of_excerpt(
9744 &mut self,
9745 _: &SelectToStartOfExcerpt,
9746 window: &mut Window,
9747 cx: &mut Context<Self>,
9748 ) {
9749 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9750 cx.propagate();
9751 return;
9752 }
9753
9754 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9755 s.move_heads_with(|map, head, _| {
9756 (
9757 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9758 SelectionGoal::None,
9759 )
9760 });
9761 })
9762 }
9763
9764 pub fn select_to_end_of_excerpt(
9765 &mut self,
9766 _: &SelectToEndOfExcerpt,
9767 window: &mut Window,
9768 cx: &mut Context<Self>,
9769 ) {
9770 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9771 cx.propagate();
9772 return;
9773 }
9774
9775 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9776 s.move_heads_with(|map, head, _| {
9777 (
9778 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9779 SelectionGoal::None,
9780 )
9781 });
9782 })
9783 }
9784
9785 pub fn move_to_beginning(
9786 &mut self,
9787 _: &MoveToBeginning,
9788 window: &mut Window,
9789 cx: &mut Context<Self>,
9790 ) {
9791 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9792 cx.propagate();
9793 return;
9794 }
9795
9796 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9797 s.select_ranges(vec![0..0]);
9798 });
9799 }
9800
9801 pub fn select_to_beginning(
9802 &mut self,
9803 _: &SelectToBeginning,
9804 window: &mut Window,
9805 cx: &mut Context<Self>,
9806 ) {
9807 let mut selection = self.selections.last::<Point>(cx);
9808 selection.set_head(Point::zero(), SelectionGoal::None);
9809
9810 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9811 s.select(vec![selection]);
9812 });
9813 }
9814
9815 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9816 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9817 cx.propagate();
9818 return;
9819 }
9820
9821 let cursor = self.buffer.read(cx).read(cx).len();
9822 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9823 s.select_ranges(vec![cursor..cursor])
9824 });
9825 }
9826
9827 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9828 self.nav_history = nav_history;
9829 }
9830
9831 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9832 self.nav_history.as_ref()
9833 }
9834
9835 fn push_to_nav_history(
9836 &mut self,
9837 cursor_anchor: Anchor,
9838 new_position: Option<Point>,
9839 cx: &mut Context<Self>,
9840 ) {
9841 if let Some(nav_history) = self.nav_history.as_mut() {
9842 let buffer = self.buffer.read(cx).read(cx);
9843 let cursor_position = cursor_anchor.to_point(&buffer);
9844 let scroll_state = self.scroll_manager.anchor();
9845 let scroll_top_row = scroll_state.top_row(&buffer);
9846 drop(buffer);
9847
9848 if let Some(new_position) = new_position {
9849 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9850 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9851 return;
9852 }
9853 }
9854
9855 nav_history.push(
9856 Some(NavigationData {
9857 cursor_anchor,
9858 cursor_position,
9859 scroll_anchor: scroll_state,
9860 scroll_top_row,
9861 }),
9862 cx,
9863 );
9864 }
9865 }
9866
9867 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9868 let buffer = self.buffer.read(cx).snapshot(cx);
9869 let mut selection = self.selections.first::<usize>(cx);
9870 selection.set_head(buffer.len(), SelectionGoal::None);
9871 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9872 s.select(vec![selection]);
9873 });
9874 }
9875
9876 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9877 let end = self.buffer.read(cx).read(cx).len();
9878 self.change_selections(None, window, cx, |s| {
9879 s.select_ranges(vec![0..end]);
9880 });
9881 }
9882
9883 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9884 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9885 let mut selections = self.selections.all::<Point>(cx);
9886 let max_point = display_map.buffer_snapshot.max_point();
9887 for selection in &mut selections {
9888 let rows = selection.spanned_rows(true, &display_map);
9889 selection.start = Point::new(rows.start.0, 0);
9890 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9891 selection.reversed = false;
9892 }
9893 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9894 s.select(selections);
9895 });
9896 }
9897
9898 pub fn split_selection_into_lines(
9899 &mut self,
9900 _: &SplitSelectionIntoLines,
9901 window: &mut Window,
9902 cx: &mut Context<Self>,
9903 ) {
9904 let selections = self
9905 .selections
9906 .all::<Point>(cx)
9907 .into_iter()
9908 .map(|selection| selection.start..selection.end)
9909 .collect::<Vec<_>>();
9910 self.unfold_ranges(&selections, true, true, cx);
9911
9912 let mut new_selection_ranges = Vec::new();
9913 {
9914 let buffer = self.buffer.read(cx).read(cx);
9915 for selection in selections {
9916 for row in selection.start.row..selection.end.row {
9917 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9918 new_selection_ranges.push(cursor..cursor);
9919 }
9920
9921 let is_multiline_selection = selection.start.row != selection.end.row;
9922 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9923 // so this action feels more ergonomic when paired with other selection operations
9924 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9925 if !should_skip_last {
9926 new_selection_ranges.push(selection.end..selection.end);
9927 }
9928 }
9929 }
9930 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9931 s.select_ranges(new_selection_ranges);
9932 });
9933 }
9934
9935 pub fn add_selection_above(
9936 &mut self,
9937 _: &AddSelectionAbove,
9938 window: &mut Window,
9939 cx: &mut Context<Self>,
9940 ) {
9941 self.add_selection(true, window, cx);
9942 }
9943
9944 pub fn add_selection_below(
9945 &mut self,
9946 _: &AddSelectionBelow,
9947 window: &mut Window,
9948 cx: &mut Context<Self>,
9949 ) {
9950 self.add_selection(false, window, cx);
9951 }
9952
9953 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9954 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9955 let mut selections = self.selections.all::<Point>(cx);
9956 let text_layout_details = self.text_layout_details(window);
9957 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9958 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9959 let range = oldest_selection.display_range(&display_map).sorted();
9960
9961 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9962 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9963 let positions = start_x.min(end_x)..start_x.max(end_x);
9964
9965 selections.clear();
9966 let mut stack = Vec::new();
9967 for row in range.start.row().0..=range.end.row().0 {
9968 if let Some(selection) = self.selections.build_columnar_selection(
9969 &display_map,
9970 DisplayRow(row),
9971 &positions,
9972 oldest_selection.reversed,
9973 &text_layout_details,
9974 ) {
9975 stack.push(selection.id);
9976 selections.push(selection);
9977 }
9978 }
9979
9980 if above {
9981 stack.reverse();
9982 }
9983
9984 AddSelectionsState { above, stack }
9985 });
9986
9987 let last_added_selection = *state.stack.last().unwrap();
9988 let mut new_selections = Vec::new();
9989 if above == state.above {
9990 let end_row = if above {
9991 DisplayRow(0)
9992 } else {
9993 display_map.max_point().row()
9994 };
9995
9996 'outer: for selection in selections {
9997 if selection.id == last_added_selection {
9998 let range = selection.display_range(&display_map).sorted();
9999 debug_assert_eq!(range.start.row(), range.end.row());
10000 let mut row = range.start.row();
10001 let positions =
10002 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10003 px(start)..px(end)
10004 } else {
10005 let start_x =
10006 display_map.x_for_display_point(range.start, &text_layout_details);
10007 let end_x =
10008 display_map.x_for_display_point(range.end, &text_layout_details);
10009 start_x.min(end_x)..start_x.max(end_x)
10010 };
10011
10012 while row != end_row {
10013 if above {
10014 row.0 -= 1;
10015 } else {
10016 row.0 += 1;
10017 }
10018
10019 if let Some(new_selection) = self.selections.build_columnar_selection(
10020 &display_map,
10021 row,
10022 &positions,
10023 selection.reversed,
10024 &text_layout_details,
10025 ) {
10026 state.stack.push(new_selection.id);
10027 if above {
10028 new_selections.push(new_selection);
10029 new_selections.push(selection);
10030 } else {
10031 new_selections.push(selection);
10032 new_selections.push(new_selection);
10033 }
10034
10035 continue 'outer;
10036 }
10037 }
10038 }
10039
10040 new_selections.push(selection);
10041 }
10042 } else {
10043 new_selections = selections;
10044 new_selections.retain(|s| s.id != last_added_selection);
10045 state.stack.pop();
10046 }
10047
10048 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10049 s.select(new_selections);
10050 });
10051 if state.stack.len() > 1 {
10052 self.add_selections_state = Some(state);
10053 }
10054 }
10055
10056 pub fn select_next_match_internal(
10057 &mut self,
10058 display_map: &DisplaySnapshot,
10059 replace_newest: bool,
10060 autoscroll: Option<Autoscroll>,
10061 window: &mut Window,
10062 cx: &mut Context<Self>,
10063 ) -> Result<()> {
10064 fn select_next_match_ranges(
10065 this: &mut Editor,
10066 range: Range<usize>,
10067 replace_newest: bool,
10068 auto_scroll: Option<Autoscroll>,
10069 window: &mut Window,
10070 cx: &mut Context<Editor>,
10071 ) {
10072 this.unfold_ranges(&[range.clone()], false, true, cx);
10073 this.change_selections(auto_scroll, window, cx, |s| {
10074 if replace_newest {
10075 s.delete(s.newest_anchor().id);
10076 }
10077 s.insert_range(range.clone());
10078 });
10079 }
10080
10081 let buffer = &display_map.buffer_snapshot;
10082 let mut selections = self.selections.all::<usize>(cx);
10083 if let Some(mut select_next_state) = self.select_next_state.take() {
10084 let query = &select_next_state.query;
10085 if !select_next_state.done {
10086 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10087 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10088 let mut next_selected_range = None;
10089
10090 let bytes_after_last_selection =
10091 buffer.bytes_in_range(last_selection.end..buffer.len());
10092 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10093 let query_matches = query
10094 .stream_find_iter(bytes_after_last_selection)
10095 .map(|result| (last_selection.end, result))
10096 .chain(
10097 query
10098 .stream_find_iter(bytes_before_first_selection)
10099 .map(|result| (0, result)),
10100 );
10101
10102 for (start_offset, query_match) in query_matches {
10103 let query_match = query_match.unwrap(); // can only fail due to I/O
10104 let offset_range =
10105 start_offset + query_match.start()..start_offset + query_match.end();
10106 let display_range = offset_range.start.to_display_point(display_map)
10107 ..offset_range.end.to_display_point(display_map);
10108
10109 if !select_next_state.wordwise
10110 || (!movement::is_inside_word(display_map, display_range.start)
10111 && !movement::is_inside_word(display_map, display_range.end))
10112 {
10113 // TODO: This is n^2, because we might check all the selections
10114 if !selections
10115 .iter()
10116 .any(|selection| selection.range().overlaps(&offset_range))
10117 {
10118 next_selected_range = Some(offset_range);
10119 break;
10120 }
10121 }
10122 }
10123
10124 if let Some(next_selected_range) = next_selected_range {
10125 select_next_match_ranges(
10126 self,
10127 next_selected_range,
10128 replace_newest,
10129 autoscroll,
10130 window,
10131 cx,
10132 );
10133 } else {
10134 select_next_state.done = true;
10135 }
10136 }
10137
10138 self.select_next_state = Some(select_next_state);
10139 } else {
10140 let mut only_carets = true;
10141 let mut same_text_selected = true;
10142 let mut selected_text = None;
10143
10144 let mut selections_iter = selections.iter().peekable();
10145 while let Some(selection) = selections_iter.next() {
10146 if selection.start != selection.end {
10147 only_carets = false;
10148 }
10149
10150 if same_text_selected {
10151 if selected_text.is_none() {
10152 selected_text =
10153 Some(buffer.text_for_range(selection.range()).collect::<String>());
10154 }
10155
10156 if let Some(next_selection) = selections_iter.peek() {
10157 if next_selection.range().len() == selection.range().len() {
10158 let next_selected_text = buffer
10159 .text_for_range(next_selection.range())
10160 .collect::<String>();
10161 if Some(next_selected_text) != selected_text {
10162 same_text_selected = false;
10163 selected_text = None;
10164 }
10165 } else {
10166 same_text_selected = false;
10167 selected_text = None;
10168 }
10169 }
10170 }
10171 }
10172
10173 if only_carets {
10174 for selection in &mut selections {
10175 let word_range = movement::surrounding_word(
10176 display_map,
10177 selection.start.to_display_point(display_map),
10178 );
10179 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10180 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10181 selection.goal = SelectionGoal::None;
10182 selection.reversed = false;
10183 select_next_match_ranges(
10184 self,
10185 selection.start..selection.end,
10186 replace_newest,
10187 autoscroll,
10188 window,
10189 cx,
10190 );
10191 }
10192
10193 if selections.len() == 1 {
10194 let selection = selections
10195 .last()
10196 .expect("ensured that there's only one selection");
10197 let query = buffer
10198 .text_for_range(selection.start..selection.end)
10199 .collect::<String>();
10200 let is_empty = query.is_empty();
10201 let select_state = SelectNextState {
10202 query: AhoCorasick::new(&[query])?,
10203 wordwise: true,
10204 done: is_empty,
10205 };
10206 self.select_next_state = Some(select_state);
10207 } else {
10208 self.select_next_state = None;
10209 }
10210 } else if let Some(selected_text) = selected_text {
10211 self.select_next_state = Some(SelectNextState {
10212 query: AhoCorasick::new(&[selected_text])?,
10213 wordwise: false,
10214 done: false,
10215 });
10216 self.select_next_match_internal(
10217 display_map,
10218 replace_newest,
10219 autoscroll,
10220 window,
10221 cx,
10222 )?;
10223 }
10224 }
10225 Ok(())
10226 }
10227
10228 pub fn select_all_matches(
10229 &mut self,
10230 _action: &SelectAllMatches,
10231 window: &mut Window,
10232 cx: &mut Context<Self>,
10233 ) -> Result<()> {
10234 self.push_to_selection_history();
10235 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10236
10237 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10238 let Some(select_next_state) = self.select_next_state.as_mut() else {
10239 return Ok(());
10240 };
10241 if select_next_state.done {
10242 return Ok(());
10243 }
10244
10245 let mut new_selections = self.selections.all::<usize>(cx);
10246
10247 let buffer = &display_map.buffer_snapshot;
10248 let query_matches = select_next_state
10249 .query
10250 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10251
10252 for query_match in query_matches {
10253 let query_match = query_match.unwrap(); // can only fail due to I/O
10254 let offset_range = query_match.start()..query_match.end();
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_next_state.wordwise
10259 || (!movement::is_inside_word(&display_map, display_range.start)
10260 && !movement::is_inside_word(&display_map, display_range.end))
10261 {
10262 self.selections.change_with(cx, |selections| {
10263 new_selections.push(Selection {
10264 id: selections.new_selection_id(),
10265 start: offset_range.start,
10266 end: offset_range.end,
10267 reversed: false,
10268 goal: SelectionGoal::None,
10269 });
10270 });
10271 }
10272 }
10273
10274 new_selections.sort_by_key(|selection| selection.start);
10275 let mut ix = 0;
10276 while ix + 1 < new_selections.len() {
10277 let current_selection = &new_selections[ix];
10278 let next_selection = &new_selections[ix + 1];
10279 if current_selection.range().overlaps(&next_selection.range()) {
10280 if current_selection.id < next_selection.id {
10281 new_selections.remove(ix + 1);
10282 } else {
10283 new_selections.remove(ix);
10284 }
10285 } else {
10286 ix += 1;
10287 }
10288 }
10289
10290 let reversed = self.selections.oldest::<usize>(cx).reversed;
10291
10292 for selection in new_selections.iter_mut() {
10293 selection.reversed = reversed;
10294 }
10295
10296 select_next_state.done = true;
10297 self.unfold_ranges(
10298 &new_selections
10299 .iter()
10300 .map(|selection| selection.range())
10301 .collect::<Vec<_>>(),
10302 false,
10303 false,
10304 cx,
10305 );
10306 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10307 selections.select(new_selections)
10308 });
10309
10310 Ok(())
10311 }
10312
10313 pub fn select_next(
10314 &mut self,
10315 action: &SelectNext,
10316 window: &mut Window,
10317 cx: &mut Context<Self>,
10318 ) -> Result<()> {
10319 self.push_to_selection_history();
10320 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10321 self.select_next_match_internal(
10322 &display_map,
10323 action.replace_newest,
10324 Some(Autoscroll::newest()),
10325 window,
10326 cx,
10327 )?;
10328 Ok(())
10329 }
10330
10331 pub fn select_previous(
10332 &mut self,
10333 action: &SelectPrevious,
10334 window: &mut Window,
10335 cx: &mut Context<Self>,
10336 ) -> Result<()> {
10337 self.push_to_selection_history();
10338 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10339 let buffer = &display_map.buffer_snapshot;
10340 let mut selections = self.selections.all::<usize>(cx);
10341 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10342 let query = &select_prev_state.query;
10343 if !select_prev_state.done {
10344 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10345 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10346 let mut next_selected_range = None;
10347 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10348 let bytes_before_last_selection =
10349 buffer.reversed_bytes_in_range(0..last_selection.start);
10350 let bytes_after_first_selection =
10351 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10352 let query_matches = query
10353 .stream_find_iter(bytes_before_last_selection)
10354 .map(|result| (last_selection.start, result))
10355 .chain(
10356 query
10357 .stream_find_iter(bytes_after_first_selection)
10358 .map(|result| (buffer.len(), result)),
10359 );
10360 for (end_offset, query_match) in query_matches {
10361 let query_match = query_match.unwrap(); // can only fail due to I/O
10362 let offset_range =
10363 end_offset - query_match.end()..end_offset - query_match.start();
10364 let display_range = offset_range.start.to_display_point(&display_map)
10365 ..offset_range.end.to_display_point(&display_map);
10366
10367 if !select_prev_state.wordwise
10368 || (!movement::is_inside_word(&display_map, display_range.start)
10369 && !movement::is_inside_word(&display_map, display_range.end))
10370 {
10371 next_selected_range = Some(offset_range);
10372 break;
10373 }
10374 }
10375
10376 if let Some(next_selected_range) = next_selected_range {
10377 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10378 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10379 if action.replace_newest {
10380 s.delete(s.newest_anchor().id);
10381 }
10382 s.insert_range(next_selected_range);
10383 });
10384 } else {
10385 select_prev_state.done = true;
10386 }
10387 }
10388
10389 self.select_prev_state = Some(select_prev_state);
10390 } else {
10391 let mut only_carets = true;
10392 let mut same_text_selected = true;
10393 let mut selected_text = None;
10394
10395 let mut selections_iter = selections.iter().peekable();
10396 while let Some(selection) = selections_iter.next() {
10397 if selection.start != selection.end {
10398 only_carets = false;
10399 }
10400
10401 if same_text_selected {
10402 if selected_text.is_none() {
10403 selected_text =
10404 Some(buffer.text_for_range(selection.range()).collect::<String>());
10405 }
10406
10407 if let Some(next_selection) = selections_iter.peek() {
10408 if next_selection.range().len() == selection.range().len() {
10409 let next_selected_text = buffer
10410 .text_for_range(next_selection.range())
10411 .collect::<String>();
10412 if Some(next_selected_text) != selected_text {
10413 same_text_selected = false;
10414 selected_text = None;
10415 }
10416 } else {
10417 same_text_selected = false;
10418 selected_text = None;
10419 }
10420 }
10421 }
10422 }
10423
10424 if only_carets {
10425 for selection in &mut selections {
10426 let word_range = movement::surrounding_word(
10427 &display_map,
10428 selection.start.to_display_point(&display_map),
10429 );
10430 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10431 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10432 selection.goal = SelectionGoal::None;
10433 selection.reversed = false;
10434 }
10435 if selections.len() == 1 {
10436 let selection = selections
10437 .last()
10438 .expect("ensured that there's only one selection");
10439 let query = buffer
10440 .text_for_range(selection.start..selection.end)
10441 .collect::<String>();
10442 let is_empty = query.is_empty();
10443 let select_state = SelectNextState {
10444 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10445 wordwise: true,
10446 done: is_empty,
10447 };
10448 self.select_prev_state = Some(select_state);
10449 } else {
10450 self.select_prev_state = None;
10451 }
10452
10453 self.unfold_ranges(
10454 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10455 false,
10456 true,
10457 cx,
10458 );
10459 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10460 s.select(selections);
10461 });
10462 } else if let Some(selected_text) = selected_text {
10463 self.select_prev_state = Some(SelectNextState {
10464 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10465 wordwise: false,
10466 done: false,
10467 });
10468 self.select_previous(action, window, cx)?;
10469 }
10470 }
10471 Ok(())
10472 }
10473
10474 pub fn toggle_comments(
10475 &mut self,
10476 action: &ToggleComments,
10477 window: &mut Window,
10478 cx: &mut Context<Self>,
10479 ) {
10480 if self.read_only(cx) {
10481 return;
10482 }
10483 let text_layout_details = &self.text_layout_details(window);
10484 self.transact(window, cx, |this, window, cx| {
10485 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10486 let mut edits = Vec::new();
10487 let mut selection_edit_ranges = Vec::new();
10488 let mut last_toggled_row = None;
10489 let snapshot = this.buffer.read(cx).read(cx);
10490 let empty_str: Arc<str> = Arc::default();
10491 let mut suffixes_inserted = Vec::new();
10492 let ignore_indent = action.ignore_indent;
10493
10494 fn comment_prefix_range(
10495 snapshot: &MultiBufferSnapshot,
10496 row: MultiBufferRow,
10497 comment_prefix: &str,
10498 comment_prefix_whitespace: &str,
10499 ignore_indent: bool,
10500 ) -> Range<Point> {
10501 let indent_size = if ignore_indent {
10502 0
10503 } else {
10504 snapshot.indent_size_for_line(row).len
10505 };
10506
10507 let start = Point::new(row.0, indent_size);
10508
10509 let mut line_bytes = snapshot
10510 .bytes_in_range(start..snapshot.max_point())
10511 .flatten()
10512 .copied();
10513
10514 // If this line currently begins with the line comment prefix, then record
10515 // the range containing the prefix.
10516 if line_bytes
10517 .by_ref()
10518 .take(comment_prefix.len())
10519 .eq(comment_prefix.bytes())
10520 {
10521 // Include any whitespace that matches the comment prefix.
10522 let matching_whitespace_len = line_bytes
10523 .zip(comment_prefix_whitespace.bytes())
10524 .take_while(|(a, b)| a == b)
10525 .count() as u32;
10526 let end = Point::new(
10527 start.row,
10528 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10529 );
10530 start..end
10531 } else {
10532 start..start
10533 }
10534 }
10535
10536 fn comment_suffix_range(
10537 snapshot: &MultiBufferSnapshot,
10538 row: MultiBufferRow,
10539 comment_suffix: &str,
10540 comment_suffix_has_leading_space: bool,
10541 ) -> Range<Point> {
10542 let end = Point::new(row.0, snapshot.line_len(row));
10543 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10544
10545 let mut line_end_bytes = snapshot
10546 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10547 .flatten()
10548 .copied();
10549
10550 let leading_space_len = if suffix_start_column > 0
10551 && line_end_bytes.next() == Some(b' ')
10552 && comment_suffix_has_leading_space
10553 {
10554 1
10555 } else {
10556 0
10557 };
10558
10559 // If this line currently begins with the line comment prefix, then record
10560 // the range containing the prefix.
10561 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10562 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10563 start..end
10564 } else {
10565 end..end
10566 }
10567 }
10568
10569 // TODO: Handle selections that cross excerpts
10570 for selection in &mut selections {
10571 let start_column = snapshot
10572 .indent_size_for_line(MultiBufferRow(selection.start.row))
10573 .len;
10574 let language = if let Some(language) =
10575 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10576 {
10577 language
10578 } else {
10579 continue;
10580 };
10581
10582 selection_edit_ranges.clear();
10583
10584 // If multiple selections contain a given row, avoid processing that
10585 // row more than once.
10586 let mut start_row = MultiBufferRow(selection.start.row);
10587 if last_toggled_row == Some(start_row) {
10588 start_row = start_row.next_row();
10589 }
10590 let end_row =
10591 if selection.end.row > selection.start.row && selection.end.column == 0 {
10592 MultiBufferRow(selection.end.row - 1)
10593 } else {
10594 MultiBufferRow(selection.end.row)
10595 };
10596 last_toggled_row = Some(end_row);
10597
10598 if start_row > end_row {
10599 continue;
10600 }
10601
10602 // If the language has line comments, toggle those.
10603 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10604
10605 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10606 if ignore_indent {
10607 full_comment_prefixes = full_comment_prefixes
10608 .into_iter()
10609 .map(|s| Arc::from(s.trim_end()))
10610 .collect();
10611 }
10612
10613 if !full_comment_prefixes.is_empty() {
10614 let first_prefix = full_comment_prefixes
10615 .first()
10616 .expect("prefixes is non-empty");
10617 let prefix_trimmed_lengths = full_comment_prefixes
10618 .iter()
10619 .map(|p| p.trim_end_matches(' ').len())
10620 .collect::<SmallVec<[usize; 4]>>();
10621
10622 let mut all_selection_lines_are_comments = true;
10623
10624 for row in start_row.0..=end_row.0 {
10625 let row = MultiBufferRow(row);
10626 if start_row < end_row && snapshot.is_line_blank(row) {
10627 continue;
10628 }
10629
10630 let prefix_range = full_comment_prefixes
10631 .iter()
10632 .zip(prefix_trimmed_lengths.iter().copied())
10633 .map(|(prefix, trimmed_prefix_len)| {
10634 comment_prefix_range(
10635 snapshot.deref(),
10636 row,
10637 &prefix[..trimmed_prefix_len],
10638 &prefix[trimmed_prefix_len..],
10639 ignore_indent,
10640 )
10641 })
10642 .max_by_key(|range| range.end.column - range.start.column)
10643 .expect("prefixes is non-empty");
10644
10645 if prefix_range.is_empty() {
10646 all_selection_lines_are_comments = false;
10647 }
10648
10649 selection_edit_ranges.push(prefix_range);
10650 }
10651
10652 if all_selection_lines_are_comments {
10653 edits.extend(
10654 selection_edit_ranges
10655 .iter()
10656 .cloned()
10657 .map(|range| (range, empty_str.clone())),
10658 );
10659 } else {
10660 let min_column = selection_edit_ranges
10661 .iter()
10662 .map(|range| range.start.column)
10663 .min()
10664 .unwrap_or(0);
10665 edits.extend(selection_edit_ranges.iter().map(|range| {
10666 let position = Point::new(range.start.row, min_column);
10667 (position..position, first_prefix.clone())
10668 }));
10669 }
10670 } else if let Some((full_comment_prefix, comment_suffix)) =
10671 language.block_comment_delimiters()
10672 {
10673 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10674 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10675 let prefix_range = comment_prefix_range(
10676 snapshot.deref(),
10677 start_row,
10678 comment_prefix,
10679 comment_prefix_whitespace,
10680 ignore_indent,
10681 );
10682 let suffix_range = comment_suffix_range(
10683 snapshot.deref(),
10684 end_row,
10685 comment_suffix.trim_start_matches(' '),
10686 comment_suffix.starts_with(' '),
10687 );
10688
10689 if prefix_range.is_empty() || suffix_range.is_empty() {
10690 edits.push((
10691 prefix_range.start..prefix_range.start,
10692 full_comment_prefix.clone(),
10693 ));
10694 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10695 suffixes_inserted.push((end_row, comment_suffix.len()));
10696 } else {
10697 edits.push((prefix_range, empty_str.clone()));
10698 edits.push((suffix_range, empty_str.clone()));
10699 }
10700 } else {
10701 continue;
10702 }
10703 }
10704
10705 drop(snapshot);
10706 this.buffer.update(cx, |buffer, cx| {
10707 buffer.edit(edits, None, cx);
10708 });
10709
10710 // Adjust selections so that they end before any comment suffixes that
10711 // were inserted.
10712 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10713 let mut selections = this.selections.all::<Point>(cx);
10714 let snapshot = this.buffer.read(cx).read(cx);
10715 for selection in &mut selections {
10716 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10717 match row.cmp(&MultiBufferRow(selection.end.row)) {
10718 Ordering::Less => {
10719 suffixes_inserted.next();
10720 continue;
10721 }
10722 Ordering::Greater => break,
10723 Ordering::Equal => {
10724 if selection.end.column == snapshot.line_len(row) {
10725 if selection.is_empty() {
10726 selection.start.column -= suffix_len as u32;
10727 }
10728 selection.end.column -= suffix_len as u32;
10729 }
10730 break;
10731 }
10732 }
10733 }
10734 }
10735
10736 drop(snapshot);
10737 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10738 s.select(selections)
10739 });
10740
10741 let selections = this.selections.all::<Point>(cx);
10742 let selections_on_single_row = selections.windows(2).all(|selections| {
10743 selections[0].start.row == selections[1].start.row
10744 && selections[0].end.row == selections[1].end.row
10745 && selections[0].start.row == selections[0].end.row
10746 });
10747 let selections_selecting = selections
10748 .iter()
10749 .any(|selection| selection.start != selection.end);
10750 let advance_downwards = action.advance_downwards
10751 && selections_on_single_row
10752 && !selections_selecting
10753 && !matches!(this.mode, EditorMode::SingleLine { .. });
10754
10755 if advance_downwards {
10756 let snapshot = this.buffer.read(cx).snapshot(cx);
10757
10758 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10759 s.move_cursors_with(|display_snapshot, display_point, _| {
10760 let mut point = display_point.to_point(display_snapshot);
10761 point.row += 1;
10762 point = snapshot.clip_point(point, Bias::Left);
10763 let display_point = point.to_display_point(display_snapshot);
10764 let goal = SelectionGoal::HorizontalPosition(
10765 display_snapshot
10766 .x_for_display_point(display_point, text_layout_details)
10767 .into(),
10768 );
10769 (display_point, goal)
10770 })
10771 });
10772 }
10773 });
10774 }
10775
10776 pub fn select_enclosing_symbol(
10777 &mut self,
10778 _: &SelectEnclosingSymbol,
10779 window: &mut Window,
10780 cx: &mut Context<Self>,
10781 ) {
10782 let buffer = self.buffer.read(cx).snapshot(cx);
10783 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10784
10785 fn update_selection(
10786 selection: &Selection<usize>,
10787 buffer_snap: &MultiBufferSnapshot,
10788 ) -> Option<Selection<usize>> {
10789 let cursor = selection.head();
10790 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10791 for symbol in symbols.iter().rev() {
10792 let start = symbol.range.start.to_offset(buffer_snap);
10793 let end = symbol.range.end.to_offset(buffer_snap);
10794 let new_range = start..end;
10795 if start < selection.start || end > selection.end {
10796 return Some(Selection {
10797 id: selection.id,
10798 start: new_range.start,
10799 end: new_range.end,
10800 goal: SelectionGoal::None,
10801 reversed: selection.reversed,
10802 });
10803 }
10804 }
10805 None
10806 }
10807
10808 let mut selected_larger_symbol = false;
10809 let new_selections = old_selections
10810 .iter()
10811 .map(|selection| match update_selection(selection, &buffer) {
10812 Some(new_selection) => {
10813 if new_selection.range() != selection.range() {
10814 selected_larger_symbol = true;
10815 }
10816 new_selection
10817 }
10818 None => selection.clone(),
10819 })
10820 .collect::<Vec<_>>();
10821
10822 if selected_larger_symbol {
10823 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10824 s.select(new_selections);
10825 });
10826 }
10827 }
10828
10829 pub fn select_larger_syntax_node(
10830 &mut self,
10831 _: &SelectLargerSyntaxNode,
10832 window: &mut Window,
10833 cx: &mut Context<Self>,
10834 ) {
10835 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10836 let buffer = self.buffer.read(cx).snapshot(cx);
10837 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10838
10839 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10840 let mut selected_larger_node = false;
10841 let new_selections = old_selections
10842 .iter()
10843 .map(|selection| {
10844 let old_range = selection.start..selection.end;
10845 let mut new_range = old_range.clone();
10846 let mut new_node = None;
10847 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10848 {
10849 new_node = Some(node);
10850 new_range = match containing_range {
10851 MultiOrSingleBufferOffsetRange::Single(_) => break,
10852 MultiOrSingleBufferOffsetRange::Multi(range) => range,
10853 };
10854 if !display_map.intersects_fold(new_range.start)
10855 && !display_map.intersects_fold(new_range.end)
10856 {
10857 break;
10858 }
10859 }
10860
10861 if let Some(node) = new_node {
10862 // Log the ancestor, to support using this action as a way to explore TreeSitter
10863 // nodes. Parent and grandparent are also logged because this operation will not
10864 // visit nodes that have the same range as their parent.
10865 log::info!("Node: {node:?}");
10866 let parent = node.parent();
10867 log::info!("Parent: {parent:?}");
10868 let grandparent = parent.and_then(|x| x.parent());
10869 log::info!("Grandparent: {grandparent:?}");
10870 }
10871
10872 selected_larger_node |= new_range != old_range;
10873 Selection {
10874 id: selection.id,
10875 start: new_range.start,
10876 end: new_range.end,
10877 goal: SelectionGoal::None,
10878 reversed: selection.reversed,
10879 }
10880 })
10881 .collect::<Vec<_>>();
10882
10883 if selected_larger_node {
10884 stack.push(old_selections);
10885 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10886 s.select(new_selections);
10887 });
10888 }
10889 self.select_larger_syntax_node_stack = stack;
10890 }
10891
10892 pub fn select_smaller_syntax_node(
10893 &mut self,
10894 _: &SelectSmallerSyntaxNode,
10895 window: &mut Window,
10896 cx: &mut Context<Self>,
10897 ) {
10898 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10899 if let Some(selections) = stack.pop() {
10900 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10901 s.select(selections.to_vec());
10902 });
10903 }
10904 self.select_larger_syntax_node_stack = stack;
10905 }
10906
10907 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10908 if !EditorSettings::get_global(cx).gutter.runnables {
10909 self.clear_tasks();
10910 return Task::ready(());
10911 }
10912 let project = self.project.as_ref().map(Entity::downgrade);
10913 cx.spawn_in(window, |this, mut cx| async move {
10914 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10915 let Some(project) = project.and_then(|p| p.upgrade()) else {
10916 return;
10917 };
10918 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10919 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10920 }) else {
10921 return;
10922 };
10923
10924 let hide_runnables = project
10925 .update(&mut cx, |project, cx| {
10926 // Do not display any test indicators in non-dev server remote projects.
10927 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10928 })
10929 .unwrap_or(true);
10930 if hide_runnables {
10931 return;
10932 }
10933 let new_rows =
10934 cx.background_spawn({
10935 let snapshot = display_snapshot.clone();
10936 async move {
10937 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10938 }
10939 })
10940 .await;
10941
10942 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10943 this.update(&mut cx, |this, _| {
10944 this.clear_tasks();
10945 for (key, value) in rows {
10946 this.insert_tasks(key, value);
10947 }
10948 })
10949 .ok();
10950 })
10951 }
10952 fn fetch_runnable_ranges(
10953 snapshot: &DisplaySnapshot,
10954 range: Range<Anchor>,
10955 ) -> Vec<language::RunnableRange> {
10956 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10957 }
10958
10959 fn runnable_rows(
10960 project: Entity<Project>,
10961 snapshot: DisplaySnapshot,
10962 runnable_ranges: Vec<RunnableRange>,
10963 mut cx: AsyncWindowContext,
10964 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10965 runnable_ranges
10966 .into_iter()
10967 .filter_map(|mut runnable| {
10968 let tasks = cx
10969 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10970 .ok()?;
10971 if tasks.is_empty() {
10972 return None;
10973 }
10974
10975 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10976
10977 let row = snapshot
10978 .buffer_snapshot
10979 .buffer_line_for_row(MultiBufferRow(point.row))?
10980 .1
10981 .start
10982 .row;
10983
10984 let context_range =
10985 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10986 Some((
10987 (runnable.buffer_id, row),
10988 RunnableTasks {
10989 templates: tasks,
10990 offset: snapshot
10991 .buffer_snapshot
10992 .anchor_before(runnable.run_range.start),
10993 context_range,
10994 column: point.column,
10995 extra_variables: runnable.extra_captures,
10996 },
10997 ))
10998 })
10999 .collect()
11000 }
11001
11002 fn templates_with_tags(
11003 project: &Entity<Project>,
11004 runnable: &mut Runnable,
11005 cx: &mut App,
11006 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11007 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11008 let (worktree_id, file) = project
11009 .buffer_for_id(runnable.buffer, cx)
11010 .and_then(|buffer| buffer.read(cx).file())
11011 .map(|file| (file.worktree_id(cx), file.clone()))
11012 .unzip();
11013
11014 (
11015 project.task_store().read(cx).task_inventory().cloned(),
11016 worktree_id,
11017 file,
11018 )
11019 });
11020
11021 let tags = mem::take(&mut runnable.tags);
11022 let mut tags: Vec<_> = tags
11023 .into_iter()
11024 .flat_map(|tag| {
11025 let tag = tag.0.clone();
11026 inventory
11027 .as_ref()
11028 .into_iter()
11029 .flat_map(|inventory| {
11030 inventory.read(cx).list_tasks(
11031 file.clone(),
11032 Some(runnable.language.clone()),
11033 worktree_id,
11034 cx,
11035 )
11036 })
11037 .filter(move |(_, template)| {
11038 template.tags.iter().any(|source_tag| source_tag == &tag)
11039 })
11040 })
11041 .sorted_by_key(|(kind, _)| kind.to_owned())
11042 .collect();
11043 if let Some((leading_tag_source, _)) = tags.first() {
11044 // Strongest source wins; if we have worktree tag binding, prefer that to
11045 // global and language bindings;
11046 // if we have a global binding, prefer that to language binding.
11047 let first_mismatch = tags
11048 .iter()
11049 .position(|(tag_source, _)| tag_source != leading_tag_source);
11050 if let Some(index) = first_mismatch {
11051 tags.truncate(index);
11052 }
11053 }
11054
11055 tags
11056 }
11057
11058 pub fn move_to_enclosing_bracket(
11059 &mut self,
11060 _: &MoveToEnclosingBracket,
11061 window: &mut Window,
11062 cx: &mut Context<Self>,
11063 ) {
11064 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11065 s.move_offsets_with(|snapshot, selection| {
11066 let Some(enclosing_bracket_ranges) =
11067 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11068 else {
11069 return;
11070 };
11071
11072 let mut best_length = usize::MAX;
11073 let mut best_inside = false;
11074 let mut best_in_bracket_range = false;
11075 let mut best_destination = None;
11076 for (open, close) in enclosing_bracket_ranges {
11077 let close = close.to_inclusive();
11078 let length = close.end() - open.start;
11079 let inside = selection.start >= open.end && selection.end <= *close.start();
11080 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11081 || close.contains(&selection.head());
11082
11083 // If best is next to a bracket and current isn't, skip
11084 if !in_bracket_range && best_in_bracket_range {
11085 continue;
11086 }
11087
11088 // Prefer smaller lengths unless best is inside and current isn't
11089 if length > best_length && (best_inside || !inside) {
11090 continue;
11091 }
11092
11093 best_length = length;
11094 best_inside = inside;
11095 best_in_bracket_range = in_bracket_range;
11096 best_destination = Some(
11097 if close.contains(&selection.start) && close.contains(&selection.end) {
11098 if inside {
11099 open.end
11100 } else {
11101 open.start
11102 }
11103 } else if inside {
11104 *close.start()
11105 } else {
11106 *close.end()
11107 },
11108 );
11109 }
11110
11111 if let Some(destination) = best_destination {
11112 selection.collapse_to(destination, SelectionGoal::None);
11113 }
11114 })
11115 });
11116 }
11117
11118 pub fn undo_selection(
11119 &mut self,
11120 _: &UndoSelection,
11121 window: &mut Window,
11122 cx: &mut Context<Self>,
11123 ) {
11124 self.end_selection(window, cx);
11125 self.selection_history.mode = SelectionHistoryMode::Undoing;
11126 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11127 self.change_selections(None, window, cx, |s| {
11128 s.select_anchors(entry.selections.to_vec())
11129 });
11130 self.select_next_state = entry.select_next_state;
11131 self.select_prev_state = entry.select_prev_state;
11132 self.add_selections_state = entry.add_selections_state;
11133 self.request_autoscroll(Autoscroll::newest(), cx);
11134 }
11135 self.selection_history.mode = SelectionHistoryMode::Normal;
11136 }
11137
11138 pub fn redo_selection(
11139 &mut self,
11140 _: &RedoSelection,
11141 window: &mut Window,
11142 cx: &mut Context<Self>,
11143 ) {
11144 self.end_selection(window, cx);
11145 self.selection_history.mode = SelectionHistoryMode::Redoing;
11146 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11147 self.change_selections(None, window, cx, |s| {
11148 s.select_anchors(entry.selections.to_vec())
11149 });
11150 self.select_next_state = entry.select_next_state;
11151 self.select_prev_state = entry.select_prev_state;
11152 self.add_selections_state = entry.add_selections_state;
11153 self.request_autoscroll(Autoscroll::newest(), cx);
11154 }
11155 self.selection_history.mode = SelectionHistoryMode::Normal;
11156 }
11157
11158 pub fn expand_excerpts(
11159 &mut self,
11160 action: &ExpandExcerpts,
11161 _: &mut Window,
11162 cx: &mut Context<Self>,
11163 ) {
11164 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11165 }
11166
11167 pub fn expand_excerpts_down(
11168 &mut self,
11169 action: &ExpandExcerptsDown,
11170 _: &mut Window,
11171 cx: &mut Context<Self>,
11172 ) {
11173 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11174 }
11175
11176 pub fn expand_excerpts_up(
11177 &mut self,
11178 action: &ExpandExcerptsUp,
11179 _: &mut Window,
11180 cx: &mut Context<Self>,
11181 ) {
11182 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11183 }
11184
11185 pub fn expand_excerpts_for_direction(
11186 &mut self,
11187 lines: u32,
11188 direction: ExpandExcerptDirection,
11189
11190 cx: &mut Context<Self>,
11191 ) {
11192 let selections = self.selections.disjoint_anchors();
11193
11194 let lines = if lines == 0 {
11195 EditorSettings::get_global(cx).expand_excerpt_lines
11196 } else {
11197 lines
11198 };
11199
11200 self.buffer.update(cx, |buffer, cx| {
11201 let snapshot = buffer.snapshot(cx);
11202 let mut excerpt_ids = selections
11203 .iter()
11204 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11205 .collect::<Vec<_>>();
11206 excerpt_ids.sort();
11207 excerpt_ids.dedup();
11208 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11209 })
11210 }
11211
11212 pub fn expand_excerpt(
11213 &mut self,
11214 excerpt: ExcerptId,
11215 direction: ExpandExcerptDirection,
11216 cx: &mut Context<Self>,
11217 ) {
11218 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11219 self.buffer.update(cx, |buffer, cx| {
11220 buffer.expand_excerpts([excerpt], lines, direction, cx)
11221 })
11222 }
11223
11224 pub fn go_to_singleton_buffer_point(
11225 &mut self,
11226 point: Point,
11227 window: &mut Window,
11228 cx: &mut Context<Self>,
11229 ) {
11230 self.go_to_singleton_buffer_range(point..point, window, cx);
11231 }
11232
11233 pub fn go_to_singleton_buffer_range(
11234 &mut self,
11235 range: Range<Point>,
11236 window: &mut Window,
11237 cx: &mut Context<Self>,
11238 ) {
11239 let multibuffer = self.buffer().read(cx);
11240 let Some(buffer) = multibuffer.as_singleton() else {
11241 return;
11242 };
11243 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11244 return;
11245 };
11246 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11247 return;
11248 };
11249 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11250 s.select_anchor_ranges([start..end])
11251 });
11252 }
11253
11254 fn go_to_diagnostic(
11255 &mut self,
11256 _: &GoToDiagnostic,
11257 window: &mut Window,
11258 cx: &mut Context<Self>,
11259 ) {
11260 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11261 }
11262
11263 fn go_to_prev_diagnostic(
11264 &mut self,
11265 _: &GoToPrevDiagnostic,
11266 window: &mut Window,
11267 cx: &mut Context<Self>,
11268 ) {
11269 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11270 }
11271
11272 pub fn go_to_diagnostic_impl(
11273 &mut self,
11274 direction: Direction,
11275 window: &mut Window,
11276 cx: &mut Context<Self>,
11277 ) {
11278 let buffer = self.buffer.read(cx).snapshot(cx);
11279 let selection = self.selections.newest::<usize>(cx);
11280
11281 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11282 if direction == Direction::Next {
11283 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11284 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11285 return;
11286 };
11287 self.activate_diagnostics(
11288 buffer_id,
11289 popover.local_diagnostic.diagnostic.group_id,
11290 window,
11291 cx,
11292 );
11293 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11294 let primary_range_start = active_diagnostics.primary_range.start;
11295 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11296 let mut new_selection = s.newest_anchor().clone();
11297 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11298 s.select_anchors(vec![new_selection.clone()]);
11299 });
11300 self.refresh_inline_completion(false, true, window, cx);
11301 }
11302 return;
11303 }
11304 }
11305
11306 let active_group_id = self
11307 .active_diagnostics
11308 .as_ref()
11309 .map(|active_group| active_group.group_id);
11310 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11311 active_diagnostics
11312 .primary_range
11313 .to_offset(&buffer)
11314 .to_inclusive()
11315 });
11316 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11317 if active_primary_range.contains(&selection.head()) {
11318 *active_primary_range.start()
11319 } else {
11320 selection.head()
11321 }
11322 } else {
11323 selection.head()
11324 };
11325
11326 let snapshot = self.snapshot(window, cx);
11327 let primary_diagnostics_before = buffer
11328 .diagnostics_in_range::<usize>(0..search_start)
11329 .filter(|entry| entry.diagnostic.is_primary)
11330 .filter(|entry| entry.range.start != entry.range.end)
11331 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11332 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11333 .collect::<Vec<_>>();
11334 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11335 primary_diagnostics_before
11336 .iter()
11337 .position(|entry| entry.diagnostic.group_id == active_group_id)
11338 });
11339
11340 let primary_diagnostics_after = buffer
11341 .diagnostics_in_range::<usize>(search_start..buffer.len())
11342 .filter(|entry| entry.diagnostic.is_primary)
11343 .filter(|entry| entry.range.start != entry.range.end)
11344 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11345 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11346 .collect::<Vec<_>>();
11347 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11348 primary_diagnostics_after
11349 .iter()
11350 .enumerate()
11351 .rev()
11352 .find_map(|(i, entry)| {
11353 if entry.diagnostic.group_id == active_group_id {
11354 Some(i)
11355 } else {
11356 None
11357 }
11358 })
11359 });
11360
11361 let next_primary_diagnostic = match direction {
11362 Direction::Prev => primary_diagnostics_before
11363 .iter()
11364 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11365 .rev()
11366 .next(),
11367 Direction::Next => primary_diagnostics_after
11368 .iter()
11369 .skip(
11370 last_same_group_diagnostic_after
11371 .map(|index| index + 1)
11372 .unwrap_or(0),
11373 )
11374 .next(),
11375 };
11376
11377 // Cycle around to the start of the buffer, potentially moving back to the start of
11378 // the currently active diagnostic.
11379 let cycle_around = || match direction {
11380 Direction::Prev => primary_diagnostics_after
11381 .iter()
11382 .rev()
11383 .chain(primary_diagnostics_before.iter().rev())
11384 .next(),
11385 Direction::Next => primary_diagnostics_before
11386 .iter()
11387 .chain(primary_diagnostics_after.iter())
11388 .next(),
11389 };
11390
11391 if let Some((primary_range, group_id)) = next_primary_diagnostic
11392 .or_else(cycle_around)
11393 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11394 {
11395 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11396 return;
11397 };
11398 self.activate_diagnostics(buffer_id, group_id, window, cx);
11399 if self.active_diagnostics.is_some() {
11400 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11401 s.select(vec![Selection {
11402 id: selection.id,
11403 start: primary_range.start,
11404 end: primary_range.start,
11405 reversed: false,
11406 goal: SelectionGoal::None,
11407 }]);
11408 });
11409 self.refresh_inline_completion(false, true, window, cx);
11410 }
11411 }
11412 }
11413
11414 fn go_to_next_hunk(&mut self, action: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11415 let snapshot = self.snapshot(window, cx);
11416 let selection = self.selections.newest::<Point>(cx);
11417 self.go_to_hunk_after_or_before_position(
11418 &snapshot,
11419 selection.head(),
11420 true,
11421 action.center_cursor,
11422 window,
11423 cx,
11424 );
11425 }
11426
11427 fn go_to_hunk_after_or_before_position(
11428 &mut self,
11429 snapshot: &EditorSnapshot,
11430 position: Point,
11431 after: bool,
11432 scroll_center: bool,
11433 window: &mut Window,
11434 cx: &mut Context<Editor>,
11435 ) -> Option<MultiBufferDiffHunk> {
11436 let hunk = if after {
11437 self.hunk_after_position(snapshot, position)
11438 } else {
11439 self.hunk_before_position(snapshot, position)
11440 };
11441
11442 if let Some(hunk) = &hunk {
11443 let destination = Point::new(hunk.row_range.start.0, 0);
11444 let autoscroll = if scroll_center {
11445 Autoscroll::center()
11446 } else {
11447 Autoscroll::fit()
11448 };
11449
11450 self.unfold_ranges(&[destination..destination], false, false, cx);
11451 self.change_selections(Some(autoscroll), window, cx, |s| {
11452 s.select_ranges([destination..destination]);
11453 });
11454 }
11455
11456 hunk
11457 }
11458
11459 fn hunk_after_position(
11460 &mut self,
11461 snapshot: &EditorSnapshot,
11462 position: Point,
11463 ) -> Option<MultiBufferDiffHunk> {
11464 snapshot
11465 .buffer_snapshot
11466 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11467 .find(|hunk| hunk.row_range.start.0 > position.row)
11468 .or_else(|| {
11469 snapshot
11470 .buffer_snapshot
11471 .diff_hunks_in_range(Point::zero()..position)
11472 .find(|hunk| hunk.row_range.end.0 < position.row)
11473 })
11474 }
11475
11476 fn go_to_prev_hunk(
11477 &mut self,
11478 action: &GoToPrevHunk,
11479 window: &mut Window,
11480 cx: &mut Context<Self>,
11481 ) {
11482 let snapshot = self.snapshot(window, cx);
11483 let selection = self.selections.newest::<Point>(cx);
11484 self.go_to_hunk_after_or_before_position(
11485 &snapshot,
11486 selection.head(),
11487 false,
11488 action.center_cursor,
11489 window,
11490 cx,
11491 );
11492 }
11493
11494 fn hunk_before_position(
11495 &mut self,
11496 snapshot: &EditorSnapshot,
11497 position: Point,
11498 ) -> Option<MultiBufferDiffHunk> {
11499 snapshot
11500 .buffer_snapshot
11501 .diff_hunk_before(position)
11502 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11503 }
11504
11505 pub fn go_to_definition(
11506 &mut self,
11507 _: &GoToDefinition,
11508 window: &mut Window,
11509 cx: &mut Context<Self>,
11510 ) -> Task<Result<Navigated>> {
11511 let definition =
11512 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11513 cx.spawn_in(window, |editor, mut cx| async move {
11514 if definition.await? == Navigated::Yes {
11515 return Ok(Navigated::Yes);
11516 }
11517 match editor.update_in(&mut cx, |editor, window, cx| {
11518 editor.find_all_references(&FindAllReferences, window, cx)
11519 })? {
11520 Some(references) => references.await,
11521 None => Ok(Navigated::No),
11522 }
11523 })
11524 }
11525
11526 pub fn go_to_declaration(
11527 &mut self,
11528 _: &GoToDeclaration,
11529 window: &mut Window,
11530 cx: &mut Context<Self>,
11531 ) -> Task<Result<Navigated>> {
11532 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11533 }
11534
11535 pub fn go_to_declaration_split(
11536 &mut self,
11537 _: &GoToDeclaration,
11538 window: &mut Window,
11539 cx: &mut Context<Self>,
11540 ) -> Task<Result<Navigated>> {
11541 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11542 }
11543
11544 pub fn go_to_implementation(
11545 &mut self,
11546 _: &GoToImplementation,
11547 window: &mut Window,
11548 cx: &mut Context<Self>,
11549 ) -> Task<Result<Navigated>> {
11550 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11551 }
11552
11553 pub fn go_to_implementation_split(
11554 &mut self,
11555 _: &GoToImplementationSplit,
11556 window: &mut Window,
11557 cx: &mut Context<Self>,
11558 ) -> Task<Result<Navigated>> {
11559 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11560 }
11561
11562 pub fn go_to_type_definition(
11563 &mut self,
11564 _: &GoToTypeDefinition,
11565 window: &mut Window,
11566 cx: &mut Context<Self>,
11567 ) -> Task<Result<Navigated>> {
11568 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11569 }
11570
11571 pub fn go_to_definition_split(
11572 &mut self,
11573 _: &GoToDefinitionSplit,
11574 window: &mut Window,
11575 cx: &mut Context<Self>,
11576 ) -> Task<Result<Navigated>> {
11577 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11578 }
11579
11580 pub fn go_to_type_definition_split(
11581 &mut self,
11582 _: &GoToTypeDefinitionSplit,
11583 window: &mut Window,
11584 cx: &mut Context<Self>,
11585 ) -> Task<Result<Navigated>> {
11586 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11587 }
11588
11589 fn go_to_definition_of_kind(
11590 &mut self,
11591 kind: GotoDefinitionKind,
11592 split: bool,
11593 window: &mut Window,
11594 cx: &mut Context<Self>,
11595 ) -> Task<Result<Navigated>> {
11596 let Some(provider) = self.semantics_provider.clone() else {
11597 return Task::ready(Ok(Navigated::No));
11598 };
11599 let head = self.selections.newest::<usize>(cx).head();
11600 let buffer = self.buffer.read(cx);
11601 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11602 text_anchor
11603 } else {
11604 return Task::ready(Ok(Navigated::No));
11605 };
11606
11607 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11608 return Task::ready(Ok(Navigated::No));
11609 };
11610
11611 cx.spawn_in(window, |editor, mut cx| async move {
11612 let definitions = definitions.await?;
11613 let navigated = editor
11614 .update_in(&mut cx, |editor, window, cx| {
11615 editor.navigate_to_hover_links(
11616 Some(kind),
11617 definitions
11618 .into_iter()
11619 .filter(|location| {
11620 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11621 })
11622 .map(HoverLink::Text)
11623 .collect::<Vec<_>>(),
11624 split,
11625 window,
11626 cx,
11627 )
11628 })?
11629 .await?;
11630 anyhow::Ok(navigated)
11631 })
11632 }
11633
11634 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11635 let selection = self.selections.newest_anchor();
11636 let head = selection.head();
11637 let tail = selection.tail();
11638
11639 let Some((buffer, start_position)) =
11640 self.buffer.read(cx).text_anchor_for_position(head, cx)
11641 else {
11642 return;
11643 };
11644
11645 let end_position = if head != tail {
11646 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11647 return;
11648 };
11649 Some(pos)
11650 } else {
11651 None
11652 };
11653
11654 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11655 let url = if let Some(end_pos) = end_position {
11656 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11657 } else {
11658 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11659 };
11660
11661 if let Some(url) = url {
11662 editor.update(&mut cx, |_, cx| {
11663 cx.open_url(&url);
11664 })
11665 } else {
11666 Ok(())
11667 }
11668 });
11669
11670 url_finder.detach();
11671 }
11672
11673 pub fn open_selected_filename(
11674 &mut self,
11675 _: &OpenSelectedFilename,
11676 window: &mut Window,
11677 cx: &mut Context<Self>,
11678 ) {
11679 let Some(workspace) = self.workspace() else {
11680 return;
11681 };
11682
11683 let position = self.selections.newest_anchor().head();
11684
11685 let Some((buffer, buffer_position)) =
11686 self.buffer.read(cx).text_anchor_for_position(position, cx)
11687 else {
11688 return;
11689 };
11690
11691 let project = self.project.clone();
11692
11693 cx.spawn_in(window, |_, mut cx| async move {
11694 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11695
11696 if let Some((_, path)) = result {
11697 workspace
11698 .update_in(&mut cx, |workspace, window, cx| {
11699 workspace.open_resolved_path(path, window, cx)
11700 })?
11701 .await?;
11702 }
11703 anyhow::Ok(())
11704 })
11705 .detach();
11706 }
11707
11708 pub(crate) fn navigate_to_hover_links(
11709 &mut self,
11710 kind: Option<GotoDefinitionKind>,
11711 mut definitions: Vec<HoverLink>,
11712 split: bool,
11713 window: &mut Window,
11714 cx: &mut Context<Editor>,
11715 ) -> Task<Result<Navigated>> {
11716 // If there is one definition, just open it directly
11717 if definitions.len() == 1 {
11718 let definition = definitions.pop().unwrap();
11719
11720 enum TargetTaskResult {
11721 Location(Option<Location>),
11722 AlreadyNavigated,
11723 }
11724
11725 let target_task = match definition {
11726 HoverLink::Text(link) => {
11727 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11728 }
11729 HoverLink::InlayHint(lsp_location, server_id) => {
11730 let computation =
11731 self.compute_target_location(lsp_location, server_id, window, cx);
11732 cx.background_spawn(async move {
11733 let location = computation.await?;
11734 Ok(TargetTaskResult::Location(location))
11735 })
11736 }
11737 HoverLink::Url(url) => {
11738 cx.open_url(&url);
11739 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11740 }
11741 HoverLink::File(path) => {
11742 if let Some(workspace) = self.workspace() {
11743 cx.spawn_in(window, |_, mut cx| async move {
11744 workspace
11745 .update_in(&mut cx, |workspace, window, cx| {
11746 workspace.open_resolved_path(path, window, cx)
11747 })?
11748 .await
11749 .map(|_| TargetTaskResult::AlreadyNavigated)
11750 })
11751 } else {
11752 Task::ready(Ok(TargetTaskResult::Location(None)))
11753 }
11754 }
11755 };
11756 cx.spawn_in(window, |editor, mut cx| async move {
11757 let target = match target_task.await.context("target resolution task")? {
11758 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11759 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11760 TargetTaskResult::Location(Some(target)) => target,
11761 };
11762
11763 editor.update_in(&mut cx, |editor, window, cx| {
11764 let Some(workspace) = editor.workspace() else {
11765 return Navigated::No;
11766 };
11767 let pane = workspace.read(cx).active_pane().clone();
11768
11769 let range = target.range.to_point(target.buffer.read(cx));
11770 let range = editor.range_for_match(&range);
11771 let range = collapse_multiline_range(range);
11772
11773 if !split
11774 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11775 {
11776 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11777 } else {
11778 window.defer(cx, move |window, cx| {
11779 let target_editor: Entity<Self> =
11780 workspace.update(cx, |workspace, cx| {
11781 let pane = if split {
11782 workspace.adjacent_pane(window, cx)
11783 } else {
11784 workspace.active_pane().clone()
11785 };
11786
11787 workspace.open_project_item(
11788 pane,
11789 target.buffer.clone(),
11790 true,
11791 true,
11792 window,
11793 cx,
11794 )
11795 });
11796 target_editor.update(cx, |target_editor, cx| {
11797 // When selecting a definition in a different buffer, disable the nav history
11798 // to avoid creating a history entry at the previous cursor location.
11799 pane.update(cx, |pane, _| pane.disable_history());
11800 target_editor.go_to_singleton_buffer_range(range, window, cx);
11801 pane.update(cx, |pane, _| pane.enable_history());
11802 });
11803 });
11804 }
11805 Navigated::Yes
11806 })
11807 })
11808 } else if !definitions.is_empty() {
11809 cx.spawn_in(window, |editor, mut cx| async move {
11810 let (title, location_tasks, workspace) = editor
11811 .update_in(&mut cx, |editor, window, cx| {
11812 let tab_kind = match kind {
11813 Some(GotoDefinitionKind::Implementation) => "Implementations",
11814 _ => "Definitions",
11815 };
11816 let title = definitions
11817 .iter()
11818 .find_map(|definition| match definition {
11819 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11820 let buffer = origin.buffer.read(cx);
11821 format!(
11822 "{} for {}",
11823 tab_kind,
11824 buffer
11825 .text_for_range(origin.range.clone())
11826 .collect::<String>()
11827 )
11828 }),
11829 HoverLink::InlayHint(_, _) => None,
11830 HoverLink::Url(_) => None,
11831 HoverLink::File(_) => None,
11832 })
11833 .unwrap_or(tab_kind.to_string());
11834 let location_tasks = definitions
11835 .into_iter()
11836 .map(|definition| match definition {
11837 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11838 HoverLink::InlayHint(lsp_location, server_id) => editor
11839 .compute_target_location(lsp_location, server_id, window, cx),
11840 HoverLink::Url(_) => Task::ready(Ok(None)),
11841 HoverLink::File(_) => Task::ready(Ok(None)),
11842 })
11843 .collect::<Vec<_>>();
11844 (title, location_tasks, editor.workspace().clone())
11845 })
11846 .context("location tasks preparation")?;
11847
11848 let locations = future::join_all(location_tasks)
11849 .await
11850 .into_iter()
11851 .filter_map(|location| location.transpose())
11852 .collect::<Result<_>>()
11853 .context("location tasks")?;
11854
11855 let Some(workspace) = workspace else {
11856 return Ok(Navigated::No);
11857 };
11858 let opened = workspace
11859 .update_in(&mut cx, |workspace, window, cx| {
11860 Self::open_locations_in_multibuffer(
11861 workspace,
11862 locations,
11863 title,
11864 split,
11865 MultibufferSelectionMode::First,
11866 window,
11867 cx,
11868 )
11869 })
11870 .ok();
11871
11872 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11873 })
11874 } else {
11875 Task::ready(Ok(Navigated::No))
11876 }
11877 }
11878
11879 fn compute_target_location(
11880 &self,
11881 lsp_location: lsp::Location,
11882 server_id: LanguageServerId,
11883 window: &mut Window,
11884 cx: &mut Context<Self>,
11885 ) -> Task<anyhow::Result<Option<Location>>> {
11886 let Some(project) = self.project.clone() else {
11887 return Task::ready(Ok(None));
11888 };
11889
11890 cx.spawn_in(window, move |editor, mut cx| async move {
11891 let location_task = editor.update(&mut cx, |_, cx| {
11892 project.update(cx, |project, cx| {
11893 let language_server_name = project
11894 .language_server_statuses(cx)
11895 .find(|(id, _)| server_id == *id)
11896 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11897 language_server_name.map(|language_server_name| {
11898 project.open_local_buffer_via_lsp(
11899 lsp_location.uri.clone(),
11900 server_id,
11901 language_server_name,
11902 cx,
11903 )
11904 })
11905 })
11906 })?;
11907 let location = match location_task {
11908 Some(task) => Some({
11909 let target_buffer_handle = task.await.context("open local buffer")?;
11910 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11911 let target_start = target_buffer
11912 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11913 let target_end = target_buffer
11914 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11915 target_buffer.anchor_after(target_start)
11916 ..target_buffer.anchor_before(target_end)
11917 })?;
11918 Location {
11919 buffer: target_buffer_handle,
11920 range,
11921 }
11922 }),
11923 None => None,
11924 };
11925 Ok(location)
11926 })
11927 }
11928
11929 pub fn find_all_references(
11930 &mut self,
11931 _: &FindAllReferences,
11932 window: &mut Window,
11933 cx: &mut Context<Self>,
11934 ) -> Option<Task<Result<Navigated>>> {
11935 let selection = self.selections.newest::<usize>(cx);
11936 let multi_buffer = self.buffer.read(cx);
11937 let head = selection.head();
11938
11939 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11940 let head_anchor = multi_buffer_snapshot.anchor_at(
11941 head,
11942 if head < selection.tail() {
11943 Bias::Right
11944 } else {
11945 Bias::Left
11946 },
11947 );
11948
11949 match self
11950 .find_all_references_task_sources
11951 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11952 {
11953 Ok(_) => {
11954 log::info!(
11955 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11956 );
11957 return None;
11958 }
11959 Err(i) => {
11960 self.find_all_references_task_sources.insert(i, head_anchor);
11961 }
11962 }
11963
11964 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11965 let workspace = self.workspace()?;
11966 let project = workspace.read(cx).project().clone();
11967 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11968 Some(cx.spawn_in(window, |editor, mut cx| async move {
11969 let _cleanup = defer({
11970 let mut cx = cx.clone();
11971 move || {
11972 let _ = editor.update(&mut cx, |editor, _| {
11973 if let Ok(i) =
11974 editor
11975 .find_all_references_task_sources
11976 .binary_search_by(|anchor| {
11977 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11978 })
11979 {
11980 editor.find_all_references_task_sources.remove(i);
11981 }
11982 });
11983 }
11984 });
11985
11986 let locations = references.await?;
11987 if locations.is_empty() {
11988 return anyhow::Ok(Navigated::No);
11989 }
11990
11991 workspace.update_in(&mut cx, |workspace, window, cx| {
11992 let title = locations
11993 .first()
11994 .as_ref()
11995 .map(|location| {
11996 let buffer = location.buffer.read(cx);
11997 format!(
11998 "References to `{}`",
11999 buffer
12000 .text_for_range(location.range.clone())
12001 .collect::<String>()
12002 )
12003 })
12004 .unwrap();
12005 Self::open_locations_in_multibuffer(
12006 workspace,
12007 locations,
12008 title,
12009 false,
12010 MultibufferSelectionMode::First,
12011 window,
12012 cx,
12013 );
12014 Navigated::Yes
12015 })
12016 }))
12017 }
12018
12019 /// Opens a multibuffer with the given project locations in it
12020 pub fn open_locations_in_multibuffer(
12021 workspace: &mut Workspace,
12022 mut locations: Vec<Location>,
12023 title: String,
12024 split: bool,
12025 multibuffer_selection_mode: MultibufferSelectionMode,
12026 window: &mut Window,
12027 cx: &mut Context<Workspace>,
12028 ) {
12029 // If there are multiple definitions, open them in a multibuffer
12030 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12031 let mut locations = locations.into_iter().peekable();
12032 let mut ranges = Vec::new();
12033 let capability = workspace.project().read(cx).capability();
12034
12035 let excerpt_buffer = cx.new(|cx| {
12036 let mut multibuffer = MultiBuffer::new(capability);
12037 while let Some(location) = locations.next() {
12038 let buffer = location.buffer.read(cx);
12039 let mut ranges_for_buffer = Vec::new();
12040 let range = location.range.to_offset(buffer);
12041 ranges_for_buffer.push(range.clone());
12042
12043 while let Some(next_location) = locations.peek() {
12044 if next_location.buffer == location.buffer {
12045 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12046 locations.next();
12047 } else {
12048 break;
12049 }
12050 }
12051
12052 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12053 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12054 location.buffer.clone(),
12055 ranges_for_buffer,
12056 DEFAULT_MULTIBUFFER_CONTEXT,
12057 cx,
12058 ))
12059 }
12060
12061 multibuffer.with_title(title)
12062 });
12063
12064 let editor = cx.new(|cx| {
12065 Editor::for_multibuffer(
12066 excerpt_buffer,
12067 Some(workspace.project().clone()),
12068 true,
12069 window,
12070 cx,
12071 )
12072 });
12073 editor.update(cx, |editor, cx| {
12074 match multibuffer_selection_mode {
12075 MultibufferSelectionMode::First => {
12076 if let Some(first_range) = ranges.first() {
12077 editor.change_selections(None, window, cx, |selections| {
12078 selections.clear_disjoint();
12079 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12080 });
12081 }
12082 editor.highlight_background::<Self>(
12083 &ranges,
12084 |theme| theme.editor_highlighted_line_background,
12085 cx,
12086 );
12087 }
12088 MultibufferSelectionMode::All => {
12089 editor.change_selections(None, window, cx, |selections| {
12090 selections.clear_disjoint();
12091 selections.select_anchor_ranges(ranges);
12092 });
12093 }
12094 }
12095 editor.register_buffers_with_language_servers(cx);
12096 });
12097
12098 let item = Box::new(editor);
12099 let item_id = item.item_id();
12100
12101 if split {
12102 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12103 } else {
12104 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12105 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12106 pane.close_current_preview_item(window, cx)
12107 } else {
12108 None
12109 }
12110 });
12111 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12112 }
12113 workspace.active_pane().update(cx, |pane, cx| {
12114 pane.set_preview_item_id(Some(item_id), cx);
12115 });
12116 }
12117
12118 pub fn rename(
12119 &mut self,
12120 _: &Rename,
12121 window: &mut Window,
12122 cx: &mut Context<Self>,
12123 ) -> Option<Task<Result<()>>> {
12124 use language::ToOffset as _;
12125
12126 let provider = self.semantics_provider.clone()?;
12127 let selection = self.selections.newest_anchor().clone();
12128 let (cursor_buffer, cursor_buffer_position) = self
12129 .buffer
12130 .read(cx)
12131 .text_anchor_for_position(selection.head(), cx)?;
12132 let (tail_buffer, cursor_buffer_position_end) = self
12133 .buffer
12134 .read(cx)
12135 .text_anchor_for_position(selection.tail(), cx)?;
12136 if tail_buffer != cursor_buffer {
12137 return None;
12138 }
12139
12140 let snapshot = cursor_buffer.read(cx).snapshot();
12141 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12142 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12143 let prepare_rename = provider
12144 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12145 .unwrap_or_else(|| Task::ready(Ok(None)));
12146 drop(snapshot);
12147
12148 Some(cx.spawn_in(window, |this, mut cx| async move {
12149 let rename_range = if let Some(range) = prepare_rename.await? {
12150 Some(range)
12151 } else {
12152 this.update(&mut cx, |this, cx| {
12153 let buffer = this.buffer.read(cx).snapshot(cx);
12154 let mut buffer_highlights = this
12155 .document_highlights_for_position(selection.head(), &buffer)
12156 .filter(|highlight| {
12157 highlight.start.excerpt_id == selection.head().excerpt_id
12158 && highlight.end.excerpt_id == selection.head().excerpt_id
12159 });
12160 buffer_highlights
12161 .next()
12162 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12163 })?
12164 };
12165 if let Some(rename_range) = rename_range {
12166 this.update_in(&mut cx, |this, window, cx| {
12167 let snapshot = cursor_buffer.read(cx).snapshot();
12168 let rename_buffer_range = rename_range.to_offset(&snapshot);
12169 let cursor_offset_in_rename_range =
12170 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12171 let cursor_offset_in_rename_range_end =
12172 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12173
12174 this.take_rename(false, window, cx);
12175 let buffer = this.buffer.read(cx).read(cx);
12176 let cursor_offset = selection.head().to_offset(&buffer);
12177 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12178 let rename_end = rename_start + rename_buffer_range.len();
12179 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12180 let mut old_highlight_id = None;
12181 let old_name: Arc<str> = buffer
12182 .chunks(rename_start..rename_end, true)
12183 .map(|chunk| {
12184 if old_highlight_id.is_none() {
12185 old_highlight_id = chunk.syntax_highlight_id;
12186 }
12187 chunk.text
12188 })
12189 .collect::<String>()
12190 .into();
12191
12192 drop(buffer);
12193
12194 // Position the selection in the rename editor so that it matches the current selection.
12195 this.show_local_selections = false;
12196 let rename_editor = cx.new(|cx| {
12197 let mut editor = Editor::single_line(window, cx);
12198 editor.buffer.update(cx, |buffer, cx| {
12199 buffer.edit([(0..0, old_name.clone())], None, cx)
12200 });
12201 let rename_selection_range = match cursor_offset_in_rename_range
12202 .cmp(&cursor_offset_in_rename_range_end)
12203 {
12204 Ordering::Equal => {
12205 editor.select_all(&SelectAll, window, cx);
12206 return editor;
12207 }
12208 Ordering::Less => {
12209 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12210 }
12211 Ordering::Greater => {
12212 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12213 }
12214 };
12215 if rename_selection_range.end > old_name.len() {
12216 editor.select_all(&SelectAll, window, cx);
12217 } else {
12218 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12219 s.select_ranges([rename_selection_range]);
12220 });
12221 }
12222 editor
12223 });
12224 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12225 if e == &EditorEvent::Focused {
12226 cx.emit(EditorEvent::FocusedIn)
12227 }
12228 })
12229 .detach();
12230
12231 let write_highlights =
12232 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12233 let read_highlights =
12234 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12235 let ranges = write_highlights
12236 .iter()
12237 .flat_map(|(_, ranges)| ranges.iter())
12238 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12239 .cloned()
12240 .collect();
12241
12242 this.highlight_text::<Rename>(
12243 ranges,
12244 HighlightStyle {
12245 fade_out: Some(0.6),
12246 ..Default::default()
12247 },
12248 cx,
12249 );
12250 let rename_focus_handle = rename_editor.focus_handle(cx);
12251 window.focus(&rename_focus_handle);
12252 let block_id = this.insert_blocks(
12253 [BlockProperties {
12254 style: BlockStyle::Flex,
12255 placement: BlockPlacement::Below(range.start),
12256 height: 1,
12257 render: Arc::new({
12258 let rename_editor = rename_editor.clone();
12259 move |cx: &mut BlockContext| {
12260 let mut text_style = cx.editor_style.text.clone();
12261 if let Some(highlight_style) = old_highlight_id
12262 .and_then(|h| h.style(&cx.editor_style.syntax))
12263 {
12264 text_style = text_style.highlight(highlight_style);
12265 }
12266 div()
12267 .block_mouse_down()
12268 .pl(cx.anchor_x)
12269 .child(EditorElement::new(
12270 &rename_editor,
12271 EditorStyle {
12272 background: cx.theme().system().transparent,
12273 local_player: cx.editor_style.local_player,
12274 text: text_style,
12275 scrollbar_width: cx.editor_style.scrollbar_width,
12276 syntax: cx.editor_style.syntax.clone(),
12277 status: cx.editor_style.status.clone(),
12278 inlay_hints_style: HighlightStyle {
12279 font_weight: Some(FontWeight::BOLD),
12280 ..make_inlay_hints_style(cx.app)
12281 },
12282 inline_completion_styles: make_suggestion_styles(
12283 cx.app,
12284 ),
12285 ..EditorStyle::default()
12286 },
12287 ))
12288 .into_any_element()
12289 }
12290 }),
12291 priority: 0,
12292 }],
12293 Some(Autoscroll::fit()),
12294 cx,
12295 )[0];
12296 this.pending_rename = Some(RenameState {
12297 range,
12298 old_name,
12299 editor: rename_editor,
12300 block_id,
12301 });
12302 })?;
12303 }
12304
12305 Ok(())
12306 }))
12307 }
12308
12309 pub fn confirm_rename(
12310 &mut self,
12311 _: &ConfirmRename,
12312 window: &mut Window,
12313 cx: &mut Context<Self>,
12314 ) -> Option<Task<Result<()>>> {
12315 let rename = self.take_rename(false, window, cx)?;
12316 let workspace = self.workspace()?.downgrade();
12317 let (buffer, start) = self
12318 .buffer
12319 .read(cx)
12320 .text_anchor_for_position(rename.range.start, cx)?;
12321 let (end_buffer, _) = self
12322 .buffer
12323 .read(cx)
12324 .text_anchor_for_position(rename.range.end, cx)?;
12325 if buffer != end_buffer {
12326 return None;
12327 }
12328
12329 let old_name = rename.old_name;
12330 let new_name = rename.editor.read(cx).text(cx);
12331
12332 let rename = self.semantics_provider.as_ref()?.perform_rename(
12333 &buffer,
12334 start,
12335 new_name.clone(),
12336 cx,
12337 )?;
12338
12339 Some(cx.spawn_in(window, |editor, mut cx| async move {
12340 let project_transaction = rename.await?;
12341 Self::open_project_transaction(
12342 &editor,
12343 workspace,
12344 project_transaction,
12345 format!("Rename: {} → {}", old_name, new_name),
12346 cx.clone(),
12347 )
12348 .await?;
12349
12350 editor.update(&mut cx, |editor, cx| {
12351 editor.refresh_document_highlights(cx);
12352 })?;
12353 Ok(())
12354 }))
12355 }
12356
12357 fn take_rename(
12358 &mut self,
12359 moving_cursor: bool,
12360 window: &mut Window,
12361 cx: &mut Context<Self>,
12362 ) -> Option<RenameState> {
12363 let rename = self.pending_rename.take()?;
12364 if rename.editor.focus_handle(cx).is_focused(window) {
12365 window.focus(&self.focus_handle);
12366 }
12367
12368 self.remove_blocks(
12369 [rename.block_id].into_iter().collect(),
12370 Some(Autoscroll::fit()),
12371 cx,
12372 );
12373 self.clear_highlights::<Rename>(cx);
12374 self.show_local_selections = true;
12375
12376 if moving_cursor {
12377 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12378 editor.selections.newest::<usize>(cx).head()
12379 });
12380
12381 // Update the selection to match the position of the selection inside
12382 // the rename editor.
12383 let snapshot = self.buffer.read(cx).read(cx);
12384 let rename_range = rename.range.to_offset(&snapshot);
12385 let cursor_in_editor = snapshot
12386 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12387 .min(rename_range.end);
12388 drop(snapshot);
12389
12390 self.change_selections(None, window, cx, |s| {
12391 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12392 });
12393 } else {
12394 self.refresh_document_highlights(cx);
12395 }
12396
12397 Some(rename)
12398 }
12399
12400 pub fn pending_rename(&self) -> Option<&RenameState> {
12401 self.pending_rename.as_ref()
12402 }
12403
12404 fn format(
12405 &mut self,
12406 _: &Format,
12407 window: &mut Window,
12408 cx: &mut Context<Self>,
12409 ) -> Option<Task<Result<()>>> {
12410 let project = match &self.project {
12411 Some(project) => project.clone(),
12412 None => return None,
12413 };
12414
12415 Some(self.perform_format(
12416 project,
12417 FormatTrigger::Manual,
12418 FormatTarget::Buffers,
12419 window,
12420 cx,
12421 ))
12422 }
12423
12424 fn format_selections(
12425 &mut self,
12426 _: &FormatSelections,
12427 window: &mut Window,
12428 cx: &mut Context<Self>,
12429 ) -> Option<Task<Result<()>>> {
12430 let project = match &self.project {
12431 Some(project) => project.clone(),
12432 None => return None,
12433 };
12434
12435 let ranges = self
12436 .selections
12437 .all_adjusted(cx)
12438 .into_iter()
12439 .map(|selection| selection.range())
12440 .collect_vec();
12441
12442 Some(self.perform_format(
12443 project,
12444 FormatTrigger::Manual,
12445 FormatTarget::Ranges(ranges),
12446 window,
12447 cx,
12448 ))
12449 }
12450
12451 fn perform_format(
12452 &mut self,
12453 project: Entity<Project>,
12454 trigger: FormatTrigger,
12455 target: FormatTarget,
12456 window: &mut Window,
12457 cx: &mut Context<Self>,
12458 ) -> Task<Result<()>> {
12459 let buffer = self.buffer.clone();
12460 let (buffers, target) = match target {
12461 FormatTarget::Buffers => {
12462 let mut buffers = buffer.read(cx).all_buffers();
12463 if trigger == FormatTrigger::Save {
12464 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12465 }
12466 (buffers, LspFormatTarget::Buffers)
12467 }
12468 FormatTarget::Ranges(selection_ranges) => {
12469 let multi_buffer = buffer.read(cx);
12470 let snapshot = multi_buffer.read(cx);
12471 let mut buffers = HashSet::default();
12472 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12473 BTreeMap::new();
12474 for selection_range in selection_ranges {
12475 for (buffer, buffer_range, _) in
12476 snapshot.range_to_buffer_ranges(selection_range)
12477 {
12478 let buffer_id = buffer.remote_id();
12479 let start = buffer.anchor_before(buffer_range.start);
12480 let end = buffer.anchor_after(buffer_range.end);
12481 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12482 buffer_id_to_ranges
12483 .entry(buffer_id)
12484 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12485 .or_insert_with(|| vec![start..end]);
12486 }
12487 }
12488 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12489 }
12490 };
12491
12492 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12493 let format = project.update(cx, |project, cx| {
12494 project.format(buffers, target, true, trigger, cx)
12495 });
12496
12497 cx.spawn_in(window, |_, mut cx| async move {
12498 let transaction = futures::select_biased! {
12499 () = timeout => {
12500 log::warn!("timed out waiting for formatting");
12501 None
12502 }
12503 transaction = format.log_err().fuse() => transaction,
12504 };
12505
12506 buffer
12507 .update(&mut cx, |buffer, cx| {
12508 if let Some(transaction) = transaction {
12509 if !buffer.is_singleton() {
12510 buffer.push_transaction(&transaction.0, cx);
12511 }
12512 }
12513 cx.notify();
12514 })
12515 .ok();
12516
12517 Ok(())
12518 })
12519 }
12520
12521 fn organize_imports(
12522 &mut self,
12523 _: &OrganizeImports,
12524 window: &mut Window,
12525 cx: &mut Context<Self>,
12526 ) -> Option<Task<Result<()>>> {
12527 let project = match &self.project {
12528 Some(project) => project.clone(),
12529 None => return None,
12530 };
12531 Some(self.perform_code_action_kind(
12532 project,
12533 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12534 window,
12535 cx,
12536 ))
12537 }
12538
12539 fn perform_code_action_kind(
12540 &mut self,
12541 project: Entity<Project>,
12542 kind: CodeActionKind,
12543 window: &mut Window,
12544 cx: &mut Context<Self>,
12545 ) -> Task<Result<()>> {
12546 let buffer = self.buffer.clone();
12547 let buffers = buffer.read(cx).all_buffers();
12548 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12549 let apply_action = project.update(cx, |project, cx| {
12550 project.apply_code_action_kind(buffers, kind, true, cx)
12551 });
12552 cx.spawn_in(window, |_, mut cx| async move {
12553 let transaction = futures::select_biased! {
12554 () = timeout => {
12555 log::warn!("timed out waiting for executing code action");
12556 None
12557 }
12558 transaction = apply_action.log_err().fuse() => transaction,
12559 };
12560 buffer
12561 .update(&mut cx, |buffer, cx| {
12562 // check if we need this
12563 if let Some(transaction) = transaction {
12564 if !buffer.is_singleton() {
12565 buffer.push_transaction(&transaction.0, cx);
12566 }
12567 }
12568 cx.notify();
12569 })
12570 .ok();
12571 Ok(())
12572 })
12573 }
12574
12575 fn restart_language_server(
12576 &mut self,
12577 _: &RestartLanguageServer,
12578 _: &mut Window,
12579 cx: &mut Context<Self>,
12580 ) {
12581 if let Some(project) = self.project.clone() {
12582 self.buffer.update(cx, |multi_buffer, cx| {
12583 project.update(cx, |project, cx| {
12584 project.restart_language_servers_for_buffers(
12585 multi_buffer.all_buffers().into_iter().collect(),
12586 cx,
12587 );
12588 });
12589 })
12590 }
12591 }
12592
12593 fn cancel_language_server_work(
12594 workspace: &mut Workspace,
12595 _: &actions::CancelLanguageServerWork,
12596 _: &mut Window,
12597 cx: &mut Context<Workspace>,
12598 ) {
12599 let project = workspace.project();
12600 let buffers = workspace
12601 .active_item(cx)
12602 .and_then(|item| item.act_as::<Editor>(cx))
12603 .map_or(HashSet::default(), |editor| {
12604 editor.read(cx).buffer.read(cx).all_buffers()
12605 });
12606 project.update(cx, |project, cx| {
12607 project.cancel_language_server_work_for_buffers(buffers, cx);
12608 });
12609 }
12610
12611 fn show_character_palette(
12612 &mut self,
12613 _: &ShowCharacterPalette,
12614 window: &mut Window,
12615 _: &mut Context<Self>,
12616 ) {
12617 window.show_character_palette();
12618 }
12619
12620 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12621 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12622 let buffer = self.buffer.read(cx).snapshot(cx);
12623 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12624 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12625 let is_valid = buffer
12626 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12627 .any(|entry| {
12628 entry.diagnostic.is_primary
12629 && !entry.range.is_empty()
12630 && entry.range.start == primary_range_start
12631 && entry.diagnostic.message == active_diagnostics.primary_message
12632 });
12633
12634 if is_valid != active_diagnostics.is_valid {
12635 active_diagnostics.is_valid = is_valid;
12636 if is_valid {
12637 let mut new_styles = HashMap::default();
12638 for (block_id, diagnostic) in &active_diagnostics.blocks {
12639 new_styles.insert(
12640 *block_id,
12641 diagnostic_block_renderer(diagnostic.clone(), None, true),
12642 );
12643 }
12644 self.display_map.update(cx, |display_map, _cx| {
12645 display_map.replace_blocks(new_styles);
12646 });
12647 } else {
12648 self.dismiss_diagnostics(cx);
12649 }
12650 }
12651 }
12652 }
12653
12654 fn activate_diagnostics(
12655 &mut self,
12656 buffer_id: BufferId,
12657 group_id: usize,
12658 window: &mut Window,
12659 cx: &mut Context<Self>,
12660 ) {
12661 self.dismiss_diagnostics(cx);
12662 let snapshot = self.snapshot(window, cx);
12663 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12664 let buffer = self.buffer.read(cx).snapshot(cx);
12665
12666 let mut primary_range = None;
12667 let mut primary_message = None;
12668 let diagnostic_group = buffer
12669 .diagnostic_group(buffer_id, group_id)
12670 .filter_map(|entry| {
12671 let start = entry.range.start;
12672 let end = entry.range.end;
12673 if snapshot.is_line_folded(MultiBufferRow(start.row))
12674 && (start.row == end.row
12675 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12676 {
12677 return None;
12678 }
12679 if entry.diagnostic.is_primary {
12680 primary_range = Some(entry.range.clone());
12681 primary_message = Some(entry.diagnostic.message.clone());
12682 }
12683 Some(entry)
12684 })
12685 .collect::<Vec<_>>();
12686 let primary_range = primary_range?;
12687 let primary_message = primary_message?;
12688
12689 let blocks = display_map
12690 .insert_blocks(
12691 diagnostic_group.iter().map(|entry| {
12692 let diagnostic = entry.diagnostic.clone();
12693 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12694 BlockProperties {
12695 style: BlockStyle::Fixed,
12696 placement: BlockPlacement::Below(
12697 buffer.anchor_after(entry.range.start),
12698 ),
12699 height: message_height,
12700 render: diagnostic_block_renderer(diagnostic, None, true),
12701 priority: 0,
12702 }
12703 }),
12704 cx,
12705 )
12706 .into_iter()
12707 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12708 .collect();
12709
12710 Some(ActiveDiagnosticGroup {
12711 primary_range: buffer.anchor_before(primary_range.start)
12712 ..buffer.anchor_after(primary_range.end),
12713 primary_message,
12714 group_id,
12715 blocks,
12716 is_valid: true,
12717 })
12718 });
12719 }
12720
12721 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12722 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12723 self.display_map.update(cx, |display_map, cx| {
12724 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12725 });
12726 cx.notify();
12727 }
12728 }
12729
12730 /// Disable inline diagnostics rendering for this editor.
12731 pub fn disable_inline_diagnostics(&mut self) {
12732 self.inline_diagnostics_enabled = false;
12733 self.inline_diagnostics_update = Task::ready(());
12734 self.inline_diagnostics.clear();
12735 }
12736
12737 pub fn inline_diagnostics_enabled(&self) -> bool {
12738 self.inline_diagnostics_enabled
12739 }
12740
12741 pub fn show_inline_diagnostics(&self) -> bool {
12742 self.show_inline_diagnostics
12743 }
12744
12745 pub fn toggle_inline_diagnostics(
12746 &mut self,
12747 _: &ToggleInlineDiagnostics,
12748 window: &mut Window,
12749 cx: &mut Context<'_, Editor>,
12750 ) {
12751 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12752 self.refresh_inline_diagnostics(false, window, cx);
12753 }
12754
12755 fn refresh_inline_diagnostics(
12756 &mut self,
12757 debounce: bool,
12758 window: &mut Window,
12759 cx: &mut Context<Self>,
12760 ) {
12761 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12762 self.inline_diagnostics_update = Task::ready(());
12763 self.inline_diagnostics.clear();
12764 return;
12765 }
12766
12767 let debounce_ms = ProjectSettings::get_global(cx)
12768 .diagnostics
12769 .inline
12770 .update_debounce_ms;
12771 let debounce = if debounce && debounce_ms > 0 {
12772 Some(Duration::from_millis(debounce_ms))
12773 } else {
12774 None
12775 };
12776 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12777 if let Some(debounce) = debounce {
12778 cx.background_executor().timer(debounce).await;
12779 }
12780 let Some(snapshot) = editor
12781 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12782 .ok()
12783 else {
12784 return;
12785 };
12786
12787 let new_inline_diagnostics = cx
12788 .background_spawn(async move {
12789 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12790 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12791 let message = diagnostic_entry
12792 .diagnostic
12793 .message
12794 .split_once('\n')
12795 .map(|(line, _)| line)
12796 .map(SharedString::new)
12797 .unwrap_or_else(|| {
12798 SharedString::from(diagnostic_entry.diagnostic.message)
12799 });
12800 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12801 let (Ok(i) | Err(i)) = inline_diagnostics
12802 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12803 inline_diagnostics.insert(
12804 i,
12805 (
12806 start_anchor,
12807 InlineDiagnostic {
12808 message,
12809 group_id: diagnostic_entry.diagnostic.group_id,
12810 start: diagnostic_entry.range.start.to_point(&snapshot),
12811 is_primary: diagnostic_entry.diagnostic.is_primary,
12812 severity: diagnostic_entry.diagnostic.severity,
12813 },
12814 ),
12815 );
12816 }
12817 inline_diagnostics
12818 })
12819 .await;
12820
12821 editor
12822 .update(&mut cx, |editor, cx| {
12823 editor.inline_diagnostics = new_inline_diagnostics;
12824 cx.notify();
12825 })
12826 .ok();
12827 });
12828 }
12829
12830 pub fn set_selections_from_remote(
12831 &mut self,
12832 selections: Vec<Selection<Anchor>>,
12833 pending_selection: Option<Selection<Anchor>>,
12834 window: &mut Window,
12835 cx: &mut Context<Self>,
12836 ) {
12837 let old_cursor_position = self.selections.newest_anchor().head();
12838 self.selections.change_with(cx, |s| {
12839 s.select_anchors(selections);
12840 if let Some(pending_selection) = pending_selection {
12841 s.set_pending(pending_selection, SelectMode::Character);
12842 } else {
12843 s.clear_pending();
12844 }
12845 });
12846 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12847 }
12848
12849 fn push_to_selection_history(&mut self) {
12850 self.selection_history.push(SelectionHistoryEntry {
12851 selections: self.selections.disjoint_anchors(),
12852 select_next_state: self.select_next_state.clone(),
12853 select_prev_state: self.select_prev_state.clone(),
12854 add_selections_state: self.add_selections_state.clone(),
12855 });
12856 }
12857
12858 pub fn transact(
12859 &mut self,
12860 window: &mut Window,
12861 cx: &mut Context<Self>,
12862 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12863 ) -> Option<TransactionId> {
12864 self.start_transaction_at(Instant::now(), window, cx);
12865 update(self, window, cx);
12866 self.end_transaction_at(Instant::now(), cx)
12867 }
12868
12869 pub fn start_transaction_at(
12870 &mut self,
12871 now: Instant,
12872 window: &mut Window,
12873 cx: &mut Context<Self>,
12874 ) {
12875 self.end_selection(window, cx);
12876 if let Some(tx_id) = self
12877 .buffer
12878 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12879 {
12880 self.selection_history
12881 .insert_transaction(tx_id, self.selections.disjoint_anchors());
12882 cx.emit(EditorEvent::TransactionBegun {
12883 transaction_id: tx_id,
12884 })
12885 }
12886 }
12887
12888 pub fn end_transaction_at(
12889 &mut self,
12890 now: Instant,
12891 cx: &mut Context<Self>,
12892 ) -> Option<TransactionId> {
12893 if let Some(transaction_id) = self
12894 .buffer
12895 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12896 {
12897 if let Some((_, end_selections)) =
12898 self.selection_history.transaction_mut(transaction_id)
12899 {
12900 *end_selections = Some(self.selections.disjoint_anchors());
12901 } else {
12902 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12903 }
12904
12905 cx.emit(EditorEvent::Edited { transaction_id });
12906 Some(transaction_id)
12907 } else {
12908 None
12909 }
12910 }
12911
12912 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12913 if self.selection_mark_mode {
12914 self.change_selections(None, window, cx, |s| {
12915 s.move_with(|_, sel| {
12916 sel.collapse_to(sel.head(), SelectionGoal::None);
12917 });
12918 })
12919 }
12920 self.selection_mark_mode = true;
12921 cx.notify();
12922 }
12923
12924 pub fn swap_selection_ends(
12925 &mut self,
12926 _: &actions::SwapSelectionEnds,
12927 window: &mut Window,
12928 cx: &mut Context<Self>,
12929 ) {
12930 self.change_selections(None, window, cx, |s| {
12931 s.move_with(|_, sel| {
12932 if sel.start != sel.end {
12933 sel.reversed = !sel.reversed
12934 }
12935 });
12936 });
12937 self.request_autoscroll(Autoscroll::newest(), cx);
12938 cx.notify();
12939 }
12940
12941 pub fn toggle_fold(
12942 &mut self,
12943 _: &actions::ToggleFold,
12944 window: &mut Window,
12945 cx: &mut Context<Self>,
12946 ) {
12947 if self.is_singleton(cx) {
12948 let selection = self.selections.newest::<Point>(cx);
12949
12950 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12951 let range = if selection.is_empty() {
12952 let point = selection.head().to_display_point(&display_map);
12953 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12954 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12955 .to_point(&display_map);
12956 start..end
12957 } else {
12958 selection.range()
12959 };
12960 if display_map.folds_in_range(range).next().is_some() {
12961 self.unfold_lines(&Default::default(), window, cx)
12962 } else {
12963 self.fold(&Default::default(), window, cx)
12964 }
12965 } else {
12966 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12967 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12968 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12969 .map(|(snapshot, _, _)| snapshot.remote_id())
12970 .collect();
12971
12972 for buffer_id in buffer_ids {
12973 if self.is_buffer_folded(buffer_id, cx) {
12974 self.unfold_buffer(buffer_id, cx);
12975 } else {
12976 self.fold_buffer(buffer_id, cx);
12977 }
12978 }
12979 }
12980 }
12981
12982 pub fn toggle_fold_recursive(
12983 &mut self,
12984 _: &actions::ToggleFoldRecursive,
12985 window: &mut Window,
12986 cx: &mut Context<Self>,
12987 ) {
12988 let selection = self.selections.newest::<Point>(cx);
12989
12990 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12991 let range = if selection.is_empty() {
12992 let point = selection.head().to_display_point(&display_map);
12993 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12994 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12995 .to_point(&display_map);
12996 start..end
12997 } else {
12998 selection.range()
12999 };
13000 if display_map.folds_in_range(range).next().is_some() {
13001 self.unfold_recursive(&Default::default(), window, cx)
13002 } else {
13003 self.fold_recursive(&Default::default(), window, cx)
13004 }
13005 }
13006
13007 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13008 if self.is_singleton(cx) {
13009 let mut to_fold = Vec::new();
13010 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13011 let selections = self.selections.all_adjusted(cx);
13012
13013 for selection in selections {
13014 let range = selection.range().sorted();
13015 let buffer_start_row = range.start.row;
13016
13017 if range.start.row != range.end.row {
13018 let mut found = false;
13019 let mut row = range.start.row;
13020 while row <= range.end.row {
13021 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13022 {
13023 found = true;
13024 row = crease.range().end.row + 1;
13025 to_fold.push(crease);
13026 } else {
13027 row += 1
13028 }
13029 }
13030 if found {
13031 continue;
13032 }
13033 }
13034
13035 for row in (0..=range.start.row).rev() {
13036 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13037 if crease.range().end.row >= buffer_start_row {
13038 to_fold.push(crease);
13039 if row <= range.start.row {
13040 break;
13041 }
13042 }
13043 }
13044 }
13045 }
13046
13047 self.fold_creases(to_fold, true, window, cx);
13048 } else {
13049 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13050 let buffer_ids = self
13051 .selections
13052 .disjoint_anchor_ranges()
13053 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13054 .collect::<HashSet<_>>();
13055 for buffer_id in buffer_ids {
13056 self.fold_buffer(buffer_id, cx);
13057 }
13058 }
13059 }
13060
13061 fn fold_at_level(
13062 &mut self,
13063 fold_at: &FoldAtLevel,
13064 window: &mut Window,
13065 cx: &mut Context<Self>,
13066 ) {
13067 if !self.buffer.read(cx).is_singleton() {
13068 return;
13069 }
13070
13071 let fold_at_level = fold_at.0;
13072 let snapshot = self.buffer.read(cx).snapshot(cx);
13073 let mut to_fold = Vec::new();
13074 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13075
13076 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13077 while start_row < end_row {
13078 match self
13079 .snapshot(window, cx)
13080 .crease_for_buffer_row(MultiBufferRow(start_row))
13081 {
13082 Some(crease) => {
13083 let nested_start_row = crease.range().start.row + 1;
13084 let nested_end_row = crease.range().end.row;
13085
13086 if current_level < fold_at_level {
13087 stack.push((nested_start_row, nested_end_row, current_level + 1));
13088 } else if current_level == fold_at_level {
13089 to_fold.push(crease);
13090 }
13091
13092 start_row = nested_end_row + 1;
13093 }
13094 None => start_row += 1,
13095 }
13096 }
13097 }
13098
13099 self.fold_creases(to_fold, true, window, cx);
13100 }
13101
13102 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13103 if self.buffer.read(cx).is_singleton() {
13104 let mut fold_ranges = Vec::new();
13105 let snapshot = self.buffer.read(cx).snapshot(cx);
13106
13107 for row in 0..snapshot.max_row().0 {
13108 if let Some(foldable_range) = self
13109 .snapshot(window, cx)
13110 .crease_for_buffer_row(MultiBufferRow(row))
13111 {
13112 fold_ranges.push(foldable_range);
13113 }
13114 }
13115
13116 self.fold_creases(fold_ranges, true, window, cx);
13117 } else {
13118 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13119 editor
13120 .update_in(&mut cx, |editor, _, cx| {
13121 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13122 editor.fold_buffer(buffer_id, cx);
13123 }
13124 })
13125 .ok();
13126 });
13127 }
13128 }
13129
13130 pub fn fold_function_bodies(
13131 &mut self,
13132 _: &actions::FoldFunctionBodies,
13133 window: &mut Window,
13134 cx: &mut Context<Self>,
13135 ) {
13136 let snapshot = self.buffer.read(cx).snapshot(cx);
13137
13138 let ranges = snapshot
13139 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13140 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13141 .collect::<Vec<_>>();
13142
13143 let creases = ranges
13144 .into_iter()
13145 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13146 .collect();
13147
13148 self.fold_creases(creases, true, window, cx);
13149 }
13150
13151 pub fn fold_recursive(
13152 &mut self,
13153 _: &actions::FoldRecursive,
13154 window: &mut Window,
13155 cx: &mut Context<Self>,
13156 ) {
13157 let mut to_fold = Vec::new();
13158 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13159 let selections = self.selections.all_adjusted(cx);
13160
13161 for selection in selections {
13162 let range = selection.range().sorted();
13163 let buffer_start_row = range.start.row;
13164
13165 if range.start.row != range.end.row {
13166 let mut found = false;
13167 for row in range.start.row..=range.end.row {
13168 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13169 found = true;
13170 to_fold.push(crease);
13171 }
13172 }
13173 if found {
13174 continue;
13175 }
13176 }
13177
13178 for row in (0..=range.start.row).rev() {
13179 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13180 if crease.range().end.row >= buffer_start_row {
13181 to_fold.push(crease);
13182 } else {
13183 break;
13184 }
13185 }
13186 }
13187 }
13188
13189 self.fold_creases(to_fold, true, window, cx);
13190 }
13191
13192 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13193 let buffer_row = fold_at.buffer_row;
13194 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13195
13196 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13197 let autoscroll = self
13198 .selections
13199 .all::<Point>(cx)
13200 .iter()
13201 .any(|selection| crease.range().overlaps(&selection.range()));
13202
13203 self.fold_creases(vec![crease], autoscroll, window, cx);
13204 }
13205 }
13206
13207 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13208 if self.is_singleton(cx) {
13209 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13210 let buffer = &display_map.buffer_snapshot;
13211 let selections = self.selections.all::<Point>(cx);
13212 let ranges = selections
13213 .iter()
13214 .map(|s| {
13215 let range = s.display_range(&display_map).sorted();
13216 let mut start = range.start.to_point(&display_map);
13217 let mut end = range.end.to_point(&display_map);
13218 start.column = 0;
13219 end.column = buffer.line_len(MultiBufferRow(end.row));
13220 start..end
13221 })
13222 .collect::<Vec<_>>();
13223
13224 self.unfold_ranges(&ranges, true, true, cx);
13225 } else {
13226 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13227 let buffer_ids = self
13228 .selections
13229 .disjoint_anchor_ranges()
13230 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13231 .collect::<HashSet<_>>();
13232 for buffer_id in buffer_ids {
13233 self.unfold_buffer(buffer_id, cx);
13234 }
13235 }
13236 }
13237
13238 pub fn unfold_recursive(
13239 &mut self,
13240 _: &UnfoldRecursive,
13241 _window: &mut Window,
13242 cx: &mut Context<Self>,
13243 ) {
13244 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13245 let selections = self.selections.all::<Point>(cx);
13246 let ranges = selections
13247 .iter()
13248 .map(|s| {
13249 let mut range = s.display_range(&display_map).sorted();
13250 *range.start.column_mut() = 0;
13251 *range.end.column_mut() = display_map.line_len(range.end.row());
13252 let start = range.start.to_point(&display_map);
13253 let end = range.end.to_point(&display_map);
13254 start..end
13255 })
13256 .collect::<Vec<_>>();
13257
13258 self.unfold_ranges(&ranges, true, true, cx);
13259 }
13260
13261 pub fn unfold_at(
13262 &mut self,
13263 unfold_at: &UnfoldAt,
13264 _window: &mut Window,
13265 cx: &mut Context<Self>,
13266 ) {
13267 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13268
13269 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13270 ..Point::new(
13271 unfold_at.buffer_row.0,
13272 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13273 );
13274
13275 let autoscroll = self
13276 .selections
13277 .all::<Point>(cx)
13278 .iter()
13279 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13280
13281 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13282 }
13283
13284 pub fn unfold_all(
13285 &mut self,
13286 _: &actions::UnfoldAll,
13287 _window: &mut Window,
13288 cx: &mut Context<Self>,
13289 ) {
13290 if self.buffer.read(cx).is_singleton() {
13291 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13292 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13293 } else {
13294 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13295 editor
13296 .update(&mut cx, |editor, cx| {
13297 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13298 editor.unfold_buffer(buffer_id, cx);
13299 }
13300 })
13301 .ok();
13302 });
13303 }
13304 }
13305
13306 pub fn fold_selected_ranges(
13307 &mut self,
13308 _: &FoldSelectedRanges,
13309 window: &mut Window,
13310 cx: &mut Context<Self>,
13311 ) {
13312 let selections = self.selections.all::<Point>(cx);
13313 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13314 let line_mode = self.selections.line_mode;
13315 let ranges = selections
13316 .into_iter()
13317 .map(|s| {
13318 if line_mode {
13319 let start = Point::new(s.start.row, 0);
13320 let end = Point::new(
13321 s.end.row,
13322 display_map
13323 .buffer_snapshot
13324 .line_len(MultiBufferRow(s.end.row)),
13325 );
13326 Crease::simple(start..end, display_map.fold_placeholder.clone())
13327 } else {
13328 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13329 }
13330 })
13331 .collect::<Vec<_>>();
13332 self.fold_creases(ranges, true, window, cx);
13333 }
13334
13335 pub fn fold_ranges<T: ToOffset + Clone>(
13336 &mut self,
13337 ranges: Vec<Range<T>>,
13338 auto_scroll: bool,
13339 window: &mut Window,
13340 cx: &mut Context<Self>,
13341 ) {
13342 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13343 let ranges = ranges
13344 .into_iter()
13345 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13346 .collect::<Vec<_>>();
13347 self.fold_creases(ranges, auto_scroll, window, cx);
13348 }
13349
13350 pub fn fold_creases<T: ToOffset + Clone>(
13351 &mut self,
13352 creases: Vec<Crease<T>>,
13353 auto_scroll: bool,
13354 window: &mut Window,
13355 cx: &mut Context<Self>,
13356 ) {
13357 if creases.is_empty() {
13358 return;
13359 }
13360
13361 let mut buffers_affected = HashSet::default();
13362 let multi_buffer = self.buffer().read(cx);
13363 for crease in &creases {
13364 if let Some((_, buffer, _)) =
13365 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13366 {
13367 buffers_affected.insert(buffer.read(cx).remote_id());
13368 };
13369 }
13370
13371 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13372
13373 if auto_scroll {
13374 self.request_autoscroll(Autoscroll::fit(), cx);
13375 }
13376
13377 cx.notify();
13378
13379 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13380 // Clear diagnostics block when folding a range that contains it.
13381 let snapshot = self.snapshot(window, cx);
13382 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13383 drop(snapshot);
13384 self.active_diagnostics = Some(active_diagnostics);
13385 self.dismiss_diagnostics(cx);
13386 } else {
13387 self.active_diagnostics = Some(active_diagnostics);
13388 }
13389 }
13390
13391 self.scrollbar_marker_state.dirty = true;
13392 }
13393
13394 /// Removes any folds whose ranges intersect any of the given ranges.
13395 pub fn unfold_ranges<T: ToOffset + Clone>(
13396 &mut self,
13397 ranges: &[Range<T>],
13398 inclusive: bool,
13399 auto_scroll: bool,
13400 cx: &mut Context<Self>,
13401 ) {
13402 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13403 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13404 });
13405 }
13406
13407 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13408 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13409 return;
13410 }
13411 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13412 self.display_map.update(cx, |display_map, cx| {
13413 display_map.fold_buffers([buffer_id], cx)
13414 });
13415 cx.emit(EditorEvent::BufferFoldToggled {
13416 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13417 folded: true,
13418 });
13419 cx.notify();
13420 }
13421
13422 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13423 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13424 return;
13425 }
13426 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13427 self.display_map.update(cx, |display_map, cx| {
13428 display_map.unfold_buffers([buffer_id], cx);
13429 });
13430 cx.emit(EditorEvent::BufferFoldToggled {
13431 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13432 folded: false,
13433 });
13434 cx.notify();
13435 }
13436
13437 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13438 self.display_map.read(cx).is_buffer_folded(buffer)
13439 }
13440
13441 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13442 self.display_map.read(cx).folded_buffers()
13443 }
13444
13445 /// Removes any folds with the given ranges.
13446 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13447 &mut self,
13448 ranges: &[Range<T>],
13449 type_id: TypeId,
13450 auto_scroll: bool,
13451 cx: &mut Context<Self>,
13452 ) {
13453 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13454 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13455 });
13456 }
13457
13458 fn remove_folds_with<T: ToOffset + Clone>(
13459 &mut self,
13460 ranges: &[Range<T>],
13461 auto_scroll: bool,
13462 cx: &mut Context<Self>,
13463 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13464 ) {
13465 if ranges.is_empty() {
13466 return;
13467 }
13468
13469 let mut buffers_affected = HashSet::default();
13470 let multi_buffer = self.buffer().read(cx);
13471 for range in ranges {
13472 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13473 buffers_affected.insert(buffer.read(cx).remote_id());
13474 };
13475 }
13476
13477 self.display_map.update(cx, update);
13478
13479 if auto_scroll {
13480 self.request_autoscroll(Autoscroll::fit(), cx);
13481 }
13482
13483 cx.notify();
13484 self.scrollbar_marker_state.dirty = true;
13485 self.active_indent_guides_state.dirty = true;
13486 }
13487
13488 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13489 self.display_map.read(cx).fold_placeholder.clone()
13490 }
13491
13492 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13493 self.buffer.update(cx, |buffer, cx| {
13494 buffer.set_all_diff_hunks_expanded(cx);
13495 });
13496 }
13497
13498 pub fn expand_all_diff_hunks(
13499 &mut self,
13500 _: &ExpandAllDiffHunks,
13501 _window: &mut Window,
13502 cx: &mut Context<Self>,
13503 ) {
13504 self.buffer.update(cx, |buffer, cx| {
13505 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13506 });
13507 }
13508
13509 pub fn toggle_selected_diff_hunks(
13510 &mut self,
13511 _: &ToggleSelectedDiffHunks,
13512 _window: &mut Window,
13513 cx: &mut Context<Self>,
13514 ) {
13515 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13516 self.toggle_diff_hunks_in_ranges(ranges, cx);
13517 }
13518
13519 pub fn diff_hunks_in_ranges<'a>(
13520 &'a self,
13521 ranges: &'a [Range<Anchor>],
13522 buffer: &'a MultiBufferSnapshot,
13523 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13524 ranges.iter().flat_map(move |range| {
13525 let end_excerpt_id = range.end.excerpt_id;
13526 let range = range.to_point(buffer);
13527 let mut peek_end = range.end;
13528 if range.end.row < buffer.max_row().0 {
13529 peek_end = Point::new(range.end.row + 1, 0);
13530 }
13531 buffer
13532 .diff_hunks_in_range(range.start..peek_end)
13533 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13534 })
13535 }
13536
13537 pub fn has_stageable_diff_hunks_in_ranges(
13538 &self,
13539 ranges: &[Range<Anchor>],
13540 snapshot: &MultiBufferSnapshot,
13541 ) -> bool {
13542 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13543 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13544 }
13545
13546 pub fn toggle_staged_selected_diff_hunks(
13547 &mut self,
13548 _: &::git::ToggleStaged,
13549 window: &mut Window,
13550 cx: &mut Context<Self>,
13551 ) {
13552 let snapshot = self.buffer.read(cx).snapshot(cx);
13553 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13554 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13555 self.stage_or_unstage_diff_hunks(stage, &ranges, window, cx);
13556 }
13557
13558 pub fn stage_and_next(
13559 &mut self,
13560 action: &::git::StageAndNext,
13561 window: &mut Window,
13562 cx: &mut Context<Self>,
13563 ) {
13564 self.do_stage_or_unstage_and_next(true, action.whole_excerpt, window, cx);
13565 }
13566
13567 pub fn unstage_and_next(
13568 &mut self,
13569 action: &::git::UnstageAndNext,
13570 window: &mut Window,
13571 cx: &mut Context<Self>,
13572 ) {
13573 self.do_stage_or_unstage_and_next(false, action.whole_excerpt, window, cx);
13574 }
13575
13576 pub fn stage_or_unstage_diff_hunks(
13577 &mut self,
13578 stage: bool,
13579 ranges: &[Range<Anchor>],
13580 window: &mut Window,
13581 cx: &mut Context<Self>,
13582 ) {
13583 let snapshot = self.buffer.read(cx).snapshot(cx);
13584 let chunk_by = self
13585 .diff_hunks_in_ranges(&ranges, &snapshot)
13586 .chunk_by(|hunk| hunk.buffer_id);
13587 for (buffer_id, hunks) in &chunk_by {
13588 self.do_stage_or_unstage(stage, buffer_id, hunks, window, cx);
13589 }
13590 }
13591
13592 fn do_stage_or_unstage_and_next(
13593 &mut self,
13594 stage: bool,
13595 whole_excerpt: bool,
13596 window: &mut Window,
13597 cx: &mut Context<Self>,
13598 ) {
13599 let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13600
13601 if ranges.iter().any(|range| range.start != range.end) {
13602 self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13603 return;
13604 }
13605
13606 if !whole_excerpt {
13607 let snapshot = self.snapshot(window, cx);
13608 let newest_range = self.selections.newest::<Point>(cx).range();
13609
13610 let run_twice = snapshot
13611 .hunks_for_ranges([newest_range])
13612 .first()
13613 .is_some_and(|hunk| {
13614 let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13615 self.hunk_after_position(&snapshot, next_line)
13616 .is_some_and(|other| other.row_range == hunk.row_range)
13617 });
13618
13619 if run_twice {
13620 self.go_to_next_hunk(
13621 &GoToHunk {
13622 center_cursor: true,
13623 },
13624 window,
13625 cx,
13626 );
13627 }
13628 } else if !self.buffer().read(cx).is_singleton() {
13629 self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13630
13631 if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13632 if buffer.read(cx).is_empty() {
13633 let buffer = buffer.read(cx);
13634 let Some(file) = buffer.file() else {
13635 return;
13636 };
13637 let project_path = project::ProjectPath {
13638 worktree_id: file.worktree_id(cx),
13639 path: file.path().clone(),
13640 };
13641 let Some(project) = self.project.as_ref() else {
13642 return;
13643 };
13644
13645 let Some(repo) = project.read(cx).git_store().read(cx).active_repository()
13646 else {
13647 return;
13648 };
13649
13650 repo.update(cx, |repo, cx| {
13651 let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13652 return;
13653 };
13654 let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13655 return;
13656 };
13657 if stage && status.status == FileStatus::Untracked {
13658 repo.stage_entries(vec![repo_path], cx)
13659 .detach_and_log_err(cx);
13660 return;
13661 }
13662 })
13663 }
13664 ranges = vec![multi_buffer::Anchor::range_in_buffer(
13665 excerpt_id,
13666 buffer.read(cx).remote_id(),
13667 range,
13668 )];
13669 self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13670 let snapshot = self.buffer().read(cx).snapshot(cx);
13671 let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13672 if point.row < snapshot.max_row().0 {
13673 point.row += 1;
13674 point.column = 0;
13675 point = snapshot.clip_point(point, Bias::Right);
13676 self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13677 s.select_ranges([point..point]);
13678 });
13679 }
13680 return;
13681 }
13682 }
13683 self.stage_or_unstage_diff_hunks(stage, &ranges[..], window, cx);
13684 self.go_to_next_hunk(
13685 &GoToHunk {
13686 center_cursor: true,
13687 },
13688 window,
13689 cx,
13690 );
13691 }
13692
13693 fn do_stage_or_unstage(
13694 &self,
13695 stage: bool,
13696 buffer_id: BufferId,
13697 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13698 window: &mut Window,
13699 cx: &mut App,
13700 ) {
13701 let Some(project) = self.project.as_ref() else {
13702 return;
13703 };
13704 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13705 return;
13706 };
13707 let Some(diff) = self.buffer.read(cx).diff_for(buffer_id) else {
13708 return;
13709 };
13710 let buffer_snapshot = buffer.read(cx).snapshot();
13711 let file_exists = buffer_snapshot
13712 .file()
13713 .is_some_and(|file| file.disk_state().exists());
13714 let Some((repo, path)) = project
13715 .read(cx)
13716 .repository_and_path_for_buffer_id(buffer_id, cx)
13717 else {
13718 log::debug!("no git repo for buffer id");
13719 return;
13720 };
13721
13722 let new_index_text = diff.update(cx, |diff, cx| {
13723 diff.stage_or_unstage_hunks(
13724 stage,
13725 &hunks
13726 .map(|hunk| buffer_diff::DiffHunk {
13727 buffer_range: hunk.buffer_range,
13728 diff_base_byte_range: hunk.diff_base_byte_range,
13729 secondary_status: hunk.secondary_status,
13730 row_range: 0..0, // unused
13731 })
13732 .collect::<Vec<_>>(),
13733 &buffer_snapshot,
13734 file_exists,
13735 cx,
13736 )
13737 });
13738
13739 if file_exists {
13740 let buffer_store = project.read(cx).buffer_store().clone();
13741 buffer_store
13742 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13743 .detach_and_log_err(cx);
13744 }
13745
13746 let recv = repo
13747 .read(cx)
13748 .set_index_text(&path, new_index_text.map(|rope| rope.to_string()));
13749
13750 cx.background_spawn(async move { recv.await? })
13751 .detach_and_notify_err(window, cx);
13752 }
13753
13754 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13755 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13756 self.buffer
13757 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13758 }
13759
13760 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13761 self.buffer.update(cx, |buffer, cx| {
13762 let ranges = vec![Anchor::min()..Anchor::max()];
13763 if !buffer.all_diff_hunks_expanded()
13764 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13765 {
13766 buffer.collapse_diff_hunks(ranges, cx);
13767 true
13768 } else {
13769 false
13770 }
13771 })
13772 }
13773
13774 fn toggle_diff_hunks_in_ranges(
13775 &mut self,
13776 ranges: Vec<Range<Anchor>>,
13777 cx: &mut Context<'_, Editor>,
13778 ) {
13779 self.buffer.update(cx, |buffer, cx| {
13780 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13781 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13782 })
13783 }
13784
13785 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13786 self.buffer.update(cx, |buffer, cx| {
13787 let snapshot = buffer.snapshot(cx);
13788 let excerpt_id = range.end.excerpt_id;
13789 let point_range = range.to_point(&snapshot);
13790 let expand = !buffer.single_hunk_is_expanded(range, cx);
13791 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13792 })
13793 }
13794
13795 pub(crate) fn apply_all_diff_hunks(
13796 &mut self,
13797 _: &ApplyAllDiffHunks,
13798 window: &mut Window,
13799 cx: &mut Context<Self>,
13800 ) {
13801 let buffers = self.buffer.read(cx).all_buffers();
13802 for branch_buffer in buffers {
13803 branch_buffer.update(cx, |branch_buffer, cx| {
13804 branch_buffer.merge_into_base(Vec::new(), cx);
13805 });
13806 }
13807
13808 if let Some(project) = self.project.clone() {
13809 self.save(true, project, window, cx).detach_and_log_err(cx);
13810 }
13811 }
13812
13813 pub(crate) fn apply_selected_diff_hunks(
13814 &mut self,
13815 _: &ApplyDiffHunk,
13816 window: &mut Window,
13817 cx: &mut Context<Self>,
13818 ) {
13819 let snapshot = self.snapshot(window, cx);
13820 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13821 let mut ranges_by_buffer = HashMap::default();
13822 self.transact(window, cx, |editor, _window, cx| {
13823 for hunk in hunks {
13824 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13825 ranges_by_buffer
13826 .entry(buffer.clone())
13827 .or_insert_with(Vec::new)
13828 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13829 }
13830 }
13831
13832 for (buffer, ranges) in ranges_by_buffer {
13833 buffer.update(cx, |buffer, cx| {
13834 buffer.merge_into_base(ranges, cx);
13835 });
13836 }
13837 });
13838
13839 if let Some(project) = self.project.clone() {
13840 self.save(true, project, window, cx).detach_and_log_err(cx);
13841 }
13842 }
13843
13844 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13845 if hovered != self.gutter_hovered {
13846 self.gutter_hovered = hovered;
13847 cx.notify();
13848 }
13849 }
13850
13851 pub fn insert_blocks(
13852 &mut self,
13853 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13854 autoscroll: Option<Autoscroll>,
13855 cx: &mut Context<Self>,
13856 ) -> Vec<CustomBlockId> {
13857 let blocks = self
13858 .display_map
13859 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13860 if let Some(autoscroll) = autoscroll {
13861 self.request_autoscroll(autoscroll, cx);
13862 }
13863 cx.notify();
13864 blocks
13865 }
13866
13867 pub fn resize_blocks(
13868 &mut self,
13869 heights: HashMap<CustomBlockId, u32>,
13870 autoscroll: Option<Autoscroll>,
13871 cx: &mut Context<Self>,
13872 ) {
13873 self.display_map
13874 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13875 if let Some(autoscroll) = autoscroll {
13876 self.request_autoscroll(autoscroll, cx);
13877 }
13878 cx.notify();
13879 }
13880
13881 pub fn replace_blocks(
13882 &mut self,
13883 renderers: HashMap<CustomBlockId, RenderBlock>,
13884 autoscroll: Option<Autoscroll>,
13885 cx: &mut Context<Self>,
13886 ) {
13887 self.display_map
13888 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13889 if let Some(autoscroll) = autoscroll {
13890 self.request_autoscroll(autoscroll, cx);
13891 }
13892 cx.notify();
13893 }
13894
13895 pub fn remove_blocks(
13896 &mut self,
13897 block_ids: HashSet<CustomBlockId>,
13898 autoscroll: Option<Autoscroll>,
13899 cx: &mut Context<Self>,
13900 ) {
13901 self.display_map.update(cx, |display_map, cx| {
13902 display_map.remove_blocks(block_ids, cx)
13903 });
13904 if let Some(autoscroll) = autoscroll {
13905 self.request_autoscroll(autoscroll, cx);
13906 }
13907 cx.notify();
13908 }
13909
13910 pub fn row_for_block(
13911 &self,
13912 block_id: CustomBlockId,
13913 cx: &mut Context<Self>,
13914 ) -> Option<DisplayRow> {
13915 self.display_map
13916 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13917 }
13918
13919 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13920 self.focused_block = Some(focused_block);
13921 }
13922
13923 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13924 self.focused_block.take()
13925 }
13926
13927 pub fn insert_creases(
13928 &mut self,
13929 creases: impl IntoIterator<Item = Crease<Anchor>>,
13930 cx: &mut Context<Self>,
13931 ) -> Vec<CreaseId> {
13932 self.display_map
13933 .update(cx, |map, cx| map.insert_creases(creases, cx))
13934 }
13935
13936 pub fn remove_creases(
13937 &mut self,
13938 ids: impl IntoIterator<Item = CreaseId>,
13939 cx: &mut Context<Self>,
13940 ) {
13941 self.display_map
13942 .update(cx, |map, cx| map.remove_creases(ids, cx));
13943 }
13944
13945 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13946 self.display_map
13947 .update(cx, |map, cx| map.snapshot(cx))
13948 .longest_row()
13949 }
13950
13951 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13952 self.display_map
13953 .update(cx, |map, cx| map.snapshot(cx))
13954 .max_point()
13955 }
13956
13957 pub fn text(&self, cx: &App) -> String {
13958 self.buffer.read(cx).read(cx).text()
13959 }
13960
13961 pub fn is_empty(&self, cx: &App) -> bool {
13962 self.buffer.read(cx).read(cx).is_empty()
13963 }
13964
13965 pub fn text_option(&self, cx: &App) -> Option<String> {
13966 let text = self.text(cx);
13967 let text = text.trim();
13968
13969 if text.is_empty() {
13970 return None;
13971 }
13972
13973 Some(text.to_string())
13974 }
13975
13976 pub fn set_text(
13977 &mut self,
13978 text: impl Into<Arc<str>>,
13979 window: &mut Window,
13980 cx: &mut Context<Self>,
13981 ) {
13982 self.transact(window, cx, |this, _, cx| {
13983 this.buffer
13984 .read(cx)
13985 .as_singleton()
13986 .expect("you can only call set_text on editors for singleton buffers")
13987 .update(cx, |buffer, cx| buffer.set_text(text, cx));
13988 });
13989 }
13990
13991 pub fn display_text(&self, cx: &mut App) -> String {
13992 self.display_map
13993 .update(cx, |map, cx| map.snapshot(cx))
13994 .text()
13995 }
13996
13997 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13998 let mut wrap_guides = smallvec::smallvec![];
13999
14000 if self.show_wrap_guides == Some(false) {
14001 return wrap_guides;
14002 }
14003
14004 let settings = self.buffer.read(cx).settings_at(0, cx);
14005 if settings.show_wrap_guides {
14006 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
14007 wrap_guides.push((soft_wrap as usize, true));
14008 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
14009 wrap_guides.push((soft_wrap as usize, true));
14010 }
14011 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14012 }
14013
14014 wrap_guides
14015 }
14016
14017 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14018 let settings = self.buffer.read(cx).settings_at(0, cx);
14019 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14020 match mode {
14021 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14022 SoftWrap::None
14023 }
14024 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14025 language_settings::SoftWrap::PreferredLineLength => {
14026 SoftWrap::Column(settings.preferred_line_length)
14027 }
14028 language_settings::SoftWrap::Bounded => {
14029 SoftWrap::Bounded(settings.preferred_line_length)
14030 }
14031 }
14032 }
14033
14034 pub fn set_soft_wrap_mode(
14035 &mut self,
14036 mode: language_settings::SoftWrap,
14037
14038 cx: &mut Context<Self>,
14039 ) {
14040 self.soft_wrap_mode_override = Some(mode);
14041 cx.notify();
14042 }
14043
14044 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14045 self.text_style_refinement = Some(style);
14046 }
14047
14048 /// called by the Element so we know what style we were most recently rendered with.
14049 pub(crate) fn set_style(
14050 &mut self,
14051 style: EditorStyle,
14052 window: &mut Window,
14053 cx: &mut Context<Self>,
14054 ) {
14055 let rem_size = window.rem_size();
14056 self.display_map.update(cx, |map, cx| {
14057 map.set_font(
14058 style.text.font(),
14059 style.text.font_size.to_pixels(rem_size),
14060 cx,
14061 )
14062 });
14063 self.style = Some(style);
14064 }
14065
14066 pub fn style(&self) -> Option<&EditorStyle> {
14067 self.style.as_ref()
14068 }
14069
14070 // Called by the element. This method is not designed to be called outside of the editor
14071 // element's layout code because it does not notify when rewrapping is computed synchronously.
14072 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14073 self.display_map
14074 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14075 }
14076
14077 pub fn set_soft_wrap(&mut self) {
14078 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14079 }
14080
14081 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14082 if self.soft_wrap_mode_override.is_some() {
14083 self.soft_wrap_mode_override.take();
14084 } else {
14085 let soft_wrap = match self.soft_wrap_mode(cx) {
14086 SoftWrap::GitDiff => return,
14087 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14088 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14089 language_settings::SoftWrap::None
14090 }
14091 };
14092 self.soft_wrap_mode_override = Some(soft_wrap);
14093 }
14094 cx.notify();
14095 }
14096
14097 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14098 let Some(workspace) = self.workspace() else {
14099 return;
14100 };
14101 let fs = workspace.read(cx).app_state().fs.clone();
14102 let current_show = TabBarSettings::get_global(cx).show;
14103 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14104 setting.show = Some(!current_show);
14105 });
14106 }
14107
14108 pub fn toggle_indent_guides(
14109 &mut self,
14110 _: &ToggleIndentGuides,
14111 _: &mut Window,
14112 cx: &mut Context<Self>,
14113 ) {
14114 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14115 self.buffer
14116 .read(cx)
14117 .settings_at(0, cx)
14118 .indent_guides
14119 .enabled
14120 });
14121 self.show_indent_guides = Some(!currently_enabled);
14122 cx.notify();
14123 }
14124
14125 fn should_show_indent_guides(&self) -> Option<bool> {
14126 self.show_indent_guides
14127 }
14128
14129 pub fn toggle_line_numbers(
14130 &mut self,
14131 _: &ToggleLineNumbers,
14132 _: &mut Window,
14133 cx: &mut Context<Self>,
14134 ) {
14135 let mut editor_settings = EditorSettings::get_global(cx).clone();
14136 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14137 EditorSettings::override_global(editor_settings, cx);
14138 }
14139
14140 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14141 self.use_relative_line_numbers
14142 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14143 }
14144
14145 pub fn toggle_relative_line_numbers(
14146 &mut self,
14147 _: &ToggleRelativeLineNumbers,
14148 _: &mut Window,
14149 cx: &mut Context<Self>,
14150 ) {
14151 let is_relative = self.should_use_relative_line_numbers(cx);
14152 self.set_relative_line_number(Some(!is_relative), cx)
14153 }
14154
14155 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14156 self.use_relative_line_numbers = is_relative;
14157 cx.notify();
14158 }
14159
14160 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14161 self.show_gutter = show_gutter;
14162 cx.notify();
14163 }
14164
14165 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14166 self.show_scrollbars = show_scrollbars;
14167 cx.notify();
14168 }
14169
14170 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14171 self.show_line_numbers = Some(show_line_numbers);
14172 cx.notify();
14173 }
14174
14175 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14176 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14177 cx.notify();
14178 }
14179
14180 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14181 self.show_code_actions = Some(show_code_actions);
14182 cx.notify();
14183 }
14184
14185 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14186 self.show_runnables = Some(show_runnables);
14187 cx.notify();
14188 }
14189
14190 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14191 if self.display_map.read(cx).masked != masked {
14192 self.display_map.update(cx, |map, _| map.masked = masked);
14193 }
14194 cx.notify()
14195 }
14196
14197 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14198 self.show_wrap_guides = Some(show_wrap_guides);
14199 cx.notify();
14200 }
14201
14202 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14203 self.show_indent_guides = Some(show_indent_guides);
14204 cx.notify();
14205 }
14206
14207 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14208 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14209 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14210 if let Some(dir) = file.abs_path(cx).parent() {
14211 return Some(dir.to_owned());
14212 }
14213 }
14214
14215 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14216 return Some(project_path.path.to_path_buf());
14217 }
14218 }
14219
14220 None
14221 }
14222
14223 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14224 self.active_excerpt(cx)?
14225 .1
14226 .read(cx)
14227 .file()
14228 .and_then(|f| f.as_local())
14229 }
14230
14231 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14232 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14233 let buffer = buffer.read(cx);
14234 if let Some(project_path) = buffer.project_path(cx) {
14235 let project = self.project.as_ref()?.read(cx);
14236 project.absolute_path(&project_path, cx)
14237 } else {
14238 buffer
14239 .file()
14240 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14241 }
14242 })
14243 }
14244
14245 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14246 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14247 let project_path = buffer.read(cx).project_path(cx)?;
14248 let project = self.project.as_ref()?.read(cx);
14249 let entry = project.entry_for_path(&project_path, cx)?;
14250 let path = entry.path.to_path_buf();
14251 Some(path)
14252 })
14253 }
14254
14255 pub fn reveal_in_finder(
14256 &mut self,
14257 _: &RevealInFileManager,
14258 _window: &mut Window,
14259 cx: &mut Context<Self>,
14260 ) {
14261 if let Some(target) = self.target_file(cx) {
14262 cx.reveal_path(&target.abs_path(cx));
14263 }
14264 }
14265
14266 pub fn copy_path(
14267 &mut self,
14268 _: &zed_actions::workspace::CopyPath,
14269 _window: &mut Window,
14270 cx: &mut Context<Self>,
14271 ) {
14272 if let Some(path) = self.target_file_abs_path(cx) {
14273 if let Some(path) = path.to_str() {
14274 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14275 }
14276 }
14277 }
14278
14279 pub fn copy_relative_path(
14280 &mut self,
14281 _: &zed_actions::workspace::CopyRelativePath,
14282 _window: &mut Window,
14283 cx: &mut Context<Self>,
14284 ) {
14285 if let Some(path) = self.target_file_path(cx) {
14286 if let Some(path) = path.to_str() {
14287 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14288 }
14289 }
14290 }
14291
14292 pub fn copy_file_name_without_extension(
14293 &mut self,
14294 _: &CopyFileNameWithoutExtension,
14295 _: &mut Window,
14296 cx: &mut Context<Self>,
14297 ) {
14298 if let Some(file) = self.target_file(cx) {
14299 if let Some(file_stem) = file.path().file_stem() {
14300 if let Some(name) = file_stem.to_str() {
14301 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14302 }
14303 }
14304 }
14305 }
14306
14307 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14308 if let Some(file) = self.target_file(cx) {
14309 if let Some(file_name) = file.path().file_name() {
14310 if let Some(name) = file_name.to_str() {
14311 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14312 }
14313 }
14314 }
14315 }
14316
14317 pub fn toggle_git_blame(
14318 &mut self,
14319 _: &ToggleGitBlame,
14320 window: &mut Window,
14321 cx: &mut Context<Self>,
14322 ) {
14323 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14324
14325 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14326 self.start_git_blame(true, window, cx);
14327 }
14328
14329 cx.notify();
14330 }
14331
14332 pub fn toggle_git_blame_inline(
14333 &mut self,
14334 _: &ToggleGitBlameInline,
14335 window: &mut Window,
14336 cx: &mut Context<Self>,
14337 ) {
14338 self.toggle_git_blame_inline_internal(true, window, cx);
14339 cx.notify();
14340 }
14341
14342 pub fn git_blame_inline_enabled(&self) -> bool {
14343 self.git_blame_inline_enabled
14344 }
14345
14346 pub fn toggle_selection_menu(
14347 &mut self,
14348 _: &ToggleSelectionMenu,
14349 _: &mut Window,
14350 cx: &mut Context<Self>,
14351 ) {
14352 self.show_selection_menu = self
14353 .show_selection_menu
14354 .map(|show_selections_menu| !show_selections_menu)
14355 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14356
14357 cx.notify();
14358 }
14359
14360 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14361 self.show_selection_menu
14362 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14363 }
14364
14365 fn start_git_blame(
14366 &mut self,
14367 user_triggered: bool,
14368 window: &mut Window,
14369 cx: &mut Context<Self>,
14370 ) {
14371 if let Some(project) = self.project.as_ref() {
14372 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14373 return;
14374 };
14375
14376 if buffer.read(cx).file().is_none() {
14377 return;
14378 }
14379
14380 let focused = self.focus_handle(cx).contains_focused(window, cx);
14381
14382 let project = project.clone();
14383 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14384 self.blame_subscription =
14385 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14386 self.blame = Some(blame);
14387 }
14388 }
14389
14390 fn toggle_git_blame_inline_internal(
14391 &mut self,
14392 user_triggered: bool,
14393 window: &mut Window,
14394 cx: &mut Context<Self>,
14395 ) {
14396 if self.git_blame_inline_enabled {
14397 self.git_blame_inline_enabled = false;
14398 self.show_git_blame_inline = false;
14399 self.show_git_blame_inline_delay_task.take();
14400 } else {
14401 self.git_blame_inline_enabled = true;
14402 self.start_git_blame_inline(user_triggered, window, cx);
14403 }
14404
14405 cx.notify();
14406 }
14407
14408 fn start_git_blame_inline(
14409 &mut self,
14410 user_triggered: bool,
14411 window: &mut Window,
14412 cx: &mut Context<Self>,
14413 ) {
14414 self.start_git_blame(user_triggered, window, cx);
14415
14416 if ProjectSettings::get_global(cx)
14417 .git
14418 .inline_blame_delay()
14419 .is_some()
14420 {
14421 self.start_inline_blame_timer(window, cx);
14422 } else {
14423 self.show_git_blame_inline = true
14424 }
14425 }
14426
14427 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14428 self.blame.as_ref()
14429 }
14430
14431 pub fn show_git_blame_gutter(&self) -> bool {
14432 self.show_git_blame_gutter
14433 }
14434
14435 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14436 self.show_git_blame_gutter && self.has_blame_entries(cx)
14437 }
14438
14439 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14440 self.show_git_blame_inline
14441 && (self.focus_handle.is_focused(window)
14442 || self
14443 .git_blame_inline_tooltip
14444 .as_ref()
14445 .and_then(|t| t.upgrade())
14446 .is_some())
14447 && !self.newest_selection_head_on_empty_line(cx)
14448 && self.has_blame_entries(cx)
14449 }
14450
14451 fn has_blame_entries(&self, cx: &App) -> bool {
14452 self.blame()
14453 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14454 }
14455
14456 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14457 let cursor_anchor = self.selections.newest_anchor().head();
14458
14459 let snapshot = self.buffer.read(cx).snapshot(cx);
14460 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14461
14462 snapshot.line_len(buffer_row) == 0
14463 }
14464
14465 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14466 let buffer_and_selection = maybe!({
14467 let selection = self.selections.newest::<Point>(cx);
14468 let selection_range = selection.range();
14469
14470 let multi_buffer = self.buffer().read(cx);
14471 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14472 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14473
14474 let (buffer, range, _) = if selection.reversed {
14475 buffer_ranges.first()
14476 } else {
14477 buffer_ranges.last()
14478 }?;
14479
14480 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14481 ..text::ToPoint::to_point(&range.end, &buffer).row;
14482 Some((
14483 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14484 selection,
14485 ))
14486 });
14487
14488 let Some((buffer, selection)) = buffer_and_selection else {
14489 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14490 };
14491
14492 let Some(project) = self.project.as_ref() else {
14493 return Task::ready(Err(anyhow!("editor does not have project")));
14494 };
14495
14496 project.update(cx, |project, cx| {
14497 project.get_permalink_to_line(&buffer, selection, cx)
14498 })
14499 }
14500
14501 pub fn copy_permalink_to_line(
14502 &mut self,
14503 _: &CopyPermalinkToLine,
14504 window: &mut Window,
14505 cx: &mut Context<Self>,
14506 ) {
14507 let permalink_task = self.get_permalink_to_line(cx);
14508 let workspace = self.workspace();
14509
14510 cx.spawn_in(window, |_, mut cx| async move {
14511 match permalink_task.await {
14512 Ok(permalink) => {
14513 cx.update(|_, cx| {
14514 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14515 })
14516 .ok();
14517 }
14518 Err(err) => {
14519 let message = format!("Failed to copy permalink: {err}");
14520
14521 Err::<(), anyhow::Error>(err).log_err();
14522
14523 if let Some(workspace) = workspace {
14524 workspace
14525 .update_in(&mut cx, |workspace, _, cx| {
14526 struct CopyPermalinkToLine;
14527
14528 workspace.show_toast(
14529 Toast::new(
14530 NotificationId::unique::<CopyPermalinkToLine>(),
14531 message,
14532 ),
14533 cx,
14534 )
14535 })
14536 .ok();
14537 }
14538 }
14539 }
14540 })
14541 .detach();
14542 }
14543
14544 pub fn copy_file_location(
14545 &mut self,
14546 _: &CopyFileLocation,
14547 _: &mut Window,
14548 cx: &mut Context<Self>,
14549 ) {
14550 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14551 if let Some(file) = self.target_file(cx) {
14552 if let Some(path) = file.path().to_str() {
14553 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14554 }
14555 }
14556 }
14557
14558 pub fn open_permalink_to_line(
14559 &mut self,
14560 _: &OpenPermalinkToLine,
14561 window: &mut Window,
14562 cx: &mut Context<Self>,
14563 ) {
14564 let permalink_task = self.get_permalink_to_line(cx);
14565 let workspace = self.workspace();
14566
14567 cx.spawn_in(window, |_, mut cx| async move {
14568 match permalink_task.await {
14569 Ok(permalink) => {
14570 cx.update(|_, cx| {
14571 cx.open_url(permalink.as_ref());
14572 })
14573 .ok();
14574 }
14575 Err(err) => {
14576 let message = format!("Failed to open permalink: {err}");
14577
14578 Err::<(), anyhow::Error>(err).log_err();
14579
14580 if let Some(workspace) = workspace {
14581 workspace
14582 .update(&mut cx, |workspace, cx| {
14583 struct OpenPermalinkToLine;
14584
14585 workspace.show_toast(
14586 Toast::new(
14587 NotificationId::unique::<OpenPermalinkToLine>(),
14588 message,
14589 ),
14590 cx,
14591 )
14592 })
14593 .ok();
14594 }
14595 }
14596 }
14597 })
14598 .detach();
14599 }
14600
14601 pub fn insert_uuid_v4(
14602 &mut self,
14603 _: &InsertUuidV4,
14604 window: &mut Window,
14605 cx: &mut Context<Self>,
14606 ) {
14607 self.insert_uuid(UuidVersion::V4, window, cx);
14608 }
14609
14610 pub fn insert_uuid_v7(
14611 &mut self,
14612 _: &InsertUuidV7,
14613 window: &mut Window,
14614 cx: &mut Context<Self>,
14615 ) {
14616 self.insert_uuid(UuidVersion::V7, window, cx);
14617 }
14618
14619 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14620 self.transact(window, cx, |this, window, cx| {
14621 let edits = this
14622 .selections
14623 .all::<Point>(cx)
14624 .into_iter()
14625 .map(|selection| {
14626 let uuid = match version {
14627 UuidVersion::V4 => uuid::Uuid::new_v4(),
14628 UuidVersion::V7 => uuid::Uuid::now_v7(),
14629 };
14630
14631 (selection.range(), uuid.to_string())
14632 });
14633 this.edit(edits, cx);
14634 this.refresh_inline_completion(true, false, window, cx);
14635 });
14636 }
14637
14638 pub fn open_selections_in_multibuffer(
14639 &mut self,
14640 _: &OpenSelectionsInMultibuffer,
14641 window: &mut Window,
14642 cx: &mut Context<Self>,
14643 ) {
14644 let multibuffer = self.buffer.read(cx);
14645
14646 let Some(buffer) = multibuffer.as_singleton() else {
14647 return;
14648 };
14649
14650 let Some(workspace) = self.workspace() else {
14651 return;
14652 };
14653
14654 let locations = self
14655 .selections
14656 .disjoint_anchors()
14657 .iter()
14658 .map(|range| Location {
14659 buffer: buffer.clone(),
14660 range: range.start.text_anchor..range.end.text_anchor,
14661 })
14662 .collect::<Vec<_>>();
14663
14664 let title = multibuffer.title(cx).to_string();
14665
14666 cx.spawn_in(window, |_, mut cx| async move {
14667 workspace.update_in(&mut cx, |workspace, window, cx| {
14668 Self::open_locations_in_multibuffer(
14669 workspace,
14670 locations,
14671 format!("Selections for '{title}'"),
14672 false,
14673 MultibufferSelectionMode::All,
14674 window,
14675 cx,
14676 );
14677 })
14678 })
14679 .detach();
14680 }
14681
14682 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14683 /// last highlight added will be used.
14684 ///
14685 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14686 pub fn highlight_rows<T: 'static>(
14687 &mut self,
14688 range: Range<Anchor>,
14689 color: Hsla,
14690 should_autoscroll: bool,
14691 cx: &mut Context<Self>,
14692 ) {
14693 let snapshot = self.buffer().read(cx).snapshot(cx);
14694 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14695 let ix = row_highlights.binary_search_by(|highlight| {
14696 Ordering::Equal
14697 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14698 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14699 });
14700
14701 if let Err(mut ix) = ix {
14702 let index = post_inc(&mut self.highlight_order);
14703
14704 // If this range intersects with the preceding highlight, then merge it with
14705 // the preceding highlight. Otherwise insert a new highlight.
14706 let mut merged = false;
14707 if ix > 0 {
14708 let prev_highlight = &mut row_highlights[ix - 1];
14709 if prev_highlight
14710 .range
14711 .end
14712 .cmp(&range.start, &snapshot)
14713 .is_ge()
14714 {
14715 ix -= 1;
14716 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14717 prev_highlight.range.end = range.end;
14718 }
14719 merged = true;
14720 prev_highlight.index = index;
14721 prev_highlight.color = color;
14722 prev_highlight.should_autoscroll = should_autoscroll;
14723 }
14724 }
14725
14726 if !merged {
14727 row_highlights.insert(
14728 ix,
14729 RowHighlight {
14730 range: range.clone(),
14731 index,
14732 color,
14733 should_autoscroll,
14734 },
14735 );
14736 }
14737
14738 // If any of the following highlights intersect with this one, merge them.
14739 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14740 let highlight = &row_highlights[ix];
14741 if next_highlight
14742 .range
14743 .start
14744 .cmp(&highlight.range.end, &snapshot)
14745 .is_le()
14746 {
14747 if next_highlight
14748 .range
14749 .end
14750 .cmp(&highlight.range.end, &snapshot)
14751 .is_gt()
14752 {
14753 row_highlights[ix].range.end = next_highlight.range.end;
14754 }
14755 row_highlights.remove(ix + 1);
14756 } else {
14757 break;
14758 }
14759 }
14760 }
14761 }
14762
14763 /// Remove any highlighted row ranges of the given type that intersect the
14764 /// given ranges.
14765 pub fn remove_highlighted_rows<T: 'static>(
14766 &mut self,
14767 ranges_to_remove: Vec<Range<Anchor>>,
14768 cx: &mut Context<Self>,
14769 ) {
14770 let snapshot = self.buffer().read(cx).snapshot(cx);
14771 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14772 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14773 row_highlights.retain(|highlight| {
14774 while let Some(range_to_remove) = ranges_to_remove.peek() {
14775 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14776 Ordering::Less | Ordering::Equal => {
14777 ranges_to_remove.next();
14778 }
14779 Ordering::Greater => {
14780 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14781 Ordering::Less | Ordering::Equal => {
14782 return false;
14783 }
14784 Ordering::Greater => break,
14785 }
14786 }
14787 }
14788 }
14789
14790 true
14791 })
14792 }
14793
14794 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14795 pub fn clear_row_highlights<T: 'static>(&mut self) {
14796 self.highlighted_rows.remove(&TypeId::of::<T>());
14797 }
14798
14799 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14800 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14801 self.highlighted_rows
14802 .get(&TypeId::of::<T>())
14803 .map_or(&[] as &[_], |vec| vec.as_slice())
14804 .iter()
14805 .map(|highlight| (highlight.range.clone(), highlight.color))
14806 }
14807
14808 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14809 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14810 /// Allows to ignore certain kinds of highlights.
14811 pub fn highlighted_display_rows(
14812 &self,
14813 window: &mut Window,
14814 cx: &mut App,
14815 ) -> BTreeMap<DisplayRow, Background> {
14816 let snapshot = self.snapshot(window, cx);
14817 let mut used_highlight_orders = HashMap::default();
14818 self.highlighted_rows
14819 .iter()
14820 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14821 .fold(
14822 BTreeMap::<DisplayRow, Background>::new(),
14823 |mut unique_rows, highlight| {
14824 let start = highlight.range.start.to_display_point(&snapshot);
14825 let end = highlight.range.end.to_display_point(&snapshot);
14826 let start_row = start.row().0;
14827 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14828 && end.column() == 0
14829 {
14830 end.row().0.saturating_sub(1)
14831 } else {
14832 end.row().0
14833 };
14834 for row in start_row..=end_row {
14835 let used_index =
14836 used_highlight_orders.entry(row).or_insert(highlight.index);
14837 if highlight.index >= *used_index {
14838 *used_index = highlight.index;
14839 unique_rows.insert(DisplayRow(row), highlight.color.into());
14840 }
14841 }
14842 unique_rows
14843 },
14844 )
14845 }
14846
14847 pub fn highlighted_display_row_for_autoscroll(
14848 &self,
14849 snapshot: &DisplaySnapshot,
14850 ) -> Option<DisplayRow> {
14851 self.highlighted_rows
14852 .values()
14853 .flat_map(|highlighted_rows| highlighted_rows.iter())
14854 .filter_map(|highlight| {
14855 if highlight.should_autoscroll {
14856 Some(highlight.range.start.to_display_point(snapshot).row())
14857 } else {
14858 None
14859 }
14860 })
14861 .min()
14862 }
14863
14864 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14865 self.highlight_background::<SearchWithinRange>(
14866 ranges,
14867 |colors| colors.editor_document_highlight_read_background,
14868 cx,
14869 )
14870 }
14871
14872 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14873 self.breadcrumb_header = Some(new_header);
14874 }
14875
14876 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14877 self.clear_background_highlights::<SearchWithinRange>(cx);
14878 }
14879
14880 pub fn highlight_background<T: 'static>(
14881 &mut self,
14882 ranges: &[Range<Anchor>],
14883 color_fetcher: fn(&ThemeColors) -> Hsla,
14884 cx: &mut Context<Self>,
14885 ) {
14886 self.background_highlights
14887 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14888 self.scrollbar_marker_state.dirty = true;
14889 cx.notify();
14890 }
14891
14892 pub fn clear_background_highlights<T: 'static>(
14893 &mut self,
14894 cx: &mut Context<Self>,
14895 ) -> Option<BackgroundHighlight> {
14896 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14897 if !text_highlights.1.is_empty() {
14898 self.scrollbar_marker_state.dirty = true;
14899 cx.notify();
14900 }
14901 Some(text_highlights)
14902 }
14903
14904 pub fn highlight_gutter<T: 'static>(
14905 &mut self,
14906 ranges: &[Range<Anchor>],
14907 color_fetcher: fn(&App) -> Hsla,
14908 cx: &mut Context<Self>,
14909 ) {
14910 self.gutter_highlights
14911 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14912 cx.notify();
14913 }
14914
14915 pub fn clear_gutter_highlights<T: 'static>(
14916 &mut self,
14917 cx: &mut Context<Self>,
14918 ) -> Option<GutterHighlight> {
14919 cx.notify();
14920 self.gutter_highlights.remove(&TypeId::of::<T>())
14921 }
14922
14923 #[cfg(feature = "test-support")]
14924 pub fn all_text_background_highlights(
14925 &self,
14926 window: &mut Window,
14927 cx: &mut Context<Self>,
14928 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14929 let snapshot = self.snapshot(window, cx);
14930 let buffer = &snapshot.buffer_snapshot;
14931 let start = buffer.anchor_before(0);
14932 let end = buffer.anchor_after(buffer.len());
14933 let theme = cx.theme().colors();
14934 self.background_highlights_in_range(start..end, &snapshot, theme)
14935 }
14936
14937 #[cfg(feature = "test-support")]
14938 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14939 let snapshot = self.buffer().read(cx).snapshot(cx);
14940
14941 let highlights = self
14942 .background_highlights
14943 .get(&TypeId::of::<items::BufferSearchHighlights>());
14944
14945 if let Some((_color, ranges)) = highlights {
14946 ranges
14947 .iter()
14948 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14949 .collect_vec()
14950 } else {
14951 vec![]
14952 }
14953 }
14954
14955 fn document_highlights_for_position<'a>(
14956 &'a self,
14957 position: Anchor,
14958 buffer: &'a MultiBufferSnapshot,
14959 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14960 let read_highlights = self
14961 .background_highlights
14962 .get(&TypeId::of::<DocumentHighlightRead>())
14963 .map(|h| &h.1);
14964 let write_highlights = self
14965 .background_highlights
14966 .get(&TypeId::of::<DocumentHighlightWrite>())
14967 .map(|h| &h.1);
14968 let left_position = position.bias_left(buffer);
14969 let right_position = position.bias_right(buffer);
14970 read_highlights
14971 .into_iter()
14972 .chain(write_highlights)
14973 .flat_map(move |ranges| {
14974 let start_ix = match ranges.binary_search_by(|probe| {
14975 let cmp = probe.end.cmp(&left_position, buffer);
14976 if cmp.is_ge() {
14977 Ordering::Greater
14978 } else {
14979 Ordering::Less
14980 }
14981 }) {
14982 Ok(i) | Err(i) => i,
14983 };
14984
14985 ranges[start_ix..]
14986 .iter()
14987 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14988 })
14989 }
14990
14991 pub fn has_background_highlights<T: 'static>(&self) -> bool {
14992 self.background_highlights
14993 .get(&TypeId::of::<T>())
14994 .map_or(false, |(_, highlights)| !highlights.is_empty())
14995 }
14996
14997 pub fn background_highlights_in_range(
14998 &self,
14999 search_range: Range<Anchor>,
15000 display_snapshot: &DisplaySnapshot,
15001 theme: &ThemeColors,
15002 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15003 let mut results = Vec::new();
15004 for (color_fetcher, ranges) in self.background_highlights.values() {
15005 let color = color_fetcher(theme);
15006 let start_ix = match ranges.binary_search_by(|probe| {
15007 let cmp = probe
15008 .end
15009 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15010 if cmp.is_gt() {
15011 Ordering::Greater
15012 } else {
15013 Ordering::Less
15014 }
15015 }) {
15016 Ok(i) | Err(i) => i,
15017 };
15018 for range in &ranges[start_ix..] {
15019 if range
15020 .start
15021 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15022 .is_ge()
15023 {
15024 break;
15025 }
15026
15027 let start = range.start.to_display_point(display_snapshot);
15028 let end = range.end.to_display_point(display_snapshot);
15029 results.push((start..end, color))
15030 }
15031 }
15032 results
15033 }
15034
15035 pub fn background_highlight_row_ranges<T: 'static>(
15036 &self,
15037 search_range: Range<Anchor>,
15038 display_snapshot: &DisplaySnapshot,
15039 count: usize,
15040 ) -> Vec<RangeInclusive<DisplayPoint>> {
15041 let mut results = Vec::new();
15042 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15043 return vec![];
15044 };
15045
15046 let start_ix = match ranges.binary_search_by(|probe| {
15047 let cmp = probe
15048 .end
15049 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15050 if cmp.is_gt() {
15051 Ordering::Greater
15052 } else {
15053 Ordering::Less
15054 }
15055 }) {
15056 Ok(i) | Err(i) => i,
15057 };
15058 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15059 if let (Some(start_display), Some(end_display)) = (start, end) {
15060 results.push(
15061 start_display.to_display_point(display_snapshot)
15062 ..=end_display.to_display_point(display_snapshot),
15063 );
15064 }
15065 };
15066 let mut start_row: Option<Point> = None;
15067 let mut end_row: Option<Point> = None;
15068 if ranges.len() > count {
15069 return Vec::new();
15070 }
15071 for range in &ranges[start_ix..] {
15072 if range
15073 .start
15074 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15075 .is_ge()
15076 {
15077 break;
15078 }
15079 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15080 if let Some(current_row) = &end_row {
15081 if end.row == current_row.row {
15082 continue;
15083 }
15084 }
15085 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15086 if start_row.is_none() {
15087 assert_eq!(end_row, None);
15088 start_row = Some(start);
15089 end_row = Some(end);
15090 continue;
15091 }
15092 if let Some(current_end) = end_row.as_mut() {
15093 if start.row > current_end.row + 1 {
15094 push_region(start_row, end_row);
15095 start_row = Some(start);
15096 end_row = Some(end);
15097 } else {
15098 // Merge two hunks.
15099 *current_end = end;
15100 }
15101 } else {
15102 unreachable!();
15103 }
15104 }
15105 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15106 push_region(start_row, end_row);
15107 results
15108 }
15109
15110 pub fn gutter_highlights_in_range(
15111 &self,
15112 search_range: Range<Anchor>,
15113 display_snapshot: &DisplaySnapshot,
15114 cx: &App,
15115 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15116 let mut results = Vec::new();
15117 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15118 let color = color_fetcher(cx);
15119 let start_ix = match ranges.binary_search_by(|probe| {
15120 let cmp = probe
15121 .end
15122 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15123 if cmp.is_gt() {
15124 Ordering::Greater
15125 } else {
15126 Ordering::Less
15127 }
15128 }) {
15129 Ok(i) | Err(i) => i,
15130 };
15131 for range in &ranges[start_ix..] {
15132 if range
15133 .start
15134 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15135 .is_ge()
15136 {
15137 break;
15138 }
15139
15140 let start = range.start.to_display_point(display_snapshot);
15141 let end = range.end.to_display_point(display_snapshot);
15142 results.push((start..end, color))
15143 }
15144 }
15145 results
15146 }
15147
15148 /// Get the text ranges corresponding to the redaction query
15149 pub fn redacted_ranges(
15150 &self,
15151 search_range: Range<Anchor>,
15152 display_snapshot: &DisplaySnapshot,
15153 cx: &App,
15154 ) -> Vec<Range<DisplayPoint>> {
15155 display_snapshot
15156 .buffer_snapshot
15157 .redacted_ranges(search_range, |file| {
15158 if let Some(file) = file {
15159 file.is_private()
15160 && EditorSettings::get(
15161 Some(SettingsLocation {
15162 worktree_id: file.worktree_id(cx),
15163 path: file.path().as_ref(),
15164 }),
15165 cx,
15166 )
15167 .redact_private_values
15168 } else {
15169 false
15170 }
15171 })
15172 .map(|range| {
15173 range.start.to_display_point(display_snapshot)
15174 ..range.end.to_display_point(display_snapshot)
15175 })
15176 .collect()
15177 }
15178
15179 pub fn highlight_text<T: 'static>(
15180 &mut self,
15181 ranges: Vec<Range<Anchor>>,
15182 style: HighlightStyle,
15183 cx: &mut Context<Self>,
15184 ) {
15185 self.display_map.update(cx, |map, _| {
15186 map.highlight_text(TypeId::of::<T>(), ranges, style)
15187 });
15188 cx.notify();
15189 }
15190
15191 pub(crate) fn highlight_inlays<T: 'static>(
15192 &mut self,
15193 highlights: Vec<InlayHighlight>,
15194 style: HighlightStyle,
15195 cx: &mut Context<Self>,
15196 ) {
15197 self.display_map.update(cx, |map, _| {
15198 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15199 });
15200 cx.notify();
15201 }
15202
15203 pub fn text_highlights<'a, T: 'static>(
15204 &'a self,
15205 cx: &'a App,
15206 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15207 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15208 }
15209
15210 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15211 let cleared = self
15212 .display_map
15213 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15214 if cleared {
15215 cx.notify();
15216 }
15217 }
15218
15219 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15220 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15221 && self.focus_handle.is_focused(window)
15222 }
15223
15224 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15225 self.show_cursor_when_unfocused = is_enabled;
15226 cx.notify();
15227 }
15228
15229 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15230 cx.notify();
15231 }
15232
15233 fn on_buffer_event(
15234 &mut self,
15235 multibuffer: &Entity<MultiBuffer>,
15236 event: &multi_buffer::Event,
15237 window: &mut Window,
15238 cx: &mut Context<Self>,
15239 ) {
15240 match event {
15241 multi_buffer::Event::Edited {
15242 singleton_buffer_edited,
15243 edited_buffer: buffer_edited,
15244 } => {
15245 self.scrollbar_marker_state.dirty = true;
15246 self.active_indent_guides_state.dirty = true;
15247 self.refresh_active_diagnostics(cx);
15248 self.refresh_code_actions(window, cx);
15249 if self.has_active_inline_completion() {
15250 self.update_visible_inline_completion(window, cx);
15251 }
15252 if let Some(buffer) = buffer_edited {
15253 let buffer_id = buffer.read(cx).remote_id();
15254 if !self.registered_buffers.contains_key(&buffer_id) {
15255 if let Some(project) = self.project.as_ref() {
15256 project.update(cx, |project, cx| {
15257 self.registered_buffers.insert(
15258 buffer_id,
15259 project.register_buffer_with_language_servers(&buffer, cx),
15260 );
15261 })
15262 }
15263 }
15264 }
15265 cx.emit(EditorEvent::BufferEdited);
15266 cx.emit(SearchEvent::MatchesInvalidated);
15267 if *singleton_buffer_edited {
15268 if let Some(project) = &self.project {
15269 #[allow(clippy::mutable_key_type)]
15270 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15271 multibuffer
15272 .all_buffers()
15273 .into_iter()
15274 .filter_map(|buffer| {
15275 buffer.update(cx, |buffer, cx| {
15276 let language = buffer.language()?;
15277 let should_discard = project.update(cx, |project, cx| {
15278 project.is_local()
15279 && !project.has_language_servers_for(buffer, cx)
15280 });
15281 should_discard.not().then_some(language.clone())
15282 })
15283 })
15284 .collect::<HashSet<_>>()
15285 });
15286 if !languages_affected.is_empty() {
15287 self.refresh_inlay_hints(
15288 InlayHintRefreshReason::BufferEdited(languages_affected),
15289 cx,
15290 );
15291 }
15292 }
15293 }
15294
15295 let Some(project) = &self.project else { return };
15296 let (telemetry, is_via_ssh) = {
15297 let project = project.read(cx);
15298 let telemetry = project.client().telemetry().clone();
15299 let is_via_ssh = project.is_via_ssh();
15300 (telemetry, is_via_ssh)
15301 };
15302 refresh_linked_ranges(self, window, cx);
15303 telemetry.log_edit_event("editor", is_via_ssh);
15304 }
15305 multi_buffer::Event::ExcerptsAdded {
15306 buffer,
15307 predecessor,
15308 excerpts,
15309 } => {
15310 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15311 let buffer_id = buffer.read(cx).remote_id();
15312 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15313 if let Some(project) = &self.project {
15314 get_uncommitted_diff_for_buffer(
15315 project,
15316 [buffer.clone()],
15317 self.buffer.clone(),
15318 cx,
15319 )
15320 .detach();
15321 }
15322 }
15323 cx.emit(EditorEvent::ExcerptsAdded {
15324 buffer: buffer.clone(),
15325 predecessor: *predecessor,
15326 excerpts: excerpts.clone(),
15327 });
15328 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15329 }
15330 multi_buffer::Event::ExcerptsRemoved { ids } => {
15331 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15332 let buffer = self.buffer.read(cx);
15333 self.registered_buffers
15334 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15335 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15336 }
15337 multi_buffer::Event::ExcerptsEdited {
15338 excerpt_ids,
15339 buffer_ids,
15340 } => {
15341 self.display_map.update(cx, |map, cx| {
15342 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15343 });
15344 cx.emit(EditorEvent::ExcerptsEdited {
15345 ids: excerpt_ids.clone(),
15346 })
15347 }
15348 multi_buffer::Event::ExcerptsExpanded { ids } => {
15349 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15350 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15351 }
15352 multi_buffer::Event::Reparsed(buffer_id) => {
15353 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15354
15355 cx.emit(EditorEvent::Reparsed(*buffer_id));
15356 }
15357 multi_buffer::Event::DiffHunksToggled => {
15358 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15359 }
15360 multi_buffer::Event::LanguageChanged(buffer_id) => {
15361 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15362 cx.emit(EditorEvent::Reparsed(*buffer_id));
15363 cx.notify();
15364 }
15365 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15366 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15367 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15368 cx.emit(EditorEvent::TitleChanged)
15369 }
15370 // multi_buffer::Event::DiffBaseChanged => {
15371 // self.scrollbar_marker_state.dirty = true;
15372 // cx.emit(EditorEvent::DiffBaseChanged);
15373 // cx.notify();
15374 // }
15375 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15376 multi_buffer::Event::DiagnosticsUpdated => {
15377 self.refresh_active_diagnostics(cx);
15378 self.refresh_inline_diagnostics(true, window, cx);
15379 self.scrollbar_marker_state.dirty = true;
15380 cx.notify();
15381 }
15382 _ => {}
15383 };
15384 }
15385
15386 fn on_display_map_changed(
15387 &mut self,
15388 _: Entity<DisplayMap>,
15389 _: &mut Window,
15390 cx: &mut Context<Self>,
15391 ) {
15392 cx.notify();
15393 }
15394
15395 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15396 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15397 self.update_edit_prediction_settings(cx);
15398 self.refresh_inline_completion(true, false, window, cx);
15399 self.refresh_inlay_hints(
15400 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15401 self.selections.newest_anchor().head(),
15402 &self.buffer.read(cx).snapshot(cx),
15403 cx,
15404 )),
15405 cx,
15406 );
15407
15408 let old_cursor_shape = self.cursor_shape;
15409
15410 {
15411 let editor_settings = EditorSettings::get_global(cx);
15412 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15413 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15414 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15415 }
15416
15417 if old_cursor_shape != self.cursor_shape {
15418 cx.emit(EditorEvent::CursorShapeChanged);
15419 }
15420
15421 let project_settings = ProjectSettings::get_global(cx);
15422 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15423
15424 if self.mode == EditorMode::Full {
15425 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15426 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15427 if self.show_inline_diagnostics != show_inline_diagnostics {
15428 self.show_inline_diagnostics = show_inline_diagnostics;
15429 self.refresh_inline_diagnostics(false, window, cx);
15430 }
15431
15432 if self.git_blame_inline_enabled != inline_blame_enabled {
15433 self.toggle_git_blame_inline_internal(false, window, cx);
15434 }
15435 }
15436
15437 cx.notify();
15438 }
15439
15440 pub fn set_searchable(&mut self, searchable: bool) {
15441 self.searchable = searchable;
15442 }
15443
15444 pub fn searchable(&self) -> bool {
15445 self.searchable
15446 }
15447
15448 fn open_proposed_changes_editor(
15449 &mut self,
15450 _: &OpenProposedChangesEditor,
15451 window: &mut Window,
15452 cx: &mut Context<Self>,
15453 ) {
15454 let Some(workspace) = self.workspace() else {
15455 cx.propagate();
15456 return;
15457 };
15458
15459 let selections = self.selections.all::<usize>(cx);
15460 let multi_buffer = self.buffer.read(cx);
15461 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15462 let mut new_selections_by_buffer = HashMap::default();
15463 for selection in selections {
15464 for (buffer, range, _) in
15465 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15466 {
15467 let mut range = range.to_point(buffer);
15468 range.start.column = 0;
15469 range.end.column = buffer.line_len(range.end.row);
15470 new_selections_by_buffer
15471 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15472 .or_insert(Vec::new())
15473 .push(range)
15474 }
15475 }
15476
15477 let proposed_changes_buffers = new_selections_by_buffer
15478 .into_iter()
15479 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15480 .collect::<Vec<_>>();
15481 let proposed_changes_editor = cx.new(|cx| {
15482 ProposedChangesEditor::new(
15483 "Proposed changes",
15484 proposed_changes_buffers,
15485 self.project.clone(),
15486 window,
15487 cx,
15488 )
15489 });
15490
15491 window.defer(cx, move |window, cx| {
15492 workspace.update(cx, |workspace, cx| {
15493 workspace.active_pane().update(cx, |pane, cx| {
15494 pane.add_item(
15495 Box::new(proposed_changes_editor),
15496 true,
15497 true,
15498 None,
15499 window,
15500 cx,
15501 );
15502 });
15503 });
15504 });
15505 }
15506
15507 pub fn open_excerpts_in_split(
15508 &mut self,
15509 _: &OpenExcerptsSplit,
15510 window: &mut Window,
15511 cx: &mut Context<Self>,
15512 ) {
15513 self.open_excerpts_common(None, true, window, cx)
15514 }
15515
15516 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15517 self.open_excerpts_common(None, false, window, cx)
15518 }
15519
15520 fn open_excerpts_common(
15521 &mut self,
15522 jump_data: Option<JumpData>,
15523 split: bool,
15524 window: &mut Window,
15525 cx: &mut Context<Self>,
15526 ) {
15527 let Some(workspace) = self.workspace() else {
15528 cx.propagate();
15529 return;
15530 };
15531
15532 if self.buffer.read(cx).is_singleton() {
15533 cx.propagate();
15534 return;
15535 }
15536
15537 let mut new_selections_by_buffer = HashMap::default();
15538 match &jump_data {
15539 Some(JumpData::MultiBufferPoint {
15540 excerpt_id,
15541 position,
15542 anchor,
15543 line_offset_from_top,
15544 }) => {
15545 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15546 if let Some(buffer) = multi_buffer_snapshot
15547 .buffer_id_for_excerpt(*excerpt_id)
15548 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15549 {
15550 let buffer_snapshot = buffer.read(cx).snapshot();
15551 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15552 language::ToPoint::to_point(anchor, &buffer_snapshot)
15553 } else {
15554 buffer_snapshot.clip_point(*position, Bias::Left)
15555 };
15556 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15557 new_selections_by_buffer.insert(
15558 buffer,
15559 (
15560 vec![jump_to_offset..jump_to_offset],
15561 Some(*line_offset_from_top),
15562 ),
15563 );
15564 }
15565 }
15566 Some(JumpData::MultiBufferRow {
15567 row,
15568 line_offset_from_top,
15569 }) => {
15570 let point = MultiBufferPoint::new(row.0, 0);
15571 if let Some((buffer, buffer_point, _)) =
15572 self.buffer.read(cx).point_to_buffer_point(point, cx)
15573 {
15574 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15575 new_selections_by_buffer
15576 .entry(buffer)
15577 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15578 .0
15579 .push(buffer_offset..buffer_offset)
15580 }
15581 }
15582 None => {
15583 let selections = self.selections.all::<usize>(cx);
15584 let multi_buffer = self.buffer.read(cx);
15585 for selection in selections {
15586 for (snapshot, range, _, anchor) in multi_buffer
15587 .snapshot(cx)
15588 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15589 {
15590 if let Some(anchor) = anchor {
15591 // selection is in a deleted hunk
15592 let Some(buffer_id) = anchor.buffer_id else {
15593 continue;
15594 };
15595 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15596 continue;
15597 };
15598 let offset = text::ToOffset::to_offset(
15599 &anchor.text_anchor,
15600 &buffer_handle.read(cx).snapshot(),
15601 );
15602 let range = offset..offset;
15603 new_selections_by_buffer
15604 .entry(buffer_handle)
15605 .or_insert((Vec::new(), None))
15606 .0
15607 .push(range)
15608 } else {
15609 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15610 else {
15611 continue;
15612 };
15613 new_selections_by_buffer
15614 .entry(buffer_handle)
15615 .or_insert((Vec::new(), None))
15616 .0
15617 .push(range)
15618 }
15619 }
15620 }
15621 }
15622 }
15623
15624 if new_selections_by_buffer.is_empty() {
15625 return;
15626 }
15627
15628 // We defer the pane interaction because we ourselves are a workspace item
15629 // and activating a new item causes the pane to call a method on us reentrantly,
15630 // which panics if we're on the stack.
15631 window.defer(cx, move |window, cx| {
15632 workspace.update(cx, |workspace, cx| {
15633 let pane = if split {
15634 workspace.adjacent_pane(window, cx)
15635 } else {
15636 workspace.active_pane().clone()
15637 };
15638
15639 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15640 let editor = buffer
15641 .read(cx)
15642 .file()
15643 .is_none()
15644 .then(|| {
15645 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15646 // so `workspace.open_project_item` will never find them, always opening a new editor.
15647 // Instead, we try to activate the existing editor in the pane first.
15648 let (editor, pane_item_index) =
15649 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15650 let editor = item.downcast::<Editor>()?;
15651 let singleton_buffer =
15652 editor.read(cx).buffer().read(cx).as_singleton()?;
15653 if singleton_buffer == buffer {
15654 Some((editor, i))
15655 } else {
15656 None
15657 }
15658 })?;
15659 pane.update(cx, |pane, cx| {
15660 pane.activate_item(pane_item_index, true, true, window, cx)
15661 });
15662 Some(editor)
15663 })
15664 .flatten()
15665 .unwrap_or_else(|| {
15666 workspace.open_project_item::<Self>(
15667 pane.clone(),
15668 buffer,
15669 true,
15670 true,
15671 window,
15672 cx,
15673 )
15674 });
15675
15676 editor.update(cx, |editor, cx| {
15677 let autoscroll = match scroll_offset {
15678 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15679 None => Autoscroll::newest(),
15680 };
15681 let nav_history = editor.nav_history.take();
15682 editor.change_selections(Some(autoscroll), window, cx, |s| {
15683 s.select_ranges(ranges);
15684 });
15685 editor.nav_history = nav_history;
15686 });
15687 }
15688 })
15689 });
15690 }
15691
15692 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15693 let snapshot = self.buffer.read(cx).read(cx);
15694 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15695 Some(
15696 ranges
15697 .iter()
15698 .map(move |range| {
15699 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15700 })
15701 .collect(),
15702 )
15703 }
15704
15705 fn selection_replacement_ranges(
15706 &self,
15707 range: Range<OffsetUtf16>,
15708 cx: &mut App,
15709 ) -> Vec<Range<OffsetUtf16>> {
15710 let selections = self.selections.all::<OffsetUtf16>(cx);
15711 let newest_selection = selections
15712 .iter()
15713 .max_by_key(|selection| selection.id)
15714 .unwrap();
15715 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15716 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15717 let snapshot = self.buffer.read(cx).read(cx);
15718 selections
15719 .into_iter()
15720 .map(|mut selection| {
15721 selection.start.0 =
15722 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15723 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15724 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15725 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15726 })
15727 .collect()
15728 }
15729
15730 fn report_editor_event(
15731 &self,
15732 event_type: &'static str,
15733 file_extension: Option<String>,
15734 cx: &App,
15735 ) {
15736 if cfg!(any(test, feature = "test-support")) {
15737 return;
15738 }
15739
15740 let Some(project) = &self.project else { return };
15741
15742 // If None, we are in a file without an extension
15743 let file = self
15744 .buffer
15745 .read(cx)
15746 .as_singleton()
15747 .and_then(|b| b.read(cx).file());
15748 let file_extension = file_extension.or(file
15749 .as_ref()
15750 .and_then(|file| Path::new(file.file_name(cx)).extension())
15751 .and_then(|e| e.to_str())
15752 .map(|a| a.to_string()));
15753
15754 let vim_mode = cx
15755 .global::<SettingsStore>()
15756 .raw_user_settings()
15757 .get("vim_mode")
15758 == Some(&serde_json::Value::Bool(true));
15759
15760 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15761 let copilot_enabled = edit_predictions_provider
15762 == language::language_settings::EditPredictionProvider::Copilot;
15763 let copilot_enabled_for_language = self
15764 .buffer
15765 .read(cx)
15766 .settings_at(0, cx)
15767 .show_edit_predictions;
15768
15769 let project = project.read(cx);
15770 telemetry::event!(
15771 event_type,
15772 file_extension,
15773 vim_mode,
15774 copilot_enabled,
15775 copilot_enabled_for_language,
15776 edit_predictions_provider,
15777 is_via_ssh = project.is_via_ssh(),
15778 );
15779 }
15780
15781 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15782 /// with each line being an array of {text, highlight} objects.
15783 fn copy_highlight_json(
15784 &mut self,
15785 _: &CopyHighlightJson,
15786 window: &mut Window,
15787 cx: &mut Context<Self>,
15788 ) {
15789 #[derive(Serialize)]
15790 struct Chunk<'a> {
15791 text: String,
15792 highlight: Option<&'a str>,
15793 }
15794
15795 let snapshot = self.buffer.read(cx).snapshot(cx);
15796 let range = self
15797 .selected_text_range(false, window, cx)
15798 .and_then(|selection| {
15799 if selection.range.is_empty() {
15800 None
15801 } else {
15802 Some(selection.range)
15803 }
15804 })
15805 .unwrap_or_else(|| 0..snapshot.len());
15806
15807 let chunks = snapshot.chunks(range, true);
15808 let mut lines = Vec::new();
15809 let mut line: VecDeque<Chunk> = VecDeque::new();
15810
15811 let Some(style) = self.style.as_ref() else {
15812 return;
15813 };
15814
15815 for chunk in chunks {
15816 let highlight = chunk
15817 .syntax_highlight_id
15818 .and_then(|id| id.name(&style.syntax));
15819 let mut chunk_lines = chunk.text.split('\n').peekable();
15820 while let Some(text) = chunk_lines.next() {
15821 let mut merged_with_last_token = false;
15822 if let Some(last_token) = line.back_mut() {
15823 if last_token.highlight == highlight {
15824 last_token.text.push_str(text);
15825 merged_with_last_token = true;
15826 }
15827 }
15828
15829 if !merged_with_last_token {
15830 line.push_back(Chunk {
15831 text: text.into(),
15832 highlight,
15833 });
15834 }
15835
15836 if chunk_lines.peek().is_some() {
15837 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15838 line.pop_front();
15839 }
15840 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15841 line.pop_back();
15842 }
15843
15844 lines.push(mem::take(&mut line));
15845 }
15846 }
15847 }
15848
15849 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15850 return;
15851 };
15852 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15853 }
15854
15855 pub fn open_context_menu(
15856 &mut self,
15857 _: &OpenContextMenu,
15858 window: &mut Window,
15859 cx: &mut Context<Self>,
15860 ) {
15861 self.request_autoscroll(Autoscroll::newest(), cx);
15862 let position = self.selections.newest_display(cx).start;
15863 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15864 }
15865
15866 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15867 &self.inlay_hint_cache
15868 }
15869
15870 pub fn replay_insert_event(
15871 &mut self,
15872 text: &str,
15873 relative_utf16_range: Option<Range<isize>>,
15874 window: &mut Window,
15875 cx: &mut Context<Self>,
15876 ) {
15877 if !self.input_enabled {
15878 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15879 return;
15880 }
15881 if let Some(relative_utf16_range) = relative_utf16_range {
15882 let selections = self.selections.all::<OffsetUtf16>(cx);
15883 self.change_selections(None, window, cx, |s| {
15884 let new_ranges = selections.into_iter().map(|range| {
15885 let start = OffsetUtf16(
15886 range
15887 .head()
15888 .0
15889 .saturating_add_signed(relative_utf16_range.start),
15890 );
15891 let end = OffsetUtf16(
15892 range
15893 .head()
15894 .0
15895 .saturating_add_signed(relative_utf16_range.end),
15896 );
15897 start..end
15898 });
15899 s.select_ranges(new_ranges);
15900 });
15901 }
15902
15903 self.handle_input(text, window, cx);
15904 }
15905
15906 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15907 let Some(provider) = self.semantics_provider.as_ref() else {
15908 return false;
15909 };
15910
15911 let mut supports = false;
15912 self.buffer().update(cx, |this, cx| {
15913 this.for_each_buffer(|buffer| {
15914 supports |= provider.supports_inlay_hints(buffer, cx);
15915 });
15916 });
15917
15918 supports
15919 }
15920
15921 pub fn is_focused(&self, window: &Window) -> bool {
15922 self.focus_handle.is_focused(window)
15923 }
15924
15925 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15926 cx.emit(EditorEvent::Focused);
15927
15928 if let Some(descendant) = self
15929 .last_focused_descendant
15930 .take()
15931 .and_then(|descendant| descendant.upgrade())
15932 {
15933 window.focus(&descendant);
15934 } else {
15935 if let Some(blame) = self.blame.as_ref() {
15936 blame.update(cx, GitBlame::focus)
15937 }
15938
15939 self.blink_manager.update(cx, BlinkManager::enable);
15940 self.show_cursor_names(window, cx);
15941 self.buffer.update(cx, |buffer, cx| {
15942 buffer.finalize_last_transaction(cx);
15943 if self.leader_peer_id.is_none() {
15944 buffer.set_active_selections(
15945 &self.selections.disjoint_anchors(),
15946 self.selections.line_mode,
15947 self.cursor_shape,
15948 cx,
15949 );
15950 }
15951 });
15952 }
15953 }
15954
15955 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15956 cx.emit(EditorEvent::FocusedIn)
15957 }
15958
15959 fn handle_focus_out(
15960 &mut self,
15961 event: FocusOutEvent,
15962 _window: &mut Window,
15963 cx: &mut Context<Self>,
15964 ) {
15965 if event.blurred != self.focus_handle {
15966 self.last_focused_descendant = Some(event.blurred);
15967 }
15968 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
15969 }
15970
15971 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15972 self.blink_manager.update(cx, BlinkManager::disable);
15973 self.buffer
15974 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15975
15976 if let Some(blame) = self.blame.as_ref() {
15977 blame.update(cx, GitBlame::blur)
15978 }
15979 if !self.hover_state.focused(window, cx) {
15980 hide_hover(self, cx);
15981 }
15982 if !self
15983 .context_menu
15984 .borrow()
15985 .as_ref()
15986 .is_some_and(|context_menu| context_menu.focused(window, cx))
15987 {
15988 self.hide_context_menu(window, cx);
15989 }
15990 self.discard_inline_completion(false, cx);
15991 cx.emit(EditorEvent::Blurred);
15992 cx.notify();
15993 }
15994
15995 pub fn register_action<A: Action>(
15996 &mut self,
15997 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15998 ) -> Subscription {
15999 let id = self.next_editor_action_id.post_inc();
16000 let listener = Arc::new(listener);
16001 self.editor_actions.borrow_mut().insert(
16002 id,
16003 Box::new(move |window, _| {
16004 let listener = listener.clone();
16005 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16006 let action = action.downcast_ref().unwrap();
16007 if phase == DispatchPhase::Bubble {
16008 listener(action, window, cx)
16009 }
16010 })
16011 }),
16012 );
16013
16014 let editor_actions = self.editor_actions.clone();
16015 Subscription::new(move || {
16016 editor_actions.borrow_mut().remove(&id);
16017 })
16018 }
16019
16020 pub fn file_header_size(&self) -> u32 {
16021 FILE_HEADER_HEIGHT
16022 }
16023
16024 pub fn restore(
16025 &mut self,
16026 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16027 window: &mut Window,
16028 cx: &mut Context<Self>,
16029 ) {
16030 let workspace = self.workspace();
16031 let project = self.project.as_ref();
16032 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16033 let mut tasks = Vec::new();
16034 for (buffer_id, changes) in revert_changes {
16035 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16036 buffer.update(cx, |buffer, cx| {
16037 buffer.edit(
16038 changes.into_iter().map(|(range, text)| {
16039 (range, text.to_string().map(Arc::<str>::from))
16040 }),
16041 None,
16042 cx,
16043 );
16044 });
16045
16046 if let Some(project) =
16047 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16048 {
16049 project.update(cx, |project, cx| {
16050 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16051 })
16052 }
16053 }
16054 }
16055 tasks
16056 });
16057 cx.spawn_in(window, |_, mut cx| async move {
16058 for (buffer, task) in save_tasks {
16059 let result = task.await;
16060 if result.is_err() {
16061 let Some(path) = buffer
16062 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16063 .ok()
16064 else {
16065 continue;
16066 };
16067 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16068 let Some(task) = cx
16069 .update_window_entity(&workspace, |workspace, window, cx| {
16070 workspace
16071 .open_path_preview(path, None, false, false, false, window, cx)
16072 })
16073 .ok()
16074 else {
16075 continue;
16076 };
16077 task.await.log_err();
16078 }
16079 }
16080 }
16081 })
16082 .detach();
16083 self.change_selections(None, window, cx, |selections| selections.refresh());
16084 }
16085
16086 pub fn to_pixel_point(
16087 &self,
16088 source: multi_buffer::Anchor,
16089 editor_snapshot: &EditorSnapshot,
16090 window: &mut Window,
16091 ) -> Option<gpui::Point<Pixels>> {
16092 let source_point = source.to_display_point(editor_snapshot);
16093 self.display_to_pixel_point(source_point, editor_snapshot, window)
16094 }
16095
16096 pub fn display_to_pixel_point(
16097 &self,
16098 source: DisplayPoint,
16099 editor_snapshot: &EditorSnapshot,
16100 window: &mut Window,
16101 ) -> Option<gpui::Point<Pixels>> {
16102 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16103 let text_layout_details = self.text_layout_details(window);
16104 let scroll_top = text_layout_details
16105 .scroll_anchor
16106 .scroll_position(editor_snapshot)
16107 .y;
16108
16109 if source.row().as_f32() < scroll_top.floor() {
16110 return None;
16111 }
16112 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16113 let source_y = line_height * (source.row().as_f32() - scroll_top);
16114 Some(gpui::Point::new(source_x, source_y))
16115 }
16116
16117 pub fn has_visible_completions_menu(&self) -> bool {
16118 !self.edit_prediction_preview_is_active()
16119 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16120 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16121 })
16122 }
16123
16124 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16125 self.addons
16126 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16127 }
16128
16129 pub fn unregister_addon<T: Addon>(&mut self) {
16130 self.addons.remove(&std::any::TypeId::of::<T>());
16131 }
16132
16133 pub fn addon<T: Addon>(&self) -> Option<&T> {
16134 let type_id = std::any::TypeId::of::<T>();
16135 self.addons
16136 .get(&type_id)
16137 .and_then(|item| item.to_any().downcast_ref::<T>())
16138 }
16139
16140 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16141 let text_layout_details = self.text_layout_details(window);
16142 let style = &text_layout_details.editor_style;
16143 let font_id = window.text_system().resolve_font(&style.text.font());
16144 let font_size = style.text.font_size.to_pixels(window.rem_size());
16145 let line_height = style.text.line_height_in_pixels(window.rem_size());
16146 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16147
16148 gpui::Size::new(em_width, line_height)
16149 }
16150
16151 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16152 self.load_diff_task.clone()
16153 }
16154
16155 fn read_selections_from_db(
16156 &mut self,
16157 item_id: u64,
16158 workspace_id: WorkspaceId,
16159 window: &mut Window,
16160 cx: &mut Context<Editor>,
16161 ) {
16162 if !self.is_singleton(cx)
16163 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16164 {
16165 return;
16166 }
16167 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16168 return;
16169 };
16170 if selections.is_empty() {
16171 return;
16172 }
16173
16174 let snapshot = self.buffer.read(cx).snapshot(cx);
16175 self.change_selections(None, window, cx, |s| {
16176 s.select_ranges(selections.into_iter().map(|(start, end)| {
16177 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16178 }));
16179 });
16180 }
16181}
16182
16183fn insert_extra_newline_brackets(
16184 buffer: &MultiBufferSnapshot,
16185 range: Range<usize>,
16186 language: &language::LanguageScope,
16187) -> bool {
16188 let leading_whitespace_len = buffer
16189 .reversed_chars_at(range.start)
16190 .take_while(|c| c.is_whitespace() && *c != '\n')
16191 .map(|c| c.len_utf8())
16192 .sum::<usize>();
16193 let trailing_whitespace_len = buffer
16194 .chars_at(range.end)
16195 .take_while(|c| c.is_whitespace() && *c != '\n')
16196 .map(|c| c.len_utf8())
16197 .sum::<usize>();
16198 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16199
16200 language.brackets().any(|(pair, enabled)| {
16201 let pair_start = pair.start.trim_end();
16202 let pair_end = pair.end.trim_start();
16203
16204 enabled
16205 && pair.newline
16206 && buffer.contains_str_at(range.end, pair_end)
16207 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16208 })
16209}
16210
16211fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16212 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16213 [(buffer, range, _)] => (*buffer, range.clone()),
16214 _ => return false,
16215 };
16216 let pair = {
16217 let mut result: Option<BracketMatch> = None;
16218
16219 for pair in buffer
16220 .all_bracket_ranges(range.clone())
16221 .filter(move |pair| {
16222 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16223 })
16224 {
16225 let len = pair.close_range.end - pair.open_range.start;
16226
16227 if let Some(existing) = &result {
16228 let existing_len = existing.close_range.end - existing.open_range.start;
16229 if len > existing_len {
16230 continue;
16231 }
16232 }
16233
16234 result = Some(pair);
16235 }
16236
16237 result
16238 };
16239 let Some(pair) = pair else {
16240 return false;
16241 };
16242 pair.newline_only
16243 && buffer
16244 .chars_for_range(pair.open_range.end..range.start)
16245 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16246 .all(|c| c.is_whitespace() && c != '\n')
16247}
16248
16249fn get_uncommitted_diff_for_buffer(
16250 project: &Entity<Project>,
16251 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16252 buffer: Entity<MultiBuffer>,
16253 cx: &mut App,
16254) -> Task<()> {
16255 let mut tasks = Vec::new();
16256 project.update(cx, |project, cx| {
16257 for buffer in buffers {
16258 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16259 }
16260 });
16261 cx.spawn(|mut cx| async move {
16262 let diffs = futures::future::join_all(tasks).await;
16263 buffer
16264 .update(&mut cx, |buffer, cx| {
16265 for diff in diffs.into_iter().flatten() {
16266 buffer.add_diff(diff, cx);
16267 }
16268 })
16269 .ok();
16270 })
16271}
16272
16273fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16274 let tab_size = tab_size.get() as usize;
16275 let mut width = offset;
16276
16277 for ch in text.chars() {
16278 width += if ch == '\t' {
16279 tab_size - (width % tab_size)
16280 } else {
16281 1
16282 };
16283 }
16284
16285 width - offset
16286}
16287
16288#[cfg(test)]
16289mod tests {
16290 use super::*;
16291
16292 #[test]
16293 fn test_string_size_with_expanded_tabs() {
16294 let nz = |val| NonZeroU32::new(val).unwrap();
16295 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16296 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16297 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16298 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16299 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16300 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16301 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16302 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16303 }
16304}
16305
16306/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16307struct WordBreakingTokenizer<'a> {
16308 input: &'a str,
16309}
16310
16311impl<'a> WordBreakingTokenizer<'a> {
16312 fn new(input: &'a str) -> Self {
16313 Self { input }
16314 }
16315}
16316
16317fn is_char_ideographic(ch: char) -> bool {
16318 use unicode_script::Script::*;
16319 use unicode_script::UnicodeScript;
16320 matches!(ch.script(), Han | Tangut | Yi)
16321}
16322
16323fn is_grapheme_ideographic(text: &str) -> bool {
16324 text.chars().any(is_char_ideographic)
16325}
16326
16327fn is_grapheme_whitespace(text: &str) -> bool {
16328 text.chars().any(|x| x.is_whitespace())
16329}
16330
16331fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16332 text.chars().next().map_or(false, |ch| {
16333 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16334 })
16335}
16336
16337#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16338struct WordBreakToken<'a> {
16339 token: &'a str,
16340 grapheme_len: usize,
16341 is_whitespace: bool,
16342}
16343
16344impl<'a> Iterator for WordBreakingTokenizer<'a> {
16345 /// Yields a span, the count of graphemes in the token, and whether it was
16346 /// whitespace. Note that it also breaks at word boundaries.
16347 type Item = WordBreakToken<'a>;
16348
16349 fn next(&mut self) -> Option<Self::Item> {
16350 use unicode_segmentation::UnicodeSegmentation;
16351 if self.input.is_empty() {
16352 return None;
16353 }
16354
16355 let mut iter = self.input.graphemes(true).peekable();
16356 let mut offset = 0;
16357 let mut graphemes = 0;
16358 if let Some(first_grapheme) = iter.next() {
16359 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16360 offset += first_grapheme.len();
16361 graphemes += 1;
16362 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16363 if let Some(grapheme) = iter.peek().copied() {
16364 if should_stay_with_preceding_ideograph(grapheme) {
16365 offset += grapheme.len();
16366 graphemes += 1;
16367 }
16368 }
16369 } else {
16370 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16371 let mut next_word_bound = words.peek().copied();
16372 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16373 next_word_bound = words.next();
16374 }
16375 while let Some(grapheme) = iter.peek().copied() {
16376 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16377 break;
16378 };
16379 if is_grapheme_whitespace(grapheme) != is_whitespace {
16380 break;
16381 };
16382 offset += grapheme.len();
16383 graphemes += 1;
16384 iter.next();
16385 }
16386 }
16387 let token = &self.input[..offset];
16388 self.input = &self.input[offset..];
16389 if is_whitespace {
16390 Some(WordBreakToken {
16391 token: " ",
16392 grapheme_len: 1,
16393 is_whitespace: true,
16394 })
16395 } else {
16396 Some(WordBreakToken {
16397 token,
16398 grapheme_len: graphemes,
16399 is_whitespace: false,
16400 })
16401 }
16402 } else {
16403 None
16404 }
16405 }
16406}
16407
16408#[test]
16409fn test_word_breaking_tokenizer() {
16410 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16411 ("", &[]),
16412 (" ", &[(" ", 1, true)]),
16413 ("Ʒ", &[("Ʒ", 1, false)]),
16414 ("Ǽ", &[("Ǽ", 1, false)]),
16415 ("⋑", &[("⋑", 1, false)]),
16416 ("⋑⋑", &[("⋑⋑", 2, false)]),
16417 (
16418 "原理,进而",
16419 &[
16420 ("原", 1, false),
16421 ("理,", 2, false),
16422 ("进", 1, false),
16423 ("而", 1, false),
16424 ],
16425 ),
16426 (
16427 "hello world",
16428 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16429 ),
16430 (
16431 "hello, world",
16432 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16433 ),
16434 (
16435 " hello world",
16436 &[
16437 (" ", 1, true),
16438 ("hello", 5, false),
16439 (" ", 1, true),
16440 ("world", 5, false),
16441 ],
16442 ),
16443 (
16444 "这是什么 \n 钢笔",
16445 &[
16446 ("这", 1, false),
16447 ("是", 1, false),
16448 ("什", 1, false),
16449 ("么", 1, false),
16450 (" ", 1, true),
16451 ("钢", 1, false),
16452 ("笔", 1, false),
16453 ],
16454 ),
16455 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16456 ];
16457
16458 for (input, result) in tests {
16459 assert_eq!(
16460 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16461 result
16462 .iter()
16463 .copied()
16464 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16465 token,
16466 grapheme_len,
16467 is_whitespace,
16468 })
16469 .collect::<Vec<_>>()
16470 );
16471 }
16472}
16473
16474fn wrap_with_prefix(
16475 line_prefix: String,
16476 unwrapped_text: String,
16477 wrap_column: usize,
16478 tab_size: NonZeroU32,
16479) -> String {
16480 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16481 let mut wrapped_text = String::new();
16482 let mut current_line = line_prefix.clone();
16483
16484 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16485 let mut current_line_len = line_prefix_len;
16486 for WordBreakToken {
16487 token,
16488 grapheme_len,
16489 is_whitespace,
16490 } in tokenizer
16491 {
16492 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16493 wrapped_text.push_str(current_line.trim_end());
16494 wrapped_text.push('\n');
16495 current_line.truncate(line_prefix.len());
16496 current_line_len = line_prefix_len;
16497 if !is_whitespace {
16498 current_line.push_str(token);
16499 current_line_len += grapheme_len;
16500 }
16501 } else if !is_whitespace {
16502 current_line.push_str(token);
16503 current_line_len += grapheme_len;
16504 } else if current_line_len != line_prefix_len {
16505 current_line.push(' ');
16506 current_line_len += 1;
16507 }
16508 }
16509
16510 if !current_line.is_empty() {
16511 wrapped_text.push_str(¤t_line);
16512 }
16513 wrapped_text
16514}
16515
16516#[test]
16517fn test_wrap_with_prefix() {
16518 assert_eq!(
16519 wrap_with_prefix(
16520 "# ".to_string(),
16521 "abcdefg".to_string(),
16522 4,
16523 NonZeroU32::new(4).unwrap()
16524 ),
16525 "# abcdefg"
16526 );
16527 assert_eq!(
16528 wrap_with_prefix(
16529 "".to_string(),
16530 "\thello world".to_string(),
16531 8,
16532 NonZeroU32::new(4).unwrap()
16533 ),
16534 "hello\nworld"
16535 );
16536 assert_eq!(
16537 wrap_with_prefix(
16538 "// ".to_string(),
16539 "xx \nyy zz aa bb cc".to_string(),
16540 12,
16541 NonZeroU32::new(4).unwrap()
16542 ),
16543 "// xx yy zz\n// aa bb cc"
16544 );
16545 assert_eq!(
16546 wrap_with_prefix(
16547 String::new(),
16548 "这是什么 \n 钢笔".to_string(),
16549 3,
16550 NonZeroU32::new(4).unwrap()
16551 ),
16552 "这是什\n么 钢\n笔"
16553 );
16554}
16555
16556pub trait CollaborationHub {
16557 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16558 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16559 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16560}
16561
16562impl CollaborationHub for Entity<Project> {
16563 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16564 self.read(cx).collaborators()
16565 }
16566
16567 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16568 self.read(cx).user_store().read(cx).participant_indices()
16569 }
16570
16571 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16572 let this = self.read(cx);
16573 let user_ids = this.collaborators().values().map(|c| c.user_id);
16574 this.user_store().read_with(cx, |user_store, cx| {
16575 user_store.participant_names(user_ids, cx)
16576 })
16577 }
16578}
16579
16580pub trait SemanticsProvider {
16581 fn hover(
16582 &self,
16583 buffer: &Entity<Buffer>,
16584 position: text::Anchor,
16585 cx: &mut App,
16586 ) -> Option<Task<Vec<project::Hover>>>;
16587
16588 fn inlay_hints(
16589 &self,
16590 buffer_handle: Entity<Buffer>,
16591 range: Range<text::Anchor>,
16592 cx: &mut App,
16593 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16594
16595 fn resolve_inlay_hint(
16596 &self,
16597 hint: InlayHint,
16598 buffer_handle: Entity<Buffer>,
16599 server_id: LanguageServerId,
16600 cx: &mut App,
16601 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16602
16603 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16604
16605 fn document_highlights(
16606 &self,
16607 buffer: &Entity<Buffer>,
16608 position: text::Anchor,
16609 cx: &mut App,
16610 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16611
16612 fn definitions(
16613 &self,
16614 buffer: &Entity<Buffer>,
16615 position: text::Anchor,
16616 kind: GotoDefinitionKind,
16617 cx: &mut App,
16618 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16619
16620 fn range_for_rename(
16621 &self,
16622 buffer: &Entity<Buffer>,
16623 position: text::Anchor,
16624 cx: &mut App,
16625 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16626
16627 fn perform_rename(
16628 &self,
16629 buffer: &Entity<Buffer>,
16630 position: text::Anchor,
16631 new_name: String,
16632 cx: &mut App,
16633 ) -> Option<Task<Result<ProjectTransaction>>>;
16634}
16635
16636pub trait CompletionProvider {
16637 fn completions(
16638 &self,
16639 buffer: &Entity<Buffer>,
16640 buffer_position: text::Anchor,
16641 trigger: CompletionContext,
16642 window: &mut Window,
16643 cx: &mut Context<Editor>,
16644 ) -> Task<Result<Vec<Completion>>>;
16645
16646 fn resolve_completions(
16647 &self,
16648 buffer: Entity<Buffer>,
16649 completion_indices: Vec<usize>,
16650 completions: Rc<RefCell<Box<[Completion]>>>,
16651 cx: &mut Context<Editor>,
16652 ) -> Task<Result<bool>>;
16653
16654 fn apply_additional_edits_for_completion(
16655 &self,
16656 _buffer: Entity<Buffer>,
16657 _completions: Rc<RefCell<Box<[Completion]>>>,
16658 _completion_index: usize,
16659 _push_to_history: bool,
16660 _cx: &mut Context<Editor>,
16661 ) -> Task<Result<Option<language::Transaction>>> {
16662 Task::ready(Ok(None))
16663 }
16664
16665 fn is_completion_trigger(
16666 &self,
16667 buffer: &Entity<Buffer>,
16668 position: language::Anchor,
16669 text: &str,
16670 trigger_in_words: bool,
16671 cx: &mut Context<Editor>,
16672 ) -> bool;
16673
16674 fn sort_completions(&self) -> bool {
16675 true
16676 }
16677}
16678
16679pub trait CodeActionProvider {
16680 fn id(&self) -> Arc<str>;
16681
16682 fn code_actions(
16683 &self,
16684 buffer: &Entity<Buffer>,
16685 range: Range<text::Anchor>,
16686 window: &mut Window,
16687 cx: &mut App,
16688 ) -> Task<Result<Vec<CodeAction>>>;
16689
16690 fn apply_code_action(
16691 &self,
16692 buffer_handle: Entity<Buffer>,
16693 action: CodeAction,
16694 excerpt_id: ExcerptId,
16695 push_to_history: bool,
16696 window: &mut Window,
16697 cx: &mut App,
16698 ) -> Task<Result<ProjectTransaction>>;
16699}
16700
16701impl CodeActionProvider for Entity<Project> {
16702 fn id(&self) -> Arc<str> {
16703 "project".into()
16704 }
16705
16706 fn code_actions(
16707 &self,
16708 buffer: &Entity<Buffer>,
16709 range: Range<text::Anchor>,
16710 _window: &mut Window,
16711 cx: &mut App,
16712 ) -> Task<Result<Vec<CodeAction>>> {
16713 self.update(cx, |project, cx| {
16714 project.code_actions(buffer, range, None, cx)
16715 })
16716 }
16717
16718 fn apply_code_action(
16719 &self,
16720 buffer_handle: Entity<Buffer>,
16721 action: CodeAction,
16722 _excerpt_id: ExcerptId,
16723 push_to_history: bool,
16724 _window: &mut Window,
16725 cx: &mut App,
16726 ) -> Task<Result<ProjectTransaction>> {
16727 self.update(cx, |project, cx| {
16728 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16729 })
16730 }
16731}
16732
16733fn snippet_completions(
16734 project: &Project,
16735 buffer: &Entity<Buffer>,
16736 buffer_position: text::Anchor,
16737 cx: &mut App,
16738) -> Task<Result<Vec<Completion>>> {
16739 let language = buffer.read(cx).language_at(buffer_position);
16740 let language_name = language.as_ref().map(|language| language.lsp_id());
16741 let snippet_store = project.snippets().read(cx);
16742 let snippets = snippet_store.snippets_for(language_name, cx);
16743
16744 if snippets.is_empty() {
16745 return Task::ready(Ok(vec![]));
16746 }
16747 let snapshot = buffer.read(cx).text_snapshot();
16748 let chars: String = snapshot
16749 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16750 .collect();
16751
16752 let scope = language.map(|language| language.default_scope());
16753 let executor = cx.background_executor().clone();
16754
16755 cx.background_spawn(async move {
16756 let classifier = CharClassifier::new(scope).for_completion(true);
16757 let mut last_word = chars
16758 .chars()
16759 .take_while(|c| classifier.is_word(*c))
16760 .collect::<String>();
16761 last_word = last_word.chars().rev().collect();
16762
16763 if last_word.is_empty() {
16764 return Ok(vec![]);
16765 }
16766
16767 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16768 let to_lsp = |point: &text::Anchor| {
16769 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16770 point_to_lsp(end)
16771 };
16772 let lsp_end = to_lsp(&buffer_position);
16773
16774 let candidates = snippets
16775 .iter()
16776 .enumerate()
16777 .flat_map(|(ix, snippet)| {
16778 snippet
16779 .prefix
16780 .iter()
16781 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16782 })
16783 .collect::<Vec<StringMatchCandidate>>();
16784
16785 let mut matches = fuzzy::match_strings(
16786 &candidates,
16787 &last_word,
16788 last_word.chars().any(|c| c.is_uppercase()),
16789 100,
16790 &Default::default(),
16791 executor,
16792 )
16793 .await;
16794
16795 // Remove all candidates where the query's start does not match the start of any word in the candidate
16796 if let Some(query_start) = last_word.chars().next() {
16797 matches.retain(|string_match| {
16798 split_words(&string_match.string).any(|word| {
16799 // Check that the first codepoint of the word as lowercase matches the first
16800 // codepoint of the query as lowercase
16801 word.chars()
16802 .flat_map(|codepoint| codepoint.to_lowercase())
16803 .zip(query_start.to_lowercase())
16804 .all(|(word_cp, query_cp)| word_cp == query_cp)
16805 })
16806 });
16807 }
16808
16809 let matched_strings = matches
16810 .into_iter()
16811 .map(|m| m.string)
16812 .collect::<HashSet<_>>();
16813
16814 let result: Vec<Completion> = snippets
16815 .into_iter()
16816 .filter_map(|snippet| {
16817 let matching_prefix = snippet
16818 .prefix
16819 .iter()
16820 .find(|prefix| matched_strings.contains(*prefix))?;
16821 let start = as_offset - last_word.len();
16822 let start = snapshot.anchor_before(start);
16823 let range = start..buffer_position;
16824 let lsp_start = to_lsp(&start);
16825 let lsp_range = lsp::Range {
16826 start: lsp_start,
16827 end: lsp_end,
16828 };
16829 Some(Completion {
16830 old_range: range,
16831 new_text: snippet.body.clone(),
16832 resolved: false,
16833 label: CodeLabel {
16834 text: matching_prefix.clone(),
16835 runs: vec![],
16836 filter_range: 0..matching_prefix.len(),
16837 },
16838 server_id: LanguageServerId(usize::MAX),
16839 documentation: snippet
16840 .description
16841 .clone()
16842 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16843 lsp_completion: lsp::CompletionItem {
16844 label: snippet.prefix.first().unwrap().clone(),
16845 kind: Some(CompletionItemKind::SNIPPET),
16846 label_details: snippet.description.as_ref().map(|description| {
16847 lsp::CompletionItemLabelDetails {
16848 detail: Some(description.clone()),
16849 description: None,
16850 }
16851 }),
16852 insert_text_format: Some(InsertTextFormat::SNIPPET),
16853 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16854 lsp::InsertReplaceEdit {
16855 new_text: snippet.body.clone(),
16856 insert: lsp_range,
16857 replace: lsp_range,
16858 },
16859 )),
16860 filter_text: Some(snippet.body.clone()),
16861 sort_text: Some(char::MAX.to_string()),
16862 ..Default::default()
16863 },
16864 confirm: None,
16865 })
16866 })
16867 .collect();
16868
16869 Ok(result)
16870 })
16871}
16872
16873impl CompletionProvider for Entity<Project> {
16874 fn completions(
16875 &self,
16876 buffer: &Entity<Buffer>,
16877 buffer_position: text::Anchor,
16878 options: CompletionContext,
16879 _window: &mut Window,
16880 cx: &mut Context<Editor>,
16881 ) -> Task<Result<Vec<Completion>>> {
16882 self.update(cx, |project, cx| {
16883 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16884 let project_completions = project.completions(buffer, buffer_position, options, cx);
16885 cx.background_spawn(async move {
16886 let mut completions = project_completions.await?;
16887 let snippets_completions = snippets.await?;
16888 completions.extend(snippets_completions);
16889 Ok(completions)
16890 })
16891 })
16892 }
16893
16894 fn resolve_completions(
16895 &self,
16896 buffer: Entity<Buffer>,
16897 completion_indices: Vec<usize>,
16898 completions: Rc<RefCell<Box<[Completion]>>>,
16899 cx: &mut Context<Editor>,
16900 ) -> Task<Result<bool>> {
16901 self.update(cx, |project, cx| {
16902 project.lsp_store().update(cx, |lsp_store, cx| {
16903 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16904 })
16905 })
16906 }
16907
16908 fn apply_additional_edits_for_completion(
16909 &self,
16910 buffer: Entity<Buffer>,
16911 completions: Rc<RefCell<Box<[Completion]>>>,
16912 completion_index: usize,
16913 push_to_history: bool,
16914 cx: &mut Context<Editor>,
16915 ) -> Task<Result<Option<language::Transaction>>> {
16916 self.update(cx, |project, cx| {
16917 project.lsp_store().update(cx, |lsp_store, cx| {
16918 lsp_store.apply_additional_edits_for_completion(
16919 buffer,
16920 completions,
16921 completion_index,
16922 push_to_history,
16923 cx,
16924 )
16925 })
16926 })
16927 }
16928
16929 fn is_completion_trigger(
16930 &self,
16931 buffer: &Entity<Buffer>,
16932 position: language::Anchor,
16933 text: &str,
16934 trigger_in_words: bool,
16935 cx: &mut Context<Editor>,
16936 ) -> bool {
16937 let mut chars = text.chars();
16938 let char = if let Some(char) = chars.next() {
16939 char
16940 } else {
16941 return false;
16942 };
16943 if chars.next().is_some() {
16944 return false;
16945 }
16946
16947 let buffer = buffer.read(cx);
16948 let snapshot = buffer.snapshot();
16949 if !snapshot.settings_at(position, cx).show_completions_on_input {
16950 return false;
16951 }
16952 let classifier = snapshot.char_classifier_at(position).for_completion(true);
16953 if trigger_in_words && classifier.is_word(char) {
16954 return true;
16955 }
16956
16957 buffer.completion_triggers().contains(text)
16958 }
16959}
16960
16961impl SemanticsProvider for Entity<Project> {
16962 fn hover(
16963 &self,
16964 buffer: &Entity<Buffer>,
16965 position: text::Anchor,
16966 cx: &mut App,
16967 ) -> Option<Task<Vec<project::Hover>>> {
16968 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16969 }
16970
16971 fn document_highlights(
16972 &self,
16973 buffer: &Entity<Buffer>,
16974 position: text::Anchor,
16975 cx: &mut App,
16976 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16977 Some(self.update(cx, |project, cx| {
16978 project.document_highlights(buffer, position, cx)
16979 }))
16980 }
16981
16982 fn definitions(
16983 &self,
16984 buffer: &Entity<Buffer>,
16985 position: text::Anchor,
16986 kind: GotoDefinitionKind,
16987 cx: &mut App,
16988 ) -> Option<Task<Result<Vec<LocationLink>>>> {
16989 Some(self.update(cx, |project, cx| match kind {
16990 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16991 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16992 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16993 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16994 }))
16995 }
16996
16997 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16998 // TODO: make this work for remote projects
16999 self.update(cx, |this, cx| {
17000 buffer.update(cx, |buffer, cx| {
17001 this.any_language_server_supports_inlay_hints(buffer, cx)
17002 })
17003 })
17004 }
17005
17006 fn inlay_hints(
17007 &self,
17008 buffer_handle: Entity<Buffer>,
17009 range: Range<text::Anchor>,
17010 cx: &mut App,
17011 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17012 Some(self.update(cx, |project, cx| {
17013 project.inlay_hints(buffer_handle, range, cx)
17014 }))
17015 }
17016
17017 fn resolve_inlay_hint(
17018 &self,
17019 hint: InlayHint,
17020 buffer_handle: Entity<Buffer>,
17021 server_id: LanguageServerId,
17022 cx: &mut App,
17023 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17024 Some(self.update(cx, |project, cx| {
17025 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17026 }))
17027 }
17028
17029 fn range_for_rename(
17030 &self,
17031 buffer: &Entity<Buffer>,
17032 position: text::Anchor,
17033 cx: &mut App,
17034 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17035 Some(self.update(cx, |project, cx| {
17036 let buffer = buffer.clone();
17037 let task = project.prepare_rename(buffer.clone(), position, cx);
17038 cx.spawn(|_, mut cx| async move {
17039 Ok(match task.await? {
17040 PrepareRenameResponse::Success(range) => Some(range),
17041 PrepareRenameResponse::InvalidPosition => None,
17042 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17043 // Fallback on using TreeSitter info to determine identifier range
17044 buffer.update(&mut cx, |buffer, _| {
17045 let snapshot = buffer.snapshot();
17046 let (range, kind) = snapshot.surrounding_word(position);
17047 if kind != Some(CharKind::Word) {
17048 return None;
17049 }
17050 Some(
17051 snapshot.anchor_before(range.start)
17052 ..snapshot.anchor_after(range.end),
17053 )
17054 })?
17055 }
17056 })
17057 })
17058 }))
17059 }
17060
17061 fn perform_rename(
17062 &self,
17063 buffer: &Entity<Buffer>,
17064 position: text::Anchor,
17065 new_name: String,
17066 cx: &mut App,
17067 ) -> Option<Task<Result<ProjectTransaction>>> {
17068 Some(self.update(cx, |project, cx| {
17069 project.perform_rename(buffer.clone(), position, new_name, cx)
17070 }))
17071 }
17072}
17073
17074fn inlay_hint_settings(
17075 location: Anchor,
17076 snapshot: &MultiBufferSnapshot,
17077 cx: &mut Context<Editor>,
17078) -> InlayHintSettings {
17079 let file = snapshot.file_at(location);
17080 let language = snapshot.language_at(location).map(|l| l.name());
17081 language_settings(language, file, cx).inlay_hints
17082}
17083
17084fn consume_contiguous_rows(
17085 contiguous_row_selections: &mut Vec<Selection<Point>>,
17086 selection: &Selection<Point>,
17087 display_map: &DisplaySnapshot,
17088 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17089) -> (MultiBufferRow, MultiBufferRow) {
17090 contiguous_row_selections.push(selection.clone());
17091 let start_row = MultiBufferRow(selection.start.row);
17092 let mut end_row = ending_row(selection, display_map);
17093
17094 while let Some(next_selection) = selections.peek() {
17095 if next_selection.start.row <= end_row.0 {
17096 end_row = ending_row(next_selection, display_map);
17097 contiguous_row_selections.push(selections.next().unwrap().clone());
17098 } else {
17099 break;
17100 }
17101 }
17102 (start_row, end_row)
17103}
17104
17105fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17106 if next_selection.end.column > 0 || next_selection.is_empty() {
17107 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17108 } else {
17109 MultiBufferRow(next_selection.end.row)
17110 }
17111}
17112
17113impl EditorSnapshot {
17114 pub fn remote_selections_in_range<'a>(
17115 &'a self,
17116 range: &'a Range<Anchor>,
17117 collaboration_hub: &dyn CollaborationHub,
17118 cx: &'a App,
17119 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17120 let participant_names = collaboration_hub.user_names(cx);
17121 let participant_indices = collaboration_hub.user_participant_indices(cx);
17122 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17123 let collaborators_by_replica_id = collaborators_by_peer_id
17124 .iter()
17125 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17126 .collect::<HashMap<_, _>>();
17127 self.buffer_snapshot
17128 .selections_in_range(range, false)
17129 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17130 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17131 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17132 let user_name = participant_names.get(&collaborator.user_id).cloned();
17133 Some(RemoteSelection {
17134 replica_id,
17135 selection,
17136 cursor_shape,
17137 line_mode,
17138 participant_index,
17139 peer_id: collaborator.peer_id,
17140 user_name,
17141 })
17142 })
17143 }
17144
17145 pub fn hunks_for_ranges(
17146 &self,
17147 ranges: impl IntoIterator<Item = Range<Point>>,
17148 ) -> Vec<MultiBufferDiffHunk> {
17149 let mut hunks = Vec::new();
17150 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17151 HashMap::default();
17152 for query_range in ranges {
17153 let query_rows =
17154 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17155 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17156 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17157 ) {
17158 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
17159 // when the caret is just above or just below the deleted hunk.
17160 let allow_adjacent = hunk.status().is_deleted();
17161 let related_to_selection = if allow_adjacent {
17162 hunk.row_range.overlaps(&query_rows)
17163 || hunk.row_range.start == query_rows.end
17164 || hunk.row_range.end == query_rows.start
17165 } else {
17166 hunk.row_range.overlaps(&query_rows)
17167 };
17168 if related_to_selection {
17169 if !processed_buffer_rows
17170 .entry(hunk.buffer_id)
17171 .or_default()
17172 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17173 {
17174 continue;
17175 }
17176 hunks.push(hunk);
17177 }
17178 }
17179 }
17180
17181 hunks
17182 }
17183
17184 fn display_diff_hunks_for_rows<'a>(
17185 &'a self,
17186 display_rows: Range<DisplayRow>,
17187 folded_buffers: &'a HashSet<BufferId>,
17188 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17189 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17190 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17191
17192 self.buffer_snapshot
17193 .diff_hunks_in_range(buffer_start..buffer_end)
17194 .filter_map(|hunk| {
17195 if folded_buffers.contains(&hunk.buffer_id) {
17196 return None;
17197 }
17198
17199 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17200 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17201
17202 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17203 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17204
17205 let display_hunk = if hunk_display_start.column() != 0 {
17206 DisplayDiffHunk::Folded {
17207 display_row: hunk_display_start.row(),
17208 }
17209 } else {
17210 let mut end_row = hunk_display_end.row();
17211 if hunk_display_end.column() > 0 {
17212 end_row.0 += 1;
17213 }
17214 DisplayDiffHunk::Unfolded {
17215 status: hunk.status(),
17216 diff_base_byte_range: hunk.diff_base_byte_range,
17217 display_row_range: hunk_display_start.row()..end_row,
17218 multi_buffer_range: Anchor::range_in_buffer(
17219 hunk.excerpt_id,
17220 hunk.buffer_id,
17221 hunk.buffer_range,
17222 ),
17223 }
17224 };
17225
17226 Some(display_hunk)
17227 })
17228 }
17229
17230 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17231 self.display_snapshot.buffer_snapshot.language_at(position)
17232 }
17233
17234 pub fn is_focused(&self) -> bool {
17235 self.is_focused
17236 }
17237
17238 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17239 self.placeholder_text.as_ref()
17240 }
17241
17242 pub fn scroll_position(&self) -> gpui::Point<f32> {
17243 self.scroll_anchor.scroll_position(&self.display_snapshot)
17244 }
17245
17246 fn gutter_dimensions(
17247 &self,
17248 font_id: FontId,
17249 font_size: Pixels,
17250 max_line_number_width: Pixels,
17251 cx: &App,
17252 ) -> Option<GutterDimensions> {
17253 if !self.show_gutter {
17254 return None;
17255 }
17256
17257 let descent = cx.text_system().descent(font_id, font_size);
17258 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17259 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17260
17261 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17262 matches!(
17263 ProjectSettings::get_global(cx).git.git_gutter,
17264 Some(GitGutterSetting::TrackedFiles)
17265 )
17266 });
17267 let gutter_settings = EditorSettings::get_global(cx).gutter;
17268 let show_line_numbers = self
17269 .show_line_numbers
17270 .unwrap_or(gutter_settings.line_numbers);
17271 let line_gutter_width = if show_line_numbers {
17272 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17273 let min_width_for_number_on_gutter = em_advance * 4.0;
17274 max_line_number_width.max(min_width_for_number_on_gutter)
17275 } else {
17276 0.0.into()
17277 };
17278
17279 let show_code_actions = self
17280 .show_code_actions
17281 .unwrap_or(gutter_settings.code_actions);
17282
17283 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17284
17285 let git_blame_entries_width =
17286 self.git_blame_gutter_max_author_length
17287 .map(|max_author_length| {
17288 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17289
17290 /// The number of characters to dedicate to gaps and margins.
17291 const SPACING_WIDTH: usize = 4;
17292
17293 let max_char_count = max_author_length
17294 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17295 + ::git::SHORT_SHA_LENGTH
17296 + MAX_RELATIVE_TIMESTAMP.len()
17297 + SPACING_WIDTH;
17298
17299 em_advance * max_char_count
17300 });
17301
17302 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17303 left_padding += if show_code_actions || show_runnables {
17304 em_width * 3.0
17305 } else if show_git_gutter && show_line_numbers {
17306 em_width * 2.0
17307 } else if show_git_gutter || show_line_numbers {
17308 em_width
17309 } else {
17310 px(0.)
17311 };
17312
17313 let right_padding = if gutter_settings.folds && show_line_numbers {
17314 em_width * 4.0
17315 } else if gutter_settings.folds {
17316 em_width * 3.0
17317 } else if show_line_numbers {
17318 em_width
17319 } else {
17320 px(0.)
17321 };
17322
17323 Some(GutterDimensions {
17324 left_padding,
17325 right_padding,
17326 width: line_gutter_width + left_padding + right_padding,
17327 margin: -descent,
17328 git_blame_entries_width,
17329 })
17330 }
17331
17332 pub fn render_crease_toggle(
17333 &self,
17334 buffer_row: MultiBufferRow,
17335 row_contains_cursor: bool,
17336 editor: Entity<Editor>,
17337 window: &mut Window,
17338 cx: &mut App,
17339 ) -> Option<AnyElement> {
17340 let folded = self.is_line_folded(buffer_row);
17341 let mut is_foldable = false;
17342
17343 if let Some(crease) = self
17344 .crease_snapshot
17345 .query_row(buffer_row, &self.buffer_snapshot)
17346 {
17347 is_foldable = true;
17348 match crease {
17349 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17350 if let Some(render_toggle) = render_toggle {
17351 let toggle_callback =
17352 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17353 if folded {
17354 editor.update(cx, |editor, cx| {
17355 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17356 });
17357 } else {
17358 editor.update(cx, |editor, cx| {
17359 editor.unfold_at(
17360 &crate::UnfoldAt { buffer_row },
17361 window,
17362 cx,
17363 )
17364 });
17365 }
17366 });
17367 return Some((render_toggle)(
17368 buffer_row,
17369 folded,
17370 toggle_callback,
17371 window,
17372 cx,
17373 ));
17374 }
17375 }
17376 }
17377 }
17378
17379 is_foldable |= self.starts_indent(buffer_row);
17380
17381 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17382 Some(
17383 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17384 .toggle_state(folded)
17385 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17386 if folded {
17387 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17388 } else {
17389 this.fold_at(&FoldAt { buffer_row }, window, cx);
17390 }
17391 }))
17392 .into_any_element(),
17393 )
17394 } else {
17395 None
17396 }
17397 }
17398
17399 pub fn render_crease_trailer(
17400 &self,
17401 buffer_row: MultiBufferRow,
17402 window: &mut Window,
17403 cx: &mut App,
17404 ) -> Option<AnyElement> {
17405 let folded = self.is_line_folded(buffer_row);
17406 if let Crease::Inline { render_trailer, .. } = self
17407 .crease_snapshot
17408 .query_row(buffer_row, &self.buffer_snapshot)?
17409 {
17410 let render_trailer = render_trailer.as_ref()?;
17411 Some(render_trailer(buffer_row, folded, window, cx))
17412 } else {
17413 None
17414 }
17415 }
17416}
17417
17418impl Deref for EditorSnapshot {
17419 type Target = DisplaySnapshot;
17420
17421 fn deref(&self) -> &Self::Target {
17422 &self.display_snapshot
17423 }
17424}
17425
17426#[derive(Clone, Debug, PartialEq, Eq)]
17427pub enum EditorEvent {
17428 InputIgnored {
17429 text: Arc<str>,
17430 },
17431 InputHandled {
17432 utf16_range_to_replace: Option<Range<isize>>,
17433 text: Arc<str>,
17434 },
17435 ExcerptsAdded {
17436 buffer: Entity<Buffer>,
17437 predecessor: ExcerptId,
17438 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17439 },
17440 ExcerptsRemoved {
17441 ids: Vec<ExcerptId>,
17442 },
17443 BufferFoldToggled {
17444 ids: Vec<ExcerptId>,
17445 folded: bool,
17446 },
17447 ExcerptsEdited {
17448 ids: Vec<ExcerptId>,
17449 },
17450 ExcerptsExpanded {
17451 ids: Vec<ExcerptId>,
17452 },
17453 BufferEdited,
17454 Edited {
17455 transaction_id: clock::Lamport,
17456 },
17457 Reparsed(BufferId),
17458 Focused,
17459 FocusedIn,
17460 Blurred,
17461 DirtyChanged,
17462 Saved,
17463 TitleChanged,
17464 DiffBaseChanged,
17465 SelectionsChanged {
17466 local: bool,
17467 },
17468 ScrollPositionChanged {
17469 local: bool,
17470 autoscroll: bool,
17471 },
17472 Closed,
17473 TransactionUndone {
17474 transaction_id: clock::Lamport,
17475 },
17476 TransactionBegun {
17477 transaction_id: clock::Lamport,
17478 },
17479 Reloaded,
17480 CursorShapeChanged,
17481}
17482
17483impl EventEmitter<EditorEvent> for Editor {}
17484
17485impl Focusable for Editor {
17486 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17487 self.focus_handle.clone()
17488 }
17489}
17490
17491impl Render for Editor {
17492 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17493 let settings = ThemeSettings::get_global(cx);
17494
17495 let mut text_style = match self.mode {
17496 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17497 color: cx.theme().colors().editor_foreground,
17498 font_family: settings.ui_font.family.clone(),
17499 font_features: settings.ui_font.features.clone(),
17500 font_fallbacks: settings.ui_font.fallbacks.clone(),
17501 font_size: rems(0.875).into(),
17502 font_weight: settings.ui_font.weight,
17503 line_height: relative(settings.buffer_line_height.value()),
17504 ..Default::default()
17505 },
17506 EditorMode::Full => TextStyle {
17507 color: cx.theme().colors().editor_foreground,
17508 font_family: settings.buffer_font.family.clone(),
17509 font_features: settings.buffer_font.features.clone(),
17510 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17511 font_size: settings.buffer_font_size(cx).into(),
17512 font_weight: settings.buffer_font.weight,
17513 line_height: relative(settings.buffer_line_height.value()),
17514 ..Default::default()
17515 },
17516 };
17517 if let Some(text_style_refinement) = &self.text_style_refinement {
17518 text_style.refine(text_style_refinement)
17519 }
17520
17521 let background = match self.mode {
17522 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17523 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17524 EditorMode::Full => cx.theme().colors().editor_background,
17525 };
17526
17527 EditorElement::new(
17528 &cx.entity(),
17529 EditorStyle {
17530 background,
17531 local_player: cx.theme().players().local(),
17532 text: text_style,
17533 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17534 syntax: cx.theme().syntax().clone(),
17535 status: cx.theme().status().clone(),
17536 inlay_hints_style: make_inlay_hints_style(cx),
17537 inline_completion_styles: make_suggestion_styles(cx),
17538 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17539 },
17540 )
17541 }
17542}
17543
17544impl EntityInputHandler for Editor {
17545 fn text_for_range(
17546 &mut self,
17547 range_utf16: Range<usize>,
17548 adjusted_range: &mut Option<Range<usize>>,
17549 _: &mut Window,
17550 cx: &mut Context<Self>,
17551 ) -> Option<String> {
17552 let snapshot = self.buffer.read(cx).read(cx);
17553 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17554 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17555 if (start.0..end.0) != range_utf16 {
17556 adjusted_range.replace(start.0..end.0);
17557 }
17558 Some(snapshot.text_for_range(start..end).collect())
17559 }
17560
17561 fn selected_text_range(
17562 &mut self,
17563 ignore_disabled_input: bool,
17564 _: &mut Window,
17565 cx: &mut Context<Self>,
17566 ) -> Option<UTF16Selection> {
17567 // Prevent the IME menu from appearing when holding down an alphabetic key
17568 // while input is disabled.
17569 if !ignore_disabled_input && !self.input_enabled {
17570 return None;
17571 }
17572
17573 let selection = self.selections.newest::<OffsetUtf16>(cx);
17574 let range = selection.range();
17575
17576 Some(UTF16Selection {
17577 range: range.start.0..range.end.0,
17578 reversed: selection.reversed,
17579 })
17580 }
17581
17582 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17583 let snapshot = self.buffer.read(cx).read(cx);
17584 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17585 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17586 }
17587
17588 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17589 self.clear_highlights::<InputComposition>(cx);
17590 self.ime_transaction.take();
17591 }
17592
17593 fn replace_text_in_range(
17594 &mut self,
17595 range_utf16: Option<Range<usize>>,
17596 text: &str,
17597 window: &mut Window,
17598 cx: &mut Context<Self>,
17599 ) {
17600 if !self.input_enabled {
17601 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17602 return;
17603 }
17604
17605 self.transact(window, cx, |this, window, cx| {
17606 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17607 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17608 Some(this.selection_replacement_ranges(range_utf16, cx))
17609 } else {
17610 this.marked_text_ranges(cx)
17611 };
17612
17613 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17614 let newest_selection_id = this.selections.newest_anchor().id;
17615 this.selections
17616 .all::<OffsetUtf16>(cx)
17617 .iter()
17618 .zip(ranges_to_replace.iter())
17619 .find_map(|(selection, range)| {
17620 if selection.id == newest_selection_id {
17621 Some(
17622 (range.start.0 as isize - selection.head().0 as isize)
17623 ..(range.end.0 as isize - selection.head().0 as isize),
17624 )
17625 } else {
17626 None
17627 }
17628 })
17629 });
17630
17631 cx.emit(EditorEvent::InputHandled {
17632 utf16_range_to_replace: range_to_replace,
17633 text: text.into(),
17634 });
17635
17636 if let Some(new_selected_ranges) = new_selected_ranges {
17637 this.change_selections(None, window, cx, |selections| {
17638 selections.select_ranges(new_selected_ranges)
17639 });
17640 this.backspace(&Default::default(), window, cx);
17641 }
17642
17643 this.handle_input(text, window, cx);
17644 });
17645
17646 if let Some(transaction) = self.ime_transaction {
17647 self.buffer.update(cx, |buffer, cx| {
17648 buffer.group_until_transaction(transaction, cx);
17649 });
17650 }
17651
17652 self.unmark_text(window, cx);
17653 }
17654
17655 fn replace_and_mark_text_in_range(
17656 &mut self,
17657 range_utf16: Option<Range<usize>>,
17658 text: &str,
17659 new_selected_range_utf16: Option<Range<usize>>,
17660 window: &mut Window,
17661 cx: &mut Context<Self>,
17662 ) {
17663 if !self.input_enabled {
17664 return;
17665 }
17666
17667 let transaction = self.transact(window, cx, |this, window, cx| {
17668 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17669 let snapshot = this.buffer.read(cx).read(cx);
17670 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17671 for marked_range in &mut marked_ranges {
17672 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17673 marked_range.start.0 += relative_range_utf16.start;
17674 marked_range.start =
17675 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17676 marked_range.end =
17677 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17678 }
17679 }
17680 Some(marked_ranges)
17681 } else if let Some(range_utf16) = range_utf16 {
17682 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17683 Some(this.selection_replacement_ranges(range_utf16, cx))
17684 } else {
17685 None
17686 };
17687
17688 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17689 let newest_selection_id = this.selections.newest_anchor().id;
17690 this.selections
17691 .all::<OffsetUtf16>(cx)
17692 .iter()
17693 .zip(ranges_to_replace.iter())
17694 .find_map(|(selection, range)| {
17695 if selection.id == newest_selection_id {
17696 Some(
17697 (range.start.0 as isize - selection.head().0 as isize)
17698 ..(range.end.0 as isize - selection.head().0 as isize),
17699 )
17700 } else {
17701 None
17702 }
17703 })
17704 });
17705
17706 cx.emit(EditorEvent::InputHandled {
17707 utf16_range_to_replace: range_to_replace,
17708 text: text.into(),
17709 });
17710
17711 if let Some(ranges) = ranges_to_replace {
17712 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17713 }
17714
17715 let marked_ranges = {
17716 let snapshot = this.buffer.read(cx).read(cx);
17717 this.selections
17718 .disjoint_anchors()
17719 .iter()
17720 .map(|selection| {
17721 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17722 })
17723 .collect::<Vec<_>>()
17724 };
17725
17726 if text.is_empty() {
17727 this.unmark_text(window, cx);
17728 } else {
17729 this.highlight_text::<InputComposition>(
17730 marked_ranges.clone(),
17731 HighlightStyle {
17732 underline: Some(UnderlineStyle {
17733 thickness: px(1.),
17734 color: None,
17735 wavy: false,
17736 }),
17737 ..Default::default()
17738 },
17739 cx,
17740 );
17741 }
17742
17743 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17744 let use_autoclose = this.use_autoclose;
17745 let use_auto_surround = this.use_auto_surround;
17746 this.set_use_autoclose(false);
17747 this.set_use_auto_surround(false);
17748 this.handle_input(text, window, cx);
17749 this.set_use_autoclose(use_autoclose);
17750 this.set_use_auto_surround(use_auto_surround);
17751
17752 if let Some(new_selected_range) = new_selected_range_utf16 {
17753 let snapshot = this.buffer.read(cx).read(cx);
17754 let new_selected_ranges = marked_ranges
17755 .into_iter()
17756 .map(|marked_range| {
17757 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17758 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17759 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17760 snapshot.clip_offset_utf16(new_start, Bias::Left)
17761 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17762 })
17763 .collect::<Vec<_>>();
17764
17765 drop(snapshot);
17766 this.change_selections(None, window, cx, |selections| {
17767 selections.select_ranges(new_selected_ranges)
17768 });
17769 }
17770 });
17771
17772 self.ime_transaction = self.ime_transaction.or(transaction);
17773 if let Some(transaction) = self.ime_transaction {
17774 self.buffer.update(cx, |buffer, cx| {
17775 buffer.group_until_transaction(transaction, cx);
17776 });
17777 }
17778
17779 if self.text_highlights::<InputComposition>(cx).is_none() {
17780 self.ime_transaction.take();
17781 }
17782 }
17783
17784 fn bounds_for_range(
17785 &mut self,
17786 range_utf16: Range<usize>,
17787 element_bounds: gpui::Bounds<Pixels>,
17788 window: &mut Window,
17789 cx: &mut Context<Self>,
17790 ) -> Option<gpui::Bounds<Pixels>> {
17791 let text_layout_details = self.text_layout_details(window);
17792 let gpui::Size {
17793 width: em_width,
17794 height: line_height,
17795 } = self.character_size(window);
17796
17797 let snapshot = self.snapshot(window, cx);
17798 let scroll_position = snapshot.scroll_position();
17799 let scroll_left = scroll_position.x * em_width;
17800
17801 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17802 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17803 + self.gutter_dimensions.width
17804 + self.gutter_dimensions.margin;
17805 let y = line_height * (start.row().as_f32() - scroll_position.y);
17806
17807 Some(Bounds {
17808 origin: element_bounds.origin + point(x, y),
17809 size: size(em_width, line_height),
17810 })
17811 }
17812
17813 fn character_index_for_point(
17814 &mut self,
17815 point: gpui::Point<Pixels>,
17816 _window: &mut Window,
17817 _cx: &mut Context<Self>,
17818 ) -> Option<usize> {
17819 let position_map = self.last_position_map.as_ref()?;
17820 if !position_map.text_hitbox.contains(&point) {
17821 return None;
17822 }
17823 let display_point = position_map.point_for_position(point).previous_valid;
17824 let anchor = position_map
17825 .snapshot
17826 .display_point_to_anchor(display_point, Bias::Left);
17827 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17828 Some(utf16_offset.0)
17829 }
17830}
17831
17832trait SelectionExt {
17833 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17834 fn spanned_rows(
17835 &self,
17836 include_end_if_at_line_start: bool,
17837 map: &DisplaySnapshot,
17838 ) -> Range<MultiBufferRow>;
17839}
17840
17841impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17842 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17843 let start = self
17844 .start
17845 .to_point(&map.buffer_snapshot)
17846 .to_display_point(map);
17847 let end = self
17848 .end
17849 .to_point(&map.buffer_snapshot)
17850 .to_display_point(map);
17851 if self.reversed {
17852 end..start
17853 } else {
17854 start..end
17855 }
17856 }
17857
17858 fn spanned_rows(
17859 &self,
17860 include_end_if_at_line_start: bool,
17861 map: &DisplaySnapshot,
17862 ) -> Range<MultiBufferRow> {
17863 let start = self.start.to_point(&map.buffer_snapshot);
17864 let mut end = self.end.to_point(&map.buffer_snapshot);
17865 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17866 end.row -= 1;
17867 }
17868
17869 let buffer_start = map.prev_line_boundary(start).0;
17870 let buffer_end = map.next_line_boundary(end).0;
17871 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17872 }
17873}
17874
17875impl<T: InvalidationRegion> InvalidationStack<T> {
17876 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17877 where
17878 S: Clone + ToOffset,
17879 {
17880 while let Some(region) = self.last() {
17881 let all_selections_inside_invalidation_ranges =
17882 if selections.len() == region.ranges().len() {
17883 selections
17884 .iter()
17885 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17886 .all(|(selection, invalidation_range)| {
17887 let head = selection.head().to_offset(buffer);
17888 invalidation_range.start <= head && invalidation_range.end >= head
17889 })
17890 } else {
17891 false
17892 };
17893
17894 if all_selections_inside_invalidation_ranges {
17895 break;
17896 } else {
17897 self.pop();
17898 }
17899 }
17900 }
17901}
17902
17903impl<T> Default for InvalidationStack<T> {
17904 fn default() -> Self {
17905 Self(Default::default())
17906 }
17907}
17908
17909impl<T> Deref for InvalidationStack<T> {
17910 type Target = Vec<T>;
17911
17912 fn deref(&self) -> &Self::Target {
17913 &self.0
17914 }
17915}
17916
17917impl<T> DerefMut for InvalidationStack<T> {
17918 fn deref_mut(&mut self) -> &mut Self::Target {
17919 &mut self.0
17920 }
17921}
17922
17923impl InvalidationRegion for SnippetState {
17924 fn ranges(&self) -> &[Range<Anchor>] {
17925 &self.ranges[self.active_index]
17926 }
17927}
17928
17929pub fn diagnostic_block_renderer(
17930 diagnostic: Diagnostic,
17931 max_message_rows: Option<u8>,
17932 allow_closing: bool,
17933) -> RenderBlock {
17934 let (text_without_backticks, code_ranges) =
17935 highlight_diagnostic_message(&diagnostic, max_message_rows);
17936
17937 Arc::new(move |cx: &mut BlockContext| {
17938 let group_id: SharedString = cx.block_id.to_string().into();
17939
17940 let mut text_style = cx.window.text_style().clone();
17941 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17942 let theme_settings = ThemeSettings::get_global(cx);
17943 text_style.font_family = theme_settings.buffer_font.family.clone();
17944 text_style.font_style = theme_settings.buffer_font.style;
17945 text_style.font_features = theme_settings.buffer_font.features.clone();
17946 text_style.font_weight = theme_settings.buffer_font.weight;
17947
17948 let multi_line_diagnostic = diagnostic.message.contains('\n');
17949
17950 let buttons = |diagnostic: &Diagnostic| {
17951 if multi_line_diagnostic {
17952 v_flex()
17953 } else {
17954 h_flex()
17955 }
17956 .when(allow_closing, |div| {
17957 div.children(diagnostic.is_primary.then(|| {
17958 IconButton::new("close-block", IconName::XCircle)
17959 .icon_color(Color::Muted)
17960 .size(ButtonSize::Compact)
17961 .style(ButtonStyle::Transparent)
17962 .visible_on_hover(group_id.clone())
17963 .on_click(move |_click, window, cx| {
17964 window.dispatch_action(Box::new(Cancel), cx)
17965 })
17966 .tooltip(|window, cx| {
17967 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17968 })
17969 }))
17970 })
17971 .child(
17972 IconButton::new("copy-block", IconName::Copy)
17973 .icon_color(Color::Muted)
17974 .size(ButtonSize::Compact)
17975 .style(ButtonStyle::Transparent)
17976 .visible_on_hover(group_id.clone())
17977 .on_click({
17978 let message = diagnostic.message.clone();
17979 move |_click, _, cx| {
17980 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17981 }
17982 })
17983 .tooltip(Tooltip::text("Copy diagnostic message")),
17984 )
17985 };
17986
17987 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17988 AvailableSpace::min_size(),
17989 cx.window,
17990 cx.app,
17991 );
17992
17993 h_flex()
17994 .id(cx.block_id)
17995 .group(group_id.clone())
17996 .relative()
17997 .size_full()
17998 .block_mouse_down()
17999 .pl(cx.gutter_dimensions.width)
18000 .w(cx.max_width - cx.gutter_dimensions.full_width())
18001 .child(
18002 div()
18003 .flex()
18004 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18005 .flex_shrink(),
18006 )
18007 .child(buttons(&diagnostic))
18008 .child(div().flex().flex_shrink_0().child(
18009 StyledText::new(text_without_backticks.clone()).with_highlights(
18010 &text_style,
18011 code_ranges.iter().map(|range| {
18012 (
18013 range.clone(),
18014 HighlightStyle {
18015 font_weight: Some(FontWeight::BOLD),
18016 ..Default::default()
18017 },
18018 )
18019 }),
18020 ),
18021 ))
18022 .into_any_element()
18023 })
18024}
18025
18026fn inline_completion_edit_text(
18027 current_snapshot: &BufferSnapshot,
18028 edits: &[(Range<Anchor>, String)],
18029 edit_preview: &EditPreview,
18030 include_deletions: bool,
18031 cx: &App,
18032) -> HighlightedText {
18033 let edits = edits
18034 .iter()
18035 .map(|(anchor, text)| {
18036 (
18037 anchor.start.text_anchor..anchor.end.text_anchor,
18038 text.clone(),
18039 )
18040 })
18041 .collect::<Vec<_>>();
18042
18043 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18044}
18045
18046pub fn highlight_diagnostic_message(
18047 diagnostic: &Diagnostic,
18048 mut max_message_rows: Option<u8>,
18049) -> (SharedString, Vec<Range<usize>>) {
18050 let mut text_without_backticks = String::new();
18051 let mut code_ranges = Vec::new();
18052
18053 if let Some(source) = &diagnostic.source {
18054 text_without_backticks.push_str(source);
18055 code_ranges.push(0..source.len());
18056 text_without_backticks.push_str(": ");
18057 }
18058
18059 let mut prev_offset = 0;
18060 let mut in_code_block = false;
18061 let has_row_limit = max_message_rows.is_some();
18062 let mut newline_indices = diagnostic
18063 .message
18064 .match_indices('\n')
18065 .filter(|_| has_row_limit)
18066 .map(|(ix, _)| ix)
18067 .fuse()
18068 .peekable();
18069
18070 for (quote_ix, _) in diagnostic
18071 .message
18072 .match_indices('`')
18073 .chain([(diagnostic.message.len(), "")])
18074 {
18075 let mut first_newline_ix = None;
18076 let mut last_newline_ix = None;
18077 while let Some(newline_ix) = newline_indices.peek() {
18078 if *newline_ix < quote_ix {
18079 if first_newline_ix.is_none() {
18080 first_newline_ix = Some(*newline_ix);
18081 }
18082 last_newline_ix = Some(*newline_ix);
18083
18084 if let Some(rows_left) = &mut max_message_rows {
18085 if *rows_left == 0 {
18086 break;
18087 } else {
18088 *rows_left -= 1;
18089 }
18090 }
18091 let _ = newline_indices.next();
18092 } else {
18093 break;
18094 }
18095 }
18096 let prev_len = text_without_backticks.len();
18097 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18098 text_without_backticks.push_str(new_text);
18099 if in_code_block {
18100 code_ranges.push(prev_len..text_without_backticks.len());
18101 }
18102 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18103 in_code_block = !in_code_block;
18104 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18105 text_without_backticks.push_str("...");
18106 break;
18107 }
18108 }
18109
18110 (text_without_backticks.into(), code_ranges)
18111}
18112
18113fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18114 match severity {
18115 DiagnosticSeverity::ERROR => colors.error,
18116 DiagnosticSeverity::WARNING => colors.warning,
18117 DiagnosticSeverity::INFORMATION => colors.info,
18118 DiagnosticSeverity::HINT => colors.info,
18119 _ => colors.ignored,
18120 }
18121}
18122
18123pub fn styled_runs_for_code_label<'a>(
18124 label: &'a CodeLabel,
18125 syntax_theme: &'a theme::SyntaxTheme,
18126) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18127 let fade_out = HighlightStyle {
18128 fade_out: Some(0.35),
18129 ..Default::default()
18130 };
18131
18132 let mut prev_end = label.filter_range.end;
18133 label
18134 .runs
18135 .iter()
18136 .enumerate()
18137 .flat_map(move |(ix, (range, highlight_id))| {
18138 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18139 style
18140 } else {
18141 return Default::default();
18142 };
18143 let mut muted_style = style;
18144 muted_style.highlight(fade_out);
18145
18146 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18147 if range.start >= label.filter_range.end {
18148 if range.start > prev_end {
18149 runs.push((prev_end..range.start, fade_out));
18150 }
18151 runs.push((range.clone(), muted_style));
18152 } else if range.end <= label.filter_range.end {
18153 runs.push((range.clone(), style));
18154 } else {
18155 runs.push((range.start..label.filter_range.end, style));
18156 runs.push((label.filter_range.end..range.end, muted_style));
18157 }
18158 prev_end = cmp::max(prev_end, range.end);
18159
18160 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18161 runs.push((prev_end..label.text.len(), fade_out));
18162 }
18163
18164 runs
18165 })
18166}
18167
18168pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18169 let mut prev_index = 0;
18170 let mut prev_codepoint: Option<char> = None;
18171 text.char_indices()
18172 .chain([(text.len(), '\0')])
18173 .filter_map(move |(index, codepoint)| {
18174 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18175 let is_boundary = index == text.len()
18176 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18177 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18178 if is_boundary {
18179 let chunk = &text[prev_index..index];
18180 prev_index = index;
18181 Some(chunk)
18182 } else {
18183 None
18184 }
18185 })
18186}
18187
18188pub trait RangeToAnchorExt: Sized {
18189 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18190
18191 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18192 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18193 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18194 }
18195}
18196
18197impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18198 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18199 let start_offset = self.start.to_offset(snapshot);
18200 let end_offset = self.end.to_offset(snapshot);
18201 if start_offset == end_offset {
18202 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18203 } else {
18204 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18205 }
18206 }
18207}
18208
18209pub trait RowExt {
18210 fn as_f32(&self) -> f32;
18211
18212 fn next_row(&self) -> Self;
18213
18214 fn previous_row(&self) -> Self;
18215
18216 fn minus(&self, other: Self) -> u32;
18217}
18218
18219impl RowExt for DisplayRow {
18220 fn as_f32(&self) -> f32 {
18221 self.0 as f32
18222 }
18223
18224 fn next_row(&self) -> Self {
18225 Self(self.0 + 1)
18226 }
18227
18228 fn previous_row(&self) -> Self {
18229 Self(self.0.saturating_sub(1))
18230 }
18231
18232 fn minus(&self, other: Self) -> u32 {
18233 self.0 - other.0
18234 }
18235}
18236
18237impl RowExt for MultiBufferRow {
18238 fn as_f32(&self) -> f32 {
18239 self.0 as f32
18240 }
18241
18242 fn next_row(&self) -> Self {
18243 Self(self.0 + 1)
18244 }
18245
18246 fn previous_row(&self) -> Self {
18247 Self(self.0.saturating_sub(1))
18248 }
18249
18250 fn minus(&self, other: Self) -> u32 {
18251 self.0 - other.0
18252 }
18253}
18254
18255trait RowRangeExt {
18256 type Row;
18257
18258 fn len(&self) -> usize;
18259
18260 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18261}
18262
18263impl RowRangeExt for Range<MultiBufferRow> {
18264 type Row = MultiBufferRow;
18265
18266 fn len(&self) -> usize {
18267 (self.end.0 - self.start.0) as usize
18268 }
18269
18270 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18271 (self.start.0..self.end.0).map(MultiBufferRow)
18272 }
18273}
18274
18275impl RowRangeExt for Range<DisplayRow> {
18276 type Row = DisplayRow;
18277
18278 fn len(&self) -> usize {
18279 (self.end.0 - self.start.0) as usize
18280 }
18281
18282 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18283 (self.start.0..self.end.0).map(DisplayRow)
18284 }
18285}
18286
18287/// If select range has more than one line, we
18288/// just point the cursor to range.start.
18289fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18290 if range.start.row == range.end.row {
18291 range
18292 } else {
18293 range.start..range.start
18294 }
18295}
18296pub struct KillRing(ClipboardItem);
18297impl Global for KillRing {}
18298
18299const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18300
18301fn all_edits_insertions_or_deletions(
18302 edits: &Vec<(Range<Anchor>, String)>,
18303 snapshot: &MultiBufferSnapshot,
18304) -> bool {
18305 let mut all_insertions = true;
18306 let mut all_deletions = true;
18307
18308 for (range, new_text) in edits.iter() {
18309 let range_is_empty = range.to_offset(&snapshot).is_empty();
18310 let text_is_empty = new_text.is_empty();
18311
18312 if range_is_empty != text_is_empty {
18313 if range_is_empty {
18314 all_deletions = false;
18315 } else {
18316 all_insertions = false;
18317 }
18318 } else {
18319 return false;
18320 }
18321
18322 if !all_insertions && !all_deletions {
18323 return false;
18324 }
18325 }
18326 all_insertions || all_deletions
18327}