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::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 sync_selections(
2237 &mut self,
2238 other: Entity<Editor>,
2239 cx: &mut Context<Self>,
2240 ) -> gpui::Subscription {
2241 let other_selections = other.read(cx).selections.disjoint.to_vec();
2242 self.selections.change_with(cx, |selections| {
2243 selections.select_anchors(other_selections);
2244 });
2245
2246 let other_subscription =
2247 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2248 EditorEvent::SelectionsChanged { local: true } => {
2249 let other_selections = other.read(cx).selections.disjoint.to_vec();
2250 if other_selections.is_empty() {
2251 return;
2252 }
2253 this.selections.change_with(cx, |selections| {
2254 selections.select_anchors(other_selections);
2255 });
2256 }
2257 _ => {}
2258 });
2259
2260 let this_subscription =
2261 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2262 EditorEvent::SelectionsChanged { local: true } => {
2263 let these_selections = this.selections.disjoint.to_vec();
2264 if these_selections.is_empty() {
2265 return;
2266 }
2267 other.update(cx, |other_editor, cx| {
2268 other_editor.selections.change_with(cx, |selections| {
2269 selections.select_anchors(these_selections);
2270 })
2271 });
2272 }
2273 _ => {}
2274 });
2275
2276 Subscription::join(other_subscription, this_subscription)
2277 }
2278
2279 pub fn change_selections<R>(
2280 &mut self,
2281 autoscroll: Option<Autoscroll>,
2282 window: &mut Window,
2283 cx: &mut Context<Self>,
2284 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2285 ) -> R {
2286 self.change_selections_inner(autoscroll, true, window, cx, change)
2287 }
2288
2289 fn change_selections_inner<R>(
2290 &mut self,
2291 autoscroll: Option<Autoscroll>,
2292 request_completions: bool,
2293 window: &mut Window,
2294 cx: &mut Context<Self>,
2295 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2296 ) -> R {
2297 let old_cursor_position = self.selections.newest_anchor().head();
2298 self.push_to_selection_history();
2299
2300 let (changed, result) = self.selections.change_with(cx, change);
2301
2302 if changed {
2303 if let Some(autoscroll) = autoscroll {
2304 self.request_autoscroll(autoscroll, cx);
2305 }
2306 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2307
2308 if self.should_open_signature_help_automatically(
2309 &old_cursor_position,
2310 self.signature_help_state.backspace_pressed(),
2311 cx,
2312 ) {
2313 self.show_signature_help(&ShowSignatureHelp, window, cx);
2314 }
2315 self.signature_help_state.set_backspace_pressed(false);
2316 }
2317
2318 result
2319 }
2320
2321 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2322 where
2323 I: IntoIterator<Item = (Range<S>, T)>,
2324 S: ToOffset,
2325 T: Into<Arc<str>>,
2326 {
2327 if self.read_only(cx) {
2328 return;
2329 }
2330
2331 self.buffer
2332 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2333 }
2334
2335 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2336 where
2337 I: IntoIterator<Item = (Range<S>, T)>,
2338 S: ToOffset,
2339 T: Into<Arc<str>>,
2340 {
2341 if self.read_only(cx) {
2342 return;
2343 }
2344
2345 self.buffer.update(cx, |buffer, cx| {
2346 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2347 });
2348 }
2349
2350 pub fn edit_with_block_indent<I, S, T>(
2351 &mut self,
2352 edits: I,
2353 original_start_columns: Vec<u32>,
2354 cx: &mut Context<Self>,
2355 ) where
2356 I: IntoIterator<Item = (Range<S>, T)>,
2357 S: ToOffset,
2358 T: Into<Arc<str>>,
2359 {
2360 if self.read_only(cx) {
2361 return;
2362 }
2363
2364 self.buffer.update(cx, |buffer, cx| {
2365 buffer.edit(
2366 edits,
2367 Some(AutoindentMode::Block {
2368 original_start_columns,
2369 }),
2370 cx,
2371 )
2372 });
2373 }
2374
2375 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2376 self.hide_context_menu(window, cx);
2377
2378 match phase {
2379 SelectPhase::Begin {
2380 position,
2381 add,
2382 click_count,
2383 } => self.begin_selection(position, add, click_count, window, cx),
2384 SelectPhase::BeginColumnar {
2385 position,
2386 goal_column,
2387 reset,
2388 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2389 SelectPhase::Extend {
2390 position,
2391 click_count,
2392 } => self.extend_selection(position, click_count, window, cx),
2393 SelectPhase::Update {
2394 position,
2395 goal_column,
2396 scroll_delta,
2397 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2398 SelectPhase::End => self.end_selection(window, cx),
2399 }
2400 }
2401
2402 fn extend_selection(
2403 &mut self,
2404 position: DisplayPoint,
2405 click_count: usize,
2406 window: &mut Window,
2407 cx: &mut Context<Self>,
2408 ) {
2409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2410 let tail = self.selections.newest::<usize>(cx).tail();
2411 self.begin_selection(position, false, click_count, window, cx);
2412
2413 let position = position.to_offset(&display_map, Bias::Left);
2414 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2415
2416 let mut pending_selection = self
2417 .selections
2418 .pending_anchor()
2419 .expect("extend_selection not called with pending selection");
2420 if position >= tail {
2421 pending_selection.start = tail_anchor;
2422 } else {
2423 pending_selection.end = tail_anchor;
2424 pending_selection.reversed = true;
2425 }
2426
2427 let mut pending_mode = self.selections.pending_mode().unwrap();
2428 match &mut pending_mode {
2429 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2430 _ => {}
2431 }
2432
2433 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2434 s.set_pending(pending_selection, pending_mode)
2435 });
2436 }
2437
2438 fn begin_selection(
2439 &mut self,
2440 position: DisplayPoint,
2441 add: bool,
2442 click_count: usize,
2443 window: &mut Window,
2444 cx: &mut Context<Self>,
2445 ) {
2446 if !self.focus_handle.is_focused(window) {
2447 self.last_focused_descendant = None;
2448 window.focus(&self.focus_handle);
2449 }
2450
2451 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2452 let buffer = &display_map.buffer_snapshot;
2453 let newest_selection = self.selections.newest_anchor().clone();
2454 let position = display_map.clip_point(position, Bias::Left);
2455
2456 let start;
2457 let end;
2458 let mode;
2459 let mut auto_scroll;
2460 match click_count {
2461 1 => {
2462 start = buffer.anchor_before(position.to_point(&display_map));
2463 end = start;
2464 mode = SelectMode::Character;
2465 auto_scroll = true;
2466 }
2467 2 => {
2468 let range = movement::surrounding_word(&display_map, position);
2469 start = buffer.anchor_before(range.start.to_point(&display_map));
2470 end = buffer.anchor_before(range.end.to_point(&display_map));
2471 mode = SelectMode::Word(start..end);
2472 auto_scroll = true;
2473 }
2474 3 => {
2475 let position = display_map
2476 .clip_point(position, Bias::Left)
2477 .to_point(&display_map);
2478 let line_start = display_map.prev_line_boundary(position).0;
2479 let next_line_start = buffer.clip_point(
2480 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2481 Bias::Left,
2482 );
2483 start = buffer.anchor_before(line_start);
2484 end = buffer.anchor_before(next_line_start);
2485 mode = SelectMode::Line(start..end);
2486 auto_scroll = true;
2487 }
2488 _ => {
2489 start = buffer.anchor_before(0);
2490 end = buffer.anchor_before(buffer.len());
2491 mode = SelectMode::All;
2492 auto_scroll = false;
2493 }
2494 }
2495 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2496
2497 let point_to_delete: Option<usize> = {
2498 let selected_points: Vec<Selection<Point>> =
2499 self.selections.disjoint_in_range(start..end, cx);
2500
2501 if !add || click_count > 1 {
2502 None
2503 } else if !selected_points.is_empty() {
2504 Some(selected_points[0].id)
2505 } else {
2506 let clicked_point_already_selected =
2507 self.selections.disjoint.iter().find(|selection| {
2508 selection.start.to_point(buffer) == start.to_point(buffer)
2509 || selection.end.to_point(buffer) == end.to_point(buffer)
2510 });
2511
2512 clicked_point_already_selected.map(|selection| selection.id)
2513 }
2514 };
2515
2516 let selections_count = self.selections.count();
2517
2518 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2519 if let Some(point_to_delete) = point_to_delete {
2520 s.delete(point_to_delete);
2521
2522 if selections_count == 1 {
2523 s.set_pending_anchor_range(start..end, mode);
2524 }
2525 } else {
2526 if !add {
2527 s.clear_disjoint();
2528 } else if click_count > 1 {
2529 s.delete(newest_selection.id)
2530 }
2531
2532 s.set_pending_anchor_range(start..end, mode);
2533 }
2534 });
2535 }
2536
2537 fn begin_columnar_selection(
2538 &mut self,
2539 position: DisplayPoint,
2540 goal_column: u32,
2541 reset: bool,
2542 window: &mut Window,
2543 cx: &mut Context<Self>,
2544 ) {
2545 if !self.focus_handle.is_focused(window) {
2546 self.last_focused_descendant = None;
2547 window.focus(&self.focus_handle);
2548 }
2549
2550 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2551
2552 if reset {
2553 let pointer_position = display_map
2554 .buffer_snapshot
2555 .anchor_before(position.to_point(&display_map));
2556
2557 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2558 s.clear_disjoint();
2559 s.set_pending_anchor_range(
2560 pointer_position..pointer_position,
2561 SelectMode::Character,
2562 );
2563 });
2564 }
2565
2566 let tail = self.selections.newest::<Point>(cx).tail();
2567 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2568
2569 if !reset {
2570 self.select_columns(
2571 tail.to_display_point(&display_map),
2572 position,
2573 goal_column,
2574 &display_map,
2575 window,
2576 cx,
2577 );
2578 }
2579 }
2580
2581 fn update_selection(
2582 &mut self,
2583 position: DisplayPoint,
2584 goal_column: u32,
2585 scroll_delta: gpui::Point<f32>,
2586 window: &mut Window,
2587 cx: &mut Context<Self>,
2588 ) {
2589 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2590
2591 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2592 let tail = tail.to_display_point(&display_map);
2593 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2594 } else if let Some(mut pending) = self.selections.pending_anchor() {
2595 let buffer = self.buffer.read(cx).snapshot(cx);
2596 let head;
2597 let tail;
2598 let mode = self.selections.pending_mode().unwrap();
2599 match &mode {
2600 SelectMode::Character => {
2601 head = position.to_point(&display_map);
2602 tail = pending.tail().to_point(&buffer);
2603 }
2604 SelectMode::Word(original_range) => {
2605 let original_display_range = original_range.start.to_display_point(&display_map)
2606 ..original_range.end.to_display_point(&display_map);
2607 let original_buffer_range = original_display_range.start.to_point(&display_map)
2608 ..original_display_range.end.to_point(&display_map);
2609 if movement::is_inside_word(&display_map, position)
2610 || original_display_range.contains(&position)
2611 {
2612 let word_range = movement::surrounding_word(&display_map, position);
2613 if word_range.start < original_display_range.start {
2614 head = word_range.start.to_point(&display_map);
2615 } else {
2616 head = word_range.end.to_point(&display_map);
2617 }
2618 } else {
2619 head = position.to_point(&display_map);
2620 }
2621
2622 if head <= original_buffer_range.start {
2623 tail = original_buffer_range.end;
2624 } else {
2625 tail = original_buffer_range.start;
2626 }
2627 }
2628 SelectMode::Line(original_range) => {
2629 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2630
2631 let position = display_map
2632 .clip_point(position, Bias::Left)
2633 .to_point(&display_map);
2634 let line_start = display_map.prev_line_boundary(position).0;
2635 let next_line_start = buffer.clip_point(
2636 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2637 Bias::Left,
2638 );
2639
2640 if line_start < original_range.start {
2641 head = line_start
2642 } else {
2643 head = next_line_start
2644 }
2645
2646 if head <= original_range.start {
2647 tail = original_range.end;
2648 } else {
2649 tail = original_range.start;
2650 }
2651 }
2652 SelectMode::All => {
2653 return;
2654 }
2655 };
2656
2657 if head < tail {
2658 pending.start = buffer.anchor_before(head);
2659 pending.end = buffer.anchor_before(tail);
2660 pending.reversed = true;
2661 } else {
2662 pending.start = buffer.anchor_before(tail);
2663 pending.end = buffer.anchor_before(head);
2664 pending.reversed = false;
2665 }
2666
2667 self.change_selections(None, window, cx, |s| {
2668 s.set_pending(pending, mode);
2669 });
2670 } else {
2671 log::error!("update_selection dispatched with no pending selection");
2672 return;
2673 }
2674
2675 self.apply_scroll_delta(scroll_delta, window, cx);
2676 cx.notify();
2677 }
2678
2679 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2680 self.columnar_selection_tail.take();
2681 if self.selections.pending_anchor().is_some() {
2682 let selections = self.selections.all::<usize>(cx);
2683 self.change_selections(None, window, cx, |s| {
2684 s.select(selections);
2685 s.clear_pending();
2686 });
2687 }
2688 }
2689
2690 fn select_columns(
2691 &mut self,
2692 tail: DisplayPoint,
2693 head: DisplayPoint,
2694 goal_column: u32,
2695 display_map: &DisplaySnapshot,
2696 window: &mut Window,
2697 cx: &mut Context<Self>,
2698 ) {
2699 let start_row = cmp::min(tail.row(), head.row());
2700 let end_row = cmp::max(tail.row(), head.row());
2701 let start_column = cmp::min(tail.column(), goal_column);
2702 let end_column = cmp::max(tail.column(), goal_column);
2703 let reversed = start_column < tail.column();
2704
2705 let selection_ranges = (start_row.0..=end_row.0)
2706 .map(DisplayRow)
2707 .filter_map(|row| {
2708 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2709 let start = display_map
2710 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2711 .to_point(display_map);
2712 let end = display_map
2713 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2714 .to_point(display_map);
2715 if reversed {
2716 Some(end..start)
2717 } else {
2718 Some(start..end)
2719 }
2720 } else {
2721 None
2722 }
2723 })
2724 .collect::<Vec<_>>();
2725
2726 self.change_selections(None, window, cx, |s| {
2727 s.select_ranges(selection_ranges);
2728 });
2729 cx.notify();
2730 }
2731
2732 pub fn has_pending_nonempty_selection(&self) -> bool {
2733 let pending_nonempty_selection = match self.selections.pending_anchor() {
2734 Some(Selection { start, end, .. }) => start != end,
2735 None => false,
2736 };
2737
2738 pending_nonempty_selection
2739 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2740 }
2741
2742 pub fn has_pending_selection(&self) -> bool {
2743 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2744 }
2745
2746 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2747 self.selection_mark_mode = false;
2748
2749 if self.clear_expanded_diff_hunks(cx) {
2750 cx.notify();
2751 return;
2752 }
2753 if self.dismiss_menus_and_popups(true, window, cx) {
2754 return;
2755 }
2756
2757 if self.mode == EditorMode::Full
2758 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2759 {
2760 return;
2761 }
2762
2763 cx.propagate();
2764 }
2765
2766 pub fn dismiss_menus_and_popups(
2767 &mut self,
2768 is_user_requested: bool,
2769 window: &mut Window,
2770 cx: &mut Context<Self>,
2771 ) -> bool {
2772 if self.take_rename(false, window, cx).is_some() {
2773 return true;
2774 }
2775
2776 if hide_hover(self, cx) {
2777 return true;
2778 }
2779
2780 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2781 return true;
2782 }
2783
2784 if self.hide_context_menu(window, cx).is_some() {
2785 return true;
2786 }
2787
2788 if self.mouse_context_menu.take().is_some() {
2789 return true;
2790 }
2791
2792 if is_user_requested && self.discard_inline_completion(true, cx) {
2793 return true;
2794 }
2795
2796 if self.snippet_stack.pop().is_some() {
2797 return true;
2798 }
2799
2800 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2801 self.dismiss_diagnostics(cx);
2802 return true;
2803 }
2804
2805 false
2806 }
2807
2808 fn linked_editing_ranges_for(
2809 &self,
2810 selection: Range<text::Anchor>,
2811 cx: &App,
2812 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2813 if self.linked_edit_ranges.is_empty() {
2814 return None;
2815 }
2816 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2817 selection.end.buffer_id.and_then(|end_buffer_id| {
2818 if selection.start.buffer_id != Some(end_buffer_id) {
2819 return None;
2820 }
2821 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2822 let snapshot = buffer.read(cx).snapshot();
2823 self.linked_edit_ranges
2824 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2825 .map(|ranges| (ranges, snapshot, buffer))
2826 })?;
2827 use text::ToOffset as TO;
2828 // find offset from the start of current range to current cursor position
2829 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2830
2831 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2832 let start_difference = start_offset - start_byte_offset;
2833 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2834 let end_difference = end_offset - start_byte_offset;
2835 // Current range has associated linked ranges.
2836 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2837 for range in linked_ranges.iter() {
2838 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2839 let end_offset = start_offset + end_difference;
2840 let start_offset = start_offset + start_difference;
2841 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2842 continue;
2843 }
2844 if self.selections.disjoint_anchor_ranges().any(|s| {
2845 if s.start.buffer_id != selection.start.buffer_id
2846 || s.end.buffer_id != selection.end.buffer_id
2847 {
2848 return false;
2849 }
2850 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2851 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2852 }) {
2853 continue;
2854 }
2855 let start = buffer_snapshot.anchor_after(start_offset);
2856 let end = buffer_snapshot.anchor_after(end_offset);
2857 linked_edits
2858 .entry(buffer.clone())
2859 .or_default()
2860 .push(start..end);
2861 }
2862 Some(linked_edits)
2863 }
2864
2865 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2866 let text: Arc<str> = text.into();
2867
2868 if self.read_only(cx) {
2869 return;
2870 }
2871
2872 let selections = self.selections.all_adjusted(cx);
2873 let mut bracket_inserted = false;
2874 let mut edits = Vec::new();
2875 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2876 let mut new_selections = Vec::with_capacity(selections.len());
2877 let mut new_autoclose_regions = Vec::new();
2878 let snapshot = self.buffer.read(cx).read(cx);
2879
2880 for (selection, autoclose_region) in
2881 self.selections_with_autoclose_regions(selections, &snapshot)
2882 {
2883 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2884 // Determine if the inserted text matches the opening or closing
2885 // bracket of any of this language's bracket pairs.
2886 let mut bracket_pair = None;
2887 let mut is_bracket_pair_start = false;
2888 let mut is_bracket_pair_end = false;
2889 if !text.is_empty() {
2890 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2891 // and they are removing the character that triggered IME popup.
2892 for (pair, enabled) in scope.brackets() {
2893 if !pair.close && !pair.surround {
2894 continue;
2895 }
2896
2897 if enabled && pair.start.ends_with(text.as_ref()) {
2898 let prefix_len = pair.start.len() - text.len();
2899 let preceding_text_matches_prefix = prefix_len == 0
2900 || (selection.start.column >= (prefix_len as u32)
2901 && snapshot.contains_str_at(
2902 Point::new(
2903 selection.start.row,
2904 selection.start.column - (prefix_len as u32),
2905 ),
2906 &pair.start[..prefix_len],
2907 ));
2908 if preceding_text_matches_prefix {
2909 bracket_pair = Some(pair.clone());
2910 is_bracket_pair_start = true;
2911 break;
2912 }
2913 }
2914 if pair.end.as_str() == text.as_ref() {
2915 bracket_pair = Some(pair.clone());
2916 is_bracket_pair_end = true;
2917 break;
2918 }
2919 }
2920 }
2921
2922 if let Some(bracket_pair) = bracket_pair {
2923 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2924 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2925 let auto_surround =
2926 self.use_auto_surround && snapshot_settings.use_auto_surround;
2927 if selection.is_empty() {
2928 if is_bracket_pair_start {
2929 // If the inserted text is a suffix of an opening bracket and the
2930 // selection is preceded by the rest of the opening bracket, then
2931 // insert the closing bracket.
2932 let following_text_allows_autoclose = snapshot
2933 .chars_at(selection.start)
2934 .next()
2935 .map_or(true, |c| scope.should_autoclose_before(c));
2936
2937 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2938 && bracket_pair.start.len() == 1
2939 {
2940 let target = bracket_pair.start.chars().next().unwrap();
2941 let current_line_count = snapshot
2942 .reversed_chars_at(selection.start)
2943 .take_while(|&c| c != '\n')
2944 .filter(|&c| c == target)
2945 .count();
2946 current_line_count % 2 == 1
2947 } else {
2948 false
2949 };
2950
2951 if autoclose
2952 && bracket_pair.close
2953 && following_text_allows_autoclose
2954 && !is_closing_quote
2955 {
2956 let anchor = snapshot.anchor_before(selection.end);
2957 new_selections.push((selection.map(|_| anchor), text.len()));
2958 new_autoclose_regions.push((
2959 anchor,
2960 text.len(),
2961 selection.id,
2962 bracket_pair.clone(),
2963 ));
2964 edits.push((
2965 selection.range(),
2966 format!("{}{}", text, bracket_pair.end).into(),
2967 ));
2968 bracket_inserted = true;
2969 continue;
2970 }
2971 }
2972
2973 if let Some(region) = autoclose_region {
2974 // If the selection is followed by an auto-inserted closing bracket,
2975 // then don't insert that closing bracket again; just move the selection
2976 // past the closing bracket.
2977 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2978 && text.as_ref() == region.pair.end.as_str();
2979 if should_skip {
2980 let anchor = snapshot.anchor_after(selection.end);
2981 new_selections
2982 .push((selection.map(|_| anchor), region.pair.end.len()));
2983 continue;
2984 }
2985 }
2986
2987 let always_treat_brackets_as_autoclosed = snapshot
2988 .settings_at(selection.start, cx)
2989 .always_treat_brackets_as_autoclosed;
2990 if always_treat_brackets_as_autoclosed
2991 && is_bracket_pair_end
2992 && snapshot.contains_str_at(selection.end, text.as_ref())
2993 {
2994 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2995 // and the inserted text is a closing bracket and the selection is followed
2996 // by the closing bracket then move the selection past the closing bracket.
2997 let anchor = snapshot.anchor_after(selection.end);
2998 new_selections.push((selection.map(|_| anchor), text.len()));
2999 continue;
3000 }
3001 }
3002 // If an opening bracket is 1 character long and is typed while
3003 // text is selected, then surround that text with the bracket pair.
3004 else if auto_surround
3005 && bracket_pair.surround
3006 && is_bracket_pair_start
3007 && bracket_pair.start.chars().count() == 1
3008 {
3009 edits.push((selection.start..selection.start, text.clone()));
3010 edits.push((
3011 selection.end..selection.end,
3012 bracket_pair.end.as_str().into(),
3013 ));
3014 bracket_inserted = true;
3015 new_selections.push((
3016 Selection {
3017 id: selection.id,
3018 start: snapshot.anchor_after(selection.start),
3019 end: snapshot.anchor_before(selection.end),
3020 reversed: selection.reversed,
3021 goal: selection.goal,
3022 },
3023 0,
3024 ));
3025 continue;
3026 }
3027 }
3028 }
3029
3030 if self.auto_replace_emoji_shortcode
3031 && selection.is_empty()
3032 && text.as_ref().ends_with(':')
3033 {
3034 if let Some(possible_emoji_short_code) =
3035 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3036 {
3037 if !possible_emoji_short_code.is_empty() {
3038 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3039 let emoji_shortcode_start = Point::new(
3040 selection.start.row,
3041 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3042 );
3043
3044 // Remove shortcode from buffer
3045 edits.push((
3046 emoji_shortcode_start..selection.start,
3047 "".to_string().into(),
3048 ));
3049 new_selections.push((
3050 Selection {
3051 id: selection.id,
3052 start: snapshot.anchor_after(emoji_shortcode_start),
3053 end: snapshot.anchor_before(selection.start),
3054 reversed: selection.reversed,
3055 goal: selection.goal,
3056 },
3057 0,
3058 ));
3059
3060 // Insert emoji
3061 let selection_start_anchor = snapshot.anchor_after(selection.start);
3062 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3063 edits.push((selection.start..selection.end, emoji.to_string().into()));
3064
3065 continue;
3066 }
3067 }
3068 }
3069 }
3070
3071 // If not handling any auto-close operation, then just replace the selected
3072 // text with the given input and move the selection to the end of the
3073 // newly inserted text.
3074 let anchor = snapshot.anchor_after(selection.end);
3075 if !self.linked_edit_ranges.is_empty() {
3076 let start_anchor = snapshot.anchor_before(selection.start);
3077
3078 let is_word_char = text.chars().next().map_or(true, |char| {
3079 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3080 classifier.is_word(char)
3081 });
3082
3083 if is_word_char {
3084 if let Some(ranges) = self
3085 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3086 {
3087 for (buffer, edits) in ranges {
3088 linked_edits
3089 .entry(buffer.clone())
3090 .or_default()
3091 .extend(edits.into_iter().map(|range| (range, text.clone())));
3092 }
3093 }
3094 }
3095 }
3096
3097 new_selections.push((selection.map(|_| anchor), 0));
3098 edits.push((selection.start..selection.end, text.clone()));
3099 }
3100
3101 drop(snapshot);
3102
3103 self.transact(window, cx, |this, window, cx| {
3104 this.buffer.update(cx, |buffer, cx| {
3105 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3106 });
3107 for (buffer, edits) in linked_edits {
3108 buffer.update(cx, |buffer, cx| {
3109 let snapshot = buffer.snapshot();
3110 let edits = edits
3111 .into_iter()
3112 .map(|(range, text)| {
3113 use text::ToPoint as TP;
3114 let end_point = TP::to_point(&range.end, &snapshot);
3115 let start_point = TP::to_point(&range.start, &snapshot);
3116 (start_point..end_point, text)
3117 })
3118 .sorted_by_key(|(range, _)| range.start)
3119 .collect::<Vec<_>>();
3120 buffer.edit(edits, None, cx);
3121 })
3122 }
3123 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3124 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3125 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3126 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3127 .zip(new_selection_deltas)
3128 .map(|(selection, delta)| Selection {
3129 id: selection.id,
3130 start: selection.start + delta,
3131 end: selection.end + delta,
3132 reversed: selection.reversed,
3133 goal: SelectionGoal::None,
3134 })
3135 .collect::<Vec<_>>();
3136
3137 let mut i = 0;
3138 for (position, delta, selection_id, pair) in new_autoclose_regions {
3139 let position = position.to_offset(&map.buffer_snapshot) + delta;
3140 let start = map.buffer_snapshot.anchor_before(position);
3141 let end = map.buffer_snapshot.anchor_after(position);
3142 while let Some(existing_state) = this.autoclose_regions.get(i) {
3143 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3144 Ordering::Less => i += 1,
3145 Ordering::Greater => break,
3146 Ordering::Equal => {
3147 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3148 Ordering::Less => i += 1,
3149 Ordering::Equal => break,
3150 Ordering::Greater => break,
3151 }
3152 }
3153 }
3154 }
3155 this.autoclose_regions.insert(
3156 i,
3157 AutocloseRegion {
3158 selection_id,
3159 range: start..end,
3160 pair,
3161 },
3162 );
3163 }
3164
3165 let had_active_inline_completion = this.has_active_inline_completion();
3166 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3167 s.select(new_selections)
3168 });
3169
3170 if !bracket_inserted {
3171 if let Some(on_type_format_task) =
3172 this.trigger_on_type_formatting(text.to_string(), window, cx)
3173 {
3174 on_type_format_task.detach_and_log_err(cx);
3175 }
3176 }
3177
3178 let editor_settings = EditorSettings::get_global(cx);
3179 if bracket_inserted
3180 && (editor_settings.auto_signature_help
3181 || editor_settings.show_signature_help_after_edits)
3182 {
3183 this.show_signature_help(&ShowSignatureHelp, window, cx);
3184 }
3185
3186 let trigger_in_words =
3187 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3188 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3189 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3190 this.refresh_inline_completion(true, false, window, cx);
3191 });
3192 }
3193
3194 fn find_possible_emoji_shortcode_at_position(
3195 snapshot: &MultiBufferSnapshot,
3196 position: Point,
3197 ) -> Option<String> {
3198 let mut chars = Vec::new();
3199 let mut found_colon = false;
3200 for char in snapshot.reversed_chars_at(position).take(100) {
3201 // Found a possible emoji shortcode in the middle of the buffer
3202 if found_colon {
3203 if char.is_whitespace() {
3204 chars.reverse();
3205 return Some(chars.iter().collect());
3206 }
3207 // If the previous character is not a whitespace, we are in the middle of a word
3208 // and we only want to complete the shortcode if the word is made up of other emojis
3209 let mut containing_word = String::new();
3210 for ch in snapshot
3211 .reversed_chars_at(position)
3212 .skip(chars.len() + 1)
3213 .take(100)
3214 {
3215 if ch.is_whitespace() {
3216 break;
3217 }
3218 containing_word.push(ch);
3219 }
3220 let containing_word = containing_word.chars().rev().collect::<String>();
3221 if util::word_consists_of_emojis(containing_word.as_str()) {
3222 chars.reverse();
3223 return Some(chars.iter().collect());
3224 }
3225 }
3226
3227 if char.is_whitespace() || !char.is_ascii() {
3228 return None;
3229 }
3230 if char == ':' {
3231 found_colon = true;
3232 } else {
3233 chars.push(char);
3234 }
3235 }
3236 // Found a possible emoji shortcode at the beginning of the buffer
3237 chars.reverse();
3238 Some(chars.iter().collect())
3239 }
3240
3241 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3242 self.transact(window, cx, |this, window, cx| {
3243 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3244 let selections = this.selections.all::<usize>(cx);
3245 let multi_buffer = this.buffer.read(cx);
3246 let buffer = multi_buffer.snapshot(cx);
3247 selections
3248 .iter()
3249 .map(|selection| {
3250 let start_point = selection.start.to_point(&buffer);
3251 let mut indent =
3252 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3253 indent.len = cmp::min(indent.len, start_point.column);
3254 let start = selection.start;
3255 let end = selection.end;
3256 let selection_is_empty = start == end;
3257 let language_scope = buffer.language_scope_at(start);
3258 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3259 &language_scope
3260 {
3261 let insert_extra_newline =
3262 insert_extra_newline_brackets(&buffer, start..end, language)
3263 || insert_extra_newline_tree_sitter(&buffer, start..end);
3264
3265 // Comment extension on newline is allowed only for cursor selections
3266 let comment_delimiter = maybe!({
3267 if !selection_is_empty {
3268 return None;
3269 }
3270
3271 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3272 return None;
3273 }
3274
3275 let delimiters = language.line_comment_prefixes();
3276 let max_len_of_delimiter =
3277 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3278 let (snapshot, range) =
3279 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3280
3281 let mut index_of_first_non_whitespace = 0;
3282 let comment_candidate = snapshot
3283 .chars_for_range(range)
3284 .skip_while(|c| {
3285 let should_skip = c.is_whitespace();
3286 if should_skip {
3287 index_of_first_non_whitespace += 1;
3288 }
3289 should_skip
3290 })
3291 .take(max_len_of_delimiter)
3292 .collect::<String>();
3293 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3294 comment_candidate.starts_with(comment_prefix.as_ref())
3295 })?;
3296 let cursor_is_placed_after_comment_marker =
3297 index_of_first_non_whitespace + comment_prefix.len()
3298 <= start_point.column as usize;
3299 if cursor_is_placed_after_comment_marker {
3300 Some(comment_prefix.clone())
3301 } else {
3302 None
3303 }
3304 });
3305 (comment_delimiter, insert_extra_newline)
3306 } else {
3307 (None, false)
3308 };
3309
3310 let capacity_for_delimiter = comment_delimiter
3311 .as_deref()
3312 .map(str::len)
3313 .unwrap_or_default();
3314 let mut new_text =
3315 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3316 new_text.push('\n');
3317 new_text.extend(indent.chars());
3318 if let Some(delimiter) = &comment_delimiter {
3319 new_text.push_str(delimiter);
3320 }
3321 if insert_extra_newline {
3322 new_text = new_text.repeat(2);
3323 }
3324
3325 let anchor = buffer.anchor_after(end);
3326 let new_selection = selection.map(|_| anchor);
3327 (
3328 (start..end, new_text),
3329 (insert_extra_newline, new_selection),
3330 )
3331 })
3332 .unzip()
3333 };
3334
3335 this.edit_with_autoindent(edits, cx);
3336 let buffer = this.buffer.read(cx).snapshot(cx);
3337 let new_selections = selection_fixup_info
3338 .into_iter()
3339 .map(|(extra_newline_inserted, new_selection)| {
3340 let mut cursor = new_selection.end.to_point(&buffer);
3341 if extra_newline_inserted {
3342 cursor.row -= 1;
3343 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3344 }
3345 new_selection.map(|_| cursor)
3346 })
3347 .collect();
3348
3349 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3350 s.select(new_selections)
3351 });
3352 this.refresh_inline_completion(true, false, window, cx);
3353 });
3354 }
3355
3356 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3357 let buffer = self.buffer.read(cx);
3358 let snapshot = buffer.snapshot(cx);
3359
3360 let mut edits = Vec::new();
3361 let mut rows = Vec::new();
3362
3363 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3364 let cursor = selection.head();
3365 let row = cursor.row;
3366
3367 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3368
3369 let newline = "\n".to_string();
3370 edits.push((start_of_line..start_of_line, newline));
3371
3372 rows.push(row + rows_inserted as u32);
3373 }
3374
3375 self.transact(window, cx, |editor, window, cx| {
3376 editor.edit(edits, cx);
3377
3378 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3379 let mut index = 0;
3380 s.move_cursors_with(|map, _, _| {
3381 let row = rows[index];
3382 index += 1;
3383
3384 let point = Point::new(row, 0);
3385 let boundary = map.next_line_boundary(point).1;
3386 let clipped = map.clip_point(boundary, Bias::Left);
3387
3388 (clipped, SelectionGoal::None)
3389 });
3390 });
3391
3392 let mut indent_edits = Vec::new();
3393 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3394 for row in rows {
3395 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3396 for (row, indent) in indents {
3397 if indent.len == 0 {
3398 continue;
3399 }
3400
3401 let text = match indent.kind {
3402 IndentKind::Space => " ".repeat(indent.len as usize),
3403 IndentKind::Tab => "\t".repeat(indent.len as usize),
3404 };
3405 let point = Point::new(row.0, 0);
3406 indent_edits.push((point..point, text));
3407 }
3408 }
3409 editor.edit(indent_edits, cx);
3410 });
3411 }
3412
3413 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3414 let buffer = self.buffer.read(cx);
3415 let snapshot = buffer.snapshot(cx);
3416
3417 let mut edits = Vec::new();
3418 let mut rows = Vec::new();
3419 let mut rows_inserted = 0;
3420
3421 for selection in self.selections.all_adjusted(cx) {
3422 let cursor = selection.head();
3423 let row = cursor.row;
3424
3425 let point = Point::new(row + 1, 0);
3426 let start_of_line = snapshot.clip_point(point, Bias::Left);
3427
3428 let newline = "\n".to_string();
3429 edits.push((start_of_line..start_of_line, newline));
3430
3431 rows_inserted += 1;
3432 rows.push(row + rows_inserted);
3433 }
3434
3435 self.transact(window, cx, |editor, window, cx| {
3436 editor.edit(edits, cx);
3437
3438 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3439 let mut index = 0;
3440 s.move_cursors_with(|map, _, _| {
3441 let row = rows[index];
3442 index += 1;
3443
3444 let point = Point::new(row, 0);
3445 let boundary = map.next_line_boundary(point).1;
3446 let clipped = map.clip_point(boundary, Bias::Left);
3447
3448 (clipped, SelectionGoal::None)
3449 });
3450 });
3451
3452 let mut indent_edits = Vec::new();
3453 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3454 for row in rows {
3455 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3456 for (row, indent) in indents {
3457 if indent.len == 0 {
3458 continue;
3459 }
3460
3461 let text = match indent.kind {
3462 IndentKind::Space => " ".repeat(indent.len as usize),
3463 IndentKind::Tab => "\t".repeat(indent.len as usize),
3464 };
3465 let point = Point::new(row.0, 0);
3466 indent_edits.push((point..point, text));
3467 }
3468 }
3469 editor.edit(indent_edits, cx);
3470 });
3471 }
3472
3473 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3474 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3475 original_start_columns: Vec::new(),
3476 });
3477 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3478 }
3479
3480 fn insert_with_autoindent_mode(
3481 &mut self,
3482 text: &str,
3483 autoindent_mode: Option<AutoindentMode>,
3484 window: &mut Window,
3485 cx: &mut Context<Self>,
3486 ) {
3487 if self.read_only(cx) {
3488 return;
3489 }
3490
3491 let text: Arc<str> = text.into();
3492 self.transact(window, cx, |this, window, cx| {
3493 let old_selections = this.selections.all_adjusted(cx);
3494 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3495 let anchors = {
3496 let snapshot = buffer.read(cx);
3497 old_selections
3498 .iter()
3499 .map(|s| {
3500 let anchor = snapshot.anchor_after(s.head());
3501 s.map(|_| anchor)
3502 })
3503 .collect::<Vec<_>>()
3504 };
3505 buffer.edit(
3506 old_selections
3507 .iter()
3508 .map(|s| (s.start..s.end, text.clone())),
3509 autoindent_mode,
3510 cx,
3511 );
3512 anchors
3513 });
3514
3515 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3516 s.select_anchors(selection_anchors);
3517 });
3518
3519 cx.notify();
3520 });
3521 }
3522
3523 fn trigger_completion_on_input(
3524 &mut self,
3525 text: &str,
3526 trigger_in_words: bool,
3527 window: &mut Window,
3528 cx: &mut Context<Self>,
3529 ) {
3530 if self.is_completion_trigger(text, trigger_in_words, cx) {
3531 self.show_completions(
3532 &ShowCompletions {
3533 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3534 },
3535 window,
3536 cx,
3537 );
3538 } else {
3539 self.hide_context_menu(window, cx);
3540 }
3541 }
3542
3543 fn is_completion_trigger(
3544 &self,
3545 text: &str,
3546 trigger_in_words: bool,
3547 cx: &mut Context<Self>,
3548 ) -> bool {
3549 let position = self.selections.newest_anchor().head();
3550 let multibuffer = self.buffer.read(cx);
3551 let Some(buffer) = position
3552 .buffer_id
3553 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3554 else {
3555 return false;
3556 };
3557
3558 if let Some(completion_provider) = &self.completion_provider {
3559 completion_provider.is_completion_trigger(
3560 &buffer,
3561 position.text_anchor,
3562 text,
3563 trigger_in_words,
3564 cx,
3565 )
3566 } else {
3567 false
3568 }
3569 }
3570
3571 /// If any empty selections is touching the start of its innermost containing autoclose
3572 /// region, expand it to select the brackets.
3573 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3574 let selections = self.selections.all::<usize>(cx);
3575 let buffer = self.buffer.read(cx).read(cx);
3576 let new_selections = self
3577 .selections_with_autoclose_regions(selections, &buffer)
3578 .map(|(mut selection, region)| {
3579 if !selection.is_empty() {
3580 return selection;
3581 }
3582
3583 if let Some(region) = region {
3584 let mut range = region.range.to_offset(&buffer);
3585 if selection.start == range.start && range.start >= region.pair.start.len() {
3586 range.start -= region.pair.start.len();
3587 if buffer.contains_str_at(range.start, ®ion.pair.start)
3588 && buffer.contains_str_at(range.end, ®ion.pair.end)
3589 {
3590 range.end += region.pair.end.len();
3591 selection.start = range.start;
3592 selection.end = range.end;
3593
3594 return selection;
3595 }
3596 }
3597 }
3598
3599 let always_treat_brackets_as_autoclosed = buffer
3600 .settings_at(selection.start, cx)
3601 .always_treat_brackets_as_autoclosed;
3602
3603 if !always_treat_brackets_as_autoclosed {
3604 return selection;
3605 }
3606
3607 if let Some(scope) = buffer.language_scope_at(selection.start) {
3608 for (pair, enabled) in scope.brackets() {
3609 if !enabled || !pair.close {
3610 continue;
3611 }
3612
3613 if buffer.contains_str_at(selection.start, &pair.end) {
3614 let pair_start_len = pair.start.len();
3615 if buffer.contains_str_at(
3616 selection.start.saturating_sub(pair_start_len),
3617 &pair.start,
3618 ) {
3619 selection.start -= pair_start_len;
3620 selection.end += pair.end.len();
3621
3622 return selection;
3623 }
3624 }
3625 }
3626 }
3627
3628 selection
3629 })
3630 .collect();
3631
3632 drop(buffer);
3633 self.change_selections(None, window, cx, |selections| {
3634 selections.select(new_selections)
3635 });
3636 }
3637
3638 /// Iterate the given selections, and for each one, find the smallest surrounding
3639 /// autoclose region. This uses the ordering of the selections and the autoclose
3640 /// regions to avoid repeated comparisons.
3641 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3642 &'a self,
3643 selections: impl IntoIterator<Item = Selection<D>>,
3644 buffer: &'a MultiBufferSnapshot,
3645 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3646 let mut i = 0;
3647 let mut regions = self.autoclose_regions.as_slice();
3648 selections.into_iter().map(move |selection| {
3649 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3650
3651 let mut enclosing = None;
3652 while let Some(pair_state) = regions.get(i) {
3653 if pair_state.range.end.to_offset(buffer) < range.start {
3654 regions = ®ions[i + 1..];
3655 i = 0;
3656 } else if pair_state.range.start.to_offset(buffer) > range.end {
3657 break;
3658 } else {
3659 if pair_state.selection_id == selection.id {
3660 enclosing = Some(pair_state);
3661 }
3662 i += 1;
3663 }
3664 }
3665
3666 (selection, enclosing)
3667 })
3668 }
3669
3670 /// Remove any autoclose regions that no longer contain their selection.
3671 fn invalidate_autoclose_regions(
3672 &mut self,
3673 mut selections: &[Selection<Anchor>],
3674 buffer: &MultiBufferSnapshot,
3675 ) {
3676 self.autoclose_regions.retain(|state| {
3677 let mut i = 0;
3678 while let Some(selection) = selections.get(i) {
3679 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3680 selections = &selections[1..];
3681 continue;
3682 }
3683 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3684 break;
3685 }
3686 if selection.id == state.selection_id {
3687 return true;
3688 } else {
3689 i += 1;
3690 }
3691 }
3692 false
3693 });
3694 }
3695
3696 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3697 let offset = position.to_offset(buffer);
3698 let (word_range, kind) = buffer.surrounding_word(offset, true);
3699 if offset > word_range.start && kind == Some(CharKind::Word) {
3700 Some(
3701 buffer
3702 .text_for_range(word_range.start..offset)
3703 .collect::<String>(),
3704 )
3705 } else {
3706 None
3707 }
3708 }
3709
3710 pub fn toggle_inlay_hints(
3711 &mut self,
3712 _: &ToggleInlayHints,
3713 _: &mut Window,
3714 cx: &mut Context<Self>,
3715 ) {
3716 self.refresh_inlay_hints(
3717 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3718 cx,
3719 );
3720 }
3721
3722 pub fn inlay_hints_enabled(&self) -> bool {
3723 self.inlay_hint_cache.enabled
3724 }
3725
3726 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3727 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3728 return;
3729 }
3730
3731 let reason_description = reason.description();
3732 let ignore_debounce = matches!(
3733 reason,
3734 InlayHintRefreshReason::SettingsChange(_)
3735 | InlayHintRefreshReason::Toggle(_)
3736 | InlayHintRefreshReason::ExcerptsRemoved(_)
3737 | InlayHintRefreshReason::ModifiersChanged(_)
3738 );
3739 let (invalidate_cache, required_languages) = match reason {
3740 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3741 match self.inlay_hint_cache.modifiers_override(enabled) {
3742 Some(enabled) => {
3743 if enabled {
3744 (InvalidationStrategy::RefreshRequested, None)
3745 } else {
3746 self.splice_inlays(
3747 &self
3748 .visible_inlay_hints(cx)
3749 .iter()
3750 .map(|inlay| inlay.id)
3751 .collect::<Vec<InlayId>>(),
3752 Vec::new(),
3753 cx,
3754 );
3755 return;
3756 }
3757 }
3758 None => return,
3759 }
3760 }
3761 InlayHintRefreshReason::Toggle(enabled) => {
3762 if self.inlay_hint_cache.toggle(enabled) {
3763 if enabled {
3764 (InvalidationStrategy::RefreshRequested, None)
3765 } else {
3766 self.splice_inlays(
3767 &self
3768 .visible_inlay_hints(cx)
3769 .iter()
3770 .map(|inlay| inlay.id)
3771 .collect::<Vec<InlayId>>(),
3772 Vec::new(),
3773 cx,
3774 );
3775 return;
3776 }
3777 } else {
3778 return;
3779 }
3780 }
3781 InlayHintRefreshReason::SettingsChange(new_settings) => {
3782 match self.inlay_hint_cache.update_settings(
3783 &self.buffer,
3784 new_settings,
3785 self.visible_inlay_hints(cx),
3786 cx,
3787 ) {
3788 ControlFlow::Break(Some(InlaySplice {
3789 to_remove,
3790 to_insert,
3791 })) => {
3792 self.splice_inlays(&to_remove, to_insert, cx);
3793 return;
3794 }
3795 ControlFlow::Break(None) => return,
3796 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3797 }
3798 }
3799 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3800 if let Some(InlaySplice {
3801 to_remove,
3802 to_insert,
3803 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3804 {
3805 self.splice_inlays(&to_remove, to_insert, cx);
3806 }
3807 return;
3808 }
3809 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3810 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3811 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3812 }
3813 InlayHintRefreshReason::RefreshRequested => {
3814 (InvalidationStrategy::RefreshRequested, None)
3815 }
3816 };
3817
3818 if let Some(InlaySplice {
3819 to_remove,
3820 to_insert,
3821 }) = self.inlay_hint_cache.spawn_hint_refresh(
3822 reason_description,
3823 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3824 invalidate_cache,
3825 ignore_debounce,
3826 cx,
3827 ) {
3828 self.splice_inlays(&to_remove, to_insert, cx);
3829 }
3830 }
3831
3832 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3833 self.display_map
3834 .read(cx)
3835 .current_inlays()
3836 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3837 .cloned()
3838 .collect()
3839 }
3840
3841 pub fn excerpts_for_inlay_hints_query(
3842 &self,
3843 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3844 cx: &mut Context<Editor>,
3845 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3846 let Some(project) = self.project.as_ref() else {
3847 return HashMap::default();
3848 };
3849 let project = project.read(cx);
3850 let multi_buffer = self.buffer().read(cx);
3851 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3852 let multi_buffer_visible_start = self
3853 .scroll_manager
3854 .anchor()
3855 .anchor
3856 .to_point(&multi_buffer_snapshot);
3857 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3858 multi_buffer_visible_start
3859 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3860 Bias::Left,
3861 );
3862 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3863 multi_buffer_snapshot
3864 .range_to_buffer_ranges(multi_buffer_visible_range)
3865 .into_iter()
3866 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3867 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3868 let buffer_file = project::File::from_dyn(buffer.file())?;
3869 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3870 let worktree_entry = buffer_worktree
3871 .read(cx)
3872 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3873 if worktree_entry.is_ignored {
3874 return None;
3875 }
3876
3877 let language = buffer.language()?;
3878 if let Some(restrict_to_languages) = restrict_to_languages {
3879 if !restrict_to_languages.contains(language) {
3880 return None;
3881 }
3882 }
3883 Some((
3884 excerpt_id,
3885 (
3886 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3887 buffer.version().clone(),
3888 excerpt_visible_range,
3889 ),
3890 ))
3891 })
3892 .collect()
3893 }
3894
3895 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3896 TextLayoutDetails {
3897 text_system: window.text_system().clone(),
3898 editor_style: self.style.clone().unwrap(),
3899 rem_size: window.rem_size(),
3900 scroll_anchor: self.scroll_manager.anchor(),
3901 visible_rows: self.visible_line_count(),
3902 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3903 }
3904 }
3905
3906 pub fn splice_inlays(
3907 &self,
3908 to_remove: &[InlayId],
3909 to_insert: Vec<Inlay>,
3910 cx: &mut Context<Self>,
3911 ) {
3912 self.display_map.update(cx, |display_map, cx| {
3913 display_map.splice_inlays(to_remove, to_insert, cx)
3914 });
3915 cx.notify();
3916 }
3917
3918 fn trigger_on_type_formatting(
3919 &self,
3920 input: String,
3921 window: &mut Window,
3922 cx: &mut Context<Self>,
3923 ) -> Option<Task<Result<()>>> {
3924 if input.len() != 1 {
3925 return None;
3926 }
3927
3928 let project = self.project.as_ref()?;
3929 let position = self.selections.newest_anchor().head();
3930 let (buffer, buffer_position) = self
3931 .buffer
3932 .read(cx)
3933 .text_anchor_for_position(position, cx)?;
3934
3935 let settings = language_settings::language_settings(
3936 buffer
3937 .read(cx)
3938 .language_at(buffer_position)
3939 .map(|l| l.name()),
3940 buffer.read(cx).file(),
3941 cx,
3942 );
3943 if !settings.use_on_type_format {
3944 return None;
3945 }
3946
3947 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3948 // hence we do LSP request & edit on host side only — add formats to host's history.
3949 let push_to_lsp_host_history = true;
3950 // If this is not the host, append its history with new edits.
3951 let push_to_client_history = project.read(cx).is_via_collab();
3952
3953 let on_type_formatting = project.update(cx, |project, cx| {
3954 project.on_type_format(
3955 buffer.clone(),
3956 buffer_position,
3957 input,
3958 push_to_lsp_host_history,
3959 cx,
3960 )
3961 });
3962 Some(cx.spawn_in(window, |editor, mut cx| async move {
3963 if let Some(transaction) = on_type_formatting.await? {
3964 if push_to_client_history {
3965 buffer
3966 .update(&mut cx, |buffer, _| {
3967 buffer.push_transaction(transaction, Instant::now());
3968 })
3969 .ok();
3970 }
3971 editor.update(&mut cx, |editor, cx| {
3972 editor.refresh_document_highlights(cx);
3973 })?;
3974 }
3975 Ok(())
3976 }))
3977 }
3978
3979 pub fn show_completions(
3980 &mut self,
3981 options: &ShowCompletions,
3982 window: &mut Window,
3983 cx: &mut Context<Self>,
3984 ) {
3985 if self.pending_rename.is_some() {
3986 return;
3987 }
3988
3989 let Some(provider) = self.completion_provider.as_ref() else {
3990 return;
3991 };
3992
3993 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3994 return;
3995 }
3996
3997 let position = self.selections.newest_anchor().head();
3998 if position.diff_base_anchor.is_some() {
3999 return;
4000 }
4001 let (buffer, buffer_position) =
4002 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4003 output
4004 } else {
4005 return;
4006 };
4007 let show_completion_documentation = buffer
4008 .read(cx)
4009 .snapshot()
4010 .settings_at(buffer_position, cx)
4011 .show_completion_documentation;
4012
4013 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4014
4015 let trigger_kind = match &options.trigger {
4016 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4017 CompletionTriggerKind::TRIGGER_CHARACTER
4018 }
4019 _ => CompletionTriggerKind::INVOKED,
4020 };
4021 let completion_context = CompletionContext {
4022 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4023 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4024 Some(String::from(trigger))
4025 } else {
4026 None
4027 }
4028 }),
4029 trigger_kind,
4030 };
4031 let completions =
4032 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4033 let sort_completions = provider.sort_completions();
4034
4035 let id = post_inc(&mut self.next_completion_id);
4036 let task = cx.spawn_in(window, |editor, mut cx| {
4037 async move {
4038 editor.update(&mut cx, |this, _| {
4039 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4040 })?;
4041 let completions = completions.await.log_err();
4042 let menu = if let Some(completions) = completions {
4043 let mut menu = CompletionsMenu::new(
4044 id,
4045 sort_completions,
4046 show_completion_documentation,
4047 position,
4048 buffer.clone(),
4049 completions.into(),
4050 );
4051
4052 menu.filter(query.as_deref(), cx.background_executor().clone())
4053 .await;
4054
4055 menu.visible().then_some(menu)
4056 } else {
4057 None
4058 };
4059
4060 editor.update_in(&mut cx, |editor, window, cx| {
4061 match editor.context_menu.borrow().as_ref() {
4062 None => {}
4063 Some(CodeContextMenu::Completions(prev_menu)) => {
4064 if prev_menu.id > id {
4065 return;
4066 }
4067 }
4068 _ => return,
4069 }
4070
4071 if editor.focus_handle.is_focused(window) && menu.is_some() {
4072 let mut menu = menu.unwrap();
4073 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4074
4075 *editor.context_menu.borrow_mut() =
4076 Some(CodeContextMenu::Completions(menu));
4077
4078 if editor.show_edit_predictions_in_menu() {
4079 editor.update_visible_inline_completion(window, cx);
4080 } else {
4081 editor.discard_inline_completion(false, cx);
4082 }
4083
4084 cx.notify();
4085 } else if editor.completion_tasks.len() <= 1 {
4086 // If there are no more completion tasks and the last menu was
4087 // empty, we should hide it.
4088 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4089 // If it was already hidden and we don't show inline
4090 // completions in the menu, we should also show the
4091 // inline-completion when available.
4092 if was_hidden && editor.show_edit_predictions_in_menu() {
4093 editor.update_visible_inline_completion(window, cx);
4094 }
4095 }
4096 })?;
4097
4098 Ok::<_, anyhow::Error>(())
4099 }
4100 .log_err()
4101 });
4102
4103 self.completion_tasks.push((id, task));
4104 }
4105
4106 pub fn confirm_completion(
4107 &mut self,
4108 action: &ConfirmCompletion,
4109 window: &mut Window,
4110 cx: &mut Context<Self>,
4111 ) -> Option<Task<Result<()>>> {
4112 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4113 }
4114
4115 pub fn compose_completion(
4116 &mut self,
4117 action: &ComposeCompletion,
4118 window: &mut Window,
4119 cx: &mut Context<Self>,
4120 ) -> Option<Task<Result<()>>> {
4121 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4122 }
4123
4124 fn do_completion(
4125 &mut self,
4126 item_ix: Option<usize>,
4127 intent: CompletionIntent,
4128 window: &mut Window,
4129 cx: &mut Context<Editor>,
4130 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4131 use language::ToOffset as _;
4132
4133 let completions_menu =
4134 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4135 menu
4136 } else {
4137 return None;
4138 };
4139
4140 let entries = completions_menu.entries.borrow();
4141 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4142 if self.show_edit_predictions_in_menu() {
4143 self.discard_inline_completion(true, cx);
4144 }
4145 let candidate_id = mat.candidate_id;
4146 drop(entries);
4147
4148 let buffer_handle = completions_menu.buffer;
4149 let completion = completions_menu
4150 .completions
4151 .borrow()
4152 .get(candidate_id)?
4153 .clone();
4154 cx.stop_propagation();
4155
4156 let snippet;
4157 let text;
4158
4159 if completion.is_snippet() {
4160 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4161 text = snippet.as_ref().unwrap().text.clone();
4162 } else {
4163 snippet = None;
4164 text = completion.new_text.clone();
4165 };
4166 let selections = self.selections.all::<usize>(cx);
4167 let buffer = buffer_handle.read(cx);
4168 let old_range = completion.old_range.to_offset(buffer);
4169 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4170
4171 let newest_selection = self.selections.newest_anchor();
4172 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4173 return None;
4174 }
4175
4176 let lookbehind = newest_selection
4177 .start
4178 .text_anchor
4179 .to_offset(buffer)
4180 .saturating_sub(old_range.start);
4181 let lookahead = old_range
4182 .end
4183 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4184 let mut common_prefix_len = old_text
4185 .bytes()
4186 .zip(text.bytes())
4187 .take_while(|(a, b)| a == b)
4188 .count();
4189
4190 let snapshot = self.buffer.read(cx).snapshot(cx);
4191 let mut range_to_replace: Option<Range<isize>> = None;
4192 let mut ranges = Vec::new();
4193 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4194 for selection in &selections {
4195 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4196 let start = selection.start.saturating_sub(lookbehind);
4197 let end = selection.end + lookahead;
4198 if selection.id == newest_selection.id {
4199 range_to_replace = Some(
4200 ((start + common_prefix_len) as isize - selection.start as isize)
4201 ..(end as isize - selection.start as isize),
4202 );
4203 }
4204 ranges.push(start + common_prefix_len..end);
4205 } else {
4206 common_prefix_len = 0;
4207 ranges.clear();
4208 ranges.extend(selections.iter().map(|s| {
4209 if s.id == newest_selection.id {
4210 range_to_replace = Some(
4211 old_range.start.to_offset_utf16(&snapshot).0 as isize
4212 - selection.start as isize
4213 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4214 - selection.start as isize,
4215 );
4216 old_range.clone()
4217 } else {
4218 s.start..s.end
4219 }
4220 }));
4221 break;
4222 }
4223 if !self.linked_edit_ranges.is_empty() {
4224 let start_anchor = snapshot.anchor_before(selection.head());
4225 let end_anchor = snapshot.anchor_after(selection.tail());
4226 if let Some(ranges) = self
4227 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4228 {
4229 for (buffer, edits) in ranges {
4230 linked_edits.entry(buffer.clone()).or_default().extend(
4231 edits
4232 .into_iter()
4233 .map(|range| (range, text[common_prefix_len..].to_owned())),
4234 );
4235 }
4236 }
4237 }
4238 }
4239 let text = &text[common_prefix_len..];
4240
4241 cx.emit(EditorEvent::InputHandled {
4242 utf16_range_to_replace: range_to_replace,
4243 text: text.into(),
4244 });
4245
4246 self.transact(window, cx, |this, window, cx| {
4247 if let Some(mut snippet) = snippet {
4248 snippet.text = text.to_string();
4249 for tabstop in snippet
4250 .tabstops
4251 .iter_mut()
4252 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4253 {
4254 tabstop.start -= common_prefix_len as isize;
4255 tabstop.end -= common_prefix_len as isize;
4256 }
4257
4258 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4259 } else {
4260 this.buffer.update(cx, |buffer, cx| {
4261 buffer.edit(
4262 ranges.iter().map(|range| (range.clone(), text)),
4263 this.autoindent_mode.clone(),
4264 cx,
4265 );
4266 });
4267 }
4268 for (buffer, edits) in linked_edits {
4269 buffer.update(cx, |buffer, cx| {
4270 let snapshot = buffer.snapshot();
4271 let edits = edits
4272 .into_iter()
4273 .map(|(range, text)| {
4274 use text::ToPoint as TP;
4275 let end_point = TP::to_point(&range.end, &snapshot);
4276 let start_point = TP::to_point(&range.start, &snapshot);
4277 (start_point..end_point, text)
4278 })
4279 .sorted_by_key(|(range, _)| range.start)
4280 .collect::<Vec<_>>();
4281 buffer.edit(edits, None, cx);
4282 })
4283 }
4284
4285 this.refresh_inline_completion(true, false, window, cx);
4286 });
4287
4288 let show_new_completions_on_confirm = completion
4289 .confirm
4290 .as_ref()
4291 .map_or(false, |confirm| confirm(intent, window, cx));
4292 if show_new_completions_on_confirm {
4293 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4294 }
4295
4296 let provider = self.completion_provider.as_ref()?;
4297 drop(completion);
4298 let apply_edits = provider.apply_additional_edits_for_completion(
4299 buffer_handle,
4300 completions_menu.completions.clone(),
4301 candidate_id,
4302 true,
4303 cx,
4304 );
4305
4306 let editor_settings = EditorSettings::get_global(cx);
4307 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4308 // After the code completion is finished, users often want to know what signatures are needed.
4309 // so we should automatically call signature_help
4310 self.show_signature_help(&ShowSignatureHelp, window, cx);
4311 }
4312
4313 Some(cx.foreground_executor().spawn(async move {
4314 apply_edits.await?;
4315 Ok(())
4316 }))
4317 }
4318
4319 pub fn toggle_code_actions(
4320 &mut self,
4321 action: &ToggleCodeActions,
4322 window: &mut Window,
4323 cx: &mut Context<Self>,
4324 ) {
4325 let mut context_menu = self.context_menu.borrow_mut();
4326 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4327 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4328 // Toggle if we're selecting the same one
4329 *context_menu = None;
4330 cx.notify();
4331 return;
4332 } else {
4333 // Otherwise, clear it and start a new one
4334 *context_menu = None;
4335 cx.notify();
4336 }
4337 }
4338 drop(context_menu);
4339 let snapshot = self.snapshot(window, cx);
4340 let deployed_from_indicator = action.deployed_from_indicator;
4341 let mut task = self.code_actions_task.take();
4342 let action = action.clone();
4343 cx.spawn_in(window, |editor, mut cx| async move {
4344 while let Some(prev_task) = task {
4345 prev_task.await.log_err();
4346 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4347 }
4348
4349 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4350 if editor.focus_handle.is_focused(window) {
4351 let multibuffer_point = action
4352 .deployed_from_indicator
4353 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4354 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4355 let (buffer, buffer_row) = snapshot
4356 .buffer_snapshot
4357 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4358 .and_then(|(buffer_snapshot, range)| {
4359 editor
4360 .buffer
4361 .read(cx)
4362 .buffer(buffer_snapshot.remote_id())
4363 .map(|buffer| (buffer, range.start.row))
4364 })?;
4365 let (_, code_actions) = editor
4366 .available_code_actions
4367 .clone()
4368 .and_then(|(location, code_actions)| {
4369 let snapshot = location.buffer.read(cx).snapshot();
4370 let point_range = location.range.to_point(&snapshot);
4371 let point_range = point_range.start.row..=point_range.end.row;
4372 if point_range.contains(&buffer_row) {
4373 Some((location, code_actions))
4374 } else {
4375 None
4376 }
4377 })
4378 .unzip();
4379 let buffer_id = buffer.read(cx).remote_id();
4380 let tasks = editor
4381 .tasks
4382 .get(&(buffer_id, buffer_row))
4383 .map(|t| Arc::new(t.to_owned()));
4384 if tasks.is_none() && code_actions.is_none() {
4385 return None;
4386 }
4387
4388 editor.completion_tasks.clear();
4389 editor.discard_inline_completion(false, cx);
4390 let task_context =
4391 tasks
4392 .as_ref()
4393 .zip(editor.project.clone())
4394 .map(|(tasks, project)| {
4395 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4396 });
4397
4398 Some(cx.spawn_in(window, |editor, mut cx| async move {
4399 let task_context = match task_context {
4400 Some(task_context) => task_context.await,
4401 None => None,
4402 };
4403 let resolved_tasks =
4404 tasks.zip(task_context).map(|(tasks, task_context)| {
4405 Rc::new(ResolvedTasks {
4406 templates: tasks.resolve(&task_context).collect(),
4407 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4408 multibuffer_point.row,
4409 tasks.column,
4410 )),
4411 })
4412 });
4413 let spawn_straight_away = resolved_tasks
4414 .as_ref()
4415 .map_or(false, |tasks| tasks.templates.len() == 1)
4416 && code_actions
4417 .as_ref()
4418 .map_or(true, |actions| actions.is_empty());
4419 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4420 *editor.context_menu.borrow_mut() =
4421 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4422 buffer,
4423 actions: CodeActionContents {
4424 tasks: resolved_tasks,
4425 actions: code_actions,
4426 },
4427 selected_item: Default::default(),
4428 scroll_handle: UniformListScrollHandle::default(),
4429 deployed_from_indicator,
4430 }));
4431 if spawn_straight_away {
4432 if let Some(task) = editor.confirm_code_action(
4433 &ConfirmCodeAction { item_ix: Some(0) },
4434 window,
4435 cx,
4436 ) {
4437 cx.notify();
4438 return task;
4439 }
4440 }
4441 cx.notify();
4442 Task::ready(Ok(()))
4443 }) {
4444 task.await
4445 } else {
4446 Ok(())
4447 }
4448 }))
4449 } else {
4450 Some(Task::ready(Ok(())))
4451 }
4452 })?;
4453 if let Some(task) = spawned_test_task {
4454 task.await?;
4455 }
4456
4457 Ok::<_, anyhow::Error>(())
4458 })
4459 .detach_and_log_err(cx);
4460 }
4461
4462 pub fn confirm_code_action(
4463 &mut self,
4464 action: &ConfirmCodeAction,
4465 window: &mut Window,
4466 cx: &mut Context<Self>,
4467 ) -> Option<Task<Result<()>>> {
4468 let actions_menu =
4469 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4470 menu
4471 } else {
4472 return None;
4473 };
4474 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4475 let action = actions_menu.actions.get(action_ix)?;
4476 let title = action.label();
4477 let buffer = actions_menu.buffer;
4478 let workspace = self.workspace()?;
4479
4480 match action {
4481 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4482 workspace.update(cx, |workspace, cx| {
4483 workspace::tasks::schedule_resolved_task(
4484 workspace,
4485 task_source_kind,
4486 resolved_task,
4487 false,
4488 cx,
4489 );
4490
4491 Some(Task::ready(Ok(())))
4492 })
4493 }
4494 CodeActionsItem::CodeAction {
4495 excerpt_id,
4496 action,
4497 provider,
4498 } => {
4499 let apply_code_action =
4500 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4501 let workspace = workspace.downgrade();
4502 Some(cx.spawn_in(window, |editor, cx| async move {
4503 let project_transaction = apply_code_action.await?;
4504 Self::open_project_transaction(
4505 &editor,
4506 workspace,
4507 project_transaction,
4508 title,
4509 cx,
4510 )
4511 .await
4512 }))
4513 }
4514 }
4515 }
4516
4517 pub async fn open_project_transaction(
4518 this: &WeakEntity<Editor>,
4519 workspace: WeakEntity<Workspace>,
4520 transaction: ProjectTransaction,
4521 title: String,
4522 mut cx: AsyncWindowContext,
4523 ) -> Result<()> {
4524 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4525 cx.update(|_, cx| {
4526 entries.sort_unstable_by_key(|(buffer, _)| {
4527 buffer.read(cx).file().map(|f| f.path().clone())
4528 });
4529 })?;
4530
4531 // If the project transaction's edits are all contained within this editor, then
4532 // avoid opening a new editor to display them.
4533
4534 if let Some((buffer, transaction)) = entries.first() {
4535 if entries.len() == 1 {
4536 let excerpt = this.update(&mut cx, |editor, cx| {
4537 editor
4538 .buffer()
4539 .read(cx)
4540 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4541 })?;
4542 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4543 if excerpted_buffer == *buffer {
4544 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4545 let excerpt_range = excerpt_range.to_offset(buffer);
4546 buffer
4547 .edited_ranges_for_transaction::<usize>(transaction)
4548 .all(|range| {
4549 excerpt_range.start <= range.start
4550 && excerpt_range.end >= range.end
4551 })
4552 })?;
4553
4554 if all_edits_within_excerpt {
4555 return Ok(());
4556 }
4557 }
4558 }
4559 }
4560 } else {
4561 return Ok(());
4562 }
4563
4564 let mut ranges_to_highlight = Vec::new();
4565 let excerpt_buffer = cx.new(|cx| {
4566 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4567 for (buffer_handle, transaction) in &entries {
4568 let buffer = buffer_handle.read(cx);
4569 ranges_to_highlight.extend(
4570 multibuffer.push_excerpts_with_context_lines(
4571 buffer_handle.clone(),
4572 buffer
4573 .edited_ranges_for_transaction::<usize>(transaction)
4574 .collect(),
4575 DEFAULT_MULTIBUFFER_CONTEXT,
4576 cx,
4577 ),
4578 );
4579 }
4580 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4581 multibuffer
4582 })?;
4583
4584 workspace.update_in(&mut cx, |workspace, window, cx| {
4585 let project = workspace.project().clone();
4586 let editor = cx
4587 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4588 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4589 editor.update(cx, |editor, cx| {
4590 editor.highlight_background::<Self>(
4591 &ranges_to_highlight,
4592 |theme| theme.editor_highlighted_line_background,
4593 cx,
4594 );
4595 });
4596 })?;
4597
4598 Ok(())
4599 }
4600
4601 pub fn clear_code_action_providers(&mut self) {
4602 self.code_action_providers.clear();
4603 self.available_code_actions.take();
4604 }
4605
4606 pub fn add_code_action_provider(
4607 &mut self,
4608 provider: Rc<dyn CodeActionProvider>,
4609 window: &mut Window,
4610 cx: &mut Context<Self>,
4611 ) {
4612 if self
4613 .code_action_providers
4614 .iter()
4615 .any(|existing_provider| existing_provider.id() == provider.id())
4616 {
4617 return;
4618 }
4619
4620 self.code_action_providers.push(provider);
4621 self.refresh_code_actions(window, cx);
4622 }
4623
4624 pub fn remove_code_action_provider(
4625 &mut self,
4626 id: Arc<str>,
4627 window: &mut Window,
4628 cx: &mut Context<Self>,
4629 ) {
4630 self.code_action_providers
4631 .retain(|provider| provider.id() != id);
4632 self.refresh_code_actions(window, cx);
4633 }
4634
4635 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4636 let buffer = self.buffer.read(cx);
4637 let newest_selection = self.selections.newest_anchor().clone();
4638 if newest_selection.head().diff_base_anchor.is_some() {
4639 return None;
4640 }
4641 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4642 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4643 if start_buffer != end_buffer {
4644 return None;
4645 }
4646
4647 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4648 cx.background_executor()
4649 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4650 .await;
4651
4652 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4653 let providers = this.code_action_providers.clone();
4654 let tasks = this
4655 .code_action_providers
4656 .iter()
4657 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4658 .collect::<Vec<_>>();
4659 (providers, tasks)
4660 })?;
4661
4662 let mut actions = Vec::new();
4663 for (provider, provider_actions) in
4664 providers.into_iter().zip(future::join_all(tasks).await)
4665 {
4666 if let Some(provider_actions) = provider_actions.log_err() {
4667 actions.extend(provider_actions.into_iter().map(|action| {
4668 AvailableCodeAction {
4669 excerpt_id: newest_selection.start.excerpt_id,
4670 action,
4671 provider: provider.clone(),
4672 }
4673 }));
4674 }
4675 }
4676
4677 this.update(&mut cx, |this, cx| {
4678 this.available_code_actions = if actions.is_empty() {
4679 None
4680 } else {
4681 Some((
4682 Location {
4683 buffer: start_buffer,
4684 range: start..end,
4685 },
4686 actions.into(),
4687 ))
4688 };
4689 cx.notify();
4690 })
4691 }));
4692 None
4693 }
4694
4695 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4696 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4697 self.show_git_blame_inline = false;
4698
4699 self.show_git_blame_inline_delay_task =
4700 Some(cx.spawn_in(window, |this, mut cx| async move {
4701 cx.background_executor().timer(delay).await;
4702
4703 this.update(&mut cx, |this, cx| {
4704 this.show_git_blame_inline = true;
4705 cx.notify();
4706 })
4707 .log_err();
4708 }));
4709 }
4710 }
4711
4712 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4713 if self.pending_rename.is_some() {
4714 return None;
4715 }
4716
4717 let provider = self.semantics_provider.clone()?;
4718 let buffer = self.buffer.read(cx);
4719 let newest_selection = self.selections.newest_anchor().clone();
4720 let cursor_position = newest_selection.head();
4721 let (cursor_buffer, cursor_buffer_position) =
4722 buffer.text_anchor_for_position(cursor_position, cx)?;
4723 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4724 if cursor_buffer != tail_buffer {
4725 return None;
4726 }
4727 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4728 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4729 cx.background_executor()
4730 .timer(Duration::from_millis(debounce))
4731 .await;
4732
4733 let highlights = if let Some(highlights) = cx
4734 .update(|cx| {
4735 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4736 })
4737 .ok()
4738 .flatten()
4739 {
4740 highlights.await.log_err()
4741 } else {
4742 None
4743 };
4744
4745 if let Some(highlights) = highlights {
4746 this.update(&mut cx, |this, cx| {
4747 if this.pending_rename.is_some() {
4748 return;
4749 }
4750
4751 let buffer_id = cursor_position.buffer_id;
4752 let buffer = this.buffer.read(cx);
4753 if !buffer
4754 .text_anchor_for_position(cursor_position, cx)
4755 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4756 {
4757 return;
4758 }
4759
4760 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4761 let mut write_ranges = Vec::new();
4762 let mut read_ranges = Vec::new();
4763 for highlight in highlights {
4764 for (excerpt_id, excerpt_range) in
4765 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4766 {
4767 let start = highlight
4768 .range
4769 .start
4770 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4771 let end = highlight
4772 .range
4773 .end
4774 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4775 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4776 continue;
4777 }
4778
4779 let range = Anchor {
4780 buffer_id,
4781 excerpt_id,
4782 text_anchor: start,
4783 diff_base_anchor: None,
4784 }..Anchor {
4785 buffer_id,
4786 excerpt_id,
4787 text_anchor: end,
4788 diff_base_anchor: None,
4789 };
4790 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4791 write_ranges.push(range);
4792 } else {
4793 read_ranges.push(range);
4794 }
4795 }
4796 }
4797
4798 this.highlight_background::<DocumentHighlightRead>(
4799 &read_ranges,
4800 |theme| theme.editor_document_highlight_read_background,
4801 cx,
4802 );
4803 this.highlight_background::<DocumentHighlightWrite>(
4804 &write_ranges,
4805 |theme| theme.editor_document_highlight_write_background,
4806 cx,
4807 );
4808 cx.notify();
4809 })
4810 .log_err();
4811 }
4812 }));
4813 None
4814 }
4815
4816 pub fn refresh_selected_text_highlights(
4817 &mut self,
4818 window: &mut Window,
4819 cx: &mut Context<Editor>,
4820 ) {
4821 self.selection_highlight_task.take();
4822 if !EditorSettings::get_global(cx).selection_highlight {
4823 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4824 return;
4825 }
4826 if self.selections.count() != 1 || self.selections.line_mode {
4827 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4828 return;
4829 }
4830 let selection = self.selections.newest::<Point>(cx);
4831 if selection.is_empty() || selection.start.row != selection.end.row {
4832 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4833 return;
4834 }
4835 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4836 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4837 cx.background_executor()
4838 .timer(Duration::from_millis(debounce))
4839 .await;
4840 let Some(Some(matches_task)) = editor
4841 .update_in(&mut cx, |editor, _, cx| {
4842 if editor.selections.count() != 1 || editor.selections.line_mode {
4843 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4844 return None;
4845 }
4846 let selection = editor.selections.newest::<Point>(cx);
4847 if selection.is_empty() || selection.start.row != selection.end.row {
4848 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4849 return None;
4850 }
4851 let buffer = editor.buffer().read(cx).snapshot(cx);
4852 let query = buffer.text_for_range(selection.range()).collect::<String>();
4853 if query.trim().is_empty() {
4854 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4855 return None;
4856 }
4857 Some(cx.background_spawn(async move {
4858 let mut ranges = Vec::new();
4859 let selection_anchors = selection.range().to_anchors(&buffer);
4860 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4861 for (search_buffer, search_range, excerpt_id) in
4862 buffer.range_to_buffer_ranges(range)
4863 {
4864 ranges.extend(
4865 project::search::SearchQuery::text(
4866 query.clone(),
4867 false,
4868 false,
4869 false,
4870 Default::default(),
4871 Default::default(),
4872 None,
4873 )
4874 .unwrap()
4875 .search(search_buffer, Some(search_range.clone()))
4876 .await
4877 .into_iter()
4878 .filter_map(
4879 |match_range| {
4880 let start = search_buffer.anchor_after(
4881 search_range.start + match_range.start,
4882 );
4883 let end = search_buffer.anchor_before(
4884 search_range.start + match_range.end,
4885 );
4886 let range = Anchor::range_in_buffer(
4887 excerpt_id,
4888 search_buffer.remote_id(),
4889 start..end,
4890 );
4891 (range != selection_anchors).then_some(range)
4892 },
4893 ),
4894 );
4895 }
4896 }
4897 ranges
4898 }))
4899 })
4900 .log_err()
4901 else {
4902 return;
4903 };
4904 let matches = matches_task.await;
4905 editor
4906 .update_in(&mut cx, |editor, _, cx| {
4907 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4908 if !matches.is_empty() {
4909 editor.highlight_background::<SelectedTextHighlight>(
4910 &matches,
4911 |theme| theme.editor_document_highlight_bracket_background,
4912 cx,
4913 )
4914 }
4915 })
4916 .log_err();
4917 }));
4918 }
4919
4920 pub fn refresh_inline_completion(
4921 &mut self,
4922 debounce: bool,
4923 user_requested: bool,
4924 window: &mut Window,
4925 cx: &mut Context<Self>,
4926 ) -> Option<()> {
4927 let provider = self.edit_prediction_provider()?;
4928 let cursor = self.selections.newest_anchor().head();
4929 let (buffer, cursor_buffer_position) =
4930 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4931
4932 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4933 self.discard_inline_completion(false, cx);
4934 return None;
4935 }
4936
4937 if !user_requested
4938 && (!self.should_show_edit_predictions()
4939 || !self.is_focused(window)
4940 || buffer.read(cx).is_empty())
4941 {
4942 self.discard_inline_completion(false, cx);
4943 return None;
4944 }
4945
4946 self.update_visible_inline_completion(window, cx);
4947 provider.refresh(
4948 self.project.clone(),
4949 buffer,
4950 cursor_buffer_position,
4951 debounce,
4952 cx,
4953 );
4954 Some(())
4955 }
4956
4957 fn show_edit_predictions_in_menu(&self) -> bool {
4958 match self.edit_prediction_settings {
4959 EditPredictionSettings::Disabled => false,
4960 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4961 }
4962 }
4963
4964 pub fn edit_predictions_enabled(&self) -> bool {
4965 match self.edit_prediction_settings {
4966 EditPredictionSettings::Disabled => false,
4967 EditPredictionSettings::Enabled { .. } => true,
4968 }
4969 }
4970
4971 fn edit_prediction_requires_modifier(&self) -> bool {
4972 match self.edit_prediction_settings {
4973 EditPredictionSettings::Disabled => false,
4974 EditPredictionSettings::Enabled {
4975 preview_requires_modifier,
4976 ..
4977 } => preview_requires_modifier,
4978 }
4979 }
4980
4981 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4982 if self.edit_prediction_provider.is_none() {
4983 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4984 } else {
4985 let selection = self.selections.newest_anchor();
4986 let cursor = selection.head();
4987
4988 if let Some((buffer, cursor_buffer_position)) =
4989 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4990 {
4991 self.edit_prediction_settings =
4992 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
4993 }
4994 }
4995 }
4996
4997 fn edit_prediction_settings_at_position(
4998 &self,
4999 buffer: &Entity<Buffer>,
5000 buffer_position: language::Anchor,
5001 cx: &App,
5002 ) -> EditPredictionSettings {
5003 if self.mode != EditorMode::Full
5004 || !self.show_inline_completions_override.unwrap_or(true)
5005 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5006 {
5007 return EditPredictionSettings::Disabled;
5008 }
5009
5010 let buffer = buffer.read(cx);
5011
5012 let file = buffer.file();
5013
5014 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5015 return EditPredictionSettings::Disabled;
5016 };
5017
5018 let by_provider = matches!(
5019 self.menu_inline_completions_policy,
5020 MenuInlineCompletionsPolicy::ByProvider
5021 );
5022
5023 let show_in_menu = by_provider
5024 && self
5025 .edit_prediction_provider
5026 .as_ref()
5027 .map_or(false, |provider| {
5028 provider.provider.show_completions_in_menu()
5029 });
5030
5031 let preview_requires_modifier =
5032 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5033
5034 EditPredictionSettings::Enabled {
5035 show_in_menu,
5036 preview_requires_modifier,
5037 }
5038 }
5039
5040 fn should_show_edit_predictions(&self) -> bool {
5041 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5042 }
5043
5044 pub fn edit_prediction_preview_is_active(&self) -> bool {
5045 matches!(
5046 self.edit_prediction_preview,
5047 EditPredictionPreview::Active { .. }
5048 )
5049 }
5050
5051 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5052 let cursor = self.selections.newest_anchor().head();
5053 if let Some((buffer, cursor_position)) =
5054 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5055 {
5056 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5057 } else {
5058 false
5059 }
5060 }
5061
5062 fn edit_predictions_enabled_in_buffer(
5063 &self,
5064 buffer: &Entity<Buffer>,
5065 buffer_position: language::Anchor,
5066 cx: &App,
5067 ) -> bool {
5068 maybe!({
5069 let provider = self.edit_prediction_provider()?;
5070 if !provider.is_enabled(&buffer, buffer_position, cx) {
5071 return Some(false);
5072 }
5073 let buffer = buffer.read(cx);
5074 let Some(file) = buffer.file() else {
5075 return Some(true);
5076 };
5077 let settings = all_language_settings(Some(file), cx);
5078 Some(settings.edit_predictions_enabled_for_file(file, cx))
5079 })
5080 .unwrap_or(false)
5081 }
5082
5083 fn cycle_inline_completion(
5084 &mut self,
5085 direction: Direction,
5086 window: &mut Window,
5087 cx: &mut Context<Self>,
5088 ) -> Option<()> {
5089 let provider = self.edit_prediction_provider()?;
5090 let cursor = self.selections.newest_anchor().head();
5091 let (buffer, cursor_buffer_position) =
5092 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5093 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5094 return None;
5095 }
5096
5097 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5098 self.update_visible_inline_completion(window, cx);
5099
5100 Some(())
5101 }
5102
5103 pub fn show_inline_completion(
5104 &mut self,
5105 _: &ShowEditPrediction,
5106 window: &mut Window,
5107 cx: &mut Context<Self>,
5108 ) {
5109 if !self.has_active_inline_completion() {
5110 self.refresh_inline_completion(false, true, window, cx);
5111 return;
5112 }
5113
5114 self.update_visible_inline_completion(window, cx);
5115 }
5116
5117 pub fn display_cursor_names(
5118 &mut self,
5119 _: &DisplayCursorNames,
5120 window: &mut Window,
5121 cx: &mut Context<Self>,
5122 ) {
5123 self.show_cursor_names(window, cx);
5124 }
5125
5126 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5127 self.show_cursor_names = true;
5128 cx.notify();
5129 cx.spawn_in(window, |this, mut cx| async move {
5130 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5131 this.update(&mut cx, |this, cx| {
5132 this.show_cursor_names = false;
5133 cx.notify()
5134 })
5135 .ok()
5136 })
5137 .detach();
5138 }
5139
5140 pub fn next_edit_prediction(
5141 &mut self,
5142 _: &NextEditPrediction,
5143 window: &mut Window,
5144 cx: &mut Context<Self>,
5145 ) {
5146 if self.has_active_inline_completion() {
5147 self.cycle_inline_completion(Direction::Next, window, cx);
5148 } else {
5149 let is_copilot_disabled = self
5150 .refresh_inline_completion(false, true, window, cx)
5151 .is_none();
5152 if is_copilot_disabled {
5153 cx.propagate();
5154 }
5155 }
5156 }
5157
5158 pub fn previous_edit_prediction(
5159 &mut self,
5160 _: &PreviousEditPrediction,
5161 window: &mut Window,
5162 cx: &mut Context<Self>,
5163 ) {
5164 if self.has_active_inline_completion() {
5165 self.cycle_inline_completion(Direction::Prev, window, cx);
5166 } else {
5167 let is_copilot_disabled = self
5168 .refresh_inline_completion(false, true, window, cx)
5169 .is_none();
5170 if is_copilot_disabled {
5171 cx.propagate();
5172 }
5173 }
5174 }
5175
5176 pub fn accept_edit_prediction(
5177 &mut self,
5178 _: &AcceptEditPrediction,
5179 window: &mut Window,
5180 cx: &mut Context<Self>,
5181 ) {
5182 if self.show_edit_predictions_in_menu() {
5183 self.hide_context_menu(window, cx);
5184 }
5185
5186 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5187 return;
5188 };
5189
5190 self.report_inline_completion_event(
5191 active_inline_completion.completion_id.clone(),
5192 true,
5193 cx,
5194 );
5195
5196 match &active_inline_completion.completion {
5197 InlineCompletion::Move { target, .. } => {
5198 let target = *target;
5199
5200 if let Some(position_map) = &self.last_position_map {
5201 if position_map
5202 .visible_row_range
5203 .contains(&target.to_display_point(&position_map.snapshot).row())
5204 || !self.edit_prediction_requires_modifier()
5205 {
5206 self.unfold_ranges(&[target..target], true, false, cx);
5207 // Note that this is also done in vim's handler of the Tab action.
5208 self.change_selections(
5209 Some(Autoscroll::newest()),
5210 window,
5211 cx,
5212 |selections| {
5213 selections.select_anchor_ranges([target..target]);
5214 },
5215 );
5216 self.clear_row_highlights::<EditPredictionPreview>();
5217
5218 self.edit_prediction_preview
5219 .set_previous_scroll_position(None);
5220 } else {
5221 self.edit_prediction_preview
5222 .set_previous_scroll_position(Some(
5223 position_map.snapshot.scroll_anchor,
5224 ));
5225
5226 self.highlight_rows::<EditPredictionPreview>(
5227 target..target,
5228 cx.theme().colors().editor_highlighted_line_background,
5229 true,
5230 cx,
5231 );
5232 self.request_autoscroll(Autoscroll::fit(), cx);
5233 }
5234 }
5235 }
5236 InlineCompletion::Edit { edits, .. } => {
5237 if let Some(provider) = self.edit_prediction_provider() {
5238 provider.accept(cx);
5239 }
5240
5241 let snapshot = self.buffer.read(cx).snapshot(cx);
5242 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5243
5244 self.buffer.update(cx, |buffer, cx| {
5245 buffer.edit(edits.iter().cloned(), None, cx)
5246 });
5247
5248 self.change_selections(None, window, cx, |s| {
5249 s.select_anchor_ranges([last_edit_end..last_edit_end])
5250 });
5251
5252 self.update_visible_inline_completion(window, cx);
5253 if self.active_inline_completion.is_none() {
5254 self.refresh_inline_completion(true, true, window, cx);
5255 }
5256
5257 cx.notify();
5258 }
5259 }
5260
5261 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5262 }
5263
5264 pub fn accept_partial_inline_completion(
5265 &mut self,
5266 _: &AcceptPartialEditPrediction,
5267 window: &mut Window,
5268 cx: &mut Context<Self>,
5269 ) {
5270 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5271 return;
5272 };
5273 if self.selections.count() != 1 {
5274 return;
5275 }
5276
5277 self.report_inline_completion_event(
5278 active_inline_completion.completion_id.clone(),
5279 true,
5280 cx,
5281 );
5282
5283 match &active_inline_completion.completion {
5284 InlineCompletion::Move { target, .. } => {
5285 let target = *target;
5286 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5287 selections.select_anchor_ranges([target..target]);
5288 });
5289 }
5290 InlineCompletion::Edit { edits, .. } => {
5291 // Find an insertion that starts at the cursor position.
5292 let snapshot = self.buffer.read(cx).snapshot(cx);
5293 let cursor_offset = self.selections.newest::<usize>(cx).head();
5294 let insertion = edits.iter().find_map(|(range, text)| {
5295 let range = range.to_offset(&snapshot);
5296 if range.is_empty() && range.start == cursor_offset {
5297 Some(text)
5298 } else {
5299 None
5300 }
5301 });
5302
5303 if let Some(text) = insertion {
5304 let mut partial_completion = text
5305 .chars()
5306 .by_ref()
5307 .take_while(|c| c.is_alphabetic())
5308 .collect::<String>();
5309 if partial_completion.is_empty() {
5310 partial_completion = text
5311 .chars()
5312 .by_ref()
5313 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5314 .collect::<String>();
5315 }
5316
5317 cx.emit(EditorEvent::InputHandled {
5318 utf16_range_to_replace: None,
5319 text: partial_completion.clone().into(),
5320 });
5321
5322 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5323
5324 self.refresh_inline_completion(true, true, window, cx);
5325 cx.notify();
5326 } else {
5327 self.accept_edit_prediction(&Default::default(), window, cx);
5328 }
5329 }
5330 }
5331 }
5332
5333 fn discard_inline_completion(
5334 &mut self,
5335 should_report_inline_completion_event: bool,
5336 cx: &mut Context<Self>,
5337 ) -> bool {
5338 if should_report_inline_completion_event {
5339 let completion_id = self
5340 .active_inline_completion
5341 .as_ref()
5342 .and_then(|active_completion| active_completion.completion_id.clone());
5343
5344 self.report_inline_completion_event(completion_id, false, cx);
5345 }
5346
5347 if let Some(provider) = self.edit_prediction_provider() {
5348 provider.discard(cx);
5349 }
5350
5351 self.take_active_inline_completion(cx)
5352 }
5353
5354 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5355 let Some(provider) = self.edit_prediction_provider() else {
5356 return;
5357 };
5358
5359 let Some((_, buffer, _)) = self
5360 .buffer
5361 .read(cx)
5362 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5363 else {
5364 return;
5365 };
5366
5367 let extension = buffer
5368 .read(cx)
5369 .file()
5370 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5371
5372 let event_type = match accepted {
5373 true => "Edit Prediction Accepted",
5374 false => "Edit Prediction Discarded",
5375 };
5376 telemetry::event!(
5377 event_type,
5378 provider = provider.name(),
5379 prediction_id = id,
5380 suggestion_accepted = accepted,
5381 file_extension = extension,
5382 );
5383 }
5384
5385 pub fn has_active_inline_completion(&self) -> bool {
5386 self.active_inline_completion.is_some()
5387 }
5388
5389 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5390 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5391 return false;
5392 };
5393
5394 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5395 self.clear_highlights::<InlineCompletionHighlight>(cx);
5396 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5397 true
5398 }
5399
5400 /// Returns true when we're displaying the edit prediction popover below the cursor
5401 /// like we are not previewing and the LSP autocomplete menu is visible
5402 /// or we are in `when_holding_modifier` mode.
5403 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5404 if self.edit_prediction_preview_is_active()
5405 || !self.show_edit_predictions_in_menu()
5406 || !self.edit_predictions_enabled()
5407 {
5408 return false;
5409 }
5410
5411 if self.has_visible_completions_menu() {
5412 return true;
5413 }
5414
5415 has_completion && self.edit_prediction_requires_modifier()
5416 }
5417
5418 fn handle_modifiers_changed(
5419 &mut self,
5420 modifiers: Modifiers,
5421 position_map: &PositionMap,
5422 window: &mut Window,
5423 cx: &mut Context<Self>,
5424 ) {
5425 if self.show_edit_predictions_in_menu() {
5426 self.update_edit_prediction_preview(&modifiers, window, cx);
5427 }
5428
5429 self.update_selection_mode(&modifiers, position_map, window, cx);
5430
5431 let mouse_position = window.mouse_position();
5432 if !position_map.text_hitbox.is_hovered(window) {
5433 return;
5434 }
5435
5436 self.update_hovered_link(
5437 position_map.point_for_position(mouse_position),
5438 &position_map.snapshot,
5439 modifiers,
5440 window,
5441 cx,
5442 )
5443 }
5444
5445 fn update_selection_mode(
5446 &mut self,
5447 modifiers: &Modifiers,
5448 position_map: &PositionMap,
5449 window: &mut Window,
5450 cx: &mut Context<Self>,
5451 ) {
5452 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5453 return;
5454 }
5455
5456 let mouse_position = window.mouse_position();
5457 let point_for_position = position_map.point_for_position(mouse_position);
5458 let position = point_for_position.previous_valid;
5459
5460 self.select(
5461 SelectPhase::BeginColumnar {
5462 position,
5463 reset: false,
5464 goal_column: point_for_position.exact_unclipped.column(),
5465 },
5466 window,
5467 cx,
5468 );
5469 }
5470
5471 fn update_edit_prediction_preview(
5472 &mut self,
5473 modifiers: &Modifiers,
5474 window: &mut Window,
5475 cx: &mut Context<Self>,
5476 ) {
5477 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5478 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5479 return;
5480 };
5481
5482 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5483 if matches!(
5484 self.edit_prediction_preview,
5485 EditPredictionPreview::Inactive { .. }
5486 ) {
5487 self.edit_prediction_preview = EditPredictionPreview::Active {
5488 previous_scroll_position: None,
5489 since: Instant::now(),
5490 };
5491
5492 self.update_visible_inline_completion(window, cx);
5493 cx.notify();
5494 }
5495 } else if let EditPredictionPreview::Active {
5496 previous_scroll_position,
5497 since,
5498 } = self.edit_prediction_preview
5499 {
5500 if let (Some(previous_scroll_position), Some(position_map)) =
5501 (previous_scroll_position, self.last_position_map.as_ref())
5502 {
5503 self.set_scroll_position(
5504 previous_scroll_position
5505 .scroll_position(&position_map.snapshot.display_snapshot),
5506 window,
5507 cx,
5508 );
5509 }
5510
5511 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5512 released_too_fast: since.elapsed() < Duration::from_millis(200),
5513 };
5514 self.clear_row_highlights::<EditPredictionPreview>();
5515 self.update_visible_inline_completion(window, cx);
5516 cx.notify();
5517 }
5518 }
5519
5520 fn update_visible_inline_completion(
5521 &mut self,
5522 _window: &mut Window,
5523 cx: &mut Context<Self>,
5524 ) -> Option<()> {
5525 let selection = self.selections.newest_anchor();
5526 let cursor = selection.head();
5527 let multibuffer = self.buffer.read(cx).snapshot(cx);
5528 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5529 let excerpt_id = cursor.excerpt_id;
5530
5531 let show_in_menu = self.show_edit_predictions_in_menu();
5532 let completions_menu_has_precedence = !show_in_menu
5533 && (self.context_menu.borrow().is_some()
5534 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5535
5536 if completions_menu_has_precedence
5537 || !offset_selection.is_empty()
5538 || self
5539 .active_inline_completion
5540 .as_ref()
5541 .map_or(false, |completion| {
5542 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5543 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5544 !invalidation_range.contains(&offset_selection.head())
5545 })
5546 {
5547 self.discard_inline_completion(false, cx);
5548 return None;
5549 }
5550
5551 self.take_active_inline_completion(cx);
5552 let Some(provider) = self.edit_prediction_provider() else {
5553 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5554 return None;
5555 };
5556
5557 let (buffer, cursor_buffer_position) =
5558 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5559
5560 self.edit_prediction_settings =
5561 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5562
5563 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5564
5565 if self.edit_prediction_indent_conflict {
5566 let cursor_point = cursor.to_point(&multibuffer);
5567
5568 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5569
5570 if let Some((_, indent)) = indents.iter().next() {
5571 if indent.len == cursor_point.column {
5572 self.edit_prediction_indent_conflict = false;
5573 }
5574 }
5575 }
5576
5577 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5578 let edits = inline_completion
5579 .edits
5580 .into_iter()
5581 .flat_map(|(range, new_text)| {
5582 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5583 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5584 Some((start..end, new_text))
5585 })
5586 .collect::<Vec<_>>();
5587 if edits.is_empty() {
5588 return None;
5589 }
5590
5591 let first_edit_start = edits.first().unwrap().0.start;
5592 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5593 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5594
5595 let last_edit_end = edits.last().unwrap().0.end;
5596 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5597 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5598
5599 let cursor_row = cursor.to_point(&multibuffer).row;
5600
5601 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5602
5603 let mut inlay_ids = Vec::new();
5604 let invalidation_row_range;
5605 let move_invalidation_row_range = if cursor_row < edit_start_row {
5606 Some(cursor_row..edit_end_row)
5607 } else if cursor_row > edit_end_row {
5608 Some(edit_start_row..cursor_row)
5609 } else {
5610 None
5611 };
5612 let is_move =
5613 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5614 let completion = if is_move {
5615 invalidation_row_range =
5616 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5617 let target = first_edit_start;
5618 InlineCompletion::Move { target, snapshot }
5619 } else {
5620 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5621 && !self.inline_completions_hidden_for_vim_mode;
5622
5623 if show_completions_in_buffer {
5624 if edits
5625 .iter()
5626 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5627 {
5628 let mut inlays = Vec::new();
5629 for (range, new_text) in &edits {
5630 let inlay = Inlay::inline_completion(
5631 post_inc(&mut self.next_inlay_id),
5632 range.start,
5633 new_text.as_str(),
5634 );
5635 inlay_ids.push(inlay.id);
5636 inlays.push(inlay);
5637 }
5638
5639 self.splice_inlays(&[], inlays, cx);
5640 } else {
5641 let background_color = cx.theme().status().deleted_background;
5642 self.highlight_text::<InlineCompletionHighlight>(
5643 edits.iter().map(|(range, _)| range.clone()).collect(),
5644 HighlightStyle {
5645 background_color: Some(background_color),
5646 ..Default::default()
5647 },
5648 cx,
5649 );
5650 }
5651 }
5652
5653 invalidation_row_range = edit_start_row..edit_end_row;
5654
5655 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5656 if provider.show_tab_accept_marker() {
5657 EditDisplayMode::TabAccept
5658 } else {
5659 EditDisplayMode::Inline
5660 }
5661 } else {
5662 EditDisplayMode::DiffPopover
5663 };
5664
5665 InlineCompletion::Edit {
5666 edits,
5667 edit_preview: inline_completion.edit_preview,
5668 display_mode,
5669 snapshot,
5670 }
5671 };
5672
5673 let invalidation_range = multibuffer
5674 .anchor_before(Point::new(invalidation_row_range.start, 0))
5675 ..multibuffer.anchor_after(Point::new(
5676 invalidation_row_range.end,
5677 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5678 ));
5679
5680 self.stale_inline_completion_in_menu = None;
5681 self.active_inline_completion = Some(InlineCompletionState {
5682 inlay_ids,
5683 completion,
5684 completion_id: inline_completion.id,
5685 invalidation_range,
5686 });
5687
5688 cx.notify();
5689
5690 Some(())
5691 }
5692
5693 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5694 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5695 }
5696
5697 fn render_code_actions_indicator(
5698 &self,
5699 _style: &EditorStyle,
5700 row: DisplayRow,
5701 is_active: bool,
5702 cx: &mut Context<Self>,
5703 ) -> Option<IconButton> {
5704 if self.available_code_actions.is_some() {
5705 Some(
5706 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5707 .shape(ui::IconButtonShape::Square)
5708 .icon_size(IconSize::XSmall)
5709 .icon_color(Color::Muted)
5710 .toggle_state(is_active)
5711 .tooltip({
5712 let focus_handle = self.focus_handle.clone();
5713 move |window, cx| {
5714 Tooltip::for_action_in(
5715 "Toggle Code Actions",
5716 &ToggleCodeActions {
5717 deployed_from_indicator: None,
5718 },
5719 &focus_handle,
5720 window,
5721 cx,
5722 )
5723 }
5724 })
5725 .on_click(cx.listener(move |editor, _e, window, cx| {
5726 window.focus(&editor.focus_handle(cx));
5727 editor.toggle_code_actions(
5728 &ToggleCodeActions {
5729 deployed_from_indicator: Some(row),
5730 },
5731 window,
5732 cx,
5733 );
5734 })),
5735 )
5736 } else {
5737 None
5738 }
5739 }
5740
5741 fn clear_tasks(&mut self) {
5742 self.tasks.clear()
5743 }
5744
5745 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5746 if self.tasks.insert(key, value).is_some() {
5747 // This case should hopefully be rare, but just in case...
5748 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5749 }
5750 }
5751
5752 fn build_tasks_context(
5753 project: &Entity<Project>,
5754 buffer: &Entity<Buffer>,
5755 buffer_row: u32,
5756 tasks: &Arc<RunnableTasks>,
5757 cx: &mut Context<Self>,
5758 ) -> Task<Option<task::TaskContext>> {
5759 let position = Point::new(buffer_row, tasks.column);
5760 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5761 let location = Location {
5762 buffer: buffer.clone(),
5763 range: range_start..range_start,
5764 };
5765 // Fill in the environmental variables from the tree-sitter captures
5766 let mut captured_task_variables = TaskVariables::default();
5767 for (capture_name, value) in tasks.extra_variables.clone() {
5768 captured_task_variables.insert(
5769 task::VariableName::Custom(capture_name.into()),
5770 value.clone(),
5771 );
5772 }
5773 project.update(cx, |project, cx| {
5774 project.task_store().update(cx, |task_store, cx| {
5775 task_store.task_context_for_location(captured_task_variables, location, cx)
5776 })
5777 })
5778 }
5779
5780 pub fn spawn_nearest_task(
5781 &mut self,
5782 action: &SpawnNearestTask,
5783 window: &mut Window,
5784 cx: &mut Context<Self>,
5785 ) {
5786 let Some((workspace, _)) = self.workspace.clone() else {
5787 return;
5788 };
5789 let Some(project) = self.project.clone() else {
5790 return;
5791 };
5792
5793 // Try to find a closest, enclosing node using tree-sitter that has a
5794 // task
5795 let Some((buffer, buffer_row, tasks)) = self
5796 .find_enclosing_node_task(cx)
5797 // Or find the task that's closest in row-distance.
5798 .or_else(|| self.find_closest_task(cx))
5799 else {
5800 return;
5801 };
5802
5803 let reveal_strategy = action.reveal;
5804 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5805 cx.spawn_in(window, |_, mut cx| async move {
5806 let context = task_context.await?;
5807 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5808
5809 let resolved = resolved_task.resolved.as_mut()?;
5810 resolved.reveal = reveal_strategy;
5811
5812 workspace
5813 .update(&mut cx, |workspace, cx| {
5814 workspace::tasks::schedule_resolved_task(
5815 workspace,
5816 task_source_kind,
5817 resolved_task,
5818 false,
5819 cx,
5820 );
5821 })
5822 .ok()
5823 })
5824 .detach();
5825 }
5826
5827 fn find_closest_task(
5828 &mut self,
5829 cx: &mut Context<Self>,
5830 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5831 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5832
5833 let ((buffer_id, row), tasks) = self
5834 .tasks
5835 .iter()
5836 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5837
5838 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5839 let tasks = Arc::new(tasks.to_owned());
5840 Some((buffer, *row, tasks))
5841 }
5842
5843 fn find_enclosing_node_task(
5844 &mut self,
5845 cx: &mut Context<Self>,
5846 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5847 let snapshot = self.buffer.read(cx).snapshot(cx);
5848 let offset = self.selections.newest::<usize>(cx).head();
5849 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5850 let buffer_id = excerpt.buffer().remote_id();
5851
5852 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5853 let mut cursor = layer.node().walk();
5854
5855 while cursor.goto_first_child_for_byte(offset).is_some() {
5856 if cursor.node().end_byte() == offset {
5857 cursor.goto_next_sibling();
5858 }
5859 }
5860
5861 // Ascend to the smallest ancestor that contains the range and has a task.
5862 loop {
5863 let node = cursor.node();
5864 let node_range = node.byte_range();
5865 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5866
5867 // Check if this node contains our offset
5868 if node_range.start <= offset && node_range.end >= offset {
5869 // If it contains offset, check for task
5870 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5871 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5872 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5873 }
5874 }
5875
5876 if !cursor.goto_parent() {
5877 break;
5878 }
5879 }
5880 None
5881 }
5882
5883 fn render_run_indicator(
5884 &self,
5885 _style: &EditorStyle,
5886 is_active: bool,
5887 row: DisplayRow,
5888 cx: &mut Context<Self>,
5889 ) -> IconButton {
5890 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5891 .shape(ui::IconButtonShape::Square)
5892 .icon_size(IconSize::XSmall)
5893 .icon_color(Color::Muted)
5894 .toggle_state(is_active)
5895 .on_click(cx.listener(move |editor, _e, window, cx| {
5896 window.focus(&editor.focus_handle(cx));
5897 editor.toggle_code_actions(
5898 &ToggleCodeActions {
5899 deployed_from_indicator: Some(row),
5900 },
5901 window,
5902 cx,
5903 );
5904 }))
5905 }
5906
5907 pub fn context_menu_visible(&self) -> bool {
5908 !self.edit_prediction_preview_is_active()
5909 && self
5910 .context_menu
5911 .borrow()
5912 .as_ref()
5913 .map_or(false, |menu| menu.visible())
5914 }
5915
5916 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5917 self.context_menu
5918 .borrow()
5919 .as_ref()
5920 .map(|menu| menu.origin())
5921 }
5922
5923 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5924 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5925
5926 #[allow(clippy::too_many_arguments)]
5927 fn render_edit_prediction_popover(
5928 &mut self,
5929 text_bounds: &Bounds<Pixels>,
5930 content_origin: gpui::Point<Pixels>,
5931 editor_snapshot: &EditorSnapshot,
5932 visible_row_range: Range<DisplayRow>,
5933 scroll_top: f32,
5934 scroll_bottom: f32,
5935 line_layouts: &[LineWithInvisibles],
5936 line_height: Pixels,
5937 scroll_pixel_position: gpui::Point<Pixels>,
5938 newest_selection_head: Option<DisplayPoint>,
5939 editor_width: Pixels,
5940 style: &EditorStyle,
5941 window: &mut Window,
5942 cx: &mut App,
5943 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5944 let active_inline_completion = self.active_inline_completion.as_ref()?;
5945
5946 if self.edit_prediction_visible_in_cursor_popover(true) {
5947 return None;
5948 }
5949
5950 match &active_inline_completion.completion {
5951 InlineCompletion::Move { target, .. } => {
5952 let target_display_point = target.to_display_point(editor_snapshot);
5953
5954 if self.edit_prediction_requires_modifier() {
5955 if !self.edit_prediction_preview_is_active() {
5956 return None;
5957 }
5958
5959 self.render_edit_prediction_modifier_jump_popover(
5960 text_bounds,
5961 content_origin,
5962 visible_row_range,
5963 line_layouts,
5964 line_height,
5965 scroll_pixel_position,
5966 newest_selection_head,
5967 target_display_point,
5968 window,
5969 cx,
5970 )
5971 } else {
5972 self.render_edit_prediction_eager_jump_popover(
5973 text_bounds,
5974 content_origin,
5975 editor_snapshot,
5976 visible_row_range,
5977 scroll_top,
5978 scroll_bottom,
5979 line_height,
5980 scroll_pixel_position,
5981 target_display_point,
5982 editor_width,
5983 window,
5984 cx,
5985 )
5986 }
5987 }
5988 InlineCompletion::Edit {
5989 display_mode: EditDisplayMode::Inline,
5990 ..
5991 } => None,
5992 InlineCompletion::Edit {
5993 display_mode: EditDisplayMode::TabAccept,
5994 edits,
5995 ..
5996 } => {
5997 let range = &edits.first()?.0;
5998 let target_display_point = range.end.to_display_point(editor_snapshot);
5999
6000 self.render_edit_prediction_end_of_line_popover(
6001 "Accept",
6002 editor_snapshot,
6003 visible_row_range,
6004 target_display_point,
6005 line_height,
6006 scroll_pixel_position,
6007 content_origin,
6008 editor_width,
6009 window,
6010 cx,
6011 )
6012 }
6013 InlineCompletion::Edit {
6014 edits,
6015 edit_preview,
6016 display_mode: EditDisplayMode::DiffPopover,
6017 snapshot,
6018 } => self.render_edit_prediction_diff_popover(
6019 text_bounds,
6020 content_origin,
6021 editor_snapshot,
6022 visible_row_range,
6023 line_layouts,
6024 line_height,
6025 scroll_pixel_position,
6026 newest_selection_head,
6027 editor_width,
6028 style,
6029 edits,
6030 edit_preview,
6031 snapshot,
6032 window,
6033 cx,
6034 ),
6035 }
6036 }
6037
6038 #[allow(clippy::too_many_arguments)]
6039 fn render_edit_prediction_modifier_jump_popover(
6040 &mut self,
6041 text_bounds: &Bounds<Pixels>,
6042 content_origin: gpui::Point<Pixels>,
6043 visible_row_range: Range<DisplayRow>,
6044 line_layouts: &[LineWithInvisibles],
6045 line_height: Pixels,
6046 scroll_pixel_position: gpui::Point<Pixels>,
6047 newest_selection_head: Option<DisplayPoint>,
6048 target_display_point: DisplayPoint,
6049 window: &mut Window,
6050 cx: &mut App,
6051 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6052 let scrolled_content_origin =
6053 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6054
6055 const SCROLL_PADDING_Y: Pixels = px(12.);
6056
6057 if target_display_point.row() < visible_row_range.start {
6058 return self.render_edit_prediction_scroll_popover(
6059 |_| SCROLL_PADDING_Y,
6060 IconName::ArrowUp,
6061 visible_row_range,
6062 line_layouts,
6063 newest_selection_head,
6064 scrolled_content_origin,
6065 window,
6066 cx,
6067 );
6068 } else if target_display_point.row() >= visible_row_range.end {
6069 return self.render_edit_prediction_scroll_popover(
6070 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6071 IconName::ArrowDown,
6072 visible_row_range,
6073 line_layouts,
6074 newest_selection_head,
6075 scrolled_content_origin,
6076 window,
6077 cx,
6078 );
6079 }
6080
6081 const POLE_WIDTH: Pixels = px(2.);
6082
6083 let line_layout =
6084 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6085 let target_column = target_display_point.column() as usize;
6086
6087 let target_x = line_layout.x_for_index(target_column);
6088 let target_y =
6089 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6090
6091 let flag_on_right = target_x < text_bounds.size.width / 2.;
6092
6093 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6094 border_color.l += 0.001;
6095
6096 let mut element = v_flex()
6097 .items_end()
6098 .when(flag_on_right, |el| el.items_start())
6099 .child(if flag_on_right {
6100 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6101 .rounded_bl(px(0.))
6102 .rounded_tl(px(0.))
6103 .border_l_2()
6104 .border_color(border_color)
6105 } else {
6106 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6107 .rounded_br(px(0.))
6108 .rounded_tr(px(0.))
6109 .border_r_2()
6110 .border_color(border_color)
6111 })
6112 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6113 .into_any();
6114
6115 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6116
6117 let mut origin = scrolled_content_origin + point(target_x, target_y)
6118 - point(
6119 if flag_on_right {
6120 POLE_WIDTH
6121 } else {
6122 size.width - POLE_WIDTH
6123 },
6124 size.height - line_height,
6125 );
6126
6127 origin.x = origin.x.max(content_origin.x);
6128
6129 element.prepaint_at(origin, window, cx);
6130
6131 Some((element, origin))
6132 }
6133
6134 #[allow(clippy::too_many_arguments)]
6135 fn render_edit_prediction_scroll_popover(
6136 &mut self,
6137 to_y: impl Fn(Size<Pixels>) -> Pixels,
6138 scroll_icon: IconName,
6139 visible_row_range: Range<DisplayRow>,
6140 line_layouts: &[LineWithInvisibles],
6141 newest_selection_head: Option<DisplayPoint>,
6142 scrolled_content_origin: gpui::Point<Pixels>,
6143 window: &mut Window,
6144 cx: &mut App,
6145 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6146 let mut element = self
6147 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6148 .into_any();
6149
6150 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6151
6152 let cursor = newest_selection_head?;
6153 let cursor_row_layout =
6154 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6155 let cursor_column = cursor.column() as usize;
6156
6157 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6158
6159 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6160
6161 element.prepaint_at(origin, window, cx);
6162 Some((element, origin))
6163 }
6164
6165 #[allow(clippy::too_many_arguments)]
6166 fn render_edit_prediction_eager_jump_popover(
6167 &mut self,
6168 text_bounds: &Bounds<Pixels>,
6169 content_origin: gpui::Point<Pixels>,
6170 editor_snapshot: &EditorSnapshot,
6171 visible_row_range: Range<DisplayRow>,
6172 scroll_top: f32,
6173 scroll_bottom: f32,
6174 line_height: Pixels,
6175 scroll_pixel_position: gpui::Point<Pixels>,
6176 target_display_point: DisplayPoint,
6177 editor_width: Pixels,
6178 window: &mut Window,
6179 cx: &mut App,
6180 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6181 if target_display_point.row().as_f32() < scroll_top {
6182 let mut element = self
6183 .render_edit_prediction_line_popover(
6184 "Jump to Edit",
6185 Some(IconName::ArrowUp),
6186 window,
6187 cx,
6188 )?
6189 .into_any();
6190
6191 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6192 let offset = point(
6193 (text_bounds.size.width - size.width) / 2.,
6194 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6195 );
6196
6197 let origin = text_bounds.origin + offset;
6198 element.prepaint_at(origin, window, cx);
6199 Some((element, origin))
6200 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6201 let mut element = self
6202 .render_edit_prediction_line_popover(
6203 "Jump to Edit",
6204 Some(IconName::ArrowDown),
6205 window,
6206 cx,
6207 )?
6208 .into_any();
6209
6210 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6211 let offset = point(
6212 (text_bounds.size.width - size.width) / 2.,
6213 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6214 );
6215
6216 let origin = text_bounds.origin + offset;
6217 element.prepaint_at(origin, window, cx);
6218 Some((element, origin))
6219 } else {
6220 self.render_edit_prediction_end_of_line_popover(
6221 "Jump to Edit",
6222 editor_snapshot,
6223 visible_row_range,
6224 target_display_point,
6225 line_height,
6226 scroll_pixel_position,
6227 content_origin,
6228 editor_width,
6229 window,
6230 cx,
6231 )
6232 }
6233 }
6234
6235 #[allow(clippy::too_many_arguments)]
6236 fn render_edit_prediction_end_of_line_popover(
6237 self: &mut Editor,
6238 label: &'static str,
6239 editor_snapshot: &EditorSnapshot,
6240 visible_row_range: Range<DisplayRow>,
6241 target_display_point: DisplayPoint,
6242 line_height: Pixels,
6243 scroll_pixel_position: gpui::Point<Pixels>,
6244 content_origin: gpui::Point<Pixels>,
6245 editor_width: Pixels,
6246 window: &mut Window,
6247 cx: &mut App,
6248 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6249 let target_line_end = DisplayPoint::new(
6250 target_display_point.row(),
6251 editor_snapshot.line_len(target_display_point.row()),
6252 );
6253
6254 let mut element = self
6255 .render_edit_prediction_line_popover(label, None, window, cx)?
6256 .into_any();
6257
6258 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6259
6260 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6261
6262 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6263 let mut origin = start_point
6264 + line_origin
6265 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6266 origin.x = origin.x.max(content_origin.x);
6267
6268 let max_x = content_origin.x + editor_width - size.width;
6269
6270 if origin.x > max_x {
6271 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6272
6273 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6274 origin.y += offset;
6275 IconName::ArrowUp
6276 } else {
6277 origin.y -= offset;
6278 IconName::ArrowDown
6279 };
6280
6281 element = self
6282 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6283 .into_any();
6284
6285 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6286
6287 origin.x = content_origin.x + editor_width - size.width - px(2.);
6288 }
6289
6290 element.prepaint_at(origin, window, cx);
6291 Some((element, origin))
6292 }
6293
6294 #[allow(clippy::too_many_arguments)]
6295 fn render_edit_prediction_diff_popover(
6296 self: &Editor,
6297 text_bounds: &Bounds<Pixels>,
6298 content_origin: gpui::Point<Pixels>,
6299 editor_snapshot: &EditorSnapshot,
6300 visible_row_range: Range<DisplayRow>,
6301 line_layouts: &[LineWithInvisibles],
6302 line_height: Pixels,
6303 scroll_pixel_position: gpui::Point<Pixels>,
6304 newest_selection_head: Option<DisplayPoint>,
6305 editor_width: Pixels,
6306 style: &EditorStyle,
6307 edits: &Vec<(Range<Anchor>, String)>,
6308 edit_preview: &Option<language::EditPreview>,
6309 snapshot: &language::BufferSnapshot,
6310 window: &mut Window,
6311 cx: &mut App,
6312 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6313 let edit_start = edits
6314 .first()
6315 .unwrap()
6316 .0
6317 .start
6318 .to_display_point(editor_snapshot);
6319 let edit_end = edits
6320 .last()
6321 .unwrap()
6322 .0
6323 .end
6324 .to_display_point(editor_snapshot);
6325
6326 let is_visible = visible_row_range.contains(&edit_start.row())
6327 || visible_row_range.contains(&edit_end.row());
6328 if !is_visible {
6329 return None;
6330 }
6331
6332 let highlighted_edits =
6333 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6334
6335 let styled_text = highlighted_edits.to_styled_text(&style.text);
6336 let line_count = highlighted_edits.text.lines().count();
6337
6338 const BORDER_WIDTH: Pixels = px(1.);
6339
6340 let mut element = h_flex()
6341 .items_start()
6342 .child(
6343 h_flex()
6344 .bg(cx.theme().colors().editor_background)
6345 .border(BORDER_WIDTH)
6346 .shadow_sm()
6347 .border_color(cx.theme().colors().border)
6348 .rounded_l_lg()
6349 .when(line_count > 1, |el| el.rounded_br_lg())
6350 .pr_1()
6351 .child(styled_text),
6352 )
6353 .child(
6354 h_flex()
6355 .h(line_height + BORDER_WIDTH * px(2.))
6356 .px_1p5()
6357 .gap_1()
6358 // Workaround: For some reason, there's a gap if we don't do this
6359 .ml(-BORDER_WIDTH)
6360 .shadow(smallvec![gpui::BoxShadow {
6361 color: gpui::black().opacity(0.05),
6362 offset: point(px(1.), px(1.)),
6363 blur_radius: px(2.),
6364 spread_radius: px(0.),
6365 }])
6366 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6367 .border(BORDER_WIDTH)
6368 .border_color(cx.theme().colors().border)
6369 .rounded_r_lg()
6370 .children(self.render_edit_prediction_accept_keybind(window, cx)),
6371 )
6372 .into_any();
6373
6374 let longest_row =
6375 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6376 let longest_line_width = if visible_row_range.contains(&longest_row) {
6377 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6378 } else {
6379 layout_line(
6380 longest_row,
6381 editor_snapshot,
6382 style,
6383 editor_width,
6384 |_| false,
6385 window,
6386 cx,
6387 )
6388 .width
6389 };
6390
6391 let viewport_bounds =
6392 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6393 right: -EditorElement::SCROLLBAR_WIDTH,
6394 ..Default::default()
6395 });
6396
6397 let x_after_longest =
6398 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6399 - scroll_pixel_position.x;
6400
6401 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6402
6403 // Fully visible if it can be displayed within the window (allow overlapping other
6404 // panes). However, this is only allowed if the popover starts within text_bounds.
6405 let can_position_to_the_right = x_after_longest < text_bounds.right()
6406 && x_after_longest + element_bounds.width < viewport_bounds.right();
6407
6408 let mut origin = if can_position_to_the_right {
6409 point(
6410 x_after_longest,
6411 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6412 - scroll_pixel_position.y,
6413 )
6414 } else {
6415 let cursor_row = newest_selection_head.map(|head| head.row());
6416 let above_edit = edit_start
6417 .row()
6418 .0
6419 .checked_sub(line_count as u32)
6420 .map(DisplayRow);
6421 let below_edit = Some(edit_end.row() + 1);
6422 let above_cursor =
6423 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6424 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6425
6426 // Place the edit popover adjacent to the edit if there is a location
6427 // available that is onscreen and does not obscure the cursor. Otherwise,
6428 // place it adjacent to the cursor.
6429 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6430 .into_iter()
6431 .flatten()
6432 .find(|&start_row| {
6433 let end_row = start_row + line_count as u32;
6434 visible_row_range.contains(&start_row)
6435 && visible_row_range.contains(&end_row)
6436 && cursor_row.map_or(true, |cursor_row| {
6437 !((start_row..end_row).contains(&cursor_row))
6438 })
6439 })?;
6440
6441 content_origin
6442 + point(
6443 -scroll_pixel_position.x,
6444 row_target.as_f32() * line_height - scroll_pixel_position.y,
6445 )
6446 };
6447
6448 origin.x -= BORDER_WIDTH;
6449
6450 window.defer_draw(element, origin, 1);
6451
6452 // Do not return an element, since it will already be drawn due to defer_draw.
6453 None
6454 }
6455
6456 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6457 px(30.)
6458 }
6459
6460 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6461 if self.read_only(cx) {
6462 cx.theme().players().read_only()
6463 } else {
6464 self.style.as_ref().unwrap().local_player
6465 }
6466 }
6467
6468 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
6469 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6470 let accept_keystroke = accept_binding.keystroke()?;
6471
6472 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6473
6474 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6475 Color::Accent
6476 } else {
6477 Color::Muted
6478 };
6479
6480 h_flex()
6481 .px_0p5()
6482 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6483 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6484 .text_size(TextSize::XSmall.rems(cx))
6485 .child(h_flex().children(ui::render_modifiers(
6486 &accept_keystroke.modifiers,
6487 PlatformStyle::platform(),
6488 Some(modifiers_color),
6489 Some(IconSize::XSmall.rems().into()),
6490 true,
6491 )))
6492 .when(is_platform_style_mac, |parent| {
6493 parent.child(accept_keystroke.key.clone())
6494 })
6495 .when(!is_platform_style_mac, |parent| {
6496 parent.child(
6497 Key::new(
6498 util::capitalize(&accept_keystroke.key),
6499 Some(Color::Default),
6500 )
6501 .size(Some(IconSize::XSmall.rems().into())),
6502 )
6503 })
6504 .into()
6505 }
6506
6507 fn render_edit_prediction_line_popover(
6508 &self,
6509 label: impl Into<SharedString>,
6510 icon: Option<IconName>,
6511 window: &mut Window,
6512 cx: &App,
6513 ) -> Option<Div> {
6514 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6515
6516 let result = h_flex()
6517 .py_0p5()
6518 .pl_1()
6519 .pr(padding_right)
6520 .gap_1()
6521 .rounded(px(6.))
6522 .border_1()
6523 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6524 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6525 .shadow_sm()
6526 .children(self.render_edit_prediction_accept_keybind(window, cx))
6527 .child(Label::new(label).size(LabelSize::Small))
6528 .when_some(icon, |element, icon| {
6529 element.child(
6530 div()
6531 .mt(px(1.5))
6532 .child(Icon::new(icon).size(IconSize::Small)),
6533 )
6534 });
6535
6536 Some(result)
6537 }
6538
6539 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6540 let accent_color = cx.theme().colors().text_accent;
6541 let editor_bg_color = cx.theme().colors().editor_background;
6542 editor_bg_color.blend(accent_color.opacity(0.1))
6543 }
6544
6545 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6546 let accent_color = cx.theme().colors().text_accent;
6547 let editor_bg_color = cx.theme().colors().editor_background;
6548 editor_bg_color.blend(accent_color.opacity(0.6))
6549 }
6550
6551 #[allow(clippy::too_many_arguments)]
6552 fn render_edit_prediction_cursor_popover(
6553 &self,
6554 min_width: Pixels,
6555 max_width: Pixels,
6556 cursor_point: Point,
6557 style: &EditorStyle,
6558 accept_keystroke: Option<&gpui::Keystroke>,
6559 _window: &Window,
6560 cx: &mut Context<Editor>,
6561 ) -> Option<AnyElement> {
6562 let provider = self.edit_prediction_provider.as_ref()?;
6563
6564 if provider.provider.needs_terms_acceptance(cx) {
6565 return Some(
6566 h_flex()
6567 .min_w(min_width)
6568 .flex_1()
6569 .px_2()
6570 .py_1()
6571 .gap_3()
6572 .elevation_2(cx)
6573 .hover(|style| style.bg(cx.theme().colors().element_hover))
6574 .id("accept-terms")
6575 .cursor_pointer()
6576 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6577 .on_click(cx.listener(|this, _event, window, cx| {
6578 cx.stop_propagation();
6579 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6580 window.dispatch_action(
6581 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6582 cx,
6583 );
6584 }))
6585 .child(
6586 h_flex()
6587 .flex_1()
6588 .gap_2()
6589 .child(Icon::new(IconName::ZedPredict))
6590 .child(Label::new("Accept Terms of Service"))
6591 .child(div().w_full())
6592 .child(
6593 Icon::new(IconName::ArrowUpRight)
6594 .color(Color::Muted)
6595 .size(IconSize::Small),
6596 )
6597 .into_any_element(),
6598 )
6599 .into_any(),
6600 );
6601 }
6602
6603 let is_refreshing = provider.provider.is_refreshing(cx);
6604
6605 fn pending_completion_container() -> Div {
6606 h_flex()
6607 .h_full()
6608 .flex_1()
6609 .gap_2()
6610 .child(Icon::new(IconName::ZedPredict))
6611 }
6612
6613 let completion = match &self.active_inline_completion {
6614 Some(prediction) => {
6615 if !self.has_visible_completions_menu() {
6616 const RADIUS: Pixels = px(6.);
6617 const BORDER_WIDTH: Pixels = px(1.);
6618
6619 return Some(
6620 h_flex()
6621 .elevation_2(cx)
6622 .border(BORDER_WIDTH)
6623 .border_color(cx.theme().colors().border)
6624 .rounded(RADIUS)
6625 .rounded_tl(px(0.))
6626 .overflow_hidden()
6627 .child(div().px_1p5().child(match &prediction.completion {
6628 InlineCompletion::Move { target, snapshot } => {
6629 use text::ToPoint as _;
6630 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6631 {
6632 Icon::new(IconName::ZedPredictDown)
6633 } else {
6634 Icon::new(IconName::ZedPredictUp)
6635 }
6636 }
6637 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6638 }))
6639 .child(
6640 h_flex()
6641 .gap_1()
6642 .py_1()
6643 .px_2()
6644 .rounded_r(RADIUS - BORDER_WIDTH)
6645 .border_l_1()
6646 .border_color(cx.theme().colors().border)
6647 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6648 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6649 el.child(
6650 Label::new("Hold")
6651 .size(LabelSize::Small)
6652 .line_height_style(LineHeightStyle::UiLabel),
6653 )
6654 })
6655 .child(h_flex().children(ui::render_modifiers(
6656 &accept_keystroke?.modifiers,
6657 PlatformStyle::platform(),
6658 Some(Color::Default),
6659 Some(IconSize::XSmall.rems().into()),
6660 false,
6661 ))),
6662 )
6663 .into_any(),
6664 );
6665 }
6666
6667 self.render_edit_prediction_cursor_popover_preview(
6668 prediction,
6669 cursor_point,
6670 style,
6671 cx,
6672 )?
6673 }
6674
6675 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6676 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6677 stale_completion,
6678 cursor_point,
6679 style,
6680 cx,
6681 )?,
6682
6683 None => {
6684 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6685 }
6686 },
6687
6688 None => pending_completion_container().child(Label::new("No Prediction")),
6689 };
6690
6691 let completion = if is_refreshing {
6692 completion
6693 .with_animation(
6694 "loading-completion",
6695 Animation::new(Duration::from_secs(2))
6696 .repeat()
6697 .with_easing(pulsating_between(0.4, 0.8)),
6698 |label, delta| label.opacity(delta),
6699 )
6700 .into_any_element()
6701 } else {
6702 completion.into_any_element()
6703 };
6704
6705 let has_completion = self.active_inline_completion.is_some();
6706
6707 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6708 Some(
6709 h_flex()
6710 .min_w(min_width)
6711 .max_w(max_width)
6712 .flex_1()
6713 .elevation_2(cx)
6714 .border_color(cx.theme().colors().border)
6715 .child(
6716 div()
6717 .flex_1()
6718 .py_1()
6719 .px_2()
6720 .overflow_hidden()
6721 .child(completion),
6722 )
6723 .when_some(accept_keystroke, |el, accept_keystroke| {
6724 if !accept_keystroke.modifiers.modified() {
6725 return el;
6726 }
6727
6728 el.child(
6729 h_flex()
6730 .h_full()
6731 .border_l_1()
6732 .rounded_r_lg()
6733 .border_color(cx.theme().colors().border)
6734 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6735 .gap_1()
6736 .py_1()
6737 .px_2()
6738 .child(
6739 h_flex()
6740 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6741 .when(is_platform_style_mac, |parent| parent.gap_1())
6742 .child(h_flex().children(ui::render_modifiers(
6743 &accept_keystroke.modifiers,
6744 PlatformStyle::platform(),
6745 Some(if !has_completion {
6746 Color::Muted
6747 } else {
6748 Color::Default
6749 }),
6750 None,
6751 false,
6752 ))),
6753 )
6754 .child(Label::new("Preview").into_any_element())
6755 .opacity(if has_completion { 1.0 } else { 0.4 }),
6756 )
6757 })
6758 .into_any(),
6759 )
6760 }
6761
6762 fn render_edit_prediction_cursor_popover_preview(
6763 &self,
6764 completion: &InlineCompletionState,
6765 cursor_point: Point,
6766 style: &EditorStyle,
6767 cx: &mut Context<Editor>,
6768 ) -> Option<Div> {
6769 use text::ToPoint as _;
6770
6771 fn render_relative_row_jump(
6772 prefix: impl Into<String>,
6773 current_row: u32,
6774 target_row: u32,
6775 ) -> Div {
6776 let (row_diff, arrow) = if target_row < current_row {
6777 (current_row - target_row, IconName::ArrowUp)
6778 } else {
6779 (target_row - current_row, IconName::ArrowDown)
6780 };
6781
6782 h_flex()
6783 .child(
6784 Label::new(format!("{}{}", prefix.into(), row_diff))
6785 .color(Color::Muted)
6786 .size(LabelSize::Small),
6787 )
6788 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6789 }
6790
6791 match &completion.completion {
6792 InlineCompletion::Move {
6793 target, snapshot, ..
6794 } => Some(
6795 h_flex()
6796 .px_2()
6797 .gap_2()
6798 .flex_1()
6799 .child(
6800 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6801 Icon::new(IconName::ZedPredictDown)
6802 } else {
6803 Icon::new(IconName::ZedPredictUp)
6804 },
6805 )
6806 .child(Label::new("Jump to Edit")),
6807 ),
6808
6809 InlineCompletion::Edit {
6810 edits,
6811 edit_preview,
6812 snapshot,
6813 display_mode: _,
6814 } => {
6815 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6816
6817 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6818 &snapshot,
6819 &edits,
6820 edit_preview.as_ref()?,
6821 true,
6822 cx,
6823 )
6824 .first_line_preview();
6825
6826 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6827 .with_default_highlights(&style.text, highlighted_edits.highlights);
6828
6829 let preview = h_flex()
6830 .gap_1()
6831 .min_w_16()
6832 .child(styled_text)
6833 .when(has_more_lines, |parent| parent.child("…"));
6834
6835 let left = if first_edit_row != cursor_point.row {
6836 render_relative_row_jump("", cursor_point.row, first_edit_row)
6837 .into_any_element()
6838 } else {
6839 Icon::new(IconName::ZedPredict).into_any_element()
6840 };
6841
6842 Some(
6843 h_flex()
6844 .h_full()
6845 .flex_1()
6846 .gap_2()
6847 .pr_1()
6848 .overflow_x_hidden()
6849 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6850 .child(left)
6851 .child(preview),
6852 )
6853 }
6854 }
6855 }
6856
6857 fn render_context_menu(
6858 &self,
6859 style: &EditorStyle,
6860 max_height_in_lines: u32,
6861 y_flipped: bool,
6862 window: &mut Window,
6863 cx: &mut Context<Editor>,
6864 ) -> Option<AnyElement> {
6865 let menu = self.context_menu.borrow();
6866 let menu = menu.as_ref()?;
6867 if !menu.visible() {
6868 return None;
6869 };
6870 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6871 }
6872
6873 fn render_context_menu_aside(
6874 &mut self,
6875 max_size: Size<Pixels>,
6876 window: &mut Window,
6877 cx: &mut Context<Editor>,
6878 ) -> Option<AnyElement> {
6879 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6880 if menu.visible() {
6881 menu.render_aside(self, max_size, window, cx)
6882 } else {
6883 None
6884 }
6885 })
6886 }
6887
6888 fn hide_context_menu(
6889 &mut self,
6890 window: &mut Window,
6891 cx: &mut Context<Self>,
6892 ) -> Option<CodeContextMenu> {
6893 cx.notify();
6894 self.completion_tasks.clear();
6895 let context_menu = self.context_menu.borrow_mut().take();
6896 self.stale_inline_completion_in_menu.take();
6897 self.update_visible_inline_completion(window, cx);
6898 context_menu
6899 }
6900
6901 fn show_snippet_choices(
6902 &mut self,
6903 choices: &Vec<String>,
6904 selection: Range<Anchor>,
6905 cx: &mut Context<Self>,
6906 ) {
6907 if selection.start.buffer_id.is_none() {
6908 return;
6909 }
6910 let buffer_id = selection.start.buffer_id.unwrap();
6911 let buffer = self.buffer().read(cx).buffer(buffer_id);
6912 let id = post_inc(&mut self.next_completion_id);
6913
6914 if let Some(buffer) = buffer {
6915 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6916 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6917 ));
6918 }
6919 }
6920
6921 pub fn insert_snippet(
6922 &mut self,
6923 insertion_ranges: &[Range<usize>],
6924 snippet: Snippet,
6925 window: &mut Window,
6926 cx: &mut Context<Self>,
6927 ) -> Result<()> {
6928 struct Tabstop<T> {
6929 is_end_tabstop: bool,
6930 ranges: Vec<Range<T>>,
6931 choices: Option<Vec<String>>,
6932 }
6933
6934 let tabstops = self.buffer.update(cx, |buffer, cx| {
6935 let snippet_text: Arc<str> = snippet.text.clone().into();
6936 buffer.edit(
6937 insertion_ranges
6938 .iter()
6939 .cloned()
6940 .map(|range| (range, snippet_text.clone())),
6941 Some(AutoindentMode::EachLine),
6942 cx,
6943 );
6944
6945 let snapshot = &*buffer.read(cx);
6946 let snippet = &snippet;
6947 snippet
6948 .tabstops
6949 .iter()
6950 .map(|tabstop| {
6951 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6952 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6953 });
6954 let mut tabstop_ranges = tabstop
6955 .ranges
6956 .iter()
6957 .flat_map(|tabstop_range| {
6958 let mut delta = 0_isize;
6959 insertion_ranges.iter().map(move |insertion_range| {
6960 let insertion_start = insertion_range.start as isize + delta;
6961 delta +=
6962 snippet.text.len() as isize - insertion_range.len() as isize;
6963
6964 let start = ((insertion_start + tabstop_range.start) as usize)
6965 .min(snapshot.len());
6966 let end = ((insertion_start + tabstop_range.end) as usize)
6967 .min(snapshot.len());
6968 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6969 })
6970 })
6971 .collect::<Vec<_>>();
6972 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6973
6974 Tabstop {
6975 is_end_tabstop,
6976 ranges: tabstop_ranges,
6977 choices: tabstop.choices.clone(),
6978 }
6979 })
6980 .collect::<Vec<_>>()
6981 });
6982 if let Some(tabstop) = tabstops.first() {
6983 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6984 s.select_ranges(tabstop.ranges.iter().cloned());
6985 });
6986
6987 if let Some(choices) = &tabstop.choices {
6988 if let Some(selection) = tabstop.ranges.first() {
6989 self.show_snippet_choices(choices, selection.clone(), cx)
6990 }
6991 }
6992
6993 // If we're already at the last tabstop and it's at the end of the snippet,
6994 // we're done, we don't need to keep the state around.
6995 if !tabstop.is_end_tabstop {
6996 let choices = tabstops
6997 .iter()
6998 .map(|tabstop| tabstop.choices.clone())
6999 .collect();
7000
7001 let ranges = tabstops
7002 .into_iter()
7003 .map(|tabstop| tabstop.ranges)
7004 .collect::<Vec<_>>();
7005
7006 self.snippet_stack.push(SnippetState {
7007 active_index: 0,
7008 ranges,
7009 choices,
7010 });
7011 }
7012
7013 // Check whether the just-entered snippet ends with an auto-closable bracket.
7014 if self.autoclose_regions.is_empty() {
7015 let snapshot = self.buffer.read(cx).snapshot(cx);
7016 for selection in &mut self.selections.all::<Point>(cx) {
7017 let selection_head = selection.head();
7018 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7019 continue;
7020 };
7021
7022 let mut bracket_pair = None;
7023 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7024 let prev_chars = snapshot
7025 .reversed_chars_at(selection_head)
7026 .collect::<String>();
7027 for (pair, enabled) in scope.brackets() {
7028 if enabled
7029 && pair.close
7030 && prev_chars.starts_with(pair.start.as_str())
7031 && next_chars.starts_with(pair.end.as_str())
7032 {
7033 bracket_pair = Some(pair.clone());
7034 break;
7035 }
7036 }
7037 if let Some(pair) = bracket_pair {
7038 let start = snapshot.anchor_after(selection_head);
7039 let end = snapshot.anchor_after(selection_head);
7040 self.autoclose_regions.push(AutocloseRegion {
7041 selection_id: selection.id,
7042 range: start..end,
7043 pair,
7044 });
7045 }
7046 }
7047 }
7048 }
7049 Ok(())
7050 }
7051
7052 pub fn move_to_next_snippet_tabstop(
7053 &mut self,
7054 window: &mut Window,
7055 cx: &mut Context<Self>,
7056 ) -> bool {
7057 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7058 }
7059
7060 pub fn move_to_prev_snippet_tabstop(
7061 &mut self,
7062 window: &mut Window,
7063 cx: &mut Context<Self>,
7064 ) -> bool {
7065 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7066 }
7067
7068 pub fn move_to_snippet_tabstop(
7069 &mut self,
7070 bias: Bias,
7071 window: &mut Window,
7072 cx: &mut Context<Self>,
7073 ) -> bool {
7074 if let Some(mut snippet) = self.snippet_stack.pop() {
7075 match bias {
7076 Bias::Left => {
7077 if snippet.active_index > 0 {
7078 snippet.active_index -= 1;
7079 } else {
7080 self.snippet_stack.push(snippet);
7081 return false;
7082 }
7083 }
7084 Bias::Right => {
7085 if snippet.active_index + 1 < snippet.ranges.len() {
7086 snippet.active_index += 1;
7087 } else {
7088 self.snippet_stack.push(snippet);
7089 return false;
7090 }
7091 }
7092 }
7093 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7094 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7095 s.select_anchor_ranges(current_ranges.iter().cloned())
7096 });
7097
7098 if let Some(choices) = &snippet.choices[snippet.active_index] {
7099 if let Some(selection) = current_ranges.first() {
7100 self.show_snippet_choices(&choices, selection.clone(), cx);
7101 }
7102 }
7103
7104 // If snippet state is not at the last tabstop, push it back on the stack
7105 if snippet.active_index + 1 < snippet.ranges.len() {
7106 self.snippet_stack.push(snippet);
7107 }
7108 return true;
7109 }
7110 }
7111
7112 false
7113 }
7114
7115 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7116 self.transact(window, cx, |this, window, cx| {
7117 this.select_all(&SelectAll, window, cx);
7118 this.insert("", window, cx);
7119 });
7120 }
7121
7122 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7123 self.transact(window, cx, |this, window, cx| {
7124 this.select_autoclose_pair(window, cx);
7125 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7126 if !this.linked_edit_ranges.is_empty() {
7127 let selections = this.selections.all::<MultiBufferPoint>(cx);
7128 let snapshot = this.buffer.read(cx).snapshot(cx);
7129
7130 for selection in selections.iter() {
7131 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7132 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7133 if selection_start.buffer_id != selection_end.buffer_id {
7134 continue;
7135 }
7136 if let Some(ranges) =
7137 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7138 {
7139 for (buffer, entries) in ranges {
7140 linked_ranges.entry(buffer).or_default().extend(entries);
7141 }
7142 }
7143 }
7144 }
7145
7146 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7147 if !this.selections.line_mode {
7148 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7149 for selection in &mut selections {
7150 if selection.is_empty() {
7151 let old_head = selection.head();
7152 let mut new_head =
7153 movement::left(&display_map, old_head.to_display_point(&display_map))
7154 .to_point(&display_map);
7155 if let Some((buffer, line_buffer_range)) = display_map
7156 .buffer_snapshot
7157 .buffer_line_for_row(MultiBufferRow(old_head.row))
7158 {
7159 let indent_size =
7160 buffer.indent_size_for_line(line_buffer_range.start.row);
7161 let indent_len = match indent_size.kind {
7162 IndentKind::Space => {
7163 buffer.settings_at(line_buffer_range.start, cx).tab_size
7164 }
7165 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7166 };
7167 if old_head.column <= indent_size.len && old_head.column > 0 {
7168 let indent_len = indent_len.get();
7169 new_head = cmp::min(
7170 new_head,
7171 MultiBufferPoint::new(
7172 old_head.row,
7173 ((old_head.column - 1) / indent_len) * indent_len,
7174 ),
7175 );
7176 }
7177 }
7178
7179 selection.set_head(new_head, SelectionGoal::None);
7180 }
7181 }
7182 }
7183
7184 this.signature_help_state.set_backspace_pressed(true);
7185 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7186 s.select(selections)
7187 });
7188 this.insert("", window, cx);
7189 let empty_str: Arc<str> = Arc::from("");
7190 for (buffer, edits) in linked_ranges {
7191 let snapshot = buffer.read(cx).snapshot();
7192 use text::ToPoint as TP;
7193
7194 let edits = edits
7195 .into_iter()
7196 .map(|range| {
7197 let end_point = TP::to_point(&range.end, &snapshot);
7198 let mut start_point = TP::to_point(&range.start, &snapshot);
7199
7200 if end_point == start_point {
7201 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7202 .saturating_sub(1);
7203 start_point =
7204 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7205 };
7206
7207 (start_point..end_point, empty_str.clone())
7208 })
7209 .sorted_by_key(|(range, _)| range.start)
7210 .collect::<Vec<_>>();
7211 buffer.update(cx, |this, cx| {
7212 this.edit(edits, None, cx);
7213 })
7214 }
7215 this.refresh_inline_completion(true, false, window, cx);
7216 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7217 });
7218 }
7219
7220 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7221 self.transact(window, cx, |this, window, cx| {
7222 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7223 let line_mode = s.line_mode;
7224 s.move_with(|map, selection| {
7225 if selection.is_empty() && !line_mode {
7226 let cursor = movement::right(map, selection.head());
7227 selection.end = cursor;
7228 selection.reversed = true;
7229 selection.goal = SelectionGoal::None;
7230 }
7231 })
7232 });
7233 this.insert("", window, cx);
7234 this.refresh_inline_completion(true, false, window, cx);
7235 });
7236 }
7237
7238 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7239 if self.move_to_prev_snippet_tabstop(window, cx) {
7240 return;
7241 }
7242
7243 self.outdent(&Outdent, window, cx);
7244 }
7245
7246 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7247 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7248 return;
7249 }
7250
7251 let mut selections = self.selections.all_adjusted(cx);
7252 let buffer = self.buffer.read(cx);
7253 let snapshot = buffer.snapshot(cx);
7254 let rows_iter = selections.iter().map(|s| s.head().row);
7255 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7256
7257 let mut edits = Vec::new();
7258 let mut prev_edited_row = 0;
7259 let mut row_delta = 0;
7260 for selection in &mut selections {
7261 if selection.start.row != prev_edited_row {
7262 row_delta = 0;
7263 }
7264 prev_edited_row = selection.end.row;
7265
7266 // If the selection is non-empty, then increase the indentation of the selected lines.
7267 if !selection.is_empty() {
7268 row_delta =
7269 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7270 continue;
7271 }
7272
7273 // If the selection is empty and the cursor is in the leading whitespace before the
7274 // suggested indentation, then auto-indent the line.
7275 let cursor = selection.head();
7276 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7277 if let Some(suggested_indent) =
7278 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7279 {
7280 if cursor.column < suggested_indent.len
7281 && cursor.column <= current_indent.len
7282 && current_indent.len <= suggested_indent.len
7283 {
7284 selection.start = Point::new(cursor.row, suggested_indent.len);
7285 selection.end = selection.start;
7286 if row_delta == 0 {
7287 edits.extend(Buffer::edit_for_indent_size_adjustment(
7288 cursor.row,
7289 current_indent,
7290 suggested_indent,
7291 ));
7292 row_delta = suggested_indent.len - current_indent.len;
7293 }
7294 continue;
7295 }
7296 }
7297
7298 // Otherwise, insert a hard or soft tab.
7299 let settings = buffer.settings_at(cursor, cx);
7300 let tab_size = if settings.hard_tabs {
7301 IndentSize::tab()
7302 } else {
7303 let tab_size = settings.tab_size.get();
7304 let char_column = snapshot
7305 .text_for_range(Point::new(cursor.row, 0)..cursor)
7306 .flat_map(str::chars)
7307 .count()
7308 + row_delta as usize;
7309 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7310 IndentSize::spaces(chars_to_next_tab_stop)
7311 };
7312 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7313 selection.end = selection.start;
7314 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7315 row_delta += tab_size.len;
7316 }
7317
7318 self.transact(window, cx, |this, window, cx| {
7319 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7320 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7321 s.select(selections)
7322 });
7323 this.refresh_inline_completion(true, false, window, cx);
7324 });
7325 }
7326
7327 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7328 if self.read_only(cx) {
7329 return;
7330 }
7331 let mut selections = self.selections.all::<Point>(cx);
7332 let mut prev_edited_row = 0;
7333 let mut row_delta = 0;
7334 let mut edits = Vec::new();
7335 let buffer = self.buffer.read(cx);
7336 let snapshot = buffer.snapshot(cx);
7337 for selection in &mut selections {
7338 if selection.start.row != prev_edited_row {
7339 row_delta = 0;
7340 }
7341 prev_edited_row = selection.end.row;
7342
7343 row_delta =
7344 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7345 }
7346
7347 self.transact(window, cx, |this, window, cx| {
7348 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7349 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7350 s.select(selections)
7351 });
7352 });
7353 }
7354
7355 fn indent_selection(
7356 buffer: &MultiBuffer,
7357 snapshot: &MultiBufferSnapshot,
7358 selection: &mut Selection<Point>,
7359 edits: &mut Vec<(Range<Point>, String)>,
7360 delta_for_start_row: u32,
7361 cx: &App,
7362 ) -> u32 {
7363 let settings = buffer.settings_at(selection.start, cx);
7364 let tab_size = settings.tab_size.get();
7365 let indent_kind = if settings.hard_tabs {
7366 IndentKind::Tab
7367 } else {
7368 IndentKind::Space
7369 };
7370 let mut start_row = selection.start.row;
7371 let mut end_row = selection.end.row + 1;
7372
7373 // If a selection ends at the beginning of a line, don't indent
7374 // that last line.
7375 if selection.end.column == 0 && selection.end.row > selection.start.row {
7376 end_row -= 1;
7377 }
7378
7379 // Avoid re-indenting a row that has already been indented by a
7380 // previous selection, but still update this selection's column
7381 // to reflect that indentation.
7382 if delta_for_start_row > 0 {
7383 start_row += 1;
7384 selection.start.column += delta_for_start_row;
7385 if selection.end.row == selection.start.row {
7386 selection.end.column += delta_for_start_row;
7387 }
7388 }
7389
7390 let mut delta_for_end_row = 0;
7391 let has_multiple_rows = start_row + 1 != end_row;
7392 for row in start_row..end_row {
7393 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7394 let indent_delta = match (current_indent.kind, indent_kind) {
7395 (IndentKind::Space, IndentKind::Space) => {
7396 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7397 IndentSize::spaces(columns_to_next_tab_stop)
7398 }
7399 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7400 (_, IndentKind::Tab) => IndentSize::tab(),
7401 };
7402
7403 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7404 0
7405 } else {
7406 selection.start.column
7407 };
7408 let row_start = Point::new(row, start);
7409 edits.push((
7410 row_start..row_start,
7411 indent_delta.chars().collect::<String>(),
7412 ));
7413
7414 // Update this selection's endpoints to reflect the indentation.
7415 if row == selection.start.row {
7416 selection.start.column += indent_delta.len;
7417 }
7418 if row == selection.end.row {
7419 selection.end.column += indent_delta.len;
7420 delta_for_end_row = indent_delta.len;
7421 }
7422 }
7423
7424 if selection.start.row == selection.end.row {
7425 delta_for_start_row + delta_for_end_row
7426 } else {
7427 delta_for_end_row
7428 }
7429 }
7430
7431 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7432 if self.read_only(cx) {
7433 return;
7434 }
7435 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7436 let selections = self.selections.all::<Point>(cx);
7437 let mut deletion_ranges = Vec::new();
7438 let mut last_outdent = None;
7439 {
7440 let buffer = self.buffer.read(cx);
7441 let snapshot = buffer.snapshot(cx);
7442 for selection in &selections {
7443 let settings = buffer.settings_at(selection.start, cx);
7444 let tab_size = settings.tab_size.get();
7445 let mut rows = selection.spanned_rows(false, &display_map);
7446
7447 // Avoid re-outdenting a row that has already been outdented by a
7448 // previous selection.
7449 if let Some(last_row) = last_outdent {
7450 if last_row == rows.start {
7451 rows.start = rows.start.next_row();
7452 }
7453 }
7454 let has_multiple_rows = rows.len() > 1;
7455 for row in rows.iter_rows() {
7456 let indent_size = snapshot.indent_size_for_line(row);
7457 if indent_size.len > 0 {
7458 let deletion_len = match indent_size.kind {
7459 IndentKind::Space => {
7460 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7461 if columns_to_prev_tab_stop == 0 {
7462 tab_size
7463 } else {
7464 columns_to_prev_tab_stop
7465 }
7466 }
7467 IndentKind::Tab => 1,
7468 };
7469 let start = if has_multiple_rows
7470 || deletion_len > selection.start.column
7471 || indent_size.len < selection.start.column
7472 {
7473 0
7474 } else {
7475 selection.start.column - deletion_len
7476 };
7477 deletion_ranges.push(
7478 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7479 );
7480 last_outdent = Some(row);
7481 }
7482 }
7483 }
7484 }
7485
7486 self.transact(window, cx, |this, window, cx| {
7487 this.buffer.update(cx, |buffer, cx| {
7488 let empty_str: Arc<str> = Arc::default();
7489 buffer.edit(
7490 deletion_ranges
7491 .into_iter()
7492 .map(|range| (range, empty_str.clone())),
7493 None,
7494 cx,
7495 );
7496 });
7497 let selections = this.selections.all::<usize>(cx);
7498 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7499 s.select(selections)
7500 });
7501 });
7502 }
7503
7504 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7505 if self.read_only(cx) {
7506 return;
7507 }
7508 let selections = self
7509 .selections
7510 .all::<usize>(cx)
7511 .into_iter()
7512 .map(|s| s.range());
7513
7514 self.transact(window, cx, |this, window, cx| {
7515 this.buffer.update(cx, |buffer, cx| {
7516 buffer.autoindent_ranges(selections, cx);
7517 });
7518 let selections = this.selections.all::<usize>(cx);
7519 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7520 s.select(selections)
7521 });
7522 });
7523 }
7524
7525 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7526 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7527 let selections = self.selections.all::<Point>(cx);
7528
7529 let mut new_cursors = Vec::new();
7530 let mut edit_ranges = Vec::new();
7531 let mut selections = selections.iter().peekable();
7532 while let Some(selection) = selections.next() {
7533 let mut rows = selection.spanned_rows(false, &display_map);
7534 let goal_display_column = selection.head().to_display_point(&display_map).column();
7535
7536 // Accumulate contiguous regions of rows that we want to delete.
7537 while let Some(next_selection) = selections.peek() {
7538 let next_rows = next_selection.spanned_rows(false, &display_map);
7539 if next_rows.start <= rows.end {
7540 rows.end = next_rows.end;
7541 selections.next().unwrap();
7542 } else {
7543 break;
7544 }
7545 }
7546
7547 let buffer = &display_map.buffer_snapshot;
7548 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7549 let edit_end;
7550 let cursor_buffer_row;
7551 if buffer.max_point().row >= rows.end.0 {
7552 // If there's a line after the range, delete the \n from the end of the row range
7553 // and position the cursor on the next line.
7554 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7555 cursor_buffer_row = rows.end;
7556 } else {
7557 // If there isn't a line after the range, delete the \n from the line before the
7558 // start of the row range and position the cursor there.
7559 edit_start = edit_start.saturating_sub(1);
7560 edit_end = buffer.len();
7561 cursor_buffer_row = rows.start.previous_row();
7562 }
7563
7564 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7565 *cursor.column_mut() =
7566 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7567
7568 new_cursors.push((
7569 selection.id,
7570 buffer.anchor_after(cursor.to_point(&display_map)),
7571 ));
7572 edit_ranges.push(edit_start..edit_end);
7573 }
7574
7575 self.transact(window, cx, |this, window, cx| {
7576 let buffer = this.buffer.update(cx, |buffer, cx| {
7577 let empty_str: Arc<str> = Arc::default();
7578 buffer.edit(
7579 edit_ranges
7580 .into_iter()
7581 .map(|range| (range, empty_str.clone())),
7582 None,
7583 cx,
7584 );
7585 buffer.snapshot(cx)
7586 });
7587 let new_selections = new_cursors
7588 .into_iter()
7589 .map(|(id, cursor)| {
7590 let cursor = cursor.to_point(&buffer);
7591 Selection {
7592 id,
7593 start: cursor,
7594 end: cursor,
7595 reversed: false,
7596 goal: SelectionGoal::None,
7597 }
7598 })
7599 .collect();
7600
7601 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7602 s.select(new_selections);
7603 });
7604 });
7605 }
7606
7607 pub fn join_lines_impl(
7608 &mut self,
7609 insert_whitespace: bool,
7610 window: &mut Window,
7611 cx: &mut Context<Self>,
7612 ) {
7613 if self.read_only(cx) {
7614 return;
7615 }
7616 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7617 for selection in self.selections.all::<Point>(cx) {
7618 let start = MultiBufferRow(selection.start.row);
7619 // Treat single line selections as if they include the next line. Otherwise this action
7620 // would do nothing for single line selections individual cursors.
7621 let end = if selection.start.row == selection.end.row {
7622 MultiBufferRow(selection.start.row + 1)
7623 } else {
7624 MultiBufferRow(selection.end.row)
7625 };
7626
7627 if let Some(last_row_range) = row_ranges.last_mut() {
7628 if start <= last_row_range.end {
7629 last_row_range.end = end;
7630 continue;
7631 }
7632 }
7633 row_ranges.push(start..end);
7634 }
7635
7636 let snapshot = self.buffer.read(cx).snapshot(cx);
7637 let mut cursor_positions = Vec::new();
7638 for row_range in &row_ranges {
7639 let anchor = snapshot.anchor_before(Point::new(
7640 row_range.end.previous_row().0,
7641 snapshot.line_len(row_range.end.previous_row()),
7642 ));
7643 cursor_positions.push(anchor..anchor);
7644 }
7645
7646 self.transact(window, cx, |this, window, cx| {
7647 for row_range in row_ranges.into_iter().rev() {
7648 for row in row_range.iter_rows().rev() {
7649 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7650 let next_line_row = row.next_row();
7651 let indent = snapshot.indent_size_for_line(next_line_row);
7652 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7653
7654 let replace =
7655 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7656 " "
7657 } else {
7658 ""
7659 };
7660
7661 this.buffer.update(cx, |buffer, cx| {
7662 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7663 });
7664 }
7665 }
7666
7667 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7668 s.select_anchor_ranges(cursor_positions)
7669 });
7670 });
7671 }
7672
7673 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7674 self.join_lines_impl(true, window, cx);
7675 }
7676
7677 pub fn sort_lines_case_sensitive(
7678 &mut self,
7679 _: &SortLinesCaseSensitive,
7680 window: &mut Window,
7681 cx: &mut Context<Self>,
7682 ) {
7683 self.manipulate_lines(window, cx, |lines| lines.sort())
7684 }
7685
7686 pub fn sort_lines_case_insensitive(
7687 &mut self,
7688 _: &SortLinesCaseInsensitive,
7689 window: &mut Window,
7690 cx: &mut Context<Self>,
7691 ) {
7692 self.manipulate_lines(window, cx, |lines| {
7693 lines.sort_by_key(|line| line.to_lowercase())
7694 })
7695 }
7696
7697 pub fn unique_lines_case_insensitive(
7698 &mut self,
7699 _: &UniqueLinesCaseInsensitive,
7700 window: &mut Window,
7701 cx: &mut Context<Self>,
7702 ) {
7703 self.manipulate_lines(window, cx, |lines| {
7704 let mut seen = HashSet::default();
7705 lines.retain(|line| seen.insert(line.to_lowercase()));
7706 })
7707 }
7708
7709 pub fn unique_lines_case_sensitive(
7710 &mut self,
7711 _: &UniqueLinesCaseSensitive,
7712 window: &mut Window,
7713 cx: &mut Context<Self>,
7714 ) {
7715 self.manipulate_lines(window, cx, |lines| {
7716 let mut seen = HashSet::default();
7717 lines.retain(|line| seen.insert(*line));
7718 })
7719 }
7720
7721 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7722 let Some(project) = self.project.clone() else {
7723 return;
7724 };
7725 self.reload(project, window, cx)
7726 .detach_and_notify_err(window, cx);
7727 }
7728
7729 pub fn restore_file(
7730 &mut self,
7731 _: &::git::RestoreFile,
7732 window: &mut Window,
7733 cx: &mut Context<Self>,
7734 ) {
7735 let mut buffer_ids = HashSet::default();
7736 let snapshot = self.buffer().read(cx).snapshot(cx);
7737 for selection in self.selections.all::<usize>(cx) {
7738 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7739 }
7740
7741 let buffer = self.buffer().read(cx);
7742 let ranges = buffer_ids
7743 .into_iter()
7744 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7745 .collect::<Vec<_>>();
7746
7747 self.restore_hunks_in_ranges(ranges, window, cx);
7748 }
7749
7750 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7751 let selections = self
7752 .selections
7753 .all(cx)
7754 .into_iter()
7755 .map(|s| s.range())
7756 .collect();
7757 self.restore_hunks_in_ranges(selections, window, cx);
7758 }
7759
7760 fn restore_hunks_in_ranges(
7761 &mut self,
7762 ranges: Vec<Range<Point>>,
7763 window: &mut Window,
7764 cx: &mut Context<Editor>,
7765 ) {
7766 let mut revert_changes = HashMap::default();
7767 let chunk_by = self
7768 .snapshot(window, cx)
7769 .hunks_for_ranges(ranges)
7770 .into_iter()
7771 .chunk_by(|hunk| hunk.buffer_id);
7772 for (buffer_id, hunks) in &chunk_by {
7773 let hunks = hunks.collect::<Vec<_>>();
7774 for hunk in &hunks {
7775 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7776 }
7777 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7778 }
7779 drop(chunk_by);
7780 if !revert_changes.is_empty() {
7781 self.transact(window, cx, |editor, window, cx| {
7782 editor.restore(revert_changes, window, cx);
7783 });
7784 }
7785 }
7786
7787 pub fn open_active_item_in_terminal(
7788 &mut self,
7789 _: &OpenInTerminal,
7790 window: &mut Window,
7791 cx: &mut Context<Self>,
7792 ) {
7793 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7794 let project_path = buffer.read(cx).project_path(cx)?;
7795 let project = self.project.as_ref()?.read(cx);
7796 let entry = project.entry_for_path(&project_path, cx)?;
7797 let parent = match &entry.canonical_path {
7798 Some(canonical_path) => canonical_path.to_path_buf(),
7799 None => project.absolute_path(&project_path, cx)?,
7800 }
7801 .parent()?
7802 .to_path_buf();
7803 Some(parent)
7804 }) {
7805 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7806 }
7807 }
7808
7809 pub fn prepare_restore_change(
7810 &self,
7811 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7812 hunk: &MultiBufferDiffHunk,
7813 cx: &mut App,
7814 ) -> Option<()> {
7815 let buffer = self.buffer.read(cx);
7816 let diff = buffer.diff_for(hunk.buffer_id)?;
7817 let buffer = buffer.buffer(hunk.buffer_id)?;
7818 let buffer = buffer.read(cx);
7819 let original_text = diff
7820 .read(cx)
7821 .base_text()
7822 .as_rope()
7823 .slice(hunk.diff_base_byte_range.clone());
7824 let buffer_snapshot = buffer.snapshot();
7825 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7826 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7827 probe
7828 .0
7829 .start
7830 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7831 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7832 }) {
7833 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7834 Some(())
7835 } else {
7836 None
7837 }
7838 }
7839
7840 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7841 self.manipulate_lines(window, cx, |lines| lines.reverse())
7842 }
7843
7844 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7845 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7846 }
7847
7848 fn manipulate_lines<Fn>(
7849 &mut self,
7850 window: &mut Window,
7851 cx: &mut Context<Self>,
7852 mut callback: Fn,
7853 ) where
7854 Fn: FnMut(&mut Vec<&str>),
7855 {
7856 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7857 let buffer = self.buffer.read(cx).snapshot(cx);
7858
7859 let mut edits = Vec::new();
7860
7861 let selections = self.selections.all::<Point>(cx);
7862 let mut selections = selections.iter().peekable();
7863 let mut contiguous_row_selections = Vec::new();
7864 let mut new_selections = Vec::new();
7865 let mut added_lines = 0;
7866 let mut removed_lines = 0;
7867
7868 while let Some(selection) = selections.next() {
7869 let (start_row, end_row) = consume_contiguous_rows(
7870 &mut contiguous_row_selections,
7871 selection,
7872 &display_map,
7873 &mut selections,
7874 );
7875
7876 let start_point = Point::new(start_row.0, 0);
7877 let end_point = Point::new(
7878 end_row.previous_row().0,
7879 buffer.line_len(end_row.previous_row()),
7880 );
7881 let text = buffer
7882 .text_for_range(start_point..end_point)
7883 .collect::<String>();
7884
7885 let mut lines = text.split('\n').collect_vec();
7886
7887 let lines_before = lines.len();
7888 callback(&mut lines);
7889 let lines_after = lines.len();
7890
7891 edits.push((start_point..end_point, lines.join("\n")));
7892
7893 // Selections must change based on added and removed line count
7894 let start_row =
7895 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7896 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7897 new_selections.push(Selection {
7898 id: selection.id,
7899 start: start_row,
7900 end: end_row,
7901 goal: SelectionGoal::None,
7902 reversed: selection.reversed,
7903 });
7904
7905 if lines_after > lines_before {
7906 added_lines += lines_after - lines_before;
7907 } else if lines_before > lines_after {
7908 removed_lines += lines_before - lines_after;
7909 }
7910 }
7911
7912 self.transact(window, cx, |this, window, cx| {
7913 let buffer = this.buffer.update(cx, |buffer, cx| {
7914 buffer.edit(edits, None, cx);
7915 buffer.snapshot(cx)
7916 });
7917
7918 // Recalculate offsets on newly edited buffer
7919 let new_selections = new_selections
7920 .iter()
7921 .map(|s| {
7922 let start_point = Point::new(s.start.0, 0);
7923 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7924 Selection {
7925 id: s.id,
7926 start: buffer.point_to_offset(start_point),
7927 end: buffer.point_to_offset(end_point),
7928 goal: s.goal,
7929 reversed: s.reversed,
7930 }
7931 })
7932 .collect();
7933
7934 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7935 s.select(new_selections);
7936 });
7937
7938 this.request_autoscroll(Autoscroll::fit(), cx);
7939 });
7940 }
7941
7942 pub fn convert_to_upper_case(
7943 &mut self,
7944 _: &ConvertToUpperCase,
7945 window: &mut Window,
7946 cx: &mut Context<Self>,
7947 ) {
7948 self.manipulate_text(window, cx, |text| text.to_uppercase())
7949 }
7950
7951 pub fn convert_to_lower_case(
7952 &mut self,
7953 _: &ConvertToLowerCase,
7954 window: &mut Window,
7955 cx: &mut Context<Self>,
7956 ) {
7957 self.manipulate_text(window, cx, |text| text.to_lowercase())
7958 }
7959
7960 pub fn convert_to_title_case(
7961 &mut self,
7962 _: &ConvertToTitleCase,
7963 window: &mut Window,
7964 cx: &mut Context<Self>,
7965 ) {
7966 self.manipulate_text(window, cx, |text| {
7967 text.split('\n')
7968 .map(|line| line.to_case(Case::Title))
7969 .join("\n")
7970 })
7971 }
7972
7973 pub fn convert_to_snake_case(
7974 &mut self,
7975 _: &ConvertToSnakeCase,
7976 window: &mut Window,
7977 cx: &mut Context<Self>,
7978 ) {
7979 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7980 }
7981
7982 pub fn convert_to_kebab_case(
7983 &mut self,
7984 _: &ConvertToKebabCase,
7985 window: &mut Window,
7986 cx: &mut Context<Self>,
7987 ) {
7988 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7989 }
7990
7991 pub fn convert_to_upper_camel_case(
7992 &mut self,
7993 _: &ConvertToUpperCamelCase,
7994 window: &mut Window,
7995 cx: &mut Context<Self>,
7996 ) {
7997 self.manipulate_text(window, cx, |text| {
7998 text.split('\n')
7999 .map(|line| line.to_case(Case::UpperCamel))
8000 .join("\n")
8001 })
8002 }
8003
8004 pub fn convert_to_lower_camel_case(
8005 &mut self,
8006 _: &ConvertToLowerCamelCase,
8007 window: &mut Window,
8008 cx: &mut Context<Self>,
8009 ) {
8010 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8011 }
8012
8013 pub fn convert_to_opposite_case(
8014 &mut self,
8015 _: &ConvertToOppositeCase,
8016 window: &mut Window,
8017 cx: &mut Context<Self>,
8018 ) {
8019 self.manipulate_text(window, cx, |text| {
8020 text.chars()
8021 .fold(String::with_capacity(text.len()), |mut t, c| {
8022 if c.is_uppercase() {
8023 t.extend(c.to_lowercase());
8024 } else {
8025 t.extend(c.to_uppercase());
8026 }
8027 t
8028 })
8029 })
8030 }
8031
8032 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8033 where
8034 Fn: FnMut(&str) -> String,
8035 {
8036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8037 let buffer = self.buffer.read(cx).snapshot(cx);
8038
8039 let mut new_selections = Vec::new();
8040 let mut edits = Vec::new();
8041 let mut selection_adjustment = 0i32;
8042
8043 for selection in self.selections.all::<usize>(cx) {
8044 let selection_is_empty = selection.is_empty();
8045
8046 let (start, end) = if selection_is_empty {
8047 let word_range = movement::surrounding_word(
8048 &display_map,
8049 selection.start.to_display_point(&display_map),
8050 );
8051 let start = word_range.start.to_offset(&display_map, Bias::Left);
8052 let end = word_range.end.to_offset(&display_map, Bias::Left);
8053 (start, end)
8054 } else {
8055 (selection.start, selection.end)
8056 };
8057
8058 let text = buffer.text_for_range(start..end).collect::<String>();
8059 let old_length = text.len() as i32;
8060 let text = callback(&text);
8061
8062 new_selections.push(Selection {
8063 start: (start as i32 - selection_adjustment) as usize,
8064 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8065 goal: SelectionGoal::None,
8066 ..selection
8067 });
8068
8069 selection_adjustment += old_length - text.len() as i32;
8070
8071 edits.push((start..end, text));
8072 }
8073
8074 self.transact(window, cx, |this, window, cx| {
8075 this.buffer.update(cx, |buffer, cx| {
8076 buffer.edit(edits, None, cx);
8077 });
8078
8079 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8080 s.select(new_selections);
8081 });
8082
8083 this.request_autoscroll(Autoscroll::fit(), cx);
8084 });
8085 }
8086
8087 pub fn duplicate(
8088 &mut self,
8089 upwards: bool,
8090 whole_lines: bool,
8091 window: &mut Window,
8092 cx: &mut Context<Self>,
8093 ) {
8094 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8095 let buffer = &display_map.buffer_snapshot;
8096 let selections = self.selections.all::<Point>(cx);
8097
8098 let mut edits = Vec::new();
8099 let mut selections_iter = selections.iter().peekable();
8100 while let Some(selection) = selections_iter.next() {
8101 let mut rows = selection.spanned_rows(false, &display_map);
8102 // duplicate line-wise
8103 if whole_lines || selection.start == selection.end {
8104 // Avoid duplicating the same lines twice.
8105 while let Some(next_selection) = selections_iter.peek() {
8106 let next_rows = next_selection.spanned_rows(false, &display_map);
8107 if next_rows.start < rows.end {
8108 rows.end = next_rows.end;
8109 selections_iter.next().unwrap();
8110 } else {
8111 break;
8112 }
8113 }
8114
8115 // Copy the text from the selected row region and splice it either at the start
8116 // or end of the region.
8117 let start = Point::new(rows.start.0, 0);
8118 let end = Point::new(
8119 rows.end.previous_row().0,
8120 buffer.line_len(rows.end.previous_row()),
8121 );
8122 let text = buffer
8123 .text_for_range(start..end)
8124 .chain(Some("\n"))
8125 .collect::<String>();
8126 let insert_location = if upwards {
8127 Point::new(rows.end.0, 0)
8128 } else {
8129 start
8130 };
8131 edits.push((insert_location..insert_location, text));
8132 } else {
8133 // duplicate character-wise
8134 let start = selection.start;
8135 let end = selection.end;
8136 let text = buffer.text_for_range(start..end).collect::<String>();
8137 edits.push((selection.end..selection.end, text));
8138 }
8139 }
8140
8141 self.transact(window, cx, |this, _, cx| {
8142 this.buffer.update(cx, |buffer, cx| {
8143 buffer.edit(edits, None, cx);
8144 });
8145
8146 this.request_autoscroll(Autoscroll::fit(), cx);
8147 });
8148 }
8149
8150 pub fn duplicate_line_up(
8151 &mut self,
8152 _: &DuplicateLineUp,
8153 window: &mut Window,
8154 cx: &mut Context<Self>,
8155 ) {
8156 self.duplicate(true, true, window, cx);
8157 }
8158
8159 pub fn duplicate_line_down(
8160 &mut self,
8161 _: &DuplicateLineDown,
8162 window: &mut Window,
8163 cx: &mut Context<Self>,
8164 ) {
8165 self.duplicate(false, true, window, cx);
8166 }
8167
8168 pub fn duplicate_selection(
8169 &mut self,
8170 _: &DuplicateSelection,
8171 window: &mut Window,
8172 cx: &mut Context<Self>,
8173 ) {
8174 self.duplicate(false, false, window, cx);
8175 }
8176
8177 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8178 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8179 let buffer = self.buffer.read(cx).snapshot(cx);
8180
8181 let mut edits = Vec::new();
8182 let mut unfold_ranges = Vec::new();
8183 let mut refold_creases = Vec::new();
8184
8185 let selections = self.selections.all::<Point>(cx);
8186 let mut selections = selections.iter().peekable();
8187 let mut contiguous_row_selections = Vec::new();
8188 let mut new_selections = Vec::new();
8189
8190 while let Some(selection) = selections.next() {
8191 // Find all the selections that span a contiguous row range
8192 let (start_row, end_row) = consume_contiguous_rows(
8193 &mut contiguous_row_selections,
8194 selection,
8195 &display_map,
8196 &mut selections,
8197 );
8198
8199 // Move the text spanned by the row range to be before the line preceding the row range
8200 if start_row.0 > 0 {
8201 let range_to_move = Point::new(
8202 start_row.previous_row().0,
8203 buffer.line_len(start_row.previous_row()),
8204 )
8205 ..Point::new(
8206 end_row.previous_row().0,
8207 buffer.line_len(end_row.previous_row()),
8208 );
8209 let insertion_point = display_map
8210 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8211 .0;
8212
8213 // Don't move lines across excerpts
8214 if buffer
8215 .excerpt_containing(insertion_point..range_to_move.end)
8216 .is_some()
8217 {
8218 let text = buffer
8219 .text_for_range(range_to_move.clone())
8220 .flat_map(|s| s.chars())
8221 .skip(1)
8222 .chain(['\n'])
8223 .collect::<String>();
8224
8225 edits.push((
8226 buffer.anchor_after(range_to_move.start)
8227 ..buffer.anchor_before(range_to_move.end),
8228 String::new(),
8229 ));
8230 let insertion_anchor = buffer.anchor_after(insertion_point);
8231 edits.push((insertion_anchor..insertion_anchor, text));
8232
8233 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8234
8235 // Move selections up
8236 new_selections.extend(contiguous_row_selections.drain(..).map(
8237 |mut selection| {
8238 selection.start.row -= row_delta;
8239 selection.end.row -= row_delta;
8240 selection
8241 },
8242 ));
8243
8244 // Move folds up
8245 unfold_ranges.push(range_to_move.clone());
8246 for fold in display_map.folds_in_range(
8247 buffer.anchor_before(range_to_move.start)
8248 ..buffer.anchor_after(range_to_move.end),
8249 ) {
8250 let mut start = fold.range.start.to_point(&buffer);
8251 let mut end = fold.range.end.to_point(&buffer);
8252 start.row -= row_delta;
8253 end.row -= row_delta;
8254 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8255 }
8256 }
8257 }
8258
8259 // If we didn't move line(s), preserve the existing selections
8260 new_selections.append(&mut contiguous_row_selections);
8261 }
8262
8263 self.transact(window, cx, |this, window, cx| {
8264 this.unfold_ranges(&unfold_ranges, true, true, cx);
8265 this.buffer.update(cx, |buffer, cx| {
8266 for (range, text) in edits {
8267 buffer.edit([(range, text)], None, cx);
8268 }
8269 });
8270 this.fold_creases(refold_creases, true, window, cx);
8271 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8272 s.select(new_selections);
8273 })
8274 });
8275 }
8276
8277 pub fn move_line_down(
8278 &mut self,
8279 _: &MoveLineDown,
8280 window: &mut Window,
8281 cx: &mut Context<Self>,
8282 ) {
8283 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8284 let buffer = self.buffer.read(cx).snapshot(cx);
8285
8286 let mut edits = Vec::new();
8287 let mut unfold_ranges = Vec::new();
8288 let mut refold_creases = Vec::new();
8289
8290 let selections = self.selections.all::<Point>(cx);
8291 let mut selections = selections.iter().peekable();
8292 let mut contiguous_row_selections = Vec::new();
8293 let mut new_selections = Vec::new();
8294
8295 while let Some(selection) = selections.next() {
8296 // Find all the selections that span a contiguous row range
8297 let (start_row, end_row) = consume_contiguous_rows(
8298 &mut contiguous_row_selections,
8299 selection,
8300 &display_map,
8301 &mut selections,
8302 );
8303
8304 // Move the text spanned by the row range to be after the last line of the row range
8305 if end_row.0 <= buffer.max_point().row {
8306 let range_to_move =
8307 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8308 let insertion_point = display_map
8309 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8310 .0;
8311
8312 // Don't move lines across excerpt boundaries
8313 if buffer
8314 .excerpt_containing(range_to_move.start..insertion_point)
8315 .is_some()
8316 {
8317 let mut text = String::from("\n");
8318 text.extend(buffer.text_for_range(range_to_move.clone()));
8319 text.pop(); // Drop trailing newline
8320 edits.push((
8321 buffer.anchor_after(range_to_move.start)
8322 ..buffer.anchor_before(range_to_move.end),
8323 String::new(),
8324 ));
8325 let insertion_anchor = buffer.anchor_after(insertion_point);
8326 edits.push((insertion_anchor..insertion_anchor, text));
8327
8328 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8329
8330 // Move selections down
8331 new_selections.extend(contiguous_row_selections.drain(..).map(
8332 |mut selection| {
8333 selection.start.row += row_delta;
8334 selection.end.row += row_delta;
8335 selection
8336 },
8337 ));
8338
8339 // Move folds down
8340 unfold_ranges.push(range_to_move.clone());
8341 for fold in display_map.folds_in_range(
8342 buffer.anchor_before(range_to_move.start)
8343 ..buffer.anchor_after(range_to_move.end),
8344 ) {
8345 let mut start = fold.range.start.to_point(&buffer);
8346 let mut end = fold.range.end.to_point(&buffer);
8347 start.row += row_delta;
8348 end.row += row_delta;
8349 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8350 }
8351 }
8352 }
8353
8354 // If we didn't move line(s), preserve the existing selections
8355 new_selections.append(&mut contiguous_row_selections);
8356 }
8357
8358 self.transact(window, cx, |this, window, cx| {
8359 this.unfold_ranges(&unfold_ranges, true, true, cx);
8360 this.buffer.update(cx, |buffer, cx| {
8361 for (range, text) in edits {
8362 buffer.edit([(range, text)], None, cx);
8363 }
8364 });
8365 this.fold_creases(refold_creases, true, window, cx);
8366 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8367 s.select(new_selections)
8368 });
8369 });
8370 }
8371
8372 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8373 let text_layout_details = &self.text_layout_details(window);
8374 self.transact(window, cx, |this, window, cx| {
8375 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8376 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8377 let line_mode = s.line_mode;
8378 s.move_with(|display_map, selection| {
8379 if !selection.is_empty() || line_mode {
8380 return;
8381 }
8382
8383 let mut head = selection.head();
8384 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8385 if head.column() == display_map.line_len(head.row()) {
8386 transpose_offset = display_map
8387 .buffer_snapshot
8388 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8389 }
8390
8391 if transpose_offset == 0 {
8392 return;
8393 }
8394
8395 *head.column_mut() += 1;
8396 head = display_map.clip_point(head, Bias::Right);
8397 let goal = SelectionGoal::HorizontalPosition(
8398 display_map
8399 .x_for_display_point(head, text_layout_details)
8400 .into(),
8401 );
8402 selection.collapse_to(head, goal);
8403
8404 let transpose_start = display_map
8405 .buffer_snapshot
8406 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8407 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8408 let transpose_end = display_map
8409 .buffer_snapshot
8410 .clip_offset(transpose_offset + 1, Bias::Right);
8411 if let Some(ch) =
8412 display_map.buffer_snapshot.chars_at(transpose_start).next()
8413 {
8414 edits.push((transpose_start..transpose_offset, String::new()));
8415 edits.push((transpose_end..transpose_end, ch.to_string()));
8416 }
8417 }
8418 });
8419 edits
8420 });
8421 this.buffer
8422 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8423 let selections = this.selections.all::<usize>(cx);
8424 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8425 s.select(selections);
8426 });
8427 });
8428 }
8429
8430 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8431 self.rewrap_impl(IsVimMode::No, cx)
8432 }
8433
8434 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8435 let buffer = self.buffer.read(cx).snapshot(cx);
8436 let selections = self.selections.all::<Point>(cx);
8437 let mut selections = selections.iter().peekable();
8438
8439 let mut edits = Vec::new();
8440 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8441
8442 while let Some(selection) = selections.next() {
8443 let mut start_row = selection.start.row;
8444 let mut end_row = selection.end.row;
8445
8446 // Skip selections that overlap with a range that has already been rewrapped.
8447 let selection_range = start_row..end_row;
8448 if rewrapped_row_ranges
8449 .iter()
8450 .any(|range| range.overlaps(&selection_range))
8451 {
8452 continue;
8453 }
8454
8455 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
8456
8457 // Since not all lines in the selection may be at the same indent
8458 // level, choose the indent size that is the most common between all
8459 // of the lines.
8460 //
8461 // If there is a tie, we use the deepest indent.
8462 let (indent_size, indent_end) = {
8463 let mut indent_size_occurrences = HashMap::default();
8464 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8465
8466 for row in start_row..=end_row {
8467 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8468 rows_by_indent_size.entry(indent).or_default().push(row);
8469 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8470 }
8471
8472 let indent_size = indent_size_occurrences
8473 .into_iter()
8474 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8475 .map(|(indent, _)| indent)
8476 .unwrap_or_default();
8477 let row = rows_by_indent_size[&indent_size][0];
8478 let indent_end = Point::new(row, indent_size.len);
8479
8480 (indent_size, indent_end)
8481 };
8482
8483 let mut line_prefix = indent_size.chars().collect::<String>();
8484
8485 let mut inside_comment = false;
8486 if let Some(comment_prefix) =
8487 buffer
8488 .language_scope_at(selection.head())
8489 .and_then(|language| {
8490 language
8491 .line_comment_prefixes()
8492 .iter()
8493 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8494 .cloned()
8495 })
8496 {
8497 line_prefix.push_str(&comment_prefix);
8498 inside_comment = true;
8499 }
8500
8501 let language_settings = buffer.settings_at(selection.head(), cx);
8502 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8503 RewrapBehavior::InComments => inside_comment,
8504 RewrapBehavior::InSelections => !selection.is_empty(),
8505 RewrapBehavior::Anywhere => true,
8506 };
8507
8508 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8509 if !should_rewrap {
8510 continue;
8511 }
8512
8513 if selection.is_empty() {
8514 'expand_upwards: while start_row > 0 {
8515 let prev_row = start_row - 1;
8516 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8517 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8518 {
8519 start_row = prev_row;
8520 } else {
8521 break 'expand_upwards;
8522 }
8523 }
8524
8525 'expand_downwards: while end_row < buffer.max_point().row {
8526 let next_row = end_row + 1;
8527 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8528 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8529 {
8530 end_row = next_row;
8531 } else {
8532 break 'expand_downwards;
8533 }
8534 }
8535 }
8536
8537 let start = Point::new(start_row, 0);
8538 let start_offset = start.to_offset(&buffer);
8539 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8540 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8541 let Some(lines_without_prefixes) = selection_text
8542 .lines()
8543 .map(|line| {
8544 line.strip_prefix(&line_prefix)
8545 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8546 .ok_or_else(|| {
8547 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8548 })
8549 })
8550 .collect::<Result<Vec<_>, _>>()
8551 .log_err()
8552 else {
8553 continue;
8554 };
8555
8556 let wrap_column = buffer
8557 .settings_at(Point::new(start_row, 0), cx)
8558 .preferred_line_length as usize;
8559 let wrapped_text = wrap_with_prefix(
8560 line_prefix,
8561 lines_without_prefixes.join(" "),
8562 wrap_column,
8563 tab_size,
8564 );
8565
8566 // TODO: should always use char-based diff while still supporting cursor behavior that
8567 // matches vim.
8568 let mut diff_options = DiffOptions::default();
8569 if is_vim_mode == IsVimMode::Yes {
8570 diff_options.max_word_diff_len = 0;
8571 diff_options.max_word_diff_line_count = 0;
8572 } else {
8573 diff_options.max_word_diff_len = usize::MAX;
8574 diff_options.max_word_diff_line_count = usize::MAX;
8575 }
8576
8577 for (old_range, new_text) in
8578 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8579 {
8580 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8581 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8582 edits.push((edit_start..edit_end, new_text));
8583 }
8584
8585 rewrapped_row_ranges.push(start_row..=end_row);
8586 }
8587
8588 self.buffer
8589 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8590 }
8591
8592 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8593 let mut text = String::new();
8594 let buffer = self.buffer.read(cx).snapshot(cx);
8595 let mut selections = self.selections.all::<Point>(cx);
8596 let mut clipboard_selections = Vec::with_capacity(selections.len());
8597 {
8598 let max_point = buffer.max_point();
8599 let mut is_first = true;
8600 for selection in &mut selections {
8601 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8602 if is_entire_line {
8603 selection.start = Point::new(selection.start.row, 0);
8604 if !selection.is_empty() && selection.end.column == 0 {
8605 selection.end = cmp::min(max_point, selection.end);
8606 } else {
8607 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8608 }
8609 selection.goal = SelectionGoal::None;
8610 }
8611 if is_first {
8612 is_first = false;
8613 } else {
8614 text += "\n";
8615 }
8616 let mut len = 0;
8617 for chunk in buffer.text_for_range(selection.start..selection.end) {
8618 text.push_str(chunk);
8619 len += chunk.len();
8620 }
8621 clipboard_selections.push(ClipboardSelection {
8622 len,
8623 is_entire_line,
8624 start_column: selection.start.column,
8625 });
8626 }
8627 }
8628
8629 self.transact(window, cx, |this, window, cx| {
8630 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8631 s.select(selections);
8632 });
8633 this.insert("", window, cx);
8634 });
8635 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8636 }
8637
8638 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8639 let item = self.cut_common(window, cx);
8640 cx.write_to_clipboard(item);
8641 }
8642
8643 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8644 self.change_selections(None, window, cx, |s| {
8645 s.move_with(|snapshot, sel| {
8646 if sel.is_empty() {
8647 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8648 }
8649 });
8650 });
8651 let item = self.cut_common(window, cx);
8652 cx.set_global(KillRing(item))
8653 }
8654
8655 pub fn kill_ring_yank(
8656 &mut self,
8657 _: &KillRingYank,
8658 window: &mut Window,
8659 cx: &mut Context<Self>,
8660 ) {
8661 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8662 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8663 (kill_ring.text().to_string(), kill_ring.metadata_json())
8664 } else {
8665 return;
8666 }
8667 } else {
8668 return;
8669 };
8670 self.do_paste(&text, metadata, false, window, cx);
8671 }
8672
8673 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8674 let selections = self.selections.all::<Point>(cx);
8675 let buffer = self.buffer.read(cx).read(cx);
8676 let mut text = String::new();
8677
8678 let mut clipboard_selections = Vec::with_capacity(selections.len());
8679 {
8680 let max_point = buffer.max_point();
8681 let mut is_first = true;
8682 for selection in selections.iter() {
8683 let mut start = selection.start;
8684 let mut end = selection.end;
8685 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8686 if is_entire_line {
8687 start = Point::new(start.row, 0);
8688 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8689 }
8690 if is_first {
8691 is_first = false;
8692 } else {
8693 text += "\n";
8694 }
8695 let mut len = 0;
8696 for chunk in buffer.text_for_range(start..end) {
8697 text.push_str(chunk);
8698 len += chunk.len();
8699 }
8700 clipboard_selections.push(ClipboardSelection {
8701 len,
8702 is_entire_line,
8703 start_column: start.column,
8704 });
8705 }
8706 }
8707
8708 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8709 text,
8710 clipboard_selections,
8711 ));
8712 }
8713
8714 pub fn do_paste(
8715 &mut self,
8716 text: &String,
8717 clipboard_selections: Option<Vec<ClipboardSelection>>,
8718 handle_entire_lines: bool,
8719 window: &mut Window,
8720 cx: &mut Context<Self>,
8721 ) {
8722 if self.read_only(cx) {
8723 return;
8724 }
8725
8726 let clipboard_text = Cow::Borrowed(text);
8727
8728 self.transact(window, cx, |this, window, cx| {
8729 if let Some(mut clipboard_selections) = clipboard_selections {
8730 let old_selections = this.selections.all::<usize>(cx);
8731 let all_selections_were_entire_line =
8732 clipboard_selections.iter().all(|s| s.is_entire_line);
8733 let first_selection_start_column =
8734 clipboard_selections.first().map(|s| s.start_column);
8735 if clipboard_selections.len() != old_selections.len() {
8736 clipboard_selections.drain(..);
8737 }
8738 let cursor_offset = this.selections.last::<usize>(cx).head();
8739 let mut auto_indent_on_paste = true;
8740
8741 this.buffer.update(cx, |buffer, cx| {
8742 let snapshot = buffer.read(cx);
8743 auto_indent_on_paste =
8744 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8745
8746 let mut start_offset = 0;
8747 let mut edits = Vec::new();
8748 let mut original_start_columns = Vec::new();
8749 for (ix, selection) in old_selections.iter().enumerate() {
8750 let to_insert;
8751 let entire_line;
8752 let original_start_column;
8753 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8754 let end_offset = start_offset + clipboard_selection.len;
8755 to_insert = &clipboard_text[start_offset..end_offset];
8756 entire_line = clipboard_selection.is_entire_line;
8757 start_offset = end_offset + 1;
8758 original_start_column = Some(clipboard_selection.start_column);
8759 } else {
8760 to_insert = clipboard_text.as_str();
8761 entire_line = all_selections_were_entire_line;
8762 original_start_column = first_selection_start_column
8763 }
8764
8765 // If the corresponding selection was empty when this slice of the
8766 // clipboard text was written, then the entire line containing the
8767 // selection was copied. If this selection is also currently empty,
8768 // then paste the line before the current line of the buffer.
8769 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8770 let column = selection.start.to_point(&snapshot).column as usize;
8771 let line_start = selection.start - column;
8772 line_start..line_start
8773 } else {
8774 selection.range()
8775 };
8776
8777 edits.push((range, to_insert));
8778 original_start_columns.extend(original_start_column);
8779 }
8780 drop(snapshot);
8781
8782 buffer.edit(
8783 edits,
8784 if auto_indent_on_paste {
8785 Some(AutoindentMode::Block {
8786 original_start_columns,
8787 })
8788 } else {
8789 None
8790 },
8791 cx,
8792 );
8793 });
8794
8795 let selections = this.selections.all::<usize>(cx);
8796 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8797 s.select(selections)
8798 });
8799 } else {
8800 this.insert(&clipboard_text, window, cx);
8801 }
8802 });
8803 }
8804
8805 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8806 if let Some(item) = cx.read_from_clipboard() {
8807 let entries = item.entries();
8808
8809 match entries.first() {
8810 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8811 // of all the pasted entries.
8812 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8813 .do_paste(
8814 clipboard_string.text(),
8815 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8816 true,
8817 window,
8818 cx,
8819 ),
8820 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8821 }
8822 }
8823 }
8824
8825 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8826 if self.read_only(cx) {
8827 return;
8828 }
8829
8830 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8831 if let Some((selections, _)) =
8832 self.selection_history.transaction(transaction_id).cloned()
8833 {
8834 self.change_selections(None, window, cx, |s| {
8835 s.select_anchors(selections.to_vec());
8836 });
8837 } else {
8838 log::error!(
8839 "No entry in selection_history found for undo. \
8840 This may correspond to a bug where undo does not update the selection. \
8841 If this is occurring, please add details to \
8842 https://github.com/zed-industries/zed/issues/22692"
8843 );
8844 }
8845 self.request_autoscroll(Autoscroll::fit(), cx);
8846 self.unmark_text(window, cx);
8847 self.refresh_inline_completion(true, false, window, cx);
8848 cx.emit(EditorEvent::Edited { transaction_id });
8849 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8850 }
8851 }
8852
8853 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8854 if self.read_only(cx) {
8855 return;
8856 }
8857
8858 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8859 if let Some((_, Some(selections))) =
8860 self.selection_history.transaction(transaction_id).cloned()
8861 {
8862 self.change_selections(None, window, cx, |s| {
8863 s.select_anchors(selections.to_vec());
8864 });
8865 } else {
8866 log::error!(
8867 "No entry in selection_history found for redo. \
8868 This may correspond to a bug where undo does not update the selection. \
8869 If this is occurring, please add details to \
8870 https://github.com/zed-industries/zed/issues/22692"
8871 );
8872 }
8873 self.request_autoscroll(Autoscroll::fit(), cx);
8874 self.unmark_text(window, cx);
8875 self.refresh_inline_completion(true, false, window, cx);
8876 cx.emit(EditorEvent::Edited { transaction_id });
8877 }
8878 }
8879
8880 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8881 self.buffer
8882 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8883 }
8884
8885 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8886 self.buffer
8887 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8888 }
8889
8890 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8891 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8892 let line_mode = s.line_mode;
8893 s.move_with(|map, selection| {
8894 let cursor = if selection.is_empty() && !line_mode {
8895 movement::left(map, selection.start)
8896 } else {
8897 selection.start
8898 };
8899 selection.collapse_to(cursor, SelectionGoal::None);
8900 });
8901 })
8902 }
8903
8904 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8905 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8906 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8907 })
8908 }
8909
8910 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8911 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8912 let line_mode = s.line_mode;
8913 s.move_with(|map, selection| {
8914 let cursor = if selection.is_empty() && !line_mode {
8915 movement::right(map, selection.end)
8916 } else {
8917 selection.end
8918 };
8919 selection.collapse_to(cursor, SelectionGoal::None)
8920 });
8921 })
8922 }
8923
8924 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8925 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8926 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8927 })
8928 }
8929
8930 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8931 if self.take_rename(true, window, cx).is_some() {
8932 return;
8933 }
8934
8935 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8936 cx.propagate();
8937 return;
8938 }
8939
8940 let text_layout_details = &self.text_layout_details(window);
8941 let selection_count = self.selections.count();
8942 let first_selection = self.selections.first_anchor();
8943
8944 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8945 let line_mode = s.line_mode;
8946 s.move_with(|map, selection| {
8947 if !selection.is_empty() && !line_mode {
8948 selection.goal = SelectionGoal::None;
8949 }
8950 let (cursor, goal) = movement::up(
8951 map,
8952 selection.start,
8953 selection.goal,
8954 false,
8955 text_layout_details,
8956 );
8957 selection.collapse_to(cursor, goal);
8958 });
8959 });
8960
8961 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8962 {
8963 cx.propagate();
8964 }
8965 }
8966
8967 pub fn move_up_by_lines(
8968 &mut self,
8969 action: &MoveUpByLines,
8970 window: &mut Window,
8971 cx: &mut Context<Self>,
8972 ) {
8973 if self.take_rename(true, window, cx).is_some() {
8974 return;
8975 }
8976
8977 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8978 cx.propagate();
8979 return;
8980 }
8981
8982 let text_layout_details = &self.text_layout_details(window);
8983
8984 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8985 let line_mode = s.line_mode;
8986 s.move_with(|map, selection| {
8987 if !selection.is_empty() && !line_mode {
8988 selection.goal = SelectionGoal::None;
8989 }
8990 let (cursor, goal) = movement::up_by_rows(
8991 map,
8992 selection.start,
8993 action.lines,
8994 selection.goal,
8995 false,
8996 text_layout_details,
8997 );
8998 selection.collapse_to(cursor, goal);
8999 });
9000 })
9001 }
9002
9003 pub fn move_down_by_lines(
9004 &mut self,
9005 action: &MoveDownByLines,
9006 window: &mut Window,
9007 cx: &mut Context<Self>,
9008 ) {
9009 if self.take_rename(true, window, cx).is_some() {
9010 return;
9011 }
9012
9013 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9014 cx.propagate();
9015 return;
9016 }
9017
9018 let text_layout_details = &self.text_layout_details(window);
9019
9020 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9021 let line_mode = s.line_mode;
9022 s.move_with(|map, selection| {
9023 if !selection.is_empty() && !line_mode {
9024 selection.goal = SelectionGoal::None;
9025 }
9026 let (cursor, goal) = movement::down_by_rows(
9027 map,
9028 selection.start,
9029 action.lines,
9030 selection.goal,
9031 false,
9032 text_layout_details,
9033 );
9034 selection.collapse_to(cursor, goal);
9035 });
9036 })
9037 }
9038
9039 pub fn select_down_by_lines(
9040 &mut self,
9041 action: &SelectDownByLines,
9042 window: &mut Window,
9043 cx: &mut Context<Self>,
9044 ) {
9045 let text_layout_details = &self.text_layout_details(window);
9046 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9047 s.move_heads_with(|map, head, goal| {
9048 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9049 })
9050 })
9051 }
9052
9053 pub fn select_up_by_lines(
9054 &mut self,
9055 action: &SelectUpByLines,
9056 window: &mut Window,
9057 cx: &mut Context<Self>,
9058 ) {
9059 let text_layout_details = &self.text_layout_details(window);
9060 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9061 s.move_heads_with(|map, head, goal| {
9062 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9063 })
9064 })
9065 }
9066
9067 pub fn select_page_up(
9068 &mut self,
9069 _: &SelectPageUp,
9070 window: &mut Window,
9071 cx: &mut Context<Self>,
9072 ) {
9073 let Some(row_count) = self.visible_row_count() else {
9074 return;
9075 };
9076
9077 let text_layout_details = &self.text_layout_details(window);
9078
9079 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9080 s.move_heads_with(|map, head, goal| {
9081 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9082 })
9083 })
9084 }
9085
9086 pub fn move_page_up(
9087 &mut self,
9088 action: &MovePageUp,
9089 window: &mut Window,
9090 cx: &mut Context<Self>,
9091 ) {
9092 if self.take_rename(true, window, cx).is_some() {
9093 return;
9094 }
9095
9096 if self
9097 .context_menu
9098 .borrow_mut()
9099 .as_mut()
9100 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9101 .unwrap_or(false)
9102 {
9103 return;
9104 }
9105
9106 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9107 cx.propagate();
9108 return;
9109 }
9110
9111 let Some(row_count) = self.visible_row_count() else {
9112 return;
9113 };
9114
9115 let autoscroll = if action.center_cursor {
9116 Autoscroll::center()
9117 } else {
9118 Autoscroll::fit()
9119 };
9120
9121 let text_layout_details = &self.text_layout_details(window);
9122
9123 self.change_selections(Some(autoscroll), window, cx, |s| {
9124 let line_mode = s.line_mode;
9125 s.move_with(|map, selection| {
9126 if !selection.is_empty() && !line_mode {
9127 selection.goal = SelectionGoal::None;
9128 }
9129 let (cursor, goal) = movement::up_by_rows(
9130 map,
9131 selection.end,
9132 row_count,
9133 selection.goal,
9134 false,
9135 text_layout_details,
9136 );
9137 selection.collapse_to(cursor, goal);
9138 });
9139 });
9140 }
9141
9142 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9143 let text_layout_details = &self.text_layout_details(window);
9144 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9145 s.move_heads_with(|map, head, goal| {
9146 movement::up(map, head, goal, false, text_layout_details)
9147 })
9148 })
9149 }
9150
9151 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9152 self.take_rename(true, window, cx);
9153
9154 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9155 cx.propagate();
9156 return;
9157 }
9158
9159 let text_layout_details = &self.text_layout_details(window);
9160 let selection_count = self.selections.count();
9161 let first_selection = self.selections.first_anchor();
9162
9163 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9164 let line_mode = s.line_mode;
9165 s.move_with(|map, selection| {
9166 if !selection.is_empty() && !line_mode {
9167 selection.goal = SelectionGoal::None;
9168 }
9169 let (cursor, goal) = movement::down(
9170 map,
9171 selection.end,
9172 selection.goal,
9173 false,
9174 text_layout_details,
9175 );
9176 selection.collapse_to(cursor, goal);
9177 });
9178 });
9179
9180 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9181 {
9182 cx.propagate();
9183 }
9184 }
9185
9186 pub fn select_page_down(
9187 &mut self,
9188 _: &SelectPageDown,
9189 window: &mut Window,
9190 cx: &mut Context<Self>,
9191 ) {
9192 let Some(row_count) = self.visible_row_count() else {
9193 return;
9194 };
9195
9196 let text_layout_details = &self.text_layout_details(window);
9197
9198 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9199 s.move_heads_with(|map, head, goal| {
9200 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9201 })
9202 })
9203 }
9204
9205 pub fn move_page_down(
9206 &mut self,
9207 action: &MovePageDown,
9208 window: &mut Window,
9209 cx: &mut Context<Self>,
9210 ) {
9211 if self.take_rename(true, window, cx).is_some() {
9212 return;
9213 }
9214
9215 if self
9216 .context_menu
9217 .borrow_mut()
9218 .as_mut()
9219 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9220 .unwrap_or(false)
9221 {
9222 return;
9223 }
9224
9225 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9226 cx.propagate();
9227 return;
9228 }
9229
9230 let Some(row_count) = self.visible_row_count() else {
9231 return;
9232 };
9233
9234 let autoscroll = if action.center_cursor {
9235 Autoscroll::center()
9236 } else {
9237 Autoscroll::fit()
9238 };
9239
9240 let text_layout_details = &self.text_layout_details(window);
9241 self.change_selections(Some(autoscroll), window, cx, |s| {
9242 let line_mode = s.line_mode;
9243 s.move_with(|map, selection| {
9244 if !selection.is_empty() && !line_mode {
9245 selection.goal = SelectionGoal::None;
9246 }
9247 let (cursor, goal) = movement::down_by_rows(
9248 map,
9249 selection.end,
9250 row_count,
9251 selection.goal,
9252 false,
9253 text_layout_details,
9254 );
9255 selection.collapse_to(cursor, goal);
9256 });
9257 });
9258 }
9259
9260 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9261 let text_layout_details = &self.text_layout_details(window);
9262 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9263 s.move_heads_with(|map, head, goal| {
9264 movement::down(map, head, goal, false, text_layout_details)
9265 })
9266 });
9267 }
9268
9269 pub fn context_menu_first(
9270 &mut self,
9271 _: &ContextMenuFirst,
9272 _window: &mut Window,
9273 cx: &mut Context<Self>,
9274 ) {
9275 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9276 context_menu.select_first(self.completion_provider.as_deref(), cx);
9277 }
9278 }
9279
9280 pub fn context_menu_prev(
9281 &mut self,
9282 _: &ContextMenuPrevious,
9283 _window: &mut Window,
9284 cx: &mut Context<Self>,
9285 ) {
9286 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9287 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9288 }
9289 }
9290
9291 pub fn context_menu_next(
9292 &mut self,
9293 _: &ContextMenuNext,
9294 _window: &mut Window,
9295 cx: &mut Context<Self>,
9296 ) {
9297 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9298 context_menu.select_next(self.completion_provider.as_deref(), cx);
9299 }
9300 }
9301
9302 pub fn context_menu_last(
9303 &mut self,
9304 _: &ContextMenuLast,
9305 _window: &mut Window,
9306 cx: &mut Context<Self>,
9307 ) {
9308 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9309 context_menu.select_last(self.completion_provider.as_deref(), cx);
9310 }
9311 }
9312
9313 pub fn move_to_previous_word_start(
9314 &mut self,
9315 _: &MoveToPreviousWordStart,
9316 window: &mut Window,
9317 cx: &mut Context<Self>,
9318 ) {
9319 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9320 s.move_cursors_with(|map, head, _| {
9321 (
9322 movement::previous_word_start(map, head),
9323 SelectionGoal::None,
9324 )
9325 });
9326 })
9327 }
9328
9329 pub fn move_to_previous_subword_start(
9330 &mut self,
9331 _: &MoveToPreviousSubwordStart,
9332 window: &mut Window,
9333 cx: &mut Context<Self>,
9334 ) {
9335 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9336 s.move_cursors_with(|map, head, _| {
9337 (
9338 movement::previous_subword_start(map, head),
9339 SelectionGoal::None,
9340 )
9341 });
9342 })
9343 }
9344
9345 pub fn select_to_previous_word_start(
9346 &mut self,
9347 _: &SelectToPreviousWordStart,
9348 window: &mut Window,
9349 cx: &mut Context<Self>,
9350 ) {
9351 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9352 s.move_heads_with(|map, head, _| {
9353 (
9354 movement::previous_word_start(map, head),
9355 SelectionGoal::None,
9356 )
9357 });
9358 })
9359 }
9360
9361 pub fn select_to_previous_subword_start(
9362 &mut self,
9363 _: &SelectToPreviousSubwordStart,
9364 window: &mut Window,
9365 cx: &mut Context<Self>,
9366 ) {
9367 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9368 s.move_heads_with(|map, head, _| {
9369 (
9370 movement::previous_subword_start(map, head),
9371 SelectionGoal::None,
9372 )
9373 });
9374 })
9375 }
9376
9377 pub fn delete_to_previous_word_start(
9378 &mut self,
9379 action: &DeleteToPreviousWordStart,
9380 window: &mut Window,
9381 cx: &mut Context<Self>,
9382 ) {
9383 self.transact(window, cx, |this, window, cx| {
9384 this.select_autoclose_pair(window, cx);
9385 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9386 let line_mode = s.line_mode;
9387 s.move_with(|map, selection| {
9388 if selection.is_empty() && !line_mode {
9389 let cursor = if action.ignore_newlines {
9390 movement::previous_word_start(map, selection.head())
9391 } else {
9392 movement::previous_word_start_or_newline(map, selection.head())
9393 };
9394 selection.set_head(cursor, SelectionGoal::None);
9395 }
9396 });
9397 });
9398 this.insert("", window, cx);
9399 });
9400 }
9401
9402 pub fn delete_to_previous_subword_start(
9403 &mut self,
9404 _: &DeleteToPreviousSubwordStart,
9405 window: &mut Window,
9406 cx: &mut Context<Self>,
9407 ) {
9408 self.transact(window, cx, |this, window, cx| {
9409 this.select_autoclose_pair(window, cx);
9410 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9411 let line_mode = s.line_mode;
9412 s.move_with(|map, selection| {
9413 if selection.is_empty() && !line_mode {
9414 let cursor = movement::previous_subword_start(map, selection.head());
9415 selection.set_head(cursor, SelectionGoal::None);
9416 }
9417 });
9418 });
9419 this.insert("", window, cx);
9420 });
9421 }
9422
9423 pub fn move_to_next_word_end(
9424 &mut self,
9425 _: &MoveToNextWordEnd,
9426 window: &mut Window,
9427 cx: &mut Context<Self>,
9428 ) {
9429 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9430 s.move_cursors_with(|map, head, _| {
9431 (movement::next_word_end(map, head), SelectionGoal::None)
9432 });
9433 })
9434 }
9435
9436 pub fn move_to_next_subword_end(
9437 &mut self,
9438 _: &MoveToNextSubwordEnd,
9439 window: &mut Window,
9440 cx: &mut Context<Self>,
9441 ) {
9442 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9443 s.move_cursors_with(|map, head, _| {
9444 (movement::next_subword_end(map, head), SelectionGoal::None)
9445 });
9446 })
9447 }
9448
9449 pub fn select_to_next_word_end(
9450 &mut self,
9451 _: &SelectToNextWordEnd,
9452 window: &mut Window,
9453 cx: &mut Context<Self>,
9454 ) {
9455 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9456 s.move_heads_with(|map, head, _| {
9457 (movement::next_word_end(map, head), SelectionGoal::None)
9458 });
9459 })
9460 }
9461
9462 pub fn select_to_next_subword_end(
9463 &mut self,
9464 _: &SelectToNextSubwordEnd,
9465 window: &mut Window,
9466 cx: &mut Context<Self>,
9467 ) {
9468 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9469 s.move_heads_with(|map, head, _| {
9470 (movement::next_subword_end(map, head), SelectionGoal::None)
9471 });
9472 })
9473 }
9474
9475 pub fn delete_to_next_word_end(
9476 &mut self,
9477 action: &DeleteToNextWordEnd,
9478 window: &mut Window,
9479 cx: &mut Context<Self>,
9480 ) {
9481 self.transact(window, cx, |this, window, cx| {
9482 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9483 let line_mode = s.line_mode;
9484 s.move_with(|map, selection| {
9485 if selection.is_empty() && !line_mode {
9486 let cursor = if action.ignore_newlines {
9487 movement::next_word_end(map, selection.head())
9488 } else {
9489 movement::next_word_end_or_newline(map, selection.head())
9490 };
9491 selection.set_head(cursor, SelectionGoal::None);
9492 }
9493 });
9494 });
9495 this.insert("", window, cx);
9496 });
9497 }
9498
9499 pub fn delete_to_next_subword_end(
9500 &mut self,
9501 _: &DeleteToNextSubwordEnd,
9502 window: &mut Window,
9503 cx: &mut Context<Self>,
9504 ) {
9505 self.transact(window, cx, |this, window, cx| {
9506 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9507 s.move_with(|map, selection| {
9508 if selection.is_empty() {
9509 let cursor = movement::next_subword_end(map, selection.head());
9510 selection.set_head(cursor, SelectionGoal::None);
9511 }
9512 });
9513 });
9514 this.insert("", window, cx);
9515 });
9516 }
9517
9518 pub fn move_to_beginning_of_line(
9519 &mut self,
9520 action: &MoveToBeginningOfLine,
9521 window: &mut Window,
9522 cx: &mut Context<Self>,
9523 ) {
9524 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9525 s.move_cursors_with(|map, head, _| {
9526 (
9527 movement::indented_line_beginning(
9528 map,
9529 head,
9530 action.stop_at_soft_wraps,
9531 action.stop_at_indent,
9532 ),
9533 SelectionGoal::None,
9534 )
9535 });
9536 })
9537 }
9538
9539 pub fn select_to_beginning_of_line(
9540 &mut self,
9541 action: &SelectToBeginningOfLine,
9542 window: &mut Window,
9543 cx: &mut Context<Self>,
9544 ) {
9545 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9546 s.move_heads_with(|map, head, _| {
9547 (
9548 movement::indented_line_beginning(
9549 map,
9550 head,
9551 action.stop_at_soft_wraps,
9552 action.stop_at_indent,
9553 ),
9554 SelectionGoal::None,
9555 )
9556 });
9557 });
9558 }
9559
9560 pub fn delete_to_beginning_of_line(
9561 &mut self,
9562 action: &DeleteToBeginningOfLine,
9563 window: &mut Window,
9564 cx: &mut Context<Self>,
9565 ) {
9566 self.transact(window, cx, |this, window, cx| {
9567 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9568 s.move_with(|_, selection| {
9569 selection.reversed = true;
9570 });
9571 });
9572
9573 this.select_to_beginning_of_line(
9574 &SelectToBeginningOfLine {
9575 stop_at_soft_wraps: false,
9576 stop_at_indent: action.stop_at_indent,
9577 },
9578 window,
9579 cx,
9580 );
9581 this.backspace(&Backspace, window, cx);
9582 });
9583 }
9584
9585 pub fn move_to_end_of_line(
9586 &mut self,
9587 action: &MoveToEndOfLine,
9588 window: &mut Window,
9589 cx: &mut Context<Self>,
9590 ) {
9591 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9592 s.move_cursors_with(|map, head, _| {
9593 (
9594 movement::line_end(map, head, action.stop_at_soft_wraps),
9595 SelectionGoal::None,
9596 )
9597 });
9598 })
9599 }
9600
9601 pub fn select_to_end_of_line(
9602 &mut self,
9603 action: &SelectToEndOfLine,
9604 window: &mut Window,
9605 cx: &mut Context<Self>,
9606 ) {
9607 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9608 s.move_heads_with(|map, head, _| {
9609 (
9610 movement::line_end(map, head, action.stop_at_soft_wraps),
9611 SelectionGoal::None,
9612 )
9613 });
9614 })
9615 }
9616
9617 pub fn delete_to_end_of_line(
9618 &mut self,
9619 _: &DeleteToEndOfLine,
9620 window: &mut Window,
9621 cx: &mut Context<Self>,
9622 ) {
9623 self.transact(window, cx, |this, window, cx| {
9624 this.select_to_end_of_line(
9625 &SelectToEndOfLine {
9626 stop_at_soft_wraps: false,
9627 },
9628 window,
9629 cx,
9630 );
9631 this.delete(&Delete, window, cx);
9632 });
9633 }
9634
9635 pub fn cut_to_end_of_line(
9636 &mut self,
9637 _: &CutToEndOfLine,
9638 window: &mut Window,
9639 cx: &mut Context<Self>,
9640 ) {
9641 self.transact(window, cx, |this, window, cx| {
9642 this.select_to_end_of_line(
9643 &SelectToEndOfLine {
9644 stop_at_soft_wraps: false,
9645 },
9646 window,
9647 cx,
9648 );
9649 this.cut(&Cut, window, cx);
9650 });
9651 }
9652
9653 pub fn move_to_start_of_paragraph(
9654 &mut self,
9655 _: &MoveToStartOfParagraph,
9656 window: &mut Window,
9657 cx: &mut Context<Self>,
9658 ) {
9659 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9660 cx.propagate();
9661 return;
9662 }
9663
9664 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9665 s.move_with(|map, selection| {
9666 selection.collapse_to(
9667 movement::start_of_paragraph(map, selection.head(), 1),
9668 SelectionGoal::None,
9669 )
9670 });
9671 })
9672 }
9673
9674 pub fn move_to_end_of_paragraph(
9675 &mut self,
9676 _: &MoveToEndOfParagraph,
9677 window: &mut Window,
9678 cx: &mut Context<Self>,
9679 ) {
9680 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9681 cx.propagate();
9682 return;
9683 }
9684
9685 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9686 s.move_with(|map, selection| {
9687 selection.collapse_to(
9688 movement::end_of_paragraph(map, selection.head(), 1),
9689 SelectionGoal::None,
9690 )
9691 });
9692 })
9693 }
9694
9695 pub fn select_to_start_of_paragraph(
9696 &mut self,
9697 _: &SelectToStartOfParagraph,
9698 window: &mut Window,
9699 cx: &mut Context<Self>,
9700 ) {
9701 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9702 cx.propagate();
9703 return;
9704 }
9705
9706 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9707 s.move_heads_with(|map, head, _| {
9708 (
9709 movement::start_of_paragraph(map, head, 1),
9710 SelectionGoal::None,
9711 )
9712 });
9713 })
9714 }
9715
9716 pub fn select_to_end_of_paragraph(
9717 &mut self,
9718 _: &SelectToEndOfParagraph,
9719 window: &mut Window,
9720 cx: &mut Context<Self>,
9721 ) {
9722 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9723 cx.propagate();
9724 return;
9725 }
9726
9727 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9728 s.move_heads_with(|map, head, _| {
9729 (
9730 movement::end_of_paragraph(map, head, 1),
9731 SelectionGoal::None,
9732 )
9733 });
9734 })
9735 }
9736
9737 pub fn move_to_start_of_excerpt(
9738 &mut self,
9739 _: &MoveToStartOfExcerpt,
9740 window: &mut Window,
9741 cx: &mut Context<Self>,
9742 ) {
9743 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9744 cx.propagate();
9745 return;
9746 }
9747
9748 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9749 s.move_with(|map, selection| {
9750 selection.collapse_to(
9751 movement::start_of_excerpt(
9752 map,
9753 selection.head(),
9754 workspace::searchable::Direction::Prev,
9755 ),
9756 SelectionGoal::None,
9757 )
9758 });
9759 })
9760 }
9761
9762 pub fn move_to_end_of_excerpt(
9763 &mut self,
9764 _: &MoveToEndOfExcerpt,
9765 window: &mut Window,
9766 cx: &mut Context<Self>,
9767 ) {
9768 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9769 cx.propagate();
9770 return;
9771 }
9772
9773 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9774 s.move_with(|map, selection| {
9775 selection.collapse_to(
9776 movement::end_of_excerpt(
9777 map,
9778 selection.head(),
9779 workspace::searchable::Direction::Next,
9780 ),
9781 SelectionGoal::None,
9782 )
9783 });
9784 })
9785 }
9786
9787 pub fn select_to_start_of_excerpt(
9788 &mut self,
9789 _: &SelectToStartOfExcerpt,
9790 window: &mut Window,
9791 cx: &mut Context<Self>,
9792 ) {
9793 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9794 cx.propagate();
9795 return;
9796 }
9797
9798 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9799 s.move_heads_with(|map, head, _| {
9800 (
9801 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9802 SelectionGoal::None,
9803 )
9804 });
9805 })
9806 }
9807
9808 pub fn select_to_end_of_excerpt(
9809 &mut self,
9810 _: &SelectToEndOfExcerpt,
9811 window: &mut Window,
9812 cx: &mut Context<Self>,
9813 ) {
9814 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9815 cx.propagate();
9816 return;
9817 }
9818
9819 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9820 s.move_heads_with(|map, head, _| {
9821 (
9822 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9823 SelectionGoal::None,
9824 )
9825 });
9826 })
9827 }
9828
9829 pub fn move_to_beginning(
9830 &mut self,
9831 _: &MoveToBeginning,
9832 window: &mut Window,
9833 cx: &mut Context<Self>,
9834 ) {
9835 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9836 cx.propagate();
9837 return;
9838 }
9839
9840 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9841 s.select_ranges(vec![0..0]);
9842 });
9843 }
9844
9845 pub fn select_to_beginning(
9846 &mut self,
9847 _: &SelectToBeginning,
9848 window: &mut Window,
9849 cx: &mut Context<Self>,
9850 ) {
9851 let mut selection = self.selections.last::<Point>(cx);
9852 selection.set_head(Point::zero(), SelectionGoal::None);
9853
9854 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9855 s.select(vec![selection]);
9856 });
9857 }
9858
9859 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9860 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9861 cx.propagate();
9862 return;
9863 }
9864
9865 let cursor = self.buffer.read(cx).read(cx).len();
9866 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9867 s.select_ranges(vec![cursor..cursor])
9868 });
9869 }
9870
9871 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9872 self.nav_history = nav_history;
9873 }
9874
9875 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9876 self.nav_history.as_ref()
9877 }
9878
9879 fn push_to_nav_history(
9880 &mut self,
9881 cursor_anchor: Anchor,
9882 new_position: Option<Point>,
9883 cx: &mut Context<Self>,
9884 ) {
9885 if let Some(nav_history) = self.nav_history.as_mut() {
9886 let buffer = self.buffer.read(cx).read(cx);
9887 let cursor_position = cursor_anchor.to_point(&buffer);
9888 let scroll_state = self.scroll_manager.anchor();
9889 let scroll_top_row = scroll_state.top_row(&buffer);
9890 drop(buffer);
9891
9892 if let Some(new_position) = new_position {
9893 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9894 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9895 return;
9896 }
9897 }
9898
9899 nav_history.push(
9900 Some(NavigationData {
9901 cursor_anchor,
9902 cursor_position,
9903 scroll_anchor: scroll_state,
9904 scroll_top_row,
9905 }),
9906 cx,
9907 );
9908 }
9909 }
9910
9911 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9912 let buffer = self.buffer.read(cx).snapshot(cx);
9913 let mut selection = self.selections.first::<usize>(cx);
9914 selection.set_head(buffer.len(), SelectionGoal::None);
9915 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9916 s.select(vec![selection]);
9917 });
9918 }
9919
9920 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9921 let end = self.buffer.read(cx).read(cx).len();
9922 self.change_selections(None, window, cx, |s| {
9923 s.select_ranges(vec![0..end]);
9924 });
9925 }
9926
9927 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9928 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9929 let mut selections = self.selections.all::<Point>(cx);
9930 let max_point = display_map.buffer_snapshot.max_point();
9931 for selection in &mut selections {
9932 let rows = selection.spanned_rows(true, &display_map);
9933 selection.start = Point::new(rows.start.0, 0);
9934 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9935 selection.reversed = false;
9936 }
9937 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9938 s.select(selections);
9939 });
9940 }
9941
9942 pub fn split_selection_into_lines(
9943 &mut self,
9944 _: &SplitSelectionIntoLines,
9945 window: &mut Window,
9946 cx: &mut Context<Self>,
9947 ) {
9948 let selections = self
9949 .selections
9950 .all::<Point>(cx)
9951 .into_iter()
9952 .map(|selection| selection.start..selection.end)
9953 .collect::<Vec<_>>();
9954 self.unfold_ranges(&selections, true, true, cx);
9955
9956 let mut new_selection_ranges = Vec::new();
9957 {
9958 let buffer = self.buffer.read(cx).read(cx);
9959 for selection in selections {
9960 for row in selection.start.row..selection.end.row {
9961 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9962 new_selection_ranges.push(cursor..cursor);
9963 }
9964
9965 let is_multiline_selection = selection.start.row != selection.end.row;
9966 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9967 // so this action feels more ergonomic when paired with other selection operations
9968 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9969 if !should_skip_last {
9970 new_selection_ranges.push(selection.end..selection.end);
9971 }
9972 }
9973 }
9974 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9975 s.select_ranges(new_selection_ranges);
9976 });
9977 }
9978
9979 pub fn add_selection_above(
9980 &mut self,
9981 _: &AddSelectionAbove,
9982 window: &mut Window,
9983 cx: &mut Context<Self>,
9984 ) {
9985 self.add_selection(true, window, cx);
9986 }
9987
9988 pub fn add_selection_below(
9989 &mut self,
9990 _: &AddSelectionBelow,
9991 window: &mut Window,
9992 cx: &mut Context<Self>,
9993 ) {
9994 self.add_selection(false, window, cx);
9995 }
9996
9997 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9998 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9999 let mut selections = self.selections.all::<Point>(cx);
10000 let text_layout_details = self.text_layout_details(window);
10001 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10002 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10003 let range = oldest_selection.display_range(&display_map).sorted();
10004
10005 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10006 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10007 let positions = start_x.min(end_x)..start_x.max(end_x);
10008
10009 selections.clear();
10010 let mut stack = Vec::new();
10011 for row in range.start.row().0..=range.end.row().0 {
10012 if let Some(selection) = self.selections.build_columnar_selection(
10013 &display_map,
10014 DisplayRow(row),
10015 &positions,
10016 oldest_selection.reversed,
10017 &text_layout_details,
10018 ) {
10019 stack.push(selection.id);
10020 selections.push(selection);
10021 }
10022 }
10023
10024 if above {
10025 stack.reverse();
10026 }
10027
10028 AddSelectionsState { above, stack }
10029 });
10030
10031 let last_added_selection = *state.stack.last().unwrap();
10032 let mut new_selections = Vec::new();
10033 if above == state.above {
10034 let end_row = if above {
10035 DisplayRow(0)
10036 } else {
10037 display_map.max_point().row()
10038 };
10039
10040 'outer: for selection in selections {
10041 if selection.id == last_added_selection {
10042 let range = selection.display_range(&display_map).sorted();
10043 debug_assert_eq!(range.start.row(), range.end.row());
10044 let mut row = range.start.row();
10045 let positions =
10046 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10047 px(start)..px(end)
10048 } else {
10049 let start_x =
10050 display_map.x_for_display_point(range.start, &text_layout_details);
10051 let end_x =
10052 display_map.x_for_display_point(range.end, &text_layout_details);
10053 start_x.min(end_x)..start_x.max(end_x)
10054 };
10055
10056 while row != end_row {
10057 if above {
10058 row.0 -= 1;
10059 } else {
10060 row.0 += 1;
10061 }
10062
10063 if let Some(new_selection) = self.selections.build_columnar_selection(
10064 &display_map,
10065 row,
10066 &positions,
10067 selection.reversed,
10068 &text_layout_details,
10069 ) {
10070 state.stack.push(new_selection.id);
10071 if above {
10072 new_selections.push(new_selection);
10073 new_selections.push(selection);
10074 } else {
10075 new_selections.push(selection);
10076 new_selections.push(new_selection);
10077 }
10078
10079 continue 'outer;
10080 }
10081 }
10082 }
10083
10084 new_selections.push(selection);
10085 }
10086 } else {
10087 new_selections = selections;
10088 new_selections.retain(|s| s.id != last_added_selection);
10089 state.stack.pop();
10090 }
10091
10092 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10093 s.select(new_selections);
10094 });
10095 if state.stack.len() > 1 {
10096 self.add_selections_state = Some(state);
10097 }
10098 }
10099
10100 pub fn select_next_match_internal(
10101 &mut self,
10102 display_map: &DisplaySnapshot,
10103 replace_newest: bool,
10104 autoscroll: Option<Autoscroll>,
10105 window: &mut Window,
10106 cx: &mut Context<Self>,
10107 ) -> Result<()> {
10108 fn select_next_match_ranges(
10109 this: &mut Editor,
10110 range: Range<usize>,
10111 replace_newest: bool,
10112 auto_scroll: Option<Autoscroll>,
10113 window: &mut Window,
10114 cx: &mut Context<Editor>,
10115 ) {
10116 this.unfold_ranges(&[range.clone()], false, true, cx);
10117 this.change_selections(auto_scroll, window, cx, |s| {
10118 if replace_newest {
10119 s.delete(s.newest_anchor().id);
10120 }
10121 s.insert_range(range.clone());
10122 });
10123 }
10124
10125 let buffer = &display_map.buffer_snapshot;
10126 let mut selections = self.selections.all::<usize>(cx);
10127 if let Some(mut select_next_state) = self.select_next_state.take() {
10128 let query = &select_next_state.query;
10129 if !select_next_state.done {
10130 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10131 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10132 let mut next_selected_range = None;
10133
10134 let bytes_after_last_selection =
10135 buffer.bytes_in_range(last_selection.end..buffer.len());
10136 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10137 let query_matches = query
10138 .stream_find_iter(bytes_after_last_selection)
10139 .map(|result| (last_selection.end, result))
10140 .chain(
10141 query
10142 .stream_find_iter(bytes_before_first_selection)
10143 .map(|result| (0, result)),
10144 );
10145
10146 for (start_offset, query_match) in query_matches {
10147 let query_match = query_match.unwrap(); // can only fail due to I/O
10148 let offset_range =
10149 start_offset + query_match.start()..start_offset + query_match.end();
10150 let display_range = offset_range.start.to_display_point(display_map)
10151 ..offset_range.end.to_display_point(display_map);
10152
10153 if !select_next_state.wordwise
10154 || (!movement::is_inside_word(display_map, display_range.start)
10155 && !movement::is_inside_word(display_map, display_range.end))
10156 {
10157 // TODO: This is n^2, because we might check all the selections
10158 if !selections
10159 .iter()
10160 .any(|selection| selection.range().overlaps(&offset_range))
10161 {
10162 next_selected_range = Some(offset_range);
10163 break;
10164 }
10165 }
10166 }
10167
10168 if let Some(next_selected_range) = next_selected_range {
10169 select_next_match_ranges(
10170 self,
10171 next_selected_range,
10172 replace_newest,
10173 autoscroll,
10174 window,
10175 cx,
10176 );
10177 } else {
10178 select_next_state.done = true;
10179 }
10180 }
10181
10182 self.select_next_state = Some(select_next_state);
10183 } else {
10184 let mut only_carets = true;
10185 let mut same_text_selected = true;
10186 let mut selected_text = None;
10187
10188 let mut selections_iter = selections.iter().peekable();
10189 while let Some(selection) = selections_iter.next() {
10190 if selection.start != selection.end {
10191 only_carets = false;
10192 }
10193
10194 if same_text_selected {
10195 if selected_text.is_none() {
10196 selected_text =
10197 Some(buffer.text_for_range(selection.range()).collect::<String>());
10198 }
10199
10200 if let Some(next_selection) = selections_iter.peek() {
10201 if next_selection.range().len() == selection.range().len() {
10202 let next_selected_text = buffer
10203 .text_for_range(next_selection.range())
10204 .collect::<String>();
10205 if Some(next_selected_text) != selected_text {
10206 same_text_selected = false;
10207 selected_text = None;
10208 }
10209 } else {
10210 same_text_selected = false;
10211 selected_text = None;
10212 }
10213 }
10214 }
10215 }
10216
10217 if only_carets {
10218 for selection in &mut selections {
10219 let word_range = movement::surrounding_word(
10220 display_map,
10221 selection.start.to_display_point(display_map),
10222 );
10223 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10224 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10225 selection.goal = SelectionGoal::None;
10226 selection.reversed = false;
10227 select_next_match_ranges(
10228 self,
10229 selection.start..selection.end,
10230 replace_newest,
10231 autoscroll,
10232 window,
10233 cx,
10234 );
10235 }
10236
10237 if selections.len() == 1 {
10238 let selection = selections
10239 .last()
10240 .expect("ensured that there's only one selection");
10241 let query = buffer
10242 .text_for_range(selection.start..selection.end)
10243 .collect::<String>();
10244 let is_empty = query.is_empty();
10245 let select_state = SelectNextState {
10246 query: AhoCorasick::new(&[query])?,
10247 wordwise: true,
10248 done: is_empty,
10249 };
10250 self.select_next_state = Some(select_state);
10251 } else {
10252 self.select_next_state = None;
10253 }
10254 } else if let Some(selected_text) = selected_text {
10255 self.select_next_state = Some(SelectNextState {
10256 query: AhoCorasick::new(&[selected_text])?,
10257 wordwise: false,
10258 done: false,
10259 });
10260 self.select_next_match_internal(
10261 display_map,
10262 replace_newest,
10263 autoscroll,
10264 window,
10265 cx,
10266 )?;
10267 }
10268 }
10269 Ok(())
10270 }
10271
10272 pub fn select_all_matches(
10273 &mut self,
10274 _action: &SelectAllMatches,
10275 window: &mut Window,
10276 cx: &mut Context<Self>,
10277 ) -> Result<()> {
10278 self.push_to_selection_history();
10279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10280
10281 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10282 let Some(select_next_state) = self.select_next_state.as_mut() else {
10283 return Ok(());
10284 };
10285 if select_next_state.done {
10286 return Ok(());
10287 }
10288
10289 let mut new_selections = self.selections.all::<usize>(cx);
10290
10291 let buffer = &display_map.buffer_snapshot;
10292 let query_matches = select_next_state
10293 .query
10294 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10295
10296 for query_match in query_matches {
10297 let query_match = query_match.unwrap(); // can only fail due to I/O
10298 let offset_range = query_match.start()..query_match.end();
10299 let display_range = offset_range.start.to_display_point(&display_map)
10300 ..offset_range.end.to_display_point(&display_map);
10301
10302 if !select_next_state.wordwise
10303 || (!movement::is_inside_word(&display_map, display_range.start)
10304 && !movement::is_inside_word(&display_map, display_range.end))
10305 {
10306 self.selections.change_with(cx, |selections| {
10307 new_selections.push(Selection {
10308 id: selections.new_selection_id(),
10309 start: offset_range.start,
10310 end: offset_range.end,
10311 reversed: false,
10312 goal: SelectionGoal::None,
10313 });
10314 });
10315 }
10316 }
10317
10318 new_selections.sort_by_key(|selection| selection.start);
10319 let mut ix = 0;
10320 while ix + 1 < new_selections.len() {
10321 let current_selection = &new_selections[ix];
10322 let next_selection = &new_selections[ix + 1];
10323 if current_selection.range().overlaps(&next_selection.range()) {
10324 if current_selection.id < next_selection.id {
10325 new_selections.remove(ix + 1);
10326 } else {
10327 new_selections.remove(ix);
10328 }
10329 } else {
10330 ix += 1;
10331 }
10332 }
10333
10334 let reversed = self.selections.oldest::<usize>(cx).reversed;
10335
10336 for selection in new_selections.iter_mut() {
10337 selection.reversed = reversed;
10338 }
10339
10340 select_next_state.done = true;
10341 self.unfold_ranges(
10342 &new_selections
10343 .iter()
10344 .map(|selection| selection.range())
10345 .collect::<Vec<_>>(),
10346 false,
10347 false,
10348 cx,
10349 );
10350 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10351 selections.select(new_selections)
10352 });
10353
10354 Ok(())
10355 }
10356
10357 pub fn select_next(
10358 &mut self,
10359 action: &SelectNext,
10360 window: &mut Window,
10361 cx: &mut Context<Self>,
10362 ) -> Result<()> {
10363 self.push_to_selection_history();
10364 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10365 self.select_next_match_internal(
10366 &display_map,
10367 action.replace_newest,
10368 Some(Autoscroll::newest()),
10369 window,
10370 cx,
10371 )?;
10372 Ok(())
10373 }
10374
10375 pub fn select_previous(
10376 &mut self,
10377 action: &SelectPrevious,
10378 window: &mut Window,
10379 cx: &mut Context<Self>,
10380 ) -> Result<()> {
10381 self.push_to_selection_history();
10382 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10383 let buffer = &display_map.buffer_snapshot;
10384 let mut selections = self.selections.all::<usize>(cx);
10385 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10386 let query = &select_prev_state.query;
10387 if !select_prev_state.done {
10388 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10389 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10390 let mut next_selected_range = None;
10391 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10392 let bytes_before_last_selection =
10393 buffer.reversed_bytes_in_range(0..last_selection.start);
10394 let bytes_after_first_selection =
10395 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10396 let query_matches = query
10397 .stream_find_iter(bytes_before_last_selection)
10398 .map(|result| (last_selection.start, result))
10399 .chain(
10400 query
10401 .stream_find_iter(bytes_after_first_selection)
10402 .map(|result| (buffer.len(), result)),
10403 );
10404 for (end_offset, query_match) in query_matches {
10405 let query_match = query_match.unwrap(); // can only fail due to I/O
10406 let offset_range =
10407 end_offset - query_match.end()..end_offset - query_match.start();
10408 let display_range = offset_range.start.to_display_point(&display_map)
10409 ..offset_range.end.to_display_point(&display_map);
10410
10411 if !select_prev_state.wordwise
10412 || (!movement::is_inside_word(&display_map, display_range.start)
10413 && !movement::is_inside_word(&display_map, display_range.end))
10414 {
10415 next_selected_range = Some(offset_range);
10416 break;
10417 }
10418 }
10419
10420 if let Some(next_selected_range) = next_selected_range {
10421 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10422 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10423 if action.replace_newest {
10424 s.delete(s.newest_anchor().id);
10425 }
10426 s.insert_range(next_selected_range);
10427 });
10428 } else {
10429 select_prev_state.done = true;
10430 }
10431 }
10432
10433 self.select_prev_state = Some(select_prev_state);
10434 } else {
10435 let mut only_carets = true;
10436 let mut same_text_selected = true;
10437 let mut selected_text = None;
10438
10439 let mut selections_iter = selections.iter().peekable();
10440 while let Some(selection) = selections_iter.next() {
10441 if selection.start != selection.end {
10442 only_carets = false;
10443 }
10444
10445 if same_text_selected {
10446 if selected_text.is_none() {
10447 selected_text =
10448 Some(buffer.text_for_range(selection.range()).collect::<String>());
10449 }
10450
10451 if let Some(next_selection) = selections_iter.peek() {
10452 if next_selection.range().len() == selection.range().len() {
10453 let next_selected_text = buffer
10454 .text_for_range(next_selection.range())
10455 .collect::<String>();
10456 if Some(next_selected_text) != selected_text {
10457 same_text_selected = false;
10458 selected_text = None;
10459 }
10460 } else {
10461 same_text_selected = false;
10462 selected_text = None;
10463 }
10464 }
10465 }
10466 }
10467
10468 if only_carets {
10469 for selection in &mut selections {
10470 let word_range = movement::surrounding_word(
10471 &display_map,
10472 selection.start.to_display_point(&display_map),
10473 );
10474 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10475 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10476 selection.goal = SelectionGoal::None;
10477 selection.reversed = false;
10478 }
10479 if selections.len() == 1 {
10480 let selection = selections
10481 .last()
10482 .expect("ensured that there's only one selection");
10483 let query = buffer
10484 .text_for_range(selection.start..selection.end)
10485 .collect::<String>();
10486 let is_empty = query.is_empty();
10487 let select_state = SelectNextState {
10488 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10489 wordwise: true,
10490 done: is_empty,
10491 };
10492 self.select_prev_state = Some(select_state);
10493 } else {
10494 self.select_prev_state = None;
10495 }
10496
10497 self.unfold_ranges(
10498 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10499 false,
10500 true,
10501 cx,
10502 );
10503 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10504 s.select(selections);
10505 });
10506 } else if let Some(selected_text) = selected_text {
10507 self.select_prev_state = Some(SelectNextState {
10508 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10509 wordwise: false,
10510 done: false,
10511 });
10512 self.select_previous(action, window, cx)?;
10513 }
10514 }
10515 Ok(())
10516 }
10517
10518 pub fn toggle_comments(
10519 &mut self,
10520 action: &ToggleComments,
10521 window: &mut Window,
10522 cx: &mut Context<Self>,
10523 ) {
10524 if self.read_only(cx) {
10525 return;
10526 }
10527 let text_layout_details = &self.text_layout_details(window);
10528 self.transact(window, cx, |this, window, cx| {
10529 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10530 let mut edits = Vec::new();
10531 let mut selection_edit_ranges = Vec::new();
10532 let mut last_toggled_row = None;
10533 let snapshot = this.buffer.read(cx).read(cx);
10534 let empty_str: Arc<str> = Arc::default();
10535 let mut suffixes_inserted = Vec::new();
10536 let ignore_indent = action.ignore_indent;
10537
10538 fn comment_prefix_range(
10539 snapshot: &MultiBufferSnapshot,
10540 row: MultiBufferRow,
10541 comment_prefix: &str,
10542 comment_prefix_whitespace: &str,
10543 ignore_indent: bool,
10544 ) -> Range<Point> {
10545 let indent_size = if ignore_indent {
10546 0
10547 } else {
10548 snapshot.indent_size_for_line(row).len
10549 };
10550
10551 let start = Point::new(row.0, indent_size);
10552
10553 let mut line_bytes = snapshot
10554 .bytes_in_range(start..snapshot.max_point())
10555 .flatten()
10556 .copied();
10557
10558 // If this line currently begins with the line comment prefix, then record
10559 // the range containing the prefix.
10560 if line_bytes
10561 .by_ref()
10562 .take(comment_prefix.len())
10563 .eq(comment_prefix.bytes())
10564 {
10565 // Include any whitespace that matches the comment prefix.
10566 let matching_whitespace_len = line_bytes
10567 .zip(comment_prefix_whitespace.bytes())
10568 .take_while(|(a, b)| a == b)
10569 .count() as u32;
10570 let end = Point::new(
10571 start.row,
10572 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10573 );
10574 start..end
10575 } else {
10576 start..start
10577 }
10578 }
10579
10580 fn comment_suffix_range(
10581 snapshot: &MultiBufferSnapshot,
10582 row: MultiBufferRow,
10583 comment_suffix: &str,
10584 comment_suffix_has_leading_space: bool,
10585 ) -> Range<Point> {
10586 let end = Point::new(row.0, snapshot.line_len(row));
10587 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10588
10589 let mut line_end_bytes = snapshot
10590 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10591 .flatten()
10592 .copied();
10593
10594 let leading_space_len = if suffix_start_column > 0
10595 && line_end_bytes.next() == Some(b' ')
10596 && comment_suffix_has_leading_space
10597 {
10598 1
10599 } else {
10600 0
10601 };
10602
10603 // If this line currently begins with the line comment prefix, then record
10604 // the range containing the prefix.
10605 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10606 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10607 start..end
10608 } else {
10609 end..end
10610 }
10611 }
10612
10613 // TODO: Handle selections that cross excerpts
10614 for selection in &mut selections {
10615 let start_column = snapshot
10616 .indent_size_for_line(MultiBufferRow(selection.start.row))
10617 .len;
10618 let language = if let Some(language) =
10619 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10620 {
10621 language
10622 } else {
10623 continue;
10624 };
10625
10626 selection_edit_ranges.clear();
10627
10628 // If multiple selections contain a given row, avoid processing that
10629 // row more than once.
10630 let mut start_row = MultiBufferRow(selection.start.row);
10631 if last_toggled_row == Some(start_row) {
10632 start_row = start_row.next_row();
10633 }
10634 let end_row =
10635 if selection.end.row > selection.start.row && selection.end.column == 0 {
10636 MultiBufferRow(selection.end.row - 1)
10637 } else {
10638 MultiBufferRow(selection.end.row)
10639 };
10640 last_toggled_row = Some(end_row);
10641
10642 if start_row > end_row {
10643 continue;
10644 }
10645
10646 // If the language has line comments, toggle those.
10647 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10648
10649 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10650 if ignore_indent {
10651 full_comment_prefixes = full_comment_prefixes
10652 .into_iter()
10653 .map(|s| Arc::from(s.trim_end()))
10654 .collect();
10655 }
10656
10657 if !full_comment_prefixes.is_empty() {
10658 let first_prefix = full_comment_prefixes
10659 .first()
10660 .expect("prefixes is non-empty");
10661 let prefix_trimmed_lengths = full_comment_prefixes
10662 .iter()
10663 .map(|p| p.trim_end_matches(' ').len())
10664 .collect::<SmallVec<[usize; 4]>>();
10665
10666 let mut all_selection_lines_are_comments = true;
10667
10668 for row in start_row.0..=end_row.0 {
10669 let row = MultiBufferRow(row);
10670 if start_row < end_row && snapshot.is_line_blank(row) {
10671 continue;
10672 }
10673
10674 let prefix_range = full_comment_prefixes
10675 .iter()
10676 .zip(prefix_trimmed_lengths.iter().copied())
10677 .map(|(prefix, trimmed_prefix_len)| {
10678 comment_prefix_range(
10679 snapshot.deref(),
10680 row,
10681 &prefix[..trimmed_prefix_len],
10682 &prefix[trimmed_prefix_len..],
10683 ignore_indent,
10684 )
10685 })
10686 .max_by_key(|range| range.end.column - range.start.column)
10687 .expect("prefixes is non-empty");
10688
10689 if prefix_range.is_empty() {
10690 all_selection_lines_are_comments = false;
10691 }
10692
10693 selection_edit_ranges.push(prefix_range);
10694 }
10695
10696 if all_selection_lines_are_comments {
10697 edits.extend(
10698 selection_edit_ranges
10699 .iter()
10700 .cloned()
10701 .map(|range| (range, empty_str.clone())),
10702 );
10703 } else {
10704 let min_column = selection_edit_ranges
10705 .iter()
10706 .map(|range| range.start.column)
10707 .min()
10708 .unwrap_or(0);
10709 edits.extend(selection_edit_ranges.iter().map(|range| {
10710 let position = Point::new(range.start.row, min_column);
10711 (position..position, first_prefix.clone())
10712 }));
10713 }
10714 } else if let Some((full_comment_prefix, comment_suffix)) =
10715 language.block_comment_delimiters()
10716 {
10717 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10718 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10719 let prefix_range = comment_prefix_range(
10720 snapshot.deref(),
10721 start_row,
10722 comment_prefix,
10723 comment_prefix_whitespace,
10724 ignore_indent,
10725 );
10726 let suffix_range = comment_suffix_range(
10727 snapshot.deref(),
10728 end_row,
10729 comment_suffix.trim_start_matches(' '),
10730 comment_suffix.starts_with(' '),
10731 );
10732
10733 if prefix_range.is_empty() || suffix_range.is_empty() {
10734 edits.push((
10735 prefix_range.start..prefix_range.start,
10736 full_comment_prefix.clone(),
10737 ));
10738 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10739 suffixes_inserted.push((end_row, comment_suffix.len()));
10740 } else {
10741 edits.push((prefix_range, empty_str.clone()));
10742 edits.push((suffix_range, empty_str.clone()));
10743 }
10744 } else {
10745 continue;
10746 }
10747 }
10748
10749 drop(snapshot);
10750 this.buffer.update(cx, |buffer, cx| {
10751 buffer.edit(edits, None, cx);
10752 });
10753
10754 // Adjust selections so that they end before any comment suffixes that
10755 // were inserted.
10756 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10757 let mut selections = this.selections.all::<Point>(cx);
10758 let snapshot = this.buffer.read(cx).read(cx);
10759 for selection in &mut selections {
10760 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10761 match row.cmp(&MultiBufferRow(selection.end.row)) {
10762 Ordering::Less => {
10763 suffixes_inserted.next();
10764 continue;
10765 }
10766 Ordering::Greater => break,
10767 Ordering::Equal => {
10768 if selection.end.column == snapshot.line_len(row) {
10769 if selection.is_empty() {
10770 selection.start.column -= suffix_len as u32;
10771 }
10772 selection.end.column -= suffix_len as u32;
10773 }
10774 break;
10775 }
10776 }
10777 }
10778 }
10779
10780 drop(snapshot);
10781 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10782 s.select(selections)
10783 });
10784
10785 let selections = this.selections.all::<Point>(cx);
10786 let selections_on_single_row = selections.windows(2).all(|selections| {
10787 selections[0].start.row == selections[1].start.row
10788 && selections[0].end.row == selections[1].end.row
10789 && selections[0].start.row == selections[0].end.row
10790 });
10791 let selections_selecting = selections
10792 .iter()
10793 .any(|selection| selection.start != selection.end);
10794 let advance_downwards = action.advance_downwards
10795 && selections_on_single_row
10796 && !selections_selecting
10797 && !matches!(this.mode, EditorMode::SingleLine { .. });
10798
10799 if advance_downwards {
10800 let snapshot = this.buffer.read(cx).snapshot(cx);
10801
10802 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10803 s.move_cursors_with(|display_snapshot, display_point, _| {
10804 let mut point = display_point.to_point(display_snapshot);
10805 point.row += 1;
10806 point = snapshot.clip_point(point, Bias::Left);
10807 let display_point = point.to_display_point(display_snapshot);
10808 let goal = SelectionGoal::HorizontalPosition(
10809 display_snapshot
10810 .x_for_display_point(display_point, text_layout_details)
10811 .into(),
10812 );
10813 (display_point, goal)
10814 })
10815 });
10816 }
10817 });
10818 }
10819
10820 pub fn select_enclosing_symbol(
10821 &mut self,
10822 _: &SelectEnclosingSymbol,
10823 window: &mut Window,
10824 cx: &mut Context<Self>,
10825 ) {
10826 let buffer = self.buffer.read(cx).snapshot(cx);
10827 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10828
10829 fn update_selection(
10830 selection: &Selection<usize>,
10831 buffer_snap: &MultiBufferSnapshot,
10832 ) -> Option<Selection<usize>> {
10833 let cursor = selection.head();
10834 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10835 for symbol in symbols.iter().rev() {
10836 let start = symbol.range.start.to_offset(buffer_snap);
10837 let end = symbol.range.end.to_offset(buffer_snap);
10838 let new_range = start..end;
10839 if start < selection.start || end > selection.end {
10840 return Some(Selection {
10841 id: selection.id,
10842 start: new_range.start,
10843 end: new_range.end,
10844 goal: SelectionGoal::None,
10845 reversed: selection.reversed,
10846 });
10847 }
10848 }
10849 None
10850 }
10851
10852 let mut selected_larger_symbol = false;
10853 let new_selections = old_selections
10854 .iter()
10855 .map(|selection| match update_selection(selection, &buffer) {
10856 Some(new_selection) => {
10857 if new_selection.range() != selection.range() {
10858 selected_larger_symbol = true;
10859 }
10860 new_selection
10861 }
10862 None => selection.clone(),
10863 })
10864 .collect::<Vec<_>>();
10865
10866 if selected_larger_symbol {
10867 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10868 s.select(new_selections);
10869 });
10870 }
10871 }
10872
10873 pub fn select_larger_syntax_node(
10874 &mut self,
10875 _: &SelectLargerSyntaxNode,
10876 window: &mut Window,
10877 cx: &mut Context<Self>,
10878 ) {
10879 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10880 let buffer = self.buffer.read(cx).snapshot(cx);
10881 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10882
10883 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10884 let mut selected_larger_node = false;
10885 let new_selections = old_selections
10886 .iter()
10887 .map(|selection| {
10888 let old_range = selection.start..selection.end;
10889 let mut new_range = old_range.clone();
10890 let mut new_node = None;
10891 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10892 {
10893 new_node = Some(node);
10894 new_range = match containing_range {
10895 MultiOrSingleBufferOffsetRange::Single(_) => break,
10896 MultiOrSingleBufferOffsetRange::Multi(range) => range,
10897 };
10898 if !display_map.intersects_fold(new_range.start)
10899 && !display_map.intersects_fold(new_range.end)
10900 {
10901 break;
10902 }
10903 }
10904
10905 if let Some(node) = new_node {
10906 // Log the ancestor, to support using this action as a way to explore TreeSitter
10907 // nodes. Parent and grandparent are also logged because this operation will not
10908 // visit nodes that have the same range as their parent.
10909 log::info!("Node: {node:?}");
10910 let parent = node.parent();
10911 log::info!("Parent: {parent:?}");
10912 let grandparent = parent.and_then(|x| x.parent());
10913 log::info!("Grandparent: {grandparent:?}");
10914 }
10915
10916 selected_larger_node |= new_range != old_range;
10917 Selection {
10918 id: selection.id,
10919 start: new_range.start,
10920 end: new_range.end,
10921 goal: SelectionGoal::None,
10922 reversed: selection.reversed,
10923 }
10924 })
10925 .collect::<Vec<_>>();
10926
10927 if selected_larger_node {
10928 stack.push(old_selections);
10929 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10930 s.select(new_selections);
10931 });
10932 }
10933 self.select_larger_syntax_node_stack = stack;
10934 }
10935
10936 pub fn select_smaller_syntax_node(
10937 &mut self,
10938 _: &SelectSmallerSyntaxNode,
10939 window: &mut Window,
10940 cx: &mut Context<Self>,
10941 ) {
10942 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10943 if let Some(selections) = stack.pop() {
10944 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10945 s.select(selections.to_vec());
10946 });
10947 }
10948 self.select_larger_syntax_node_stack = stack;
10949 }
10950
10951 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10952 if !EditorSettings::get_global(cx).gutter.runnables {
10953 self.clear_tasks();
10954 return Task::ready(());
10955 }
10956 let project = self.project.as_ref().map(Entity::downgrade);
10957 cx.spawn_in(window, |this, mut cx| async move {
10958 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10959 let Some(project) = project.and_then(|p| p.upgrade()) else {
10960 return;
10961 };
10962 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10963 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10964 }) else {
10965 return;
10966 };
10967
10968 let hide_runnables = project
10969 .update(&mut cx, |project, cx| {
10970 // Do not display any test indicators in non-dev server remote projects.
10971 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10972 })
10973 .unwrap_or(true);
10974 if hide_runnables {
10975 return;
10976 }
10977 let new_rows =
10978 cx.background_spawn({
10979 let snapshot = display_snapshot.clone();
10980 async move {
10981 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10982 }
10983 })
10984 .await;
10985
10986 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10987 this.update(&mut cx, |this, _| {
10988 this.clear_tasks();
10989 for (key, value) in rows {
10990 this.insert_tasks(key, value);
10991 }
10992 })
10993 .ok();
10994 })
10995 }
10996 fn fetch_runnable_ranges(
10997 snapshot: &DisplaySnapshot,
10998 range: Range<Anchor>,
10999 ) -> Vec<language::RunnableRange> {
11000 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11001 }
11002
11003 fn runnable_rows(
11004 project: Entity<Project>,
11005 snapshot: DisplaySnapshot,
11006 runnable_ranges: Vec<RunnableRange>,
11007 mut cx: AsyncWindowContext,
11008 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11009 runnable_ranges
11010 .into_iter()
11011 .filter_map(|mut runnable| {
11012 let tasks = cx
11013 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11014 .ok()?;
11015 if tasks.is_empty() {
11016 return None;
11017 }
11018
11019 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11020
11021 let row = snapshot
11022 .buffer_snapshot
11023 .buffer_line_for_row(MultiBufferRow(point.row))?
11024 .1
11025 .start
11026 .row;
11027
11028 let context_range =
11029 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11030 Some((
11031 (runnable.buffer_id, row),
11032 RunnableTasks {
11033 templates: tasks,
11034 offset: snapshot
11035 .buffer_snapshot
11036 .anchor_before(runnable.run_range.start),
11037 context_range,
11038 column: point.column,
11039 extra_variables: runnable.extra_captures,
11040 },
11041 ))
11042 })
11043 .collect()
11044 }
11045
11046 fn templates_with_tags(
11047 project: &Entity<Project>,
11048 runnable: &mut Runnable,
11049 cx: &mut App,
11050 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11051 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11052 let (worktree_id, file) = project
11053 .buffer_for_id(runnable.buffer, cx)
11054 .and_then(|buffer| buffer.read(cx).file())
11055 .map(|file| (file.worktree_id(cx), file.clone()))
11056 .unzip();
11057
11058 (
11059 project.task_store().read(cx).task_inventory().cloned(),
11060 worktree_id,
11061 file,
11062 )
11063 });
11064
11065 let tags = mem::take(&mut runnable.tags);
11066 let mut tags: Vec<_> = tags
11067 .into_iter()
11068 .flat_map(|tag| {
11069 let tag = tag.0.clone();
11070 inventory
11071 .as_ref()
11072 .into_iter()
11073 .flat_map(|inventory| {
11074 inventory.read(cx).list_tasks(
11075 file.clone(),
11076 Some(runnable.language.clone()),
11077 worktree_id,
11078 cx,
11079 )
11080 })
11081 .filter(move |(_, template)| {
11082 template.tags.iter().any(|source_tag| source_tag == &tag)
11083 })
11084 })
11085 .sorted_by_key(|(kind, _)| kind.to_owned())
11086 .collect();
11087 if let Some((leading_tag_source, _)) = tags.first() {
11088 // Strongest source wins; if we have worktree tag binding, prefer that to
11089 // global and language bindings;
11090 // if we have a global binding, prefer that to language binding.
11091 let first_mismatch = tags
11092 .iter()
11093 .position(|(tag_source, _)| tag_source != leading_tag_source);
11094 if let Some(index) = first_mismatch {
11095 tags.truncate(index);
11096 }
11097 }
11098
11099 tags
11100 }
11101
11102 pub fn move_to_enclosing_bracket(
11103 &mut self,
11104 _: &MoveToEnclosingBracket,
11105 window: &mut Window,
11106 cx: &mut Context<Self>,
11107 ) {
11108 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11109 s.move_offsets_with(|snapshot, selection| {
11110 let Some(enclosing_bracket_ranges) =
11111 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11112 else {
11113 return;
11114 };
11115
11116 let mut best_length = usize::MAX;
11117 let mut best_inside = false;
11118 let mut best_in_bracket_range = false;
11119 let mut best_destination = None;
11120 for (open, close) in enclosing_bracket_ranges {
11121 let close = close.to_inclusive();
11122 let length = close.end() - open.start;
11123 let inside = selection.start >= open.end && selection.end <= *close.start();
11124 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11125 || close.contains(&selection.head());
11126
11127 // If best is next to a bracket and current isn't, skip
11128 if !in_bracket_range && best_in_bracket_range {
11129 continue;
11130 }
11131
11132 // Prefer smaller lengths unless best is inside and current isn't
11133 if length > best_length && (best_inside || !inside) {
11134 continue;
11135 }
11136
11137 best_length = length;
11138 best_inside = inside;
11139 best_in_bracket_range = in_bracket_range;
11140 best_destination = Some(
11141 if close.contains(&selection.start) && close.contains(&selection.end) {
11142 if inside {
11143 open.end
11144 } else {
11145 open.start
11146 }
11147 } else if inside {
11148 *close.start()
11149 } else {
11150 *close.end()
11151 },
11152 );
11153 }
11154
11155 if let Some(destination) = best_destination {
11156 selection.collapse_to(destination, SelectionGoal::None);
11157 }
11158 })
11159 });
11160 }
11161
11162 pub fn undo_selection(
11163 &mut self,
11164 _: &UndoSelection,
11165 window: &mut Window,
11166 cx: &mut Context<Self>,
11167 ) {
11168 self.end_selection(window, cx);
11169 self.selection_history.mode = SelectionHistoryMode::Undoing;
11170 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11171 self.change_selections(None, window, cx, |s| {
11172 s.select_anchors(entry.selections.to_vec())
11173 });
11174 self.select_next_state = entry.select_next_state;
11175 self.select_prev_state = entry.select_prev_state;
11176 self.add_selections_state = entry.add_selections_state;
11177 self.request_autoscroll(Autoscroll::newest(), cx);
11178 }
11179 self.selection_history.mode = SelectionHistoryMode::Normal;
11180 }
11181
11182 pub fn redo_selection(
11183 &mut self,
11184 _: &RedoSelection,
11185 window: &mut Window,
11186 cx: &mut Context<Self>,
11187 ) {
11188 self.end_selection(window, cx);
11189 self.selection_history.mode = SelectionHistoryMode::Redoing;
11190 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11191 self.change_selections(None, window, cx, |s| {
11192 s.select_anchors(entry.selections.to_vec())
11193 });
11194 self.select_next_state = entry.select_next_state;
11195 self.select_prev_state = entry.select_prev_state;
11196 self.add_selections_state = entry.add_selections_state;
11197 self.request_autoscroll(Autoscroll::newest(), cx);
11198 }
11199 self.selection_history.mode = SelectionHistoryMode::Normal;
11200 }
11201
11202 pub fn expand_excerpts(
11203 &mut self,
11204 action: &ExpandExcerpts,
11205 _: &mut Window,
11206 cx: &mut Context<Self>,
11207 ) {
11208 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11209 }
11210
11211 pub fn expand_excerpts_down(
11212 &mut self,
11213 action: &ExpandExcerptsDown,
11214 _: &mut Window,
11215 cx: &mut Context<Self>,
11216 ) {
11217 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11218 }
11219
11220 pub fn expand_excerpts_up(
11221 &mut self,
11222 action: &ExpandExcerptsUp,
11223 _: &mut Window,
11224 cx: &mut Context<Self>,
11225 ) {
11226 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11227 }
11228
11229 pub fn expand_excerpts_for_direction(
11230 &mut self,
11231 lines: u32,
11232 direction: ExpandExcerptDirection,
11233
11234 cx: &mut Context<Self>,
11235 ) {
11236 let selections = self.selections.disjoint_anchors();
11237
11238 let lines = if lines == 0 {
11239 EditorSettings::get_global(cx).expand_excerpt_lines
11240 } else {
11241 lines
11242 };
11243
11244 self.buffer.update(cx, |buffer, cx| {
11245 let snapshot = buffer.snapshot(cx);
11246 let mut excerpt_ids = selections
11247 .iter()
11248 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11249 .collect::<Vec<_>>();
11250 excerpt_ids.sort();
11251 excerpt_ids.dedup();
11252 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11253 })
11254 }
11255
11256 pub fn expand_excerpt(
11257 &mut self,
11258 excerpt: ExcerptId,
11259 direction: ExpandExcerptDirection,
11260 cx: &mut Context<Self>,
11261 ) {
11262 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11263 self.buffer.update(cx, |buffer, cx| {
11264 buffer.expand_excerpts([excerpt], lines, direction, cx)
11265 })
11266 }
11267
11268 pub fn go_to_singleton_buffer_point(
11269 &mut self,
11270 point: Point,
11271 window: &mut Window,
11272 cx: &mut Context<Self>,
11273 ) {
11274 self.go_to_singleton_buffer_range(point..point, window, cx);
11275 }
11276
11277 pub fn go_to_singleton_buffer_range(
11278 &mut self,
11279 range: Range<Point>,
11280 window: &mut Window,
11281 cx: &mut Context<Self>,
11282 ) {
11283 let multibuffer = self.buffer().read(cx);
11284 let Some(buffer) = multibuffer.as_singleton() else {
11285 return;
11286 };
11287 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11288 return;
11289 };
11290 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11291 return;
11292 };
11293 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11294 s.select_anchor_ranges([start..end])
11295 });
11296 }
11297
11298 fn go_to_diagnostic(
11299 &mut self,
11300 _: &GoToDiagnostic,
11301 window: &mut Window,
11302 cx: &mut Context<Self>,
11303 ) {
11304 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11305 }
11306
11307 fn go_to_prev_diagnostic(
11308 &mut self,
11309 _: &GoToPreviousDiagnostic,
11310 window: &mut Window,
11311 cx: &mut Context<Self>,
11312 ) {
11313 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11314 }
11315
11316 pub fn go_to_diagnostic_impl(
11317 &mut self,
11318 direction: Direction,
11319 window: &mut Window,
11320 cx: &mut Context<Self>,
11321 ) {
11322 let buffer = self.buffer.read(cx).snapshot(cx);
11323 let selection = self.selections.newest::<usize>(cx);
11324
11325 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11326 if direction == Direction::Next {
11327 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11328 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11329 return;
11330 };
11331 self.activate_diagnostics(
11332 buffer_id,
11333 popover.local_diagnostic.diagnostic.group_id,
11334 window,
11335 cx,
11336 );
11337 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11338 let primary_range_start = active_diagnostics.primary_range.start;
11339 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11340 let mut new_selection = s.newest_anchor().clone();
11341 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11342 s.select_anchors(vec![new_selection.clone()]);
11343 });
11344 self.refresh_inline_completion(false, true, window, cx);
11345 }
11346 return;
11347 }
11348 }
11349
11350 let active_group_id = self
11351 .active_diagnostics
11352 .as_ref()
11353 .map(|active_group| active_group.group_id);
11354 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11355 active_diagnostics
11356 .primary_range
11357 .to_offset(&buffer)
11358 .to_inclusive()
11359 });
11360 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11361 if active_primary_range.contains(&selection.head()) {
11362 *active_primary_range.start()
11363 } else {
11364 selection.head()
11365 }
11366 } else {
11367 selection.head()
11368 };
11369
11370 let snapshot = self.snapshot(window, cx);
11371 let primary_diagnostics_before = buffer
11372 .diagnostics_in_range::<usize>(0..search_start)
11373 .filter(|entry| entry.diagnostic.is_primary)
11374 .filter(|entry| entry.range.start != entry.range.end)
11375 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11376 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11377 .collect::<Vec<_>>();
11378 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11379 primary_diagnostics_before
11380 .iter()
11381 .position(|entry| entry.diagnostic.group_id == active_group_id)
11382 });
11383
11384 let primary_diagnostics_after = buffer
11385 .diagnostics_in_range::<usize>(search_start..buffer.len())
11386 .filter(|entry| entry.diagnostic.is_primary)
11387 .filter(|entry| entry.range.start != entry.range.end)
11388 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11389 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11390 .collect::<Vec<_>>();
11391 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11392 primary_diagnostics_after
11393 .iter()
11394 .enumerate()
11395 .rev()
11396 .find_map(|(i, entry)| {
11397 if entry.diagnostic.group_id == active_group_id {
11398 Some(i)
11399 } else {
11400 None
11401 }
11402 })
11403 });
11404
11405 let next_primary_diagnostic = match direction {
11406 Direction::Prev => primary_diagnostics_before
11407 .iter()
11408 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11409 .rev()
11410 .next(),
11411 Direction::Next => primary_diagnostics_after
11412 .iter()
11413 .skip(
11414 last_same_group_diagnostic_after
11415 .map(|index| index + 1)
11416 .unwrap_or(0),
11417 )
11418 .next(),
11419 };
11420
11421 // Cycle around to the start of the buffer, potentially moving back to the start of
11422 // the currently active diagnostic.
11423 let cycle_around = || match direction {
11424 Direction::Prev => primary_diagnostics_after
11425 .iter()
11426 .rev()
11427 .chain(primary_diagnostics_before.iter().rev())
11428 .next(),
11429 Direction::Next => primary_diagnostics_before
11430 .iter()
11431 .chain(primary_diagnostics_after.iter())
11432 .next(),
11433 };
11434
11435 if let Some((primary_range, group_id)) = next_primary_diagnostic
11436 .or_else(cycle_around)
11437 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11438 {
11439 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11440 return;
11441 };
11442 self.activate_diagnostics(buffer_id, group_id, window, cx);
11443 if self.active_diagnostics.is_some() {
11444 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11445 s.select(vec![Selection {
11446 id: selection.id,
11447 start: primary_range.start,
11448 end: primary_range.start,
11449 reversed: false,
11450 goal: SelectionGoal::None,
11451 }]);
11452 });
11453 self.refresh_inline_completion(false, true, window, cx);
11454 }
11455 }
11456 }
11457
11458 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11459 let snapshot = self.snapshot(window, cx);
11460 let selection = self.selections.newest::<Point>(cx);
11461 self.go_to_hunk_after_or_before_position(
11462 &snapshot,
11463 selection.head(),
11464 Direction::Next,
11465 window,
11466 cx,
11467 );
11468 }
11469
11470 fn go_to_hunk_after_or_before_position(
11471 &mut self,
11472 snapshot: &EditorSnapshot,
11473 position: Point,
11474 direction: Direction,
11475 window: &mut Window,
11476 cx: &mut Context<Editor>,
11477 ) {
11478 let row = if direction == Direction::Next {
11479 self.hunk_after_position(snapshot, position)
11480 .map(|hunk| hunk.row_range.start)
11481 } else {
11482 self.hunk_before_position(snapshot, position)
11483 };
11484
11485 if let Some(row) = row {
11486 let destination = Point::new(row.0, 0);
11487 let autoscroll = Autoscroll::center();
11488
11489 self.unfold_ranges(&[destination..destination], false, false, cx);
11490 self.change_selections(Some(autoscroll), window, cx, |s| {
11491 s.select_ranges([destination..destination]);
11492 });
11493 }
11494 }
11495
11496 fn hunk_after_position(
11497 &mut self,
11498 snapshot: &EditorSnapshot,
11499 position: Point,
11500 ) -> Option<MultiBufferDiffHunk> {
11501 snapshot
11502 .buffer_snapshot
11503 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11504 .find(|hunk| hunk.row_range.start.0 > position.row)
11505 .or_else(|| {
11506 snapshot
11507 .buffer_snapshot
11508 .diff_hunks_in_range(Point::zero()..position)
11509 .find(|hunk| hunk.row_range.end.0 < position.row)
11510 })
11511 }
11512
11513 fn go_to_prev_hunk(
11514 &mut self,
11515 _: &GoToPreviousHunk,
11516 window: &mut Window,
11517 cx: &mut Context<Self>,
11518 ) {
11519 let snapshot = self.snapshot(window, cx);
11520 let selection = self.selections.newest::<Point>(cx);
11521 self.go_to_hunk_after_or_before_position(
11522 &snapshot,
11523 selection.head(),
11524 Direction::Prev,
11525 window,
11526 cx,
11527 );
11528 }
11529
11530 fn hunk_before_position(
11531 &mut self,
11532 snapshot: &EditorSnapshot,
11533 position: Point,
11534 ) -> Option<MultiBufferRow> {
11535 snapshot
11536 .buffer_snapshot
11537 .diff_hunk_before(position)
11538 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11539 }
11540
11541 pub fn go_to_definition(
11542 &mut self,
11543 _: &GoToDefinition,
11544 window: &mut Window,
11545 cx: &mut Context<Self>,
11546 ) -> Task<Result<Navigated>> {
11547 let definition =
11548 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11549 cx.spawn_in(window, |editor, mut cx| async move {
11550 if definition.await? == Navigated::Yes {
11551 return Ok(Navigated::Yes);
11552 }
11553 match editor.update_in(&mut cx, |editor, window, cx| {
11554 editor.find_all_references(&FindAllReferences, window, cx)
11555 })? {
11556 Some(references) => references.await,
11557 None => Ok(Navigated::No),
11558 }
11559 })
11560 }
11561
11562 pub fn go_to_declaration(
11563 &mut self,
11564 _: &GoToDeclaration,
11565 window: &mut Window,
11566 cx: &mut Context<Self>,
11567 ) -> Task<Result<Navigated>> {
11568 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11569 }
11570
11571 pub fn go_to_declaration_split(
11572 &mut self,
11573 _: &GoToDeclaration,
11574 window: &mut Window,
11575 cx: &mut Context<Self>,
11576 ) -> Task<Result<Navigated>> {
11577 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11578 }
11579
11580 pub fn go_to_implementation(
11581 &mut self,
11582 _: &GoToImplementation,
11583 window: &mut Window,
11584 cx: &mut Context<Self>,
11585 ) -> Task<Result<Navigated>> {
11586 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11587 }
11588
11589 pub fn go_to_implementation_split(
11590 &mut self,
11591 _: &GoToImplementationSplit,
11592 window: &mut Window,
11593 cx: &mut Context<Self>,
11594 ) -> Task<Result<Navigated>> {
11595 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11596 }
11597
11598 pub fn go_to_type_definition(
11599 &mut self,
11600 _: &GoToTypeDefinition,
11601 window: &mut Window,
11602 cx: &mut Context<Self>,
11603 ) -> Task<Result<Navigated>> {
11604 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11605 }
11606
11607 pub fn go_to_definition_split(
11608 &mut self,
11609 _: &GoToDefinitionSplit,
11610 window: &mut Window,
11611 cx: &mut Context<Self>,
11612 ) -> Task<Result<Navigated>> {
11613 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11614 }
11615
11616 pub fn go_to_type_definition_split(
11617 &mut self,
11618 _: &GoToTypeDefinitionSplit,
11619 window: &mut Window,
11620 cx: &mut Context<Self>,
11621 ) -> Task<Result<Navigated>> {
11622 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11623 }
11624
11625 fn go_to_definition_of_kind(
11626 &mut self,
11627 kind: GotoDefinitionKind,
11628 split: bool,
11629 window: &mut Window,
11630 cx: &mut Context<Self>,
11631 ) -> Task<Result<Navigated>> {
11632 let Some(provider) = self.semantics_provider.clone() else {
11633 return Task::ready(Ok(Navigated::No));
11634 };
11635 let head = self.selections.newest::<usize>(cx).head();
11636 let buffer = self.buffer.read(cx);
11637 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11638 text_anchor
11639 } else {
11640 return Task::ready(Ok(Navigated::No));
11641 };
11642
11643 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11644 return Task::ready(Ok(Navigated::No));
11645 };
11646
11647 cx.spawn_in(window, |editor, mut cx| async move {
11648 let definitions = definitions.await?;
11649 let navigated = editor
11650 .update_in(&mut cx, |editor, window, cx| {
11651 editor.navigate_to_hover_links(
11652 Some(kind),
11653 definitions
11654 .into_iter()
11655 .filter(|location| {
11656 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11657 })
11658 .map(HoverLink::Text)
11659 .collect::<Vec<_>>(),
11660 split,
11661 window,
11662 cx,
11663 )
11664 })?
11665 .await?;
11666 anyhow::Ok(navigated)
11667 })
11668 }
11669
11670 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11671 let selection = self.selections.newest_anchor();
11672 let head = selection.head();
11673 let tail = selection.tail();
11674
11675 let Some((buffer, start_position)) =
11676 self.buffer.read(cx).text_anchor_for_position(head, cx)
11677 else {
11678 return;
11679 };
11680
11681 let end_position = if head != tail {
11682 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11683 return;
11684 };
11685 Some(pos)
11686 } else {
11687 None
11688 };
11689
11690 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11691 let url = if let Some(end_pos) = end_position {
11692 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11693 } else {
11694 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11695 };
11696
11697 if let Some(url) = url {
11698 editor.update(&mut cx, |_, cx| {
11699 cx.open_url(&url);
11700 })
11701 } else {
11702 Ok(())
11703 }
11704 });
11705
11706 url_finder.detach();
11707 }
11708
11709 pub fn open_selected_filename(
11710 &mut self,
11711 _: &OpenSelectedFilename,
11712 window: &mut Window,
11713 cx: &mut Context<Self>,
11714 ) {
11715 let Some(workspace) = self.workspace() else {
11716 return;
11717 };
11718
11719 let position = self.selections.newest_anchor().head();
11720
11721 let Some((buffer, buffer_position)) =
11722 self.buffer.read(cx).text_anchor_for_position(position, cx)
11723 else {
11724 return;
11725 };
11726
11727 let project = self.project.clone();
11728
11729 cx.spawn_in(window, |_, mut cx| async move {
11730 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11731
11732 if let Some((_, path)) = result {
11733 workspace
11734 .update_in(&mut cx, |workspace, window, cx| {
11735 workspace.open_resolved_path(path, window, cx)
11736 })?
11737 .await?;
11738 }
11739 anyhow::Ok(())
11740 })
11741 .detach();
11742 }
11743
11744 pub(crate) fn navigate_to_hover_links(
11745 &mut self,
11746 kind: Option<GotoDefinitionKind>,
11747 mut definitions: Vec<HoverLink>,
11748 split: bool,
11749 window: &mut Window,
11750 cx: &mut Context<Editor>,
11751 ) -> Task<Result<Navigated>> {
11752 // If there is one definition, just open it directly
11753 if definitions.len() == 1 {
11754 let definition = definitions.pop().unwrap();
11755
11756 enum TargetTaskResult {
11757 Location(Option<Location>),
11758 AlreadyNavigated,
11759 }
11760
11761 let target_task = match definition {
11762 HoverLink::Text(link) => {
11763 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11764 }
11765 HoverLink::InlayHint(lsp_location, server_id) => {
11766 let computation =
11767 self.compute_target_location(lsp_location, server_id, window, cx);
11768 cx.background_spawn(async move {
11769 let location = computation.await?;
11770 Ok(TargetTaskResult::Location(location))
11771 })
11772 }
11773 HoverLink::Url(url) => {
11774 cx.open_url(&url);
11775 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11776 }
11777 HoverLink::File(path) => {
11778 if let Some(workspace) = self.workspace() {
11779 cx.spawn_in(window, |_, mut cx| async move {
11780 workspace
11781 .update_in(&mut cx, |workspace, window, cx| {
11782 workspace.open_resolved_path(path, window, cx)
11783 })?
11784 .await
11785 .map(|_| TargetTaskResult::AlreadyNavigated)
11786 })
11787 } else {
11788 Task::ready(Ok(TargetTaskResult::Location(None)))
11789 }
11790 }
11791 };
11792 cx.spawn_in(window, |editor, mut cx| async move {
11793 let target = match target_task.await.context("target resolution task")? {
11794 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11795 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11796 TargetTaskResult::Location(Some(target)) => target,
11797 };
11798
11799 editor.update_in(&mut cx, |editor, window, cx| {
11800 let Some(workspace) = editor.workspace() else {
11801 return Navigated::No;
11802 };
11803 let pane = workspace.read(cx).active_pane().clone();
11804
11805 let range = target.range.to_point(target.buffer.read(cx));
11806 let range = editor.range_for_match(&range);
11807 let range = collapse_multiline_range(range);
11808
11809 if !split
11810 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11811 {
11812 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11813 } else {
11814 window.defer(cx, move |window, cx| {
11815 let target_editor: Entity<Self> =
11816 workspace.update(cx, |workspace, cx| {
11817 let pane = if split {
11818 workspace.adjacent_pane(window, cx)
11819 } else {
11820 workspace.active_pane().clone()
11821 };
11822
11823 workspace.open_project_item(
11824 pane,
11825 target.buffer.clone(),
11826 true,
11827 true,
11828 window,
11829 cx,
11830 )
11831 });
11832 target_editor.update(cx, |target_editor, cx| {
11833 // When selecting a definition in a different buffer, disable the nav history
11834 // to avoid creating a history entry at the previous cursor location.
11835 pane.update(cx, |pane, _| pane.disable_history());
11836 target_editor.go_to_singleton_buffer_range(range, window, cx);
11837 pane.update(cx, |pane, _| pane.enable_history());
11838 });
11839 });
11840 }
11841 Navigated::Yes
11842 })
11843 })
11844 } else if !definitions.is_empty() {
11845 cx.spawn_in(window, |editor, mut cx| async move {
11846 let (title, location_tasks, workspace) = editor
11847 .update_in(&mut cx, |editor, window, cx| {
11848 let tab_kind = match kind {
11849 Some(GotoDefinitionKind::Implementation) => "Implementations",
11850 _ => "Definitions",
11851 };
11852 let title = definitions
11853 .iter()
11854 .find_map(|definition| match definition {
11855 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11856 let buffer = origin.buffer.read(cx);
11857 format!(
11858 "{} for {}",
11859 tab_kind,
11860 buffer
11861 .text_for_range(origin.range.clone())
11862 .collect::<String>()
11863 )
11864 }),
11865 HoverLink::InlayHint(_, _) => None,
11866 HoverLink::Url(_) => None,
11867 HoverLink::File(_) => None,
11868 })
11869 .unwrap_or(tab_kind.to_string());
11870 let location_tasks = definitions
11871 .into_iter()
11872 .map(|definition| match definition {
11873 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11874 HoverLink::InlayHint(lsp_location, server_id) => editor
11875 .compute_target_location(lsp_location, server_id, window, cx),
11876 HoverLink::Url(_) => Task::ready(Ok(None)),
11877 HoverLink::File(_) => Task::ready(Ok(None)),
11878 })
11879 .collect::<Vec<_>>();
11880 (title, location_tasks, editor.workspace().clone())
11881 })
11882 .context("location tasks preparation")?;
11883
11884 let locations = future::join_all(location_tasks)
11885 .await
11886 .into_iter()
11887 .filter_map(|location| location.transpose())
11888 .collect::<Result<_>>()
11889 .context("location tasks")?;
11890
11891 let Some(workspace) = workspace else {
11892 return Ok(Navigated::No);
11893 };
11894 let opened = workspace
11895 .update_in(&mut cx, |workspace, window, cx| {
11896 Self::open_locations_in_multibuffer(
11897 workspace,
11898 locations,
11899 title,
11900 split,
11901 MultibufferSelectionMode::First,
11902 window,
11903 cx,
11904 )
11905 })
11906 .ok();
11907
11908 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11909 })
11910 } else {
11911 Task::ready(Ok(Navigated::No))
11912 }
11913 }
11914
11915 fn compute_target_location(
11916 &self,
11917 lsp_location: lsp::Location,
11918 server_id: LanguageServerId,
11919 window: &mut Window,
11920 cx: &mut Context<Self>,
11921 ) -> Task<anyhow::Result<Option<Location>>> {
11922 let Some(project) = self.project.clone() else {
11923 return Task::ready(Ok(None));
11924 };
11925
11926 cx.spawn_in(window, move |editor, mut cx| async move {
11927 let location_task = editor.update(&mut cx, |_, cx| {
11928 project.update(cx, |project, cx| {
11929 let language_server_name = project
11930 .language_server_statuses(cx)
11931 .find(|(id, _)| server_id == *id)
11932 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11933 language_server_name.map(|language_server_name| {
11934 project.open_local_buffer_via_lsp(
11935 lsp_location.uri.clone(),
11936 server_id,
11937 language_server_name,
11938 cx,
11939 )
11940 })
11941 })
11942 })?;
11943 let location = match location_task {
11944 Some(task) => Some({
11945 let target_buffer_handle = task.await.context("open local buffer")?;
11946 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11947 let target_start = target_buffer
11948 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11949 let target_end = target_buffer
11950 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11951 target_buffer.anchor_after(target_start)
11952 ..target_buffer.anchor_before(target_end)
11953 })?;
11954 Location {
11955 buffer: target_buffer_handle,
11956 range,
11957 }
11958 }),
11959 None => None,
11960 };
11961 Ok(location)
11962 })
11963 }
11964
11965 pub fn find_all_references(
11966 &mut self,
11967 _: &FindAllReferences,
11968 window: &mut Window,
11969 cx: &mut Context<Self>,
11970 ) -> Option<Task<Result<Navigated>>> {
11971 let selection = self.selections.newest::<usize>(cx);
11972 let multi_buffer = self.buffer.read(cx);
11973 let head = selection.head();
11974
11975 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11976 let head_anchor = multi_buffer_snapshot.anchor_at(
11977 head,
11978 if head < selection.tail() {
11979 Bias::Right
11980 } else {
11981 Bias::Left
11982 },
11983 );
11984
11985 match self
11986 .find_all_references_task_sources
11987 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11988 {
11989 Ok(_) => {
11990 log::info!(
11991 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11992 );
11993 return None;
11994 }
11995 Err(i) => {
11996 self.find_all_references_task_sources.insert(i, head_anchor);
11997 }
11998 }
11999
12000 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12001 let workspace = self.workspace()?;
12002 let project = workspace.read(cx).project().clone();
12003 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12004 Some(cx.spawn_in(window, |editor, mut cx| async move {
12005 let _cleanup = defer({
12006 let mut cx = cx.clone();
12007 move || {
12008 let _ = editor.update(&mut cx, |editor, _| {
12009 if let Ok(i) =
12010 editor
12011 .find_all_references_task_sources
12012 .binary_search_by(|anchor| {
12013 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12014 })
12015 {
12016 editor.find_all_references_task_sources.remove(i);
12017 }
12018 });
12019 }
12020 });
12021
12022 let locations = references.await?;
12023 if locations.is_empty() {
12024 return anyhow::Ok(Navigated::No);
12025 }
12026
12027 workspace.update_in(&mut cx, |workspace, window, cx| {
12028 let title = locations
12029 .first()
12030 .as_ref()
12031 .map(|location| {
12032 let buffer = location.buffer.read(cx);
12033 format!(
12034 "References to `{}`",
12035 buffer
12036 .text_for_range(location.range.clone())
12037 .collect::<String>()
12038 )
12039 })
12040 .unwrap();
12041 Self::open_locations_in_multibuffer(
12042 workspace,
12043 locations,
12044 title,
12045 false,
12046 MultibufferSelectionMode::First,
12047 window,
12048 cx,
12049 );
12050 Navigated::Yes
12051 })
12052 }))
12053 }
12054
12055 /// Opens a multibuffer with the given project locations in it
12056 pub fn open_locations_in_multibuffer(
12057 workspace: &mut Workspace,
12058 mut locations: Vec<Location>,
12059 title: String,
12060 split: bool,
12061 multibuffer_selection_mode: MultibufferSelectionMode,
12062 window: &mut Window,
12063 cx: &mut Context<Workspace>,
12064 ) {
12065 // If there are multiple definitions, open them in a multibuffer
12066 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12067 let mut locations = locations.into_iter().peekable();
12068 let mut ranges = Vec::new();
12069 let capability = workspace.project().read(cx).capability();
12070
12071 let excerpt_buffer = cx.new(|cx| {
12072 let mut multibuffer = MultiBuffer::new(capability);
12073 while let Some(location) = locations.next() {
12074 let buffer = location.buffer.read(cx);
12075 let mut ranges_for_buffer = Vec::new();
12076 let range = location.range.to_offset(buffer);
12077 ranges_for_buffer.push(range.clone());
12078
12079 while let Some(next_location) = locations.peek() {
12080 if next_location.buffer == location.buffer {
12081 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12082 locations.next();
12083 } else {
12084 break;
12085 }
12086 }
12087
12088 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12089 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12090 location.buffer.clone(),
12091 ranges_for_buffer,
12092 DEFAULT_MULTIBUFFER_CONTEXT,
12093 cx,
12094 ))
12095 }
12096
12097 multibuffer.with_title(title)
12098 });
12099
12100 let editor = cx.new(|cx| {
12101 Editor::for_multibuffer(
12102 excerpt_buffer,
12103 Some(workspace.project().clone()),
12104 true,
12105 window,
12106 cx,
12107 )
12108 });
12109 editor.update(cx, |editor, cx| {
12110 match multibuffer_selection_mode {
12111 MultibufferSelectionMode::First => {
12112 if let Some(first_range) = ranges.first() {
12113 editor.change_selections(None, window, cx, |selections| {
12114 selections.clear_disjoint();
12115 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12116 });
12117 }
12118 editor.highlight_background::<Self>(
12119 &ranges,
12120 |theme| theme.editor_highlighted_line_background,
12121 cx,
12122 );
12123 }
12124 MultibufferSelectionMode::All => {
12125 editor.change_selections(None, window, cx, |selections| {
12126 selections.clear_disjoint();
12127 selections.select_anchor_ranges(ranges);
12128 });
12129 }
12130 }
12131 editor.register_buffers_with_language_servers(cx);
12132 });
12133
12134 let item = Box::new(editor);
12135 let item_id = item.item_id();
12136
12137 if split {
12138 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12139 } else {
12140 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12141 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12142 pane.close_current_preview_item(window, cx)
12143 } else {
12144 None
12145 }
12146 });
12147 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12148 }
12149 workspace.active_pane().update(cx, |pane, cx| {
12150 pane.set_preview_item_id(Some(item_id), cx);
12151 });
12152 }
12153
12154 pub fn rename(
12155 &mut self,
12156 _: &Rename,
12157 window: &mut Window,
12158 cx: &mut Context<Self>,
12159 ) -> Option<Task<Result<()>>> {
12160 use language::ToOffset as _;
12161
12162 let provider = self.semantics_provider.clone()?;
12163 let selection = self.selections.newest_anchor().clone();
12164 let (cursor_buffer, cursor_buffer_position) = self
12165 .buffer
12166 .read(cx)
12167 .text_anchor_for_position(selection.head(), cx)?;
12168 let (tail_buffer, cursor_buffer_position_end) = self
12169 .buffer
12170 .read(cx)
12171 .text_anchor_for_position(selection.tail(), cx)?;
12172 if tail_buffer != cursor_buffer {
12173 return None;
12174 }
12175
12176 let snapshot = cursor_buffer.read(cx).snapshot();
12177 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12178 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12179 let prepare_rename = provider
12180 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12181 .unwrap_or_else(|| Task::ready(Ok(None)));
12182 drop(snapshot);
12183
12184 Some(cx.spawn_in(window, |this, mut cx| async move {
12185 let rename_range = if let Some(range) = prepare_rename.await? {
12186 Some(range)
12187 } else {
12188 this.update(&mut cx, |this, cx| {
12189 let buffer = this.buffer.read(cx).snapshot(cx);
12190 let mut buffer_highlights = this
12191 .document_highlights_for_position(selection.head(), &buffer)
12192 .filter(|highlight| {
12193 highlight.start.excerpt_id == selection.head().excerpt_id
12194 && highlight.end.excerpt_id == selection.head().excerpt_id
12195 });
12196 buffer_highlights
12197 .next()
12198 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12199 })?
12200 };
12201 if let Some(rename_range) = rename_range {
12202 this.update_in(&mut cx, |this, window, cx| {
12203 let snapshot = cursor_buffer.read(cx).snapshot();
12204 let rename_buffer_range = rename_range.to_offset(&snapshot);
12205 let cursor_offset_in_rename_range =
12206 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12207 let cursor_offset_in_rename_range_end =
12208 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12209
12210 this.take_rename(false, window, cx);
12211 let buffer = this.buffer.read(cx).read(cx);
12212 let cursor_offset = selection.head().to_offset(&buffer);
12213 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12214 let rename_end = rename_start + rename_buffer_range.len();
12215 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12216 let mut old_highlight_id = None;
12217 let old_name: Arc<str> = buffer
12218 .chunks(rename_start..rename_end, true)
12219 .map(|chunk| {
12220 if old_highlight_id.is_none() {
12221 old_highlight_id = chunk.syntax_highlight_id;
12222 }
12223 chunk.text
12224 })
12225 .collect::<String>()
12226 .into();
12227
12228 drop(buffer);
12229
12230 // Position the selection in the rename editor so that it matches the current selection.
12231 this.show_local_selections = false;
12232 let rename_editor = cx.new(|cx| {
12233 let mut editor = Editor::single_line(window, cx);
12234 editor.buffer.update(cx, |buffer, cx| {
12235 buffer.edit([(0..0, old_name.clone())], None, cx)
12236 });
12237 let rename_selection_range = match cursor_offset_in_rename_range
12238 .cmp(&cursor_offset_in_rename_range_end)
12239 {
12240 Ordering::Equal => {
12241 editor.select_all(&SelectAll, window, cx);
12242 return editor;
12243 }
12244 Ordering::Less => {
12245 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12246 }
12247 Ordering::Greater => {
12248 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12249 }
12250 };
12251 if rename_selection_range.end > old_name.len() {
12252 editor.select_all(&SelectAll, window, cx);
12253 } else {
12254 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12255 s.select_ranges([rename_selection_range]);
12256 });
12257 }
12258 editor
12259 });
12260 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12261 if e == &EditorEvent::Focused {
12262 cx.emit(EditorEvent::FocusedIn)
12263 }
12264 })
12265 .detach();
12266
12267 let write_highlights =
12268 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12269 let read_highlights =
12270 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12271 let ranges = write_highlights
12272 .iter()
12273 .flat_map(|(_, ranges)| ranges.iter())
12274 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12275 .cloned()
12276 .collect();
12277
12278 this.highlight_text::<Rename>(
12279 ranges,
12280 HighlightStyle {
12281 fade_out: Some(0.6),
12282 ..Default::default()
12283 },
12284 cx,
12285 );
12286 let rename_focus_handle = rename_editor.focus_handle(cx);
12287 window.focus(&rename_focus_handle);
12288 let block_id = this.insert_blocks(
12289 [BlockProperties {
12290 style: BlockStyle::Flex,
12291 placement: BlockPlacement::Below(range.start),
12292 height: 1,
12293 render: Arc::new({
12294 let rename_editor = rename_editor.clone();
12295 move |cx: &mut BlockContext| {
12296 let mut text_style = cx.editor_style.text.clone();
12297 if let Some(highlight_style) = old_highlight_id
12298 .and_then(|h| h.style(&cx.editor_style.syntax))
12299 {
12300 text_style = text_style.highlight(highlight_style);
12301 }
12302 div()
12303 .block_mouse_down()
12304 .pl(cx.anchor_x)
12305 .child(EditorElement::new(
12306 &rename_editor,
12307 EditorStyle {
12308 background: cx.theme().system().transparent,
12309 local_player: cx.editor_style.local_player,
12310 text: text_style,
12311 scrollbar_width: cx.editor_style.scrollbar_width,
12312 syntax: cx.editor_style.syntax.clone(),
12313 status: cx.editor_style.status.clone(),
12314 inlay_hints_style: HighlightStyle {
12315 font_weight: Some(FontWeight::BOLD),
12316 ..make_inlay_hints_style(cx.app)
12317 },
12318 inline_completion_styles: make_suggestion_styles(
12319 cx.app,
12320 ),
12321 ..EditorStyle::default()
12322 },
12323 ))
12324 .into_any_element()
12325 }
12326 }),
12327 priority: 0,
12328 }],
12329 Some(Autoscroll::fit()),
12330 cx,
12331 )[0];
12332 this.pending_rename = Some(RenameState {
12333 range,
12334 old_name,
12335 editor: rename_editor,
12336 block_id,
12337 });
12338 })?;
12339 }
12340
12341 Ok(())
12342 }))
12343 }
12344
12345 pub fn confirm_rename(
12346 &mut self,
12347 _: &ConfirmRename,
12348 window: &mut Window,
12349 cx: &mut Context<Self>,
12350 ) -> Option<Task<Result<()>>> {
12351 let rename = self.take_rename(false, window, cx)?;
12352 let workspace = self.workspace()?.downgrade();
12353 let (buffer, start) = self
12354 .buffer
12355 .read(cx)
12356 .text_anchor_for_position(rename.range.start, cx)?;
12357 let (end_buffer, _) = self
12358 .buffer
12359 .read(cx)
12360 .text_anchor_for_position(rename.range.end, cx)?;
12361 if buffer != end_buffer {
12362 return None;
12363 }
12364
12365 let old_name = rename.old_name;
12366 let new_name = rename.editor.read(cx).text(cx);
12367
12368 let rename = self.semantics_provider.as_ref()?.perform_rename(
12369 &buffer,
12370 start,
12371 new_name.clone(),
12372 cx,
12373 )?;
12374
12375 Some(cx.spawn_in(window, |editor, mut cx| async move {
12376 let project_transaction = rename.await?;
12377 Self::open_project_transaction(
12378 &editor,
12379 workspace,
12380 project_transaction,
12381 format!("Rename: {} → {}", old_name, new_name),
12382 cx.clone(),
12383 )
12384 .await?;
12385
12386 editor.update(&mut cx, |editor, cx| {
12387 editor.refresh_document_highlights(cx);
12388 })?;
12389 Ok(())
12390 }))
12391 }
12392
12393 fn take_rename(
12394 &mut self,
12395 moving_cursor: bool,
12396 window: &mut Window,
12397 cx: &mut Context<Self>,
12398 ) -> Option<RenameState> {
12399 let rename = self.pending_rename.take()?;
12400 if rename.editor.focus_handle(cx).is_focused(window) {
12401 window.focus(&self.focus_handle);
12402 }
12403
12404 self.remove_blocks(
12405 [rename.block_id].into_iter().collect(),
12406 Some(Autoscroll::fit()),
12407 cx,
12408 );
12409 self.clear_highlights::<Rename>(cx);
12410 self.show_local_selections = true;
12411
12412 if moving_cursor {
12413 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12414 editor.selections.newest::<usize>(cx).head()
12415 });
12416
12417 // Update the selection to match the position of the selection inside
12418 // the rename editor.
12419 let snapshot = self.buffer.read(cx).read(cx);
12420 let rename_range = rename.range.to_offset(&snapshot);
12421 let cursor_in_editor = snapshot
12422 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12423 .min(rename_range.end);
12424 drop(snapshot);
12425
12426 self.change_selections(None, window, cx, |s| {
12427 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12428 });
12429 } else {
12430 self.refresh_document_highlights(cx);
12431 }
12432
12433 Some(rename)
12434 }
12435
12436 pub fn pending_rename(&self) -> Option<&RenameState> {
12437 self.pending_rename.as_ref()
12438 }
12439
12440 fn format(
12441 &mut self,
12442 _: &Format,
12443 window: &mut Window,
12444 cx: &mut Context<Self>,
12445 ) -> Option<Task<Result<()>>> {
12446 let project = match &self.project {
12447 Some(project) => project.clone(),
12448 None => return None,
12449 };
12450
12451 Some(self.perform_format(
12452 project,
12453 FormatTrigger::Manual,
12454 FormatTarget::Buffers,
12455 window,
12456 cx,
12457 ))
12458 }
12459
12460 fn format_selections(
12461 &mut self,
12462 _: &FormatSelections,
12463 window: &mut Window,
12464 cx: &mut Context<Self>,
12465 ) -> Option<Task<Result<()>>> {
12466 let project = match &self.project {
12467 Some(project) => project.clone(),
12468 None => return None,
12469 };
12470
12471 let ranges = self
12472 .selections
12473 .all_adjusted(cx)
12474 .into_iter()
12475 .map(|selection| selection.range())
12476 .collect_vec();
12477
12478 Some(self.perform_format(
12479 project,
12480 FormatTrigger::Manual,
12481 FormatTarget::Ranges(ranges),
12482 window,
12483 cx,
12484 ))
12485 }
12486
12487 fn perform_format(
12488 &mut self,
12489 project: Entity<Project>,
12490 trigger: FormatTrigger,
12491 target: FormatTarget,
12492 window: &mut Window,
12493 cx: &mut Context<Self>,
12494 ) -> Task<Result<()>> {
12495 let buffer = self.buffer.clone();
12496 let (buffers, target) = match target {
12497 FormatTarget::Buffers => {
12498 let mut buffers = buffer.read(cx).all_buffers();
12499 if trigger == FormatTrigger::Save {
12500 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12501 }
12502 (buffers, LspFormatTarget::Buffers)
12503 }
12504 FormatTarget::Ranges(selection_ranges) => {
12505 let multi_buffer = buffer.read(cx);
12506 let snapshot = multi_buffer.read(cx);
12507 let mut buffers = HashSet::default();
12508 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12509 BTreeMap::new();
12510 for selection_range in selection_ranges {
12511 for (buffer, buffer_range, _) in
12512 snapshot.range_to_buffer_ranges(selection_range)
12513 {
12514 let buffer_id = buffer.remote_id();
12515 let start = buffer.anchor_before(buffer_range.start);
12516 let end = buffer.anchor_after(buffer_range.end);
12517 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12518 buffer_id_to_ranges
12519 .entry(buffer_id)
12520 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12521 .or_insert_with(|| vec![start..end]);
12522 }
12523 }
12524 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12525 }
12526 };
12527
12528 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12529 let format = project.update(cx, |project, cx| {
12530 project.format(buffers, target, true, trigger, cx)
12531 });
12532
12533 cx.spawn_in(window, |_, mut cx| async move {
12534 let transaction = futures::select_biased! {
12535 () = timeout => {
12536 log::warn!("timed out waiting for formatting");
12537 None
12538 }
12539 transaction = format.log_err().fuse() => transaction,
12540 };
12541
12542 buffer
12543 .update(&mut cx, |buffer, cx| {
12544 if let Some(transaction) = transaction {
12545 if !buffer.is_singleton() {
12546 buffer.push_transaction(&transaction.0, cx);
12547 }
12548 }
12549 cx.notify();
12550 })
12551 .ok();
12552
12553 Ok(())
12554 })
12555 }
12556
12557 fn organize_imports(
12558 &mut self,
12559 _: &OrganizeImports,
12560 window: &mut Window,
12561 cx: &mut Context<Self>,
12562 ) -> Option<Task<Result<()>>> {
12563 let project = match &self.project {
12564 Some(project) => project.clone(),
12565 None => return None,
12566 };
12567 Some(self.perform_code_action_kind(
12568 project,
12569 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12570 window,
12571 cx,
12572 ))
12573 }
12574
12575 fn perform_code_action_kind(
12576 &mut self,
12577 project: Entity<Project>,
12578 kind: CodeActionKind,
12579 window: &mut Window,
12580 cx: &mut Context<Self>,
12581 ) -> Task<Result<()>> {
12582 let buffer = self.buffer.clone();
12583 let buffers = buffer.read(cx).all_buffers();
12584 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12585 let apply_action = project.update(cx, |project, cx| {
12586 project.apply_code_action_kind(buffers, kind, true, cx)
12587 });
12588 cx.spawn_in(window, |_, mut cx| async move {
12589 let transaction = futures::select_biased! {
12590 () = timeout => {
12591 log::warn!("timed out waiting for executing code action");
12592 None
12593 }
12594 transaction = apply_action.log_err().fuse() => transaction,
12595 };
12596 buffer
12597 .update(&mut cx, |buffer, cx| {
12598 // check if we need this
12599 if let Some(transaction) = transaction {
12600 if !buffer.is_singleton() {
12601 buffer.push_transaction(&transaction.0, cx);
12602 }
12603 }
12604 cx.notify();
12605 })
12606 .ok();
12607 Ok(())
12608 })
12609 }
12610
12611 fn restart_language_server(
12612 &mut self,
12613 _: &RestartLanguageServer,
12614 _: &mut Window,
12615 cx: &mut Context<Self>,
12616 ) {
12617 if let Some(project) = self.project.clone() {
12618 self.buffer.update(cx, |multi_buffer, cx| {
12619 project.update(cx, |project, cx| {
12620 project.restart_language_servers_for_buffers(
12621 multi_buffer.all_buffers().into_iter().collect(),
12622 cx,
12623 );
12624 });
12625 })
12626 }
12627 }
12628
12629 fn cancel_language_server_work(
12630 workspace: &mut Workspace,
12631 _: &actions::CancelLanguageServerWork,
12632 _: &mut Window,
12633 cx: &mut Context<Workspace>,
12634 ) {
12635 let project = workspace.project();
12636 let buffers = workspace
12637 .active_item(cx)
12638 .and_then(|item| item.act_as::<Editor>(cx))
12639 .map_or(HashSet::default(), |editor| {
12640 editor.read(cx).buffer.read(cx).all_buffers()
12641 });
12642 project.update(cx, |project, cx| {
12643 project.cancel_language_server_work_for_buffers(buffers, cx);
12644 });
12645 }
12646
12647 fn show_character_palette(
12648 &mut self,
12649 _: &ShowCharacterPalette,
12650 window: &mut Window,
12651 _: &mut Context<Self>,
12652 ) {
12653 window.show_character_palette();
12654 }
12655
12656 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12657 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12658 let buffer = self.buffer.read(cx).snapshot(cx);
12659 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12660 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12661 let is_valid = buffer
12662 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12663 .any(|entry| {
12664 entry.diagnostic.is_primary
12665 && !entry.range.is_empty()
12666 && entry.range.start == primary_range_start
12667 && entry.diagnostic.message == active_diagnostics.primary_message
12668 });
12669
12670 if is_valid != active_diagnostics.is_valid {
12671 active_diagnostics.is_valid = is_valid;
12672 if is_valid {
12673 let mut new_styles = HashMap::default();
12674 for (block_id, diagnostic) in &active_diagnostics.blocks {
12675 new_styles.insert(
12676 *block_id,
12677 diagnostic_block_renderer(diagnostic.clone(), None, true),
12678 );
12679 }
12680 self.display_map.update(cx, |display_map, _cx| {
12681 display_map.replace_blocks(new_styles);
12682 });
12683 } else {
12684 self.dismiss_diagnostics(cx);
12685 }
12686 }
12687 }
12688 }
12689
12690 fn activate_diagnostics(
12691 &mut self,
12692 buffer_id: BufferId,
12693 group_id: usize,
12694 window: &mut Window,
12695 cx: &mut Context<Self>,
12696 ) {
12697 self.dismiss_diagnostics(cx);
12698 let snapshot = self.snapshot(window, cx);
12699 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12700 let buffer = self.buffer.read(cx).snapshot(cx);
12701
12702 let mut primary_range = None;
12703 let mut primary_message = None;
12704 let diagnostic_group = buffer
12705 .diagnostic_group(buffer_id, group_id)
12706 .filter_map(|entry| {
12707 let start = entry.range.start;
12708 let end = entry.range.end;
12709 if snapshot.is_line_folded(MultiBufferRow(start.row))
12710 && (start.row == end.row
12711 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12712 {
12713 return None;
12714 }
12715 if entry.diagnostic.is_primary {
12716 primary_range = Some(entry.range.clone());
12717 primary_message = Some(entry.diagnostic.message.clone());
12718 }
12719 Some(entry)
12720 })
12721 .collect::<Vec<_>>();
12722 let primary_range = primary_range?;
12723 let primary_message = primary_message?;
12724
12725 let blocks = display_map
12726 .insert_blocks(
12727 diagnostic_group.iter().map(|entry| {
12728 let diagnostic = entry.diagnostic.clone();
12729 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12730 BlockProperties {
12731 style: BlockStyle::Fixed,
12732 placement: BlockPlacement::Below(
12733 buffer.anchor_after(entry.range.start),
12734 ),
12735 height: message_height,
12736 render: diagnostic_block_renderer(diagnostic, None, true),
12737 priority: 0,
12738 }
12739 }),
12740 cx,
12741 )
12742 .into_iter()
12743 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12744 .collect();
12745
12746 Some(ActiveDiagnosticGroup {
12747 primary_range: buffer.anchor_before(primary_range.start)
12748 ..buffer.anchor_after(primary_range.end),
12749 primary_message,
12750 group_id,
12751 blocks,
12752 is_valid: true,
12753 })
12754 });
12755 }
12756
12757 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12758 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12759 self.display_map.update(cx, |display_map, cx| {
12760 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12761 });
12762 cx.notify();
12763 }
12764 }
12765
12766 /// Disable inline diagnostics rendering for this editor.
12767 pub fn disable_inline_diagnostics(&mut self) {
12768 self.inline_diagnostics_enabled = false;
12769 self.inline_diagnostics_update = Task::ready(());
12770 self.inline_diagnostics.clear();
12771 }
12772
12773 pub fn inline_diagnostics_enabled(&self) -> bool {
12774 self.inline_diagnostics_enabled
12775 }
12776
12777 pub fn show_inline_diagnostics(&self) -> bool {
12778 self.show_inline_diagnostics
12779 }
12780
12781 pub fn toggle_inline_diagnostics(
12782 &mut self,
12783 _: &ToggleInlineDiagnostics,
12784 window: &mut Window,
12785 cx: &mut Context<'_, Editor>,
12786 ) {
12787 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12788 self.refresh_inline_diagnostics(false, window, cx);
12789 }
12790
12791 fn refresh_inline_diagnostics(
12792 &mut self,
12793 debounce: bool,
12794 window: &mut Window,
12795 cx: &mut Context<Self>,
12796 ) {
12797 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12798 self.inline_diagnostics_update = Task::ready(());
12799 self.inline_diagnostics.clear();
12800 return;
12801 }
12802
12803 let debounce_ms = ProjectSettings::get_global(cx)
12804 .diagnostics
12805 .inline
12806 .update_debounce_ms;
12807 let debounce = if debounce && debounce_ms > 0 {
12808 Some(Duration::from_millis(debounce_ms))
12809 } else {
12810 None
12811 };
12812 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12813 if let Some(debounce) = debounce {
12814 cx.background_executor().timer(debounce).await;
12815 }
12816 let Some(snapshot) = editor
12817 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12818 .ok()
12819 else {
12820 return;
12821 };
12822
12823 let new_inline_diagnostics = cx
12824 .background_spawn(async move {
12825 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12826 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12827 let message = diagnostic_entry
12828 .diagnostic
12829 .message
12830 .split_once('\n')
12831 .map(|(line, _)| line)
12832 .map(SharedString::new)
12833 .unwrap_or_else(|| {
12834 SharedString::from(diagnostic_entry.diagnostic.message)
12835 });
12836 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12837 let (Ok(i) | Err(i)) = inline_diagnostics
12838 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12839 inline_diagnostics.insert(
12840 i,
12841 (
12842 start_anchor,
12843 InlineDiagnostic {
12844 message,
12845 group_id: diagnostic_entry.diagnostic.group_id,
12846 start: diagnostic_entry.range.start.to_point(&snapshot),
12847 is_primary: diagnostic_entry.diagnostic.is_primary,
12848 severity: diagnostic_entry.diagnostic.severity,
12849 },
12850 ),
12851 );
12852 }
12853 inline_diagnostics
12854 })
12855 .await;
12856
12857 editor
12858 .update(&mut cx, |editor, cx| {
12859 editor.inline_diagnostics = new_inline_diagnostics;
12860 cx.notify();
12861 })
12862 .ok();
12863 });
12864 }
12865
12866 pub fn set_selections_from_remote(
12867 &mut self,
12868 selections: Vec<Selection<Anchor>>,
12869 pending_selection: Option<Selection<Anchor>>,
12870 window: &mut Window,
12871 cx: &mut Context<Self>,
12872 ) {
12873 let old_cursor_position = self.selections.newest_anchor().head();
12874 self.selections.change_with(cx, |s| {
12875 s.select_anchors(selections);
12876 if let Some(pending_selection) = pending_selection {
12877 s.set_pending(pending_selection, SelectMode::Character);
12878 } else {
12879 s.clear_pending();
12880 }
12881 });
12882 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12883 }
12884
12885 fn push_to_selection_history(&mut self) {
12886 self.selection_history.push(SelectionHistoryEntry {
12887 selections: self.selections.disjoint_anchors(),
12888 select_next_state: self.select_next_state.clone(),
12889 select_prev_state: self.select_prev_state.clone(),
12890 add_selections_state: self.add_selections_state.clone(),
12891 });
12892 }
12893
12894 pub fn transact(
12895 &mut self,
12896 window: &mut Window,
12897 cx: &mut Context<Self>,
12898 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12899 ) -> Option<TransactionId> {
12900 self.start_transaction_at(Instant::now(), window, cx);
12901 update(self, window, cx);
12902 self.end_transaction_at(Instant::now(), cx)
12903 }
12904
12905 pub fn start_transaction_at(
12906 &mut self,
12907 now: Instant,
12908 window: &mut Window,
12909 cx: &mut Context<Self>,
12910 ) {
12911 self.end_selection(window, cx);
12912 if let Some(tx_id) = self
12913 .buffer
12914 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12915 {
12916 self.selection_history
12917 .insert_transaction(tx_id, self.selections.disjoint_anchors());
12918 cx.emit(EditorEvent::TransactionBegun {
12919 transaction_id: tx_id,
12920 })
12921 }
12922 }
12923
12924 pub fn end_transaction_at(
12925 &mut self,
12926 now: Instant,
12927 cx: &mut Context<Self>,
12928 ) -> Option<TransactionId> {
12929 if let Some(transaction_id) = self
12930 .buffer
12931 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12932 {
12933 if let Some((_, end_selections)) =
12934 self.selection_history.transaction_mut(transaction_id)
12935 {
12936 *end_selections = Some(self.selections.disjoint_anchors());
12937 } else {
12938 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12939 }
12940
12941 cx.emit(EditorEvent::Edited { transaction_id });
12942 Some(transaction_id)
12943 } else {
12944 None
12945 }
12946 }
12947
12948 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12949 if self.selection_mark_mode {
12950 self.change_selections(None, window, cx, |s| {
12951 s.move_with(|_, sel| {
12952 sel.collapse_to(sel.head(), SelectionGoal::None);
12953 });
12954 })
12955 }
12956 self.selection_mark_mode = true;
12957 cx.notify();
12958 }
12959
12960 pub fn swap_selection_ends(
12961 &mut self,
12962 _: &actions::SwapSelectionEnds,
12963 window: &mut Window,
12964 cx: &mut Context<Self>,
12965 ) {
12966 self.change_selections(None, window, cx, |s| {
12967 s.move_with(|_, sel| {
12968 if sel.start != sel.end {
12969 sel.reversed = !sel.reversed
12970 }
12971 });
12972 });
12973 self.request_autoscroll(Autoscroll::newest(), cx);
12974 cx.notify();
12975 }
12976
12977 pub fn toggle_fold(
12978 &mut self,
12979 _: &actions::ToggleFold,
12980 window: &mut Window,
12981 cx: &mut Context<Self>,
12982 ) {
12983 if self.is_singleton(cx) {
12984 let selection = self.selections.newest::<Point>(cx);
12985
12986 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12987 let range = if selection.is_empty() {
12988 let point = selection.head().to_display_point(&display_map);
12989 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12990 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12991 .to_point(&display_map);
12992 start..end
12993 } else {
12994 selection.range()
12995 };
12996 if display_map.folds_in_range(range).next().is_some() {
12997 self.unfold_lines(&Default::default(), window, cx)
12998 } else {
12999 self.fold(&Default::default(), window, cx)
13000 }
13001 } else {
13002 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13003 let buffer_ids: HashSet<_> = self
13004 .selections
13005 .disjoint_anchor_ranges()
13006 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13007 .collect();
13008
13009 let should_unfold = buffer_ids
13010 .iter()
13011 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13012
13013 for buffer_id in buffer_ids {
13014 if should_unfold {
13015 self.unfold_buffer(buffer_id, cx);
13016 } else {
13017 self.fold_buffer(buffer_id, cx);
13018 }
13019 }
13020 }
13021 }
13022
13023 pub fn toggle_fold_recursive(
13024 &mut self,
13025 _: &actions::ToggleFoldRecursive,
13026 window: &mut Window,
13027 cx: &mut Context<Self>,
13028 ) {
13029 let selection = self.selections.newest::<Point>(cx);
13030
13031 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13032 let range = if selection.is_empty() {
13033 let point = selection.head().to_display_point(&display_map);
13034 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13035 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13036 .to_point(&display_map);
13037 start..end
13038 } else {
13039 selection.range()
13040 };
13041 if display_map.folds_in_range(range).next().is_some() {
13042 self.unfold_recursive(&Default::default(), window, cx)
13043 } else {
13044 self.fold_recursive(&Default::default(), window, cx)
13045 }
13046 }
13047
13048 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13049 if self.is_singleton(cx) {
13050 let mut to_fold = Vec::new();
13051 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13052 let selections = self.selections.all_adjusted(cx);
13053
13054 for selection in selections {
13055 let range = selection.range().sorted();
13056 let buffer_start_row = range.start.row;
13057
13058 if range.start.row != range.end.row {
13059 let mut found = false;
13060 let mut row = range.start.row;
13061 while row <= range.end.row {
13062 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13063 {
13064 found = true;
13065 row = crease.range().end.row + 1;
13066 to_fold.push(crease);
13067 } else {
13068 row += 1
13069 }
13070 }
13071 if found {
13072 continue;
13073 }
13074 }
13075
13076 for row in (0..=range.start.row).rev() {
13077 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13078 if crease.range().end.row >= buffer_start_row {
13079 to_fold.push(crease);
13080 if row <= range.start.row {
13081 break;
13082 }
13083 }
13084 }
13085 }
13086 }
13087
13088 self.fold_creases(to_fold, true, window, cx);
13089 } else {
13090 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13091 let buffer_ids = self
13092 .selections
13093 .disjoint_anchor_ranges()
13094 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13095 .collect::<HashSet<_>>();
13096 for buffer_id in buffer_ids {
13097 self.fold_buffer(buffer_id, cx);
13098 }
13099 }
13100 }
13101
13102 fn fold_at_level(
13103 &mut self,
13104 fold_at: &FoldAtLevel,
13105 window: &mut Window,
13106 cx: &mut Context<Self>,
13107 ) {
13108 if !self.buffer.read(cx).is_singleton() {
13109 return;
13110 }
13111
13112 let fold_at_level = fold_at.0;
13113 let snapshot = self.buffer.read(cx).snapshot(cx);
13114 let mut to_fold = Vec::new();
13115 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13116
13117 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13118 while start_row < end_row {
13119 match self
13120 .snapshot(window, cx)
13121 .crease_for_buffer_row(MultiBufferRow(start_row))
13122 {
13123 Some(crease) => {
13124 let nested_start_row = crease.range().start.row + 1;
13125 let nested_end_row = crease.range().end.row;
13126
13127 if current_level < fold_at_level {
13128 stack.push((nested_start_row, nested_end_row, current_level + 1));
13129 } else if current_level == fold_at_level {
13130 to_fold.push(crease);
13131 }
13132
13133 start_row = nested_end_row + 1;
13134 }
13135 None => start_row += 1,
13136 }
13137 }
13138 }
13139
13140 self.fold_creases(to_fold, true, window, cx);
13141 }
13142
13143 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13144 if self.buffer.read(cx).is_singleton() {
13145 let mut fold_ranges = Vec::new();
13146 let snapshot = self.buffer.read(cx).snapshot(cx);
13147
13148 for row in 0..snapshot.max_row().0 {
13149 if let Some(foldable_range) = self
13150 .snapshot(window, cx)
13151 .crease_for_buffer_row(MultiBufferRow(row))
13152 {
13153 fold_ranges.push(foldable_range);
13154 }
13155 }
13156
13157 self.fold_creases(fold_ranges, true, window, cx);
13158 } else {
13159 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13160 editor
13161 .update_in(&mut cx, |editor, _, cx| {
13162 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13163 editor.fold_buffer(buffer_id, cx);
13164 }
13165 })
13166 .ok();
13167 });
13168 }
13169 }
13170
13171 pub fn fold_function_bodies(
13172 &mut self,
13173 _: &actions::FoldFunctionBodies,
13174 window: &mut Window,
13175 cx: &mut Context<Self>,
13176 ) {
13177 let snapshot = self.buffer.read(cx).snapshot(cx);
13178
13179 let ranges = snapshot
13180 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13181 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13182 .collect::<Vec<_>>();
13183
13184 let creases = ranges
13185 .into_iter()
13186 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13187 .collect();
13188
13189 self.fold_creases(creases, true, window, cx);
13190 }
13191
13192 pub fn fold_recursive(
13193 &mut self,
13194 _: &actions::FoldRecursive,
13195 window: &mut Window,
13196 cx: &mut Context<Self>,
13197 ) {
13198 let mut to_fold = Vec::new();
13199 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13200 let selections = self.selections.all_adjusted(cx);
13201
13202 for selection in selections {
13203 let range = selection.range().sorted();
13204 let buffer_start_row = range.start.row;
13205
13206 if range.start.row != range.end.row {
13207 let mut found = false;
13208 for row in range.start.row..=range.end.row {
13209 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13210 found = true;
13211 to_fold.push(crease);
13212 }
13213 }
13214 if found {
13215 continue;
13216 }
13217 }
13218
13219 for row in (0..=range.start.row).rev() {
13220 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13221 if crease.range().end.row >= buffer_start_row {
13222 to_fold.push(crease);
13223 } else {
13224 break;
13225 }
13226 }
13227 }
13228 }
13229
13230 self.fold_creases(to_fold, true, window, cx);
13231 }
13232
13233 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13234 let buffer_row = fold_at.buffer_row;
13235 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13236
13237 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13238 let autoscroll = self
13239 .selections
13240 .all::<Point>(cx)
13241 .iter()
13242 .any(|selection| crease.range().overlaps(&selection.range()));
13243
13244 self.fold_creases(vec![crease], autoscroll, window, cx);
13245 }
13246 }
13247
13248 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13249 if self.is_singleton(cx) {
13250 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13251 let buffer = &display_map.buffer_snapshot;
13252 let selections = self.selections.all::<Point>(cx);
13253 let ranges = selections
13254 .iter()
13255 .map(|s| {
13256 let range = s.display_range(&display_map).sorted();
13257 let mut start = range.start.to_point(&display_map);
13258 let mut end = range.end.to_point(&display_map);
13259 start.column = 0;
13260 end.column = buffer.line_len(MultiBufferRow(end.row));
13261 start..end
13262 })
13263 .collect::<Vec<_>>();
13264
13265 self.unfold_ranges(&ranges, true, true, cx);
13266 } else {
13267 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13268 let buffer_ids = self
13269 .selections
13270 .disjoint_anchor_ranges()
13271 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13272 .collect::<HashSet<_>>();
13273 for buffer_id in buffer_ids {
13274 self.unfold_buffer(buffer_id, cx);
13275 }
13276 }
13277 }
13278
13279 pub fn unfold_recursive(
13280 &mut self,
13281 _: &UnfoldRecursive,
13282 _window: &mut Window,
13283 cx: &mut Context<Self>,
13284 ) {
13285 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13286 let selections = self.selections.all::<Point>(cx);
13287 let ranges = selections
13288 .iter()
13289 .map(|s| {
13290 let mut range = s.display_range(&display_map).sorted();
13291 *range.start.column_mut() = 0;
13292 *range.end.column_mut() = display_map.line_len(range.end.row());
13293 let start = range.start.to_point(&display_map);
13294 let end = range.end.to_point(&display_map);
13295 start..end
13296 })
13297 .collect::<Vec<_>>();
13298
13299 self.unfold_ranges(&ranges, true, true, cx);
13300 }
13301
13302 pub fn unfold_at(
13303 &mut self,
13304 unfold_at: &UnfoldAt,
13305 _window: &mut Window,
13306 cx: &mut Context<Self>,
13307 ) {
13308 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13309
13310 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13311 ..Point::new(
13312 unfold_at.buffer_row.0,
13313 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13314 );
13315
13316 let autoscroll = self
13317 .selections
13318 .all::<Point>(cx)
13319 .iter()
13320 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13321
13322 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13323 }
13324
13325 pub fn unfold_all(
13326 &mut self,
13327 _: &actions::UnfoldAll,
13328 _window: &mut Window,
13329 cx: &mut Context<Self>,
13330 ) {
13331 if self.buffer.read(cx).is_singleton() {
13332 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13333 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13334 } else {
13335 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13336 editor
13337 .update(&mut cx, |editor, cx| {
13338 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13339 editor.unfold_buffer(buffer_id, cx);
13340 }
13341 })
13342 .ok();
13343 });
13344 }
13345 }
13346
13347 pub fn fold_selected_ranges(
13348 &mut self,
13349 _: &FoldSelectedRanges,
13350 window: &mut Window,
13351 cx: &mut Context<Self>,
13352 ) {
13353 let selections = self.selections.all::<Point>(cx);
13354 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13355 let line_mode = self.selections.line_mode;
13356 let ranges = selections
13357 .into_iter()
13358 .map(|s| {
13359 if line_mode {
13360 let start = Point::new(s.start.row, 0);
13361 let end = Point::new(
13362 s.end.row,
13363 display_map
13364 .buffer_snapshot
13365 .line_len(MultiBufferRow(s.end.row)),
13366 );
13367 Crease::simple(start..end, display_map.fold_placeholder.clone())
13368 } else {
13369 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13370 }
13371 })
13372 .collect::<Vec<_>>();
13373 self.fold_creases(ranges, true, window, cx);
13374 }
13375
13376 pub fn fold_ranges<T: ToOffset + Clone>(
13377 &mut self,
13378 ranges: Vec<Range<T>>,
13379 auto_scroll: bool,
13380 window: &mut Window,
13381 cx: &mut Context<Self>,
13382 ) {
13383 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13384 let ranges = ranges
13385 .into_iter()
13386 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13387 .collect::<Vec<_>>();
13388 self.fold_creases(ranges, auto_scroll, window, cx);
13389 }
13390
13391 pub fn fold_creases<T: ToOffset + Clone>(
13392 &mut self,
13393 creases: Vec<Crease<T>>,
13394 auto_scroll: bool,
13395 window: &mut Window,
13396 cx: &mut Context<Self>,
13397 ) {
13398 if creases.is_empty() {
13399 return;
13400 }
13401
13402 let mut buffers_affected = HashSet::default();
13403 let multi_buffer = self.buffer().read(cx);
13404 for crease in &creases {
13405 if let Some((_, buffer, _)) =
13406 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13407 {
13408 buffers_affected.insert(buffer.read(cx).remote_id());
13409 };
13410 }
13411
13412 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13413
13414 if auto_scroll {
13415 self.request_autoscroll(Autoscroll::fit(), cx);
13416 }
13417
13418 cx.notify();
13419
13420 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13421 // Clear diagnostics block when folding a range that contains it.
13422 let snapshot = self.snapshot(window, cx);
13423 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13424 drop(snapshot);
13425 self.active_diagnostics = Some(active_diagnostics);
13426 self.dismiss_diagnostics(cx);
13427 } else {
13428 self.active_diagnostics = Some(active_diagnostics);
13429 }
13430 }
13431
13432 self.scrollbar_marker_state.dirty = true;
13433 }
13434
13435 /// Removes any folds whose ranges intersect any of the given ranges.
13436 pub fn unfold_ranges<T: ToOffset + Clone>(
13437 &mut self,
13438 ranges: &[Range<T>],
13439 inclusive: bool,
13440 auto_scroll: bool,
13441 cx: &mut Context<Self>,
13442 ) {
13443 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13444 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13445 });
13446 }
13447
13448 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13449 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13450 return;
13451 }
13452 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13453 self.display_map.update(cx, |display_map, cx| {
13454 display_map.fold_buffers([buffer_id], cx)
13455 });
13456 cx.emit(EditorEvent::BufferFoldToggled {
13457 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13458 folded: true,
13459 });
13460 cx.notify();
13461 }
13462
13463 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13464 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13465 return;
13466 }
13467 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13468 self.display_map.update(cx, |display_map, cx| {
13469 display_map.unfold_buffers([buffer_id], cx);
13470 });
13471 cx.emit(EditorEvent::BufferFoldToggled {
13472 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13473 folded: false,
13474 });
13475 cx.notify();
13476 }
13477
13478 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13479 self.display_map.read(cx).is_buffer_folded(buffer)
13480 }
13481
13482 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13483 self.display_map.read(cx).folded_buffers()
13484 }
13485
13486 /// Removes any folds with the given ranges.
13487 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13488 &mut self,
13489 ranges: &[Range<T>],
13490 type_id: TypeId,
13491 auto_scroll: bool,
13492 cx: &mut Context<Self>,
13493 ) {
13494 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13495 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13496 });
13497 }
13498
13499 fn remove_folds_with<T: ToOffset + Clone>(
13500 &mut self,
13501 ranges: &[Range<T>],
13502 auto_scroll: bool,
13503 cx: &mut Context<Self>,
13504 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13505 ) {
13506 if ranges.is_empty() {
13507 return;
13508 }
13509
13510 let mut buffers_affected = HashSet::default();
13511 let multi_buffer = self.buffer().read(cx);
13512 for range in ranges {
13513 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13514 buffers_affected.insert(buffer.read(cx).remote_id());
13515 };
13516 }
13517
13518 self.display_map.update(cx, update);
13519
13520 if auto_scroll {
13521 self.request_autoscroll(Autoscroll::fit(), cx);
13522 }
13523
13524 cx.notify();
13525 self.scrollbar_marker_state.dirty = true;
13526 self.active_indent_guides_state.dirty = true;
13527 }
13528
13529 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13530 self.display_map.read(cx).fold_placeholder.clone()
13531 }
13532
13533 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13534 self.buffer.update(cx, |buffer, cx| {
13535 buffer.set_all_diff_hunks_expanded(cx);
13536 });
13537 }
13538
13539 pub fn expand_all_diff_hunks(
13540 &mut self,
13541 _: &ExpandAllDiffHunks,
13542 _window: &mut Window,
13543 cx: &mut Context<Self>,
13544 ) {
13545 self.buffer.update(cx, |buffer, cx| {
13546 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13547 });
13548 }
13549
13550 pub fn toggle_selected_diff_hunks(
13551 &mut self,
13552 _: &ToggleSelectedDiffHunks,
13553 _window: &mut Window,
13554 cx: &mut Context<Self>,
13555 ) {
13556 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13557 self.toggle_diff_hunks_in_ranges(ranges, cx);
13558 }
13559
13560 pub fn diff_hunks_in_ranges<'a>(
13561 &'a self,
13562 ranges: &'a [Range<Anchor>],
13563 buffer: &'a MultiBufferSnapshot,
13564 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13565 ranges.iter().flat_map(move |range| {
13566 let end_excerpt_id = range.end.excerpt_id;
13567 let range = range.to_point(buffer);
13568 let mut peek_end = range.end;
13569 if range.end.row < buffer.max_row().0 {
13570 peek_end = Point::new(range.end.row + 1, 0);
13571 }
13572 buffer
13573 .diff_hunks_in_range(range.start..peek_end)
13574 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13575 })
13576 }
13577
13578 pub fn has_stageable_diff_hunks_in_ranges(
13579 &self,
13580 ranges: &[Range<Anchor>],
13581 snapshot: &MultiBufferSnapshot,
13582 ) -> bool {
13583 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13584 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13585 }
13586
13587 pub fn toggle_staged_selected_diff_hunks(
13588 &mut self,
13589 _: &::git::ToggleStaged,
13590 _: &mut Window,
13591 cx: &mut Context<Self>,
13592 ) {
13593 let snapshot = self.buffer.read(cx).snapshot(cx);
13594 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13595 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13596 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13597 }
13598
13599 pub fn stage_and_next(
13600 &mut self,
13601 _: &::git::StageAndNext,
13602 window: &mut Window,
13603 cx: &mut Context<Self>,
13604 ) {
13605 self.do_stage_or_unstage_and_next(true, window, cx);
13606 }
13607
13608 pub fn unstage_and_next(
13609 &mut self,
13610 _: &::git::UnstageAndNext,
13611 window: &mut Window,
13612 cx: &mut Context<Self>,
13613 ) {
13614 self.do_stage_or_unstage_and_next(false, window, cx);
13615 }
13616
13617 pub fn stage_or_unstage_diff_hunks(
13618 &mut self,
13619 stage: bool,
13620 ranges: Vec<Range<Anchor>>,
13621 cx: &mut Context<Self>,
13622 ) {
13623 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13624 cx.spawn(|this, mut cx| async move {
13625 task.await?;
13626 this.update(&mut cx, |this, cx| {
13627 let snapshot = this.buffer.read(cx).snapshot(cx);
13628 let chunk_by = this
13629 .diff_hunks_in_ranges(&ranges, &snapshot)
13630 .chunk_by(|hunk| hunk.buffer_id);
13631 for (buffer_id, hunks) in &chunk_by {
13632 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13633 }
13634 })
13635 })
13636 .detach_and_log_err(cx);
13637 }
13638
13639 fn save_buffers_for_ranges_if_needed(
13640 &mut self,
13641 ranges: &[Range<Anchor>],
13642 cx: &mut Context<'_, Editor>,
13643 ) -> Task<Result<()>> {
13644 let multibuffer = self.buffer.read(cx);
13645 let snapshot = multibuffer.read(cx);
13646 let buffer_ids: HashSet<_> = ranges
13647 .iter()
13648 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13649 .collect();
13650 drop(snapshot);
13651
13652 let mut buffers = HashSet::default();
13653 for buffer_id in buffer_ids {
13654 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13655 let buffer = buffer_entity.read(cx);
13656 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13657 {
13658 buffers.insert(buffer_entity);
13659 }
13660 }
13661 }
13662
13663 if let Some(project) = &self.project {
13664 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13665 } else {
13666 Task::ready(Ok(()))
13667 }
13668 }
13669
13670 fn do_stage_or_unstage_and_next(
13671 &mut self,
13672 stage: bool,
13673 window: &mut Window,
13674 cx: &mut Context<Self>,
13675 ) {
13676 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13677
13678 if ranges.iter().any(|range| range.start != range.end) {
13679 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13680 return;
13681 }
13682
13683 let snapshot = self.snapshot(window, cx);
13684 let newest_range = self.selections.newest::<Point>(cx).range();
13685
13686 let run_twice = snapshot
13687 .hunks_for_ranges([newest_range])
13688 .first()
13689 .is_some_and(|hunk| {
13690 let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13691 self.hunk_after_position(&snapshot, next_line)
13692 .is_some_and(|other| other.row_range == hunk.row_range)
13693 });
13694
13695 if run_twice {
13696 self.go_to_next_hunk(&GoToHunk, window, cx);
13697 }
13698 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13699 self.go_to_next_hunk(&GoToHunk, window, cx);
13700 }
13701
13702 fn do_stage_or_unstage(
13703 &self,
13704 stage: bool,
13705 buffer_id: BufferId,
13706 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13707 cx: &mut App,
13708 ) -> Option<()> {
13709 let project = self.project.as_ref()?;
13710 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13711 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13712 let buffer_snapshot = buffer.read(cx).snapshot();
13713 let file_exists = buffer_snapshot
13714 .file()
13715 .is_some_and(|file| file.disk_state().exists());
13716 diff.update(cx, |diff, cx| {
13717 diff.stage_or_unstage_hunks(
13718 stage,
13719 &hunks
13720 .map(|hunk| buffer_diff::DiffHunk {
13721 buffer_range: hunk.buffer_range,
13722 diff_base_byte_range: hunk.diff_base_byte_range,
13723 secondary_status: hunk.secondary_status,
13724 range: Point::zero()..Point::zero(), // unused
13725 })
13726 .collect::<Vec<_>>(),
13727 &buffer_snapshot,
13728 file_exists,
13729 cx,
13730 )
13731 });
13732 None
13733 }
13734
13735 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13736 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13737 self.buffer
13738 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13739 }
13740
13741 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13742 self.buffer.update(cx, |buffer, cx| {
13743 let ranges = vec![Anchor::min()..Anchor::max()];
13744 if !buffer.all_diff_hunks_expanded()
13745 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13746 {
13747 buffer.collapse_diff_hunks(ranges, cx);
13748 true
13749 } else {
13750 false
13751 }
13752 })
13753 }
13754
13755 fn toggle_diff_hunks_in_ranges(
13756 &mut self,
13757 ranges: Vec<Range<Anchor>>,
13758 cx: &mut Context<'_, Editor>,
13759 ) {
13760 self.buffer.update(cx, |buffer, cx| {
13761 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13762 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13763 })
13764 }
13765
13766 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13767 self.buffer.update(cx, |buffer, cx| {
13768 let snapshot = buffer.snapshot(cx);
13769 let excerpt_id = range.end.excerpt_id;
13770 let point_range = range.to_point(&snapshot);
13771 let expand = !buffer.single_hunk_is_expanded(range, cx);
13772 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13773 })
13774 }
13775
13776 pub(crate) fn apply_all_diff_hunks(
13777 &mut self,
13778 _: &ApplyAllDiffHunks,
13779 window: &mut Window,
13780 cx: &mut Context<Self>,
13781 ) {
13782 let buffers = self.buffer.read(cx).all_buffers();
13783 for branch_buffer in buffers {
13784 branch_buffer.update(cx, |branch_buffer, cx| {
13785 branch_buffer.merge_into_base(Vec::new(), cx);
13786 });
13787 }
13788
13789 if let Some(project) = self.project.clone() {
13790 self.save(true, project, window, cx).detach_and_log_err(cx);
13791 }
13792 }
13793
13794 pub(crate) fn apply_selected_diff_hunks(
13795 &mut self,
13796 _: &ApplyDiffHunk,
13797 window: &mut Window,
13798 cx: &mut Context<Self>,
13799 ) {
13800 let snapshot = self.snapshot(window, cx);
13801 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13802 let mut ranges_by_buffer = HashMap::default();
13803 self.transact(window, cx, |editor, _window, cx| {
13804 for hunk in hunks {
13805 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13806 ranges_by_buffer
13807 .entry(buffer.clone())
13808 .or_insert_with(Vec::new)
13809 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13810 }
13811 }
13812
13813 for (buffer, ranges) in ranges_by_buffer {
13814 buffer.update(cx, |buffer, cx| {
13815 buffer.merge_into_base(ranges, cx);
13816 });
13817 }
13818 });
13819
13820 if let Some(project) = self.project.clone() {
13821 self.save(true, project, window, cx).detach_and_log_err(cx);
13822 }
13823 }
13824
13825 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13826 if hovered != self.gutter_hovered {
13827 self.gutter_hovered = hovered;
13828 cx.notify();
13829 }
13830 }
13831
13832 pub fn insert_blocks(
13833 &mut self,
13834 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13835 autoscroll: Option<Autoscroll>,
13836 cx: &mut Context<Self>,
13837 ) -> Vec<CustomBlockId> {
13838 let blocks = self
13839 .display_map
13840 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13841 if let Some(autoscroll) = autoscroll {
13842 self.request_autoscroll(autoscroll, cx);
13843 }
13844 cx.notify();
13845 blocks
13846 }
13847
13848 pub fn resize_blocks(
13849 &mut self,
13850 heights: HashMap<CustomBlockId, u32>,
13851 autoscroll: Option<Autoscroll>,
13852 cx: &mut Context<Self>,
13853 ) {
13854 self.display_map
13855 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13856 if let Some(autoscroll) = autoscroll {
13857 self.request_autoscroll(autoscroll, cx);
13858 }
13859 cx.notify();
13860 }
13861
13862 pub fn replace_blocks(
13863 &mut self,
13864 renderers: HashMap<CustomBlockId, RenderBlock>,
13865 autoscroll: Option<Autoscroll>,
13866 cx: &mut Context<Self>,
13867 ) {
13868 self.display_map
13869 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13870 if let Some(autoscroll) = autoscroll {
13871 self.request_autoscroll(autoscroll, cx);
13872 }
13873 cx.notify();
13874 }
13875
13876 pub fn remove_blocks(
13877 &mut self,
13878 block_ids: HashSet<CustomBlockId>,
13879 autoscroll: Option<Autoscroll>,
13880 cx: &mut Context<Self>,
13881 ) {
13882 self.display_map.update(cx, |display_map, cx| {
13883 display_map.remove_blocks(block_ids, cx)
13884 });
13885 if let Some(autoscroll) = autoscroll {
13886 self.request_autoscroll(autoscroll, cx);
13887 }
13888 cx.notify();
13889 }
13890
13891 pub fn row_for_block(
13892 &self,
13893 block_id: CustomBlockId,
13894 cx: &mut Context<Self>,
13895 ) -> Option<DisplayRow> {
13896 self.display_map
13897 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13898 }
13899
13900 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13901 self.focused_block = Some(focused_block);
13902 }
13903
13904 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13905 self.focused_block.take()
13906 }
13907
13908 pub fn insert_creases(
13909 &mut self,
13910 creases: impl IntoIterator<Item = Crease<Anchor>>,
13911 cx: &mut Context<Self>,
13912 ) -> Vec<CreaseId> {
13913 self.display_map
13914 .update(cx, |map, cx| map.insert_creases(creases, cx))
13915 }
13916
13917 pub fn remove_creases(
13918 &mut self,
13919 ids: impl IntoIterator<Item = CreaseId>,
13920 cx: &mut Context<Self>,
13921 ) {
13922 self.display_map
13923 .update(cx, |map, cx| map.remove_creases(ids, cx));
13924 }
13925
13926 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13927 self.display_map
13928 .update(cx, |map, cx| map.snapshot(cx))
13929 .longest_row()
13930 }
13931
13932 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13933 self.display_map
13934 .update(cx, |map, cx| map.snapshot(cx))
13935 .max_point()
13936 }
13937
13938 pub fn text(&self, cx: &App) -> String {
13939 self.buffer.read(cx).read(cx).text()
13940 }
13941
13942 pub fn is_empty(&self, cx: &App) -> bool {
13943 self.buffer.read(cx).read(cx).is_empty()
13944 }
13945
13946 pub fn text_option(&self, cx: &App) -> Option<String> {
13947 let text = self.text(cx);
13948 let text = text.trim();
13949
13950 if text.is_empty() {
13951 return None;
13952 }
13953
13954 Some(text.to_string())
13955 }
13956
13957 pub fn set_text(
13958 &mut self,
13959 text: impl Into<Arc<str>>,
13960 window: &mut Window,
13961 cx: &mut Context<Self>,
13962 ) {
13963 self.transact(window, cx, |this, _, cx| {
13964 this.buffer
13965 .read(cx)
13966 .as_singleton()
13967 .expect("you can only call set_text on editors for singleton buffers")
13968 .update(cx, |buffer, cx| buffer.set_text(text, cx));
13969 });
13970 }
13971
13972 pub fn display_text(&self, cx: &mut App) -> String {
13973 self.display_map
13974 .update(cx, |map, cx| map.snapshot(cx))
13975 .text()
13976 }
13977
13978 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13979 let mut wrap_guides = smallvec::smallvec![];
13980
13981 if self.show_wrap_guides == Some(false) {
13982 return wrap_guides;
13983 }
13984
13985 let settings = self.buffer.read(cx).settings_at(0, cx);
13986 if settings.show_wrap_guides {
13987 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13988 wrap_guides.push((soft_wrap as usize, true));
13989 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13990 wrap_guides.push((soft_wrap as usize, true));
13991 }
13992 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13993 }
13994
13995 wrap_guides
13996 }
13997
13998 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13999 let settings = self.buffer.read(cx).settings_at(0, cx);
14000 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14001 match mode {
14002 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14003 SoftWrap::None
14004 }
14005 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14006 language_settings::SoftWrap::PreferredLineLength => {
14007 SoftWrap::Column(settings.preferred_line_length)
14008 }
14009 language_settings::SoftWrap::Bounded => {
14010 SoftWrap::Bounded(settings.preferred_line_length)
14011 }
14012 }
14013 }
14014
14015 pub fn set_soft_wrap_mode(
14016 &mut self,
14017 mode: language_settings::SoftWrap,
14018
14019 cx: &mut Context<Self>,
14020 ) {
14021 self.soft_wrap_mode_override = Some(mode);
14022 cx.notify();
14023 }
14024
14025 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14026 self.text_style_refinement = Some(style);
14027 }
14028
14029 /// called by the Element so we know what style we were most recently rendered with.
14030 pub(crate) fn set_style(
14031 &mut self,
14032 style: EditorStyle,
14033 window: &mut Window,
14034 cx: &mut Context<Self>,
14035 ) {
14036 let rem_size = window.rem_size();
14037 self.display_map.update(cx, |map, cx| {
14038 map.set_font(
14039 style.text.font(),
14040 style.text.font_size.to_pixels(rem_size),
14041 cx,
14042 )
14043 });
14044 self.style = Some(style);
14045 }
14046
14047 pub fn style(&self) -> Option<&EditorStyle> {
14048 self.style.as_ref()
14049 }
14050
14051 // Called by the element. This method is not designed to be called outside of the editor
14052 // element's layout code because it does not notify when rewrapping is computed synchronously.
14053 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14054 self.display_map
14055 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14056 }
14057
14058 pub fn set_soft_wrap(&mut self) {
14059 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14060 }
14061
14062 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14063 if self.soft_wrap_mode_override.is_some() {
14064 self.soft_wrap_mode_override.take();
14065 } else {
14066 let soft_wrap = match self.soft_wrap_mode(cx) {
14067 SoftWrap::GitDiff => return,
14068 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14069 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14070 language_settings::SoftWrap::None
14071 }
14072 };
14073 self.soft_wrap_mode_override = Some(soft_wrap);
14074 }
14075 cx.notify();
14076 }
14077
14078 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14079 let Some(workspace) = self.workspace() else {
14080 return;
14081 };
14082 let fs = workspace.read(cx).app_state().fs.clone();
14083 let current_show = TabBarSettings::get_global(cx).show;
14084 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14085 setting.show = Some(!current_show);
14086 });
14087 }
14088
14089 pub fn toggle_indent_guides(
14090 &mut self,
14091 _: &ToggleIndentGuides,
14092 _: &mut Window,
14093 cx: &mut Context<Self>,
14094 ) {
14095 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14096 self.buffer
14097 .read(cx)
14098 .settings_at(0, cx)
14099 .indent_guides
14100 .enabled
14101 });
14102 self.show_indent_guides = Some(!currently_enabled);
14103 cx.notify();
14104 }
14105
14106 fn should_show_indent_guides(&self) -> Option<bool> {
14107 self.show_indent_guides
14108 }
14109
14110 pub fn toggle_line_numbers(
14111 &mut self,
14112 _: &ToggleLineNumbers,
14113 _: &mut Window,
14114 cx: &mut Context<Self>,
14115 ) {
14116 let mut editor_settings = EditorSettings::get_global(cx).clone();
14117 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14118 EditorSettings::override_global(editor_settings, cx);
14119 }
14120
14121 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14122 self.use_relative_line_numbers
14123 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14124 }
14125
14126 pub fn toggle_relative_line_numbers(
14127 &mut self,
14128 _: &ToggleRelativeLineNumbers,
14129 _: &mut Window,
14130 cx: &mut Context<Self>,
14131 ) {
14132 let is_relative = self.should_use_relative_line_numbers(cx);
14133 self.set_relative_line_number(Some(!is_relative), cx)
14134 }
14135
14136 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14137 self.use_relative_line_numbers = is_relative;
14138 cx.notify();
14139 }
14140
14141 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14142 self.show_gutter = show_gutter;
14143 cx.notify();
14144 }
14145
14146 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14147 self.show_scrollbars = show_scrollbars;
14148 cx.notify();
14149 }
14150
14151 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14152 self.show_line_numbers = Some(show_line_numbers);
14153 cx.notify();
14154 }
14155
14156 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14157 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14158 cx.notify();
14159 }
14160
14161 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14162 self.show_code_actions = Some(show_code_actions);
14163 cx.notify();
14164 }
14165
14166 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14167 self.show_runnables = Some(show_runnables);
14168 cx.notify();
14169 }
14170
14171 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14172 if self.display_map.read(cx).masked != masked {
14173 self.display_map.update(cx, |map, _| map.masked = masked);
14174 }
14175 cx.notify()
14176 }
14177
14178 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14179 self.show_wrap_guides = Some(show_wrap_guides);
14180 cx.notify();
14181 }
14182
14183 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14184 self.show_indent_guides = Some(show_indent_guides);
14185 cx.notify();
14186 }
14187
14188 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14189 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14190 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14191 if let Some(dir) = file.abs_path(cx).parent() {
14192 return Some(dir.to_owned());
14193 }
14194 }
14195
14196 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14197 return Some(project_path.path.to_path_buf());
14198 }
14199 }
14200
14201 None
14202 }
14203
14204 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14205 self.active_excerpt(cx)?
14206 .1
14207 .read(cx)
14208 .file()
14209 .and_then(|f| f.as_local())
14210 }
14211
14212 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14213 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14214 let buffer = buffer.read(cx);
14215 if let Some(project_path) = buffer.project_path(cx) {
14216 let project = self.project.as_ref()?.read(cx);
14217 project.absolute_path(&project_path, cx)
14218 } else {
14219 buffer
14220 .file()
14221 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14222 }
14223 })
14224 }
14225
14226 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14227 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14228 let project_path = buffer.read(cx).project_path(cx)?;
14229 let project = self.project.as_ref()?.read(cx);
14230 let entry = project.entry_for_path(&project_path, cx)?;
14231 let path = entry.path.to_path_buf();
14232 Some(path)
14233 })
14234 }
14235
14236 pub fn reveal_in_finder(
14237 &mut self,
14238 _: &RevealInFileManager,
14239 _window: &mut Window,
14240 cx: &mut Context<Self>,
14241 ) {
14242 if let Some(target) = self.target_file(cx) {
14243 cx.reveal_path(&target.abs_path(cx));
14244 }
14245 }
14246
14247 pub fn copy_path(
14248 &mut self,
14249 _: &zed_actions::workspace::CopyPath,
14250 _window: &mut Window,
14251 cx: &mut Context<Self>,
14252 ) {
14253 if let Some(path) = self.target_file_abs_path(cx) {
14254 if let Some(path) = path.to_str() {
14255 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14256 }
14257 }
14258 }
14259
14260 pub fn copy_relative_path(
14261 &mut self,
14262 _: &zed_actions::workspace::CopyRelativePath,
14263 _window: &mut Window,
14264 cx: &mut Context<Self>,
14265 ) {
14266 if let Some(path) = self.target_file_path(cx) {
14267 if let Some(path) = path.to_str() {
14268 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14269 }
14270 }
14271 }
14272
14273 pub fn copy_file_name_without_extension(
14274 &mut self,
14275 _: &CopyFileNameWithoutExtension,
14276 _: &mut Window,
14277 cx: &mut Context<Self>,
14278 ) {
14279 if let Some(file) = self.target_file(cx) {
14280 if let Some(file_stem) = file.path().file_stem() {
14281 if let Some(name) = file_stem.to_str() {
14282 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14283 }
14284 }
14285 }
14286 }
14287
14288 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14289 if let Some(file) = self.target_file(cx) {
14290 if let Some(file_name) = file.path().file_name() {
14291 if let Some(name) = file_name.to_str() {
14292 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14293 }
14294 }
14295 }
14296 }
14297
14298 pub fn toggle_git_blame(
14299 &mut self,
14300 _: &ToggleGitBlame,
14301 window: &mut Window,
14302 cx: &mut Context<Self>,
14303 ) {
14304 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14305
14306 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14307 self.start_git_blame(true, window, cx);
14308 }
14309
14310 cx.notify();
14311 }
14312
14313 pub fn toggle_git_blame_inline(
14314 &mut self,
14315 _: &ToggleGitBlameInline,
14316 window: &mut Window,
14317 cx: &mut Context<Self>,
14318 ) {
14319 self.toggle_git_blame_inline_internal(true, window, cx);
14320 cx.notify();
14321 }
14322
14323 pub fn git_blame_inline_enabled(&self) -> bool {
14324 self.git_blame_inline_enabled
14325 }
14326
14327 pub fn toggle_selection_menu(
14328 &mut self,
14329 _: &ToggleSelectionMenu,
14330 _: &mut Window,
14331 cx: &mut Context<Self>,
14332 ) {
14333 self.show_selection_menu = self
14334 .show_selection_menu
14335 .map(|show_selections_menu| !show_selections_menu)
14336 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14337
14338 cx.notify();
14339 }
14340
14341 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14342 self.show_selection_menu
14343 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14344 }
14345
14346 fn start_git_blame(
14347 &mut self,
14348 user_triggered: bool,
14349 window: &mut Window,
14350 cx: &mut Context<Self>,
14351 ) {
14352 if let Some(project) = self.project.as_ref() {
14353 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14354 return;
14355 };
14356
14357 if buffer.read(cx).file().is_none() {
14358 return;
14359 }
14360
14361 let focused = self.focus_handle(cx).contains_focused(window, cx);
14362
14363 let project = project.clone();
14364 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14365 self.blame_subscription =
14366 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14367 self.blame = Some(blame);
14368 }
14369 }
14370
14371 fn toggle_git_blame_inline_internal(
14372 &mut self,
14373 user_triggered: bool,
14374 window: &mut Window,
14375 cx: &mut Context<Self>,
14376 ) {
14377 if self.git_blame_inline_enabled {
14378 self.git_blame_inline_enabled = false;
14379 self.show_git_blame_inline = false;
14380 self.show_git_blame_inline_delay_task.take();
14381 } else {
14382 self.git_blame_inline_enabled = true;
14383 self.start_git_blame_inline(user_triggered, window, cx);
14384 }
14385
14386 cx.notify();
14387 }
14388
14389 fn start_git_blame_inline(
14390 &mut self,
14391 user_triggered: bool,
14392 window: &mut Window,
14393 cx: &mut Context<Self>,
14394 ) {
14395 self.start_git_blame(user_triggered, window, cx);
14396
14397 if ProjectSettings::get_global(cx)
14398 .git
14399 .inline_blame_delay()
14400 .is_some()
14401 {
14402 self.start_inline_blame_timer(window, cx);
14403 } else {
14404 self.show_git_blame_inline = true
14405 }
14406 }
14407
14408 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14409 self.blame.as_ref()
14410 }
14411
14412 pub fn show_git_blame_gutter(&self) -> bool {
14413 self.show_git_blame_gutter
14414 }
14415
14416 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14417 self.show_git_blame_gutter && self.has_blame_entries(cx)
14418 }
14419
14420 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14421 self.show_git_blame_inline
14422 && (self.focus_handle.is_focused(window)
14423 || self
14424 .git_blame_inline_tooltip
14425 .as_ref()
14426 .and_then(|t| t.upgrade())
14427 .is_some())
14428 && !self.newest_selection_head_on_empty_line(cx)
14429 && self.has_blame_entries(cx)
14430 }
14431
14432 fn has_blame_entries(&self, cx: &App) -> bool {
14433 self.blame()
14434 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14435 }
14436
14437 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14438 let cursor_anchor = self.selections.newest_anchor().head();
14439
14440 let snapshot = self.buffer.read(cx).snapshot(cx);
14441 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14442
14443 snapshot.line_len(buffer_row) == 0
14444 }
14445
14446 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14447 let buffer_and_selection = maybe!({
14448 let selection = self.selections.newest::<Point>(cx);
14449 let selection_range = selection.range();
14450
14451 let multi_buffer = self.buffer().read(cx);
14452 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14453 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14454
14455 let (buffer, range, _) = if selection.reversed {
14456 buffer_ranges.first()
14457 } else {
14458 buffer_ranges.last()
14459 }?;
14460
14461 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14462 ..text::ToPoint::to_point(&range.end, &buffer).row;
14463 Some((
14464 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14465 selection,
14466 ))
14467 });
14468
14469 let Some((buffer, selection)) = buffer_and_selection else {
14470 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14471 };
14472
14473 let Some(project) = self.project.as_ref() else {
14474 return Task::ready(Err(anyhow!("editor does not have project")));
14475 };
14476
14477 project.update(cx, |project, cx| {
14478 project.get_permalink_to_line(&buffer, selection, cx)
14479 })
14480 }
14481
14482 pub fn copy_permalink_to_line(
14483 &mut self,
14484 _: &CopyPermalinkToLine,
14485 window: &mut Window,
14486 cx: &mut Context<Self>,
14487 ) {
14488 let permalink_task = self.get_permalink_to_line(cx);
14489 let workspace = self.workspace();
14490
14491 cx.spawn_in(window, |_, mut cx| async move {
14492 match permalink_task.await {
14493 Ok(permalink) => {
14494 cx.update(|_, cx| {
14495 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14496 })
14497 .ok();
14498 }
14499 Err(err) => {
14500 let message = format!("Failed to copy permalink: {err}");
14501
14502 Err::<(), anyhow::Error>(err).log_err();
14503
14504 if let Some(workspace) = workspace {
14505 workspace
14506 .update_in(&mut cx, |workspace, _, cx| {
14507 struct CopyPermalinkToLine;
14508
14509 workspace.show_toast(
14510 Toast::new(
14511 NotificationId::unique::<CopyPermalinkToLine>(),
14512 message,
14513 ),
14514 cx,
14515 )
14516 })
14517 .ok();
14518 }
14519 }
14520 }
14521 })
14522 .detach();
14523 }
14524
14525 pub fn copy_file_location(
14526 &mut self,
14527 _: &CopyFileLocation,
14528 _: &mut Window,
14529 cx: &mut Context<Self>,
14530 ) {
14531 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14532 if let Some(file) = self.target_file(cx) {
14533 if let Some(path) = file.path().to_str() {
14534 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14535 }
14536 }
14537 }
14538
14539 pub fn open_permalink_to_line(
14540 &mut self,
14541 _: &OpenPermalinkToLine,
14542 window: &mut Window,
14543 cx: &mut Context<Self>,
14544 ) {
14545 let permalink_task = self.get_permalink_to_line(cx);
14546 let workspace = self.workspace();
14547
14548 cx.spawn_in(window, |_, mut cx| async move {
14549 match permalink_task.await {
14550 Ok(permalink) => {
14551 cx.update(|_, cx| {
14552 cx.open_url(permalink.as_ref());
14553 })
14554 .ok();
14555 }
14556 Err(err) => {
14557 let message = format!("Failed to open permalink: {err}");
14558
14559 Err::<(), anyhow::Error>(err).log_err();
14560
14561 if let Some(workspace) = workspace {
14562 workspace
14563 .update(&mut cx, |workspace, cx| {
14564 struct OpenPermalinkToLine;
14565
14566 workspace.show_toast(
14567 Toast::new(
14568 NotificationId::unique::<OpenPermalinkToLine>(),
14569 message,
14570 ),
14571 cx,
14572 )
14573 })
14574 .ok();
14575 }
14576 }
14577 }
14578 })
14579 .detach();
14580 }
14581
14582 pub fn insert_uuid_v4(
14583 &mut self,
14584 _: &InsertUuidV4,
14585 window: &mut Window,
14586 cx: &mut Context<Self>,
14587 ) {
14588 self.insert_uuid(UuidVersion::V4, window, cx);
14589 }
14590
14591 pub fn insert_uuid_v7(
14592 &mut self,
14593 _: &InsertUuidV7,
14594 window: &mut Window,
14595 cx: &mut Context<Self>,
14596 ) {
14597 self.insert_uuid(UuidVersion::V7, window, cx);
14598 }
14599
14600 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14601 self.transact(window, cx, |this, window, cx| {
14602 let edits = this
14603 .selections
14604 .all::<Point>(cx)
14605 .into_iter()
14606 .map(|selection| {
14607 let uuid = match version {
14608 UuidVersion::V4 => uuid::Uuid::new_v4(),
14609 UuidVersion::V7 => uuid::Uuid::now_v7(),
14610 };
14611
14612 (selection.range(), uuid.to_string())
14613 });
14614 this.edit(edits, cx);
14615 this.refresh_inline_completion(true, false, window, cx);
14616 });
14617 }
14618
14619 pub fn open_selections_in_multibuffer(
14620 &mut self,
14621 _: &OpenSelectionsInMultibuffer,
14622 window: &mut Window,
14623 cx: &mut Context<Self>,
14624 ) {
14625 let multibuffer = self.buffer.read(cx);
14626
14627 let Some(buffer) = multibuffer.as_singleton() else {
14628 return;
14629 };
14630
14631 let Some(workspace) = self.workspace() else {
14632 return;
14633 };
14634
14635 let locations = self
14636 .selections
14637 .disjoint_anchors()
14638 .iter()
14639 .map(|range| Location {
14640 buffer: buffer.clone(),
14641 range: range.start.text_anchor..range.end.text_anchor,
14642 })
14643 .collect::<Vec<_>>();
14644
14645 let title = multibuffer.title(cx).to_string();
14646
14647 cx.spawn_in(window, |_, mut cx| async move {
14648 workspace.update_in(&mut cx, |workspace, window, cx| {
14649 Self::open_locations_in_multibuffer(
14650 workspace,
14651 locations,
14652 format!("Selections for '{title}'"),
14653 false,
14654 MultibufferSelectionMode::All,
14655 window,
14656 cx,
14657 );
14658 })
14659 })
14660 .detach();
14661 }
14662
14663 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14664 /// last highlight added will be used.
14665 ///
14666 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14667 pub fn highlight_rows<T: 'static>(
14668 &mut self,
14669 range: Range<Anchor>,
14670 color: Hsla,
14671 should_autoscroll: bool,
14672 cx: &mut Context<Self>,
14673 ) {
14674 let snapshot = self.buffer().read(cx).snapshot(cx);
14675 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14676 let ix = row_highlights.binary_search_by(|highlight| {
14677 Ordering::Equal
14678 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14679 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14680 });
14681
14682 if let Err(mut ix) = ix {
14683 let index = post_inc(&mut self.highlight_order);
14684
14685 // If this range intersects with the preceding highlight, then merge it with
14686 // the preceding highlight. Otherwise insert a new highlight.
14687 let mut merged = false;
14688 if ix > 0 {
14689 let prev_highlight = &mut row_highlights[ix - 1];
14690 if prev_highlight
14691 .range
14692 .end
14693 .cmp(&range.start, &snapshot)
14694 .is_ge()
14695 {
14696 ix -= 1;
14697 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14698 prev_highlight.range.end = range.end;
14699 }
14700 merged = true;
14701 prev_highlight.index = index;
14702 prev_highlight.color = color;
14703 prev_highlight.should_autoscroll = should_autoscroll;
14704 }
14705 }
14706
14707 if !merged {
14708 row_highlights.insert(
14709 ix,
14710 RowHighlight {
14711 range: range.clone(),
14712 index,
14713 color,
14714 should_autoscroll,
14715 },
14716 );
14717 }
14718
14719 // If any of the following highlights intersect with this one, merge them.
14720 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14721 let highlight = &row_highlights[ix];
14722 if next_highlight
14723 .range
14724 .start
14725 .cmp(&highlight.range.end, &snapshot)
14726 .is_le()
14727 {
14728 if next_highlight
14729 .range
14730 .end
14731 .cmp(&highlight.range.end, &snapshot)
14732 .is_gt()
14733 {
14734 row_highlights[ix].range.end = next_highlight.range.end;
14735 }
14736 row_highlights.remove(ix + 1);
14737 } else {
14738 break;
14739 }
14740 }
14741 }
14742 }
14743
14744 /// Remove any highlighted row ranges of the given type that intersect the
14745 /// given ranges.
14746 pub fn remove_highlighted_rows<T: 'static>(
14747 &mut self,
14748 ranges_to_remove: Vec<Range<Anchor>>,
14749 cx: &mut Context<Self>,
14750 ) {
14751 let snapshot = self.buffer().read(cx).snapshot(cx);
14752 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14753 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14754 row_highlights.retain(|highlight| {
14755 while let Some(range_to_remove) = ranges_to_remove.peek() {
14756 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14757 Ordering::Less | Ordering::Equal => {
14758 ranges_to_remove.next();
14759 }
14760 Ordering::Greater => {
14761 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14762 Ordering::Less | Ordering::Equal => {
14763 return false;
14764 }
14765 Ordering::Greater => break,
14766 }
14767 }
14768 }
14769 }
14770
14771 true
14772 })
14773 }
14774
14775 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14776 pub fn clear_row_highlights<T: 'static>(&mut self) {
14777 self.highlighted_rows.remove(&TypeId::of::<T>());
14778 }
14779
14780 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14781 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14782 self.highlighted_rows
14783 .get(&TypeId::of::<T>())
14784 .map_or(&[] as &[_], |vec| vec.as_slice())
14785 .iter()
14786 .map(|highlight| (highlight.range.clone(), highlight.color))
14787 }
14788
14789 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14790 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14791 /// Allows to ignore certain kinds of highlights.
14792 pub fn highlighted_display_rows(
14793 &self,
14794 window: &mut Window,
14795 cx: &mut App,
14796 ) -> BTreeMap<DisplayRow, Background> {
14797 let snapshot = self.snapshot(window, cx);
14798 let mut used_highlight_orders = HashMap::default();
14799 self.highlighted_rows
14800 .iter()
14801 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14802 .fold(
14803 BTreeMap::<DisplayRow, Background>::new(),
14804 |mut unique_rows, highlight| {
14805 let start = highlight.range.start.to_display_point(&snapshot);
14806 let end = highlight.range.end.to_display_point(&snapshot);
14807 let start_row = start.row().0;
14808 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14809 && end.column() == 0
14810 {
14811 end.row().0.saturating_sub(1)
14812 } else {
14813 end.row().0
14814 };
14815 for row in start_row..=end_row {
14816 let used_index =
14817 used_highlight_orders.entry(row).or_insert(highlight.index);
14818 if highlight.index >= *used_index {
14819 *used_index = highlight.index;
14820 unique_rows.insert(DisplayRow(row), highlight.color.into());
14821 }
14822 }
14823 unique_rows
14824 },
14825 )
14826 }
14827
14828 pub fn highlighted_display_row_for_autoscroll(
14829 &self,
14830 snapshot: &DisplaySnapshot,
14831 ) -> Option<DisplayRow> {
14832 self.highlighted_rows
14833 .values()
14834 .flat_map(|highlighted_rows| highlighted_rows.iter())
14835 .filter_map(|highlight| {
14836 if highlight.should_autoscroll {
14837 Some(highlight.range.start.to_display_point(snapshot).row())
14838 } else {
14839 None
14840 }
14841 })
14842 .min()
14843 }
14844
14845 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14846 self.highlight_background::<SearchWithinRange>(
14847 ranges,
14848 |colors| colors.editor_document_highlight_read_background,
14849 cx,
14850 )
14851 }
14852
14853 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14854 self.breadcrumb_header = Some(new_header);
14855 }
14856
14857 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14858 self.clear_background_highlights::<SearchWithinRange>(cx);
14859 }
14860
14861 pub fn highlight_background<T: 'static>(
14862 &mut self,
14863 ranges: &[Range<Anchor>],
14864 color_fetcher: fn(&ThemeColors) -> Hsla,
14865 cx: &mut Context<Self>,
14866 ) {
14867 self.background_highlights
14868 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14869 self.scrollbar_marker_state.dirty = true;
14870 cx.notify();
14871 }
14872
14873 pub fn clear_background_highlights<T: 'static>(
14874 &mut self,
14875 cx: &mut Context<Self>,
14876 ) -> Option<BackgroundHighlight> {
14877 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14878 if !text_highlights.1.is_empty() {
14879 self.scrollbar_marker_state.dirty = true;
14880 cx.notify();
14881 }
14882 Some(text_highlights)
14883 }
14884
14885 pub fn highlight_gutter<T: 'static>(
14886 &mut self,
14887 ranges: &[Range<Anchor>],
14888 color_fetcher: fn(&App) -> Hsla,
14889 cx: &mut Context<Self>,
14890 ) {
14891 self.gutter_highlights
14892 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14893 cx.notify();
14894 }
14895
14896 pub fn clear_gutter_highlights<T: 'static>(
14897 &mut self,
14898 cx: &mut Context<Self>,
14899 ) -> Option<GutterHighlight> {
14900 cx.notify();
14901 self.gutter_highlights.remove(&TypeId::of::<T>())
14902 }
14903
14904 #[cfg(feature = "test-support")]
14905 pub fn all_text_background_highlights(
14906 &self,
14907 window: &mut Window,
14908 cx: &mut Context<Self>,
14909 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14910 let snapshot = self.snapshot(window, cx);
14911 let buffer = &snapshot.buffer_snapshot;
14912 let start = buffer.anchor_before(0);
14913 let end = buffer.anchor_after(buffer.len());
14914 let theme = cx.theme().colors();
14915 self.background_highlights_in_range(start..end, &snapshot, theme)
14916 }
14917
14918 #[cfg(feature = "test-support")]
14919 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14920 let snapshot = self.buffer().read(cx).snapshot(cx);
14921
14922 let highlights = self
14923 .background_highlights
14924 .get(&TypeId::of::<items::BufferSearchHighlights>());
14925
14926 if let Some((_color, ranges)) = highlights {
14927 ranges
14928 .iter()
14929 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14930 .collect_vec()
14931 } else {
14932 vec![]
14933 }
14934 }
14935
14936 fn document_highlights_for_position<'a>(
14937 &'a self,
14938 position: Anchor,
14939 buffer: &'a MultiBufferSnapshot,
14940 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14941 let read_highlights = self
14942 .background_highlights
14943 .get(&TypeId::of::<DocumentHighlightRead>())
14944 .map(|h| &h.1);
14945 let write_highlights = self
14946 .background_highlights
14947 .get(&TypeId::of::<DocumentHighlightWrite>())
14948 .map(|h| &h.1);
14949 let left_position = position.bias_left(buffer);
14950 let right_position = position.bias_right(buffer);
14951 read_highlights
14952 .into_iter()
14953 .chain(write_highlights)
14954 .flat_map(move |ranges| {
14955 let start_ix = match ranges.binary_search_by(|probe| {
14956 let cmp = probe.end.cmp(&left_position, buffer);
14957 if cmp.is_ge() {
14958 Ordering::Greater
14959 } else {
14960 Ordering::Less
14961 }
14962 }) {
14963 Ok(i) | Err(i) => i,
14964 };
14965
14966 ranges[start_ix..]
14967 .iter()
14968 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14969 })
14970 }
14971
14972 pub fn has_background_highlights<T: 'static>(&self) -> bool {
14973 self.background_highlights
14974 .get(&TypeId::of::<T>())
14975 .map_or(false, |(_, highlights)| !highlights.is_empty())
14976 }
14977
14978 pub fn background_highlights_in_range(
14979 &self,
14980 search_range: Range<Anchor>,
14981 display_snapshot: &DisplaySnapshot,
14982 theme: &ThemeColors,
14983 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14984 let mut results = Vec::new();
14985 for (color_fetcher, ranges) in self.background_highlights.values() {
14986 let color = color_fetcher(theme);
14987 let start_ix = match ranges.binary_search_by(|probe| {
14988 let cmp = probe
14989 .end
14990 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14991 if cmp.is_gt() {
14992 Ordering::Greater
14993 } else {
14994 Ordering::Less
14995 }
14996 }) {
14997 Ok(i) | Err(i) => i,
14998 };
14999 for range in &ranges[start_ix..] {
15000 if range
15001 .start
15002 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15003 .is_ge()
15004 {
15005 break;
15006 }
15007
15008 let start = range.start.to_display_point(display_snapshot);
15009 let end = range.end.to_display_point(display_snapshot);
15010 results.push((start..end, color))
15011 }
15012 }
15013 results
15014 }
15015
15016 pub fn background_highlight_row_ranges<T: 'static>(
15017 &self,
15018 search_range: Range<Anchor>,
15019 display_snapshot: &DisplaySnapshot,
15020 count: usize,
15021 ) -> Vec<RangeInclusive<DisplayPoint>> {
15022 let mut results = Vec::new();
15023 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15024 return vec![];
15025 };
15026
15027 let start_ix = match ranges.binary_search_by(|probe| {
15028 let cmp = probe
15029 .end
15030 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15031 if cmp.is_gt() {
15032 Ordering::Greater
15033 } else {
15034 Ordering::Less
15035 }
15036 }) {
15037 Ok(i) | Err(i) => i,
15038 };
15039 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15040 if let (Some(start_display), Some(end_display)) = (start, end) {
15041 results.push(
15042 start_display.to_display_point(display_snapshot)
15043 ..=end_display.to_display_point(display_snapshot),
15044 );
15045 }
15046 };
15047 let mut start_row: Option<Point> = None;
15048 let mut end_row: Option<Point> = None;
15049 if ranges.len() > count {
15050 return Vec::new();
15051 }
15052 for range in &ranges[start_ix..] {
15053 if range
15054 .start
15055 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15056 .is_ge()
15057 {
15058 break;
15059 }
15060 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15061 if let Some(current_row) = &end_row {
15062 if end.row == current_row.row {
15063 continue;
15064 }
15065 }
15066 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15067 if start_row.is_none() {
15068 assert_eq!(end_row, None);
15069 start_row = Some(start);
15070 end_row = Some(end);
15071 continue;
15072 }
15073 if let Some(current_end) = end_row.as_mut() {
15074 if start.row > current_end.row + 1 {
15075 push_region(start_row, end_row);
15076 start_row = Some(start);
15077 end_row = Some(end);
15078 } else {
15079 // Merge two hunks.
15080 *current_end = end;
15081 }
15082 } else {
15083 unreachable!();
15084 }
15085 }
15086 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15087 push_region(start_row, end_row);
15088 results
15089 }
15090
15091 pub fn gutter_highlights_in_range(
15092 &self,
15093 search_range: Range<Anchor>,
15094 display_snapshot: &DisplaySnapshot,
15095 cx: &App,
15096 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15097 let mut results = Vec::new();
15098 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15099 let color = color_fetcher(cx);
15100 let start_ix = match ranges.binary_search_by(|probe| {
15101 let cmp = probe
15102 .end
15103 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15104 if cmp.is_gt() {
15105 Ordering::Greater
15106 } else {
15107 Ordering::Less
15108 }
15109 }) {
15110 Ok(i) | Err(i) => i,
15111 };
15112 for range in &ranges[start_ix..] {
15113 if range
15114 .start
15115 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15116 .is_ge()
15117 {
15118 break;
15119 }
15120
15121 let start = range.start.to_display_point(display_snapshot);
15122 let end = range.end.to_display_point(display_snapshot);
15123 results.push((start..end, color))
15124 }
15125 }
15126 results
15127 }
15128
15129 /// Get the text ranges corresponding to the redaction query
15130 pub fn redacted_ranges(
15131 &self,
15132 search_range: Range<Anchor>,
15133 display_snapshot: &DisplaySnapshot,
15134 cx: &App,
15135 ) -> Vec<Range<DisplayPoint>> {
15136 display_snapshot
15137 .buffer_snapshot
15138 .redacted_ranges(search_range, |file| {
15139 if let Some(file) = file {
15140 file.is_private()
15141 && EditorSettings::get(
15142 Some(SettingsLocation {
15143 worktree_id: file.worktree_id(cx),
15144 path: file.path().as_ref(),
15145 }),
15146 cx,
15147 )
15148 .redact_private_values
15149 } else {
15150 false
15151 }
15152 })
15153 .map(|range| {
15154 range.start.to_display_point(display_snapshot)
15155 ..range.end.to_display_point(display_snapshot)
15156 })
15157 .collect()
15158 }
15159
15160 pub fn highlight_text<T: 'static>(
15161 &mut self,
15162 ranges: Vec<Range<Anchor>>,
15163 style: HighlightStyle,
15164 cx: &mut Context<Self>,
15165 ) {
15166 self.display_map.update(cx, |map, _| {
15167 map.highlight_text(TypeId::of::<T>(), ranges, style)
15168 });
15169 cx.notify();
15170 }
15171
15172 pub(crate) fn highlight_inlays<T: 'static>(
15173 &mut self,
15174 highlights: Vec<InlayHighlight>,
15175 style: HighlightStyle,
15176 cx: &mut Context<Self>,
15177 ) {
15178 self.display_map.update(cx, |map, _| {
15179 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15180 });
15181 cx.notify();
15182 }
15183
15184 pub fn text_highlights<'a, T: 'static>(
15185 &'a self,
15186 cx: &'a App,
15187 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15188 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15189 }
15190
15191 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15192 let cleared = self
15193 .display_map
15194 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15195 if cleared {
15196 cx.notify();
15197 }
15198 }
15199
15200 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15201 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15202 && self.focus_handle.is_focused(window)
15203 }
15204
15205 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15206 self.show_cursor_when_unfocused = is_enabled;
15207 cx.notify();
15208 }
15209
15210 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15211 cx.notify();
15212 }
15213
15214 fn on_buffer_event(
15215 &mut self,
15216 multibuffer: &Entity<MultiBuffer>,
15217 event: &multi_buffer::Event,
15218 window: &mut Window,
15219 cx: &mut Context<Self>,
15220 ) {
15221 match event {
15222 multi_buffer::Event::Edited {
15223 singleton_buffer_edited,
15224 edited_buffer: buffer_edited,
15225 } => {
15226 self.scrollbar_marker_state.dirty = true;
15227 self.active_indent_guides_state.dirty = true;
15228 self.refresh_active_diagnostics(cx);
15229 self.refresh_code_actions(window, cx);
15230 if self.has_active_inline_completion() {
15231 self.update_visible_inline_completion(window, cx);
15232 }
15233 if let Some(buffer) = buffer_edited {
15234 let buffer_id = buffer.read(cx).remote_id();
15235 if !self.registered_buffers.contains_key(&buffer_id) {
15236 if let Some(project) = self.project.as_ref() {
15237 project.update(cx, |project, cx| {
15238 self.registered_buffers.insert(
15239 buffer_id,
15240 project.register_buffer_with_language_servers(&buffer, cx),
15241 );
15242 })
15243 }
15244 }
15245 }
15246 cx.emit(EditorEvent::BufferEdited);
15247 cx.emit(SearchEvent::MatchesInvalidated);
15248 if *singleton_buffer_edited {
15249 if let Some(project) = &self.project {
15250 #[allow(clippy::mutable_key_type)]
15251 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15252 multibuffer
15253 .all_buffers()
15254 .into_iter()
15255 .filter_map(|buffer| {
15256 buffer.update(cx, |buffer, cx| {
15257 let language = buffer.language()?;
15258 let should_discard = project.update(cx, |project, cx| {
15259 project.is_local()
15260 && !project.has_language_servers_for(buffer, cx)
15261 });
15262 should_discard.not().then_some(language.clone())
15263 })
15264 })
15265 .collect::<HashSet<_>>()
15266 });
15267 if !languages_affected.is_empty() {
15268 self.refresh_inlay_hints(
15269 InlayHintRefreshReason::BufferEdited(languages_affected),
15270 cx,
15271 );
15272 }
15273 }
15274 }
15275
15276 let Some(project) = &self.project else { return };
15277 let (telemetry, is_via_ssh) = {
15278 let project = project.read(cx);
15279 let telemetry = project.client().telemetry().clone();
15280 let is_via_ssh = project.is_via_ssh();
15281 (telemetry, is_via_ssh)
15282 };
15283 refresh_linked_ranges(self, window, cx);
15284 telemetry.log_edit_event("editor", is_via_ssh);
15285 }
15286 multi_buffer::Event::ExcerptsAdded {
15287 buffer,
15288 predecessor,
15289 excerpts,
15290 } => {
15291 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15292 let buffer_id = buffer.read(cx).remote_id();
15293 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15294 if let Some(project) = &self.project {
15295 get_uncommitted_diff_for_buffer(
15296 project,
15297 [buffer.clone()],
15298 self.buffer.clone(),
15299 cx,
15300 )
15301 .detach();
15302 }
15303 }
15304 cx.emit(EditorEvent::ExcerptsAdded {
15305 buffer: buffer.clone(),
15306 predecessor: *predecessor,
15307 excerpts: excerpts.clone(),
15308 });
15309 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15310 }
15311 multi_buffer::Event::ExcerptsRemoved { ids } => {
15312 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15313 let buffer = self.buffer.read(cx);
15314 self.registered_buffers
15315 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15316 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15317 }
15318 multi_buffer::Event::ExcerptsEdited {
15319 excerpt_ids,
15320 buffer_ids,
15321 } => {
15322 self.display_map.update(cx, |map, cx| {
15323 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15324 });
15325 cx.emit(EditorEvent::ExcerptsEdited {
15326 ids: excerpt_ids.clone(),
15327 })
15328 }
15329 multi_buffer::Event::ExcerptsExpanded { ids } => {
15330 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15331 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15332 }
15333 multi_buffer::Event::Reparsed(buffer_id) => {
15334 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15335
15336 cx.emit(EditorEvent::Reparsed(*buffer_id));
15337 }
15338 multi_buffer::Event::DiffHunksToggled => {
15339 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15340 }
15341 multi_buffer::Event::LanguageChanged(buffer_id) => {
15342 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15343 cx.emit(EditorEvent::Reparsed(*buffer_id));
15344 cx.notify();
15345 }
15346 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15347 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15348 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15349 cx.emit(EditorEvent::TitleChanged)
15350 }
15351 // multi_buffer::Event::DiffBaseChanged => {
15352 // self.scrollbar_marker_state.dirty = true;
15353 // cx.emit(EditorEvent::DiffBaseChanged);
15354 // cx.notify();
15355 // }
15356 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15357 multi_buffer::Event::DiagnosticsUpdated => {
15358 self.refresh_active_diagnostics(cx);
15359 self.refresh_inline_diagnostics(true, window, cx);
15360 self.scrollbar_marker_state.dirty = true;
15361 cx.notify();
15362 }
15363 _ => {}
15364 };
15365 }
15366
15367 fn on_display_map_changed(
15368 &mut self,
15369 _: Entity<DisplayMap>,
15370 _: &mut Window,
15371 cx: &mut Context<Self>,
15372 ) {
15373 cx.notify();
15374 }
15375
15376 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15377 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15378 self.update_edit_prediction_settings(cx);
15379 self.refresh_inline_completion(true, false, window, cx);
15380 self.refresh_inlay_hints(
15381 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15382 self.selections.newest_anchor().head(),
15383 &self.buffer.read(cx).snapshot(cx),
15384 cx,
15385 )),
15386 cx,
15387 );
15388
15389 let old_cursor_shape = self.cursor_shape;
15390
15391 {
15392 let editor_settings = EditorSettings::get_global(cx);
15393 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15394 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15395 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15396 }
15397
15398 if old_cursor_shape != self.cursor_shape {
15399 cx.emit(EditorEvent::CursorShapeChanged);
15400 }
15401
15402 let project_settings = ProjectSettings::get_global(cx);
15403 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15404
15405 if self.mode == EditorMode::Full {
15406 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15407 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15408 if self.show_inline_diagnostics != show_inline_diagnostics {
15409 self.show_inline_diagnostics = show_inline_diagnostics;
15410 self.refresh_inline_diagnostics(false, window, cx);
15411 }
15412
15413 if self.git_blame_inline_enabled != inline_blame_enabled {
15414 self.toggle_git_blame_inline_internal(false, window, cx);
15415 }
15416 }
15417
15418 cx.notify();
15419 }
15420
15421 pub fn set_searchable(&mut self, searchable: bool) {
15422 self.searchable = searchable;
15423 }
15424
15425 pub fn searchable(&self) -> bool {
15426 self.searchable
15427 }
15428
15429 fn open_proposed_changes_editor(
15430 &mut self,
15431 _: &OpenProposedChangesEditor,
15432 window: &mut Window,
15433 cx: &mut Context<Self>,
15434 ) {
15435 let Some(workspace) = self.workspace() else {
15436 cx.propagate();
15437 return;
15438 };
15439
15440 let selections = self.selections.all::<usize>(cx);
15441 let multi_buffer = self.buffer.read(cx);
15442 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15443 let mut new_selections_by_buffer = HashMap::default();
15444 for selection in selections {
15445 for (buffer, range, _) in
15446 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15447 {
15448 let mut range = range.to_point(buffer);
15449 range.start.column = 0;
15450 range.end.column = buffer.line_len(range.end.row);
15451 new_selections_by_buffer
15452 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15453 .or_insert(Vec::new())
15454 .push(range)
15455 }
15456 }
15457
15458 let proposed_changes_buffers = new_selections_by_buffer
15459 .into_iter()
15460 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15461 .collect::<Vec<_>>();
15462 let proposed_changes_editor = cx.new(|cx| {
15463 ProposedChangesEditor::new(
15464 "Proposed changes",
15465 proposed_changes_buffers,
15466 self.project.clone(),
15467 window,
15468 cx,
15469 )
15470 });
15471
15472 window.defer(cx, move |window, cx| {
15473 workspace.update(cx, |workspace, cx| {
15474 workspace.active_pane().update(cx, |pane, cx| {
15475 pane.add_item(
15476 Box::new(proposed_changes_editor),
15477 true,
15478 true,
15479 None,
15480 window,
15481 cx,
15482 );
15483 });
15484 });
15485 });
15486 }
15487
15488 pub fn open_excerpts_in_split(
15489 &mut self,
15490 _: &OpenExcerptsSplit,
15491 window: &mut Window,
15492 cx: &mut Context<Self>,
15493 ) {
15494 self.open_excerpts_common(None, true, window, cx)
15495 }
15496
15497 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15498 self.open_excerpts_common(None, false, window, cx)
15499 }
15500
15501 fn open_excerpts_common(
15502 &mut self,
15503 jump_data: Option<JumpData>,
15504 split: bool,
15505 window: &mut Window,
15506 cx: &mut Context<Self>,
15507 ) {
15508 let Some(workspace) = self.workspace() else {
15509 cx.propagate();
15510 return;
15511 };
15512
15513 if self.buffer.read(cx).is_singleton() {
15514 cx.propagate();
15515 return;
15516 }
15517
15518 let mut new_selections_by_buffer = HashMap::default();
15519 match &jump_data {
15520 Some(JumpData::MultiBufferPoint {
15521 excerpt_id,
15522 position,
15523 anchor,
15524 line_offset_from_top,
15525 }) => {
15526 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15527 if let Some(buffer) = multi_buffer_snapshot
15528 .buffer_id_for_excerpt(*excerpt_id)
15529 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15530 {
15531 let buffer_snapshot = buffer.read(cx).snapshot();
15532 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15533 language::ToPoint::to_point(anchor, &buffer_snapshot)
15534 } else {
15535 buffer_snapshot.clip_point(*position, Bias::Left)
15536 };
15537 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15538 new_selections_by_buffer.insert(
15539 buffer,
15540 (
15541 vec![jump_to_offset..jump_to_offset],
15542 Some(*line_offset_from_top),
15543 ),
15544 );
15545 }
15546 }
15547 Some(JumpData::MultiBufferRow {
15548 row,
15549 line_offset_from_top,
15550 }) => {
15551 let point = MultiBufferPoint::new(row.0, 0);
15552 if let Some((buffer, buffer_point, _)) =
15553 self.buffer.read(cx).point_to_buffer_point(point, cx)
15554 {
15555 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15556 new_selections_by_buffer
15557 .entry(buffer)
15558 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15559 .0
15560 .push(buffer_offset..buffer_offset)
15561 }
15562 }
15563 None => {
15564 let selections = self.selections.all::<usize>(cx);
15565 let multi_buffer = self.buffer.read(cx);
15566 for selection in selections {
15567 for (snapshot, range, _, anchor) in multi_buffer
15568 .snapshot(cx)
15569 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15570 {
15571 if let Some(anchor) = anchor {
15572 // selection is in a deleted hunk
15573 let Some(buffer_id) = anchor.buffer_id else {
15574 continue;
15575 };
15576 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15577 continue;
15578 };
15579 let offset = text::ToOffset::to_offset(
15580 &anchor.text_anchor,
15581 &buffer_handle.read(cx).snapshot(),
15582 );
15583 let range = offset..offset;
15584 new_selections_by_buffer
15585 .entry(buffer_handle)
15586 .or_insert((Vec::new(), None))
15587 .0
15588 .push(range)
15589 } else {
15590 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15591 else {
15592 continue;
15593 };
15594 new_selections_by_buffer
15595 .entry(buffer_handle)
15596 .or_insert((Vec::new(), None))
15597 .0
15598 .push(range)
15599 }
15600 }
15601 }
15602 }
15603 }
15604
15605 if new_selections_by_buffer.is_empty() {
15606 return;
15607 }
15608
15609 // We defer the pane interaction because we ourselves are a workspace item
15610 // and activating a new item causes the pane to call a method on us reentrantly,
15611 // which panics if we're on the stack.
15612 window.defer(cx, move |window, cx| {
15613 workspace.update(cx, |workspace, cx| {
15614 let pane = if split {
15615 workspace.adjacent_pane(window, cx)
15616 } else {
15617 workspace.active_pane().clone()
15618 };
15619
15620 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15621 let editor = buffer
15622 .read(cx)
15623 .file()
15624 .is_none()
15625 .then(|| {
15626 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15627 // so `workspace.open_project_item` will never find them, always opening a new editor.
15628 // Instead, we try to activate the existing editor in the pane first.
15629 let (editor, pane_item_index) =
15630 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15631 let editor = item.downcast::<Editor>()?;
15632 let singleton_buffer =
15633 editor.read(cx).buffer().read(cx).as_singleton()?;
15634 if singleton_buffer == buffer {
15635 Some((editor, i))
15636 } else {
15637 None
15638 }
15639 })?;
15640 pane.update(cx, |pane, cx| {
15641 pane.activate_item(pane_item_index, true, true, window, cx)
15642 });
15643 Some(editor)
15644 })
15645 .flatten()
15646 .unwrap_or_else(|| {
15647 workspace.open_project_item::<Self>(
15648 pane.clone(),
15649 buffer,
15650 true,
15651 true,
15652 window,
15653 cx,
15654 )
15655 });
15656
15657 editor.update(cx, |editor, cx| {
15658 let autoscroll = match scroll_offset {
15659 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15660 None => Autoscroll::newest(),
15661 };
15662 let nav_history = editor.nav_history.take();
15663 editor.change_selections(Some(autoscroll), window, cx, |s| {
15664 s.select_ranges(ranges);
15665 });
15666 editor.nav_history = nav_history;
15667 });
15668 }
15669 })
15670 });
15671 }
15672
15673 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15674 let snapshot = self.buffer.read(cx).read(cx);
15675 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15676 Some(
15677 ranges
15678 .iter()
15679 .map(move |range| {
15680 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15681 })
15682 .collect(),
15683 )
15684 }
15685
15686 fn selection_replacement_ranges(
15687 &self,
15688 range: Range<OffsetUtf16>,
15689 cx: &mut App,
15690 ) -> Vec<Range<OffsetUtf16>> {
15691 let selections = self.selections.all::<OffsetUtf16>(cx);
15692 let newest_selection = selections
15693 .iter()
15694 .max_by_key(|selection| selection.id)
15695 .unwrap();
15696 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15697 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15698 let snapshot = self.buffer.read(cx).read(cx);
15699 selections
15700 .into_iter()
15701 .map(|mut selection| {
15702 selection.start.0 =
15703 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15704 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15705 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15706 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15707 })
15708 .collect()
15709 }
15710
15711 fn report_editor_event(
15712 &self,
15713 event_type: &'static str,
15714 file_extension: Option<String>,
15715 cx: &App,
15716 ) {
15717 if cfg!(any(test, feature = "test-support")) {
15718 return;
15719 }
15720
15721 let Some(project) = &self.project else { return };
15722
15723 // If None, we are in a file without an extension
15724 let file = self
15725 .buffer
15726 .read(cx)
15727 .as_singleton()
15728 .and_then(|b| b.read(cx).file());
15729 let file_extension = file_extension.or(file
15730 .as_ref()
15731 .and_then(|file| Path::new(file.file_name(cx)).extension())
15732 .and_then(|e| e.to_str())
15733 .map(|a| a.to_string()));
15734
15735 let vim_mode = cx
15736 .global::<SettingsStore>()
15737 .raw_user_settings()
15738 .get("vim_mode")
15739 == Some(&serde_json::Value::Bool(true));
15740
15741 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15742 let copilot_enabled = edit_predictions_provider
15743 == language::language_settings::EditPredictionProvider::Copilot;
15744 let copilot_enabled_for_language = self
15745 .buffer
15746 .read(cx)
15747 .settings_at(0, cx)
15748 .show_edit_predictions;
15749
15750 let project = project.read(cx);
15751 telemetry::event!(
15752 event_type,
15753 file_extension,
15754 vim_mode,
15755 copilot_enabled,
15756 copilot_enabled_for_language,
15757 edit_predictions_provider,
15758 is_via_ssh = project.is_via_ssh(),
15759 );
15760 }
15761
15762 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15763 /// with each line being an array of {text, highlight} objects.
15764 fn copy_highlight_json(
15765 &mut self,
15766 _: &CopyHighlightJson,
15767 window: &mut Window,
15768 cx: &mut Context<Self>,
15769 ) {
15770 #[derive(Serialize)]
15771 struct Chunk<'a> {
15772 text: String,
15773 highlight: Option<&'a str>,
15774 }
15775
15776 let snapshot = self.buffer.read(cx).snapshot(cx);
15777 let range = self
15778 .selected_text_range(false, window, cx)
15779 .and_then(|selection| {
15780 if selection.range.is_empty() {
15781 None
15782 } else {
15783 Some(selection.range)
15784 }
15785 })
15786 .unwrap_or_else(|| 0..snapshot.len());
15787
15788 let chunks = snapshot.chunks(range, true);
15789 let mut lines = Vec::new();
15790 let mut line: VecDeque<Chunk> = VecDeque::new();
15791
15792 let Some(style) = self.style.as_ref() else {
15793 return;
15794 };
15795
15796 for chunk in chunks {
15797 let highlight = chunk
15798 .syntax_highlight_id
15799 .and_then(|id| id.name(&style.syntax));
15800 let mut chunk_lines = chunk.text.split('\n').peekable();
15801 while let Some(text) = chunk_lines.next() {
15802 let mut merged_with_last_token = false;
15803 if let Some(last_token) = line.back_mut() {
15804 if last_token.highlight == highlight {
15805 last_token.text.push_str(text);
15806 merged_with_last_token = true;
15807 }
15808 }
15809
15810 if !merged_with_last_token {
15811 line.push_back(Chunk {
15812 text: text.into(),
15813 highlight,
15814 });
15815 }
15816
15817 if chunk_lines.peek().is_some() {
15818 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15819 line.pop_front();
15820 }
15821 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15822 line.pop_back();
15823 }
15824
15825 lines.push(mem::take(&mut line));
15826 }
15827 }
15828 }
15829
15830 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15831 return;
15832 };
15833 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15834 }
15835
15836 pub fn open_context_menu(
15837 &mut self,
15838 _: &OpenContextMenu,
15839 window: &mut Window,
15840 cx: &mut Context<Self>,
15841 ) {
15842 self.request_autoscroll(Autoscroll::newest(), cx);
15843 let position = self.selections.newest_display(cx).start;
15844 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15845 }
15846
15847 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15848 &self.inlay_hint_cache
15849 }
15850
15851 pub fn replay_insert_event(
15852 &mut self,
15853 text: &str,
15854 relative_utf16_range: Option<Range<isize>>,
15855 window: &mut Window,
15856 cx: &mut Context<Self>,
15857 ) {
15858 if !self.input_enabled {
15859 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15860 return;
15861 }
15862 if let Some(relative_utf16_range) = relative_utf16_range {
15863 let selections = self.selections.all::<OffsetUtf16>(cx);
15864 self.change_selections(None, window, cx, |s| {
15865 let new_ranges = selections.into_iter().map(|range| {
15866 let start = OffsetUtf16(
15867 range
15868 .head()
15869 .0
15870 .saturating_add_signed(relative_utf16_range.start),
15871 );
15872 let end = OffsetUtf16(
15873 range
15874 .head()
15875 .0
15876 .saturating_add_signed(relative_utf16_range.end),
15877 );
15878 start..end
15879 });
15880 s.select_ranges(new_ranges);
15881 });
15882 }
15883
15884 self.handle_input(text, window, cx);
15885 }
15886
15887 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15888 let Some(provider) = self.semantics_provider.as_ref() else {
15889 return false;
15890 };
15891
15892 let mut supports = false;
15893 self.buffer().update(cx, |this, cx| {
15894 this.for_each_buffer(|buffer| {
15895 supports |= provider.supports_inlay_hints(buffer, cx);
15896 });
15897 });
15898
15899 supports
15900 }
15901
15902 pub fn is_focused(&self, window: &Window) -> bool {
15903 self.focus_handle.is_focused(window)
15904 }
15905
15906 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15907 cx.emit(EditorEvent::Focused);
15908
15909 if let Some(descendant) = self
15910 .last_focused_descendant
15911 .take()
15912 .and_then(|descendant| descendant.upgrade())
15913 {
15914 window.focus(&descendant);
15915 } else {
15916 if let Some(blame) = self.blame.as_ref() {
15917 blame.update(cx, GitBlame::focus)
15918 }
15919
15920 self.blink_manager.update(cx, BlinkManager::enable);
15921 self.show_cursor_names(window, cx);
15922 self.buffer.update(cx, |buffer, cx| {
15923 buffer.finalize_last_transaction(cx);
15924 if self.leader_peer_id.is_none() {
15925 buffer.set_active_selections(
15926 &self.selections.disjoint_anchors(),
15927 self.selections.line_mode,
15928 self.cursor_shape,
15929 cx,
15930 );
15931 }
15932 });
15933 }
15934 }
15935
15936 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15937 cx.emit(EditorEvent::FocusedIn)
15938 }
15939
15940 fn handle_focus_out(
15941 &mut self,
15942 event: FocusOutEvent,
15943 _window: &mut Window,
15944 cx: &mut Context<Self>,
15945 ) {
15946 if event.blurred != self.focus_handle {
15947 self.last_focused_descendant = Some(event.blurred);
15948 }
15949 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
15950 }
15951
15952 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15953 self.blink_manager.update(cx, BlinkManager::disable);
15954 self.buffer
15955 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15956
15957 if let Some(blame) = self.blame.as_ref() {
15958 blame.update(cx, GitBlame::blur)
15959 }
15960 if !self.hover_state.focused(window, cx) {
15961 hide_hover(self, cx);
15962 }
15963 if !self
15964 .context_menu
15965 .borrow()
15966 .as_ref()
15967 .is_some_and(|context_menu| context_menu.focused(window, cx))
15968 {
15969 self.hide_context_menu(window, cx);
15970 }
15971 self.discard_inline_completion(false, cx);
15972 cx.emit(EditorEvent::Blurred);
15973 cx.notify();
15974 }
15975
15976 pub fn register_action<A: Action>(
15977 &mut self,
15978 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15979 ) -> Subscription {
15980 let id = self.next_editor_action_id.post_inc();
15981 let listener = Arc::new(listener);
15982 self.editor_actions.borrow_mut().insert(
15983 id,
15984 Box::new(move |window, _| {
15985 let listener = listener.clone();
15986 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15987 let action = action.downcast_ref().unwrap();
15988 if phase == DispatchPhase::Bubble {
15989 listener(action, window, cx)
15990 }
15991 })
15992 }),
15993 );
15994
15995 let editor_actions = self.editor_actions.clone();
15996 Subscription::new(move || {
15997 editor_actions.borrow_mut().remove(&id);
15998 })
15999 }
16000
16001 pub fn file_header_size(&self) -> u32 {
16002 FILE_HEADER_HEIGHT
16003 }
16004
16005 pub fn restore(
16006 &mut self,
16007 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16008 window: &mut Window,
16009 cx: &mut Context<Self>,
16010 ) {
16011 let workspace = self.workspace();
16012 let project = self.project.as_ref();
16013 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16014 let mut tasks = Vec::new();
16015 for (buffer_id, changes) in revert_changes {
16016 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16017 buffer.update(cx, |buffer, cx| {
16018 buffer.edit(
16019 changes
16020 .into_iter()
16021 .map(|(range, text)| (range, text.to_string())),
16022 None,
16023 cx,
16024 );
16025 });
16026
16027 if let Some(project) =
16028 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16029 {
16030 project.update(cx, |project, cx| {
16031 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16032 })
16033 }
16034 }
16035 }
16036 tasks
16037 });
16038 cx.spawn_in(window, |_, mut cx| async move {
16039 for (buffer, task) in save_tasks {
16040 let result = task.await;
16041 if result.is_err() {
16042 let Some(path) = buffer
16043 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16044 .ok()
16045 else {
16046 continue;
16047 };
16048 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16049 let Some(task) = cx
16050 .update_window_entity(&workspace, |workspace, window, cx| {
16051 workspace
16052 .open_path_preview(path, None, false, false, false, window, cx)
16053 })
16054 .ok()
16055 else {
16056 continue;
16057 };
16058 task.await.log_err();
16059 }
16060 }
16061 }
16062 })
16063 .detach();
16064 self.change_selections(None, window, cx, |selections| selections.refresh());
16065 }
16066
16067 pub fn to_pixel_point(
16068 &self,
16069 source: multi_buffer::Anchor,
16070 editor_snapshot: &EditorSnapshot,
16071 window: &mut Window,
16072 ) -> Option<gpui::Point<Pixels>> {
16073 let source_point = source.to_display_point(editor_snapshot);
16074 self.display_to_pixel_point(source_point, editor_snapshot, window)
16075 }
16076
16077 pub fn display_to_pixel_point(
16078 &self,
16079 source: DisplayPoint,
16080 editor_snapshot: &EditorSnapshot,
16081 window: &mut Window,
16082 ) -> Option<gpui::Point<Pixels>> {
16083 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16084 let text_layout_details = self.text_layout_details(window);
16085 let scroll_top = text_layout_details
16086 .scroll_anchor
16087 .scroll_position(editor_snapshot)
16088 .y;
16089
16090 if source.row().as_f32() < scroll_top.floor() {
16091 return None;
16092 }
16093 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16094 let source_y = line_height * (source.row().as_f32() - scroll_top);
16095 Some(gpui::Point::new(source_x, source_y))
16096 }
16097
16098 pub fn has_visible_completions_menu(&self) -> bool {
16099 !self.edit_prediction_preview_is_active()
16100 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16101 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16102 })
16103 }
16104
16105 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16106 self.addons
16107 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16108 }
16109
16110 pub fn unregister_addon<T: Addon>(&mut self) {
16111 self.addons.remove(&std::any::TypeId::of::<T>());
16112 }
16113
16114 pub fn addon<T: Addon>(&self) -> Option<&T> {
16115 let type_id = std::any::TypeId::of::<T>();
16116 self.addons
16117 .get(&type_id)
16118 .and_then(|item| item.to_any().downcast_ref::<T>())
16119 }
16120
16121 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16122 let text_layout_details = self.text_layout_details(window);
16123 let style = &text_layout_details.editor_style;
16124 let font_id = window.text_system().resolve_font(&style.text.font());
16125 let font_size = style.text.font_size.to_pixels(window.rem_size());
16126 let line_height = style.text.line_height_in_pixels(window.rem_size());
16127 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16128
16129 gpui::Size::new(em_width, line_height)
16130 }
16131
16132 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16133 self.load_diff_task.clone()
16134 }
16135
16136 fn read_selections_from_db(
16137 &mut self,
16138 item_id: u64,
16139 workspace_id: WorkspaceId,
16140 window: &mut Window,
16141 cx: &mut Context<Editor>,
16142 ) {
16143 if !self.is_singleton(cx)
16144 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16145 {
16146 return;
16147 }
16148 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16149 return;
16150 };
16151 if selections.is_empty() {
16152 return;
16153 }
16154
16155 let snapshot = self.buffer.read(cx).snapshot(cx);
16156 self.change_selections(None, window, cx, |s| {
16157 s.select_ranges(selections.into_iter().map(|(start, end)| {
16158 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16159 }));
16160 });
16161 }
16162}
16163
16164fn insert_extra_newline_brackets(
16165 buffer: &MultiBufferSnapshot,
16166 range: Range<usize>,
16167 language: &language::LanguageScope,
16168) -> bool {
16169 let leading_whitespace_len = buffer
16170 .reversed_chars_at(range.start)
16171 .take_while(|c| c.is_whitespace() && *c != '\n')
16172 .map(|c| c.len_utf8())
16173 .sum::<usize>();
16174 let trailing_whitespace_len = buffer
16175 .chars_at(range.end)
16176 .take_while(|c| c.is_whitespace() && *c != '\n')
16177 .map(|c| c.len_utf8())
16178 .sum::<usize>();
16179 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16180
16181 language.brackets().any(|(pair, enabled)| {
16182 let pair_start = pair.start.trim_end();
16183 let pair_end = pair.end.trim_start();
16184
16185 enabled
16186 && pair.newline
16187 && buffer.contains_str_at(range.end, pair_end)
16188 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16189 })
16190}
16191
16192fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16193 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16194 [(buffer, range, _)] => (*buffer, range.clone()),
16195 _ => return false,
16196 };
16197 let pair = {
16198 let mut result: Option<BracketMatch> = None;
16199
16200 for pair in buffer
16201 .all_bracket_ranges(range.clone())
16202 .filter(move |pair| {
16203 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16204 })
16205 {
16206 let len = pair.close_range.end - pair.open_range.start;
16207
16208 if let Some(existing) = &result {
16209 let existing_len = existing.close_range.end - existing.open_range.start;
16210 if len > existing_len {
16211 continue;
16212 }
16213 }
16214
16215 result = Some(pair);
16216 }
16217
16218 result
16219 };
16220 let Some(pair) = pair else {
16221 return false;
16222 };
16223 pair.newline_only
16224 && buffer
16225 .chars_for_range(pair.open_range.end..range.start)
16226 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16227 .all(|c| c.is_whitespace() && c != '\n')
16228}
16229
16230fn get_uncommitted_diff_for_buffer(
16231 project: &Entity<Project>,
16232 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16233 buffer: Entity<MultiBuffer>,
16234 cx: &mut App,
16235) -> Task<()> {
16236 let mut tasks = Vec::new();
16237 project.update(cx, |project, cx| {
16238 for buffer in buffers {
16239 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16240 }
16241 });
16242 cx.spawn(|mut cx| async move {
16243 let diffs = future::join_all(tasks).await;
16244 buffer
16245 .update(&mut cx, |buffer, cx| {
16246 for diff in diffs.into_iter().flatten() {
16247 buffer.add_diff(diff, cx);
16248 }
16249 })
16250 .ok();
16251 })
16252}
16253
16254fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16255 let tab_size = tab_size.get() as usize;
16256 let mut width = offset;
16257
16258 for ch in text.chars() {
16259 width += if ch == '\t' {
16260 tab_size - (width % tab_size)
16261 } else {
16262 1
16263 };
16264 }
16265
16266 width - offset
16267}
16268
16269#[cfg(test)]
16270mod tests {
16271 use super::*;
16272
16273 #[test]
16274 fn test_string_size_with_expanded_tabs() {
16275 let nz = |val| NonZeroU32::new(val).unwrap();
16276 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16277 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16278 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16279 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16280 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16281 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16282 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16283 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16284 }
16285}
16286
16287/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16288struct WordBreakingTokenizer<'a> {
16289 input: &'a str,
16290}
16291
16292impl<'a> WordBreakingTokenizer<'a> {
16293 fn new(input: &'a str) -> Self {
16294 Self { input }
16295 }
16296}
16297
16298fn is_char_ideographic(ch: char) -> bool {
16299 use unicode_script::Script::*;
16300 use unicode_script::UnicodeScript;
16301 matches!(ch.script(), Han | Tangut | Yi)
16302}
16303
16304fn is_grapheme_ideographic(text: &str) -> bool {
16305 text.chars().any(is_char_ideographic)
16306}
16307
16308fn is_grapheme_whitespace(text: &str) -> bool {
16309 text.chars().any(|x| x.is_whitespace())
16310}
16311
16312fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16313 text.chars().next().map_or(false, |ch| {
16314 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16315 })
16316}
16317
16318#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16319struct WordBreakToken<'a> {
16320 token: &'a str,
16321 grapheme_len: usize,
16322 is_whitespace: bool,
16323}
16324
16325impl<'a> Iterator for WordBreakingTokenizer<'a> {
16326 /// Yields a span, the count of graphemes in the token, and whether it was
16327 /// whitespace. Note that it also breaks at word boundaries.
16328 type Item = WordBreakToken<'a>;
16329
16330 fn next(&mut self) -> Option<Self::Item> {
16331 use unicode_segmentation::UnicodeSegmentation;
16332 if self.input.is_empty() {
16333 return None;
16334 }
16335
16336 let mut iter = self.input.graphemes(true).peekable();
16337 let mut offset = 0;
16338 let mut graphemes = 0;
16339 if let Some(first_grapheme) = iter.next() {
16340 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16341 offset += first_grapheme.len();
16342 graphemes += 1;
16343 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16344 if let Some(grapheme) = iter.peek().copied() {
16345 if should_stay_with_preceding_ideograph(grapheme) {
16346 offset += grapheme.len();
16347 graphemes += 1;
16348 }
16349 }
16350 } else {
16351 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16352 let mut next_word_bound = words.peek().copied();
16353 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16354 next_word_bound = words.next();
16355 }
16356 while let Some(grapheme) = iter.peek().copied() {
16357 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16358 break;
16359 };
16360 if is_grapheme_whitespace(grapheme) != is_whitespace {
16361 break;
16362 };
16363 offset += grapheme.len();
16364 graphemes += 1;
16365 iter.next();
16366 }
16367 }
16368 let token = &self.input[..offset];
16369 self.input = &self.input[offset..];
16370 if is_whitespace {
16371 Some(WordBreakToken {
16372 token: " ",
16373 grapheme_len: 1,
16374 is_whitespace: true,
16375 })
16376 } else {
16377 Some(WordBreakToken {
16378 token,
16379 grapheme_len: graphemes,
16380 is_whitespace: false,
16381 })
16382 }
16383 } else {
16384 None
16385 }
16386 }
16387}
16388
16389#[test]
16390fn test_word_breaking_tokenizer() {
16391 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16392 ("", &[]),
16393 (" ", &[(" ", 1, true)]),
16394 ("Ʒ", &[("Ʒ", 1, false)]),
16395 ("Ǽ", &[("Ǽ", 1, false)]),
16396 ("⋑", &[("⋑", 1, false)]),
16397 ("⋑⋑", &[("⋑⋑", 2, false)]),
16398 (
16399 "原理,进而",
16400 &[
16401 ("原", 1, false),
16402 ("理,", 2, false),
16403 ("进", 1, false),
16404 ("而", 1, false),
16405 ],
16406 ),
16407 (
16408 "hello world",
16409 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16410 ),
16411 (
16412 "hello, world",
16413 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16414 ),
16415 (
16416 " hello world",
16417 &[
16418 (" ", 1, true),
16419 ("hello", 5, false),
16420 (" ", 1, true),
16421 ("world", 5, false),
16422 ],
16423 ),
16424 (
16425 "这是什么 \n 钢笔",
16426 &[
16427 ("这", 1, false),
16428 ("是", 1, false),
16429 ("什", 1, false),
16430 ("么", 1, false),
16431 (" ", 1, true),
16432 ("钢", 1, false),
16433 ("笔", 1, false),
16434 ],
16435 ),
16436 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16437 ];
16438
16439 for (input, result) in tests {
16440 assert_eq!(
16441 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16442 result
16443 .iter()
16444 .copied()
16445 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16446 token,
16447 grapheme_len,
16448 is_whitespace,
16449 })
16450 .collect::<Vec<_>>()
16451 );
16452 }
16453}
16454
16455fn wrap_with_prefix(
16456 line_prefix: String,
16457 unwrapped_text: String,
16458 wrap_column: usize,
16459 tab_size: NonZeroU32,
16460) -> String {
16461 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16462 let mut wrapped_text = String::new();
16463 let mut current_line = line_prefix.clone();
16464
16465 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16466 let mut current_line_len = line_prefix_len;
16467 for WordBreakToken {
16468 token,
16469 grapheme_len,
16470 is_whitespace,
16471 } in tokenizer
16472 {
16473 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16474 wrapped_text.push_str(current_line.trim_end());
16475 wrapped_text.push('\n');
16476 current_line.truncate(line_prefix.len());
16477 current_line_len = line_prefix_len;
16478 if !is_whitespace {
16479 current_line.push_str(token);
16480 current_line_len += grapheme_len;
16481 }
16482 } else if !is_whitespace {
16483 current_line.push_str(token);
16484 current_line_len += grapheme_len;
16485 } else if current_line_len != line_prefix_len {
16486 current_line.push(' ');
16487 current_line_len += 1;
16488 }
16489 }
16490
16491 if !current_line.is_empty() {
16492 wrapped_text.push_str(¤t_line);
16493 }
16494 wrapped_text
16495}
16496
16497#[test]
16498fn test_wrap_with_prefix() {
16499 assert_eq!(
16500 wrap_with_prefix(
16501 "# ".to_string(),
16502 "abcdefg".to_string(),
16503 4,
16504 NonZeroU32::new(4).unwrap()
16505 ),
16506 "# abcdefg"
16507 );
16508 assert_eq!(
16509 wrap_with_prefix(
16510 "".to_string(),
16511 "\thello world".to_string(),
16512 8,
16513 NonZeroU32::new(4).unwrap()
16514 ),
16515 "hello\nworld"
16516 );
16517 assert_eq!(
16518 wrap_with_prefix(
16519 "// ".to_string(),
16520 "xx \nyy zz aa bb cc".to_string(),
16521 12,
16522 NonZeroU32::new(4).unwrap()
16523 ),
16524 "// xx yy zz\n// aa bb cc"
16525 );
16526 assert_eq!(
16527 wrap_with_prefix(
16528 String::new(),
16529 "这是什么 \n 钢笔".to_string(),
16530 3,
16531 NonZeroU32::new(4).unwrap()
16532 ),
16533 "这是什\n么 钢\n笔"
16534 );
16535}
16536
16537pub trait CollaborationHub {
16538 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16539 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16540 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16541}
16542
16543impl CollaborationHub for Entity<Project> {
16544 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16545 self.read(cx).collaborators()
16546 }
16547
16548 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16549 self.read(cx).user_store().read(cx).participant_indices()
16550 }
16551
16552 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16553 let this = self.read(cx);
16554 let user_ids = this.collaborators().values().map(|c| c.user_id);
16555 this.user_store().read_with(cx, |user_store, cx| {
16556 user_store.participant_names(user_ids, cx)
16557 })
16558 }
16559}
16560
16561pub trait SemanticsProvider {
16562 fn hover(
16563 &self,
16564 buffer: &Entity<Buffer>,
16565 position: text::Anchor,
16566 cx: &mut App,
16567 ) -> Option<Task<Vec<project::Hover>>>;
16568
16569 fn inlay_hints(
16570 &self,
16571 buffer_handle: Entity<Buffer>,
16572 range: Range<text::Anchor>,
16573 cx: &mut App,
16574 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16575
16576 fn resolve_inlay_hint(
16577 &self,
16578 hint: InlayHint,
16579 buffer_handle: Entity<Buffer>,
16580 server_id: LanguageServerId,
16581 cx: &mut App,
16582 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16583
16584 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16585
16586 fn document_highlights(
16587 &self,
16588 buffer: &Entity<Buffer>,
16589 position: text::Anchor,
16590 cx: &mut App,
16591 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16592
16593 fn definitions(
16594 &self,
16595 buffer: &Entity<Buffer>,
16596 position: text::Anchor,
16597 kind: GotoDefinitionKind,
16598 cx: &mut App,
16599 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16600
16601 fn range_for_rename(
16602 &self,
16603 buffer: &Entity<Buffer>,
16604 position: text::Anchor,
16605 cx: &mut App,
16606 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16607
16608 fn perform_rename(
16609 &self,
16610 buffer: &Entity<Buffer>,
16611 position: text::Anchor,
16612 new_name: String,
16613 cx: &mut App,
16614 ) -> Option<Task<Result<ProjectTransaction>>>;
16615}
16616
16617pub trait CompletionProvider {
16618 fn completions(
16619 &self,
16620 buffer: &Entity<Buffer>,
16621 buffer_position: text::Anchor,
16622 trigger: CompletionContext,
16623 window: &mut Window,
16624 cx: &mut Context<Editor>,
16625 ) -> Task<Result<Vec<Completion>>>;
16626
16627 fn resolve_completions(
16628 &self,
16629 buffer: Entity<Buffer>,
16630 completion_indices: Vec<usize>,
16631 completions: Rc<RefCell<Box<[Completion]>>>,
16632 cx: &mut Context<Editor>,
16633 ) -> Task<Result<bool>>;
16634
16635 fn apply_additional_edits_for_completion(
16636 &self,
16637 _buffer: Entity<Buffer>,
16638 _completions: Rc<RefCell<Box<[Completion]>>>,
16639 _completion_index: usize,
16640 _push_to_history: bool,
16641 _cx: &mut Context<Editor>,
16642 ) -> Task<Result<Option<language::Transaction>>> {
16643 Task::ready(Ok(None))
16644 }
16645
16646 fn is_completion_trigger(
16647 &self,
16648 buffer: &Entity<Buffer>,
16649 position: language::Anchor,
16650 text: &str,
16651 trigger_in_words: bool,
16652 cx: &mut Context<Editor>,
16653 ) -> bool;
16654
16655 fn sort_completions(&self) -> bool {
16656 true
16657 }
16658}
16659
16660pub trait CodeActionProvider {
16661 fn id(&self) -> Arc<str>;
16662
16663 fn code_actions(
16664 &self,
16665 buffer: &Entity<Buffer>,
16666 range: Range<text::Anchor>,
16667 window: &mut Window,
16668 cx: &mut App,
16669 ) -> Task<Result<Vec<CodeAction>>>;
16670
16671 fn apply_code_action(
16672 &self,
16673 buffer_handle: Entity<Buffer>,
16674 action: CodeAction,
16675 excerpt_id: ExcerptId,
16676 push_to_history: bool,
16677 window: &mut Window,
16678 cx: &mut App,
16679 ) -> Task<Result<ProjectTransaction>>;
16680}
16681
16682impl CodeActionProvider for Entity<Project> {
16683 fn id(&self) -> Arc<str> {
16684 "project".into()
16685 }
16686
16687 fn code_actions(
16688 &self,
16689 buffer: &Entity<Buffer>,
16690 range: Range<text::Anchor>,
16691 _window: &mut Window,
16692 cx: &mut App,
16693 ) -> Task<Result<Vec<CodeAction>>> {
16694 self.update(cx, |project, cx| {
16695 project.code_actions(buffer, range, None, cx)
16696 })
16697 }
16698
16699 fn apply_code_action(
16700 &self,
16701 buffer_handle: Entity<Buffer>,
16702 action: CodeAction,
16703 _excerpt_id: ExcerptId,
16704 push_to_history: bool,
16705 _window: &mut Window,
16706 cx: &mut App,
16707 ) -> Task<Result<ProjectTransaction>> {
16708 self.update(cx, |project, cx| {
16709 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16710 })
16711 }
16712}
16713
16714fn snippet_completions(
16715 project: &Project,
16716 buffer: &Entity<Buffer>,
16717 buffer_position: text::Anchor,
16718 cx: &mut App,
16719) -> Task<Result<Vec<Completion>>> {
16720 let language = buffer.read(cx).language_at(buffer_position);
16721 let language_name = language.as_ref().map(|language| language.lsp_id());
16722 let snippet_store = project.snippets().read(cx);
16723 let snippets = snippet_store.snippets_for(language_name, cx);
16724
16725 if snippets.is_empty() {
16726 return Task::ready(Ok(vec![]));
16727 }
16728 let snapshot = buffer.read(cx).text_snapshot();
16729 let chars: String = snapshot
16730 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16731 .collect();
16732
16733 let scope = language.map(|language| language.default_scope());
16734 let executor = cx.background_executor().clone();
16735
16736 cx.background_spawn(async move {
16737 let classifier = CharClassifier::new(scope).for_completion(true);
16738 let mut last_word = chars
16739 .chars()
16740 .take_while(|c| classifier.is_word(*c))
16741 .collect::<String>();
16742 last_word = last_word.chars().rev().collect();
16743
16744 if last_word.is_empty() {
16745 return Ok(vec![]);
16746 }
16747
16748 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16749 let to_lsp = |point: &text::Anchor| {
16750 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16751 point_to_lsp(end)
16752 };
16753 let lsp_end = to_lsp(&buffer_position);
16754
16755 let candidates = snippets
16756 .iter()
16757 .enumerate()
16758 .flat_map(|(ix, snippet)| {
16759 snippet
16760 .prefix
16761 .iter()
16762 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16763 })
16764 .collect::<Vec<StringMatchCandidate>>();
16765
16766 let mut matches = fuzzy::match_strings(
16767 &candidates,
16768 &last_word,
16769 last_word.chars().any(|c| c.is_uppercase()),
16770 100,
16771 &Default::default(),
16772 executor,
16773 )
16774 .await;
16775
16776 // Remove all candidates where the query's start does not match the start of any word in the candidate
16777 if let Some(query_start) = last_word.chars().next() {
16778 matches.retain(|string_match| {
16779 split_words(&string_match.string).any(|word| {
16780 // Check that the first codepoint of the word as lowercase matches the first
16781 // codepoint of the query as lowercase
16782 word.chars()
16783 .flat_map(|codepoint| codepoint.to_lowercase())
16784 .zip(query_start.to_lowercase())
16785 .all(|(word_cp, query_cp)| word_cp == query_cp)
16786 })
16787 });
16788 }
16789
16790 let matched_strings = matches
16791 .into_iter()
16792 .map(|m| m.string)
16793 .collect::<HashSet<_>>();
16794
16795 let result: Vec<Completion> = snippets
16796 .into_iter()
16797 .filter_map(|snippet| {
16798 let matching_prefix = snippet
16799 .prefix
16800 .iter()
16801 .find(|prefix| matched_strings.contains(*prefix))?;
16802 let start = as_offset - last_word.len();
16803 let start = snapshot.anchor_before(start);
16804 let range = start..buffer_position;
16805 let lsp_start = to_lsp(&start);
16806 let lsp_range = lsp::Range {
16807 start: lsp_start,
16808 end: lsp_end,
16809 };
16810 Some(Completion {
16811 old_range: range,
16812 new_text: snippet.body.clone(),
16813 resolved: false,
16814 label: CodeLabel {
16815 text: matching_prefix.clone(),
16816 runs: vec![],
16817 filter_range: 0..matching_prefix.len(),
16818 },
16819 server_id: LanguageServerId(usize::MAX),
16820 documentation: snippet
16821 .description
16822 .clone()
16823 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16824 lsp_completion: lsp::CompletionItem {
16825 label: snippet.prefix.first().unwrap().clone(),
16826 kind: Some(CompletionItemKind::SNIPPET),
16827 label_details: snippet.description.as_ref().map(|description| {
16828 lsp::CompletionItemLabelDetails {
16829 detail: Some(description.clone()),
16830 description: None,
16831 }
16832 }),
16833 insert_text_format: Some(InsertTextFormat::SNIPPET),
16834 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16835 lsp::InsertReplaceEdit {
16836 new_text: snippet.body.clone(),
16837 insert: lsp_range,
16838 replace: lsp_range,
16839 },
16840 )),
16841 filter_text: Some(snippet.body.clone()),
16842 sort_text: Some(char::MAX.to_string()),
16843 ..Default::default()
16844 },
16845 confirm: None,
16846 })
16847 })
16848 .collect();
16849
16850 Ok(result)
16851 })
16852}
16853
16854impl CompletionProvider for Entity<Project> {
16855 fn completions(
16856 &self,
16857 buffer: &Entity<Buffer>,
16858 buffer_position: text::Anchor,
16859 options: CompletionContext,
16860 _window: &mut Window,
16861 cx: &mut Context<Editor>,
16862 ) -> Task<Result<Vec<Completion>>> {
16863 self.update(cx, |project, cx| {
16864 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16865 let project_completions = project.completions(buffer, buffer_position, options, cx);
16866 cx.background_spawn(async move {
16867 let mut completions = project_completions.await?;
16868 let snippets_completions = snippets.await?;
16869 completions.extend(snippets_completions);
16870 Ok(completions)
16871 })
16872 })
16873 }
16874
16875 fn resolve_completions(
16876 &self,
16877 buffer: Entity<Buffer>,
16878 completion_indices: Vec<usize>,
16879 completions: Rc<RefCell<Box<[Completion]>>>,
16880 cx: &mut Context<Editor>,
16881 ) -> Task<Result<bool>> {
16882 self.update(cx, |project, cx| {
16883 project.lsp_store().update(cx, |lsp_store, cx| {
16884 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16885 })
16886 })
16887 }
16888
16889 fn apply_additional_edits_for_completion(
16890 &self,
16891 buffer: Entity<Buffer>,
16892 completions: Rc<RefCell<Box<[Completion]>>>,
16893 completion_index: usize,
16894 push_to_history: bool,
16895 cx: &mut Context<Editor>,
16896 ) -> Task<Result<Option<language::Transaction>>> {
16897 self.update(cx, |project, cx| {
16898 project.lsp_store().update(cx, |lsp_store, cx| {
16899 lsp_store.apply_additional_edits_for_completion(
16900 buffer,
16901 completions,
16902 completion_index,
16903 push_to_history,
16904 cx,
16905 )
16906 })
16907 })
16908 }
16909
16910 fn is_completion_trigger(
16911 &self,
16912 buffer: &Entity<Buffer>,
16913 position: language::Anchor,
16914 text: &str,
16915 trigger_in_words: bool,
16916 cx: &mut Context<Editor>,
16917 ) -> bool {
16918 let mut chars = text.chars();
16919 let char = if let Some(char) = chars.next() {
16920 char
16921 } else {
16922 return false;
16923 };
16924 if chars.next().is_some() {
16925 return false;
16926 }
16927
16928 let buffer = buffer.read(cx);
16929 let snapshot = buffer.snapshot();
16930 if !snapshot.settings_at(position, cx).show_completions_on_input {
16931 return false;
16932 }
16933 let classifier = snapshot.char_classifier_at(position).for_completion(true);
16934 if trigger_in_words && classifier.is_word(char) {
16935 return true;
16936 }
16937
16938 buffer.completion_triggers().contains(text)
16939 }
16940}
16941
16942impl SemanticsProvider for Entity<Project> {
16943 fn hover(
16944 &self,
16945 buffer: &Entity<Buffer>,
16946 position: text::Anchor,
16947 cx: &mut App,
16948 ) -> Option<Task<Vec<project::Hover>>> {
16949 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16950 }
16951
16952 fn document_highlights(
16953 &self,
16954 buffer: &Entity<Buffer>,
16955 position: text::Anchor,
16956 cx: &mut App,
16957 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16958 Some(self.update(cx, |project, cx| {
16959 project.document_highlights(buffer, position, cx)
16960 }))
16961 }
16962
16963 fn definitions(
16964 &self,
16965 buffer: &Entity<Buffer>,
16966 position: text::Anchor,
16967 kind: GotoDefinitionKind,
16968 cx: &mut App,
16969 ) -> Option<Task<Result<Vec<LocationLink>>>> {
16970 Some(self.update(cx, |project, cx| match kind {
16971 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16972 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16973 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16974 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16975 }))
16976 }
16977
16978 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16979 // TODO: make this work for remote projects
16980 self.update(cx, |this, cx| {
16981 buffer.update(cx, |buffer, cx| {
16982 this.any_language_server_supports_inlay_hints(buffer, cx)
16983 })
16984 })
16985 }
16986
16987 fn inlay_hints(
16988 &self,
16989 buffer_handle: Entity<Buffer>,
16990 range: Range<text::Anchor>,
16991 cx: &mut App,
16992 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16993 Some(self.update(cx, |project, cx| {
16994 project.inlay_hints(buffer_handle, range, cx)
16995 }))
16996 }
16997
16998 fn resolve_inlay_hint(
16999 &self,
17000 hint: InlayHint,
17001 buffer_handle: Entity<Buffer>,
17002 server_id: LanguageServerId,
17003 cx: &mut App,
17004 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17005 Some(self.update(cx, |project, cx| {
17006 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17007 }))
17008 }
17009
17010 fn range_for_rename(
17011 &self,
17012 buffer: &Entity<Buffer>,
17013 position: text::Anchor,
17014 cx: &mut App,
17015 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17016 Some(self.update(cx, |project, cx| {
17017 let buffer = buffer.clone();
17018 let task = project.prepare_rename(buffer.clone(), position, cx);
17019 cx.spawn(|_, mut cx| async move {
17020 Ok(match task.await? {
17021 PrepareRenameResponse::Success(range) => Some(range),
17022 PrepareRenameResponse::InvalidPosition => None,
17023 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17024 // Fallback on using TreeSitter info to determine identifier range
17025 buffer.update(&mut cx, |buffer, _| {
17026 let snapshot = buffer.snapshot();
17027 let (range, kind) = snapshot.surrounding_word(position);
17028 if kind != Some(CharKind::Word) {
17029 return None;
17030 }
17031 Some(
17032 snapshot.anchor_before(range.start)
17033 ..snapshot.anchor_after(range.end),
17034 )
17035 })?
17036 }
17037 })
17038 })
17039 }))
17040 }
17041
17042 fn perform_rename(
17043 &self,
17044 buffer: &Entity<Buffer>,
17045 position: text::Anchor,
17046 new_name: String,
17047 cx: &mut App,
17048 ) -> Option<Task<Result<ProjectTransaction>>> {
17049 Some(self.update(cx, |project, cx| {
17050 project.perform_rename(buffer.clone(), position, new_name, cx)
17051 }))
17052 }
17053}
17054
17055fn inlay_hint_settings(
17056 location: Anchor,
17057 snapshot: &MultiBufferSnapshot,
17058 cx: &mut Context<Editor>,
17059) -> InlayHintSettings {
17060 let file = snapshot.file_at(location);
17061 let language = snapshot.language_at(location).map(|l| l.name());
17062 language_settings(language, file, cx).inlay_hints
17063}
17064
17065fn consume_contiguous_rows(
17066 contiguous_row_selections: &mut Vec<Selection<Point>>,
17067 selection: &Selection<Point>,
17068 display_map: &DisplaySnapshot,
17069 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17070) -> (MultiBufferRow, MultiBufferRow) {
17071 contiguous_row_selections.push(selection.clone());
17072 let start_row = MultiBufferRow(selection.start.row);
17073 let mut end_row = ending_row(selection, display_map);
17074
17075 while let Some(next_selection) = selections.peek() {
17076 if next_selection.start.row <= end_row.0 {
17077 end_row = ending_row(next_selection, display_map);
17078 contiguous_row_selections.push(selections.next().unwrap().clone());
17079 } else {
17080 break;
17081 }
17082 }
17083 (start_row, end_row)
17084}
17085
17086fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17087 if next_selection.end.column > 0 || next_selection.is_empty() {
17088 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17089 } else {
17090 MultiBufferRow(next_selection.end.row)
17091 }
17092}
17093
17094impl EditorSnapshot {
17095 pub fn remote_selections_in_range<'a>(
17096 &'a self,
17097 range: &'a Range<Anchor>,
17098 collaboration_hub: &dyn CollaborationHub,
17099 cx: &'a App,
17100 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17101 let participant_names = collaboration_hub.user_names(cx);
17102 let participant_indices = collaboration_hub.user_participant_indices(cx);
17103 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17104 let collaborators_by_replica_id = collaborators_by_peer_id
17105 .iter()
17106 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17107 .collect::<HashMap<_, _>>();
17108 self.buffer_snapshot
17109 .selections_in_range(range, false)
17110 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17111 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17112 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17113 let user_name = participant_names.get(&collaborator.user_id).cloned();
17114 Some(RemoteSelection {
17115 replica_id,
17116 selection,
17117 cursor_shape,
17118 line_mode,
17119 participant_index,
17120 peer_id: collaborator.peer_id,
17121 user_name,
17122 })
17123 })
17124 }
17125
17126 pub fn hunks_for_ranges(
17127 &self,
17128 ranges: impl IntoIterator<Item = Range<Point>>,
17129 ) -> Vec<MultiBufferDiffHunk> {
17130 let mut hunks = Vec::new();
17131 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17132 HashMap::default();
17133 for query_range in ranges {
17134 let query_rows =
17135 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17136 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17137 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17138 ) {
17139 // Include deleted hunks that are adjacent to the query range, because
17140 // otherwise they would be missed.
17141 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17142 if hunk.status().is_deleted() {
17143 intersects_range |= hunk.row_range.start == query_rows.end;
17144 intersects_range |= hunk.row_range.end == query_rows.start;
17145 }
17146 if intersects_range {
17147 if !processed_buffer_rows
17148 .entry(hunk.buffer_id)
17149 .or_default()
17150 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17151 {
17152 continue;
17153 }
17154 hunks.push(hunk);
17155 }
17156 }
17157 }
17158
17159 hunks
17160 }
17161
17162 fn display_diff_hunks_for_rows<'a>(
17163 &'a self,
17164 display_rows: Range<DisplayRow>,
17165 folded_buffers: &'a HashSet<BufferId>,
17166 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17167 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17168 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17169
17170 self.buffer_snapshot
17171 .diff_hunks_in_range(buffer_start..buffer_end)
17172 .filter_map(|hunk| {
17173 if folded_buffers.contains(&hunk.buffer_id) {
17174 return None;
17175 }
17176
17177 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17178 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17179
17180 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17181 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17182
17183 let display_hunk = if hunk_display_start.column() != 0 {
17184 DisplayDiffHunk::Folded {
17185 display_row: hunk_display_start.row(),
17186 }
17187 } else {
17188 let mut end_row = hunk_display_end.row();
17189 if hunk_display_end.column() > 0 {
17190 end_row.0 += 1;
17191 }
17192 DisplayDiffHunk::Unfolded {
17193 status: hunk.status(),
17194 diff_base_byte_range: hunk.diff_base_byte_range,
17195 display_row_range: hunk_display_start.row()..end_row,
17196 multi_buffer_range: Anchor::range_in_buffer(
17197 hunk.excerpt_id,
17198 hunk.buffer_id,
17199 hunk.buffer_range,
17200 ),
17201 }
17202 };
17203
17204 Some(display_hunk)
17205 })
17206 }
17207
17208 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17209 self.display_snapshot.buffer_snapshot.language_at(position)
17210 }
17211
17212 pub fn is_focused(&self) -> bool {
17213 self.is_focused
17214 }
17215
17216 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17217 self.placeholder_text.as_ref()
17218 }
17219
17220 pub fn scroll_position(&self) -> gpui::Point<f32> {
17221 self.scroll_anchor.scroll_position(&self.display_snapshot)
17222 }
17223
17224 fn gutter_dimensions(
17225 &self,
17226 font_id: FontId,
17227 font_size: Pixels,
17228 max_line_number_width: Pixels,
17229 cx: &App,
17230 ) -> Option<GutterDimensions> {
17231 if !self.show_gutter {
17232 return None;
17233 }
17234
17235 let descent = cx.text_system().descent(font_id, font_size);
17236 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17237 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17238
17239 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17240 matches!(
17241 ProjectSettings::get_global(cx).git.git_gutter,
17242 Some(GitGutterSetting::TrackedFiles)
17243 )
17244 });
17245 let gutter_settings = EditorSettings::get_global(cx).gutter;
17246 let show_line_numbers = self
17247 .show_line_numbers
17248 .unwrap_or(gutter_settings.line_numbers);
17249 let line_gutter_width = if show_line_numbers {
17250 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17251 let min_width_for_number_on_gutter = em_advance * 4.0;
17252 max_line_number_width.max(min_width_for_number_on_gutter)
17253 } else {
17254 0.0.into()
17255 };
17256
17257 let show_code_actions = self
17258 .show_code_actions
17259 .unwrap_or(gutter_settings.code_actions);
17260
17261 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17262
17263 let git_blame_entries_width =
17264 self.git_blame_gutter_max_author_length
17265 .map(|max_author_length| {
17266 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17267
17268 /// The number of characters to dedicate to gaps and margins.
17269 const SPACING_WIDTH: usize = 4;
17270
17271 let max_char_count = max_author_length
17272 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17273 + ::git::SHORT_SHA_LENGTH
17274 + MAX_RELATIVE_TIMESTAMP.len()
17275 + SPACING_WIDTH;
17276
17277 em_advance * max_char_count
17278 });
17279
17280 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17281 left_padding += if show_code_actions || show_runnables {
17282 em_width * 3.0
17283 } else if show_git_gutter && show_line_numbers {
17284 em_width * 2.0
17285 } else if show_git_gutter || show_line_numbers {
17286 em_width
17287 } else {
17288 px(0.)
17289 };
17290
17291 let right_padding = if gutter_settings.folds && show_line_numbers {
17292 em_width * 4.0
17293 } else if gutter_settings.folds {
17294 em_width * 3.0
17295 } else if show_line_numbers {
17296 em_width
17297 } else {
17298 px(0.)
17299 };
17300
17301 Some(GutterDimensions {
17302 left_padding,
17303 right_padding,
17304 width: line_gutter_width + left_padding + right_padding,
17305 margin: -descent,
17306 git_blame_entries_width,
17307 })
17308 }
17309
17310 pub fn render_crease_toggle(
17311 &self,
17312 buffer_row: MultiBufferRow,
17313 row_contains_cursor: bool,
17314 editor: Entity<Editor>,
17315 window: &mut Window,
17316 cx: &mut App,
17317 ) -> Option<AnyElement> {
17318 let folded = self.is_line_folded(buffer_row);
17319 let mut is_foldable = false;
17320
17321 if let Some(crease) = self
17322 .crease_snapshot
17323 .query_row(buffer_row, &self.buffer_snapshot)
17324 {
17325 is_foldable = true;
17326 match crease {
17327 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17328 if let Some(render_toggle) = render_toggle {
17329 let toggle_callback =
17330 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17331 if folded {
17332 editor.update(cx, |editor, cx| {
17333 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17334 });
17335 } else {
17336 editor.update(cx, |editor, cx| {
17337 editor.unfold_at(
17338 &crate::UnfoldAt { buffer_row },
17339 window,
17340 cx,
17341 )
17342 });
17343 }
17344 });
17345 return Some((render_toggle)(
17346 buffer_row,
17347 folded,
17348 toggle_callback,
17349 window,
17350 cx,
17351 ));
17352 }
17353 }
17354 }
17355 }
17356
17357 is_foldable |= self.starts_indent(buffer_row);
17358
17359 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17360 Some(
17361 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17362 .toggle_state(folded)
17363 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17364 if folded {
17365 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17366 } else {
17367 this.fold_at(&FoldAt { buffer_row }, window, cx);
17368 }
17369 }))
17370 .into_any_element(),
17371 )
17372 } else {
17373 None
17374 }
17375 }
17376
17377 pub fn render_crease_trailer(
17378 &self,
17379 buffer_row: MultiBufferRow,
17380 window: &mut Window,
17381 cx: &mut App,
17382 ) -> Option<AnyElement> {
17383 let folded = self.is_line_folded(buffer_row);
17384 if let Crease::Inline { render_trailer, .. } = self
17385 .crease_snapshot
17386 .query_row(buffer_row, &self.buffer_snapshot)?
17387 {
17388 let render_trailer = render_trailer.as_ref()?;
17389 Some(render_trailer(buffer_row, folded, window, cx))
17390 } else {
17391 None
17392 }
17393 }
17394}
17395
17396impl Deref for EditorSnapshot {
17397 type Target = DisplaySnapshot;
17398
17399 fn deref(&self) -> &Self::Target {
17400 &self.display_snapshot
17401 }
17402}
17403
17404#[derive(Clone, Debug, PartialEq, Eq)]
17405pub enum EditorEvent {
17406 InputIgnored {
17407 text: Arc<str>,
17408 },
17409 InputHandled {
17410 utf16_range_to_replace: Option<Range<isize>>,
17411 text: Arc<str>,
17412 },
17413 ExcerptsAdded {
17414 buffer: Entity<Buffer>,
17415 predecessor: ExcerptId,
17416 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17417 },
17418 ExcerptsRemoved {
17419 ids: Vec<ExcerptId>,
17420 },
17421 BufferFoldToggled {
17422 ids: Vec<ExcerptId>,
17423 folded: bool,
17424 },
17425 ExcerptsEdited {
17426 ids: Vec<ExcerptId>,
17427 },
17428 ExcerptsExpanded {
17429 ids: Vec<ExcerptId>,
17430 },
17431 BufferEdited,
17432 Edited {
17433 transaction_id: clock::Lamport,
17434 },
17435 Reparsed(BufferId),
17436 Focused,
17437 FocusedIn,
17438 Blurred,
17439 DirtyChanged,
17440 Saved,
17441 TitleChanged,
17442 DiffBaseChanged,
17443 SelectionsChanged {
17444 local: bool,
17445 },
17446 ScrollPositionChanged {
17447 local: bool,
17448 autoscroll: bool,
17449 },
17450 Closed,
17451 TransactionUndone {
17452 transaction_id: clock::Lamport,
17453 },
17454 TransactionBegun {
17455 transaction_id: clock::Lamport,
17456 },
17457 Reloaded,
17458 CursorShapeChanged,
17459}
17460
17461impl EventEmitter<EditorEvent> for Editor {}
17462
17463impl Focusable for Editor {
17464 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17465 self.focus_handle.clone()
17466 }
17467}
17468
17469impl Render for Editor {
17470 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17471 let settings = ThemeSettings::get_global(cx);
17472
17473 let mut text_style = match self.mode {
17474 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17475 color: cx.theme().colors().editor_foreground,
17476 font_family: settings.ui_font.family.clone(),
17477 font_features: settings.ui_font.features.clone(),
17478 font_fallbacks: settings.ui_font.fallbacks.clone(),
17479 font_size: rems(0.875).into(),
17480 font_weight: settings.ui_font.weight,
17481 line_height: relative(settings.buffer_line_height.value()),
17482 ..Default::default()
17483 },
17484 EditorMode::Full => TextStyle {
17485 color: cx.theme().colors().editor_foreground,
17486 font_family: settings.buffer_font.family.clone(),
17487 font_features: settings.buffer_font.features.clone(),
17488 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17489 font_size: settings.buffer_font_size(cx).into(),
17490 font_weight: settings.buffer_font.weight,
17491 line_height: relative(settings.buffer_line_height.value()),
17492 ..Default::default()
17493 },
17494 };
17495 if let Some(text_style_refinement) = &self.text_style_refinement {
17496 text_style.refine(text_style_refinement)
17497 }
17498
17499 let background = match self.mode {
17500 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17501 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17502 EditorMode::Full => cx.theme().colors().editor_background,
17503 };
17504
17505 EditorElement::new(
17506 &cx.entity(),
17507 EditorStyle {
17508 background,
17509 local_player: cx.theme().players().local(),
17510 text: text_style,
17511 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17512 syntax: cx.theme().syntax().clone(),
17513 status: cx.theme().status().clone(),
17514 inlay_hints_style: make_inlay_hints_style(cx),
17515 inline_completion_styles: make_suggestion_styles(cx),
17516 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17517 },
17518 )
17519 }
17520}
17521
17522impl EntityInputHandler for Editor {
17523 fn text_for_range(
17524 &mut self,
17525 range_utf16: Range<usize>,
17526 adjusted_range: &mut Option<Range<usize>>,
17527 _: &mut Window,
17528 cx: &mut Context<Self>,
17529 ) -> Option<String> {
17530 let snapshot = self.buffer.read(cx).read(cx);
17531 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17532 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17533 if (start.0..end.0) != range_utf16 {
17534 adjusted_range.replace(start.0..end.0);
17535 }
17536 Some(snapshot.text_for_range(start..end).collect())
17537 }
17538
17539 fn selected_text_range(
17540 &mut self,
17541 ignore_disabled_input: bool,
17542 _: &mut Window,
17543 cx: &mut Context<Self>,
17544 ) -> Option<UTF16Selection> {
17545 // Prevent the IME menu from appearing when holding down an alphabetic key
17546 // while input is disabled.
17547 if !ignore_disabled_input && !self.input_enabled {
17548 return None;
17549 }
17550
17551 let selection = self.selections.newest::<OffsetUtf16>(cx);
17552 let range = selection.range();
17553
17554 Some(UTF16Selection {
17555 range: range.start.0..range.end.0,
17556 reversed: selection.reversed,
17557 })
17558 }
17559
17560 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17561 let snapshot = self.buffer.read(cx).read(cx);
17562 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17563 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17564 }
17565
17566 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17567 self.clear_highlights::<InputComposition>(cx);
17568 self.ime_transaction.take();
17569 }
17570
17571 fn replace_text_in_range(
17572 &mut self,
17573 range_utf16: Option<Range<usize>>,
17574 text: &str,
17575 window: &mut Window,
17576 cx: &mut Context<Self>,
17577 ) {
17578 if !self.input_enabled {
17579 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17580 return;
17581 }
17582
17583 self.transact(window, cx, |this, window, cx| {
17584 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17585 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17586 Some(this.selection_replacement_ranges(range_utf16, cx))
17587 } else {
17588 this.marked_text_ranges(cx)
17589 };
17590
17591 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17592 let newest_selection_id = this.selections.newest_anchor().id;
17593 this.selections
17594 .all::<OffsetUtf16>(cx)
17595 .iter()
17596 .zip(ranges_to_replace.iter())
17597 .find_map(|(selection, range)| {
17598 if selection.id == newest_selection_id {
17599 Some(
17600 (range.start.0 as isize - selection.head().0 as isize)
17601 ..(range.end.0 as isize - selection.head().0 as isize),
17602 )
17603 } else {
17604 None
17605 }
17606 })
17607 });
17608
17609 cx.emit(EditorEvent::InputHandled {
17610 utf16_range_to_replace: range_to_replace,
17611 text: text.into(),
17612 });
17613
17614 if let Some(new_selected_ranges) = new_selected_ranges {
17615 this.change_selections(None, window, cx, |selections| {
17616 selections.select_ranges(new_selected_ranges)
17617 });
17618 this.backspace(&Default::default(), window, cx);
17619 }
17620
17621 this.handle_input(text, window, cx);
17622 });
17623
17624 if let Some(transaction) = self.ime_transaction {
17625 self.buffer.update(cx, |buffer, cx| {
17626 buffer.group_until_transaction(transaction, cx);
17627 });
17628 }
17629
17630 self.unmark_text(window, cx);
17631 }
17632
17633 fn replace_and_mark_text_in_range(
17634 &mut self,
17635 range_utf16: Option<Range<usize>>,
17636 text: &str,
17637 new_selected_range_utf16: Option<Range<usize>>,
17638 window: &mut Window,
17639 cx: &mut Context<Self>,
17640 ) {
17641 if !self.input_enabled {
17642 return;
17643 }
17644
17645 let transaction = self.transact(window, cx, |this, window, cx| {
17646 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17647 let snapshot = this.buffer.read(cx).read(cx);
17648 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17649 for marked_range in &mut marked_ranges {
17650 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17651 marked_range.start.0 += relative_range_utf16.start;
17652 marked_range.start =
17653 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17654 marked_range.end =
17655 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17656 }
17657 }
17658 Some(marked_ranges)
17659 } else if let Some(range_utf16) = range_utf16 {
17660 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17661 Some(this.selection_replacement_ranges(range_utf16, cx))
17662 } else {
17663 None
17664 };
17665
17666 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17667 let newest_selection_id = this.selections.newest_anchor().id;
17668 this.selections
17669 .all::<OffsetUtf16>(cx)
17670 .iter()
17671 .zip(ranges_to_replace.iter())
17672 .find_map(|(selection, range)| {
17673 if selection.id == newest_selection_id {
17674 Some(
17675 (range.start.0 as isize - selection.head().0 as isize)
17676 ..(range.end.0 as isize - selection.head().0 as isize),
17677 )
17678 } else {
17679 None
17680 }
17681 })
17682 });
17683
17684 cx.emit(EditorEvent::InputHandled {
17685 utf16_range_to_replace: range_to_replace,
17686 text: text.into(),
17687 });
17688
17689 if let Some(ranges) = ranges_to_replace {
17690 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17691 }
17692
17693 let marked_ranges = {
17694 let snapshot = this.buffer.read(cx).read(cx);
17695 this.selections
17696 .disjoint_anchors()
17697 .iter()
17698 .map(|selection| {
17699 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17700 })
17701 .collect::<Vec<_>>()
17702 };
17703
17704 if text.is_empty() {
17705 this.unmark_text(window, cx);
17706 } else {
17707 this.highlight_text::<InputComposition>(
17708 marked_ranges.clone(),
17709 HighlightStyle {
17710 underline: Some(UnderlineStyle {
17711 thickness: px(1.),
17712 color: None,
17713 wavy: false,
17714 }),
17715 ..Default::default()
17716 },
17717 cx,
17718 );
17719 }
17720
17721 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17722 let use_autoclose = this.use_autoclose;
17723 let use_auto_surround = this.use_auto_surround;
17724 this.set_use_autoclose(false);
17725 this.set_use_auto_surround(false);
17726 this.handle_input(text, window, cx);
17727 this.set_use_autoclose(use_autoclose);
17728 this.set_use_auto_surround(use_auto_surround);
17729
17730 if let Some(new_selected_range) = new_selected_range_utf16 {
17731 let snapshot = this.buffer.read(cx).read(cx);
17732 let new_selected_ranges = marked_ranges
17733 .into_iter()
17734 .map(|marked_range| {
17735 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17736 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17737 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17738 snapshot.clip_offset_utf16(new_start, Bias::Left)
17739 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17740 })
17741 .collect::<Vec<_>>();
17742
17743 drop(snapshot);
17744 this.change_selections(None, window, cx, |selections| {
17745 selections.select_ranges(new_selected_ranges)
17746 });
17747 }
17748 });
17749
17750 self.ime_transaction = self.ime_transaction.or(transaction);
17751 if let Some(transaction) = self.ime_transaction {
17752 self.buffer.update(cx, |buffer, cx| {
17753 buffer.group_until_transaction(transaction, cx);
17754 });
17755 }
17756
17757 if self.text_highlights::<InputComposition>(cx).is_none() {
17758 self.ime_transaction.take();
17759 }
17760 }
17761
17762 fn bounds_for_range(
17763 &mut self,
17764 range_utf16: Range<usize>,
17765 element_bounds: gpui::Bounds<Pixels>,
17766 window: &mut Window,
17767 cx: &mut Context<Self>,
17768 ) -> Option<gpui::Bounds<Pixels>> {
17769 let text_layout_details = self.text_layout_details(window);
17770 let gpui::Size {
17771 width: em_width,
17772 height: line_height,
17773 } = self.character_size(window);
17774
17775 let snapshot = self.snapshot(window, cx);
17776 let scroll_position = snapshot.scroll_position();
17777 let scroll_left = scroll_position.x * em_width;
17778
17779 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17780 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17781 + self.gutter_dimensions.width
17782 + self.gutter_dimensions.margin;
17783 let y = line_height * (start.row().as_f32() - scroll_position.y);
17784
17785 Some(Bounds {
17786 origin: element_bounds.origin + point(x, y),
17787 size: size(em_width, line_height),
17788 })
17789 }
17790
17791 fn character_index_for_point(
17792 &mut self,
17793 point: gpui::Point<Pixels>,
17794 _window: &mut Window,
17795 _cx: &mut Context<Self>,
17796 ) -> Option<usize> {
17797 let position_map = self.last_position_map.as_ref()?;
17798 if !position_map.text_hitbox.contains(&point) {
17799 return None;
17800 }
17801 let display_point = position_map.point_for_position(point).previous_valid;
17802 let anchor = position_map
17803 .snapshot
17804 .display_point_to_anchor(display_point, Bias::Left);
17805 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17806 Some(utf16_offset.0)
17807 }
17808}
17809
17810trait SelectionExt {
17811 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17812 fn spanned_rows(
17813 &self,
17814 include_end_if_at_line_start: bool,
17815 map: &DisplaySnapshot,
17816 ) -> Range<MultiBufferRow>;
17817}
17818
17819impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17820 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17821 let start = self
17822 .start
17823 .to_point(&map.buffer_snapshot)
17824 .to_display_point(map);
17825 let end = self
17826 .end
17827 .to_point(&map.buffer_snapshot)
17828 .to_display_point(map);
17829 if self.reversed {
17830 end..start
17831 } else {
17832 start..end
17833 }
17834 }
17835
17836 fn spanned_rows(
17837 &self,
17838 include_end_if_at_line_start: bool,
17839 map: &DisplaySnapshot,
17840 ) -> Range<MultiBufferRow> {
17841 let start = self.start.to_point(&map.buffer_snapshot);
17842 let mut end = self.end.to_point(&map.buffer_snapshot);
17843 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17844 end.row -= 1;
17845 }
17846
17847 let buffer_start = map.prev_line_boundary(start).0;
17848 let buffer_end = map.next_line_boundary(end).0;
17849 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17850 }
17851}
17852
17853impl<T: InvalidationRegion> InvalidationStack<T> {
17854 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17855 where
17856 S: Clone + ToOffset,
17857 {
17858 while let Some(region) = self.last() {
17859 let all_selections_inside_invalidation_ranges =
17860 if selections.len() == region.ranges().len() {
17861 selections
17862 .iter()
17863 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17864 .all(|(selection, invalidation_range)| {
17865 let head = selection.head().to_offset(buffer);
17866 invalidation_range.start <= head && invalidation_range.end >= head
17867 })
17868 } else {
17869 false
17870 };
17871
17872 if all_selections_inside_invalidation_ranges {
17873 break;
17874 } else {
17875 self.pop();
17876 }
17877 }
17878 }
17879}
17880
17881impl<T> Default for InvalidationStack<T> {
17882 fn default() -> Self {
17883 Self(Default::default())
17884 }
17885}
17886
17887impl<T> Deref for InvalidationStack<T> {
17888 type Target = Vec<T>;
17889
17890 fn deref(&self) -> &Self::Target {
17891 &self.0
17892 }
17893}
17894
17895impl<T> DerefMut for InvalidationStack<T> {
17896 fn deref_mut(&mut self) -> &mut Self::Target {
17897 &mut self.0
17898 }
17899}
17900
17901impl InvalidationRegion for SnippetState {
17902 fn ranges(&self) -> &[Range<Anchor>] {
17903 &self.ranges[self.active_index]
17904 }
17905}
17906
17907pub fn diagnostic_block_renderer(
17908 diagnostic: Diagnostic,
17909 max_message_rows: Option<u8>,
17910 allow_closing: bool,
17911) -> RenderBlock {
17912 let (text_without_backticks, code_ranges) =
17913 highlight_diagnostic_message(&diagnostic, max_message_rows);
17914
17915 Arc::new(move |cx: &mut BlockContext| {
17916 let group_id: SharedString = cx.block_id.to_string().into();
17917
17918 let mut text_style = cx.window.text_style().clone();
17919 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17920 let theme_settings = ThemeSettings::get_global(cx);
17921 text_style.font_family = theme_settings.buffer_font.family.clone();
17922 text_style.font_style = theme_settings.buffer_font.style;
17923 text_style.font_features = theme_settings.buffer_font.features.clone();
17924 text_style.font_weight = theme_settings.buffer_font.weight;
17925
17926 let multi_line_diagnostic = diagnostic.message.contains('\n');
17927
17928 let buttons = |diagnostic: &Diagnostic| {
17929 if multi_line_diagnostic {
17930 v_flex()
17931 } else {
17932 h_flex()
17933 }
17934 .when(allow_closing, |div| {
17935 div.children(diagnostic.is_primary.then(|| {
17936 IconButton::new("close-block", IconName::XCircle)
17937 .icon_color(Color::Muted)
17938 .size(ButtonSize::Compact)
17939 .style(ButtonStyle::Transparent)
17940 .visible_on_hover(group_id.clone())
17941 .on_click(move |_click, window, cx| {
17942 window.dispatch_action(Box::new(Cancel), cx)
17943 })
17944 .tooltip(|window, cx| {
17945 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17946 })
17947 }))
17948 })
17949 .child(
17950 IconButton::new("copy-block", IconName::Copy)
17951 .icon_color(Color::Muted)
17952 .size(ButtonSize::Compact)
17953 .style(ButtonStyle::Transparent)
17954 .visible_on_hover(group_id.clone())
17955 .on_click({
17956 let message = diagnostic.message.clone();
17957 move |_click, _, cx| {
17958 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17959 }
17960 })
17961 .tooltip(Tooltip::text("Copy diagnostic message")),
17962 )
17963 };
17964
17965 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17966 AvailableSpace::min_size(),
17967 cx.window,
17968 cx.app,
17969 );
17970
17971 h_flex()
17972 .id(cx.block_id)
17973 .group(group_id.clone())
17974 .relative()
17975 .size_full()
17976 .block_mouse_down()
17977 .pl(cx.gutter_dimensions.width)
17978 .w(cx.max_width - cx.gutter_dimensions.full_width())
17979 .child(
17980 div()
17981 .flex()
17982 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17983 .flex_shrink(),
17984 )
17985 .child(buttons(&diagnostic))
17986 .child(div().flex().flex_shrink_0().child(
17987 StyledText::new(text_without_backticks.clone()).with_default_highlights(
17988 &text_style,
17989 code_ranges.iter().map(|range| {
17990 (
17991 range.clone(),
17992 HighlightStyle {
17993 font_weight: Some(FontWeight::BOLD),
17994 ..Default::default()
17995 },
17996 )
17997 }),
17998 ),
17999 ))
18000 .into_any_element()
18001 })
18002}
18003
18004fn inline_completion_edit_text(
18005 current_snapshot: &BufferSnapshot,
18006 edits: &[(Range<Anchor>, String)],
18007 edit_preview: &EditPreview,
18008 include_deletions: bool,
18009 cx: &App,
18010) -> HighlightedText {
18011 let edits = edits
18012 .iter()
18013 .map(|(anchor, text)| {
18014 (
18015 anchor.start.text_anchor..anchor.end.text_anchor,
18016 text.clone(),
18017 )
18018 })
18019 .collect::<Vec<_>>();
18020
18021 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18022}
18023
18024pub fn highlight_diagnostic_message(
18025 diagnostic: &Diagnostic,
18026 mut max_message_rows: Option<u8>,
18027) -> (SharedString, Vec<Range<usize>>) {
18028 let mut text_without_backticks = String::new();
18029 let mut code_ranges = Vec::new();
18030
18031 if let Some(source) = &diagnostic.source {
18032 text_without_backticks.push_str(source);
18033 code_ranges.push(0..source.len());
18034 text_without_backticks.push_str(": ");
18035 }
18036
18037 let mut prev_offset = 0;
18038 let mut in_code_block = false;
18039 let has_row_limit = max_message_rows.is_some();
18040 let mut newline_indices = diagnostic
18041 .message
18042 .match_indices('\n')
18043 .filter(|_| has_row_limit)
18044 .map(|(ix, _)| ix)
18045 .fuse()
18046 .peekable();
18047
18048 for (quote_ix, _) in diagnostic
18049 .message
18050 .match_indices('`')
18051 .chain([(diagnostic.message.len(), "")])
18052 {
18053 let mut first_newline_ix = None;
18054 let mut last_newline_ix = None;
18055 while let Some(newline_ix) = newline_indices.peek() {
18056 if *newline_ix < quote_ix {
18057 if first_newline_ix.is_none() {
18058 first_newline_ix = Some(*newline_ix);
18059 }
18060 last_newline_ix = Some(*newline_ix);
18061
18062 if let Some(rows_left) = &mut max_message_rows {
18063 if *rows_left == 0 {
18064 break;
18065 } else {
18066 *rows_left -= 1;
18067 }
18068 }
18069 let _ = newline_indices.next();
18070 } else {
18071 break;
18072 }
18073 }
18074 let prev_len = text_without_backticks.len();
18075 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18076 text_without_backticks.push_str(new_text);
18077 if in_code_block {
18078 code_ranges.push(prev_len..text_without_backticks.len());
18079 }
18080 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18081 in_code_block = !in_code_block;
18082 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18083 text_without_backticks.push_str("...");
18084 break;
18085 }
18086 }
18087
18088 (text_without_backticks.into(), code_ranges)
18089}
18090
18091fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18092 match severity {
18093 DiagnosticSeverity::ERROR => colors.error,
18094 DiagnosticSeverity::WARNING => colors.warning,
18095 DiagnosticSeverity::INFORMATION => colors.info,
18096 DiagnosticSeverity::HINT => colors.info,
18097 _ => colors.ignored,
18098 }
18099}
18100
18101pub fn styled_runs_for_code_label<'a>(
18102 label: &'a CodeLabel,
18103 syntax_theme: &'a theme::SyntaxTheme,
18104) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18105 let fade_out = HighlightStyle {
18106 fade_out: Some(0.35),
18107 ..Default::default()
18108 };
18109
18110 let mut prev_end = label.filter_range.end;
18111 label
18112 .runs
18113 .iter()
18114 .enumerate()
18115 .flat_map(move |(ix, (range, highlight_id))| {
18116 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18117 style
18118 } else {
18119 return Default::default();
18120 };
18121 let mut muted_style = style;
18122 muted_style.highlight(fade_out);
18123
18124 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18125 if range.start >= label.filter_range.end {
18126 if range.start > prev_end {
18127 runs.push((prev_end..range.start, fade_out));
18128 }
18129 runs.push((range.clone(), muted_style));
18130 } else if range.end <= label.filter_range.end {
18131 runs.push((range.clone(), style));
18132 } else {
18133 runs.push((range.start..label.filter_range.end, style));
18134 runs.push((label.filter_range.end..range.end, muted_style));
18135 }
18136 prev_end = cmp::max(prev_end, range.end);
18137
18138 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18139 runs.push((prev_end..label.text.len(), fade_out));
18140 }
18141
18142 runs
18143 })
18144}
18145
18146pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18147 let mut prev_index = 0;
18148 let mut prev_codepoint: Option<char> = None;
18149 text.char_indices()
18150 .chain([(text.len(), '\0')])
18151 .filter_map(move |(index, codepoint)| {
18152 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18153 let is_boundary = index == text.len()
18154 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18155 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18156 if is_boundary {
18157 let chunk = &text[prev_index..index];
18158 prev_index = index;
18159 Some(chunk)
18160 } else {
18161 None
18162 }
18163 })
18164}
18165
18166pub trait RangeToAnchorExt: Sized {
18167 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18168
18169 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18170 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18171 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18172 }
18173}
18174
18175impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18176 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18177 let start_offset = self.start.to_offset(snapshot);
18178 let end_offset = self.end.to_offset(snapshot);
18179 if start_offset == end_offset {
18180 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18181 } else {
18182 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18183 }
18184 }
18185}
18186
18187pub trait RowExt {
18188 fn as_f32(&self) -> f32;
18189
18190 fn next_row(&self) -> Self;
18191
18192 fn previous_row(&self) -> Self;
18193
18194 fn minus(&self, other: Self) -> u32;
18195}
18196
18197impl RowExt for DisplayRow {
18198 fn as_f32(&self) -> f32 {
18199 self.0 as f32
18200 }
18201
18202 fn next_row(&self) -> Self {
18203 Self(self.0 + 1)
18204 }
18205
18206 fn previous_row(&self) -> Self {
18207 Self(self.0.saturating_sub(1))
18208 }
18209
18210 fn minus(&self, other: Self) -> u32 {
18211 self.0 - other.0
18212 }
18213}
18214
18215impl RowExt for MultiBufferRow {
18216 fn as_f32(&self) -> f32 {
18217 self.0 as f32
18218 }
18219
18220 fn next_row(&self) -> Self {
18221 Self(self.0 + 1)
18222 }
18223
18224 fn previous_row(&self) -> Self {
18225 Self(self.0.saturating_sub(1))
18226 }
18227
18228 fn minus(&self, other: Self) -> u32 {
18229 self.0 - other.0
18230 }
18231}
18232
18233trait RowRangeExt {
18234 type Row;
18235
18236 fn len(&self) -> usize;
18237
18238 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18239}
18240
18241impl RowRangeExt for Range<MultiBufferRow> {
18242 type Row = MultiBufferRow;
18243
18244 fn len(&self) -> usize {
18245 (self.end.0 - self.start.0) as usize
18246 }
18247
18248 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18249 (self.start.0..self.end.0).map(MultiBufferRow)
18250 }
18251}
18252
18253impl RowRangeExt for Range<DisplayRow> {
18254 type Row = DisplayRow;
18255
18256 fn len(&self) -> usize {
18257 (self.end.0 - self.start.0) as usize
18258 }
18259
18260 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18261 (self.start.0..self.end.0).map(DisplayRow)
18262 }
18263}
18264
18265/// If select range has more than one line, we
18266/// just point the cursor to range.start.
18267fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18268 if range.start.row == range.end.row {
18269 range
18270 } else {
18271 range.start..range.start
18272 }
18273}
18274pub struct KillRing(ClipboardItem);
18275impl Global for KillRing {}
18276
18277const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18278
18279fn all_edits_insertions_or_deletions(
18280 edits: &Vec<(Range<Anchor>, String)>,
18281 snapshot: &MultiBufferSnapshot,
18282) -> bool {
18283 let mut all_insertions = true;
18284 let mut all_deletions = true;
18285
18286 for (range, new_text) in edits.iter() {
18287 let range_is_empty = range.to_offset(&snapshot).is_empty();
18288 let text_is_empty = new_text.is_empty();
18289
18290 if range_is_empty != text_is_empty {
18291 if range_is_empty {
18292 all_deletions = false;
18293 } else {
18294 all_insertions = false;
18295 }
18296 } else {
18297 return false;
18298 }
18299
18300 if !all_insertions && !all_deletions {
18301 return false;
18302 }
18303 }
18304 all_insertions || all_deletions
18305}