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 is_created_file: bool,
264 diff_base_byte_range: Range<usize>,
265 display_row_range: Range<DisplayRow>,
266 multi_buffer_range: Range<Anchor>,
267 status: DiffHunkStatus,
268 },
269}
270
271pub fn init_settings(cx: &mut App) {
272 EditorSettings::register(cx);
273}
274
275pub fn init(cx: &mut App) {
276 init_settings(cx);
277
278 workspace::register_project_item::<Editor>(cx);
279 workspace::FollowableViewRegistry::register::<Editor>(cx);
280 workspace::register_serializable_item::<Editor>(cx);
281
282 cx.observe_new(
283 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
284 workspace.register_action(Editor::new_file);
285 workspace.register_action(Editor::new_file_vertical);
286 workspace.register_action(Editor::new_file_horizontal);
287 workspace.register_action(Editor::cancel_language_server_work);
288 },
289 )
290 .detach();
291
292 cx.on_action(move |_: &workspace::NewFile, cx| {
293 let app_state = workspace::AppState::global(cx);
294 if let Some(app_state) = app_state.upgrade() {
295 workspace::open_new(
296 Default::default(),
297 app_state,
298 cx,
299 |workspace, window, cx| {
300 Editor::new_file(workspace, &Default::default(), window, cx)
301 },
302 )
303 .detach();
304 }
305 });
306 cx.on_action(move |_: &workspace::NewWindow, cx| {
307 let app_state = workspace::AppState::global(cx);
308 if let Some(app_state) = app_state.upgrade() {
309 workspace::open_new(
310 Default::default(),
311 app_state,
312 cx,
313 |workspace, window, cx| {
314 cx.activate(true);
315 Editor::new_file(workspace, &Default::default(), window, cx)
316 },
317 )
318 .detach();
319 }
320 });
321}
322
323pub struct SearchWithinRange;
324
325trait InvalidationRegion {
326 fn ranges(&self) -> &[Range<Anchor>];
327}
328
329#[derive(Clone, Debug, PartialEq)]
330pub enum SelectPhase {
331 Begin {
332 position: DisplayPoint,
333 add: bool,
334 click_count: usize,
335 },
336 BeginColumnar {
337 position: DisplayPoint,
338 reset: bool,
339 goal_column: u32,
340 },
341 Extend {
342 position: DisplayPoint,
343 click_count: usize,
344 },
345 Update {
346 position: DisplayPoint,
347 goal_column: u32,
348 scroll_delta: gpui::Point<f32>,
349 },
350 End,
351}
352
353#[derive(Clone, Debug)]
354pub enum SelectMode {
355 Character,
356 Word(Range<Anchor>),
357 Line(Range<Anchor>),
358 All,
359}
360
361#[derive(Copy, Clone, PartialEq, Eq, Debug)]
362pub enum EditorMode {
363 SingleLine { auto_width: bool },
364 AutoHeight { max_lines: usize },
365 Full,
366}
367
368#[derive(Copy, Clone, Debug)]
369pub enum SoftWrap {
370 /// Prefer not to wrap at all.
371 ///
372 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
373 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
374 GitDiff,
375 /// Prefer a single line generally, unless an overly long line is encountered.
376 None,
377 /// Soft wrap lines that exceed the editor width.
378 EditorWidth,
379 /// Soft wrap lines at the preferred line length.
380 Column(u32),
381 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
382 Bounded(u32),
383}
384
385#[derive(Clone)]
386pub struct EditorStyle {
387 pub background: Hsla,
388 pub local_player: PlayerColor,
389 pub text: TextStyle,
390 pub scrollbar_width: Pixels,
391 pub syntax: Arc<SyntaxTheme>,
392 pub status: StatusColors,
393 pub inlay_hints_style: HighlightStyle,
394 pub inline_completion_styles: InlineCompletionStyles,
395 pub unnecessary_code_fade: f32,
396}
397
398impl Default for EditorStyle {
399 fn default() -> Self {
400 Self {
401 background: Hsla::default(),
402 local_player: PlayerColor::default(),
403 text: TextStyle::default(),
404 scrollbar_width: Pixels::default(),
405 syntax: Default::default(),
406 // HACK: Status colors don't have a real default.
407 // We should look into removing the status colors from the editor
408 // style and retrieve them directly from the theme.
409 status: StatusColors::dark(),
410 inlay_hints_style: HighlightStyle::default(),
411 inline_completion_styles: InlineCompletionStyles {
412 insertion: HighlightStyle::default(),
413 whitespace: HighlightStyle::default(),
414 },
415 unnecessary_code_fade: Default::default(),
416 }
417 }
418}
419
420pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
421 let show_background = language_settings::language_settings(None, None, cx)
422 .inlay_hints
423 .show_background;
424
425 HighlightStyle {
426 color: Some(cx.theme().status().hint),
427 background_color: show_background.then(|| cx.theme().status().hint_background),
428 ..HighlightStyle::default()
429 }
430}
431
432pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
433 InlineCompletionStyles {
434 insertion: HighlightStyle {
435 color: Some(cx.theme().status().predictive),
436 ..HighlightStyle::default()
437 },
438 whitespace: HighlightStyle {
439 background_color: Some(cx.theme().status().created_background),
440 ..HighlightStyle::default()
441 },
442 }
443}
444
445type CompletionId = usize;
446
447pub(crate) enum EditDisplayMode {
448 TabAccept,
449 DiffPopover,
450 Inline,
451}
452
453enum InlineCompletion {
454 Edit {
455 edits: Vec<(Range<Anchor>, String)>,
456 edit_preview: Option<EditPreview>,
457 display_mode: EditDisplayMode,
458 snapshot: BufferSnapshot,
459 },
460 Move {
461 target: Anchor,
462 snapshot: BufferSnapshot,
463 },
464}
465
466struct InlineCompletionState {
467 inlay_ids: Vec<InlayId>,
468 completion: InlineCompletion,
469 completion_id: Option<SharedString>,
470 invalidation_range: Range<Anchor>,
471}
472
473enum EditPredictionSettings {
474 Disabled,
475 Enabled {
476 show_in_menu: bool,
477 preview_requires_modifier: bool,
478 },
479}
480
481enum InlineCompletionHighlight {}
482
483#[derive(Debug, Clone)]
484struct InlineDiagnostic {
485 message: SharedString,
486 group_id: usize,
487 is_primary: bool,
488 start: Point,
489 severity: DiagnosticSeverity,
490}
491
492pub enum MenuInlineCompletionsPolicy {
493 Never,
494 ByProvider,
495}
496
497pub enum EditPredictionPreview {
498 /// Modifier is not pressed
499 Inactive { released_too_fast: bool },
500 /// Modifier pressed
501 Active {
502 since: Instant,
503 previous_scroll_position: Option<ScrollAnchor>,
504 },
505}
506
507impl EditPredictionPreview {
508 pub fn released_too_fast(&self) -> bool {
509 match self {
510 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
511 EditPredictionPreview::Active { .. } => false,
512 }
513 }
514
515 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
516 if let EditPredictionPreview::Active {
517 previous_scroll_position,
518 ..
519 } = self
520 {
521 *previous_scroll_position = scroll_position;
522 }
523 }
524}
525
526#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
527struct EditorActionId(usize);
528
529impl EditorActionId {
530 pub fn post_inc(&mut self) -> Self {
531 let answer = self.0;
532
533 *self = Self(answer + 1);
534
535 Self(answer)
536 }
537}
538
539// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
540// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
541
542type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
543type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
544
545#[derive(Default)]
546struct ScrollbarMarkerState {
547 scrollbar_size: Size<Pixels>,
548 dirty: bool,
549 markers: Arc<[PaintQuad]>,
550 pending_refresh: Option<Task<Result<()>>>,
551}
552
553impl ScrollbarMarkerState {
554 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
555 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
556 }
557}
558
559#[derive(Clone, Debug)]
560struct RunnableTasks {
561 templates: Vec<(TaskSourceKind, TaskTemplate)>,
562 offset: multi_buffer::Anchor,
563 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
564 column: u32,
565 // Values of all named captures, including those starting with '_'
566 extra_variables: HashMap<String, String>,
567 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
568 context_range: Range<BufferOffset>,
569}
570
571impl RunnableTasks {
572 fn resolve<'a>(
573 &'a self,
574 cx: &'a task::TaskContext,
575 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
576 self.templates.iter().filter_map(|(kind, template)| {
577 template
578 .resolve_task(&kind.to_id_base(), cx)
579 .map(|task| (kind.clone(), task))
580 })
581 }
582}
583
584#[derive(Clone)]
585struct ResolvedTasks {
586 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
587 position: Anchor,
588}
589#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
590struct BufferOffset(usize);
591
592// Addons allow storing per-editor state in other crates (e.g. Vim)
593pub trait Addon: 'static {
594 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
595
596 fn render_buffer_header_controls(
597 &self,
598 _: &ExcerptInfo,
599 _: &Window,
600 _: &App,
601 ) -> Option<AnyElement> {
602 None
603 }
604
605 fn to_any(&self) -> &dyn std::any::Any;
606}
607
608#[derive(Debug, Copy, Clone, PartialEq, Eq)]
609pub enum IsVimMode {
610 Yes,
611 No,
612}
613
614/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
615///
616/// See the [module level documentation](self) for more information.
617pub struct Editor {
618 focus_handle: FocusHandle,
619 last_focused_descendant: Option<WeakFocusHandle>,
620 /// The text buffer being edited
621 buffer: Entity<MultiBuffer>,
622 /// Map of how text in the buffer should be displayed.
623 /// Handles soft wraps, folds, fake inlay text insertions, etc.
624 pub display_map: Entity<DisplayMap>,
625 pub selections: SelectionsCollection,
626 pub scroll_manager: ScrollManager,
627 /// When inline assist editors are linked, they all render cursors because
628 /// typing enters text into each of them, even the ones that aren't focused.
629 pub(crate) show_cursor_when_unfocused: bool,
630 columnar_selection_tail: Option<Anchor>,
631 add_selections_state: Option<AddSelectionsState>,
632 select_next_state: Option<SelectNextState>,
633 select_prev_state: Option<SelectNextState>,
634 selection_history: SelectionHistory,
635 autoclose_regions: Vec<AutocloseRegion>,
636 snippet_stack: InvalidationStack<SnippetState>,
637 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
638 ime_transaction: Option<TransactionId>,
639 active_diagnostics: Option<ActiveDiagnosticGroup>,
640 show_inline_diagnostics: bool,
641 inline_diagnostics_update: Task<()>,
642 inline_diagnostics_enabled: bool,
643 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
644 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
645
646 // TODO: make this a access method
647 pub project: Option<Entity<Project>>,
648 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
649 completion_provider: Option<Box<dyn CompletionProvider>>,
650 collaboration_hub: Option<Box<dyn CollaborationHub>>,
651 blink_manager: Entity<BlinkManager>,
652 show_cursor_names: bool,
653 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
654 pub show_local_selections: bool,
655 mode: EditorMode,
656 show_breadcrumbs: bool,
657 show_gutter: bool,
658 show_scrollbars: bool,
659 show_line_numbers: Option<bool>,
660 use_relative_line_numbers: Option<bool>,
661 show_git_diff_gutter: Option<bool>,
662 show_code_actions: Option<bool>,
663 show_runnables: Option<bool>,
664 show_wrap_guides: Option<bool>,
665 show_indent_guides: Option<bool>,
666 placeholder_text: Option<Arc<str>>,
667 highlight_order: usize,
668 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
669 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
670 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
671 scrollbar_marker_state: ScrollbarMarkerState,
672 active_indent_guides_state: ActiveIndentGuidesState,
673 nav_history: Option<ItemNavHistory>,
674 context_menu: RefCell<Option<CodeContextMenu>>,
675 mouse_context_menu: Option<MouseContextMenu>,
676 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
677 signature_help_state: SignatureHelpState,
678 auto_signature_help: Option<bool>,
679 find_all_references_task_sources: Vec<Anchor>,
680 next_completion_id: CompletionId,
681 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
682 code_actions_task: Option<Task<Result<()>>>,
683 selection_highlight_task: Option<Task<()>>,
684 document_highlights_task: Option<Task<()>>,
685 linked_editing_range_task: Option<Task<Option<()>>>,
686 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
687 pending_rename: Option<RenameState>,
688 searchable: bool,
689 cursor_shape: CursorShape,
690 current_line_highlight: Option<CurrentLineHighlight>,
691 collapse_matches: bool,
692 autoindent_mode: Option<AutoindentMode>,
693 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
694 input_enabled: bool,
695 use_modal_editing: bool,
696 read_only: bool,
697 leader_peer_id: Option<PeerId>,
698 remote_id: Option<ViewId>,
699 hover_state: HoverState,
700 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
701 gutter_hovered: bool,
702 hovered_link_state: Option<HoveredLinkState>,
703 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
704 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
705 active_inline_completion: Option<InlineCompletionState>,
706 /// Used to prevent flickering as the user types while the menu is open
707 stale_inline_completion_in_menu: Option<InlineCompletionState>,
708 edit_prediction_settings: EditPredictionSettings,
709 inline_completions_hidden_for_vim_mode: bool,
710 show_inline_completions_override: Option<bool>,
711 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
712 edit_prediction_preview: EditPredictionPreview,
713 edit_prediction_indent_conflict: bool,
714 edit_prediction_requires_modifier_in_indent_conflict: bool,
715 inlay_hint_cache: InlayHintCache,
716 next_inlay_id: usize,
717 _subscriptions: Vec<Subscription>,
718 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
719 gutter_dimensions: GutterDimensions,
720 style: Option<EditorStyle>,
721 text_style_refinement: Option<TextStyleRefinement>,
722 next_editor_action_id: EditorActionId,
723 editor_actions:
724 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
725 use_autoclose: bool,
726 use_auto_surround: bool,
727 auto_replace_emoji_shortcode: bool,
728 show_git_blame_gutter: bool,
729 show_git_blame_inline: bool,
730 show_git_blame_inline_delay_task: Option<Task<()>>,
731 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
732 git_blame_inline_enabled: bool,
733 serialize_dirty_buffers: bool,
734 show_selection_menu: Option<bool>,
735 blame: Option<Entity<GitBlame>>,
736 blame_subscription: Option<Subscription>,
737 custom_context_menu: Option<
738 Box<
739 dyn 'static
740 + Fn(
741 &mut Self,
742 DisplayPoint,
743 &mut Window,
744 &mut Context<Self>,
745 ) -> Option<Entity<ui::ContextMenu>>,
746 >,
747 >,
748 last_bounds: Option<Bounds<Pixels>>,
749 last_position_map: Option<Rc<PositionMap>>,
750 expect_bounds_change: Option<Bounds<Pixels>>,
751 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
752 tasks_update_task: Option<Task<()>>,
753 in_project_search: bool,
754 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
755 breadcrumb_header: Option<String>,
756 focused_block: Option<FocusedBlock>,
757 next_scroll_position: NextScrollCursorCenterTopBottom,
758 addons: HashMap<TypeId, Box<dyn Addon>>,
759 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
760 load_diff_task: Option<Shared<Task<()>>>,
761 selection_mark_mode: bool,
762 toggle_fold_multiple_buffers: Task<()>,
763 _scroll_cursor_center_top_bottom_task: Task<()>,
764 serialize_selections: Task<()>,
765}
766
767#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
768enum NextScrollCursorCenterTopBottom {
769 #[default]
770 Center,
771 Top,
772 Bottom,
773}
774
775impl NextScrollCursorCenterTopBottom {
776 fn next(&self) -> Self {
777 match self {
778 Self::Center => Self::Top,
779 Self::Top => Self::Bottom,
780 Self::Bottom => Self::Center,
781 }
782 }
783}
784
785#[derive(Clone)]
786pub struct EditorSnapshot {
787 pub mode: EditorMode,
788 show_gutter: bool,
789 show_line_numbers: Option<bool>,
790 show_git_diff_gutter: Option<bool>,
791 show_code_actions: Option<bool>,
792 show_runnables: Option<bool>,
793 git_blame_gutter_max_author_length: Option<usize>,
794 pub display_snapshot: DisplaySnapshot,
795 pub placeholder_text: Option<Arc<str>>,
796 is_focused: bool,
797 scroll_anchor: ScrollAnchor,
798 ongoing_scroll: OngoingScroll,
799 current_line_highlight: CurrentLineHighlight,
800 gutter_hovered: bool,
801}
802
803const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
804
805#[derive(Default, Debug, Clone, Copy)]
806pub struct GutterDimensions {
807 pub left_padding: Pixels,
808 pub right_padding: Pixels,
809 pub width: Pixels,
810 pub margin: Pixels,
811 pub git_blame_entries_width: Option<Pixels>,
812}
813
814impl GutterDimensions {
815 /// The full width of the space taken up by the gutter.
816 pub fn full_width(&self) -> Pixels {
817 self.margin + self.width
818 }
819
820 /// The width of the space reserved for the fold indicators,
821 /// use alongside 'justify_end' and `gutter_width` to
822 /// right align content with the line numbers
823 pub fn fold_area_width(&self) -> Pixels {
824 self.margin + self.right_padding
825 }
826}
827
828#[derive(Debug)]
829pub struct RemoteSelection {
830 pub replica_id: ReplicaId,
831 pub selection: Selection<Anchor>,
832 pub cursor_shape: CursorShape,
833 pub peer_id: PeerId,
834 pub line_mode: bool,
835 pub participant_index: Option<ParticipantIndex>,
836 pub user_name: Option<SharedString>,
837}
838
839#[derive(Clone, Debug)]
840struct SelectionHistoryEntry {
841 selections: Arc<[Selection<Anchor>]>,
842 select_next_state: Option<SelectNextState>,
843 select_prev_state: Option<SelectNextState>,
844 add_selections_state: Option<AddSelectionsState>,
845}
846
847enum SelectionHistoryMode {
848 Normal,
849 Undoing,
850 Redoing,
851}
852
853#[derive(Clone, PartialEq, Eq, Hash)]
854struct HoveredCursor {
855 replica_id: u16,
856 selection_id: usize,
857}
858
859impl Default for SelectionHistoryMode {
860 fn default() -> Self {
861 Self::Normal
862 }
863}
864
865#[derive(Default)]
866struct SelectionHistory {
867 #[allow(clippy::type_complexity)]
868 selections_by_transaction:
869 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
870 mode: SelectionHistoryMode,
871 undo_stack: VecDeque<SelectionHistoryEntry>,
872 redo_stack: VecDeque<SelectionHistoryEntry>,
873}
874
875impl SelectionHistory {
876 fn insert_transaction(
877 &mut self,
878 transaction_id: TransactionId,
879 selections: Arc<[Selection<Anchor>]>,
880 ) {
881 self.selections_by_transaction
882 .insert(transaction_id, (selections, None));
883 }
884
885 #[allow(clippy::type_complexity)]
886 fn transaction(
887 &self,
888 transaction_id: TransactionId,
889 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
890 self.selections_by_transaction.get(&transaction_id)
891 }
892
893 #[allow(clippy::type_complexity)]
894 fn transaction_mut(
895 &mut self,
896 transaction_id: TransactionId,
897 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
898 self.selections_by_transaction.get_mut(&transaction_id)
899 }
900
901 fn push(&mut self, entry: SelectionHistoryEntry) {
902 if !entry.selections.is_empty() {
903 match self.mode {
904 SelectionHistoryMode::Normal => {
905 self.push_undo(entry);
906 self.redo_stack.clear();
907 }
908 SelectionHistoryMode::Undoing => self.push_redo(entry),
909 SelectionHistoryMode::Redoing => self.push_undo(entry),
910 }
911 }
912 }
913
914 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
915 if self
916 .undo_stack
917 .back()
918 .map_or(true, |e| e.selections != entry.selections)
919 {
920 self.undo_stack.push_back(entry);
921 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
922 self.undo_stack.pop_front();
923 }
924 }
925 }
926
927 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
928 if self
929 .redo_stack
930 .back()
931 .map_or(true, |e| e.selections != entry.selections)
932 {
933 self.redo_stack.push_back(entry);
934 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
935 self.redo_stack.pop_front();
936 }
937 }
938 }
939}
940
941struct RowHighlight {
942 index: usize,
943 range: Range<Anchor>,
944 color: Hsla,
945 should_autoscroll: bool,
946}
947
948#[derive(Clone, Debug)]
949struct AddSelectionsState {
950 above: bool,
951 stack: Vec<usize>,
952}
953
954#[derive(Clone)]
955struct SelectNextState {
956 query: AhoCorasick,
957 wordwise: bool,
958 done: bool,
959}
960
961impl std::fmt::Debug for SelectNextState {
962 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
963 f.debug_struct(std::any::type_name::<Self>())
964 .field("wordwise", &self.wordwise)
965 .field("done", &self.done)
966 .finish()
967 }
968}
969
970#[derive(Debug)]
971struct AutocloseRegion {
972 selection_id: usize,
973 range: Range<Anchor>,
974 pair: BracketPair,
975}
976
977#[derive(Debug)]
978struct SnippetState {
979 ranges: Vec<Vec<Range<Anchor>>>,
980 active_index: usize,
981 choices: Vec<Option<Vec<String>>>,
982}
983
984#[doc(hidden)]
985pub struct RenameState {
986 pub range: Range<Anchor>,
987 pub old_name: Arc<str>,
988 pub editor: Entity<Editor>,
989 block_id: CustomBlockId,
990}
991
992struct InvalidationStack<T>(Vec<T>);
993
994struct RegisteredInlineCompletionProvider {
995 provider: Arc<dyn InlineCompletionProviderHandle>,
996 _subscription: Subscription,
997}
998
999#[derive(Debug, PartialEq, Eq)]
1000struct ActiveDiagnosticGroup {
1001 primary_range: Range<Anchor>,
1002 primary_message: String,
1003 group_id: usize,
1004 blocks: HashMap<CustomBlockId, Diagnostic>,
1005 is_valid: bool,
1006}
1007
1008#[derive(Serialize, Deserialize, Clone, Debug)]
1009pub struct ClipboardSelection {
1010 /// The number of bytes in this selection.
1011 pub len: usize,
1012 /// Whether this was a full-line selection.
1013 pub is_entire_line: bool,
1014 /// The column where this selection originally started.
1015 pub start_column: u32,
1016}
1017
1018#[derive(Debug)]
1019pub(crate) struct NavigationData {
1020 cursor_anchor: Anchor,
1021 cursor_position: Point,
1022 scroll_anchor: ScrollAnchor,
1023 scroll_top_row: u32,
1024}
1025
1026#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1027pub enum GotoDefinitionKind {
1028 Symbol,
1029 Declaration,
1030 Type,
1031 Implementation,
1032}
1033
1034#[derive(Debug, Clone)]
1035enum InlayHintRefreshReason {
1036 ModifiersChanged(bool),
1037 Toggle(bool),
1038 SettingsChange(InlayHintSettings),
1039 NewLinesShown,
1040 BufferEdited(HashSet<Arc<Language>>),
1041 RefreshRequested,
1042 ExcerptsRemoved(Vec<ExcerptId>),
1043}
1044
1045impl InlayHintRefreshReason {
1046 fn description(&self) -> &'static str {
1047 match self {
1048 Self::ModifiersChanged(_) => "modifiers changed",
1049 Self::Toggle(_) => "toggle",
1050 Self::SettingsChange(_) => "settings change",
1051 Self::NewLinesShown => "new lines shown",
1052 Self::BufferEdited(_) => "buffer edited",
1053 Self::RefreshRequested => "refresh requested",
1054 Self::ExcerptsRemoved(_) => "excerpts removed",
1055 }
1056 }
1057}
1058
1059pub enum FormatTarget {
1060 Buffers,
1061 Ranges(Vec<Range<MultiBufferPoint>>),
1062}
1063
1064pub(crate) struct FocusedBlock {
1065 id: BlockId,
1066 focus_handle: WeakFocusHandle,
1067}
1068
1069#[derive(Clone)]
1070enum JumpData {
1071 MultiBufferRow {
1072 row: MultiBufferRow,
1073 line_offset_from_top: u32,
1074 },
1075 MultiBufferPoint {
1076 excerpt_id: ExcerptId,
1077 position: Point,
1078 anchor: text::Anchor,
1079 line_offset_from_top: u32,
1080 },
1081}
1082
1083pub enum MultibufferSelectionMode {
1084 First,
1085 All,
1086}
1087
1088impl Editor {
1089 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1090 let buffer = cx.new(|cx| Buffer::local("", cx));
1091 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1092 Self::new(
1093 EditorMode::SingleLine { auto_width: false },
1094 buffer,
1095 None,
1096 false,
1097 window,
1098 cx,
1099 )
1100 }
1101
1102 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1103 let buffer = cx.new(|cx| Buffer::local("", cx));
1104 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1105 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1106 }
1107
1108 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1109 let buffer = cx.new(|cx| Buffer::local("", cx));
1110 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1111 Self::new(
1112 EditorMode::SingleLine { auto_width: true },
1113 buffer,
1114 None,
1115 false,
1116 window,
1117 cx,
1118 )
1119 }
1120
1121 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1122 let buffer = cx.new(|cx| Buffer::local("", cx));
1123 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1124 Self::new(
1125 EditorMode::AutoHeight { max_lines },
1126 buffer,
1127 None,
1128 false,
1129 window,
1130 cx,
1131 )
1132 }
1133
1134 pub fn for_buffer(
1135 buffer: Entity<Buffer>,
1136 project: Option<Entity<Project>>,
1137 window: &mut Window,
1138 cx: &mut Context<Self>,
1139 ) -> Self {
1140 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1141 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1142 }
1143
1144 pub fn for_multibuffer(
1145 buffer: Entity<MultiBuffer>,
1146 project: Option<Entity<Project>>,
1147 show_excerpt_controls: bool,
1148 window: &mut Window,
1149 cx: &mut Context<Self>,
1150 ) -> Self {
1151 Self::new(
1152 EditorMode::Full,
1153 buffer,
1154 project,
1155 show_excerpt_controls,
1156 window,
1157 cx,
1158 )
1159 }
1160
1161 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1162 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1163 let mut clone = Self::new(
1164 self.mode,
1165 self.buffer.clone(),
1166 self.project.clone(),
1167 show_excerpt_controls,
1168 window,
1169 cx,
1170 );
1171 self.display_map.update(cx, |display_map, cx| {
1172 let snapshot = display_map.snapshot(cx);
1173 clone.display_map.update(cx, |display_map, cx| {
1174 display_map.set_state(&snapshot, cx);
1175 });
1176 });
1177 clone.selections.clone_state(&self.selections);
1178 clone.scroll_manager.clone_state(&self.scroll_manager);
1179 clone.searchable = self.searchable;
1180 clone
1181 }
1182
1183 pub fn new(
1184 mode: EditorMode,
1185 buffer: Entity<MultiBuffer>,
1186 project: Option<Entity<Project>>,
1187 show_excerpt_controls: bool,
1188 window: &mut Window,
1189 cx: &mut Context<Self>,
1190 ) -> Self {
1191 let style = window.text_style();
1192 let font_size = style.font_size.to_pixels(window.rem_size());
1193 let editor = cx.entity().downgrade();
1194 let fold_placeholder = FoldPlaceholder {
1195 constrain_width: true,
1196 render: Arc::new(move |fold_id, fold_range, cx| {
1197 let editor = editor.clone();
1198 div()
1199 .id(fold_id)
1200 .bg(cx.theme().colors().ghost_element_background)
1201 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1202 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1203 .rounded_sm()
1204 .size_full()
1205 .cursor_pointer()
1206 .child("⋯")
1207 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1208 .on_click(move |_, _window, cx| {
1209 editor
1210 .update(cx, |editor, cx| {
1211 editor.unfold_ranges(
1212 &[fold_range.start..fold_range.end],
1213 true,
1214 false,
1215 cx,
1216 );
1217 cx.stop_propagation();
1218 })
1219 .ok();
1220 })
1221 .into_any()
1222 }),
1223 merge_adjacent: true,
1224 ..Default::default()
1225 };
1226 let display_map = cx.new(|cx| {
1227 DisplayMap::new(
1228 buffer.clone(),
1229 style.font(),
1230 font_size,
1231 None,
1232 show_excerpt_controls,
1233 FILE_HEADER_HEIGHT,
1234 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1235 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1236 fold_placeholder,
1237 cx,
1238 )
1239 });
1240
1241 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1242
1243 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1244
1245 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1246 .then(|| language_settings::SoftWrap::None);
1247
1248 let mut project_subscriptions = Vec::new();
1249 if mode == EditorMode::Full {
1250 if let Some(project) = project.as_ref() {
1251 project_subscriptions.push(cx.subscribe_in(
1252 project,
1253 window,
1254 |editor, _, event, window, cx| {
1255 if let project::Event::RefreshInlayHints = event {
1256 editor
1257 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1258 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1259 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1260 let focus_handle = editor.focus_handle(cx);
1261 if focus_handle.is_focused(window) {
1262 let snapshot = buffer.read(cx).snapshot();
1263 for (range, snippet) in snippet_edits {
1264 let editor_range =
1265 language::range_from_lsp(*range).to_offset(&snapshot);
1266 editor
1267 .insert_snippet(
1268 &[editor_range],
1269 snippet.clone(),
1270 window,
1271 cx,
1272 )
1273 .ok();
1274 }
1275 }
1276 }
1277 }
1278 },
1279 ));
1280 if let Some(task_inventory) = project
1281 .read(cx)
1282 .task_store()
1283 .read(cx)
1284 .task_inventory()
1285 .cloned()
1286 {
1287 project_subscriptions.push(cx.observe_in(
1288 &task_inventory,
1289 window,
1290 |editor, _, window, cx| {
1291 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1292 },
1293 ));
1294 }
1295 }
1296 }
1297
1298 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1299
1300 let inlay_hint_settings =
1301 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1302 let focus_handle = cx.focus_handle();
1303 cx.on_focus(&focus_handle, window, Self::handle_focus)
1304 .detach();
1305 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1306 .detach();
1307 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1308 .detach();
1309 cx.on_blur(&focus_handle, window, Self::handle_blur)
1310 .detach();
1311
1312 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1313 Some(false)
1314 } else {
1315 None
1316 };
1317
1318 let mut code_action_providers = Vec::new();
1319 let mut load_uncommitted_diff = None;
1320 if let Some(project) = project.clone() {
1321 load_uncommitted_diff = Some(
1322 get_uncommitted_diff_for_buffer(
1323 &project,
1324 buffer.read(cx).all_buffers(),
1325 buffer.clone(),
1326 cx,
1327 )
1328 .shared(),
1329 );
1330 code_action_providers.push(Rc::new(project) as Rc<_>);
1331 }
1332
1333 let mut this = Self {
1334 focus_handle,
1335 show_cursor_when_unfocused: false,
1336 last_focused_descendant: None,
1337 buffer: buffer.clone(),
1338 display_map: display_map.clone(),
1339 selections,
1340 scroll_manager: ScrollManager::new(cx),
1341 columnar_selection_tail: None,
1342 add_selections_state: None,
1343 select_next_state: None,
1344 select_prev_state: None,
1345 selection_history: Default::default(),
1346 autoclose_regions: Default::default(),
1347 snippet_stack: Default::default(),
1348 select_larger_syntax_node_stack: Vec::new(),
1349 ime_transaction: Default::default(),
1350 active_diagnostics: None,
1351 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1352 inline_diagnostics_update: Task::ready(()),
1353 inline_diagnostics: Vec::new(),
1354 soft_wrap_mode_override,
1355 completion_provider: project.clone().map(|project| Box::new(project) as _),
1356 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1357 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1358 project,
1359 blink_manager: blink_manager.clone(),
1360 show_local_selections: true,
1361 show_scrollbars: true,
1362 mode,
1363 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1364 show_gutter: mode == EditorMode::Full,
1365 show_line_numbers: None,
1366 use_relative_line_numbers: None,
1367 show_git_diff_gutter: None,
1368 show_code_actions: None,
1369 show_runnables: None,
1370 show_wrap_guides: None,
1371 show_indent_guides,
1372 placeholder_text: None,
1373 highlight_order: 0,
1374 highlighted_rows: HashMap::default(),
1375 background_highlights: Default::default(),
1376 gutter_highlights: TreeMap::default(),
1377 scrollbar_marker_state: ScrollbarMarkerState::default(),
1378 active_indent_guides_state: ActiveIndentGuidesState::default(),
1379 nav_history: None,
1380 context_menu: RefCell::new(None),
1381 mouse_context_menu: None,
1382 completion_tasks: Default::default(),
1383 signature_help_state: SignatureHelpState::default(),
1384 auto_signature_help: None,
1385 find_all_references_task_sources: Vec::new(),
1386 next_completion_id: 0,
1387 next_inlay_id: 0,
1388 code_action_providers,
1389 available_code_actions: Default::default(),
1390 code_actions_task: Default::default(),
1391 selection_highlight_task: Default::default(),
1392 document_highlights_task: Default::default(),
1393 linked_editing_range_task: Default::default(),
1394 pending_rename: Default::default(),
1395 searchable: true,
1396 cursor_shape: EditorSettings::get_global(cx)
1397 .cursor_shape
1398 .unwrap_or_default(),
1399 current_line_highlight: None,
1400 autoindent_mode: Some(AutoindentMode::EachLine),
1401 collapse_matches: false,
1402 workspace: None,
1403 input_enabled: true,
1404 use_modal_editing: mode == EditorMode::Full,
1405 read_only: false,
1406 use_autoclose: true,
1407 use_auto_surround: true,
1408 auto_replace_emoji_shortcode: false,
1409 leader_peer_id: None,
1410 remote_id: None,
1411 hover_state: Default::default(),
1412 pending_mouse_down: None,
1413 hovered_link_state: Default::default(),
1414 edit_prediction_provider: None,
1415 active_inline_completion: None,
1416 stale_inline_completion_in_menu: None,
1417 edit_prediction_preview: EditPredictionPreview::Inactive {
1418 released_too_fast: false,
1419 },
1420 inline_diagnostics_enabled: mode == EditorMode::Full,
1421 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1422
1423 gutter_hovered: false,
1424 pixel_position_of_newest_cursor: None,
1425 last_bounds: None,
1426 last_position_map: None,
1427 expect_bounds_change: None,
1428 gutter_dimensions: GutterDimensions::default(),
1429 style: None,
1430 show_cursor_names: false,
1431 hovered_cursors: Default::default(),
1432 next_editor_action_id: EditorActionId::default(),
1433 editor_actions: Rc::default(),
1434 inline_completions_hidden_for_vim_mode: false,
1435 show_inline_completions_override: None,
1436 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1437 edit_prediction_settings: EditPredictionSettings::Disabled,
1438 edit_prediction_indent_conflict: false,
1439 edit_prediction_requires_modifier_in_indent_conflict: true,
1440 custom_context_menu: None,
1441 show_git_blame_gutter: false,
1442 show_git_blame_inline: false,
1443 show_selection_menu: None,
1444 show_git_blame_inline_delay_task: None,
1445 git_blame_inline_tooltip: None,
1446 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1447 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1448 .session
1449 .restore_unsaved_buffers,
1450 blame: None,
1451 blame_subscription: None,
1452 tasks: Default::default(),
1453 _subscriptions: vec![
1454 cx.observe(&buffer, Self::on_buffer_changed),
1455 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1456 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1457 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1458 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1459 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1460 cx.observe_window_activation(window, |editor, window, cx| {
1461 let active = window.is_window_active();
1462 editor.blink_manager.update(cx, |blink_manager, cx| {
1463 if active {
1464 blink_manager.enable(cx);
1465 } else {
1466 blink_manager.disable(cx);
1467 }
1468 });
1469 }),
1470 ],
1471 tasks_update_task: None,
1472 linked_edit_ranges: Default::default(),
1473 in_project_search: false,
1474 previous_search_ranges: None,
1475 breadcrumb_header: None,
1476 focused_block: None,
1477 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1478 addons: HashMap::default(),
1479 registered_buffers: HashMap::default(),
1480 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1481 selection_mark_mode: false,
1482 toggle_fold_multiple_buffers: Task::ready(()),
1483 serialize_selections: Task::ready(()),
1484 text_style_refinement: None,
1485 load_diff_task: load_uncommitted_diff,
1486 };
1487 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1488 this._subscriptions.extend(project_subscriptions);
1489
1490 this.end_selection(window, cx);
1491 this.scroll_manager.show_scrollbar(window, cx);
1492
1493 if mode == EditorMode::Full {
1494 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1495 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1496
1497 if this.git_blame_inline_enabled {
1498 this.git_blame_inline_enabled = true;
1499 this.start_git_blame_inline(false, window, cx);
1500 }
1501
1502 if let Some(buffer) = buffer.read(cx).as_singleton() {
1503 if let Some(project) = this.project.as_ref() {
1504 let handle = project.update(cx, |project, cx| {
1505 project.register_buffer_with_language_servers(&buffer, cx)
1506 });
1507 this.registered_buffers
1508 .insert(buffer.read(cx).remote_id(), handle);
1509 }
1510 }
1511 }
1512
1513 this.report_editor_event("Editor Opened", None, cx);
1514 this
1515 }
1516
1517 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1518 self.mouse_context_menu
1519 .as_ref()
1520 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1521 }
1522
1523 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1524 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1525 }
1526
1527 fn key_context_internal(
1528 &self,
1529 has_active_edit_prediction: bool,
1530 window: &Window,
1531 cx: &App,
1532 ) -> KeyContext {
1533 let mut key_context = KeyContext::new_with_defaults();
1534 key_context.add("Editor");
1535 let mode = match self.mode {
1536 EditorMode::SingleLine { .. } => "single_line",
1537 EditorMode::AutoHeight { .. } => "auto_height",
1538 EditorMode::Full => "full",
1539 };
1540
1541 if EditorSettings::jupyter_enabled(cx) {
1542 key_context.add("jupyter");
1543 }
1544
1545 key_context.set("mode", mode);
1546 if self.pending_rename.is_some() {
1547 key_context.add("renaming");
1548 }
1549
1550 match self.context_menu.borrow().as_ref() {
1551 Some(CodeContextMenu::Completions(_)) => {
1552 key_context.add("menu");
1553 key_context.add("showing_completions");
1554 }
1555 Some(CodeContextMenu::CodeActions(_)) => {
1556 key_context.add("menu");
1557 key_context.add("showing_code_actions")
1558 }
1559 None => {}
1560 }
1561
1562 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1563 if !self.focus_handle(cx).contains_focused(window, cx)
1564 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1565 {
1566 for addon in self.addons.values() {
1567 addon.extend_key_context(&mut key_context, cx)
1568 }
1569 }
1570
1571 if let Some(extension) = self
1572 .buffer
1573 .read(cx)
1574 .as_singleton()
1575 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1576 {
1577 key_context.set("extension", extension.to_string());
1578 }
1579
1580 if has_active_edit_prediction {
1581 if self.edit_prediction_in_conflict() {
1582 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1583 } else {
1584 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1585 key_context.add("copilot_suggestion");
1586 }
1587 }
1588
1589 if self.selection_mark_mode {
1590 key_context.add("selection_mode");
1591 }
1592
1593 key_context
1594 }
1595
1596 pub fn edit_prediction_in_conflict(&self) -> bool {
1597 if !self.show_edit_predictions_in_menu() {
1598 return false;
1599 }
1600
1601 let showing_completions = self
1602 .context_menu
1603 .borrow()
1604 .as_ref()
1605 .map_or(false, |context| {
1606 matches!(context, CodeContextMenu::Completions(_))
1607 });
1608
1609 showing_completions
1610 || self.edit_prediction_requires_modifier()
1611 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1612 // bindings to insert tab characters.
1613 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1614 }
1615
1616 pub fn accept_edit_prediction_keybind(
1617 &self,
1618 window: &Window,
1619 cx: &App,
1620 ) -> AcceptEditPredictionBinding {
1621 let key_context = self.key_context_internal(true, window, cx);
1622 let in_conflict = self.edit_prediction_in_conflict();
1623
1624 AcceptEditPredictionBinding(
1625 window
1626 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1627 .into_iter()
1628 .filter(|binding| {
1629 !in_conflict
1630 || binding
1631 .keystrokes()
1632 .first()
1633 .map_or(false, |keystroke| keystroke.modifiers.modified())
1634 })
1635 .rev()
1636 .min_by_key(|binding| {
1637 binding
1638 .keystrokes()
1639 .first()
1640 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1641 }),
1642 )
1643 }
1644
1645 pub fn new_file(
1646 workspace: &mut Workspace,
1647 _: &workspace::NewFile,
1648 window: &mut Window,
1649 cx: &mut Context<Workspace>,
1650 ) {
1651 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1652 "Failed to create buffer",
1653 window,
1654 cx,
1655 |e, _, _| match e.error_code() {
1656 ErrorCode::RemoteUpgradeRequired => Some(format!(
1657 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1658 e.error_tag("required").unwrap_or("the latest version")
1659 )),
1660 _ => None,
1661 },
1662 );
1663 }
1664
1665 pub fn new_in_workspace(
1666 workspace: &mut Workspace,
1667 window: &mut Window,
1668 cx: &mut Context<Workspace>,
1669 ) -> Task<Result<Entity<Editor>>> {
1670 let project = workspace.project().clone();
1671 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1672
1673 cx.spawn_in(window, |workspace, mut cx| async move {
1674 let buffer = create.await?;
1675 workspace.update_in(&mut cx, |workspace, window, cx| {
1676 let editor =
1677 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1678 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1679 editor
1680 })
1681 })
1682 }
1683
1684 fn new_file_vertical(
1685 workspace: &mut Workspace,
1686 _: &workspace::NewFileSplitVertical,
1687 window: &mut Window,
1688 cx: &mut Context<Workspace>,
1689 ) {
1690 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1691 }
1692
1693 fn new_file_horizontal(
1694 workspace: &mut Workspace,
1695 _: &workspace::NewFileSplitHorizontal,
1696 window: &mut Window,
1697 cx: &mut Context<Workspace>,
1698 ) {
1699 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1700 }
1701
1702 fn new_file_in_direction(
1703 workspace: &mut Workspace,
1704 direction: SplitDirection,
1705 window: &mut Window,
1706 cx: &mut Context<Workspace>,
1707 ) {
1708 let project = workspace.project().clone();
1709 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1710
1711 cx.spawn_in(window, |workspace, mut cx| async move {
1712 let buffer = create.await?;
1713 workspace.update_in(&mut cx, move |workspace, window, cx| {
1714 workspace.split_item(
1715 direction,
1716 Box::new(
1717 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1718 ),
1719 window,
1720 cx,
1721 )
1722 })?;
1723 anyhow::Ok(())
1724 })
1725 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1726 match e.error_code() {
1727 ErrorCode::RemoteUpgradeRequired => Some(format!(
1728 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1729 e.error_tag("required").unwrap_or("the latest version")
1730 )),
1731 _ => None,
1732 }
1733 });
1734 }
1735
1736 pub fn leader_peer_id(&self) -> Option<PeerId> {
1737 self.leader_peer_id
1738 }
1739
1740 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1741 &self.buffer
1742 }
1743
1744 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1745 self.workspace.as_ref()?.0.upgrade()
1746 }
1747
1748 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1749 self.buffer().read(cx).title(cx)
1750 }
1751
1752 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1753 let git_blame_gutter_max_author_length = self
1754 .render_git_blame_gutter(cx)
1755 .then(|| {
1756 if let Some(blame) = self.blame.as_ref() {
1757 let max_author_length =
1758 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1759 Some(max_author_length)
1760 } else {
1761 None
1762 }
1763 })
1764 .flatten();
1765
1766 EditorSnapshot {
1767 mode: self.mode,
1768 show_gutter: self.show_gutter,
1769 show_line_numbers: self.show_line_numbers,
1770 show_git_diff_gutter: self.show_git_diff_gutter,
1771 show_code_actions: self.show_code_actions,
1772 show_runnables: self.show_runnables,
1773 git_blame_gutter_max_author_length,
1774 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1775 scroll_anchor: self.scroll_manager.anchor(),
1776 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1777 placeholder_text: self.placeholder_text.clone(),
1778 is_focused: self.focus_handle.is_focused(window),
1779 current_line_highlight: self
1780 .current_line_highlight
1781 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1782 gutter_hovered: self.gutter_hovered,
1783 }
1784 }
1785
1786 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1787 self.buffer.read(cx).language_at(point, cx)
1788 }
1789
1790 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1791 self.buffer.read(cx).read(cx).file_at(point).cloned()
1792 }
1793
1794 pub fn active_excerpt(
1795 &self,
1796 cx: &App,
1797 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1798 self.buffer
1799 .read(cx)
1800 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1801 }
1802
1803 pub fn mode(&self) -> EditorMode {
1804 self.mode
1805 }
1806
1807 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1808 self.collaboration_hub.as_deref()
1809 }
1810
1811 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1812 self.collaboration_hub = Some(hub);
1813 }
1814
1815 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1816 self.in_project_search = in_project_search;
1817 }
1818
1819 pub fn set_custom_context_menu(
1820 &mut self,
1821 f: impl 'static
1822 + Fn(
1823 &mut Self,
1824 DisplayPoint,
1825 &mut Window,
1826 &mut Context<Self>,
1827 ) -> Option<Entity<ui::ContextMenu>>,
1828 ) {
1829 self.custom_context_menu = Some(Box::new(f))
1830 }
1831
1832 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1833 self.completion_provider = provider;
1834 }
1835
1836 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1837 self.semantics_provider.clone()
1838 }
1839
1840 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1841 self.semantics_provider = provider;
1842 }
1843
1844 pub fn set_edit_prediction_provider<T>(
1845 &mut self,
1846 provider: Option<Entity<T>>,
1847 window: &mut Window,
1848 cx: &mut Context<Self>,
1849 ) where
1850 T: EditPredictionProvider,
1851 {
1852 self.edit_prediction_provider =
1853 provider.map(|provider| RegisteredInlineCompletionProvider {
1854 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1855 if this.focus_handle.is_focused(window) {
1856 this.update_visible_inline_completion(window, cx);
1857 }
1858 }),
1859 provider: Arc::new(provider),
1860 });
1861 self.update_edit_prediction_settings(cx);
1862 self.refresh_inline_completion(false, false, window, cx);
1863 }
1864
1865 pub fn placeholder_text(&self) -> Option<&str> {
1866 self.placeholder_text.as_deref()
1867 }
1868
1869 pub fn set_placeholder_text(
1870 &mut self,
1871 placeholder_text: impl Into<Arc<str>>,
1872 cx: &mut Context<Self>,
1873 ) {
1874 let placeholder_text = Some(placeholder_text.into());
1875 if self.placeholder_text != placeholder_text {
1876 self.placeholder_text = placeholder_text;
1877 cx.notify();
1878 }
1879 }
1880
1881 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1882 self.cursor_shape = cursor_shape;
1883
1884 // Disrupt blink for immediate user feedback that the cursor shape has changed
1885 self.blink_manager.update(cx, BlinkManager::show_cursor);
1886
1887 cx.notify();
1888 }
1889
1890 pub fn set_current_line_highlight(
1891 &mut self,
1892 current_line_highlight: Option<CurrentLineHighlight>,
1893 ) {
1894 self.current_line_highlight = current_line_highlight;
1895 }
1896
1897 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1898 self.collapse_matches = collapse_matches;
1899 }
1900
1901 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1902 let buffers = self.buffer.read(cx).all_buffers();
1903 let Some(project) = self.project.as_ref() else {
1904 return;
1905 };
1906 project.update(cx, |project, cx| {
1907 for buffer in buffers {
1908 self.registered_buffers
1909 .entry(buffer.read(cx).remote_id())
1910 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1911 }
1912 })
1913 }
1914
1915 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1916 if self.collapse_matches {
1917 return range.start..range.start;
1918 }
1919 range.clone()
1920 }
1921
1922 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1923 if self.display_map.read(cx).clip_at_line_ends != clip {
1924 self.display_map
1925 .update(cx, |map, _| map.clip_at_line_ends = clip);
1926 }
1927 }
1928
1929 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1930 self.input_enabled = input_enabled;
1931 }
1932
1933 pub fn set_inline_completions_hidden_for_vim_mode(
1934 &mut self,
1935 hidden: bool,
1936 window: &mut Window,
1937 cx: &mut Context<Self>,
1938 ) {
1939 if hidden != self.inline_completions_hidden_for_vim_mode {
1940 self.inline_completions_hidden_for_vim_mode = hidden;
1941 if hidden {
1942 self.update_visible_inline_completion(window, cx);
1943 } else {
1944 self.refresh_inline_completion(true, false, window, cx);
1945 }
1946 }
1947 }
1948
1949 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1950 self.menu_inline_completions_policy = value;
1951 }
1952
1953 pub fn set_autoindent(&mut self, autoindent: bool) {
1954 if autoindent {
1955 self.autoindent_mode = Some(AutoindentMode::EachLine);
1956 } else {
1957 self.autoindent_mode = None;
1958 }
1959 }
1960
1961 pub fn read_only(&self, cx: &App) -> bool {
1962 self.read_only || self.buffer.read(cx).read_only()
1963 }
1964
1965 pub fn set_read_only(&mut self, read_only: bool) {
1966 self.read_only = read_only;
1967 }
1968
1969 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1970 self.use_autoclose = autoclose;
1971 }
1972
1973 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1974 self.use_auto_surround = auto_surround;
1975 }
1976
1977 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1978 self.auto_replace_emoji_shortcode = auto_replace;
1979 }
1980
1981 pub fn toggle_edit_predictions(
1982 &mut self,
1983 _: &ToggleEditPrediction,
1984 window: &mut Window,
1985 cx: &mut Context<Self>,
1986 ) {
1987 if self.show_inline_completions_override.is_some() {
1988 self.set_show_edit_predictions(None, window, cx);
1989 } else {
1990 let show_edit_predictions = !self.edit_predictions_enabled();
1991 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1992 }
1993 }
1994
1995 pub fn set_show_edit_predictions(
1996 &mut self,
1997 show_edit_predictions: Option<bool>,
1998 window: &mut Window,
1999 cx: &mut Context<Self>,
2000 ) {
2001 self.show_inline_completions_override = show_edit_predictions;
2002 self.update_edit_prediction_settings(cx);
2003
2004 if let Some(false) = show_edit_predictions {
2005 self.discard_inline_completion(false, cx);
2006 } else {
2007 self.refresh_inline_completion(false, true, window, cx);
2008 }
2009 }
2010
2011 fn inline_completions_disabled_in_scope(
2012 &self,
2013 buffer: &Entity<Buffer>,
2014 buffer_position: language::Anchor,
2015 cx: &App,
2016 ) -> bool {
2017 let snapshot = buffer.read(cx).snapshot();
2018 let settings = snapshot.settings_at(buffer_position, cx);
2019
2020 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2021 return false;
2022 };
2023
2024 scope.override_name().map_or(false, |scope_name| {
2025 settings
2026 .edit_predictions_disabled_in
2027 .iter()
2028 .any(|s| s == scope_name)
2029 })
2030 }
2031
2032 pub fn set_use_modal_editing(&mut self, to: bool) {
2033 self.use_modal_editing = to;
2034 }
2035
2036 pub fn use_modal_editing(&self) -> bool {
2037 self.use_modal_editing
2038 }
2039
2040 fn selections_did_change(
2041 &mut self,
2042 local: bool,
2043 old_cursor_position: &Anchor,
2044 show_completions: bool,
2045 window: &mut Window,
2046 cx: &mut Context<Self>,
2047 ) {
2048 window.invalidate_character_coordinates();
2049
2050 // Copy selections to primary selection buffer
2051 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2052 if local {
2053 let selections = self.selections.all::<usize>(cx);
2054 let buffer_handle = self.buffer.read(cx).read(cx);
2055
2056 let mut text = String::new();
2057 for (index, selection) in selections.iter().enumerate() {
2058 let text_for_selection = buffer_handle
2059 .text_for_range(selection.start..selection.end)
2060 .collect::<String>();
2061
2062 text.push_str(&text_for_selection);
2063 if index != selections.len() - 1 {
2064 text.push('\n');
2065 }
2066 }
2067
2068 if !text.is_empty() {
2069 cx.write_to_primary(ClipboardItem::new_string(text));
2070 }
2071 }
2072
2073 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2074 self.buffer.update(cx, |buffer, cx| {
2075 buffer.set_active_selections(
2076 &self.selections.disjoint_anchors(),
2077 self.selections.line_mode,
2078 self.cursor_shape,
2079 cx,
2080 )
2081 });
2082 }
2083 let display_map = self
2084 .display_map
2085 .update(cx, |display_map, cx| display_map.snapshot(cx));
2086 let buffer = &display_map.buffer_snapshot;
2087 self.add_selections_state = None;
2088 self.select_next_state = None;
2089 self.select_prev_state = None;
2090 self.select_larger_syntax_node_stack.clear();
2091 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2092 self.snippet_stack
2093 .invalidate(&self.selections.disjoint_anchors(), buffer);
2094 self.take_rename(false, window, cx);
2095
2096 let new_cursor_position = self.selections.newest_anchor().head();
2097
2098 self.push_to_nav_history(
2099 *old_cursor_position,
2100 Some(new_cursor_position.to_point(buffer)),
2101 cx,
2102 );
2103
2104 if local {
2105 let new_cursor_position = self.selections.newest_anchor().head();
2106 let mut context_menu = self.context_menu.borrow_mut();
2107 let completion_menu = match context_menu.as_ref() {
2108 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2109 _ => {
2110 *context_menu = None;
2111 None
2112 }
2113 };
2114 if let Some(buffer_id) = new_cursor_position.buffer_id {
2115 if !self.registered_buffers.contains_key(&buffer_id) {
2116 if let Some(project) = self.project.as_ref() {
2117 project.update(cx, |project, cx| {
2118 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2119 return;
2120 };
2121 self.registered_buffers.insert(
2122 buffer_id,
2123 project.register_buffer_with_language_servers(&buffer, cx),
2124 );
2125 })
2126 }
2127 }
2128 }
2129
2130 if let Some(completion_menu) = completion_menu {
2131 let cursor_position = new_cursor_position.to_offset(buffer);
2132 let (word_range, kind) =
2133 buffer.surrounding_word(completion_menu.initial_position, true);
2134 if kind == Some(CharKind::Word)
2135 && word_range.to_inclusive().contains(&cursor_position)
2136 {
2137 let mut completion_menu = completion_menu.clone();
2138 drop(context_menu);
2139
2140 let query = Self::completion_query(buffer, cursor_position);
2141 cx.spawn(move |this, mut cx| async move {
2142 completion_menu
2143 .filter(query.as_deref(), cx.background_executor().clone())
2144 .await;
2145
2146 this.update(&mut cx, |this, cx| {
2147 let mut context_menu = this.context_menu.borrow_mut();
2148 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2149 else {
2150 return;
2151 };
2152
2153 if menu.id > completion_menu.id {
2154 return;
2155 }
2156
2157 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2158 drop(context_menu);
2159 cx.notify();
2160 })
2161 })
2162 .detach();
2163
2164 if show_completions {
2165 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2166 }
2167 } else {
2168 drop(context_menu);
2169 self.hide_context_menu(window, cx);
2170 }
2171 } else {
2172 drop(context_menu);
2173 }
2174
2175 hide_hover(self, cx);
2176
2177 if old_cursor_position.to_display_point(&display_map).row()
2178 != new_cursor_position.to_display_point(&display_map).row()
2179 {
2180 self.available_code_actions.take();
2181 }
2182 self.refresh_code_actions(window, cx);
2183 self.refresh_document_highlights(cx);
2184 self.refresh_selected_text_highlights(window, cx);
2185 refresh_matching_bracket_highlights(self, window, cx);
2186 self.update_visible_inline_completion(window, cx);
2187 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2188 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2189 if self.git_blame_inline_enabled {
2190 self.start_inline_blame_timer(window, cx);
2191 }
2192 }
2193
2194 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2195 cx.emit(EditorEvent::SelectionsChanged { local });
2196
2197 let selections = &self.selections.disjoint;
2198 if selections.len() == 1 {
2199 cx.emit(SearchEvent::ActiveMatchChanged)
2200 }
2201 if local
2202 && self.is_singleton(cx)
2203 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2204 {
2205 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2206 let background_executor = cx.background_executor().clone();
2207 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2208 let snapshot = self.buffer().read(cx).snapshot(cx);
2209 let selections = selections.clone();
2210 self.serialize_selections = cx.background_spawn(async move {
2211 background_executor.timer(Duration::from_millis(100)).await;
2212 let selections = selections
2213 .iter()
2214 .map(|selection| {
2215 (
2216 selection.start.to_offset(&snapshot),
2217 selection.end.to_offset(&snapshot),
2218 )
2219 })
2220 .collect();
2221 DB.save_editor_selections(editor_id, workspace_id, selections)
2222 .await
2223 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2224 .log_err();
2225 });
2226 }
2227 }
2228
2229 cx.notify();
2230 }
2231
2232 pub fn sync_selections(
2233 &mut self,
2234 other: Entity<Editor>,
2235 cx: &mut Context<Self>,
2236 ) -> gpui::Subscription {
2237 let other_selections = other.read(cx).selections.disjoint.to_vec();
2238 self.selections.change_with(cx, |selections| {
2239 selections.select_anchors(other_selections);
2240 });
2241
2242 let other_subscription =
2243 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2244 EditorEvent::SelectionsChanged { local: true } => {
2245 let other_selections = other.read(cx).selections.disjoint.to_vec();
2246 if other_selections.is_empty() {
2247 return;
2248 }
2249 this.selections.change_with(cx, |selections| {
2250 selections.select_anchors(other_selections);
2251 });
2252 }
2253 _ => {}
2254 });
2255
2256 let this_subscription =
2257 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2258 EditorEvent::SelectionsChanged { local: true } => {
2259 let these_selections = this.selections.disjoint.to_vec();
2260 if these_selections.is_empty() {
2261 return;
2262 }
2263 other.update(cx, |other_editor, cx| {
2264 other_editor.selections.change_with(cx, |selections| {
2265 selections.select_anchors(these_selections);
2266 })
2267 });
2268 }
2269 _ => {}
2270 });
2271
2272 Subscription::join(other_subscription, this_subscription)
2273 }
2274
2275 pub fn change_selections<R>(
2276 &mut self,
2277 autoscroll: Option<Autoscroll>,
2278 window: &mut Window,
2279 cx: &mut Context<Self>,
2280 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2281 ) -> R {
2282 self.change_selections_inner(autoscroll, true, window, cx, change)
2283 }
2284
2285 fn change_selections_inner<R>(
2286 &mut self,
2287 autoscroll: Option<Autoscroll>,
2288 request_completions: bool,
2289 window: &mut Window,
2290 cx: &mut Context<Self>,
2291 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2292 ) -> R {
2293 let old_cursor_position = self.selections.newest_anchor().head();
2294 self.push_to_selection_history();
2295
2296 let (changed, result) = self.selections.change_with(cx, change);
2297
2298 if changed {
2299 if let Some(autoscroll) = autoscroll {
2300 self.request_autoscroll(autoscroll, cx);
2301 }
2302 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2303
2304 if self.should_open_signature_help_automatically(
2305 &old_cursor_position,
2306 self.signature_help_state.backspace_pressed(),
2307 cx,
2308 ) {
2309 self.show_signature_help(&ShowSignatureHelp, window, cx);
2310 }
2311 self.signature_help_state.set_backspace_pressed(false);
2312 }
2313
2314 result
2315 }
2316
2317 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2318 where
2319 I: IntoIterator<Item = (Range<S>, T)>,
2320 S: ToOffset,
2321 T: Into<Arc<str>>,
2322 {
2323 if self.read_only(cx) {
2324 return;
2325 }
2326
2327 self.buffer
2328 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2329 }
2330
2331 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2332 where
2333 I: IntoIterator<Item = (Range<S>, T)>,
2334 S: ToOffset,
2335 T: Into<Arc<str>>,
2336 {
2337 if self.read_only(cx) {
2338 return;
2339 }
2340
2341 self.buffer.update(cx, |buffer, cx| {
2342 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2343 });
2344 }
2345
2346 pub fn edit_with_block_indent<I, S, T>(
2347 &mut self,
2348 edits: I,
2349 original_start_columns: Vec<u32>,
2350 cx: &mut Context<Self>,
2351 ) where
2352 I: IntoIterator<Item = (Range<S>, T)>,
2353 S: ToOffset,
2354 T: Into<Arc<str>>,
2355 {
2356 if self.read_only(cx) {
2357 return;
2358 }
2359
2360 self.buffer.update(cx, |buffer, cx| {
2361 buffer.edit(
2362 edits,
2363 Some(AutoindentMode::Block {
2364 original_start_columns,
2365 }),
2366 cx,
2367 )
2368 });
2369 }
2370
2371 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2372 self.hide_context_menu(window, cx);
2373
2374 match phase {
2375 SelectPhase::Begin {
2376 position,
2377 add,
2378 click_count,
2379 } => self.begin_selection(position, add, click_count, window, cx),
2380 SelectPhase::BeginColumnar {
2381 position,
2382 goal_column,
2383 reset,
2384 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2385 SelectPhase::Extend {
2386 position,
2387 click_count,
2388 } => self.extend_selection(position, click_count, window, cx),
2389 SelectPhase::Update {
2390 position,
2391 goal_column,
2392 scroll_delta,
2393 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2394 SelectPhase::End => self.end_selection(window, cx),
2395 }
2396 }
2397
2398 fn extend_selection(
2399 &mut self,
2400 position: DisplayPoint,
2401 click_count: usize,
2402 window: &mut Window,
2403 cx: &mut Context<Self>,
2404 ) {
2405 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2406 let tail = self.selections.newest::<usize>(cx).tail();
2407 self.begin_selection(position, false, click_count, window, cx);
2408
2409 let position = position.to_offset(&display_map, Bias::Left);
2410 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2411
2412 let mut pending_selection = self
2413 .selections
2414 .pending_anchor()
2415 .expect("extend_selection not called with pending selection");
2416 if position >= tail {
2417 pending_selection.start = tail_anchor;
2418 } else {
2419 pending_selection.end = tail_anchor;
2420 pending_selection.reversed = true;
2421 }
2422
2423 let mut pending_mode = self.selections.pending_mode().unwrap();
2424 match &mut pending_mode {
2425 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2426 _ => {}
2427 }
2428
2429 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2430 s.set_pending(pending_selection, pending_mode)
2431 });
2432 }
2433
2434 fn begin_selection(
2435 &mut self,
2436 position: DisplayPoint,
2437 add: bool,
2438 click_count: usize,
2439 window: &mut Window,
2440 cx: &mut Context<Self>,
2441 ) {
2442 if !self.focus_handle.is_focused(window) {
2443 self.last_focused_descendant = None;
2444 window.focus(&self.focus_handle);
2445 }
2446
2447 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2448 let buffer = &display_map.buffer_snapshot;
2449 let newest_selection = self.selections.newest_anchor().clone();
2450 let position = display_map.clip_point(position, Bias::Left);
2451
2452 let start;
2453 let end;
2454 let mode;
2455 let mut auto_scroll;
2456 match click_count {
2457 1 => {
2458 start = buffer.anchor_before(position.to_point(&display_map));
2459 end = start;
2460 mode = SelectMode::Character;
2461 auto_scroll = true;
2462 }
2463 2 => {
2464 let range = movement::surrounding_word(&display_map, position);
2465 start = buffer.anchor_before(range.start.to_point(&display_map));
2466 end = buffer.anchor_before(range.end.to_point(&display_map));
2467 mode = SelectMode::Word(start..end);
2468 auto_scroll = true;
2469 }
2470 3 => {
2471 let position = display_map
2472 .clip_point(position, Bias::Left)
2473 .to_point(&display_map);
2474 let line_start = display_map.prev_line_boundary(position).0;
2475 let next_line_start = buffer.clip_point(
2476 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2477 Bias::Left,
2478 );
2479 start = buffer.anchor_before(line_start);
2480 end = buffer.anchor_before(next_line_start);
2481 mode = SelectMode::Line(start..end);
2482 auto_scroll = true;
2483 }
2484 _ => {
2485 start = buffer.anchor_before(0);
2486 end = buffer.anchor_before(buffer.len());
2487 mode = SelectMode::All;
2488 auto_scroll = false;
2489 }
2490 }
2491 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2492
2493 let point_to_delete: Option<usize> = {
2494 let selected_points: Vec<Selection<Point>> =
2495 self.selections.disjoint_in_range(start..end, cx);
2496
2497 if !add || click_count > 1 {
2498 None
2499 } else if !selected_points.is_empty() {
2500 Some(selected_points[0].id)
2501 } else {
2502 let clicked_point_already_selected =
2503 self.selections.disjoint.iter().find(|selection| {
2504 selection.start.to_point(buffer) == start.to_point(buffer)
2505 || selection.end.to_point(buffer) == end.to_point(buffer)
2506 });
2507
2508 clicked_point_already_selected.map(|selection| selection.id)
2509 }
2510 };
2511
2512 let selections_count = self.selections.count();
2513
2514 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2515 if let Some(point_to_delete) = point_to_delete {
2516 s.delete(point_to_delete);
2517
2518 if selections_count == 1 {
2519 s.set_pending_anchor_range(start..end, mode);
2520 }
2521 } else {
2522 if !add {
2523 s.clear_disjoint();
2524 } else if click_count > 1 {
2525 s.delete(newest_selection.id)
2526 }
2527
2528 s.set_pending_anchor_range(start..end, mode);
2529 }
2530 });
2531 }
2532
2533 fn begin_columnar_selection(
2534 &mut self,
2535 position: DisplayPoint,
2536 goal_column: u32,
2537 reset: bool,
2538 window: &mut Window,
2539 cx: &mut Context<Self>,
2540 ) {
2541 if !self.focus_handle.is_focused(window) {
2542 self.last_focused_descendant = None;
2543 window.focus(&self.focus_handle);
2544 }
2545
2546 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2547
2548 if reset {
2549 let pointer_position = display_map
2550 .buffer_snapshot
2551 .anchor_before(position.to_point(&display_map));
2552
2553 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2554 s.clear_disjoint();
2555 s.set_pending_anchor_range(
2556 pointer_position..pointer_position,
2557 SelectMode::Character,
2558 );
2559 });
2560 }
2561
2562 let tail = self.selections.newest::<Point>(cx).tail();
2563 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2564
2565 if !reset {
2566 self.select_columns(
2567 tail.to_display_point(&display_map),
2568 position,
2569 goal_column,
2570 &display_map,
2571 window,
2572 cx,
2573 );
2574 }
2575 }
2576
2577 fn update_selection(
2578 &mut self,
2579 position: DisplayPoint,
2580 goal_column: u32,
2581 scroll_delta: gpui::Point<f32>,
2582 window: &mut Window,
2583 cx: &mut Context<Self>,
2584 ) {
2585 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2586
2587 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2588 let tail = tail.to_display_point(&display_map);
2589 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2590 } else if let Some(mut pending) = self.selections.pending_anchor() {
2591 let buffer = self.buffer.read(cx).snapshot(cx);
2592 let head;
2593 let tail;
2594 let mode = self.selections.pending_mode().unwrap();
2595 match &mode {
2596 SelectMode::Character => {
2597 head = position.to_point(&display_map);
2598 tail = pending.tail().to_point(&buffer);
2599 }
2600 SelectMode::Word(original_range) => {
2601 let original_display_range = original_range.start.to_display_point(&display_map)
2602 ..original_range.end.to_display_point(&display_map);
2603 let original_buffer_range = original_display_range.start.to_point(&display_map)
2604 ..original_display_range.end.to_point(&display_map);
2605 if movement::is_inside_word(&display_map, position)
2606 || original_display_range.contains(&position)
2607 {
2608 let word_range = movement::surrounding_word(&display_map, position);
2609 if word_range.start < original_display_range.start {
2610 head = word_range.start.to_point(&display_map);
2611 } else {
2612 head = word_range.end.to_point(&display_map);
2613 }
2614 } else {
2615 head = position.to_point(&display_map);
2616 }
2617
2618 if head <= original_buffer_range.start {
2619 tail = original_buffer_range.end;
2620 } else {
2621 tail = original_buffer_range.start;
2622 }
2623 }
2624 SelectMode::Line(original_range) => {
2625 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2626
2627 let position = display_map
2628 .clip_point(position, Bias::Left)
2629 .to_point(&display_map);
2630 let line_start = display_map.prev_line_boundary(position).0;
2631 let next_line_start = buffer.clip_point(
2632 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2633 Bias::Left,
2634 );
2635
2636 if line_start < original_range.start {
2637 head = line_start
2638 } else {
2639 head = next_line_start
2640 }
2641
2642 if head <= original_range.start {
2643 tail = original_range.end;
2644 } else {
2645 tail = original_range.start;
2646 }
2647 }
2648 SelectMode::All => {
2649 return;
2650 }
2651 };
2652
2653 if head < tail {
2654 pending.start = buffer.anchor_before(head);
2655 pending.end = buffer.anchor_before(tail);
2656 pending.reversed = true;
2657 } else {
2658 pending.start = buffer.anchor_before(tail);
2659 pending.end = buffer.anchor_before(head);
2660 pending.reversed = false;
2661 }
2662
2663 self.change_selections(None, window, cx, |s| {
2664 s.set_pending(pending, mode);
2665 });
2666 } else {
2667 log::error!("update_selection dispatched with no pending selection");
2668 return;
2669 }
2670
2671 self.apply_scroll_delta(scroll_delta, window, cx);
2672 cx.notify();
2673 }
2674
2675 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2676 self.columnar_selection_tail.take();
2677 if self.selections.pending_anchor().is_some() {
2678 let selections = self.selections.all::<usize>(cx);
2679 self.change_selections(None, window, cx, |s| {
2680 s.select(selections);
2681 s.clear_pending();
2682 });
2683 }
2684 }
2685
2686 fn select_columns(
2687 &mut self,
2688 tail: DisplayPoint,
2689 head: DisplayPoint,
2690 goal_column: u32,
2691 display_map: &DisplaySnapshot,
2692 window: &mut Window,
2693 cx: &mut Context<Self>,
2694 ) {
2695 let start_row = cmp::min(tail.row(), head.row());
2696 let end_row = cmp::max(tail.row(), head.row());
2697 let start_column = cmp::min(tail.column(), goal_column);
2698 let end_column = cmp::max(tail.column(), goal_column);
2699 let reversed = start_column < tail.column();
2700
2701 let selection_ranges = (start_row.0..=end_row.0)
2702 .map(DisplayRow)
2703 .filter_map(|row| {
2704 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2705 let start = display_map
2706 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2707 .to_point(display_map);
2708 let end = display_map
2709 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2710 .to_point(display_map);
2711 if reversed {
2712 Some(end..start)
2713 } else {
2714 Some(start..end)
2715 }
2716 } else {
2717 None
2718 }
2719 })
2720 .collect::<Vec<_>>();
2721
2722 self.change_selections(None, window, cx, |s| {
2723 s.select_ranges(selection_ranges);
2724 });
2725 cx.notify();
2726 }
2727
2728 pub fn has_pending_nonempty_selection(&self) -> bool {
2729 let pending_nonempty_selection = match self.selections.pending_anchor() {
2730 Some(Selection { start, end, .. }) => start != end,
2731 None => false,
2732 };
2733
2734 pending_nonempty_selection
2735 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2736 }
2737
2738 pub fn has_pending_selection(&self) -> bool {
2739 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2740 }
2741
2742 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2743 self.selection_mark_mode = false;
2744
2745 if self.clear_expanded_diff_hunks(cx) {
2746 cx.notify();
2747 return;
2748 }
2749 if self.dismiss_menus_and_popups(true, window, cx) {
2750 return;
2751 }
2752
2753 if self.mode == EditorMode::Full
2754 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2755 {
2756 return;
2757 }
2758
2759 cx.propagate();
2760 }
2761
2762 pub fn dismiss_menus_and_popups(
2763 &mut self,
2764 is_user_requested: bool,
2765 window: &mut Window,
2766 cx: &mut Context<Self>,
2767 ) -> bool {
2768 if self.take_rename(false, window, cx).is_some() {
2769 return true;
2770 }
2771
2772 if hide_hover(self, cx) {
2773 return true;
2774 }
2775
2776 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2777 return true;
2778 }
2779
2780 if self.hide_context_menu(window, cx).is_some() {
2781 return true;
2782 }
2783
2784 if self.mouse_context_menu.take().is_some() {
2785 return true;
2786 }
2787
2788 if is_user_requested && self.discard_inline_completion(true, cx) {
2789 return true;
2790 }
2791
2792 if self.snippet_stack.pop().is_some() {
2793 return true;
2794 }
2795
2796 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2797 self.dismiss_diagnostics(cx);
2798 return true;
2799 }
2800
2801 false
2802 }
2803
2804 fn linked_editing_ranges_for(
2805 &self,
2806 selection: Range<text::Anchor>,
2807 cx: &App,
2808 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2809 if self.linked_edit_ranges.is_empty() {
2810 return None;
2811 }
2812 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2813 selection.end.buffer_id.and_then(|end_buffer_id| {
2814 if selection.start.buffer_id != Some(end_buffer_id) {
2815 return None;
2816 }
2817 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2818 let snapshot = buffer.read(cx).snapshot();
2819 self.linked_edit_ranges
2820 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2821 .map(|ranges| (ranges, snapshot, buffer))
2822 })?;
2823 use text::ToOffset as TO;
2824 // find offset from the start of current range to current cursor position
2825 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2826
2827 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2828 let start_difference = start_offset - start_byte_offset;
2829 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2830 let end_difference = end_offset - start_byte_offset;
2831 // Current range has associated linked ranges.
2832 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2833 for range in linked_ranges.iter() {
2834 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2835 let end_offset = start_offset + end_difference;
2836 let start_offset = start_offset + start_difference;
2837 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2838 continue;
2839 }
2840 if self.selections.disjoint_anchor_ranges().any(|s| {
2841 if s.start.buffer_id != selection.start.buffer_id
2842 || s.end.buffer_id != selection.end.buffer_id
2843 {
2844 return false;
2845 }
2846 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2847 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2848 }) {
2849 continue;
2850 }
2851 let start = buffer_snapshot.anchor_after(start_offset);
2852 let end = buffer_snapshot.anchor_after(end_offset);
2853 linked_edits
2854 .entry(buffer.clone())
2855 .or_default()
2856 .push(start..end);
2857 }
2858 Some(linked_edits)
2859 }
2860
2861 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2862 let text: Arc<str> = text.into();
2863
2864 if self.read_only(cx) {
2865 return;
2866 }
2867
2868 let selections = self.selections.all_adjusted(cx);
2869 let mut bracket_inserted = false;
2870 let mut edits = Vec::new();
2871 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2872 let mut new_selections = Vec::with_capacity(selections.len());
2873 let mut new_autoclose_regions = Vec::new();
2874 let snapshot = self.buffer.read(cx).read(cx);
2875
2876 for (selection, autoclose_region) in
2877 self.selections_with_autoclose_regions(selections, &snapshot)
2878 {
2879 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2880 // Determine if the inserted text matches the opening or closing
2881 // bracket of any of this language's bracket pairs.
2882 let mut bracket_pair = None;
2883 let mut is_bracket_pair_start = false;
2884 let mut is_bracket_pair_end = false;
2885 if !text.is_empty() {
2886 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2887 // and they are removing the character that triggered IME popup.
2888 for (pair, enabled) in scope.brackets() {
2889 if !pair.close && !pair.surround {
2890 continue;
2891 }
2892
2893 if enabled && pair.start.ends_with(text.as_ref()) {
2894 let prefix_len = pair.start.len() - text.len();
2895 let preceding_text_matches_prefix = prefix_len == 0
2896 || (selection.start.column >= (prefix_len as u32)
2897 && snapshot.contains_str_at(
2898 Point::new(
2899 selection.start.row,
2900 selection.start.column - (prefix_len as u32),
2901 ),
2902 &pair.start[..prefix_len],
2903 ));
2904 if preceding_text_matches_prefix {
2905 bracket_pair = Some(pair.clone());
2906 is_bracket_pair_start = true;
2907 break;
2908 }
2909 }
2910 if pair.end.as_str() == text.as_ref() {
2911 bracket_pair = Some(pair.clone());
2912 is_bracket_pair_end = true;
2913 break;
2914 }
2915 }
2916 }
2917
2918 if let Some(bracket_pair) = bracket_pair {
2919 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2920 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2921 let auto_surround =
2922 self.use_auto_surround && snapshot_settings.use_auto_surround;
2923 if selection.is_empty() {
2924 if is_bracket_pair_start {
2925 // If the inserted text is a suffix of an opening bracket and the
2926 // selection is preceded by the rest of the opening bracket, then
2927 // insert the closing bracket.
2928 let following_text_allows_autoclose = snapshot
2929 .chars_at(selection.start)
2930 .next()
2931 .map_or(true, |c| scope.should_autoclose_before(c));
2932
2933 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2934 && bracket_pair.start.len() == 1
2935 {
2936 let target = bracket_pair.start.chars().next().unwrap();
2937 let current_line_count = snapshot
2938 .reversed_chars_at(selection.start)
2939 .take_while(|&c| c != '\n')
2940 .filter(|&c| c == target)
2941 .count();
2942 current_line_count % 2 == 1
2943 } else {
2944 false
2945 };
2946
2947 if autoclose
2948 && bracket_pair.close
2949 && following_text_allows_autoclose
2950 && !is_closing_quote
2951 {
2952 let anchor = snapshot.anchor_before(selection.end);
2953 new_selections.push((selection.map(|_| anchor), text.len()));
2954 new_autoclose_regions.push((
2955 anchor,
2956 text.len(),
2957 selection.id,
2958 bracket_pair.clone(),
2959 ));
2960 edits.push((
2961 selection.range(),
2962 format!("{}{}", text, bracket_pair.end).into(),
2963 ));
2964 bracket_inserted = true;
2965 continue;
2966 }
2967 }
2968
2969 if let Some(region) = autoclose_region {
2970 // If the selection is followed by an auto-inserted closing bracket,
2971 // then don't insert that closing bracket again; just move the selection
2972 // past the closing bracket.
2973 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2974 && text.as_ref() == region.pair.end.as_str();
2975 if should_skip {
2976 let anchor = snapshot.anchor_after(selection.end);
2977 new_selections
2978 .push((selection.map(|_| anchor), region.pair.end.len()));
2979 continue;
2980 }
2981 }
2982
2983 let always_treat_brackets_as_autoclosed = snapshot
2984 .settings_at(selection.start, cx)
2985 .always_treat_brackets_as_autoclosed;
2986 if always_treat_brackets_as_autoclosed
2987 && is_bracket_pair_end
2988 && snapshot.contains_str_at(selection.end, text.as_ref())
2989 {
2990 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2991 // and the inserted text is a closing bracket and the selection is followed
2992 // by the closing bracket then move the selection past the closing bracket.
2993 let anchor = snapshot.anchor_after(selection.end);
2994 new_selections.push((selection.map(|_| anchor), text.len()));
2995 continue;
2996 }
2997 }
2998 // If an opening bracket is 1 character long and is typed while
2999 // text is selected, then surround that text with the bracket pair.
3000 else if auto_surround
3001 && bracket_pair.surround
3002 && is_bracket_pair_start
3003 && bracket_pair.start.chars().count() == 1
3004 {
3005 edits.push((selection.start..selection.start, text.clone()));
3006 edits.push((
3007 selection.end..selection.end,
3008 bracket_pair.end.as_str().into(),
3009 ));
3010 bracket_inserted = true;
3011 new_selections.push((
3012 Selection {
3013 id: selection.id,
3014 start: snapshot.anchor_after(selection.start),
3015 end: snapshot.anchor_before(selection.end),
3016 reversed: selection.reversed,
3017 goal: selection.goal,
3018 },
3019 0,
3020 ));
3021 continue;
3022 }
3023 }
3024 }
3025
3026 if self.auto_replace_emoji_shortcode
3027 && selection.is_empty()
3028 && text.as_ref().ends_with(':')
3029 {
3030 if let Some(possible_emoji_short_code) =
3031 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3032 {
3033 if !possible_emoji_short_code.is_empty() {
3034 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3035 let emoji_shortcode_start = Point::new(
3036 selection.start.row,
3037 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3038 );
3039
3040 // Remove shortcode from buffer
3041 edits.push((
3042 emoji_shortcode_start..selection.start,
3043 "".to_string().into(),
3044 ));
3045 new_selections.push((
3046 Selection {
3047 id: selection.id,
3048 start: snapshot.anchor_after(emoji_shortcode_start),
3049 end: snapshot.anchor_before(selection.start),
3050 reversed: selection.reversed,
3051 goal: selection.goal,
3052 },
3053 0,
3054 ));
3055
3056 // Insert emoji
3057 let selection_start_anchor = snapshot.anchor_after(selection.start);
3058 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3059 edits.push((selection.start..selection.end, emoji.to_string().into()));
3060
3061 continue;
3062 }
3063 }
3064 }
3065 }
3066
3067 // If not handling any auto-close operation, then just replace the selected
3068 // text with the given input and move the selection to the end of the
3069 // newly inserted text.
3070 let anchor = snapshot.anchor_after(selection.end);
3071 if !self.linked_edit_ranges.is_empty() {
3072 let start_anchor = snapshot.anchor_before(selection.start);
3073
3074 let is_word_char = text.chars().next().map_or(true, |char| {
3075 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3076 classifier.is_word(char)
3077 });
3078
3079 if is_word_char {
3080 if let Some(ranges) = self
3081 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3082 {
3083 for (buffer, edits) in ranges {
3084 linked_edits
3085 .entry(buffer.clone())
3086 .or_default()
3087 .extend(edits.into_iter().map(|range| (range, text.clone())));
3088 }
3089 }
3090 }
3091 }
3092
3093 new_selections.push((selection.map(|_| anchor), 0));
3094 edits.push((selection.start..selection.end, text.clone()));
3095 }
3096
3097 drop(snapshot);
3098
3099 self.transact(window, cx, |this, window, cx| {
3100 this.buffer.update(cx, |buffer, cx| {
3101 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3102 });
3103 for (buffer, edits) in linked_edits {
3104 buffer.update(cx, |buffer, cx| {
3105 let snapshot = buffer.snapshot();
3106 let edits = edits
3107 .into_iter()
3108 .map(|(range, text)| {
3109 use text::ToPoint as TP;
3110 let end_point = TP::to_point(&range.end, &snapshot);
3111 let start_point = TP::to_point(&range.start, &snapshot);
3112 (start_point..end_point, text)
3113 })
3114 .sorted_by_key(|(range, _)| range.start)
3115 .collect::<Vec<_>>();
3116 buffer.edit(edits, None, cx);
3117 })
3118 }
3119 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3120 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3121 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3122 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3123 .zip(new_selection_deltas)
3124 .map(|(selection, delta)| Selection {
3125 id: selection.id,
3126 start: selection.start + delta,
3127 end: selection.end + delta,
3128 reversed: selection.reversed,
3129 goal: SelectionGoal::None,
3130 })
3131 .collect::<Vec<_>>();
3132
3133 let mut i = 0;
3134 for (position, delta, selection_id, pair) in new_autoclose_regions {
3135 let position = position.to_offset(&map.buffer_snapshot) + delta;
3136 let start = map.buffer_snapshot.anchor_before(position);
3137 let end = map.buffer_snapshot.anchor_after(position);
3138 while let Some(existing_state) = this.autoclose_regions.get(i) {
3139 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3140 Ordering::Less => i += 1,
3141 Ordering::Greater => break,
3142 Ordering::Equal => {
3143 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3144 Ordering::Less => i += 1,
3145 Ordering::Equal => break,
3146 Ordering::Greater => break,
3147 }
3148 }
3149 }
3150 }
3151 this.autoclose_regions.insert(
3152 i,
3153 AutocloseRegion {
3154 selection_id,
3155 range: start..end,
3156 pair,
3157 },
3158 );
3159 }
3160
3161 let had_active_inline_completion = this.has_active_inline_completion();
3162 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3163 s.select(new_selections)
3164 });
3165
3166 if !bracket_inserted {
3167 if let Some(on_type_format_task) =
3168 this.trigger_on_type_formatting(text.to_string(), window, cx)
3169 {
3170 on_type_format_task.detach_and_log_err(cx);
3171 }
3172 }
3173
3174 let editor_settings = EditorSettings::get_global(cx);
3175 if bracket_inserted
3176 && (editor_settings.auto_signature_help
3177 || editor_settings.show_signature_help_after_edits)
3178 {
3179 this.show_signature_help(&ShowSignatureHelp, window, cx);
3180 }
3181
3182 let trigger_in_words =
3183 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3184 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3185 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3186 this.refresh_inline_completion(true, false, window, cx);
3187 });
3188 }
3189
3190 fn find_possible_emoji_shortcode_at_position(
3191 snapshot: &MultiBufferSnapshot,
3192 position: Point,
3193 ) -> Option<String> {
3194 let mut chars = Vec::new();
3195 let mut found_colon = false;
3196 for char in snapshot.reversed_chars_at(position).take(100) {
3197 // Found a possible emoji shortcode in the middle of the buffer
3198 if found_colon {
3199 if char.is_whitespace() {
3200 chars.reverse();
3201 return Some(chars.iter().collect());
3202 }
3203 // If the previous character is not a whitespace, we are in the middle of a word
3204 // and we only want to complete the shortcode if the word is made up of other emojis
3205 let mut containing_word = String::new();
3206 for ch in snapshot
3207 .reversed_chars_at(position)
3208 .skip(chars.len() + 1)
3209 .take(100)
3210 {
3211 if ch.is_whitespace() {
3212 break;
3213 }
3214 containing_word.push(ch);
3215 }
3216 let containing_word = containing_word.chars().rev().collect::<String>();
3217 if util::word_consists_of_emojis(containing_word.as_str()) {
3218 chars.reverse();
3219 return Some(chars.iter().collect());
3220 }
3221 }
3222
3223 if char.is_whitespace() || !char.is_ascii() {
3224 return None;
3225 }
3226 if char == ':' {
3227 found_colon = true;
3228 } else {
3229 chars.push(char);
3230 }
3231 }
3232 // Found a possible emoji shortcode at the beginning of the buffer
3233 chars.reverse();
3234 Some(chars.iter().collect())
3235 }
3236
3237 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3238 self.transact(window, cx, |this, window, cx| {
3239 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3240 let selections = this.selections.all::<usize>(cx);
3241 let multi_buffer = this.buffer.read(cx);
3242 let buffer = multi_buffer.snapshot(cx);
3243 selections
3244 .iter()
3245 .map(|selection| {
3246 let start_point = selection.start.to_point(&buffer);
3247 let mut indent =
3248 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3249 indent.len = cmp::min(indent.len, start_point.column);
3250 let start = selection.start;
3251 let end = selection.end;
3252 let selection_is_empty = start == end;
3253 let language_scope = buffer.language_scope_at(start);
3254 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3255 &language_scope
3256 {
3257 let insert_extra_newline =
3258 insert_extra_newline_brackets(&buffer, start..end, language)
3259 || insert_extra_newline_tree_sitter(&buffer, start..end);
3260
3261 // Comment extension on newline is allowed only for cursor selections
3262 let comment_delimiter = maybe!({
3263 if !selection_is_empty {
3264 return None;
3265 }
3266
3267 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3268 return None;
3269 }
3270
3271 let delimiters = language.line_comment_prefixes();
3272 let max_len_of_delimiter =
3273 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3274 let (snapshot, range) =
3275 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3276
3277 let mut index_of_first_non_whitespace = 0;
3278 let comment_candidate = snapshot
3279 .chars_for_range(range)
3280 .skip_while(|c| {
3281 let should_skip = c.is_whitespace();
3282 if should_skip {
3283 index_of_first_non_whitespace += 1;
3284 }
3285 should_skip
3286 })
3287 .take(max_len_of_delimiter)
3288 .collect::<String>();
3289 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3290 comment_candidate.starts_with(comment_prefix.as_ref())
3291 })?;
3292 let cursor_is_placed_after_comment_marker =
3293 index_of_first_non_whitespace + comment_prefix.len()
3294 <= start_point.column as usize;
3295 if cursor_is_placed_after_comment_marker {
3296 Some(comment_prefix.clone())
3297 } else {
3298 None
3299 }
3300 });
3301 (comment_delimiter, insert_extra_newline)
3302 } else {
3303 (None, false)
3304 };
3305
3306 let capacity_for_delimiter = comment_delimiter
3307 .as_deref()
3308 .map(str::len)
3309 .unwrap_or_default();
3310 let mut new_text =
3311 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3312 new_text.push('\n');
3313 new_text.extend(indent.chars());
3314 if let Some(delimiter) = &comment_delimiter {
3315 new_text.push_str(delimiter);
3316 }
3317 if insert_extra_newline {
3318 new_text = new_text.repeat(2);
3319 }
3320
3321 let anchor = buffer.anchor_after(end);
3322 let new_selection = selection.map(|_| anchor);
3323 (
3324 (start..end, new_text),
3325 (insert_extra_newline, new_selection),
3326 )
3327 })
3328 .unzip()
3329 };
3330
3331 this.edit_with_autoindent(edits, cx);
3332 let buffer = this.buffer.read(cx).snapshot(cx);
3333 let new_selections = selection_fixup_info
3334 .into_iter()
3335 .map(|(extra_newline_inserted, new_selection)| {
3336 let mut cursor = new_selection.end.to_point(&buffer);
3337 if extra_newline_inserted {
3338 cursor.row -= 1;
3339 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3340 }
3341 new_selection.map(|_| cursor)
3342 })
3343 .collect();
3344
3345 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3346 s.select(new_selections)
3347 });
3348 this.refresh_inline_completion(true, false, window, cx);
3349 });
3350 }
3351
3352 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3353 let buffer = self.buffer.read(cx);
3354 let snapshot = buffer.snapshot(cx);
3355
3356 let mut edits = Vec::new();
3357 let mut rows = Vec::new();
3358
3359 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3360 let cursor = selection.head();
3361 let row = cursor.row;
3362
3363 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3364
3365 let newline = "\n".to_string();
3366 edits.push((start_of_line..start_of_line, newline));
3367
3368 rows.push(row + rows_inserted as u32);
3369 }
3370
3371 self.transact(window, cx, |editor, window, cx| {
3372 editor.edit(edits, cx);
3373
3374 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3375 let mut index = 0;
3376 s.move_cursors_with(|map, _, _| {
3377 let row = rows[index];
3378 index += 1;
3379
3380 let point = Point::new(row, 0);
3381 let boundary = map.next_line_boundary(point).1;
3382 let clipped = map.clip_point(boundary, Bias::Left);
3383
3384 (clipped, SelectionGoal::None)
3385 });
3386 });
3387
3388 let mut indent_edits = Vec::new();
3389 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3390 for row in rows {
3391 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3392 for (row, indent) in indents {
3393 if indent.len == 0 {
3394 continue;
3395 }
3396
3397 let text = match indent.kind {
3398 IndentKind::Space => " ".repeat(indent.len as usize),
3399 IndentKind::Tab => "\t".repeat(indent.len as usize),
3400 };
3401 let point = Point::new(row.0, 0);
3402 indent_edits.push((point..point, text));
3403 }
3404 }
3405 editor.edit(indent_edits, cx);
3406 });
3407 }
3408
3409 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3410 let buffer = self.buffer.read(cx);
3411 let snapshot = buffer.snapshot(cx);
3412
3413 let mut edits = Vec::new();
3414 let mut rows = Vec::new();
3415 let mut rows_inserted = 0;
3416
3417 for selection in self.selections.all_adjusted(cx) {
3418 let cursor = selection.head();
3419 let row = cursor.row;
3420
3421 let point = Point::new(row + 1, 0);
3422 let start_of_line = snapshot.clip_point(point, Bias::Left);
3423
3424 let newline = "\n".to_string();
3425 edits.push((start_of_line..start_of_line, newline));
3426
3427 rows_inserted += 1;
3428 rows.push(row + rows_inserted);
3429 }
3430
3431 self.transact(window, cx, |editor, window, cx| {
3432 editor.edit(edits, cx);
3433
3434 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3435 let mut index = 0;
3436 s.move_cursors_with(|map, _, _| {
3437 let row = rows[index];
3438 index += 1;
3439
3440 let point = Point::new(row, 0);
3441 let boundary = map.next_line_boundary(point).1;
3442 let clipped = map.clip_point(boundary, Bias::Left);
3443
3444 (clipped, SelectionGoal::None)
3445 });
3446 });
3447
3448 let mut indent_edits = Vec::new();
3449 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3450 for row in rows {
3451 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3452 for (row, indent) in indents {
3453 if indent.len == 0 {
3454 continue;
3455 }
3456
3457 let text = match indent.kind {
3458 IndentKind::Space => " ".repeat(indent.len as usize),
3459 IndentKind::Tab => "\t".repeat(indent.len as usize),
3460 };
3461 let point = Point::new(row.0, 0);
3462 indent_edits.push((point..point, text));
3463 }
3464 }
3465 editor.edit(indent_edits, cx);
3466 });
3467 }
3468
3469 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3470 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3471 original_start_columns: Vec::new(),
3472 });
3473 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3474 }
3475
3476 fn insert_with_autoindent_mode(
3477 &mut self,
3478 text: &str,
3479 autoindent_mode: Option<AutoindentMode>,
3480 window: &mut Window,
3481 cx: &mut Context<Self>,
3482 ) {
3483 if self.read_only(cx) {
3484 return;
3485 }
3486
3487 let text: Arc<str> = text.into();
3488 self.transact(window, cx, |this, window, cx| {
3489 let old_selections = this.selections.all_adjusted(cx);
3490 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3491 let anchors = {
3492 let snapshot = buffer.read(cx);
3493 old_selections
3494 .iter()
3495 .map(|s| {
3496 let anchor = snapshot.anchor_after(s.head());
3497 s.map(|_| anchor)
3498 })
3499 .collect::<Vec<_>>()
3500 };
3501 buffer.edit(
3502 old_selections
3503 .iter()
3504 .map(|s| (s.start..s.end, text.clone())),
3505 autoindent_mode,
3506 cx,
3507 );
3508 anchors
3509 });
3510
3511 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3512 s.select_anchors(selection_anchors);
3513 });
3514
3515 cx.notify();
3516 });
3517 }
3518
3519 fn trigger_completion_on_input(
3520 &mut self,
3521 text: &str,
3522 trigger_in_words: bool,
3523 window: &mut Window,
3524 cx: &mut Context<Self>,
3525 ) {
3526 if self.is_completion_trigger(text, trigger_in_words, cx) {
3527 self.show_completions(
3528 &ShowCompletions {
3529 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3530 },
3531 window,
3532 cx,
3533 );
3534 } else {
3535 self.hide_context_menu(window, cx);
3536 }
3537 }
3538
3539 fn is_completion_trigger(
3540 &self,
3541 text: &str,
3542 trigger_in_words: bool,
3543 cx: &mut Context<Self>,
3544 ) -> bool {
3545 let position = self.selections.newest_anchor().head();
3546 let multibuffer = self.buffer.read(cx);
3547 let Some(buffer) = position
3548 .buffer_id
3549 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3550 else {
3551 return false;
3552 };
3553
3554 if let Some(completion_provider) = &self.completion_provider {
3555 completion_provider.is_completion_trigger(
3556 &buffer,
3557 position.text_anchor,
3558 text,
3559 trigger_in_words,
3560 cx,
3561 )
3562 } else {
3563 false
3564 }
3565 }
3566
3567 /// If any empty selections is touching the start of its innermost containing autoclose
3568 /// region, expand it to select the brackets.
3569 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3570 let selections = self.selections.all::<usize>(cx);
3571 let buffer = self.buffer.read(cx).read(cx);
3572 let new_selections = self
3573 .selections_with_autoclose_regions(selections, &buffer)
3574 .map(|(mut selection, region)| {
3575 if !selection.is_empty() {
3576 return selection;
3577 }
3578
3579 if let Some(region) = region {
3580 let mut range = region.range.to_offset(&buffer);
3581 if selection.start == range.start && range.start >= region.pair.start.len() {
3582 range.start -= region.pair.start.len();
3583 if buffer.contains_str_at(range.start, ®ion.pair.start)
3584 && buffer.contains_str_at(range.end, ®ion.pair.end)
3585 {
3586 range.end += region.pair.end.len();
3587 selection.start = range.start;
3588 selection.end = range.end;
3589
3590 return selection;
3591 }
3592 }
3593 }
3594
3595 let always_treat_brackets_as_autoclosed = buffer
3596 .settings_at(selection.start, cx)
3597 .always_treat_brackets_as_autoclosed;
3598
3599 if !always_treat_brackets_as_autoclosed {
3600 return selection;
3601 }
3602
3603 if let Some(scope) = buffer.language_scope_at(selection.start) {
3604 for (pair, enabled) in scope.brackets() {
3605 if !enabled || !pair.close {
3606 continue;
3607 }
3608
3609 if buffer.contains_str_at(selection.start, &pair.end) {
3610 let pair_start_len = pair.start.len();
3611 if buffer.contains_str_at(
3612 selection.start.saturating_sub(pair_start_len),
3613 &pair.start,
3614 ) {
3615 selection.start -= pair_start_len;
3616 selection.end += pair.end.len();
3617
3618 return selection;
3619 }
3620 }
3621 }
3622 }
3623
3624 selection
3625 })
3626 .collect();
3627
3628 drop(buffer);
3629 self.change_selections(None, window, cx, |selections| {
3630 selections.select(new_selections)
3631 });
3632 }
3633
3634 /// Iterate the given selections, and for each one, find the smallest surrounding
3635 /// autoclose region. This uses the ordering of the selections and the autoclose
3636 /// regions to avoid repeated comparisons.
3637 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3638 &'a self,
3639 selections: impl IntoIterator<Item = Selection<D>>,
3640 buffer: &'a MultiBufferSnapshot,
3641 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3642 let mut i = 0;
3643 let mut regions = self.autoclose_regions.as_slice();
3644 selections.into_iter().map(move |selection| {
3645 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3646
3647 let mut enclosing = None;
3648 while let Some(pair_state) = regions.get(i) {
3649 if pair_state.range.end.to_offset(buffer) < range.start {
3650 regions = ®ions[i + 1..];
3651 i = 0;
3652 } else if pair_state.range.start.to_offset(buffer) > range.end {
3653 break;
3654 } else {
3655 if pair_state.selection_id == selection.id {
3656 enclosing = Some(pair_state);
3657 }
3658 i += 1;
3659 }
3660 }
3661
3662 (selection, enclosing)
3663 })
3664 }
3665
3666 /// Remove any autoclose regions that no longer contain their selection.
3667 fn invalidate_autoclose_regions(
3668 &mut self,
3669 mut selections: &[Selection<Anchor>],
3670 buffer: &MultiBufferSnapshot,
3671 ) {
3672 self.autoclose_regions.retain(|state| {
3673 let mut i = 0;
3674 while let Some(selection) = selections.get(i) {
3675 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3676 selections = &selections[1..];
3677 continue;
3678 }
3679 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3680 break;
3681 }
3682 if selection.id == state.selection_id {
3683 return true;
3684 } else {
3685 i += 1;
3686 }
3687 }
3688 false
3689 });
3690 }
3691
3692 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3693 let offset = position.to_offset(buffer);
3694 let (word_range, kind) = buffer.surrounding_word(offset, true);
3695 if offset > word_range.start && kind == Some(CharKind::Word) {
3696 Some(
3697 buffer
3698 .text_for_range(word_range.start..offset)
3699 .collect::<String>(),
3700 )
3701 } else {
3702 None
3703 }
3704 }
3705
3706 pub fn toggle_inlay_hints(
3707 &mut self,
3708 _: &ToggleInlayHints,
3709 _: &mut Window,
3710 cx: &mut Context<Self>,
3711 ) {
3712 self.refresh_inlay_hints(
3713 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3714 cx,
3715 );
3716 }
3717
3718 pub fn inlay_hints_enabled(&self) -> bool {
3719 self.inlay_hint_cache.enabled
3720 }
3721
3722 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3723 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3724 return;
3725 }
3726
3727 let reason_description = reason.description();
3728 let ignore_debounce = matches!(
3729 reason,
3730 InlayHintRefreshReason::SettingsChange(_)
3731 | InlayHintRefreshReason::Toggle(_)
3732 | InlayHintRefreshReason::ExcerptsRemoved(_)
3733 | InlayHintRefreshReason::ModifiersChanged(_)
3734 );
3735 let (invalidate_cache, required_languages) = match reason {
3736 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3737 match self.inlay_hint_cache.modifiers_override(enabled) {
3738 Some(enabled) => {
3739 if enabled {
3740 (InvalidationStrategy::RefreshRequested, None)
3741 } else {
3742 self.splice_inlays(
3743 &self
3744 .visible_inlay_hints(cx)
3745 .iter()
3746 .map(|inlay| inlay.id)
3747 .collect::<Vec<InlayId>>(),
3748 Vec::new(),
3749 cx,
3750 );
3751 return;
3752 }
3753 }
3754 None => return,
3755 }
3756 }
3757 InlayHintRefreshReason::Toggle(enabled) => {
3758 if self.inlay_hint_cache.toggle(enabled) {
3759 if enabled {
3760 (InvalidationStrategy::RefreshRequested, None)
3761 } else {
3762 self.splice_inlays(
3763 &self
3764 .visible_inlay_hints(cx)
3765 .iter()
3766 .map(|inlay| inlay.id)
3767 .collect::<Vec<InlayId>>(),
3768 Vec::new(),
3769 cx,
3770 );
3771 return;
3772 }
3773 } else {
3774 return;
3775 }
3776 }
3777 InlayHintRefreshReason::SettingsChange(new_settings) => {
3778 match self.inlay_hint_cache.update_settings(
3779 &self.buffer,
3780 new_settings,
3781 self.visible_inlay_hints(cx),
3782 cx,
3783 ) {
3784 ControlFlow::Break(Some(InlaySplice {
3785 to_remove,
3786 to_insert,
3787 })) => {
3788 self.splice_inlays(&to_remove, to_insert, cx);
3789 return;
3790 }
3791 ControlFlow::Break(None) => return,
3792 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3793 }
3794 }
3795 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3796 if let Some(InlaySplice {
3797 to_remove,
3798 to_insert,
3799 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3800 {
3801 self.splice_inlays(&to_remove, to_insert, cx);
3802 }
3803 return;
3804 }
3805 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3806 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3807 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3808 }
3809 InlayHintRefreshReason::RefreshRequested => {
3810 (InvalidationStrategy::RefreshRequested, None)
3811 }
3812 };
3813
3814 if let Some(InlaySplice {
3815 to_remove,
3816 to_insert,
3817 }) = self.inlay_hint_cache.spawn_hint_refresh(
3818 reason_description,
3819 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3820 invalidate_cache,
3821 ignore_debounce,
3822 cx,
3823 ) {
3824 self.splice_inlays(&to_remove, to_insert, cx);
3825 }
3826 }
3827
3828 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3829 self.display_map
3830 .read(cx)
3831 .current_inlays()
3832 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3833 .cloned()
3834 .collect()
3835 }
3836
3837 pub fn excerpts_for_inlay_hints_query(
3838 &self,
3839 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3840 cx: &mut Context<Editor>,
3841 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3842 let Some(project) = self.project.as_ref() else {
3843 return HashMap::default();
3844 };
3845 let project = project.read(cx);
3846 let multi_buffer = self.buffer().read(cx);
3847 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3848 let multi_buffer_visible_start = self
3849 .scroll_manager
3850 .anchor()
3851 .anchor
3852 .to_point(&multi_buffer_snapshot);
3853 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3854 multi_buffer_visible_start
3855 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3856 Bias::Left,
3857 );
3858 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3859 multi_buffer_snapshot
3860 .range_to_buffer_ranges(multi_buffer_visible_range)
3861 .into_iter()
3862 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3863 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3864 let buffer_file = project::File::from_dyn(buffer.file())?;
3865 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3866 let worktree_entry = buffer_worktree
3867 .read(cx)
3868 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3869 if worktree_entry.is_ignored {
3870 return None;
3871 }
3872
3873 let language = buffer.language()?;
3874 if let Some(restrict_to_languages) = restrict_to_languages {
3875 if !restrict_to_languages.contains(language) {
3876 return None;
3877 }
3878 }
3879 Some((
3880 excerpt_id,
3881 (
3882 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3883 buffer.version().clone(),
3884 excerpt_visible_range,
3885 ),
3886 ))
3887 })
3888 .collect()
3889 }
3890
3891 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3892 TextLayoutDetails {
3893 text_system: window.text_system().clone(),
3894 editor_style: self.style.clone().unwrap(),
3895 rem_size: window.rem_size(),
3896 scroll_anchor: self.scroll_manager.anchor(),
3897 visible_rows: self.visible_line_count(),
3898 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3899 }
3900 }
3901
3902 pub fn splice_inlays(
3903 &self,
3904 to_remove: &[InlayId],
3905 to_insert: Vec<Inlay>,
3906 cx: &mut Context<Self>,
3907 ) {
3908 self.display_map.update(cx, |display_map, cx| {
3909 display_map.splice_inlays(to_remove, to_insert, cx)
3910 });
3911 cx.notify();
3912 }
3913
3914 fn trigger_on_type_formatting(
3915 &self,
3916 input: String,
3917 window: &mut Window,
3918 cx: &mut Context<Self>,
3919 ) -> Option<Task<Result<()>>> {
3920 if input.len() != 1 {
3921 return None;
3922 }
3923
3924 let project = self.project.as_ref()?;
3925 let position = self.selections.newest_anchor().head();
3926 let (buffer, buffer_position) = self
3927 .buffer
3928 .read(cx)
3929 .text_anchor_for_position(position, cx)?;
3930
3931 let settings = language_settings::language_settings(
3932 buffer
3933 .read(cx)
3934 .language_at(buffer_position)
3935 .map(|l| l.name()),
3936 buffer.read(cx).file(),
3937 cx,
3938 );
3939 if !settings.use_on_type_format {
3940 return None;
3941 }
3942
3943 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3944 // hence we do LSP request & edit on host side only — add formats to host's history.
3945 let push_to_lsp_host_history = true;
3946 // If this is not the host, append its history with new edits.
3947 let push_to_client_history = project.read(cx).is_via_collab();
3948
3949 let on_type_formatting = project.update(cx, |project, cx| {
3950 project.on_type_format(
3951 buffer.clone(),
3952 buffer_position,
3953 input,
3954 push_to_lsp_host_history,
3955 cx,
3956 )
3957 });
3958 Some(cx.spawn_in(window, |editor, mut cx| async move {
3959 if let Some(transaction) = on_type_formatting.await? {
3960 if push_to_client_history {
3961 buffer
3962 .update(&mut cx, |buffer, _| {
3963 buffer.push_transaction(transaction, Instant::now());
3964 })
3965 .ok();
3966 }
3967 editor.update(&mut cx, |editor, cx| {
3968 editor.refresh_document_highlights(cx);
3969 })?;
3970 }
3971 Ok(())
3972 }))
3973 }
3974
3975 pub fn show_completions(
3976 &mut self,
3977 options: &ShowCompletions,
3978 window: &mut Window,
3979 cx: &mut Context<Self>,
3980 ) {
3981 if self.pending_rename.is_some() {
3982 return;
3983 }
3984
3985 let Some(provider) = self.completion_provider.as_ref() else {
3986 return;
3987 };
3988
3989 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3990 return;
3991 }
3992
3993 let position = self.selections.newest_anchor().head();
3994 if position.diff_base_anchor.is_some() {
3995 return;
3996 }
3997 let (buffer, buffer_position) =
3998 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3999 output
4000 } else {
4001 return;
4002 };
4003 let show_completion_documentation = buffer
4004 .read(cx)
4005 .snapshot()
4006 .settings_at(buffer_position, cx)
4007 .show_completion_documentation;
4008
4009 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4010
4011 let trigger_kind = match &options.trigger {
4012 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4013 CompletionTriggerKind::TRIGGER_CHARACTER
4014 }
4015 _ => CompletionTriggerKind::INVOKED,
4016 };
4017 let completion_context = CompletionContext {
4018 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4019 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4020 Some(String::from(trigger))
4021 } else {
4022 None
4023 }
4024 }),
4025 trigger_kind,
4026 };
4027 let completions =
4028 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4029 let sort_completions = provider.sort_completions();
4030
4031 let id = post_inc(&mut self.next_completion_id);
4032 let task = cx.spawn_in(window, |editor, mut cx| {
4033 async move {
4034 editor.update(&mut cx, |this, _| {
4035 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4036 })?;
4037 let completions = completions.await.log_err();
4038 let menu = if let Some(completions) = completions {
4039 let mut menu = CompletionsMenu::new(
4040 id,
4041 sort_completions,
4042 show_completion_documentation,
4043 position,
4044 buffer.clone(),
4045 completions.into(),
4046 );
4047
4048 menu.filter(query.as_deref(), cx.background_executor().clone())
4049 .await;
4050
4051 menu.visible().then_some(menu)
4052 } else {
4053 None
4054 };
4055
4056 editor.update_in(&mut cx, |editor, window, cx| {
4057 match editor.context_menu.borrow().as_ref() {
4058 None => {}
4059 Some(CodeContextMenu::Completions(prev_menu)) => {
4060 if prev_menu.id > id {
4061 return;
4062 }
4063 }
4064 _ => return,
4065 }
4066
4067 if editor.focus_handle.is_focused(window) && menu.is_some() {
4068 let mut menu = menu.unwrap();
4069 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4070
4071 *editor.context_menu.borrow_mut() =
4072 Some(CodeContextMenu::Completions(menu));
4073
4074 if editor.show_edit_predictions_in_menu() {
4075 editor.update_visible_inline_completion(window, cx);
4076 } else {
4077 editor.discard_inline_completion(false, cx);
4078 }
4079
4080 cx.notify();
4081 } else if editor.completion_tasks.len() <= 1 {
4082 // If there are no more completion tasks and the last menu was
4083 // empty, we should hide it.
4084 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4085 // If it was already hidden and we don't show inline
4086 // completions in the menu, we should also show the
4087 // inline-completion when available.
4088 if was_hidden && editor.show_edit_predictions_in_menu() {
4089 editor.update_visible_inline_completion(window, cx);
4090 }
4091 }
4092 })?;
4093
4094 Ok::<_, anyhow::Error>(())
4095 }
4096 .log_err()
4097 });
4098
4099 self.completion_tasks.push((id, task));
4100 }
4101
4102 pub fn confirm_completion(
4103 &mut self,
4104 action: &ConfirmCompletion,
4105 window: &mut Window,
4106 cx: &mut Context<Self>,
4107 ) -> Option<Task<Result<()>>> {
4108 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4109 }
4110
4111 pub fn compose_completion(
4112 &mut self,
4113 action: &ComposeCompletion,
4114 window: &mut Window,
4115 cx: &mut Context<Self>,
4116 ) -> Option<Task<Result<()>>> {
4117 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4118 }
4119
4120 fn do_completion(
4121 &mut self,
4122 item_ix: Option<usize>,
4123 intent: CompletionIntent,
4124 window: &mut Window,
4125 cx: &mut Context<Editor>,
4126 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4127 use language::ToOffset as _;
4128
4129 let completions_menu =
4130 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4131 menu
4132 } else {
4133 return None;
4134 };
4135
4136 let entries = completions_menu.entries.borrow();
4137 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4138 if self.show_edit_predictions_in_menu() {
4139 self.discard_inline_completion(true, cx);
4140 }
4141 let candidate_id = mat.candidate_id;
4142 drop(entries);
4143
4144 let buffer_handle = completions_menu.buffer;
4145 let completion = completions_menu
4146 .completions
4147 .borrow()
4148 .get(candidate_id)?
4149 .clone();
4150 cx.stop_propagation();
4151
4152 let snippet;
4153 let text;
4154
4155 if completion.is_snippet() {
4156 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4157 text = snippet.as_ref().unwrap().text.clone();
4158 } else {
4159 snippet = None;
4160 text = completion.new_text.clone();
4161 };
4162 let selections = self.selections.all::<usize>(cx);
4163 let buffer = buffer_handle.read(cx);
4164 let old_range = completion.old_range.to_offset(buffer);
4165 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4166
4167 let newest_selection = self.selections.newest_anchor();
4168 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4169 return None;
4170 }
4171
4172 let lookbehind = newest_selection
4173 .start
4174 .text_anchor
4175 .to_offset(buffer)
4176 .saturating_sub(old_range.start);
4177 let lookahead = old_range
4178 .end
4179 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4180 let mut common_prefix_len = old_text
4181 .bytes()
4182 .zip(text.bytes())
4183 .take_while(|(a, b)| a == b)
4184 .count();
4185
4186 let snapshot = self.buffer.read(cx).snapshot(cx);
4187 let mut range_to_replace: Option<Range<isize>> = None;
4188 let mut ranges = Vec::new();
4189 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4190 for selection in &selections {
4191 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4192 let start = selection.start.saturating_sub(lookbehind);
4193 let end = selection.end + lookahead;
4194 if selection.id == newest_selection.id {
4195 range_to_replace = Some(
4196 ((start + common_prefix_len) as isize - selection.start as isize)
4197 ..(end as isize - selection.start as isize),
4198 );
4199 }
4200 ranges.push(start + common_prefix_len..end);
4201 } else {
4202 common_prefix_len = 0;
4203 ranges.clear();
4204 ranges.extend(selections.iter().map(|s| {
4205 if s.id == newest_selection.id {
4206 range_to_replace = Some(
4207 old_range.start.to_offset_utf16(&snapshot).0 as isize
4208 - selection.start as isize
4209 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4210 - selection.start as isize,
4211 );
4212 old_range.clone()
4213 } else {
4214 s.start..s.end
4215 }
4216 }));
4217 break;
4218 }
4219 if !self.linked_edit_ranges.is_empty() {
4220 let start_anchor = snapshot.anchor_before(selection.head());
4221 let end_anchor = snapshot.anchor_after(selection.tail());
4222 if let Some(ranges) = self
4223 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4224 {
4225 for (buffer, edits) in ranges {
4226 linked_edits.entry(buffer.clone()).or_default().extend(
4227 edits
4228 .into_iter()
4229 .map(|range| (range, text[common_prefix_len..].to_owned())),
4230 );
4231 }
4232 }
4233 }
4234 }
4235 let text = &text[common_prefix_len..];
4236
4237 cx.emit(EditorEvent::InputHandled {
4238 utf16_range_to_replace: range_to_replace,
4239 text: text.into(),
4240 });
4241
4242 self.transact(window, cx, |this, window, cx| {
4243 if let Some(mut snippet) = snippet {
4244 snippet.text = text.to_string();
4245 for tabstop in snippet
4246 .tabstops
4247 .iter_mut()
4248 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4249 {
4250 tabstop.start -= common_prefix_len as isize;
4251 tabstop.end -= common_prefix_len as isize;
4252 }
4253
4254 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4255 } else {
4256 this.buffer.update(cx, |buffer, cx| {
4257 buffer.edit(
4258 ranges.iter().map(|range| (range.clone(), text)),
4259 this.autoindent_mode.clone(),
4260 cx,
4261 );
4262 });
4263 }
4264 for (buffer, edits) in linked_edits {
4265 buffer.update(cx, |buffer, cx| {
4266 let snapshot = buffer.snapshot();
4267 let edits = edits
4268 .into_iter()
4269 .map(|(range, text)| {
4270 use text::ToPoint as TP;
4271 let end_point = TP::to_point(&range.end, &snapshot);
4272 let start_point = TP::to_point(&range.start, &snapshot);
4273 (start_point..end_point, text)
4274 })
4275 .sorted_by_key(|(range, _)| range.start)
4276 .collect::<Vec<_>>();
4277 buffer.edit(edits, None, cx);
4278 })
4279 }
4280
4281 this.refresh_inline_completion(true, false, window, cx);
4282 });
4283
4284 let show_new_completions_on_confirm = completion
4285 .confirm
4286 .as_ref()
4287 .map_or(false, |confirm| confirm(intent, window, cx));
4288 if show_new_completions_on_confirm {
4289 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4290 }
4291
4292 let provider = self.completion_provider.as_ref()?;
4293 drop(completion);
4294 let apply_edits = provider.apply_additional_edits_for_completion(
4295 buffer_handle,
4296 completions_menu.completions.clone(),
4297 candidate_id,
4298 true,
4299 cx,
4300 );
4301
4302 let editor_settings = EditorSettings::get_global(cx);
4303 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4304 // After the code completion is finished, users often want to know what signatures are needed.
4305 // so we should automatically call signature_help
4306 self.show_signature_help(&ShowSignatureHelp, window, cx);
4307 }
4308
4309 Some(cx.foreground_executor().spawn(async move {
4310 apply_edits.await?;
4311 Ok(())
4312 }))
4313 }
4314
4315 pub fn toggle_code_actions(
4316 &mut self,
4317 action: &ToggleCodeActions,
4318 window: &mut Window,
4319 cx: &mut Context<Self>,
4320 ) {
4321 let mut context_menu = self.context_menu.borrow_mut();
4322 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4323 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4324 // Toggle if we're selecting the same one
4325 *context_menu = None;
4326 cx.notify();
4327 return;
4328 } else {
4329 // Otherwise, clear it and start a new one
4330 *context_menu = None;
4331 cx.notify();
4332 }
4333 }
4334 drop(context_menu);
4335 let snapshot = self.snapshot(window, cx);
4336 let deployed_from_indicator = action.deployed_from_indicator;
4337 let mut task = self.code_actions_task.take();
4338 let action = action.clone();
4339 cx.spawn_in(window, |editor, mut cx| async move {
4340 while let Some(prev_task) = task {
4341 prev_task.await.log_err();
4342 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4343 }
4344
4345 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4346 if editor.focus_handle.is_focused(window) {
4347 let multibuffer_point = action
4348 .deployed_from_indicator
4349 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4350 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4351 let (buffer, buffer_row) = snapshot
4352 .buffer_snapshot
4353 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4354 .and_then(|(buffer_snapshot, range)| {
4355 editor
4356 .buffer
4357 .read(cx)
4358 .buffer(buffer_snapshot.remote_id())
4359 .map(|buffer| (buffer, range.start.row))
4360 })?;
4361 let (_, code_actions) = editor
4362 .available_code_actions
4363 .clone()
4364 .and_then(|(location, code_actions)| {
4365 let snapshot = location.buffer.read(cx).snapshot();
4366 let point_range = location.range.to_point(&snapshot);
4367 let point_range = point_range.start.row..=point_range.end.row;
4368 if point_range.contains(&buffer_row) {
4369 Some((location, code_actions))
4370 } else {
4371 None
4372 }
4373 })
4374 .unzip();
4375 let buffer_id = buffer.read(cx).remote_id();
4376 let tasks = editor
4377 .tasks
4378 .get(&(buffer_id, buffer_row))
4379 .map(|t| Arc::new(t.to_owned()));
4380 if tasks.is_none() && code_actions.is_none() {
4381 return None;
4382 }
4383
4384 editor.completion_tasks.clear();
4385 editor.discard_inline_completion(false, cx);
4386 let task_context =
4387 tasks
4388 .as_ref()
4389 .zip(editor.project.clone())
4390 .map(|(tasks, project)| {
4391 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4392 });
4393
4394 Some(cx.spawn_in(window, |editor, mut cx| async move {
4395 let task_context = match task_context {
4396 Some(task_context) => task_context.await,
4397 None => None,
4398 };
4399 let resolved_tasks =
4400 tasks.zip(task_context).map(|(tasks, task_context)| {
4401 Rc::new(ResolvedTasks {
4402 templates: tasks.resolve(&task_context).collect(),
4403 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4404 multibuffer_point.row,
4405 tasks.column,
4406 )),
4407 })
4408 });
4409 let spawn_straight_away = resolved_tasks
4410 .as_ref()
4411 .map_or(false, |tasks| tasks.templates.len() == 1)
4412 && code_actions
4413 .as_ref()
4414 .map_or(true, |actions| actions.is_empty());
4415 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4416 *editor.context_menu.borrow_mut() =
4417 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4418 buffer,
4419 actions: CodeActionContents {
4420 tasks: resolved_tasks,
4421 actions: code_actions,
4422 },
4423 selected_item: Default::default(),
4424 scroll_handle: UniformListScrollHandle::default(),
4425 deployed_from_indicator,
4426 }));
4427 if spawn_straight_away {
4428 if let Some(task) = editor.confirm_code_action(
4429 &ConfirmCodeAction { item_ix: Some(0) },
4430 window,
4431 cx,
4432 ) {
4433 cx.notify();
4434 return task;
4435 }
4436 }
4437 cx.notify();
4438 Task::ready(Ok(()))
4439 }) {
4440 task.await
4441 } else {
4442 Ok(())
4443 }
4444 }))
4445 } else {
4446 Some(Task::ready(Ok(())))
4447 }
4448 })?;
4449 if let Some(task) = spawned_test_task {
4450 task.await?;
4451 }
4452
4453 Ok::<_, anyhow::Error>(())
4454 })
4455 .detach_and_log_err(cx);
4456 }
4457
4458 pub fn confirm_code_action(
4459 &mut self,
4460 action: &ConfirmCodeAction,
4461 window: &mut Window,
4462 cx: &mut Context<Self>,
4463 ) -> Option<Task<Result<()>>> {
4464 let actions_menu =
4465 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4466 menu
4467 } else {
4468 return None;
4469 };
4470 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4471 let action = actions_menu.actions.get(action_ix)?;
4472 let title = action.label();
4473 let buffer = actions_menu.buffer;
4474 let workspace = self.workspace()?;
4475
4476 match action {
4477 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4478 workspace.update(cx, |workspace, cx| {
4479 workspace::tasks::schedule_resolved_task(
4480 workspace,
4481 task_source_kind,
4482 resolved_task,
4483 false,
4484 cx,
4485 );
4486
4487 Some(Task::ready(Ok(())))
4488 })
4489 }
4490 CodeActionsItem::CodeAction {
4491 excerpt_id,
4492 action,
4493 provider,
4494 } => {
4495 let apply_code_action =
4496 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4497 let workspace = workspace.downgrade();
4498 Some(cx.spawn_in(window, |editor, cx| async move {
4499 let project_transaction = apply_code_action.await?;
4500 Self::open_project_transaction(
4501 &editor,
4502 workspace,
4503 project_transaction,
4504 title,
4505 cx,
4506 )
4507 .await
4508 }))
4509 }
4510 }
4511 }
4512
4513 pub async fn open_project_transaction(
4514 this: &WeakEntity<Editor>,
4515 workspace: WeakEntity<Workspace>,
4516 transaction: ProjectTransaction,
4517 title: String,
4518 mut cx: AsyncWindowContext,
4519 ) -> Result<()> {
4520 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4521 cx.update(|_, cx| {
4522 entries.sort_unstable_by_key(|(buffer, _)| {
4523 buffer.read(cx).file().map(|f| f.path().clone())
4524 });
4525 })?;
4526
4527 // If the project transaction's edits are all contained within this editor, then
4528 // avoid opening a new editor to display them.
4529
4530 if let Some((buffer, transaction)) = entries.first() {
4531 if entries.len() == 1 {
4532 let excerpt = this.update(&mut cx, |editor, cx| {
4533 editor
4534 .buffer()
4535 .read(cx)
4536 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4537 })?;
4538 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4539 if excerpted_buffer == *buffer {
4540 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4541 let excerpt_range = excerpt_range.to_offset(buffer);
4542 buffer
4543 .edited_ranges_for_transaction::<usize>(transaction)
4544 .all(|range| {
4545 excerpt_range.start <= range.start
4546 && excerpt_range.end >= range.end
4547 })
4548 })?;
4549
4550 if all_edits_within_excerpt {
4551 return Ok(());
4552 }
4553 }
4554 }
4555 }
4556 } else {
4557 return Ok(());
4558 }
4559
4560 let mut ranges_to_highlight = Vec::new();
4561 let excerpt_buffer = cx.new(|cx| {
4562 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4563 for (buffer_handle, transaction) in &entries {
4564 let buffer = buffer_handle.read(cx);
4565 ranges_to_highlight.extend(
4566 multibuffer.push_excerpts_with_context_lines(
4567 buffer_handle.clone(),
4568 buffer
4569 .edited_ranges_for_transaction::<usize>(transaction)
4570 .collect(),
4571 DEFAULT_MULTIBUFFER_CONTEXT,
4572 cx,
4573 ),
4574 );
4575 }
4576 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4577 multibuffer
4578 })?;
4579
4580 workspace.update_in(&mut cx, |workspace, window, cx| {
4581 let project = workspace.project().clone();
4582 let editor = cx
4583 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4584 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4585 editor.update(cx, |editor, cx| {
4586 editor.highlight_background::<Self>(
4587 &ranges_to_highlight,
4588 |theme| theme.editor_highlighted_line_background,
4589 cx,
4590 );
4591 });
4592 })?;
4593
4594 Ok(())
4595 }
4596
4597 pub fn clear_code_action_providers(&mut self) {
4598 self.code_action_providers.clear();
4599 self.available_code_actions.take();
4600 }
4601
4602 pub fn add_code_action_provider(
4603 &mut self,
4604 provider: Rc<dyn CodeActionProvider>,
4605 window: &mut Window,
4606 cx: &mut Context<Self>,
4607 ) {
4608 if self
4609 .code_action_providers
4610 .iter()
4611 .any(|existing_provider| existing_provider.id() == provider.id())
4612 {
4613 return;
4614 }
4615
4616 self.code_action_providers.push(provider);
4617 self.refresh_code_actions(window, cx);
4618 }
4619
4620 pub fn remove_code_action_provider(
4621 &mut self,
4622 id: Arc<str>,
4623 window: &mut Window,
4624 cx: &mut Context<Self>,
4625 ) {
4626 self.code_action_providers
4627 .retain(|provider| provider.id() != id);
4628 self.refresh_code_actions(window, cx);
4629 }
4630
4631 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4632 let buffer = self.buffer.read(cx);
4633 let newest_selection = self.selections.newest_anchor().clone();
4634 if newest_selection.head().diff_base_anchor.is_some() {
4635 return None;
4636 }
4637 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4638 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4639 if start_buffer != end_buffer {
4640 return None;
4641 }
4642
4643 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4644 cx.background_executor()
4645 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4646 .await;
4647
4648 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4649 let providers = this.code_action_providers.clone();
4650 let tasks = this
4651 .code_action_providers
4652 .iter()
4653 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4654 .collect::<Vec<_>>();
4655 (providers, tasks)
4656 })?;
4657
4658 let mut actions = Vec::new();
4659 for (provider, provider_actions) in
4660 providers.into_iter().zip(future::join_all(tasks).await)
4661 {
4662 if let Some(provider_actions) = provider_actions.log_err() {
4663 actions.extend(provider_actions.into_iter().map(|action| {
4664 AvailableCodeAction {
4665 excerpt_id: newest_selection.start.excerpt_id,
4666 action,
4667 provider: provider.clone(),
4668 }
4669 }));
4670 }
4671 }
4672
4673 this.update(&mut cx, |this, cx| {
4674 this.available_code_actions = if actions.is_empty() {
4675 None
4676 } else {
4677 Some((
4678 Location {
4679 buffer: start_buffer,
4680 range: start..end,
4681 },
4682 actions.into(),
4683 ))
4684 };
4685 cx.notify();
4686 })
4687 }));
4688 None
4689 }
4690
4691 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4692 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4693 self.show_git_blame_inline = false;
4694
4695 self.show_git_blame_inline_delay_task =
4696 Some(cx.spawn_in(window, |this, mut cx| async move {
4697 cx.background_executor().timer(delay).await;
4698
4699 this.update(&mut cx, |this, cx| {
4700 this.show_git_blame_inline = true;
4701 cx.notify();
4702 })
4703 .log_err();
4704 }));
4705 }
4706 }
4707
4708 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4709 if self.pending_rename.is_some() {
4710 return None;
4711 }
4712
4713 let provider = self.semantics_provider.clone()?;
4714 let buffer = self.buffer.read(cx);
4715 let newest_selection = self.selections.newest_anchor().clone();
4716 let cursor_position = newest_selection.head();
4717 let (cursor_buffer, cursor_buffer_position) =
4718 buffer.text_anchor_for_position(cursor_position, cx)?;
4719 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4720 if cursor_buffer != tail_buffer {
4721 return None;
4722 }
4723 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4724 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4725 cx.background_executor()
4726 .timer(Duration::from_millis(debounce))
4727 .await;
4728
4729 let highlights = if let Some(highlights) = cx
4730 .update(|cx| {
4731 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4732 })
4733 .ok()
4734 .flatten()
4735 {
4736 highlights.await.log_err()
4737 } else {
4738 None
4739 };
4740
4741 if let Some(highlights) = highlights {
4742 this.update(&mut cx, |this, cx| {
4743 if this.pending_rename.is_some() {
4744 return;
4745 }
4746
4747 let buffer_id = cursor_position.buffer_id;
4748 let buffer = this.buffer.read(cx);
4749 if !buffer
4750 .text_anchor_for_position(cursor_position, cx)
4751 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4752 {
4753 return;
4754 }
4755
4756 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4757 let mut write_ranges = Vec::new();
4758 let mut read_ranges = Vec::new();
4759 for highlight in highlights {
4760 for (excerpt_id, excerpt_range) in
4761 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4762 {
4763 let start = highlight
4764 .range
4765 .start
4766 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4767 let end = highlight
4768 .range
4769 .end
4770 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4771 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4772 continue;
4773 }
4774
4775 let range = Anchor {
4776 buffer_id,
4777 excerpt_id,
4778 text_anchor: start,
4779 diff_base_anchor: None,
4780 }..Anchor {
4781 buffer_id,
4782 excerpt_id,
4783 text_anchor: end,
4784 diff_base_anchor: None,
4785 };
4786 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4787 write_ranges.push(range);
4788 } else {
4789 read_ranges.push(range);
4790 }
4791 }
4792 }
4793
4794 this.highlight_background::<DocumentHighlightRead>(
4795 &read_ranges,
4796 |theme| theme.editor_document_highlight_read_background,
4797 cx,
4798 );
4799 this.highlight_background::<DocumentHighlightWrite>(
4800 &write_ranges,
4801 |theme| theme.editor_document_highlight_write_background,
4802 cx,
4803 );
4804 cx.notify();
4805 })
4806 .log_err();
4807 }
4808 }));
4809 None
4810 }
4811
4812 pub fn refresh_selected_text_highlights(
4813 &mut self,
4814 window: &mut Window,
4815 cx: &mut Context<Editor>,
4816 ) {
4817 self.selection_highlight_task.take();
4818 if !EditorSettings::get_global(cx).selection_highlight {
4819 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4820 return;
4821 }
4822 if self.selections.count() != 1 || self.selections.line_mode {
4823 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4824 return;
4825 }
4826 let selection = self.selections.newest::<Point>(cx);
4827 if selection.is_empty() || selection.start.row != selection.end.row {
4828 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4829 return;
4830 }
4831 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4832 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4833 cx.background_executor()
4834 .timer(Duration::from_millis(debounce))
4835 .await;
4836 let Some(Some(matches_task)) = editor
4837 .update_in(&mut cx, |editor, _, cx| {
4838 if editor.selections.count() != 1 || editor.selections.line_mode {
4839 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4840 return None;
4841 }
4842 let selection = editor.selections.newest::<Point>(cx);
4843 if selection.is_empty() || selection.start.row != selection.end.row {
4844 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4845 return None;
4846 }
4847 let buffer = editor.buffer().read(cx).snapshot(cx);
4848 let query = buffer.text_for_range(selection.range()).collect::<String>();
4849 if query.trim().is_empty() {
4850 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4851 return None;
4852 }
4853 Some(cx.background_spawn(async move {
4854 let mut ranges = Vec::new();
4855 let selection_anchors = selection.range().to_anchors(&buffer);
4856 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4857 for (search_buffer, search_range, excerpt_id) in
4858 buffer.range_to_buffer_ranges(range)
4859 {
4860 ranges.extend(
4861 project::search::SearchQuery::text(
4862 query.clone(),
4863 false,
4864 false,
4865 false,
4866 Default::default(),
4867 Default::default(),
4868 None,
4869 )
4870 .unwrap()
4871 .search(search_buffer, Some(search_range.clone()))
4872 .await
4873 .into_iter()
4874 .filter_map(
4875 |match_range| {
4876 let start = search_buffer.anchor_after(
4877 search_range.start + match_range.start,
4878 );
4879 let end = search_buffer.anchor_before(
4880 search_range.start + match_range.end,
4881 );
4882 let range = Anchor::range_in_buffer(
4883 excerpt_id,
4884 search_buffer.remote_id(),
4885 start..end,
4886 );
4887 (range != selection_anchors).then_some(range)
4888 },
4889 ),
4890 );
4891 }
4892 }
4893 ranges
4894 }))
4895 })
4896 .log_err()
4897 else {
4898 return;
4899 };
4900 let matches = matches_task.await;
4901 editor
4902 .update_in(&mut cx, |editor, _, cx| {
4903 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4904 if !matches.is_empty() {
4905 editor.highlight_background::<SelectedTextHighlight>(
4906 &matches,
4907 |theme| theme.editor_document_highlight_bracket_background,
4908 cx,
4909 )
4910 }
4911 })
4912 .log_err();
4913 }));
4914 }
4915
4916 pub fn refresh_inline_completion(
4917 &mut self,
4918 debounce: bool,
4919 user_requested: bool,
4920 window: &mut Window,
4921 cx: &mut Context<Self>,
4922 ) -> Option<()> {
4923 let provider = self.edit_prediction_provider()?;
4924 let cursor = self.selections.newest_anchor().head();
4925 let (buffer, cursor_buffer_position) =
4926 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4927
4928 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4929 self.discard_inline_completion(false, cx);
4930 return None;
4931 }
4932
4933 if !user_requested
4934 && (!self.should_show_edit_predictions()
4935 || !self.is_focused(window)
4936 || buffer.read(cx).is_empty())
4937 {
4938 self.discard_inline_completion(false, cx);
4939 return None;
4940 }
4941
4942 self.update_visible_inline_completion(window, cx);
4943 provider.refresh(
4944 self.project.clone(),
4945 buffer,
4946 cursor_buffer_position,
4947 debounce,
4948 cx,
4949 );
4950 Some(())
4951 }
4952
4953 fn show_edit_predictions_in_menu(&self) -> bool {
4954 match self.edit_prediction_settings {
4955 EditPredictionSettings::Disabled => false,
4956 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4957 }
4958 }
4959
4960 pub fn edit_predictions_enabled(&self) -> bool {
4961 match self.edit_prediction_settings {
4962 EditPredictionSettings::Disabled => false,
4963 EditPredictionSettings::Enabled { .. } => true,
4964 }
4965 }
4966
4967 fn edit_prediction_requires_modifier(&self) -> bool {
4968 match self.edit_prediction_settings {
4969 EditPredictionSettings::Disabled => false,
4970 EditPredictionSettings::Enabled {
4971 preview_requires_modifier,
4972 ..
4973 } => preview_requires_modifier,
4974 }
4975 }
4976
4977 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4978 if self.edit_prediction_provider.is_none() {
4979 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4980 } else {
4981 let selection = self.selections.newest_anchor();
4982 let cursor = selection.head();
4983
4984 if let Some((buffer, cursor_buffer_position)) =
4985 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4986 {
4987 self.edit_prediction_settings =
4988 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
4989 }
4990 }
4991 }
4992
4993 fn edit_prediction_settings_at_position(
4994 &self,
4995 buffer: &Entity<Buffer>,
4996 buffer_position: language::Anchor,
4997 cx: &App,
4998 ) -> EditPredictionSettings {
4999 if self.mode != EditorMode::Full
5000 || !self.show_inline_completions_override.unwrap_or(true)
5001 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5002 {
5003 return EditPredictionSettings::Disabled;
5004 }
5005
5006 let buffer = buffer.read(cx);
5007
5008 let file = buffer.file();
5009
5010 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5011 return EditPredictionSettings::Disabled;
5012 };
5013
5014 let by_provider = matches!(
5015 self.menu_inline_completions_policy,
5016 MenuInlineCompletionsPolicy::ByProvider
5017 );
5018
5019 let show_in_menu = by_provider
5020 && self
5021 .edit_prediction_provider
5022 .as_ref()
5023 .map_or(false, |provider| {
5024 provider.provider.show_completions_in_menu()
5025 });
5026
5027 let preview_requires_modifier =
5028 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5029
5030 EditPredictionSettings::Enabled {
5031 show_in_menu,
5032 preview_requires_modifier,
5033 }
5034 }
5035
5036 fn should_show_edit_predictions(&self) -> bool {
5037 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5038 }
5039
5040 pub fn edit_prediction_preview_is_active(&self) -> bool {
5041 matches!(
5042 self.edit_prediction_preview,
5043 EditPredictionPreview::Active { .. }
5044 )
5045 }
5046
5047 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5048 let cursor = self.selections.newest_anchor().head();
5049 if let Some((buffer, cursor_position)) =
5050 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5051 {
5052 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5053 } else {
5054 false
5055 }
5056 }
5057
5058 fn edit_predictions_enabled_in_buffer(
5059 &self,
5060 buffer: &Entity<Buffer>,
5061 buffer_position: language::Anchor,
5062 cx: &App,
5063 ) -> bool {
5064 maybe!({
5065 let provider = self.edit_prediction_provider()?;
5066 if !provider.is_enabled(&buffer, buffer_position, cx) {
5067 return Some(false);
5068 }
5069 let buffer = buffer.read(cx);
5070 let Some(file) = buffer.file() else {
5071 return Some(true);
5072 };
5073 let settings = all_language_settings(Some(file), cx);
5074 Some(settings.edit_predictions_enabled_for_file(file, cx))
5075 })
5076 .unwrap_or(false)
5077 }
5078
5079 fn cycle_inline_completion(
5080 &mut self,
5081 direction: Direction,
5082 window: &mut Window,
5083 cx: &mut Context<Self>,
5084 ) -> Option<()> {
5085 let provider = self.edit_prediction_provider()?;
5086 let cursor = self.selections.newest_anchor().head();
5087 let (buffer, cursor_buffer_position) =
5088 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5089 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5090 return None;
5091 }
5092
5093 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5094 self.update_visible_inline_completion(window, cx);
5095
5096 Some(())
5097 }
5098
5099 pub fn show_inline_completion(
5100 &mut self,
5101 _: &ShowEditPrediction,
5102 window: &mut Window,
5103 cx: &mut Context<Self>,
5104 ) {
5105 if !self.has_active_inline_completion() {
5106 self.refresh_inline_completion(false, true, window, cx);
5107 return;
5108 }
5109
5110 self.update_visible_inline_completion(window, cx);
5111 }
5112
5113 pub fn display_cursor_names(
5114 &mut self,
5115 _: &DisplayCursorNames,
5116 window: &mut Window,
5117 cx: &mut Context<Self>,
5118 ) {
5119 self.show_cursor_names(window, cx);
5120 }
5121
5122 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5123 self.show_cursor_names = true;
5124 cx.notify();
5125 cx.spawn_in(window, |this, mut cx| async move {
5126 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5127 this.update(&mut cx, |this, cx| {
5128 this.show_cursor_names = false;
5129 cx.notify()
5130 })
5131 .ok()
5132 })
5133 .detach();
5134 }
5135
5136 pub fn next_edit_prediction(
5137 &mut self,
5138 _: &NextEditPrediction,
5139 window: &mut Window,
5140 cx: &mut Context<Self>,
5141 ) {
5142 if self.has_active_inline_completion() {
5143 self.cycle_inline_completion(Direction::Next, window, cx);
5144 } else {
5145 let is_copilot_disabled = self
5146 .refresh_inline_completion(false, true, window, cx)
5147 .is_none();
5148 if is_copilot_disabled {
5149 cx.propagate();
5150 }
5151 }
5152 }
5153
5154 pub fn previous_edit_prediction(
5155 &mut self,
5156 _: &PreviousEditPrediction,
5157 window: &mut Window,
5158 cx: &mut Context<Self>,
5159 ) {
5160 if self.has_active_inline_completion() {
5161 self.cycle_inline_completion(Direction::Prev, window, cx);
5162 } else {
5163 let is_copilot_disabled = self
5164 .refresh_inline_completion(false, true, window, cx)
5165 .is_none();
5166 if is_copilot_disabled {
5167 cx.propagate();
5168 }
5169 }
5170 }
5171
5172 pub fn accept_edit_prediction(
5173 &mut self,
5174 _: &AcceptEditPrediction,
5175 window: &mut Window,
5176 cx: &mut Context<Self>,
5177 ) {
5178 if self.show_edit_predictions_in_menu() {
5179 self.hide_context_menu(window, cx);
5180 }
5181
5182 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5183 return;
5184 };
5185
5186 self.report_inline_completion_event(
5187 active_inline_completion.completion_id.clone(),
5188 true,
5189 cx,
5190 );
5191
5192 match &active_inline_completion.completion {
5193 InlineCompletion::Move { target, .. } => {
5194 let target = *target;
5195
5196 if let Some(position_map) = &self.last_position_map {
5197 if position_map
5198 .visible_row_range
5199 .contains(&target.to_display_point(&position_map.snapshot).row())
5200 || !self.edit_prediction_requires_modifier()
5201 {
5202 self.unfold_ranges(&[target..target], true, false, cx);
5203 // Note that this is also done in vim's handler of the Tab action.
5204 self.change_selections(
5205 Some(Autoscroll::newest()),
5206 window,
5207 cx,
5208 |selections| {
5209 selections.select_anchor_ranges([target..target]);
5210 },
5211 );
5212 self.clear_row_highlights::<EditPredictionPreview>();
5213
5214 self.edit_prediction_preview
5215 .set_previous_scroll_position(None);
5216 } else {
5217 self.edit_prediction_preview
5218 .set_previous_scroll_position(Some(
5219 position_map.snapshot.scroll_anchor,
5220 ));
5221
5222 self.highlight_rows::<EditPredictionPreview>(
5223 target..target,
5224 cx.theme().colors().editor_highlighted_line_background,
5225 true,
5226 cx,
5227 );
5228 self.request_autoscroll(Autoscroll::fit(), cx);
5229 }
5230 }
5231 }
5232 InlineCompletion::Edit { edits, .. } => {
5233 if let Some(provider) = self.edit_prediction_provider() {
5234 provider.accept(cx);
5235 }
5236
5237 let snapshot = self.buffer.read(cx).snapshot(cx);
5238 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5239
5240 self.buffer.update(cx, |buffer, cx| {
5241 buffer.edit(edits.iter().cloned(), None, cx)
5242 });
5243
5244 self.change_selections(None, window, cx, |s| {
5245 s.select_anchor_ranges([last_edit_end..last_edit_end])
5246 });
5247
5248 self.update_visible_inline_completion(window, cx);
5249 if self.active_inline_completion.is_none() {
5250 self.refresh_inline_completion(true, true, window, cx);
5251 }
5252
5253 cx.notify();
5254 }
5255 }
5256
5257 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5258 }
5259
5260 pub fn accept_partial_inline_completion(
5261 &mut self,
5262 _: &AcceptPartialEditPrediction,
5263 window: &mut Window,
5264 cx: &mut Context<Self>,
5265 ) {
5266 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5267 return;
5268 };
5269 if self.selections.count() != 1 {
5270 return;
5271 }
5272
5273 self.report_inline_completion_event(
5274 active_inline_completion.completion_id.clone(),
5275 true,
5276 cx,
5277 );
5278
5279 match &active_inline_completion.completion {
5280 InlineCompletion::Move { target, .. } => {
5281 let target = *target;
5282 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5283 selections.select_anchor_ranges([target..target]);
5284 });
5285 }
5286 InlineCompletion::Edit { edits, .. } => {
5287 // Find an insertion that starts at the cursor position.
5288 let snapshot = self.buffer.read(cx).snapshot(cx);
5289 let cursor_offset = self.selections.newest::<usize>(cx).head();
5290 let insertion = edits.iter().find_map(|(range, text)| {
5291 let range = range.to_offset(&snapshot);
5292 if range.is_empty() && range.start == cursor_offset {
5293 Some(text)
5294 } else {
5295 None
5296 }
5297 });
5298
5299 if let Some(text) = insertion {
5300 let mut partial_completion = text
5301 .chars()
5302 .by_ref()
5303 .take_while(|c| c.is_alphabetic())
5304 .collect::<String>();
5305 if partial_completion.is_empty() {
5306 partial_completion = text
5307 .chars()
5308 .by_ref()
5309 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5310 .collect::<String>();
5311 }
5312
5313 cx.emit(EditorEvent::InputHandled {
5314 utf16_range_to_replace: None,
5315 text: partial_completion.clone().into(),
5316 });
5317
5318 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5319
5320 self.refresh_inline_completion(true, true, window, cx);
5321 cx.notify();
5322 } else {
5323 self.accept_edit_prediction(&Default::default(), window, cx);
5324 }
5325 }
5326 }
5327 }
5328
5329 fn discard_inline_completion(
5330 &mut self,
5331 should_report_inline_completion_event: bool,
5332 cx: &mut Context<Self>,
5333 ) -> bool {
5334 if should_report_inline_completion_event {
5335 let completion_id = self
5336 .active_inline_completion
5337 .as_ref()
5338 .and_then(|active_completion| active_completion.completion_id.clone());
5339
5340 self.report_inline_completion_event(completion_id, false, cx);
5341 }
5342
5343 if let Some(provider) = self.edit_prediction_provider() {
5344 provider.discard(cx);
5345 }
5346
5347 self.take_active_inline_completion(cx)
5348 }
5349
5350 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5351 let Some(provider) = self.edit_prediction_provider() else {
5352 return;
5353 };
5354
5355 let Some((_, buffer, _)) = self
5356 .buffer
5357 .read(cx)
5358 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5359 else {
5360 return;
5361 };
5362
5363 let extension = buffer
5364 .read(cx)
5365 .file()
5366 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5367
5368 let event_type = match accepted {
5369 true => "Edit Prediction Accepted",
5370 false => "Edit Prediction Discarded",
5371 };
5372 telemetry::event!(
5373 event_type,
5374 provider = provider.name(),
5375 prediction_id = id,
5376 suggestion_accepted = accepted,
5377 file_extension = extension,
5378 );
5379 }
5380
5381 pub fn has_active_inline_completion(&self) -> bool {
5382 self.active_inline_completion.is_some()
5383 }
5384
5385 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5386 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5387 return false;
5388 };
5389
5390 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5391 self.clear_highlights::<InlineCompletionHighlight>(cx);
5392 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5393 true
5394 }
5395
5396 /// Returns true when we're displaying the edit prediction popover below the cursor
5397 /// like we are not previewing and the LSP autocomplete menu is visible
5398 /// or we are in `when_holding_modifier` mode.
5399 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5400 if self.edit_prediction_preview_is_active()
5401 || !self.show_edit_predictions_in_menu()
5402 || !self.edit_predictions_enabled()
5403 {
5404 return false;
5405 }
5406
5407 if self.has_visible_completions_menu() {
5408 return true;
5409 }
5410
5411 has_completion && self.edit_prediction_requires_modifier()
5412 }
5413
5414 fn handle_modifiers_changed(
5415 &mut self,
5416 modifiers: Modifiers,
5417 position_map: &PositionMap,
5418 window: &mut Window,
5419 cx: &mut Context<Self>,
5420 ) {
5421 if self.show_edit_predictions_in_menu() {
5422 self.update_edit_prediction_preview(&modifiers, window, cx);
5423 }
5424
5425 self.update_selection_mode(&modifiers, position_map, window, cx);
5426
5427 let mouse_position = window.mouse_position();
5428 if !position_map.text_hitbox.is_hovered(window) {
5429 return;
5430 }
5431
5432 self.update_hovered_link(
5433 position_map.point_for_position(mouse_position),
5434 &position_map.snapshot,
5435 modifiers,
5436 window,
5437 cx,
5438 )
5439 }
5440
5441 fn update_selection_mode(
5442 &mut self,
5443 modifiers: &Modifiers,
5444 position_map: &PositionMap,
5445 window: &mut Window,
5446 cx: &mut Context<Self>,
5447 ) {
5448 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5449 return;
5450 }
5451
5452 let mouse_position = window.mouse_position();
5453 let point_for_position = position_map.point_for_position(mouse_position);
5454 let position = point_for_position.previous_valid;
5455
5456 self.select(
5457 SelectPhase::BeginColumnar {
5458 position,
5459 reset: false,
5460 goal_column: point_for_position.exact_unclipped.column(),
5461 },
5462 window,
5463 cx,
5464 );
5465 }
5466
5467 fn update_edit_prediction_preview(
5468 &mut self,
5469 modifiers: &Modifiers,
5470 window: &mut Window,
5471 cx: &mut Context<Self>,
5472 ) {
5473 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5474 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5475 return;
5476 };
5477
5478 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5479 if matches!(
5480 self.edit_prediction_preview,
5481 EditPredictionPreview::Inactive { .. }
5482 ) {
5483 self.edit_prediction_preview = EditPredictionPreview::Active {
5484 previous_scroll_position: None,
5485 since: Instant::now(),
5486 };
5487
5488 self.update_visible_inline_completion(window, cx);
5489 cx.notify();
5490 }
5491 } else if let EditPredictionPreview::Active {
5492 previous_scroll_position,
5493 since,
5494 } = self.edit_prediction_preview
5495 {
5496 if let (Some(previous_scroll_position), Some(position_map)) =
5497 (previous_scroll_position, self.last_position_map.as_ref())
5498 {
5499 self.set_scroll_position(
5500 previous_scroll_position
5501 .scroll_position(&position_map.snapshot.display_snapshot),
5502 window,
5503 cx,
5504 );
5505 }
5506
5507 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5508 released_too_fast: since.elapsed() < Duration::from_millis(200),
5509 };
5510 self.clear_row_highlights::<EditPredictionPreview>();
5511 self.update_visible_inline_completion(window, cx);
5512 cx.notify();
5513 }
5514 }
5515
5516 fn update_visible_inline_completion(
5517 &mut self,
5518 _window: &mut Window,
5519 cx: &mut Context<Self>,
5520 ) -> Option<()> {
5521 let selection = self.selections.newest_anchor();
5522 let cursor = selection.head();
5523 let multibuffer = self.buffer.read(cx).snapshot(cx);
5524 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5525 let excerpt_id = cursor.excerpt_id;
5526
5527 let show_in_menu = self.show_edit_predictions_in_menu();
5528 let completions_menu_has_precedence = !show_in_menu
5529 && (self.context_menu.borrow().is_some()
5530 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5531
5532 if completions_menu_has_precedence
5533 || !offset_selection.is_empty()
5534 || self
5535 .active_inline_completion
5536 .as_ref()
5537 .map_or(false, |completion| {
5538 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5539 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5540 !invalidation_range.contains(&offset_selection.head())
5541 })
5542 {
5543 self.discard_inline_completion(false, cx);
5544 return None;
5545 }
5546
5547 self.take_active_inline_completion(cx);
5548 let Some(provider) = self.edit_prediction_provider() else {
5549 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5550 return None;
5551 };
5552
5553 let (buffer, cursor_buffer_position) =
5554 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5555
5556 self.edit_prediction_settings =
5557 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5558
5559 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5560
5561 if self.edit_prediction_indent_conflict {
5562 let cursor_point = cursor.to_point(&multibuffer);
5563
5564 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5565
5566 if let Some((_, indent)) = indents.iter().next() {
5567 if indent.len == cursor_point.column {
5568 self.edit_prediction_indent_conflict = false;
5569 }
5570 }
5571 }
5572
5573 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5574 let edits = inline_completion
5575 .edits
5576 .into_iter()
5577 .flat_map(|(range, new_text)| {
5578 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5579 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5580 Some((start..end, new_text))
5581 })
5582 .collect::<Vec<_>>();
5583 if edits.is_empty() {
5584 return None;
5585 }
5586
5587 let first_edit_start = edits.first().unwrap().0.start;
5588 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5589 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5590
5591 let last_edit_end = edits.last().unwrap().0.end;
5592 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5593 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5594
5595 let cursor_row = cursor.to_point(&multibuffer).row;
5596
5597 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5598
5599 let mut inlay_ids = Vec::new();
5600 let invalidation_row_range;
5601 let move_invalidation_row_range = if cursor_row < edit_start_row {
5602 Some(cursor_row..edit_end_row)
5603 } else if cursor_row > edit_end_row {
5604 Some(edit_start_row..cursor_row)
5605 } else {
5606 None
5607 };
5608 let is_move =
5609 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5610 let completion = if is_move {
5611 invalidation_row_range =
5612 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5613 let target = first_edit_start;
5614 InlineCompletion::Move { target, snapshot }
5615 } else {
5616 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5617 && !self.inline_completions_hidden_for_vim_mode;
5618
5619 if show_completions_in_buffer {
5620 if edits
5621 .iter()
5622 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5623 {
5624 let mut inlays = Vec::new();
5625 for (range, new_text) in &edits {
5626 let inlay = Inlay::inline_completion(
5627 post_inc(&mut self.next_inlay_id),
5628 range.start,
5629 new_text.as_str(),
5630 );
5631 inlay_ids.push(inlay.id);
5632 inlays.push(inlay);
5633 }
5634
5635 self.splice_inlays(&[], inlays, cx);
5636 } else {
5637 let background_color = cx.theme().status().deleted_background;
5638 self.highlight_text::<InlineCompletionHighlight>(
5639 edits.iter().map(|(range, _)| range.clone()).collect(),
5640 HighlightStyle {
5641 background_color: Some(background_color),
5642 ..Default::default()
5643 },
5644 cx,
5645 );
5646 }
5647 }
5648
5649 invalidation_row_range = edit_start_row..edit_end_row;
5650
5651 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5652 if provider.show_tab_accept_marker() {
5653 EditDisplayMode::TabAccept
5654 } else {
5655 EditDisplayMode::Inline
5656 }
5657 } else {
5658 EditDisplayMode::DiffPopover
5659 };
5660
5661 InlineCompletion::Edit {
5662 edits,
5663 edit_preview: inline_completion.edit_preview,
5664 display_mode,
5665 snapshot,
5666 }
5667 };
5668
5669 let invalidation_range = multibuffer
5670 .anchor_before(Point::new(invalidation_row_range.start, 0))
5671 ..multibuffer.anchor_after(Point::new(
5672 invalidation_row_range.end,
5673 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5674 ));
5675
5676 self.stale_inline_completion_in_menu = None;
5677 self.active_inline_completion = Some(InlineCompletionState {
5678 inlay_ids,
5679 completion,
5680 completion_id: inline_completion.id,
5681 invalidation_range,
5682 });
5683
5684 cx.notify();
5685
5686 Some(())
5687 }
5688
5689 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5690 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5691 }
5692
5693 fn render_code_actions_indicator(
5694 &self,
5695 _style: &EditorStyle,
5696 row: DisplayRow,
5697 is_active: bool,
5698 cx: &mut Context<Self>,
5699 ) -> Option<IconButton> {
5700 if self.available_code_actions.is_some() {
5701 Some(
5702 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5703 .shape(ui::IconButtonShape::Square)
5704 .icon_size(IconSize::XSmall)
5705 .icon_color(Color::Muted)
5706 .toggle_state(is_active)
5707 .tooltip({
5708 let focus_handle = self.focus_handle.clone();
5709 move |window, cx| {
5710 Tooltip::for_action_in(
5711 "Toggle Code Actions",
5712 &ToggleCodeActions {
5713 deployed_from_indicator: None,
5714 },
5715 &focus_handle,
5716 window,
5717 cx,
5718 )
5719 }
5720 })
5721 .on_click(cx.listener(move |editor, _e, window, cx| {
5722 window.focus(&editor.focus_handle(cx));
5723 editor.toggle_code_actions(
5724 &ToggleCodeActions {
5725 deployed_from_indicator: Some(row),
5726 },
5727 window,
5728 cx,
5729 );
5730 })),
5731 )
5732 } else {
5733 None
5734 }
5735 }
5736
5737 fn clear_tasks(&mut self) {
5738 self.tasks.clear()
5739 }
5740
5741 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5742 if self.tasks.insert(key, value).is_some() {
5743 // This case should hopefully be rare, but just in case...
5744 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5745 }
5746 }
5747
5748 fn build_tasks_context(
5749 project: &Entity<Project>,
5750 buffer: &Entity<Buffer>,
5751 buffer_row: u32,
5752 tasks: &Arc<RunnableTasks>,
5753 cx: &mut Context<Self>,
5754 ) -> Task<Option<task::TaskContext>> {
5755 let position = Point::new(buffer_row, tasks.column);
5756 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5757 let location = Location {
5758 buffer: buffer.clone(),
5759 range: range_start..range_start,
5760 };
5761 // Fill in the environmental variables from the tree-sitter captures
5762 let mut captured_task_variables = TaskVariables::default();
5763 for (capture_name, value) in tasks.extra_variables.clone() {
5764 captured_task_variables.insert(
5765 task::VariableName::Custom(capture_name.into()),
5766 value.clone(),
5767 );
5768 }
5769 project.update(cx, |project, cx| {
5770 project.task_store().update(cx, |task_store, cx| {
5771 task_store.task_context_for_location(captured_task_variables, location, cx)
5772 })
5773 })
5774 }
5775
5776 pub fn spawn_nearest_task(
5777 &mut self,
5778 action: &SpawnNearestTask,
5779 window: &mut Window,
5780 cx: &mut Context<Self>,
5781 ) {
5782 let Some((workspace, _)) = self.workspace.clone() else {
5783 return;
5784 };
5785 let Some(project) = self.project.clone() else {
5786 return;
5787 };
5788
5789 // Try to find a closest, enclosing node using tree-sitter that has a
5790 // task
5791 let Some((buffer, buffer_row, tasks)) = self
5792 .find_enclosing_node_task(cx)
5793 // Or find the task that's closest in row-distance.
5794 .or_else(|| self.find_closest_task(cx))
5795 else {
5796 return;
5797 };
5798
5799 let reveal_strategy = action.reveal;
5800 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5801 cx.spawn_in(window, |_, mut cx| async move {
5802 let context = task_context.await?;
5803 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5804
5805 let resolved = resolved_task.resolved.as_mut()?;
5806 resolved.reveal = reveal_strategy;
5807
5808 workspace
5809 .update(&mut cx, |workspace, cx| {
5810 workspace::tasks::schedule_resolved_task(
5811 workspace,
5812 task_source_kind,
5813 resolved_task,
5814 false,
5815 cx,
5816 );
5817 })
5818 .ok()
5819 })
5820 .detach();
5821 }
5822
5823 fn find_closest_task(
5824 &mut self,
5825 cx: &mut Context<Self>,
5826 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5827 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5828
5829 let ((buffer_id, row), tasks) = self
5830 .tasks
5831 .iter()
5832 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5833
5834 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5835 let tasks = Arc::new(tasks.to_owned());
5836 Some((buffer, *row, tasks))
5837 }
5838
5839 fn find_enclosing_node_task(
5840 &mut self,
5841 cx: &mut Context<Self>,
5842 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5843 let snapshot = self.buffer.read(cx).snapshot(cx);
5844 let offset = self.selections.newest::<usize>(cx).head();
5845 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5846 let buffer_id = excerpt.buffer().remote_id();
5847
5848 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5849 let mut cursor = layer.node().walk();
5850
5851 while cursor.goto_first_child_for_byte(offset).is_some() {
5852 if cursor.node().end_byte() == offset {
5853 cursor.goto_next_sibling();
5854 }
5855 }
5856
5857 // Ascend to the smallest ancestor that contains the range and has a task.
5858 loop {
5859 let node = cursor.node();
5860 let node_range = node.byte_range();
5861 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5862
5863 // Check if this node contains our offset
5864 if node_range.start <= offset && node_range.end >= offset {
5865 // If it contains offset, check for task
5866 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5867 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5868 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5869 }
5870 }
5871
5872 if !cursor.goto_parent() {
5873 break;
5874 }
5875 }
5876 None
5877 }
5878
5879 fn render_run_indicator(
5880 &self,
5881 _style: &EditorStyle,
5882 is_active: bool,
5883 row: DisplayRow,
5884 cx: &mut Context<Self>,
5885 ) -> IconButton {
5886 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5887 .shape(ui::IconButtonShape::Square)
5888 .icon_size(IconSize::XSmall)
5889 .icon_color(Color::Muted)
5890 .toggle_state(is_active)
5891 .on_click(cx.listener(move |editor, _e, window, cx| {
5892 window.focus(&editor.focus_handle(cx));
5893 editor.toggle_code_actions(
5894 &ToggleCodeActions {
5895 deployed_from_indicator: Some(row),
5896 },
5897 window,
5898 cx,
5899 );
5900 }))
5901 }
5902
5903 pub fn context_menu_visible(&self) -> bool {
5904 !self.edit_prediction_preview_is_active()
5905 && self
5906 .context_menu
5907 .borrow()
5908 .as_ref()
5909 .map_or(false, |menu| menu.visible())
5910 }
5911
5912 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5913 self.context_menu
5914 .borrow()
5915 .as_ref()
5916 .map(|menu| menu.origin())
5917 }
5918
5919 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5920 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5921
5922 #[allow(clippy::too_many_arguments)]
5923 fn render_edit_prediction_popover(
5924 &mut self,
5925 text_bounds: &Bounds<Pixels>,
5926 content_origin: gpui::Point<Pixels>,
5927 editor_snapshot: &EditorSnapshot,
5928 visible_row_range: Range<DisplayRow>,
5929 scroll_top: f32,
5930 scroll_bottom: f32,
5931 line_layouts: &[LineWithInvisibles],
5932 line_height: Pixels,
5933 scroll_pixel_position: gpui::Point<Pixels>,
5934 newest_selection_head: Option<DisplayPoint>,
5935 editor_width: Pixels,
5936 style: &EditorStyle,
5937 window: &mut Window,
5938 cx: &mut App,
5939 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5940 let active_inline_completion = self.active_inline_completion.as_ref()?;
5941
5942 if self.edit_prediction_visible_in_cursor_popover(true) {
5943 return None;
5944 }
5945
5946 match &active_inline_completion.completion {
5947 InlineCompletion::Move { target, .. } => {
5948 let target_display_point = target.to_display_point(editor_snapshot);
5949
5950 if self.edit_prediction_requires_modifier() {
5951 if !self.edit_prediction_preview_is_active() {
5952 return None;
5953 }
5954
5955 self.render_edit_prediction_modifier_jump_popover(
5956 text_bounds,
5957 content_origin,
5958 visible_row_range,
5959 line_layouts,
5960 line_height,
5961 scroll_pixel_position,
5962 newest_selection_head,
5963 target_display_point,
5964 window,
5965 cx,
5966 )
5967 } else {
5968 self.render_edit_prediction_eager_jump_popover(
5969 text_bounds,
5970 content_origin,
5971 editor_snapshot,
5972 visible_row_range,
5973 scroll_top,
5974 scroll_bottom,
5975 line_height,
5976 scroll_pixel_position,
5977 target_display_point,
5978 editor_width,
5979 window,
5980 cx,
5981 )
5982 }
5983 }
5984 InlineCompletion::Edit {
5985 display_mode: EditDisplayMode::Inline,
5986 ..
5987 } => None,
5988 InlineCompletion::Edit {
5989 display_mode: EditDisplayMode::TabAccept,
5990 edits,
5991 ..
5992 } => {
5993 let range = &edits.first()?.0;
5994 let target_display_point = range.end.to_display_point(editor_snapshot);
5995
5996 self.render_edit_prediction_end_of_line_popover(
5997 "Accept",
5998 editor_snapshot,
5999 visible_row_range,
6000 target_display_point,
6001 line_height,
6002 scroll_pixel_position,
6003 content_origin,
6004 editor_width,
6005 window,
6006 cx,
6007 )
6008 }
6009 InlineCompletion::Edit {
6010 edits,
6011 edit_preview,
6012 display_mode: EditDisplayMode::DiffPopover,
6013 snapshot,
6014 } => self.render_edit_prediction_diff_popover(
6015 text_bounds,
6016 content_origin,
6017 editor_snapshot,
6018 visible_row_range,
6019 line_layouts,
6020 line_height,
6021 scroll_pixel_position,
6022 newest_selection_head,
6023 editor_width,
6024 style,
6025 edits,
6026 edit_preview,
6027 snapshot,
6028 window,
6029 cx,
6030 ),
6031 }
6032 }
6033
6034 #[allow(clippy::too_many_arguments)]
6035 fn render_edit_prediction_modifier_jump_popover(
6036 &mut self,
6037 text_bounds: &Bounds<Pixels>,
6038 content_origin: gpui::Point<Pixels>,
6039 visible_row_range: Range<DisplayRow>,
6040 line_layouts: &[LineWithInvisibles],
6041 line_height: Pixels,
6042 scroll_pixel_position: gpui::Point<Pixels>,
6043 newest_selection_head: Option<DisplayPoint>,
6044 target_display_point: DisplayPoint,
6045 window: &mut Window,
6046 cx: &mut App,
6047 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6048 let scrolled_content_origin =
6049 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6050
6051 const SCROLL_PADDING_Y: Pixels = px(12.);
6052
6053 if target_display_point.row() < visible_row_range.start {
6054 return self.render_edit_prediction_scroll_popover(
6055 |_| SCROLL_PADDING_Y,
6056 IconName::ArrowUp,
6057 visible_row_range,
6058 line_layouts,
6059 newest_selection_head,
6060 scrolled_content_origin,
6061 window,
6062 cx,
6063 );
6064 } else if target_display_point.row() >= visible_row_range.end {
6065 return self.render_edit_prediction_scroll_popover(
6066 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6067 IconName::ArrowDown,
6068 visible_row_range,
6069 line_layouts,
6070 newest_selection_head,
6071 scrolled_content_origin,
6072 window,
6073 cx,
6074 );
6075 }
6076
6077 const POLE_WIDTH: Pixels = px(2.);
6078
6079 let line_layout =
6080 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6081 let target_column = target_display_point.column() as usize;
6082
6083 let target_x = line_layout.x_for_index(target_column);
6084 let target_y =
6085 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6086
6087 let flag_on_right = target_x < text_bounds.size.width / 2.;
6088
6089 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6090 border_color.l += 0.001;
6091
6092 let mut element = v_flex()
6093 .items_end()
6094 .when(flag_on_right, |el| el.items_start())
6095 .child(if flag_on_right {
6096 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6097 .rounded_bl(px(0.))
6098 .rounded_tl(px(0.))
6099 .border_l_2()
6100 .border_color(border_color)
6101 } else {
6102 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6103 .rounded_br(px(0.))
6104 .rounded_tr(px(0.))
6105 .border_r_2()
6106 .border_color(border_color)
6107 })
6108 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6109 .into_any();
6110
6111 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6112
6113 let mut origin = scrolled_content_origin + point(target_x, target_y)
6114 - point(
6115 if flag_on_right {
6116 POLE_WIDTH
6117 } else {
6118 size.width - POLE_WIDTH
6119 },
6120 size.height - line_height,
6121 );
6122
6123 origin.x = origin.x.max(content_origin.x);
6124
6125 element.prepaint_at(origin, window, cx);
6126
6127 Some((element, origin))
6128 }
6129
6130 #[allow(clippy::too_many_arguments)]
6131 fn render_edit_prediction_scroll_popover(
6132 &mut self,
6133 to_y: impl Fn(Size<Pixels>) -> Pixels,
6134 scroll_icon: IconName,
6135 visible_row_range: Range<DisplayRow>,
6136 line_layouts: &[LineWithInvisibles],
6137 newest_selection_head: Option<DisplayPoint>,
6138 scrolled_content_origin: gpui::Point<Pixels>,
6139 window: &mut Window,
6140 cx: &mut App,
6141 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6142 let mut element = self
6143 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6144 .into_any();
6145
6146 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6147
6148 let cursor = newest_selection_head?;
6149 let cursor_row_layout =
6150 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6151 let cursor_column = cursor.column() as usize;
6152
6153 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6154
6155 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6156
6157 element.prepaint_at(origin, window, cx);
6158 Some((element, origin))
6159 }
6160
6161 #[allow(clippy::too_many_arguments)]
6162 fn render_edit_prediction_eager_jump_popover(
6163 &mut self,
6164 text_bounds: &Bounds<Pixels>,
6165 content_origin: gpui::Point<Pixels>,
6166 editor_snapshot: &EditorSnapshot,
6167 visible_row_range: Range<DisplayRow>,
6168 scroll_top: f32,
6169 scroll_bottom: f32,
6170 line_height: Pixels,
6171 scroll_pixel_position: gpui::Point<Pixels>,
6172 target_display_point: DisplayPoint,
6173 editor_width: Pixels,
6174 window: &mut Window,
6175 cx: &mut App,
6176 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6177 if target_display_point.row().as_f32() < scroll_top {
6178 let mut element = self
6179 .render_edit_prediction_line_popover(
6180 "Jump to Edit",
6181 Some(IconName::ArrowUp),
6182 window,
6183 cx,
6184 )?
6185 .into_any();
6186
6187 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6188 let offset = point(
6189 (text_bounds.size.width - size.width) / 2.,
6190 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6191 );
6192
6193 let origin = text_bounds.origin + offset;
6194 element.prepaint_at(origin, window, cx);
6195 Some((element, origin))
6196 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6197 let mut element = self
6198 .render_edit_prediction_line_popover(
6199 "Jump to Edit",
6200 Some(IconName::ArrowDown),
6201 window,
6202 cx,
6203 )?
6204 .into_any();
6205
6206 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6207 let offset = point(
6208 (text_bounds.size.width - size.width) / 2.,
6209 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6210 );
6211
6212 let origin = text_bounds.origin + offset;
6213 element.prepaint_at(origin, window, cx);
6214 Some((element, origin))
6215 } else {
6216 self.render_edit_prediction_end_of_line_popover(
6217 "Jump to Edit",
6218 editor_snapshot,
6219 visible_row_range,
6220 target_display_point,
6221 line_height,
6222 scroll_pixel_position,
6223 content_origin,
6224 editor_width,
6225 window,
6226 cx,
6227 )
6228 }
6229 }
6230
6231 #[allow(clippy::too_many_arguments)]
6232 fn render_edit_prediction_end_of_line_popover(
6233 self: &mut Editor,
6234 label: &'static str,
6235 editor_snapshot: &EditorSnapshot,
6236 visible_row_range: Range<DisplayRow>,
6237 target_display_point: DisplayPoint,
6238 line_height: Pixels,
6239 scroll_pixel_position: gpui::Point<Pixels>,
6240 content_origin: gpui::Point<Pixels>,
6241 editor_width: Pixels,
6242 window: &mut Window,
6243 cx: &mut App,
6244 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6245 let target_line_end = DisplayPoint::new(
6246 target_display_point.row(),
6247 editor_snapshot.line_len(target_display_point.row()),
6248 );
6249
6250 let mut element = self
6251 .render_edit_prediction_line_popover(label, None, window, cx)?
6252 .into_any();
6253
6254 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6255
6256 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6257
6258 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6259 let mut origin = start_point
6260 + line_origin
6261 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6262 origin.x = origin.x.max(content_origin.x);
6263
6264 let max_x = content_origin.x + editor_width - size.width;
6265
6266 if origin.x > max_x {
6267 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6268
6269 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6270 origin.y += offset;
6271 IconName::ArrowUp
6272 } else {
6273 origin.y -= offset;
6274 IconName::ArrowDown
6275 };
6276
6277 element = self
6278 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6279 .into_any();
6280
6281 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6282
6283 origin.x = content_origin.x + editor_width - size.width - px(2.);
6284 }
6285
6286 element.prepaint_at(origin, window, cx);
6287 Some((element, origin))
6288 }
6289
6290 #[allow(clippy::too_many_arguments)]
6291 fn render_edit_prediction_diff_popover(
6292 self: &Editor,
6293 text_bounds: &Bounds<Pixels>,
6294 content_origin: gpui::Point<Pixels>,
6295 editor_snapshot: &EditorSnapshot,
6296 visible_row_range: Range<DisplayRow>,
6297 line_layouts: &[LineWithInvisibles],
6298 line_height: Pixels,
6299 scroll_pixel_position: gpui::Point<Pixels>,
6300 newest_selection_head: Option<DisplayPoint>,
6301 editor_width: Pixels,
6302 style: &EditorStyle,
6303 edits: &Vec<(Range<Anchor>, String)>,
6304 edit_preview: &Option<language::EditPreview>,
6305 snapshot: &language::BufferSnapshot,
6306 window: &mut Window,
6307 cx: &mut App,
6308 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6309 let edit_start = edits
6310 .first()
6311 .unwrap()
6312 .0
6313 .start
6314 .to_display_point(editor_snapshot);
6315 let edit_end = edits
6316 .last()
6317 .unwrap()
6318 .0
6319 .end
6320 .to_display_point(editor_snapshot);
6321
6322 let is_visible = visible_row_range.contains(&edit_start.row())
6323 || visible_row_range.contains(&edit_end.row());
6324 if !is_visible {
6325 return None;
6326 }
6327
6328 let highlighted_edits =
6329 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6330
6331 let styled_text = highlighted_edits.to_styled_text(&style.text);
6332 let line_count = highlighted_edits.text.lines().count();
6333
6334 const BORDER_WIDTH: Pixels = px(1.);
6335
6336 let mut element = h_flex()
6337 .items_start()
6338 .child(
6339 h_flex()
6340 .bg(cx.theme().colors().editor_background)
6341 .border(BORDER_WIDTH)
6342 .shadow_sm()
6343 .border_color(cx.theme().colors().border)
6344 .rounded_l_lg()
6345 .when(line_count > 1, |el| el.rounded_br_lg())
6346 .pr_1()
6347 .child(styled_text),
6348 )
6349 .child(
6350 h_flex()
6351 .h(line_height + BORDER_WIDTH * px(2.))
6352 .px_1p5()
6353 .gap_1()
6354 // Workaround: For some reason, there's a gap if we don't do this
6355 .ml(-BORDER_WIDTH)
6356 .shadow(smallvec![gpui::BoxShadow {
6357 color: gpui::black().opacity(0.05),
6358 offset: point(px(1.), px(1.)),
6359 blur_radius: px(2.),
6360 spread_radius: px(0.),
6361 }])
6362 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6363 .border(BORDER_WIDTH)
6364 .border_color(cx.theme().colors().border)
6365 .rounded_r_lg()
6366 .children(self.render_edit_prediction_accept_keybind(window, cx)),
6367 )
6368 .into_any();
6369
6370 let longest_row =
6371 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6372 let longest_line_width = if visible_row_range.contains(&longest_row) {
6373 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6374 } else {
6375 layout_line(
6376 longest_row,
6377 editor_snapshot,
6378 style,
6379 editor_width,
6380 |_| false,
6381 window,
6382 cx,
6383 )
6384 .width
6385 };
6386
6387 let viewport_bounds =
6388 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6389 right: -EditorElement::SCROLLBAR_WIDTH,
6390 ..Default::default()
6391 });
6392
6393 let x_after_longest =
6394 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6395 - scroll_pixel_position.x;
6396
6397 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6398
6399 // Fully visible if it can be displayed within the window (allow overlapping other
6400 // panes). However, this is only allowed if the popover starts within text_bounds.
6401 let can_position_to_the_right = x_after_longest < text_bounds.right()
6402 && x_after_longest + element_bounds.width < viewport_bounds.right();
6403
6404 let mut origin = if can_position_to_the_right {
6405 point(
6406 x_after_longest,
6407 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6408 - scroll_pixel_position.y,
6409 )
6410 } else {
6411 let cursor_row = newest_selection_head.map(|head| head.row());
6412 let above_edit = edit_start
6413 .row()
6414 .0
6415 .checked_sub(line_count as u32)
6416 .map(DisplayRow);
6417 let below_edit = Some(edit_end.row() + 1);
6418 let above_cursor =
6419 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6420 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6421
6422 // Place the edit popover adjacent to the edit if there is a location
6423 // available that is onscreen and does not obscure the cursor. Otherwise,
6424 // place it adjacent to the cursor.
6425 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6426 .into_iter()
6427 .flatten()
6428 .find(|&start_row| {
6429 let end_row = start_row + line_count as u32;
6430 visible_row_range.contains(&start_row)
6431 && visible_row_range.contains(&end_row)
6432 && cursor_row.map_or(true, |cursor_row| {
6433 !((start_row..end_row).contains(&cursor_row))
6434 })
6435 })?;
6436
6437 content_origin
6438 + point(
6439 -scroll_pixel_position.x,
6440 row_target.as_f32() * line_height - scroll_pixel_position.y,
6441 )
6442 };
6443
6444 origin.x -= BORDER_WIDTH;
6445
6446 window.defer_draw(element, origin, 1);
6447
6448 // Do not return an element, since it will already be drawn due to defer_draw.
6449 None
6450 }
6451
6452 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6453 px(30.)
6454 }
6455
6456 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6457 if self.read_only(cx) {
6458 cx.theme().players().read_only()
6459 } else {
6460 self.style.as_ref().unwrap().local_player
6461 }
6462 }
6463
6464 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
6465 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6466 let accept_keystroke = accept_binding.keystroke()?;
6467
6468 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6469
6470 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6471 Color::Accent
6472 } else {
6473 Color::Muted
6474 };
6475
6476 h_flex()
6477 .px_0p5()
6478 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6479 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6480 .text_size(TextSize::XSmall.rems(cx))
6481 .child(h_flex().children(ui::render_modifiers(
6482 &accept_keystroke.modifiers,
6483 PlatformStyle::platform(),
6484 Some(modifiers_color),
6485 Some(IconSize::XSmall.rems().into()),
6486 true,
6487 )))
6488 .when(is_platform_style_mac, |parent| {
6489 parent.child(accept_keystroke.key.clone())
6490 })
6491 .when(!is_platform_style_mac, |parent| {
6492 parent.child(
6493 Key::new(
6494 util::capitalize(&accept_keystroke.key),
6495 Some(Color::Default),
6496 )
6497 .size(Some(IconSize::XSmall.rems().into())),
6498 )
6499 })
6500 .into()
6501 }
6502
6503 fn render_edit_prediction_line_popover(
6504 &self,
6505 label: impl Into<SharedString>,
6506 icon: Option<IconName>,
6507 window: &mut Window,
6508 cx: &App,
6509 ) -> Option<Div> {
6510 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6511
6512 let result = h_flex()
6513 .py_0p5()
6514 .pl_1()
6515 .pr(padding_right)
6516 .gap_1()
6517 .rounded(px(6.))
6518 .border_1()
6519 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6520 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6521 .shadow_sm()
6522 .children(self.render_edit_prediction_accept_keybind(window, cx))
6523 .child(Label::new(label).size(LabelSize::Small))
6524 .when_some(icon, |element, icon| {
6525 element.child(
6526 div()
6527 .mt(px(1.5))
6528 .child(Icon::new(icon).size(IconSize::Small)),
6529 )
6530 });
6531
6532 Some(result)
6533 }
6534
6535 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6536 let accent_color = cx.theme().colors().text_accent;
6537 let editor_bg_color = cx.theme().colors().editor_background;
6538 editor_bg_color.blend(accent_color.opacity(0.1))
6539 }
6540
6541 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6542 let accent_color = cx.theme().colors().text_accent;
6543 let editor_bg_color = cx.theme().colors().editor_background;
6544 editor_bg_color.blend(accent_color.opacity(0.6))
6545 }
6546
6547 #[allow(clippy::too_many_arguments)]
6548 fn render_edit_prediction_cursor_popover(
6549 &self,
6550 min_width: Pixels,
6551 max_width: Pixels,
6552 cursor_point: Point,
6553 style: &EditorStyle,
6554 accept_keystroke: Option<&gpui::Keystroke>,
6555 _window: &Window,
6556 cx: &mut Context<Editor>,
6557 ) -> Option<AnyElement> {
6558 let provider = self.edit_prediction_provider.as_ref()?;
6559
6560 if provider.provider.needs_terms_acceptance(cx) {
6561 return Some(
6562 h_flex()
6563 .min_w(min_width)
6564 .flex_1()
6565 .px_2()
6566 .py_1()
6567 .gap_3()
6568 .elevation_2(cx)
6569 .hover(|style| style.bg(cx.theme().colors().element_hover))
6570 .id("accept-terms")
6571 .cursor_pointer()
6572 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6573 .on_click(cx.listener(|this, _event, window, cx| {
6574 cx.stop_propagation();
6575 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6576 window.dispatch_action(
6577 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6578 cx,
6579 );
6580 }))
6581 .child(
6582 h_flex()
6583 .flex_1()
6584 .gap_2()
6585 .child(Icon::new(IconName::ZedPredict))
6586 .child(Label::new("Accept Terms of Service"))
6587 .child(div().w_full())
6588 .child(
6589 Icon::new(IconName::ArrowUpRight)
6590 .color(Color::Muted)
6591 .size(IconSize::Small),
6592 )
6593 .into_any_element(),
6594 )
6595 .into_any(),
6596 );
6597 }
6598
6599 let is_refreshing = provider.provider.is_refreshing(cx);
6600
6601 fn pending_completion_container() -> Div {
6602 h_flex()
6603 .h_full()
6604 .flex_1()
6605 .gap_2()
6606 .child(Icon::new(IconName::ZedPredict))
6607 }
6608
6609 let completion = match &self.active_inline_completion {
6610 Some(prediction) => {
6611 if !self.has_visible_completions_menu() {
6612 const RADIUS: Pixels = px(6.);
6613 const BORDER_WIDTH: Pixels = px(1.);
6614
6615 return Some(
6616 h_flex()
6617 .elevation_2(cx)
6618 .border(BORDER_WIDTH)
6619 .border_color(cx.theme().colors().border)
6620 .rounded(RADIUS)
6621 .rounded_tl(px(0.))
6622 .overflow_hidden()
6623 .child(div().px_1p5().child(match &prediction.completion {
6624 InlineCompletion::Move { target, snapshot } => {
6625 use text::ToPoint as _;
6626 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6627 {
6628 Icon::new(IconName::ZedPredictDown)
6629 } else {
6630 Icon::new(IconName::ZedPredictUp)
6631 }
6632 }
6633 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6634 }))
6635 .child(
6636 h_flex()
6637 .gap_1()
6638 .py_1()
6639 .px_2()
6640 .rounded_r(RADIUS - BORDER_WIDTH)
6641 .border_l_1()
6642 .border_color(cx.theme().colors().border)
6643 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6644 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6645 el.child(
6646 Label::new("Hold")
6647 .size(LabelSize::Small)
6648 .line_height_style(LineHeightStyle::UiLabel),
6649 )
6650 })
6651 .child(h_flex().children(ui::render_modifiers(
6652 &accept_keystroke?.modifiers,
6653 PlatformStyle::platform(),
6654 Some(Color::Default),
6655 Some(IconSize::XSmall.rems().into()),
6656 false,
6657 ))),
6658 )
6659 .into_any(),
6660 );
6661 }
6662
6663 self.render_edit_prediction_cursor_popover_preview(
6664 prediction,
6665 cursor_point,
6666 style,
6667 cx,
6668 )?
6669 }
6670
6671 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6672 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6673 stale_completion,
6674 cursor_point,
6675 style,
6676 cx,
6677 )?,
6678
6679 None => {
6680 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6681 }
6682 },
6683
6684 None => pending_completion_container().child(Label::new("No Prediction")),
6685 };
6686
6687 let completion = if is_refreshing {
6688 completion
6689 .with_animation(
6690 "loading-completion",
6691 Animation::new(Duration::from_secs(2))
6692 .repeat()
6693 .with_easing(pulsating_between(0.4, 0.8)),
6694 |label, delta| label.opacity(delta),
6695 )
6696 .into_any_element()
6697 } else {
6698 completion.into_any_element()
6699 };
6700
6701 let has_completion = self.active_inline_completion.is_some();
6702
6703 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6704 Some(
6705 h_flex()
6706 .min_w(min_width)
6707 .max_w(max_width)
6708 .flex_1()
6709 .elevation_2(cx)
6710 .border_color(cx.theme().colors().border)
6711 .child(
6712 div()
6713 .flex_1()
6714 .py_1()
6715 .px_2()
6716 .overflow_hidden()
6717 .child(completion),
6718 )
6719 .when_some(accept_keystroke, |el, accept_keystroke| {
6720 if !accept_keystroke.modifiers.modified() {
6721 return el;
6722 }
6723
6724 el.child(
6725 h_flex()
6726 .h_full()
6727 .border_l_1()
6728 .rounded_r_lg()
6729 .border_color(cx.theme().colors().border)
6730 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6731 .gap_1()
6732 .py_1()
6733 .px_2()
6734 .child(
6735 h_flex()
6736 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6737 .when(is_platform_style_mac, |parent| parent.gap_1())
6738 .child(h_flex().children(ui::render_modifiers(
6739 &accept_keystroke.modifiers,
6740 PlatformStyle::platform(),
6741 Some(if !has_completion {
6742 Color::Muted
6743 } else {
6744 Color::Default
6745 }),
6746 None,
6747 false,
6748 ))),
6749 )
6750 .child(Label::new("Preview").into_any_element())
6751 .opacity(if has_completion { 1.0 } else { 0.4 }),
6752 )
6753 })
6754 .into_any(),
6755 )
6756 }
6757
6758 fn render_edit_prediction_cursor_popover_preview(
6759 &self,
6760 completion: &InlineCompletionState,
6761 cursor_point: Point,
6762 style: &EditorStyle,
6763 cx: &mut Context<Editor>,
6764 ) -> Option<Div> {
6765 use text::ToPoint as _;
6766
6767 fn render_relative_row_jump(
6768 prefix: impl Into<String>,
6769 current_row: u32,
6770 target_row: u32,
6771 ) -> Div {
6772 let (row_diff, arrow) = if target_row < current_row {
6773 (current_row - target_row, IconName::ArrowUp)
6774 } else {
6775 (target_row - current_row, IconName::ArrowDown)
6776 };
6777
6778 h_flex()
6779 .child(
6780 Label::new(format!("{}{}", prefix.into(), row_diff))
6781 .color(Color::Muted)
6782 .size(LabelSize::Small),
6783 )
6784 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6785 }
6786
6787 match &completion.completion {
6788 InlineCompletion::Move {
6789 target, snapshot, ..
6790 } => Some(
6791 h_flex()
6792 .px_2()
6793 .gap_2()
6794 .flex_1()
6795 .child(
6796 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6797 Icon::new(IconName::ZedPredictDown)
6798 } else {
6799 Icon::new(IconName::ZedPredictUp)
6800 },
6801 )
6802 .child(Label::new("Jump to Edit")),
6803 ),
6804
6805 InlineCompletion::Edit {
6806 edits,
6807 edit_preview,
6808 snapshot,
6809 display_mode: _,
6810 } => {
6811 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6812
6813 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6814 &snapshot,
6815 &edits,
6816 edit_preview.as_ref()?,
6817 true,
6818 cx,
6819 )
6820 .first_line_preview();
6821
6822 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6823 .with_default_highlights(&style.text, highlighted_edits.highlights);
6824
6825 let preview = h_flex()
6826 .gap_1()
6827 .min_w_16()
6828 .child(styled_text)
6829 .when(has_more_lines, |parent| parent.child("…"));
6830
6831 let left = if first_edit_row != cursor_point.row {
6832 render_relative_row_jump("", cursor_point.row, first_edit_row)
6833 .into_any_element()
6834 } else {
6835 Icon::new(IconName::ZedPredict).into_any_element()
6836 };
6837
6838 Some(
6839 h_flex()
6840 .h_full()
6841 .flex_1()
6842 .gap_2()
6843 .pr_1()
6844 .overflow_x_hidden()
6845 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6846 .child(left)
6847 .child(preview),
6848 )
6849 }
6850 }
6851 }
6852
6853 fn render_context_menu(
6854 &self,
6855 style: &EditorStyle,
6856 max_height_in_lines: u32,
6857 y_flipped: bool,
6858 window: &mut Window,
6859 cx: &mut Context<Editor>,
6860 ) -> Option<AnyElement> {
6861 let menu = self.context_menu.borrow();
6862 let menu = menu.as_ref()?;
6863 if !menu.visible() {
6864 return None;
6865 };
6866 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6867 }
6868
6869 fn render_context_menu_aside(
6870 &mut self,
6871 max_size: Size<Pixels>,
6872 window: &mut Window,
6873 cx: &mut Context<Editor>,
6874 ) -> Option<AnyElement> {
6875 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6876 if menu.visible() {
6877 menu.render_aside(self, max_size, window, cx)
6878 } else {
6879 None
6880 }
6881 })
6882 }
6883
6884 fn hide_context_menu(
6885 &mut self,
6886 window: &mut Window,
6887 cx: &mut Context<Self>,
6888 ) -> Option<CodeContextMenu> {
6889 cx.notify();
6890 self.completion_tasks.clear();
6891 let context_menu = self.context_menu.borrow_mut().take();
6892 self.stale_inline_completion_in_menu.take();
6893 self.update_visible_inline_completion(window, cx);
6894 context_menu
6895 }
6896
6897 fn show_snippet_choices(
6898 &mut self,
6899 choices: &Vec<String>,
6900 selection: Range<Anchor>,
6901 cx: &mut Context<Self>,
6902 ) {
6903 if selection.start.buffer_id.is_none() {
6904 return;
6905 }
6906 let buffer_id = selection.start.buffer_id.unwrap();
6907 let buffer = self.buffer().read(cx).buffer(buffer_id);
6908 let id = post_inc(&mut self.next_completion_id);
6909
6910 if let Some(buffer) = buffer {
6911 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6912 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6913 ));
6914 }
6915 }
6916
6917 pub fn insert_snippet(
6918 &mut self,
6919 insertion_ranges: &[Range<usize>],
6920 snippet: Snippet,
6921 window: &mut Window,
6922 cx: &mut Context<Self>,
6923 ) -> Result<()> {
6924 struct Tabstop<T> {
6925 is_end_tabstop: bool,
6926 ranges: Vec<Range<T>>,
6927 choices: Option<Vec<String>>,
6928 }
6929
6930 let tabstops = self.buffer.update(cx, |buffer, cx| {
6931 let snippet_text: Arc<str> = snippet.text.clone().into();
6932 buffer.edit(
6933 insertion_ranges
6934 .iter()
6935 .cloned()
6936 .map(|range| (range, snippet_text.clone())),
6937 Some(AutoindentMode::EachLine),
6938 cx,
6939 );
6940
6941 let snapshot = &*buffer.read(cx);
6942 let snippet = &snippet;
6943 snippet
6944 .tabstops
6945 .iter()
6946 .map(|tabstop| {
6947 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6948 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6949 });
6950 let mut tabstop_ranges = tabstop
6951 .ranges
6952 .iter()
6953 .flat_map(|tabstop_range| {
6954 let mut delta = 0_isize;
6955 insertion_ranges.iter().map(move |insertion_range| {
6956 let insertion_start = insertion_range.start as isize + delta;
6957 delta +=
6958 snippet.text.len() as isize - insertion_range.len() as isize;
6959
6960 let start = ((insertion_start + tabstop_range.start) as usize)
6961 .min(snapshot.len());
6962 let end = ((insertion_start + tabstop_range.end) as usize)
6963 .min(snapshot.len());
6964 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6965 })
6966 })
6967 .collect::<Vec<_>>();
6968 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6969
6970 Tabstop {
6971 is_end_tabstop,
6972 ranges: tabstop_ranges,
6973 choices: tabstop.choices.clone(),
6974 }
6975 })
6976 .collect::<Vec<_>>()
6977 });
6978 if let Some(tabstop) = tabstops.first() {
6979 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6980 s.select_ranges(tabstop.ranges.iter().cloned());
6981 });
6982
6983 if let Some(choices) = &tabstop.choices {
6984 if let Some(selection) = tabstop.ranges.first() {
6985 self.show_snippet_choices(choices, selection.clone(), cx)
6986 }
6987 }
6988
6989 // If we're already at the last tabstop and it's at the end of the snippet,
6990 // we're done, we don't need to keep the state around.
6991 if !tabstop.is_end_tabstop {
6992 let choices = tabstops
6993 .iter()
6994 .map(|tabstop| tabstop.choices.clone())
6995 .collect();
6996
6997 let ranges = tabstops
6998 .into_iter()
6999 .map(|tabstop| tabstop.ranges)
7000 .collect::<Vec<_>>();
7001
7002 self.snippet_stack.push(SnippetState {
7003 active_index: 0,
7004 ranges,
7005 choices,
7006 });
7007 }
7008
7009 // Check whether the just-entered snippet ends with an auto-closable bracket.
7010 if self.autoclose_regions.is_empty() {
7011 let snapshot = self.buffer.read(cx).snapshot(cx);
7012 for selection in &mut self.selections.all::<Point>(cx) {
7013 let selection_head = selection.head();
7014 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7015 continue;
7016 };
7017
7018 let mut bracket_pair = None;
7019 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7020 let prev_chars = snapshot
7021 .reversed_chars_at(selection_head)
7022 .collect::<String>();
7023 for (pair, enabled) in scope.brackets() {
7024 if enabled
7025 && pair.close
7026 && prev_chars.starts_with(pair.start.as_str())
7027 && next_chars.starts_with(pair.end.as_str())
7028 {
7029 bracket_pair = Some(pair.clone());
7030 break;
7031 }
7032 }
7033 if let Some(pair) = bracket_pair {
7034 let start = snapshot.anchor_after(selection_head);
7035 let end = snapshot.anchor_after(selection_head);
7036 self.autoclose_regions.push(AutocloseRegion {
7037 selection_id: selection.id,
7038 range: start..end,
7039 pair,
7040 });
7041 }
7042 }
7043 }
7044 }
7045 Ok(())
7046 }
7047
7048 pub fn move_to_next_snippet_tabstop(
7049 &mut self,
7050 window: &mut Window,
7051 cx: &mut Context<Self>,
7052 ) -> bool {
7053 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7054 }
7055
7056 pub fn move_to_prev_snippet_tabstop(
7057 &mut self,
7058 window: &mut Window,
7059 cx: &mut Context<Self>,
7060 ) -> bool {
7061 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7062 }
7063
7064 pub fn move_to_snippet_tabstop(
7065 &mut self,
7066 bias: Bias,
7067 window: &mut Window,
7068 cx: &mut Context<Self>,
7069 ) -> bool {
7070 if let Some(mut snippet) = self.snippet_stack.pop() {
7071 match bias {
7072 Bias::Left => {
7073 if snippet.active_index > 0 {
7074 snippet.active_index -= 1;
7075 } else {
7076 self.snippet_stack.push(snippet);
7077 return false;
7078 }
7079 }
7080 Bias::Right => {
7081 if snippet.active_index + 1 < snippet.ranges.len() {
7082 snippet.active_index += 1;
7083 } else {
7084 self.snippet_stack.push(snippet);
7085 return false;
7086 }
7087 }
7088 }
7089 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7090 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7091 s.select_anchor_ranges(current_ranges.iter().cloned())
7092 });
7093
7094 if let Some(choices) = &snippet.choices[snippet.active_index] {
7095 if let Some(selection) = current_ranges.first() {
7096 self.show_snippet_choices(&choices, selection.clone(), cx);
7097 }
7098 }
7099
7100 // If snippet state is not at the last tabstop, push it back on the stack
7101 if snippet.active_index + 1 < snippet.ranges.len() {
7102 self.snippet_stack.push(snippet);
7103 }
7104 return true;
7105 }
7106 }
7107
7108 false
7109 }
7110
7111 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7112 self.transact(window, cx, |this, window, cx| {
7113 this.select_all(&SelectAll, window, cx);
7114 this.insert("", window, cx);
7115 });
7116 }
7117
7118 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7119 self.transact(window, cx, |this, window, cx| {
7120 this.select_autoclose_pair(window, cx);
7121 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7122 if !this.linked_edit_ranges.is_empty() {
7123 let selections = this.selections.all::<MultiBufferPoint>(cx);
7124 let snapshot = this.buffer.read(cx).snapshot(cx);
7125
7126 for selection in selections.iter() {
7127 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7128 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7129 if selection_start.buffer_id != selection_end.buffer_id {
7130 continue;
7131 }
7132 if let Some(ranges) =
7133 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7134 {
7135 for (buffer, entries) in ranges {
7136 linked_ranges.entry(buffer).or_default().extend(entries);
7137 }
7138 }
7139 }
7140 }
7141
7142 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7143 if !this.selections.line_mode {
7144 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7145 for selection in &mut selections {
7146 if selection.is_empty() {
7147 let old_head = selection.head();
7148 let mut new_head =
7149 movement::left(&display_map, old_head.to_display_point(&display_map))
7150 .to_point(&display_map);
7151 if let Some((buffer, line_buffer_range)) = display_map
7152 .buffer_snapshot
7153 .buffer_line_for_row(MultiBufferRow(old_head.row))
7154 {
7155 let indent_size =
7156 buffer.indent_size_for_line(line_buffer_range.start.row);
7157 let indent_len = match indent_size.kind {
7158 IndentKind::Space => {
7159 buffer.settings_at(line_buffer_range.start, cx).tab_size
7160 }
7161 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7162 };
7163 if old_head.column <= indent_size.len && old_head.column > 0 {
7164 let indent_len = indent_len.get();
7165 new_head = cmp::min(
7166 new_head,
7167 MultiBufferPoint::new(
7168 old_head.row,
7169 ((old_head.column - 1) / indent_len) * indent_len,
7170 ),
7171 );
7172 }
7173 }
7174
7175 selection.set_head(new_head, SelectionGoal::None);
7176 }
7177 }
7178 }
7179
7180 this.signature_help_state.set_backspace_pressed(true);
7181 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7182 s.select(selections)
7183 });
7184 this.insert("", window, cx);
7185 let empty_str: Arc<str> = Arc::from("");
7186 for (buffer, edits) in linked_ranges {
7187 let snapshot = buffer.read(cx).snapshot();
7188 use text::ToPoint as TP;
7189
7190 let edits = edits
7191 .into_iter()
7192 .map(|range| {
7193 let end_point = TP::to_point(&range.end, &snapshot);
7194 let mut start_point = TP::to_point(&range.start, &snapshot);
7195
7196 if end_point == start_point {
7197 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7198 .saturating_sub(1);
7199 start_point =
7200 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7201 };
7202
7203 (start_point..end_point, empty_str.clone())
7204 })
7205 .sorted_by_key(|(range, _)| range.start)
7206 .collect::<Vec<_>>();
7207 buffer.update(cx, |this, cx| {
7208 this.edit(edits, None, cx);
7209 })
7210 }
7211 this.refresh_inline_completion(true, false, window, cx);
7212 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7213 });
7214 }
7215
7216 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7217 self.transact(window, cx, |this, window, cx| {
7218 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7219 let line_mode = s.line_mode;
7220 s.move_with(|map, selection| {
7221 if selection.is_empty() && !line_mode {
7222 let cursor = movement::right(map, selection.head());
7223 selection.end = cursor;
7224 selection.reversed = true;
7225 selection.goal = SelectionGoal::None;
7226 }
7227 })
7228 });
7229 this.insert("", window, cx);
7230 this.refresh_inline_completion(true, false, window, cx);
7231 });
7232 }
7233
7234 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7235 if self.move_to_prev_snippet_tabstop(window, cx) {
7236 return;
7237 }
7238
7239 self.outdent(&Outdent, window, cx);
7240 }
7241
7242 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7243 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7244 return;
7245 }
7246
7247 let mut selections = self.selections.all_adjusted(cx);
7248 let buffer = self.buffer.read(cx);
7249 let snapshot = buffer.snapshot(cx);
7250 let rows_iter = selections.iter().map(|s| s.head().row);
7251 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7252
7253 let mut edits = Vec::new();
7254 let mut prev_edited_row = 0;
7255 let mut row_delta = 0;
7256 for selection in &mut selections {
7257 if selection.start.row != prev_edited_row {
7258 row_delta = 0;
7259 }
7260 prev_edited_row = selection.end.row;
7261
7262 // If the selection is non-empty, then increase the indentation of the selected lines.
7263 if !selection.is_empty() {
7264 row_delta =
7265 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7266 continue;
7267 }
7268
7269 // If the selection is empty and the cursor is in the leading whitespace before the
7270 // suggested indentation, then auto-indent the line.
7271 let cursor = selection.head();
7272 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7273 if let Some(suggested_indent) =
7274 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7275 {
7276 if cursor.column < suggested_indent.len
7277 && cursor.column <= current_indent.len
7278 && current_indent.len <= suggested_indent.len
7279 {
7280 selection.start = Point::new(cursor.row, suggested_indent.len);
7281 selection.end = selection.start;
7282 if row_delta == 0 {
7283 edits.extend(Buffer::edit_for_indent_size_adjustment(
7284 cursor.row,
7285 current_indent,
7286 suggested_indent,
7287 ));
7288 row_delta = suggested_indent.len - current_indent.len;
7289 }
7290 continue;
7291 }
7292 }
7293
7294 // Otherwise, insert a hard or soft tab.
7295 let settings = buffer.settings_at(cursor, cx);
7296 let tab_size = if settings.hard_tabs {
7297 IndentSize::tab()
7298 } else {
7299 let tab_size = settings.tab_size.get();
7300 let char_column = snapshot
7301 .text_for_range(Point::new(cursor.row, 0)..cursor)
7302 .flat_map(str::chars)
7303 .count()
7304 + row_delta as usize;
7305 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7306 IndentSize::spaces(chars_to_next_tab_stop)
7307 };
7308 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7309 selection.end = selection.start;
7310 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7311 row_delta += tab_size.len;
7312 }
7313
7314 self.transact(window, cx, |this, window, cx| {
7315 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7316 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7317 s.select(selections)
7318 });
7319 this.refresh_inline_completion(true, false, window, cx);
7320 });
7321 }
7322
7323 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7324 if self.read_only(cx) {
7325 return;
7326 }
7327 let mut selections = self.selections.all::<Point>(cx);
7328 let mut prev_edited_row = 0;
7329 let mut row_delta = 0;
7330 let mut edits = Vec::new();
7331 let buffer = self.buffer.read(cx);
7332 let snapshot = buffer.snapshot(cx);
7333 for selection in &mut selections {
7334 if selection.start.row != prev_edited_row {
7335 row_delta = 0;
7336 }
7337 prev_edited_row = selection.end.row;
7338
7339 row_delta =
7340 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7341 }
7342
7343 self.transact(window, cx, |this, window, cx| {
7344 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7345 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7346 s.select(selections)
7347 });
7348 });
7349 }
7350
7351 fn indent_selection(
7352 buffer: &MultiBuffer,
7353 snapshot: &MultiBufferSnapshot,
7354 selection: &mut Selection<Point>,
7355 edits: &mut Vec<(Range<Point>, String)>,
7356 delta_for_start_row: u32,
7357 cx: &App,
7358 ) -> u32 {
7359 let settings = buffer.settings_at(selection.start, cx);
7360 let tab_size = settings.tab_size.get();
7361 let indent_kind = if settings.hard_tabs {
7362 IndentKind::Tab
7363 } else {
7364 IndentKind::Space
7365 };
7366 let mut start_row = selection.start.row;
7367 let mut end_row = selection.end.row + 1;
7368
7369 // If a selection ends at the beginning of a line, don't indent
7370 // that last line.
7371 if selection.end.column == 0 && selection.end.row > selection.start.row {
7372 end_row -= 1;
7373 }
7374
7375 // Avoid re-indenting a row that has already been indented by a
7376 // previous selection, but still update this selection's column
7377 // to reflect that indentation.
7378 if delta_for_start_row > 0 {
7379 start_row += 1;
7380 selection.start.column += delta_for_start_row;
7381 if selection.end.row == selection.start.row {
7382 selection.end.column += delta_for_start_row;
7383 }
7384 }
7385
7386 let mut delta_for_end_row = 0;
7387 let has_multiple_rows = start_row + 1 != end_row;
7388 for row in start_row..end_row {
7389 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7390 let indent_delta = match (current_indent.kind, indent_kind) {
7391 (IndentKind::Space, IndentKind::Space) => {
7392 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7393 IndentSize::spaces(columns_to_next_tab_stop)
7394 }
7395 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7396 (_, IndentKind::Tab) => IndentSize::tab(),
7397 };
7398
7399 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7400 0
7401 } else {
7402 selection.start.column
7403 };
7404 let row_start = Point::new(row, start);
7405 edits.push((
7406 row_start..row_start,
7407 indent_delta.chars().collect::<String>(),
7408 ));
7409
7410 // Update this selection's endpoints to reflect the indentation.
7411 if row == selection.start.row {
7412 selection.start.column += indent_delta.len;
7413 }
7414 if row == selection.end.row {
7415 selection.end.column += indent_delta.len;
7416 delta_for_end_row = indent_delta.len;
7417 }
7418 }
7419
7420 if selection.start.row == selection.end.row {
7421 delta_for_start_row + delta_for_end_row
7422 } else {
7423 delta_for_end_row
7424 }
7425 }
7426
7427 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7428 if self.read_only(cx) {
7429 return;
7430 }
7431 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7432 let selections = self.selections.all::<Point>(cx);
7433 let mut deletion_ranges = Vec::new();
7434 let mut last_outdent = None;
7435 {
7436 let buffer = self.buffer.read(cx);
7437 let snapshot = buffer.snapshot(cx);
7438 for selection in &selections {
7439 let settings = buffer.settings_at(selection.start, cx);
7440 let tab_size = settings.tab_size.get();
7441 let mut rows = selection.spanned_rows(false, &display_map);
7442
7443 // Avoid re-outdenting a row that has already been outdented by a
7444 // previous selection.
7445 if let Some(last_row) = last_outdent {
7446 if last_row == rows.start {
7447 rows.start = rows.start.next_row();
7448 }
7449 }
7450 let has_multiple_rows = rows.len() > 1;
7451 for row in rows.iter_rows() {
7452 let indent_size = snapshot.indent_size_for_line(row);
7453 if indent_size.len > 0 {
7454 let deletion_len = match indent_size.kind {
7455 IndentKind::Space => {
7456 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7457 if columns_to_prev_tab_stop == 0 {
7458 tab_size
7459 } else {
7460 columns_to_prev_tab_stop
7461 }
7462 }
7463 IndentKind::Tab => 1,
7464 };
7465 let start = if has_multiple_rows
7466 || deletion_len > selection.start.column
7467 || indent_size.len < selection.start.column
7468 {
7469 0
7470 } else {
7471 selection.start.column - deletion_len
7472 };
7473 deletion_ranges.push(
7474 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7475 );
7476 last_outdent = Some(row);
7477 }
7478 }
7479 }
7480 }
7481
7482 self.transact(window, cx, |this, window, cx| {
7483 this.buffer.update(cx, |buffer, cx| {
7484 let empty_str: Arc<str> = Arc::default();
7485 buffer.edit(
7486 deletion_ranges
7487 .into_iter()
7488 .map(|range| (range, empty_str.clone())),
7489 None,
7490 cx,
7491 );
7492 });
7493 let selections = this.selections.all::<usize>(cx);
7494 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7495 s.select(selections)
7496 });
7497 });
7498 }
7499
7500 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7501 if self.read_only(cx) {
7502 return;
7503 }
7504 let selections = self
7505 .selections
7506 .all::<usize>(cx)
7507 .into_iter()
7508 .map(|s| s.range());
7509
7510 self.transact(window, cx, |this, window, cx| {
7511 this.buffer.update(cx, |buffer, cx| {
7512 buffer.autoindent_ranges(selections, cx);
7513 });
7514 let selections = this.selections.all::<usize>(cx);
7515 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7516 s.select(selections)
7517 });
7518 });
7519 }
7520
7521 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7522 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7523 let selections = self.selections.all::<Point>(cx);
7524
7525 let mut new_cursors = Vec::new();
7526 let mut edit_ranges = Vec::new();
7527 let mut selections = selections.iter().peekable();
7528 while let Some(selection) = selections.next() {
7529 let mut rows = selection.spanned_rows(false, &display_map);
7530 let goal_display_column = selection.head().to_display_point(&display_map).column();
7531
7532 // Accumulate contiguous regions of rows that we want to delete.
7533 while let Some(next_selection) = selections.peek() {
7534 let next_rows = next_selection.spanned_rows(false, &display_map);
7535 if next_rows.start <= rows.end {
7536 rows.end = next_rows.end;
7537 selections.next().unwrap();
7538 } else {
7539 break;
7540 }
7541 }
7542
7543 let buffer = &display_map.buffer_snapshot;
7544 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7545 let edit_end;
7546 let cursor_buffer_row;
7547 if buffer.max_point().row >= rows.end.0 {
7548 // If there's a line after the range, delete the \n from the end of the row range
7549 // and position the cursor on the next line.
7550 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7551 cursor_buffer_row = rows.end;
7552 } else {
7553 // If there isn't a line after the range, delete the \n from the line before the
7554 // start of the row range and position the cursor there.
7555 edit_start = edit_start.saturating_sub(1);
7556 edit_end = buffer.len();
7557 cursor_buffer_row = rows.start.previous_row();
7558 }
7559
7560 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7561 *cursor.column_mut() =
7562 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7563
7564 new_cursors.push((
7565 selection.id,
7566 buffer.anchor_after(cursor.to_point(&display_map)),
7567 ));
7568 edit_ranges.push(edit_start..edit_end);
7569 }
7570
7571 self.transact(window, cx, |this, window, cx| {
7572 let buffer = this.buffer.update(cx, |buffer, cx| {
7573 let empty_str: Arc<str> = Arc::default();
7574 buffer.edit(
7575 edit_ranges
7576 .into_iter()
7577 .map(|range| (range, empty_str.clone())),
7578 None,
7579 cx,
7580 );
7581 buffer.snapshot(cx)
7582 });
7583 let new_selections = new_cursors
7584 .into_iter()
7585 .map(|(id, cursor)| {
7586 let cursor = cursor.to_point(&buffer);
7587 Selection {
7588 id,
7589 start: cursor,
7590 end: cursor,
7591 reversed: false,
7592 goal: SelectionGoal::None,
7593 }
7594 })
7595 .collect();
7596
7597 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7598 s.select(new_selections);
7599 });
7600 });
7601 }
7602
7603 pub fn join_lines_impl(
7604 &mut self,
7605 insert_whitespace: bool,
7606 window: &mut Window,
7607 cx: &mut Context<Self>,
7608 ) {
7609 if self.read_only(cx) {
7610 return;
7611 }
7612 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7613 for selection in self.selections.all::<Point>(cx) {
7614 let start = MultiBufferRow(selection.start.row);
7615 // Treat single line selections as if they include the next line. Otherwise this action
7616 // would do nothing for single line selections individual cursors.
7617 let end = if selection.start.row == selection.end.row {
7618 MultiBufferRow(selection.start.row + 1)
7619 } else {
7620 MultiBufferRow(selection.end.row)
7621 };
7622
7623 if let Some(last_row_range) = row_ranges.last_mut() {
7624 if start <= last_row_range.end {
7625 last_row_range.end = end;
7626 continue;
7627 }
7628 }
7629 row_ranges.push(start..end);
7630 }
7631
7632 let snapshot = self.buffer.read(cx).snapshot(cx);
7633 let mut cursor_positions = Vec::new();
7634 for row_range in &row_ranges {
7635 let anchor = snapshot.anchor_before(Point::new(
7636 row_range.end.previous_row().0,
7637 snapshot.line_len(row_range.end.previous_row()),
7638 ));
7639 cursor_positions.push(anchor..anchor);
7640 }
7641
7642 self.transact(window, cx, |this, window, cx| {
7643 for row_range in row_ranges.into_iter().rev() {
7644 for row in row_range.iter_rows().rev() {
7645 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7646 let next_line_row = row.next_row();
7647 let indent = snapshot.indent_size_for_line(next_line_row);
7648 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7649
7650 let replace =
7651 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7652 " "
7653 } else {
7654 ""
7655 };
7656
7657 this.buffer.update(cx, |buffer, cx| {
7658 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7659 });
7660 }
7661 }
7662
7663 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7664 s.select_anchor_ranges(cursor_positions)
7665 });
7666 });
7667 }
7668
7669 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7670 self.join_lines_impl(true, window, cx);
7671 }
7672
7673 pub fn sort_lines_case_sensitive(
7674 &mut self,
7675 _: &SortLinesCaseSensitive,
7676 window: &mut Window,
7677 cx: &mut Context<Self>,
7678 ) {
7679 self.manipulate_lines(window, cx, |lines| lines.sort())
7680 }
7681
7682 pub fn sort_lines_case_insensitive(
7683 &mut self,
7684 _: &SortLinesCaseInsensitive,
7685 window: &mut Window,
7686 cx: &mut Context<Self>,
7687 ) {
7688 self.manipulate_lines(window, cx, |lines| {
7689 lines.sort_by_key(|line| line.to_lowercase())
7690 })
7691 }
7692
7693 pub fn unique_lines_case_insensitive(
7694 &mut self,
7695 _: &UniqueLinesCaseInsensitive,
7696 window: &mut Window,
7697 cx: &mut Context<Self>,
7698 ) {
7699 self.manipulate_lines(window, cx, |lines| {
7700 let mut seen = HashSet::default();
7701 lines.retain(|line| seen.insert(line.to_lowercase()));
7702 })
7703 }
7704
7705 pub fn unique_lines_case_sensitive(
7706 &mut self,
7707 _: &UniqueLinesCaseSensitive,
7708 window: &mut Window,
7709 cx: &mut Context<Self>,
7710 ) {
7711 self.manipulate_lines(window, cx, |lines| {
7712 let mut seen = HashSet::default();
7713 lines.retain(|line| seen.insert(*line));
7714 })
7715 }
7716
7717 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7718 let Some(project) = self.project.clone() else {
7719 return;
7720 };
7721 self.reload(project, window, cx)
7722 .detach_and_notify_err(window, cx);
7723 }
7724
7725 pub fn restore_file(
7726 &mut self,
7727 _: &::git::RestoreFile,
7728 window: &mut Window,
7729 cx: &mut Context<Self>,
7730 ) {
7731 let mut buffer_ids = HashSet::default();
7732 let snapshot = self.buffer().read(cx).snapshot(cx);
7733 for selection in self.selections.all::<usize>(cx) {
7734 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7735 }
7736
7737 let buffer = self.buffer().read(cx);
7738 let ranges = buffer_ids
7739 .into_iter()
7740 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7741 .collect::<Vec<_>>();
7742
7743 self.restore_hunks_in_ranges(ranges, window, cx);
7744 }
7745
7746 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7747 let selections = self
7748 .selections
7749 .all(cx)
7750 .into_iter()
7751 .map(|s| s.range())
7752 .collect();
7753 self.restore_hunks_in_ranges(selections, window, cx);
7754 }
7755
7756 fn restore_hunks_in_ranges(
7757 &mut self,
7758 ranges: Vec<Range<Point>>,
7759 window: &mut Window,
7760 cx: &mut Context<Editor>,
7761 ) {
7762 let mut revert_changes = HashMap::default();
7763 let chunk_by = self
7764 .snapshot(window, cx)
7765 .hunks_for_ranges(ranges)
7766 .into_iter()
7767 .chunk_by(|hunk| hunk.buffer_id);
7768 for (buffer_id, hunks) in &chunk_by {
7769 let hunks = hunks.collect::<Vec<_>>();
7770 for hunk in &hunks {
7771 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7772 }
7773 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7774 }
7775 drop(chunk_by);
7776 if !revert_changes.is_empty() {
7777 self.transact(window, cx, |editor, window, cx| {
7778 editor.restore(revert_changes, window, cx);
7779 });
7780 }
7781 }
7782
7783 pub fn open_active_item_in_terminal(
7784 &mut self,
7785 _: &OpenInTerminal,
7786 window: &mut Window,
7787 cx: &mut Context<Self>,
7788 ) {
7789 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7790 let project_path = buffer.read(cx).project_path(cx)?;
7791 let project = self.project.as_ref()?.read(cx);
7792 let entry = project.entry_for_path(&project_path, cx)?;
7793 let parent = match &entry.canonical_path {
7794 Some(canonical_path) => canonical_path.to_path_buf(),
7795 None => project.absolute_path(&project_path, cx)?,
7796 }
7797 .parent()?
7798 .to_path_buf();
7799 Some(parent)
7800 }) {
7801 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7802 }
7803 }
7804
7805 pub fn prepare_restore_change(
7806 &self,
7807 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7808 hunk: &MultiBufferDiffHunk,
7809 cx: &mut App,
7810 ) -> Option<()> {
7811 if hunk.is_created_file() {
7812 return None;
7813 }
7814 let buffer = self.buffer.read(cx);
7815 let diff = buffer.diff_for(hunk.buffer_id)?;
7816 let buffer = buffer.buffer(hunk.buffer_id)?;
7817 let buffer = buffer.read(cx);
7818 let original_text = diff
7819 .read(cx)
7820 .base_text()
7821 .as_rope()
7822 .slice(hunk.diff_base_byte_range.clone());
7823 let buffer_snapshot = buffer.snapshot();
7824 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7825 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7826 probe
7827 .0
7828 .start
7829 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7830 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7831 }) {
7832 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7833 Some(())
7834 } else {
7835 None
7836 }
7837 }
7838
7839 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7840 self.manipulate_lines(window, cx, |lines| lines.reverse())
7841 }
7842
7843 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7844 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7845 }
7846
7847 fn manipulate_lines<Fn>(
7848 &mut self,
7849 window: &mut Window,
7850 cx: &mut Context<Self>,
7851 mut callback: Fn,
7852 ) where
7853 Fn: FnMut(&mut Vec<&str>),
7854 {
7855 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7856 let buffer = self.buffer.read(cx).snapshot(cx);
7857
7858 let mut edits = Vec::new();
7859
7860 let selections = self.selections.all::<Point>(cx);
7861 let mut selections = selections.iter().peekable();
7862 let mut contiguous_row_selections = Vec::new();
7863 let mut new_selections = Vec::new();
7864 let mut added_lines = 0;
7865 let mut removed_lines = 0;
7866
7867 while let Some(selection) = selections.next() {
7868 let (start_row, end_row) = consume_contiguous_rows(
7869 &mut contiguous_row_selections,
7870 selection,
7871 &display_map,
7872 &mut selections,
7873 );
7874
7875 let start_point = Point::new(start_row.0, 0);
7876 let end_point = Point::new(
7877 end_row.previous_row().0,
7878 buffer.line_len(end_row.previous_row()),
7879 );
7880 let text = buffer
7881 .text_for_range(start_point..end_point)
7882 .collect::<String>();
7883
7884 let mut lines = text.split('\n').collect_vec();
7885
7886 let lines_before = lines.len();
7887 callback(&mut lines);
7888 let lines_after = lines.len();
7889
7890 edits.push((start_point..end_point, lines.join("\n")));
7891
7892 // Selections must change based on added and removed line count
7893 let start_row =
7894 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7895 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7896 new_selections.push(Selection {
7897 id: selection.id,
7898 start: start_row,
7899 end: end_row,
7900 goal: SelectionGoal::None,
7901 reversed: selection.reversed,
7902 });
7903
7904 if lines_after > lines_before {
7905 added_lines += lines_after - lines_before;
7906 } else if lines_before > lines_after {
7907 removed_lines += lines_before - lines_after;
7908 }
7909 }
7910
7911 self.transact(window, cx, |this, window, cx| {
7912 let buffer = this.buffer.update(cx, |buffer, cx| {
7913 buffer.edit(edits, None, cx);
7914 buffer.snapshot(cx)
7915 });
7916
7917 // Recalculate offsets on newly edited buffer
7918 let new_selections = new_selections
7919 .iter()
7920 .map(|s| {
7921 let start_point = Point::new(s.start.0, 0);
7922 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7923 Selection {
7924 id: s.id,
7925 start: buffer.point_to_offset(start_point),
7926 end: buffer.point_to_offset(end_point),
7927 goal: s.goal,
7928 reversed: s.reversed,
7929 }
7930 })
7931 .collect();
7932
7933 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7934 s.select(new_selections);
7935 });
7936
7937 this.request_autoscroll(Autoscroll::fit(), cx);
7938 });
7939 }
7940
7941 pub fn convert_to_upper_case(
7942 &mut self,
7943 _: &ConvertToUpperCase,
7944 window: &mut Window,
7945 cx: &mut Context<Self>,
7946 ) {
7947 self.manipulate_text(window, cx, |text| text.to_uppercase())
7948 }
7949
7950 pub fn convert_to_lower_case(
7951 &mut self,
7952 _: &ConvertToLowerCase,
7953 window: &mut Window,
7954 cx: &mut Context<Self>,
7955 ) {
7956 self.manipulate_text(window, cx, |text| text.to_lowercase())
7957 }
7958
7959 pub fn convert_to_title_case(
7960 &mut self,
7961 _: &ConvertToTitleCase,
7962 window: &mut Window,
7963 cx: &mut Context<Self>,
7964 ) {
7965 self.manipulate_text(window, cx, |text| {
7966 text.split('\n')
7967 .map(|line| line.to_case(Case::Title))
7968 .join("\n")
7969 })
7970 }
7971
7972 pub fn convert_to_snake_case(
7973 &mut self,
7974 _: &ConvertToSnakeCase,
7975 window: &mut Window,
7976 cx: &mut Context<Self>,
7977 ) {
7978 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7979 }
7980
7981 pub fn convert_to_kebab_case(
7982 &mut self,
7983 _: &ConvertToKebabCase,
7984 window: &mut Window,
7985 cx: &mut Context<Self>,
7986 ) {
7987 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7988 }
7989
7990 pub fn convert_to_upper_camel_case(
7991 &mut self,
7992 _: &ConvertToUpperCamelCase,
7993 window: &mut Window,
7994 cx: &mut Context<Self>,
7995 ) {
7996 self.manipulate_text(window, cx, |text| {
7997 text.split('\n')
7998 .map(|line| line.to_case(Case::UpperCamel))
7999 .join("\n")
8000 })
8001 }
8002
8003 pub fn convert_to_lower_camel_case(
8004 &mut self,
8005 _: &ConvertToLowerCamelCase,
8006 window: &mut Window,
8007 cx: &mut Context<Self>,
8008 ) {
8009 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8010 }
8011
8012 pub fn convert_to_opposite_case(
8013 &mut self,
8014 _: &ConvertToOppositeCase,
8015 window: &mut Window,
8016 cx: &mut Context<Self>,
8017 ) {
8018 self.manipulate_text(window, cx, |text| {
8019 text.chars()
8020 .fold(String::with_capacity(text.len()), |mut t, c| {
8021 if c.is_uppercase() {
8022 t.extend(c.to_lowercase());
8023 } else {
8024 t.extend(c.to_uppercase());
8025 }
8026 t
8027 })
8028 })
8029 }
8030
8031 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8032 where
8033 Fn: FnMut(&str) -> String,
8034 {
8035 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8036 let buffer = self.buffer.read(cx).snapshot(cx);
8037
8038 let mut new_selections = Vec::new();
8039 let mut edits = Vec::new();
8040 let mut selection_adjustment = 0i32;
8041
8042 for selection in self.selections.all::<usize>(cx) {
8043 let selection_is_empty = selection.is_empty();
8044
8045 let (start, end) = if selection_is_empty {
8046 let word_range = movement::surrounding_word(
8047 &display_map,
8048 selection.start.to_display_point(&display_map),
8049 );
8050 let start = word_range.start.to_offset(&display_map, Bias::Left);
8051 let end = word_range.end.to_offset(&display_map, Bias::Left);
8052 (start, end)
8053 } else {
8054 (selection.start, selection.end)
8055 };
8056
8057 let text = buffer.text_for_range(start..end).collect::<String>();
8058 let old_length = text.len() as i32;
8059 let text = callback(&text);
8060
8061 new_selections.push(Selection {
8062 start: (start as i32 - selection_adjustment) as usize,
8063 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8064 goal: SelectionGoal::None,
8065 ..selection
8066 });
8067
8068 selection_adjustment += old_length - text.len() as i32;
8069
8070 edits.push((start..end, text));
8071 }
8072
8073 self.transact(window, cx, |this, window, cx| {
8074 this.buffer.update(cx, |buffer, cx| {
8075 buffer.edit(edits, None, cx);
8076 });
8077
8078 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8079 s.select(new_selections);
8080 });
8081
8082 this.request_autoscroll(Autoscroll::fit(), cx);
8083 });
8084 }
8085
8086 pub fn duplicate(
8087 &mut self,
8088 upwards: bool,
8089 whole_lines: bool,
8090 window: &mut Window,
8091 cx: &mut Context<Self>,
8092 ) {
8093 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8094 let buffer = &display_map.buffer_snapshot;
8095 let selections = self.selections.all::<Point>(cx);
8096
8097 let mut edits = Vec::new();
8098 let mut selections_iter = selections.iter().peekable();
8099 while let Some(selection) = selections_iter.next() {
8100 let mut rows = selection.spanned_rows(false, &display_map);
8101 // duplicate line-wise
8102 if whole_lines || selection.start == selection.end {
8103 // Avoid duplicating the same lines twice.
8104 while let Some(next_selection) = selections_iter.peek() {
8105 let next_rows = next_selection.spanned_rows(false, &display_map);
8106 if next_rows.start < rows.end {
8107 rows.end = next_rows.end;
8108 selections_iter.next().unwrap();
8109 } else {
8110 break;
8111 }
8112 }
8113
8114 // Copy the text from the selected row region and splice it either at the start
8115 // or end of the region.
8116 let start = Point::new(rows.start.0, 0);
8117 let end = Point::new(
8118 rows.end.previous_row().0,
8119 buffer.line_len(rows.end.previous_row()),
8120 );
8121 let text = buffer
8122 .text_for_range(start..end)
8123 .chain(Some("\n"))
8124 .collect::<String>();
8125 let insert_location = if upwards {
8126 Point::new(rows.end.0, 0)
8127 } else {
8128 start
8129 };
8130 edits.push((insert_location..insert_location, text));
8131 } else {
8132 // duplicate character-wise
8133 let start = selection.start;
8134 let end = selection.end;
8135 let text = buffer.text_for_range(start..end).collect::<String>();
8136 edits.push((selection.end..selection.end, text));
8137 }
8138 }
8139
8140 self.transact(window, cx, |this, _, cx| {
8141 this.buffer.update(cx, |buffer, cx| {
8142 buffer.edit(edits, None, cx);
8143 });
8144
8145 this.request_autoscroll(Autoscroll::fit(), cx);
8146 });
8147 }
8148
8149 pub fn duplicate_line_up(
8150 &mut self,
8151 _: &DuplicateLineUp,
8152 window: &mut Window,
8153 cx: &mut Context<Self>,
8154 ) {
8155 self.duplicate(true, true, window, cx);
8156 }
8157
8158 pub fn duplicate_line_down(
8159 &mut self,
8160 _: &DuplicateLineDown,
8161 window: &mut Window,
8162 cx: &mut Context<Self>,
8163 ) {
8164 self.duplicate(false, true, window, cx);
8165 }
8166
8167 pub fn duplicate_selection(
8168 &mut self,
8169 _: &DuplicateSelection,
8170 window: &mut Window,
8171 cx: &mut Context<Self>,
8172 ) {
8173 self.duplicate(false, false, window, cx);
8174 }
8175
8176 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8177 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8178 let buffer = self.buffer.read(cx).snapshot(cx);
8179
8180 let mut edits = Vec::new();
8181 let mut unfold_ranges = Vec::new();
8182 let mut refold_creases = Vec::new();
8183
8184 let selections = self.selections.all::<Point>(cx);
8185 let mut selections = selections.iter().peekable();
8186 let mut contiguous_row_selections = Vec::new();
8187 let mut new_selections = Vec::new();
8188
8189 while let Some(selection) = selections.next() {
8190 // Find all the selections that span a contiguous row range
8191 let (start_row, end_row) = consume_contiguous_rows(
8192 &mut contiguous_row_selections,
8193 selection,
8194 &display_map,
8195 &mut selections,
8196 );
8197
8198 // Move the text spanned by the row range to be before the line preceding the row range
8199 if start_row.0 > 0 {
8200 let range_to_move = Point::new(
8201 start_row.previous_row().0,
8202 buffer.line_len(start_row.previous_row()),
8203 )
8204 ..Point::new(
8205 end_row.previous_row().0,
8206 buffer.line_len(end_row.previous_row()),
8207 );
8208 let insertion_point = display_map
8209 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8210 .0;
8211
8212 // Don't move lines across excerpts
8213 if buffer
8214 .excerpt_containing(insertion_point..range_to_move.end)
8215 .is_some()
8216 {
8217 let text = buffer
8218 .text_for_range(range_to_move.clone())
8219 .flat_map(|s| s.chars())
8220 .skip(1)
8221 .chain(['\n'])
8222 .collect::<String>();
8223
8224 edits.push((
8225 buffer.anchor_after(range_to_move.start)
8226 ..buffer.anchor_before(range_to_move.end),
8227 String::new(),
8228 ));
8229 let insertion_anchor = buffer.anchor_after(insertion_point);
8230 edits.push((insertion_anchor..insertion_anchor, text));
8231
8232 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8233
8234 // Move selections up
8235 new_selections.extend(contiguous_row_selections.drain(..).map(
8236 |mut selection| {
8237 selection.start.row -= row_delta;
8238 selection.end.row -= row_delta;
8239 selection
8240 },
8241 ));
8242
8243 // Move folds up
8244 unfold_ranges.push(range_to_move.clone());
8245 for fold in display_map.folds_in_range(
8246 buffer.anchor_before(range_to_move.start)
8247 ..buffer.anchor_after(range_to_move.end),
8248 ) {
8249 let mut start = fold.range.start.to_point(&buffer);
8250 let mut end = fold.range.end.to_point(&buffer);
8251 start.row -= row_delta;
8252 end.row -= row_delta;
8253 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8254 }
8255 }
8256 }
8257
8258 // If we didn't move line(s), preserve the existing selections
8259 new_selections.append(&mut contiguous_row_selections);
8260 }
8261
8262 self.transact(window, cx, |this, window, cx| {
8263 this.unfold_ranges(&unfold_ranges, true, true, cx);
8264 this.buffer.update(cx, |buffer, cx| {
8265 for (range, text) in edits {
8266 buffer.edit([(range, text)], None, cx);
8267 }
8268 });
8269 this.fold_creases(refold_creases, true, window, cx);
8270 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8271 s.select(new_selections);
8272 })
8273 });
8274 }
8275
8276 pub fn move_line_down(
8277 &mut self,
8278 _: &MoveLineDown,
8279 window: &mut Window,
8280 cx: &mut Context<Self>,
8281 ) {
8282 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8283 let buffer = self.buffer.read(cx).snapshot(cx);
8284
8285 let mut edits = Vec::new();
8286 let mut unfold_ranges = Vec::new();
8287 let mut refold_creases = Vec::new();
8288
8289 let selections = self.selections.all::<Point>(cx);
8290 let mut selections = selections.iter().peekable();
8291 let mut contiguous_row_selections = Vec::new();
8292 let mut new_selections = Vec::new();
8293
8294 while let Some(selection) = selections.next() {
8295 // Find all the selections that span a contiguous row range
8296 let (start_row, end_row) = consume_contiguous_rows(
8297 &mut contiguous_row_selections,
8298 selection,
8299 &display_map,
8300 &mut selections,
8301 );
8302
8303 // Move the text spanned by the row range to be after the last line of the row range
8304 if end_row.0 <= buffer.max_point().row {
8305 let range_to_move =
8306 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8307 let insertion_point = display_map
8308 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8309 .0;
8310
8311 // Don't move lines across excerpt boundaries
8312 if buffer
8313 .excerpt_containing(range_to_move.start..insertion_point)
8314 .is_some()
8315 {
8316 let mut text = String::from("\n");
8317 text.extend(buffer.text_for_range(range_to_move.clone()));
8318 text.pop(); // Drop trailing newline
8319 edits.push((
8320 buffer.anchor_after(range_to_move.start)
8321 ..buffer.anchor_before(range_to_move.end),
8322 String::new(),
8323 ));
8324 let insertion_anchor = buffer.anchor_after(insertion_point);
8325 edits.push((insertion_anchor..insertion_anchor, text));
8326
8327 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8328
8329 // Move selections down
8330 new_selections.extend(contiguous_row_selections.drain(..).map(
8331 |mut selection| {
8332 selection.start.row += row_delta;
8333 selection.end.row += row_delta;
8334 selection
8335 },
8336 ));
8337
8338 // Move folds down
8339 unfold_ranges.push(range_to_move.clone());
8340 for fold in display_map.folds_in_range(
8341 buffer.anchor_before(range_to_move.start)
8342 ..buffer.anchor_after(range_to_move.end),
8343 ) {
8344 let mut start = fold.range.start.to_point(&buffer);
8345 let mut end = fold.range.end.to_point(&buffer);
8346 start.row += row_delta;
8347 end.row += row_delta;
8348 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8349 }
8350 }
8351 }
8352
8353 // If we didn't move line(s), preserve the existing selections
8354 new_selections.append(&mut contiguous_row_selections);
8355 }
8356
8357 self.transact(window, cx, |this, window, cx| {
8358 this.unfold_ranges(&unfold_ranges, true, true, cx);
8359 this.buffer.update(cx, |buffer, cx| {
8360 for (range, text) in edits {
8361 buffer.edit([(range, text)], None, cx);
8362 }
8363 });
8364 this.fold_creases(refold_creases, true, window, cx);
8365 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8366 s.select(new_selections)
8367 });
8368 });
8369 }
8370
8371 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8372 let text_layout_details = &self.text_layout_details(window);
8373 self.transact(window, cx, |this, window, cx| {
8374 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8375 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8376 let line_mode = s.line_mode;
8377 s.move_with(|display_map, selection| {
8378 if !selection.is_empty() || line_mode {
8379 return;
8380 }
8381
8382 let mut head = selection.head();
8383 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8384 if head.column() == display_map.line_len(head.row()) {
8385 transpose_offset = display_map
8386 .buffer_snapshot
8387 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8388 }
8389
8390 if transpose_offset == 0 {
8391 return;
8392 }
8393
8394 *head.column_mut() += 1;
8395 head = display_map.clip_point(head, Bias::Right);
8396 let goal = SelectionGoal::HorizontalPosition(
8397 display_map
8398 .x_for_display_point(head, text_layout_details)
8399 .into(),
8400 );
8401 selection.collapse_to(head, goal);
8402
8403 let transpose_start = display_map
8404 .buffer_snapshot
8405 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8406 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8407 let transpose_end = display_map
8408 .buffer_snapshot
8409 .clip_offset(transpose_offset + 1, Bias::Right);
8410 if let Some(ch) =
8411 display_map.buffer_snapshot.chars_at(transpose_start).next()
8412 {
8413 edits.push((transpose_start..transpose_offset, String::new()));
8414 edits.push((transpose_end..transpose_end, ch.to_string()));
8415 }
8416 }
8417 });
8418 edits
8419 });
8420 this.buffer
8421 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8422 let selections = this.selections.all::<usize>(cx);
8423 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8424 s.select(selections);
8425 });
8426 });
8427 }
8428
8429 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8430 self.rewrap_impl(IsVimMode::No, cx)
8431 }
8432
8433 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8434 let buffer = self.buffer.read(cx).snapshot(cx);
8435 let selections = self.selections.all::<Point>(cx);
8436 let mut selections = selections.iter().peekable();
8437
8438 let mut edits = Vec::new();
8439 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8440
8441 while let Some(selection) = selections.next() {
8442 let mut start_row = selection.start.row;
8443 let mut end_row = selection.end.row;
8444
8445 // Skip selections that overlap with a range that has already been rewrapped.
8446 let selection_range = start_row..end_row;
8447 if rewrapped_row_ranges
8448 .iter()
8449 .any(|range| range.overlaps(&selection_range))
8450 {
8451 continue;
8452 }
8453
8454 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
8455
8456 // Since not all lines in the selection may be at the same indent
8457 // level, choose the indent size that is the most common between all
8458 // of the lines.
8459 //
8460 // If there is a tie, we use the deepest indent.
8461 let (indent_size, indent_end) = {
8462 let mut indent_size_occurrences = HashMap::default();
8463 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8464
8465 for row in start_row..=end_row {
8466 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8467 rows_by_indent_size.entry(indent).or_default().push(row);
8468 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8469 }
8470
8471 let indent_size = indent_size_occurrences
8472 .into_iter()
8473 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8474 .map(|(indent, _)| indent)
8475 .unwrap_or_default();
8476 let row = rows_by_indent_size[&indent_size][0];
8477 let indent_end = Point::new(row, indent_size.len);
8478
8479 (indent_size, indent_end)
8480 };
8481
8482 let mut line_prefix = indent_size.chars().collect::<String>();
8483
8484 let mut inside_comment = false;
8485 if let Some(comment_prefix) =
8486 buffer
8487 .language_scope_at(selection.head())
8488 .and_then(|language| {
8489 language
8490 .line_comment_prefixes()
8491 .iter()
8492 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8493 .cloned()
8494 })
8495 {
8496 line_prefix.push_str(&comment_prefix);
8497 inside_comment = true;
8498 }
8499
8500 let language_settings = buffer.settings_at(selection.head(), cx);
8501 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8502 RewrapBehavior::InComments => inside_comment,
8503 RewrapBehavior::InSelections => !selection.is_empty(),
8504 RewrapBehavior::Anywhere => true,
8505 };
8506
8507 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8508 if !should_rewrap {
8509 continue;
8510 }
8511
8512 if selection.is_empty() {
8513 'expand_upwards: while start_row > 0 {
8514 let prev_row = start_row - 1;
8515 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8516 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8517 {
8518 start_row = prev_row;
8519 } else {
8520 break 'expand_upwards;
8521 }
8522 }
8523
8524 'expand_downwards: while end_row < buffer.max_point().row {
8525 let next_row = end_row + 1;
8526 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8527 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8528 {
8529 end_row = next_row;
8530 } else {
8531 break 'expand_downwards;
8532 }
8533 }
8534 }
8535
8536 let start = Point::new(start_row, 0);
8537 let start_offset = start.to_offset(&buffer);
8538 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8539 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8540 let Some(lines_without_prefixes) = selection_text
8541 .lines()
8542 .map(|line| {
8543 line.strip_prefix(&line_prefix)
8544 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8545 .ok_or_else(|| {
8546 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8547 })
8548 })
8549 .collect::<Result<Vec<_>, _>>()
8550 .log_err()
8551 else {
8552 continue;
8553 };
8554
8555 let wrap_column = buffer
8556 .settings_at(Point::new(start_row, 0), cx)
8557 .preferred_line_length as usize;
8558 let wrapped_text = wrap_with_prefix(
8559 line_prefix,
8560 lines_without_prefixes.join(" "),
8561 wrap_column,
8562 tab_size,
8563 );
8564
8565 // TODO: should always use char-based diff while still supporting cursor behavior that
8566 // matches vim.
8567 let mut diff_options = DiffOptions::default();
8568 if is_vim_mode == IsVimMode::Yes {
8569 diff_options.max_word_diff_len = 0;
8570 diff_options.max_word_diff_line_count = 0;
8571 } else {
8572 diff_options.max_word_diff_len = usize::MAX;
8573 diff_options.max_word_diff_line_count = usize::MAX;
8574 }
8575
8576 for (old_range, new_text) in
8577 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8578 {
8579 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8580 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8581 edits.push((edit_start..edit_end, new_text));
8582 }
8583
8584 rewrapped_row_ranges.push(start_row..=end_row);
8585 }
8586
8587 self.buffer
8588 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8589 }
8590
8591 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8592 let mut text = String::new();
8593 let buffer = self.buffer.read(cx).snapshot(cx);
8594 let mut selections = self.selections.all::<Point>(cx);
8595 let mut clipboard_selections = Vec::with_capacity(selections.len());
8596 {
8597 let max_point = buffer.max_point();
8598 let mut is_first = true;
8599 for selection in &mut selections {
8600 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8601 if is_entire_line {
8602 selection.start = Point::new(selection.start.row, 0);
8603 if !selection.is_empty() && selection.end.column == 0 {
8604 selection.end = cmp::min(max_point, selection.end);
8605 } else {
8606 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8607 }
8608 selection.goal = SelectionGoal::None;
8609 }
8610 if is_first {
8611 is_first = false;
8612 } else {
8613 text += "\n";
8614 }
8615 let mut len = 0;
8616 for chunk in buffer.text_for_range(selection.start..selection.end) {
8617 text.push_str(chunk);
8618 len += chunk.len();
8619 }
8620 clipboard_selections.push(ClipboardSelection {
8621 len,
8622 is_entire_line,
8623 start_column: selection.start.column,
8624 });
8625 }
8626 }
8627
8628 self.transact(window, cx, |this, window, cx| {
8629 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8630 s.select(selections);
8631 });
8632 this.insert("", window, cx);
8633 });
8634 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8635 }
8636
8637 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8638 let item = self.cut_common(window, cx);
8639 cx.write_to_clipboard(item);
8640 }
8641
8642 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8643 self.change_selections(None, window, cx, |s| {
8644 s.move_with(|snapshot, sel| {
8645 if sel.is_empty() {
8646 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8647 }
8648 });
8649 });
8650 let item = self.cut_common(window, cx);
8651 cx.set_global(KillRing(item))
8652 }
8653
8654 pub fn kill_ring_yank(
8655 &mut self,
8656 _: &KillRingYank,
8657 window: &mut Window,
8658 cx: &mut Context<Self>,
8659 ) {
8660 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8661 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8662 (kill_ring.text().to_string(), kill_ring.metadata_json())
8663 } else {
8664 return;
8665 }
8666 } else {
8667 return;
8668 };
8669 self.do_paste(&text, metadata, false, window, cx);
8670 }
8671
8672 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8673 let selections = self.selections.all::<Point>(cx);
8674 let buffer = self.buffer.read(cx).read(cx);
8675 let mut text = String::new();
8676
8677 let mut clipboard_selections = Vec::with_capacity(selections.len());
8678 {
8679 let max_point = buffer.max_point();
8680 let mut is_first = true;
8681 for selection in selections.iter() {
8682 let mut start = selection.start;
8683 let mut end = selection.end;
8684 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8685 if is_entire_line {
8686 start = Point::new(start.row, 0);
8687 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8688 }
8689 if is_first {
8690 is_first = false;
8691 } else {
8692 text += "\n";
8693 }
8694 let mut len = 0;
8695 for chunk in buffer.text_for_range(start..end) {
8696 text.push_str(chunk);
8697 len += chunk.len();
8698 }
8699 clipboard_selections.push(ClipboardSelection {
8700 len,
8701 is_entire_line,
8702 start_column: start.column,
8703 });
8704 }
8705 }
8706
8707 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8708 text,
8709 clipboard_selections,
8710 ));
8711 }
8712
8713 pub fn do_paste(
8714 &mut self,
8715 text: &String,
8716 clipboard_selections: Option<Vec<ClipboardSelection>>,
8717 handle_entire_lines: bool,
8718 window: &mut Window,
8719 cx: &mut Context<Self>,
8720 ) {
8721 if self.read_only(cx) {
8722 return;
8723 }
8724
8725 let clipboard_text = Cow::Borrowed(text);
8726
8727 self.transact(window, cx, |this, window, cx| {
8728 if let Some(mut clipboard_selections) = clipboard_selections {
8729 let old_selections = this.selections.all::<usize>(cx);
8730 let all_selections_were_entire_line =
8731 clipboard_selections.iter().all(|s| s.is_entire_line);
8732 let first_selection_start_column =
8733 clipboard_selections.first().map(|s| s.start_column);
8734 if clipboard_selections.len() != old_selections.len() {
8735 clipboard_selections.drain(..);
8736 }
8737 let cursor_offset = this.selections.last::<usize>(cx).head();
8738 let mut auto_indent_on_paste = true;
8739
8740 this.buffer.update(cx, |buffer, cx| {
8741 let snapshot = buffer.read(cx);
8742 auto_indent_on_paste =
8743 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8744
8745 let mut start_offset = 0;
8746 let mut edits = Vec::new();
8747 let mut original_start_columns = Vec::new();
8748 for (ix, selection) in old_selections.iter().enumerate() {
8749 let to_insert;
8750 let entire_line;
8751 let original_start_column;
8752 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8753 let end_offset = start_offset + clipboard_selection.len;
8754 to_insert = &clipboard_text[start_offset..end_offset];
8755 entire_line = clipboard_selection.is_entire_line;
8756 start_offset = end_offset + 1;
8757 original_start_column = Some(clipboard_selection.start_column);
8758 } else {
8759 to_insert = clipboard_text.as_str();
8760 entire_line = all_selections_were_entire_line;
8761 original_start_column = first_selection_start_column
8762 }
8763
8764 // If the corresponding selection was empty when this slice of the
8765 // clipboard text was written, then the entire line containing the
8766 // selection was copied. If this selection is also currently empty,
8767 // then paste the line before the current line of the buffer.
8768 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8769 let column = selection.start.to_point(&snapshot).column as usize;
8770 let line_start = selection.start - column;
8771 line_start..line_start
8772 } else {
8773 selection.range()
8774 };
8775
8776 edits.push((range, to_insert));
8777 original_start_columns.extend(original_start_column);
8778 }
8779 drop(snapshot);
8780
8781 buffer.edit(
8782 edits,
8783 if auto_indent_on_paste {
8784 Some(AutoindentMode::Block {
8785 original_start_columns,
8786 })
8787 } else {
8788 None
8789 },
8790 cx,
8791 );
8792 });
8793
8794 let selections = this.selections.all::<usize>(cx);
8795 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8796 s.select(selections)
8797 });
8798 } else {
8799 this.insert(&clipboard_text, window, cx);
8800 }
8801 });
8802 }
8803
8804 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8805 if let Some(item) = cx.read_from_clipboard() {
8806 let entries = item.entries();
8807
8808 match entries.first() {
8809 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8810 // of all the pasted entries.
8811 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8812 .do_paste(
8813 clipboard_string.text(),
8814 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8815 true,
8816 window,
8817 cx,
8818 ),
8819 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8820 }
8821 }
8822 }
8823
8824 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8825 if self.read_only(cx) {
8826 return;
8827 }
8828
8829 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8830 if let Some((selections, _)) =
8831 self.selection_history.transaction(transaction_id).cloned()
8832 {
8833 self.change_selections(None, window, cx, |s| {
8834 s.select_anchors(selections.to_vec());
8835 });
8836 } else {
8837 log::error!(
8838 "No entry in selection_history found for undo. \
8839 This may correspond to a bug where undo does not update the selection. \
8840 If this is occurring, please add details to \
8841 https://github.com/zed-industries/zed/issues/22692"
8842 );
8843 }
8844 self.request_autoscroll(Autoscroll::fit(), cx);
8845 self.unmark_text(window, cx);
8846 self.refresh_inline_completion(true, false, window, cx);
8847 cx.emit(EditorEvent::Edited { transaction_id });
8848 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8849 }
8850 }
8851
8852 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8853 if self.read_only(cx) {
8854 return;
8855 }
8856
8857 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8858 if let Some((_, Some(selections))) =
8859 self.selection_history.transaction(transaction_id).cloned()
8860 {
8861 self.change_selections(None, window, cx, |s| {
8862 s.select_anchors(selections.to_vec());
8863 });
8864 } else {
8865 log::error!(
8866 "No entry in selection_history found for redo. \
8867 This may correspond to a bug where undo does not update the selection. \
8868 If this is occurring, please add details to \
8869 https://github.com/zed-industries/zed/issues/22692"
8870 );
8871 }
8872 self.request_autoscroll(Autoscroll::fit(), cx);
8873 self.unmark_text(window, cx);
8874 self.refresh_inline_completion(true, false, window, cx);
8875 cx.emit(EditorEvent::Edited { transaction_id });
8876 }
8877 }
8878
8879 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8880 self.buffer
8881 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8882 }
8883
8884 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8885 self.buffer
8886 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8887 }
8888
8889 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8890 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8891 let line_mode = s.line_mode;
8892 s.move_with(|map, selection| {
8893 let cursor = if selection.is_empty() && !line_mode {
8894 movement::left(map, selection.start)
8895 } else {
8896 selection.start
8897 };
8898 selection.collapse_to(cursor, SelectionGoal::None);
8899 });
8900 })
8901 }
8902
8903 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8904 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8905 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8906 })
8907 }
8908
8909 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8910 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8911 let line_mode = s.line_mode;
8912 s.move_with(|map, selection| {
8913 let cursor = if selection.is_empty() && !line_mode {
8914 movement::right(map, selection.end)
8915 } else {
8916 selection.end
8917 };
8918 selection.collapse_to(cursor, SelectionGoal::None)
8919 });
8920 })
8921 }
8922
8923 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8924 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8925 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8926 })
8927 }
8928
8929 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8930 if self.take_rename(true, window, cx).is_some() {
8931 return;
8932 }
8933
8934 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8935 cx.propagate();
8936 return;
8937 }
8938
8939 let text_layout_details = &self.text_layout_details(window);
8940 let selection_count = self.selections.count();
8941 let first_selection = self.selections.first_anchor();
8942
8943 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8944 let line_mode = s.line_mode;
8945 s.move_with(|map, selection| {
8946 if !selection.is_empty() && !line_mode {
8947 selection.goal = SelectionGoal::None;
8948 }
8949 let (cursor, goal) = movement::up(
8950 map,
8951 selection.start,
8952 selection.goal,
8953 false,
8954 text_layout_details,
8955 );
8956 selection.collapse_to(cursor, goal);
8957 });
8958 });
8959
8960 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8961 {
8962 cx.propagate();
8963 }
8964 }
8965
8966 pub fn move_up_by_lines(
8967 &mut self,
8968 action: &MoveUpByLines,
8969 window: &mut Window,
8970 cx: &mut Context<Self>,
8971 ) {
8972 if self.take_rename(true, window, cx).is_some() {
8973 return;
8974 }
8975
8976 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8977 cx.propagate();
8978 return;
8979 }
8980
8981 let text_layout_details = &self.text_layout_details(window);
8982
8983 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8984 let line_mode = s.line_mode;
8985 s.move_with(|map, selection| {
8986 if !selection.is_empty() && !line_mode {
8987 selection.goal = SelectionGoal::None;
8988 }
8989 let (cursor, goal) = movement::up_by_rows(
8990 map,
8991 selection.start,
8992 action.lines,
8993 selection.goal,
8994 false,
8995 text_layout_details,
8996 );
8997 selection.collapse_to(cursor, goal);
8998 });
8999 })
9000 }
9001
9002 pub fn move_down_by_lines(
9003 &mut self,
9004 action: &MoveDownByLines,
9005 window: &mut Window,
9006 cx: &mut Context<Self>,
9007 ) {
9008 if self.take_rename(true, window, cx).is_some() {
9009 return;
9010 }
9011
9012 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9013 cx.propagate();
9014 return;
9015 }
9016
9017 let text_layout_details = &self.text_layout_details(window);
9018
9019 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9020 let line_mode = s.line_mode;
9021 s.move_with(|map, selection| {
9022 if !selection.is_empty() && !line_mode {
9023 selection.goal = SelectionGoal::None;
9024 }
9025 let (cursor, goal) = movement::down_by_rows(
9026 map,
9027 selection.start,
9028 action.lines,
9029 selection.goal,
9030 false,
9031 text_layout_details,
9032 );
9033 selection.collapse_to(cursor, goal);
9034 });
9035 })
9036 }
9037
9038 pub fn select_down_by_lines(
9039 &mut self,
9040 action: &SelectDownByLines,
9041 window: &mut Window,
9042 cx: &mut Context<Self>,
9043 ) {
9044 let text_layout_details = &self.text_layout_details(window);
9045 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9046 s.move_heads_with(|map, head, goal| {
9047 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9048 })
9049 })
9050 }
9051
9052 pub fn select_up_by_lines(
9053 &mut self,
9054 action: &SelectUpByLines,
9055 window: &mut Window,
9056 cx: &mut Context<Self>,
9057 ) {
9058 let text_layout_details = &self.text_layout_details(window);
9059 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9060 s.move_heads_with(|map, head, goal| {
9061 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9062 })
9063 })
9064 }
9065
9066 pub fn select_page_up(
9067 &mut self,
9068 _: &SelectPageUp,
9069 window: &mut Window,
9070 cx: &mut Context<Self>,
9071 ) {
9072 let Some(row_count) = self.visible_row_count() else {
9073 return;
9074 };
9075
9076 let text_layout_details = &self.text_layout_details(window);
9077
9078 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9079 s.move_heads_with(|map, head, goal| {
9080 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9081 })
9082 })
9083 }
9084
9085 pub fn move_page_up(
9086 &mut self,
9087 action: &MovePageUp,
9088 window: &mut Window,
9089 cx: &mut Context<Self>,
9090 ) {
9091 if self.take_rename(true, window, cx).is_some() {
9092 return;
9093 }
9094
9095 if self
9096 .context_menu
9097 .borrow_mut()
9098 .as_mut()
9099 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9100 .unwrap_or(false)
9101 {
9102 return;
9103 }
9104
9105 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9106 cx.propagate();
9107 return;
9108 }
9109
9110 let Some(row_count) = self.visible_row_count() else {
9111 return;
9112 };
9113
9114 let autoscroll = if action.center_cursor {
9115 Autoscroll::center()
9116 } else {
9117 Autoscroll::fit()
9118 };
9119
9120 let text_layout_details = &self.text_layout_details(window);
9121
9122 self.change_selections(Some(autoscroll), window, cx, |s| {
9123 let line_mode = s.line_mode;
9124 s.move_with(|map, selection| {
9125 if !selection.is_empty() && !line_mode {
9126 selection.goal = SelectionGoal::None;
9127 }
9128 let (cursor, goal) = movement::up_by_rows(
9129 map,
9130 selection.end,
9131 row_count,
9132 selection.goal,
9133 false,
9134 text_layout_details,
9135 );
9136 selection.collapse_to(cursor, goal);
9137 });
9138 });
9139 }
9140
9141 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9142 let text_layout_details = &self.text_layout_details(window);
9143 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9144 s.move_heads_with(|map, head, goal| {
9145 movement::up(map, head, goal, false, text_layout_details)
9146 })
9147 })
9148 }
9149
9150 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9151 self.take_rename(true, window, cx);
9152
9153 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9154 cx.propagate();
9155 return;
9156 }
9157
9158 let text_layout_details = &self.text_layout_details(window);
9159 let selection_count = self.selections.count();
9160 let first_selection = self.selections.first_anchor();
9161
9162 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9163 let line_mode = s.line_mode;
9164 s.move_with(|map, selection| {
9165 if !selection.is_empty() && !line_mode {
9166 selection.goal = SelectionGoal::None;
9167 }
9168 let (cursor, goal) = movement::down(
9169 map,
9170 selection.end,
9171 selection.goal,
9172 false,
9173 text_layout_details,
9174 );
9175 selection.collapse_to(cursor, goal);
9176 });
9177 });
9178
9179 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9180 {
9181 cx.propagate();
9182 }
9183 }
9184
9185 pub fn select_page_down(
9186 &mut self,
9187 _: &SelectPageDown,
9188 window: &mut Window,
9189 cx: &mut Context<Self>,
9190 ) {
9191 let Some(row_count) = self.visible_row_count() else {
9192 return;
9193 };
9194
9195 let text_layout_details = &self.text_layout_details(window);
9196
9197 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9198 s.move_heads_with(|map, head, goal| {
9199 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9200 })
9201 })
9202 }
9203
9204 pub fn move_page_down(
9205 &mut self,
9206 action: &MovePageDown,
9207 window: &mut Window,
9208 cx: &mut Context<Self>,
9209 ) {
9210 if self.take_rename(true, window, cx).is_some() {
9211 return;
9212 }
9213
9214 if self
9215 .context_menu
9216 .borrow_mut()
9217 .as_mut()
9218 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9219 .unwrap_or(false)
9220 {
9221 return;
9222 }
9223
9224 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9225 cx.propagate();
9226 return;
9227 }
9228
9229 let Some(row_count) = self.visible_row_count() else {
9230 return;
9231 };
9232
9233 let autoscroll = if action.center_cursor {
9234 Autoscroll::center()
9235 } else {
9236 Autoscroll::fit()
9237 };
9238
9239 let text_layout_details = &self.text_layout_details(window);
9240 self.change_selections(Some(autoscroll), window, cx, |s| {
9241 let line_mode = s.line_mode;
9242 s.move_with(|map, selection| {
9243 if !selection.is_empty() && !line_mode {
9244 selection.goal = SelectionGoal::None;
9245 }
9246 let (cursor, goal) = movement::down_by_rows(
9247 map,
9248 selection.end,
9249 row_count,
9250 selection.goal,
9251 false,
9252 text_layout_details,
9253 );
9254 selection.collapse_to(cursor, goal);
9255 });
9256 });
9257 }
9258
9259 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9260 let text_layout_details = &self.text_layout_details(window);
9261 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9262 s.move_heads_with(|map, head, goal| {
9263 movement::down(map, head, goal, false, text_layout_details)
9264 })
9265 });
9266 }
9267
9268 pub fn context_menu_first(
9269 &mut self,
9270 _: &ContextMenuFirst,
9271 _window: &mut Window,
9272 cx: &mut Context<Self>,
9273 ) {
9274 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9275 context_menu.select_first(self.completion_provider.as_deref(), cx);
9276 }
9277 }
9278
9279 pub fn context_menu_prev(
9280 &mut self,
9281 _: &ContextMenuPrevious,
9282 _window: &mut Window,
9283 cx: &mut Context<Self>,
9284 ) {
9285 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9286 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9287 }
9288 }
9289
9290 pub fn context_menu_next(
9291 &mut self,
9292 _: &ContextMenuNext,
9293 _window: &mut Window,
9294 cx: &mut Context<Self>,
9295 ) {
9296 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9297 context_menu.select_next(self.completion_provider.as_deref(), cx);
9298 }
9299 }
9300
9301 pub fn context_menu_last(
9302 &mut self,
9303 _: &ContextMenuLast,
9304 _window: &mut Window,
9305 cx: &mut Context<Self>,
9306 ) {
9307 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9308 context_menu.select_last(self.completion_provider.as_deref(), cx);
9309 }
9310 }
9311
9312 pub fn move_to_previous_word_start(
9313 &mut self,
9314 _: &MoveToPreviousWordStart,
9315 window: &mut Window,
9316 cx: &mut Context<Self>,
9317 ) {
9318 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9319 s.move_cursors_with(|map, head, _| {
9320 (
9321 movement::previous_word_start(map, head),
9322 SelectionGoal::None,
9323 )
9324 });
9325 })
9326 }
9327
9328 pub fn move_to_previous_subword_start(
9329 &mut self,
9330 _: &MoveToPreviousSubwordStart,
9331 window: &mut Window,
9332 cx: &mut Context<Self>,
9333 ) {
9334 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9335 s.move_cursors_with(|map, head, _| {
9336 (
9337 movement::previous_subword_start(map, head),
9338 SelectionGoal::None,
9339 )
9340 });
9341 })
9342 }
9343
9344 pub fn select_to_previous_word_start(
9345 &mut self,
9346 _: &SelectToPreviousWordStart,
9347 window: &mut Window,
9348 cx: &mut Context<Self>,
9349 ) {
9350 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9351 s.move_heads_with(|map, head, _| {
9352 (
9353 movement::previous_word_start(map, head),
9354 SelectionGoal::None,
9355 )
9356 });
9357 })
9358 }
9359
9360 pub fn select_to_previous_subword_start(
9361 &mut self,
9362 _: &SelectToPreviousSubwordStart,
9363 window: &mut Window,
9364 cx: &mut Context<Self>,
9365 ) {
9366 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9367 s.move_heads_with(|map, head, _| {
9368 (
9369 movement::previous_subword_start(map, head),
9370 SelectionGoal::None,
9371 )
9372 });
9373 })
9374 }
9375
9376 pub fn delete_to_previous_word_start(
9377 &mut self,
9378 action: &DeleteToPreviousWordStart,
9379 window: &mut Window,
9380 cx: &mut Context<Self>,
9381 ) {
9382 self.transact(window, cx, |this, window, cx| {
9383 this.select_autoclose_pair(window, cx);
9384 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9385 let line_mode = s.line_mode;
9386 s.move_with(|map, selection| {
9387 if selection.is_empty() && !line_mode {
9388 let cursor = if action.ignore_newlines {
9389 movement::previous_word_start(map, selection.head())
9390 } else {
9391 movement::previous_word_start_or_newline(map, selection.head())
9392 };
9393 selection.set_head(cursor, SelectionGoal::None);
9394 }
9395 });
9396 });
9397 this.insert("", window, cx);
9398 });
9399 }
9400
9401 pub fn delete_to_previous_subword_start(
9402 &mut self,
9403 _: &DeleteToPreviousSubwordStart,
9404 window: &mut Window,
9405 cx: &mut Context<Self>,
9406 ) {
9407 self.transact(window, cx, |this, window, cx| {
9408 this.select_autoclose_pair(window, cx);
9409 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9410 let line_mode = s.line_mode;
9411 s.move_with(|map, selection| {
9412 if selection.is_empty() && !line_mode {
9413 let cursor = movement::previous_subword_start(map, selection.head());
9414 selection.set_head(cursor, SelectionGoal::None);
9415 }
9416 });
9417 });
9418 this.insert("", window, cx);
9419 });
9420 }
9421
9422 pub fn move_to_next_word_end(
9423 &mut self,
9424 _: &MoveToNextWordEnd,
9425 window: &mut Window,
9426 cx: &mut Context<Self>,
9427 ) {
9428 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9429 s.move_cursors_with(|map, head, _| {
9430 (movement::next_word_end(map, head), SelectionGoal::None)
9431 });
9432 })
9433 }
9434
9435 pub fn move_to_next_subword_end(
9436 &mut self,
9437 _: &MoveToNextSubwordEnd,
9438 window: &mut Window,
9439 cx: &mut Context<Self>,
9440 ) {
9441 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9442 s.move_cursors_with(|map, head, _| {
9443 (movement::next_subword_end(map, head), SelectionGoal::None)
9444 });
9445 })
9446 }
9447
9448 pub fn select_to_next_word_end(
9449 &mut self,
9450 _: &SelectToNextWordEnd,
9451 window: &mut Window,
9452 cx: &mut Context<Self>,
9453 ) {
9454 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9455 s.move_heads_with(|map, head, _| {
9456 (movement::next_word_end(map, head), SelectionGoal::None)
9457 });
9458 })
9459 }
9460
9461 pub fn select_to_next_subword_end(
9462 &mut self,
9463 _: &SelectToNextSubwordEnd,
9464 window: &mut Window,
9465 cx: &mut Context<Self>,
9466 ) {
9467 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9468 s.move_heads_with(|map, head, _| {
9469 (movement::next_subword_end(map, head), SelectionGoal::None)
9470 });
9471 })
9472 }
9473
9474 pub fn delete_to_next_word_end(
9475 &mut self,
9476 action: &DeleteToNextWordEnd,
9477 window: &mut Window,
9478 cx: &mut Context<Self>,
9479 ) {
9480 self.transact(window, cx, |this, window, cx| {
9481 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9482 let line_mode = s.line_mode;
9483 s.move_with(|map, selection| {
9484 if selection.is_empty() && !line_mode {
9485 let cursor = if action.ignore_newlines {
9486 movement::next_word_end(map, selection.head())
9487 } else {
9488 movement::next_word_end_or_newline(map, selection.head())
9489 };
9490 selection.set_head(cursor, SelectionGoal::None);
9491 }
9492 });
9493 });
9494 this.insert("", window, cx);
9495 });
9496 }
9497
9498 pub fn delete_to_next_subword_end(
9499 &mut self,
9500 _: &DeleteToNextSubwordEnd,
9501 window: &mut Window,
9502 cx: &mut Context<Self>,
9503 ) {
9504 self.transact(window, cx, |this, window, cx| {
9505 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9506 s.move_with(|map, selection| {
9507 if selection.is_empty() {
9508 let cursor = movement::next_subword_end(map, selection.head());
9509 selection.set_head(cursor, SelectionGoal::None);
9510 }
9511 });
9512 });
9513 this.insert("", window, cx);
9514 });
9515 }
9516
9517 pub fn move_to_beginning_of_line(
9518 &mut self,
9519 action: &MoveToBeginningOfLine,
9520 window: &mut Window,
9521 cx: &mut Context<Self>,
9522 ) {
9523 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9524 s.move_cursors_with(|map, head, _| {
9525 (
9526 movement::indented_line_beginning(
9527 map,
9528 head,
9529 action.stop_at_soft_wraps,
9530 action.stop_at_indent,
9531 ),
9532 SelectionGoal::None,
9533 )
9534 });
9535 })
9536 }
9537
9538 pub fn select_to_beginning_of_line(
9539 &mut self,
9540 action: &SelectToBeginningOfLine,
9541 window: &mut Window,
9542 cx: &mut Context<Self>,
9543 ) {
9544 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9545 s.move_heads_with(|map, head, _| {
9546 (
9547 movement::indented_line_beginning(
9548 map,
9549 head,
9550 action.stop_at_soft_wraps,
9551 action.stop_at_indent,
9552 ),
9553 SelectionGoal::None,
9554 )
9555 });
9556 });
9557 }
9558
9559 pub fn delete_to_beginning_of_line(
9560 &mut self,
9561 action: &DeleteToBeginningOfLine,
9562 window: &mut Window,
9563 cx: &mut Context<Self>,
9564 ) {
9565 self.transact(window, cx, |this, window, cx| {
9566 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9567 s.move_with(|_, selection| {
9568 selection.reversed = true;
9569 });
9570 });
9571
9572 this.select_to_beginning_of_line(
9573 &SelectToBeginningOfLine {
9574 stop_at_soft_wraps: false,
9575 stop_at_indent: action.stop_at_indent,
9576 },
9577 window,
9578 cx,
9579 );
9580 this.backspace(&Backspace, window, cx);
9581 });
9582 }
9583
9584 pub fn move_to_end_of_line(
9585 &mut self,
9586 action: &MoveToEndOfLine,
9587 window: &mut Window,
9588 cx: &mut Context<Self>,
9589 ) {
9590 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9591 s.move_cursors_with(|map, head, _| {
9592 (
9593 movement::line_end(map, head, action.stop_at_soft_wraps),
9594 SelectionGoal::None,
9595 )
9596 });
9597 })
9598 }
9599
9600 pub fn select_to_end_of_line(
9601 &mut self,
9602 action: &SelectToEndOfLine,
9603 window: &mut Window,
9604 cx: &mut Context<Self>,
9605 ) {
9606 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9607 s.move_heads_with(|map, head, _| {
9608 (
9609 movement::line_end(map, head, action.stop_at_soft_wraps),
9610 SelectionGoal::None,
9611 )
9612 });
9613 })
9614 }
9615
9616 pub fn delete_to_end_of_line(
9617 &mut self,
9618 _: &DeleteToEndOfLine,
9619 window: &mut Window,
9620 cx: &mut Context<Self>,
9621 ) {
9622 self.transact(window, cx, |this, window, cx| {
9623 this.select_to_end_of_line(
9624 &SelectToEndOfLine {
9625 stop_at_soft_wraps: false,
9626 },
9627 window,
9628 cx,
9629 );
9630 this.delete(&Delete, window, cx);
9631 });
9632 }
9633
9634 pub fn cut_to_end_of_line(
9635 &mut self,
9636 _: &CutToEndOfLine,
9637 window: &mut Window,
9638 cx: &mut Context<Self>,
9639 ) {
9640 self.transact(window, cx, |this, window, cx| {
9641 this.select_to_end_of_line(
9642 &SelectToEndOfLine {
9643 stop_at_soft_wraps: false,
9644 },
9645 window,
9646 cx,
9647 );
9648 this.cut(&Cut, window, cx);
9649 });
9650 }
9651
9652 pub fn move_to_start_of_paragraph(
9653 &mut self,
9654 _: &MoveToStartOfParagraph,
9655 window: &mut Window,
9656 cx: &mut Context<Self>,
9657 ) {
9658 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9659 cx.propagate();
9660 return;
9661 }
9662
9663 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9664 s.move_with(|map, selection| {
9665 selection.collapse_to(
9666 movement::start_of_paragraph(map, selection.head(), 1),
9667 SelectionGoal::None,
9668 )
9669 });
9670 })
9671 }
9672
9673 pub fn move_to_end_of_paragraph(
9674 &mut self,
9675 _: &MoveToEndOfParagraph,
9676 window: &mut Window,
9677 cx: &mut Context<Self>,
9678 ) {
9679 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9680 cx.propagate();
9681 return;
9682 }
9683
9684 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9685 s.move_with(|map, selection| {
9686 selection.collapse_to(
9687 movement::end_of_paragraph(map, selection.head(), 1),
9688 SelectionGoal::None,
9689 )
9690 });
9691 })
9692 }
9693
9694 pub fn select_to_start_of_paragraph(
9695 &mut self,
9696 _: &SelectToStartOfParagraph,
9697 window: &mut Window,
9698 cx: &mut Context<Self>,
9699 ) {
9700 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9701 cx.propagate();
9702 return;
9703 }
9704
9705 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9706 s.move_heads_with(|map, head, _| {
9707 (
9708 movement::start_of_paragraph(map, head, 1),
9709 SelectionGoal::None,
9710 )
9711 });
9712 })
9713 }
9714
9715 pub fn select_to_end_of_paragraph(
9716 &mut self,
9717 _: &SelectToEndOfParagraph,
9718 window: &mut Window,
9719 cx: &mut Context<Self>,
9720 ) {
9721 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9722 cx.propagate();
9723 return;
9724 }
9725
9726 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9727 s.move_heads_with(|map, head, _| {
9728 (
9729 movement::end_of_paragraph(map, head, 1),
9730 SelectionGoal::None,
9731 )
9732 });
9733 })
9734 }
9735
9736 pub fn move_to_start_of_excerpt(
9737 &mut self,
9738 _: &MoveToStartOfExcerpt,
9739 window: &mut Window,
9740 cx: &mut Context<Self>,
9741 ) {
9742 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9743 cx.propagate();
9744 return;
9745 }
9746
9747 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9748 s.move_with(|map, selection| {
9749 selection.collapse_to(
9750 movement::start_of_excerpt(
9751 map,
9752 selection.head(),
9753 workspace::searchable::Direction::Prev,
9754 ),
9755 SelectionGoal::None,
9756 )
9757 });
9758 })
9759 }
9760
9761 pub fn move_to_end_of_excerpt(
9762 &mut self,
9763 _: &MoveToEndOfExcerpt,
9764 window: &mut Window,
9765 cx: &mut Context<Self>,
9766 ) {
9767 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9768 cx.propagate();
9769 return;
9770 }
9771
9772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9773 s.move_with(|map, selection| {
9774 selection.collapse_to(
9775 movement::end_of_excerpt(
9776 map,
9777 selection.head(),
9778 workspace::searchable::Direction::Next,
9779 ),
9780 SelectionGoal::None,
9781 )
9782 });
9783 })
9784 }
9785
9786 pub fn select_to_start_of_excerpt(
9787 &mut self,
9788 _: &SelectToStartOfExcerpt,
9789 window: &mut Window,
9790 cx: &mut Context<Self>,
9791 ) {
9792 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9793 cx.propagate();
9794 return;
9795 }
9796
9797 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9798 s.move_heads_with(|map, head, _| {
9799 (
9800 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9801 SelectionGoal::None,
9802 )
9803 });
9804 })
9805 }
9806
9807 pub fn select_to_end_of_excerpt(
9808 &mut self,
9809 _: &SelectToEndOfExcerpt,
9810 window: &mut Window,
9811 cx: &mut Context<Self>,
9812 ) {
9813 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9814 cx.propagate();
9815 return;
9816 }
9817
9818 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9819 s.move_heads_with(|map, head, _| {
9820 (
9821 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9822 SelectionGoal::None,
9823 )
9824 });
9825 })
9826 }
9827
9828 pub fn move_to_beginning(
9829 &mut self,
9830 _: &MoveToBeginning,
9831 window: &mut Window,
9832 cx: &mut Context<Self>,
9833 ) {
9834 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9835 cx.propagate();
9836 return;
9837 }
9838
9839 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9840 s.select_ranges(vec![0..0]);
9841 });
9842 }
9843
9844 pub fn select_to_beginning(
9845 &mut self,
9846 _: &SelectToBeginning,
9847 window: &mut Window,
9848 cx: &mut Context<Self>,
9849 ) {
9850 let mut selection = self.selections.last::<Point>(cx);
9851 selection.set_head(Point::zero(), SelectionGoal::None);
9852
9853 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9854 s.select(vec![selection]);
9855 });
9856 }
9857
9858 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9859 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9860 cx.propagate();
9861 return;
9862 }
9863
9864 let cursor = self.buffer.read(cx).read(cx).len();
9865 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9866 s.select_ranges(vec![cursor..cursor])
9867 });
9868 }
9869
9870 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9871 self.nav_history = nav_history;
9872 }
9873
9874 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9875 self.nav_history.as_ref()
9876 }
9877
9878 fn push_to_nav_history(
9879 &mut self,
9880 cursor_anchor: Anchor,
9881 new_position: Option<Point>,
9882 cx: &mut Context<Self>,
9883 ) {
9884 if let Some(nav_history) = self.nav_history.as_mut() {
9885 let buffer = self.buffer.read(cx).read(cx);
9886 let cursor_position = cursor_anchor.to_point(&buffer);
9887 let scroll_state = self.scroll_manager.anchor();
9888 let scroll_top_row = scroll_state.top_row(&buffer);
9889 drop(buffer);
9890
9891 if let Some(new_position) = new_position {
9892 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9893 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9894 return;
9895 }
9896 }
9897
9898 nav_history.push(
9899 Some(NavigationData {
9900 cursor_anchor,
9901 cursor_position,
9902 scroll_anchor: scroll_state,
9903 scroll_top_row,
9904 }),
9905 cx,
9906 );
9907 }
9908 }
9909
9910 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9911 let buffer = self.buffer.read(cx).snapshot(cx);
9912 let mut selection = self.selections.first::<usize>(cx);
9913 selection.set_head(buffer.len(), SelectionGoal::None);
9914 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9915 s.select(vec![selection]);
9916 });
9917 }
9918
9919 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9920 let end = self.buffer.read(cx).read(cx).len();
9921 self.change_selections(None, window, cx, |s| {
9922 s.select_ranges(vec![0..end]);
9923 });
9924 }
9925
9926 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9927 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9928 let mut selections = self.selections.all::<Point>(cx);
9929 let max_point = display_map.buffer_snapshot.max_point();
9930 for selection in &mut selections {
9931 let rows = selection.spanned_rows(true, &display_map);
9932 selection.start = Point::new(rows.start.0, 0);
9933 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9934 selection.reversed = false;
9935 }
9936 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9937 s.select(selections);
9938 });
9939 }
9940
9941 pub fn split_selection_into_lines(
9942 &mut self,
9943 _: &SplitSelectionIntoLines,
9944 window: &mut Window,
9945 cx: &mut Context<Self>,
9946 ) {
9947 let selections = self
9948 .selections
9949 .all::<Point>(cx)
9950 .into_iter()
9951 .map(|selection| selection.start..selection.end)
9952 .collect::<Vec<_>>();
9953 self.unfold_ranges(&selections, true, true, cx);
9954
9955 let mut new_selection_ranges = Vec::new();
9956 {
9957 let buffer = self.buffer.read(cx).read(cx);
9958 for selection in selections {
9959 for row in selection.start.row..selection.end.row {
9960 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9961 new_selection_ranges.push(cursor..cursor);
9962 }
9963
9964 let is_multiline_selection = selection.start.row != selection.end.row;
9965 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9966 // so this action feels more ergonomic when paired with other selection operations
9967 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9968 if !should_skip_last {
9969 new_selection_ranges.push(selection.end..selection.end);
9970 }
9971 }
9972 }
9973 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9974 s.select_ranges(new_selection_ranges);
9975 });
9976 }
9977
9978 pub fn add_selection_above(
9979 &mut self,
9980 _: &AddSelectionAbove,
9981 window: &mut Window,
9982 cx: &mut Context<Self>,
9983 ) {
9984 self.add_selection(true, window, cx);
9985 }
9986
9987 pub fn add_selection_below(
9988 &mut self,
9989 _: &AddSelectionBelow,
9990 window: &mut Window,
9991 cx: &mut Context<Self>,
9992 ) {
9993 self.add_selection(false, window, cx);
9994 }
9995
9996 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9997 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9998 let mut selections = self.selections.all::<Point>(cx);
9999 let text_layout_details = self.text_layout_details(window);
10000 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10001 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10002 let range = oldest_selection.display_range(&display_map).sorted();
10003
10004 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10005 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10006 let positions = start_x.min(end_x)..start_x.max(end_x);
10007
10008 selections.clear();
10009 let mut stack = Vec::new();
10010 for row in range.start.row().0..=range.end.row().0 {
10011 if let Some(selection) = self.selections.build_columnar_selection(
10012 &display_map,
10013 DisplayRow(row),
10014 &positions,
10015 oldest_selection.reversed,
10016 &text_layout_details,
10017 ) {
10018 stack.push(selection.id);
10019 selections.push(selection);
10020 }
10021 }
10022
10023 if above {
10024 stack.reverse();
10025 }
10026
10027 AddSelectionsState { above, stack }
10028 });
10029
10030 let last_added_selection = *state.stack.last().unwrap();
10031 let mut new_selections = Vec::new();
10032 if above == state.above {
10033 let end_row = if above {
10034 DisplayRow(0)
10035 } else {
10036 display_map.max_point().row()
10037 };
10038
10039 'outer: for selection in selections {
10040 if selection.id == last_added_selection {
10041 let range = selection.display_range(&display_map).sorted();
10042 debug_assert_eq!(range.start.row(), range.end.row());
10043 let mut row = range.start.row();
10044 let positions =
10045 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10046 px(start)..px(end)
10047 } else {
10048 let start_x =
10049 display_map.x_for_display_point(range.start, &text_layout_details);
10050 let end_x =
10051 display_map.x_for_display_point(range.end, &text_layout_details);
10052 start_x.min(end_x)..start_x.max(end_x)
10053 };
10054
10055 while row != end_row {
10056 if above {
10057 row.0 -= 1;
10058 } else {
10059 row.0 += 1;
10060 }
10061
10062 if let Some(new_selection) = self.selections.build_columnar_selection(
10063 &display_map,
10064 row,
10065 &positions,
10066 selection.reversed,
10067 &text_layout_details,
10068 ) {
10069 state.stack.push(new_selection.id);
10070 if above {
10071 new_selections.push(new_selection);
10072 new_selections.push(selection);
10073 } else {
10074 new_selections.push(selection);
10075 new_selections.push(new_selection);
10076 }
10077
10078 continue 'outer;
10079 }
10080 }
10081 }
10082
10083 new_selections.push(selection);
10084 }
10085 } else {
10086 new_selections = selections;
10087 new_selections.retain(|s| s.id != last_added_selection);
10088 state.stack.pop();
10089 }
10090
10091 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10092 s.select(new_selections);
10093 });
10094 if state.stack.len() > 1 {
10095 self.add_selections_state = Some(state);
10096 }
10097 }
10098
10099 pub fn select_next_match_internal(
10100 &mut self,
10101 display_map: &DisplaySnapshot,
10102 replace_newest: bool,
10103 autoscroll: Option<Autoscroll>,
10104 window: &mut Window,
10105 cx: &mut Context<Self>,
10106 ) -> Result<()> {
10107 fn select_next_match_ranges(
10108 this: &mut Editor,
10109 range: Range<usize>,
10110 replace_newest: bool,
10111 auto_scroll: Option<Autoscroll>,
10112 window: &mut Window,
10113 cx: &mut Context<Editor>,
10114 ) {
10115 this.unfold_ranges(&[range.clone()], false, true, cx);
10116 this.change_selections(auto_scroll, window, cx, |s| {
10117 if replace_newest {
10118 s.delete(s.newest_anchor().id);
10119 }
10120 s.insert_range(range.clone());
10121 });
10122 }
10123
10124 let buffer = &display_map.buffer_snapshot;
10125 let mut selections = self.selections.all::<usize>(cx);
10126 if let Some(mut select_next_state) = self.select_next_state.take() {
10127 let query = &select_next_state.query;
10128 if !select_next_state.done {
10129 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10130 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10131 let mut next_selected_range = None;
10132
10133 let bytes_after_last_selection =
10134 buffer.bytes_in_range(last_selection.end..buffer.len());
10135 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10136 let query_matches = query
10137 .stream_find_iter(bytes_after_last_selection)
10138 .map(|result| (last_selection.end, result))
10139 .chain(
10140 query
10141 .stream_find_iter(bytes_before_first_selection)
10142 .map(|result| (0, result)),
10143 );
10144
10145 for (start_offset, query_match) in query_matches {
10146 let query_match = query_match.unwrap(); // can only fail due to I/O
10147 let offset_range =
10148 start_offset + query_match.start()..start_offset + query_match.end();
10149 let display_range = offset_range.start.to_display_point(display_map)
10150 ..offset_range.end.to_display_point(display_map);
10151
10152 if !select_next_state.wordwise
10153 || (!movement::is_inside_word(display_map, display_range.start)
10154 && !movement::is_inside_word(display_map, display_range.end))
10155 {
10156 // TODO: This is n^2, because we might check all the selections
10157 if !selections
10158 .iter()
10159 .any(|selection| selection.range().overlaps(&offset_range))
10160 {
10161 next_selected_range = Some(offset_range);
10162 break;
10163 }
10164 }
10165 }
10166
10167 if let Some(next_selected_range) = next_selected_range {
10168 select_next_match_ranges(
10169 self,
10170 next_selected_range,
10171 replace_newest,
10172 autoscroll,
10173 window,
10174 cx,
10175 );
10176 } else {
10177 select_next_state.done = true;
10178 }
10179 }
10180
10181 self.select_next_state = Some(select_next_state);
10182 } else {
10183 let mut only_carets = true;
10184 let mut same_text_selected = true;
10185 let mut selected_text = None;
10186
10187 let mut selections_iter = selections.iter().peekable();
10188 while let Some(selection) = selections_iter.next() {
10189 if selection.start != selection.end {
10190 only_carets = false;
10191 }
10192
10193 if same_text_selected {
10194 if selected_text.is_none() {
10195 selected_text =
10196 Some(buffer.text_for_range(selection.range()).collect::<String>());
10197 }
10198
10199 if let Some(next_selection) = selections_iter.peek() {
10200 if next_selection.range().len() == selection.range().len() {
10201 let next_selected_text = buffer
10202 .text_for_range(next_selection.range())
10203 .collect::<String>();
10204 if Some(next_selected_text) != selected_text {
10205 same_text_selected = false;
10206 selected_text = None;
10207 }
10208 } else {
10209 same_text_selected = false;
10210 selected_text = None;
10211 }
10212 }
10213 }
10214 }
10215
10216 if only_carets {
10217 for selection in &mut selections {
10218 let word_range = movement::surrounding_word(
10219 display_map,
10220 selection.start.to_display_point(display_map),
10221 );
10222 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10223 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10224 selection.goal = SelectionGoal::None;
10225 selection.reversed = false;
10226 select_next_match_ranges(
10227 self,
10228 selection.start..selection.end,
10229 replace_newest,
10230 autoscroll,
10231 window,
10232 cx,
10233 );
10234 }
10235
10236 if selections.len() == 1 {
10237 let selection = selections
10238 .last()
10239 .expect("ensured that there's only one selection");
10240 let query = buffer
10241 .text_for_range(selection.start..selection.end)
10242 .collect::<String>();
10243 let is_empty = query.is_empty();
10244 let select_state = SelectNextState {
10245 query: AhoCorasick::new(&[query])?,
10246 wordwise: true,
10247 done: is_empty,
10248 };
10249 self.select_next_state = Some(select_state);
10250 } else {
10251 self.select_next_state = None;
10252 }
10253 } else if let Some(selected_text) = selected_text {
10254 self.select_next_state = Some(SelectNextState {
10255 query: AhoCorasick::new(&[selected_text])?,
10256 wordwise: false,
10257 done: false,
10258 });
10259 self.select_next_match_internal(
10260 display_map,
10261 replace_newest,
10262 autoscroll,
10263 window,
10264 cx,
10265 )?;
10266 }
10267 }
10268 Ok(())
10269 }
10270
10271 pub fn select_all_matches(
10272 &mut self,
10273 _action: &SelectAllMatches,
10274 window: &mut Window,
10275 cx: &mut Context<Self>,
10276 ) -> Result<()> {
10277 self.push_to_selection_history();
10278 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10279
10280 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10281 let Some(select_next_state) = self.select_next_state.as_mut() else {
10282 return Ok(());
10283 };
10284 if select_next_state.done {
10285 return Ok(());
10286 }
10287
10288 let mut new_selections = self.selections.all::<usize>(cx);
10289
10290 let buffer = &display_map.buffer_snapshot;
10291 let query_matches = select_next_state
10292 .query
10293 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10294
10295 for query_match in query_matches {
10296 let query_match = query_match.unwrap(); // can only fail due to I/O
10297 let offset_range = query_match.start()..query_match.end();
10298 let display_range = offset_range.start.to_display_point(&display_map)
10299 ..offset_range.end.to_display_point(&display_map);
10300
10301 if !select_next_state.wordwise
10302 || (!movement::is_inside_word(&display_map, display_range.start)
10303 && !movement::is_inside_word(&display_map, display_range.end))
10304 {
10305 self.selections.change_with(cx, |selections| {
10306 new_selections.push(Selection {
10307 id: selections.new_selection_id(),
10308 start: offset_range.start,
10309 end: offset_range.end,
10310 reversed: false,
10311 goal: SelectionGoal::None,
10312 });
10313 });
10314 }
10315 }
10316
10317 new_selections.sort_by_key(|selection| selection.start);
10318 let mut ix = 0;
10319 while ix + 1 < new_selections.len() {
10320 let current_selection = &new_selections[ix];
10321 let next_selection = &new_selections[ix + 1];
10322 if current_selection.range().overlaps(&next_selection.range()) {
10323 if current_selection.id < next_selection.id {
10324 new_selections.remove(ix + 1);
10325 } else {
10326 new_selections.remove(ix);
10327 }
10328 } else {
10329 ix += 1;
10330 }
10331 }
10332
10333 let reversed = self.selections.oldest::<usize>(cx).reversed;
10334
10335 for selection in new_selections.iter_mut() {
10336 selection.reversed = reversed;
10337 }
10338
10339 select_next_state.done = true;
10340 self.unfold_ranges(
10341 &new_selections
10342 .iter()
10343 .map(|selection| selection.range())
10344 .collect::<Vec<_>>(),
10345 false,
10346 false,
10347 cx,
10348 );
10349 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10350 selections.select(new_selections)
10351 });
10352
10353 Ok(())
10354 }
10355
10356 pub fn select_next(
10357 &mut self,
10358 action: &SelectNext,
10359 window: &mut Window,
10360 cx: &mut Context<Self>,
10361 ) -> Result<()> {
10362 self.push_to_selection_history();
10363 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10364 self.select_next_match_internal(
10365 &display_map,
10366 action.replace_newest,
10367 Some(Autoscroll::newest()),
10368 window,
10369 cx,
10370 )?;
10371 Ok(())
10372 }
10373
10374 pub fn select_previous(
10375 &mut self,
10376 action: &SelectPrevious,
10377 window: &mut Window,
10378 cx: &mut Context<Self>,
10379 ) -> Result<()> {
10380 self.push_to_selection_history();
10381 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10382 let buffer = &display_map.buffer_snapshot;
10383 let mut selections = self.selections.all::<usize>(cx);
10384 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10385 let query = &select_prev_state.query;
10386 if !select_prev_state.done {
10387 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10388 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10389 let mut next_selected_range = None;
10390 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10391 let bytes_before_last_selection =
10392 buffer.reversed_bytes_in_range(0..last_selection.start);
10393 let bytes_after_first_selection =
10394 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10395 let query_matches = query
10396 .stream_find_iter(bytes_before_last_selection)
10397 .map(|result| (last_selection.start, result))
10398 .chain(
10399 query
10400 .stream_find_iter(bytes_after_first_selection)
10401 .map(|result| (buffer.len(), result)),
10402 );
10403 for (end_offset, query_match) in query_matches {
10404 let query_match = query_match.unwrap(); // can only fail due to I/O
10405 let offset_range =
10406 end_offset - query_match.end()..end_offset - query_match.start();
10407 let display_range = offset_range.start.to_display_point(&display_map)
10408 ..offset_range.end.to_display_point(&display_map);
10409
10410 if !select_prev_state.wordwise
10411 || (!movement::is_inside_word(&display_map, display_range.start)
10412 && !movement::is_inside_word(&display_map, display_range.end))
10413 {
10414 next_selected_range = Some(offset_range);
10415 break;
10416 }
10417 }
10418
10419 if let Some(next_selected_range) = next_selected_range {
10420 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10421 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10422 if action.replace_newest {
10423 s.delete(s.newest_anchor().id);
10424 }
10425 s.insert_range(next_selected_range);
10426 });
10427 } else {
10428 select_prev_state.done = true;
10429 }
10430 }
10431
10432 self.select_prev_state = Some(select_prev_state);
10433 } else {
10434 let mut only_carets = true;
10435 let mut same_text_selected = true;
10436 let mut selected_text = None;
10437
10438 let mut selections_iter = selections.iter().peekable();
10439 while let Some(selection) = selections_iter.next() {
10440 if selection.start != selection.end {
10441 only_carets = false;
10442 }
10443
10444 if same_text_selected {
10445 if selected_text.is_none() {
10446 selected_text =
10447 Some(buffer.text_for_range(selection.range()).collect::<String>());
10448 }
10449
10450 if let Some(next_selection) = selections_iter.peek() {
10451 if next_selection.range().len() == selection.range().len() {
10452 let next_selected_text = buffer
10453 .text_for_range(next_selection.range())
10454 .collect::<String>();
10455 if Some(next_selected_text) != selected_text {
10456 same_text_selected = false;
10457 selected_text = None;
10458 }
10459 } else {
10460 same_text_selected = false;
10461 selected_text = None;
10462 }
10463 }
10464 }
10465 }
10466
10467 if only_carets {
10468 for selection in &mut selections {
10469 let word_range = movement::surrounding_word(
10470 &display_map,
10471 selection.start.to_display_point(&display_map),
10472 );
10473 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10474 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10475 selection.goal = SelectionGoal::None;
10476 selection.reversed = false;
10477 }
10478 if selections.len() == 1 {
10479 let selection = selections
10480 .last()
10481 .expect("ensured that there's only one selection");
10482 let query = buffer
10483 .text_for_range(selection.start..selection.end)
10484 .collect::<String>();
10485 let is_empty = query.is_empty();
10486 let select_state = SelectNextState {
10487 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10488 wordwise: true,
10489 done: is_empty,
10490 };
10491 self.select_prev_state = Some(select_state);
10492 } else {
10493 self.select_prev_state = None;
10494 }
10495
10496 self.unfold_ranges(
10497 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10498 false,
10499 true,
10500 cx,
10501 );
10502 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10503 s.select(selections);
10504 });
10505 } else if let Some(selected_text) = selected_text {
10506 self.select_prev_state = Some(SelectNextState {
10507 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10508 wordwise: false,
10509 done: false,
10510 });
10511 self.select_previous(action, window, cx)?;
10512 }
10513 }
10514 Ok(())
10515 }
10516
10517 pub fn toggle_comments(
10518 &mut self,
10519 action: &ToggleComments,
10520 window: &mut Window,
10521 cx: &mut Context<Self>,
10522 ) {
10523 if self.read_only(cx) {
10524 return;
10525 }
10526 let text_layout_details = &self.text_layout_details(window);
10527 self.transact(window, cx, |this, window, cx| {
10528 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10529 let mut edits = Vec::new();
10530 let mut selection_edit_ranges = Vec::new();
10531 let mut last_toggled_row = None;
10532 let snapshot = this.buffer.read(cx).read(cx);
10533 let empty_str: Arc<str> = Arc::default();
10534 let mut suffixes_inserted = Vec::new();
10535 let ignore_indent = action.ignore_indent;
10536
10537 fn comment_prefix_range(
10538 snapshot: &MultiBufferSnapshot,
10539 row: MultiBufferRow,
10540 comment_prefix: &str,
10541 comment_prefix_whitespace: &str,
10542 ignore_indent: bool,
10543 ) -> Range<Point> {
10544 let indent_size = if ignore_indent {
10545 0
10546 } else {
10547 snapshot.indent_size_for_line(row).len
10548 };
10549
10550 let start = Point::new(row.0, indent_size);
10551
10552 let mut line_bytes = snapshot
10553 .bytes_in_range(start..snapshot.max_point())
10554 .flatten()
10555 .copied();
10556
10557 // If this line currently begins with the line comment prefix, then record
10558 // the range containing the prefix.
10559 if line_bytes
10560 .by_ref()
10561 .take(comment_prefix.len())
10562 .eq(comment_prefix.bytes())
10563 {
10564 // Include any whitespace that matches the comment prefix.
10565 let matching_whitespace_len = line_bytes
10566 .zip(comment_prefix_whitespace.bytes())
10567 .take_while(|(a, b)| a == b)
10568 .count() as u32;
10569 let end = Point::new(
10570 start.row,
10571 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10572 );
10573 start..end
10574 } else {
10575 start..start
10576 }
10577 }
10578
10579 fn comment_suffix_range(
10580 snapshot: &MultiBufferSnapshot,
10581 row: MultiBufferRow,
10582 comment_suffix: &str,
10583 comment_suffix_has_leading_space: bool,
10584 ) -> Range<Point> {
10585 let end = Point::new(row.0, snapshot.line_len(row));
10586 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10587
10588 let mut line_end_bytes = snapshot
10589 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10590 .flatten()
10591 .copied();
10592
10593 let leading_space_len = if suffix_start_column > 0
10594 && line_end_bytes.next() == Some(b' ')
10595 && comment_suffix_has_leading_space
10596 {
10597 1
10598 } else {
10599 0
10600 };
10601
10602 // If this line currently begins with the line comment prefix, then record
10603 // the range containing the prefix.
10604 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10605 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10606 start..end
10607 } else {
10608 end..end
10609 }
10610 }
10611
10612 // TODO: Handle selections that cross excerpts
10613 for selection in &mut selections {
10614 let start_column = snapshot
10615 .indent_size_for_line(MultiBufferRow(selection.start.row))
10616 .len;
10617 let language = if let Some(language) =
10618 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10619 {
10620 language
10621 } else {
10622 continue;
10623 };
10624
10625 selection_edit_ranges.clear();
10626
10627 // If multiple selections contain a given row, avoid processing that
10628 // row more than once.
10629 let mut start_row = MultiBufferRow(selection.start.row);
10630 if last_toggled_row == Some(start_row) {
10631 start_row = start_row.next_row();
10632 }
10633 let end_row =
10634 if selection.end.row > selection.start.row && selection.end.column == 0 {
10635 MultiBufferRow(selection.end.row - 1)
10636 } else {
10637 MultiBufferRow(selection.end.row)
10638 };
10639 last_toggled_row = Some(end_row);
10640
10641 if start_row > end_row {
10642 continue;
10643 }
10644
10645 // If the language has line comments, toggle those.
10646 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10647
10648 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10649 if ignore_indent {
10650 full_comment_prefixes = full_comment_prefixes
10651 .into_iter()
10652 .map(|s| Arc::from(s.trim_end()))
10653 .collect();
10654 }
10655
10656 if !full_comment_prefixes.is_empty() {
10657 let first_prefix = full_comment_prefixes
10658 .first()
10659 .expect("prefixes is non-empty");
10660 let prefix_trimmed_lengths = full_comment_prefixes
10661 .iter()
10662 .map(|p| p.trim_end_matches(' ').len())
10663 .collect::<SmallVec<[usize; 4]>>();
10664
10665 let mut all_selection_lines_are_comments = true;
10666
10667 for row in start_row.0..=end_row.0 {
10668 let row = MultiBufferRow(row);
10669 if start_row < end_row && snapshot.is_line_blank(row) {
10670 continue;
10671 }
10672
10673 let prefix_range = full_comment_prefixes
10674 .iter()
10675 .zip(prefix_trimmed_lengths.iter().copied())
10676 .map(|(prefix, trimmed_prefix_len)| {
10677 comment_prefix_range(
10678 snapshot.deref(),
10679 row,
10680 &prefix[..trimmed_prefix_len],
10681 &prefix[trimmed_prefix_len..],
10682 ignore_indent,
10683 )
10684 })
10685 .max_by_key(|range| range.end.column - range.start.column)
10686 .expect("prefixes is non-empty");
10687
10688 if prefix_range.is_empty() {
10689 all_selection_lines_are_comments = false;
10690 }
10691
10692 selection_edit_ranges.push(prefix_range);
10693 }
10694
10695 if all_selection_lines_are_comments {
10696 edits.extend(
10697 selection_edit_ranges
10698 .iter()
10699 .cloned()
10700 .map(|range| (range, empty_str.clone())),
10701 );
10702 } else {
10703 let min_column = selection_edit_ranges
10704 .iter()
10705 .map(|range| range.start.column)
10706 .min()
10707 .unwrap_or(0);
10708 edits.extend(selection_edit_ranges.iter().map(|range| {
10709 let position = Point::new(range.start.row, min_column);
10710 (position..position, first_prefix.clone())
10711 }));
10712 }
10713 } else if let Some((full_comment_prefix, comment_suffix)) =
10714 language.block_comment_delimiters()
10715 {
10716 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10717 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10718 let prefix_range = comment_prefix_range(
10719 snapshot.deref(),
10720 start_row,
10721 comment_prefix,
10722 comment_prefix_whitespace,
10723 ignore_indent,
10724 );
10725 let suffix_range = comment_suffix_range(
10726 snapshot.deref(),
10727 end_row,
10728 comment_suffix.trim_start_matches(' '),
10729 comment_suffix.starts_with(' '),
10730 );
10731
10732 if prefix_range.is_empty() || suffix_range.is_empty() {
10733 edits.push((
10734 prefix_range.start..prefix_range.start,
10735 full_comment_prefix.clone(),
10736 ));
10737 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10738 suffixes_inserted.push((end_row, comment_suffix.len()));
10739 } else {
10740 edits.push((prefix_range, empty_str.clone()));
10741 edits.push((suffix_range, empty_str.clone()));
10742 }
10743 } else {
10744 continue;
10745 }
10746 }
10747
10748 drop(snapshot);
10749 this.buffer.update(cx, |buffer, cx| {
10750 buffer.edit(edits, None, cx);
10751 });
10752
10753 // Adjust selections so that they end before any comment suffixes that
10754 // were inserted.
10755 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10756 let mut selections = this.selections.all::<Point>(cx);
10757 let snapshot = this.buffer.read(cx).read(cx);
10758 for selection in &mut selections {
10759 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10760 match row.cmp(&MultiBufferRow(selection.end.row)) {
10761 Ordering::Less => {
10762 suffixes_inserted.next();
10763 continue;
10764 }
10765 Ordering::Greater => break,
10766 Ordering::Equal => {
10767 if selection.end.column == snapshot.line_len(row) {
10768 if selection.is_empty() {
10769 selection.start.column -= suffix_len as u32;
10770 }
10771 selection.end.column -= suffix_len as u32;
10772 }
10773 break;
10774 }
10775 }
10776 }
10777 }
10778
10779 drop(snapshot);
10780 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10781 s.select(selections)
10782 });
10783
10784 let selections = this.selections.all::<Point>(cx);
10785 let selections_on_single_row = selections.windows(2).all(|selections| {
10786 selections[0].start.row == selections[1].start.row
10787 && selections[0].end.row == selections[1].end.row
10788 && selections[0].start.row == selections[0].end.row
10789 });
10790 let selections_selecting = selections
10791 .iter()
10792 .any(|selection| selection.start != selection.end);
10793 let advance_downwards = action.advance_downwards
10794 && selections_on_single_row
10795 && !selections_selecting
10796 && !matches!(this.mode, EditorMode::SingleLine { .. });
10797
10798 if advance_downwards {
10799 let snapshot = this.buffer.read(cx).snapshot(cx);
10800
10801 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10802 s.move_cursors_with(|display_snapshot, display_point, _| {
10803 let mut point = display_point.to_point(display_snapshot);
10804 point.row += 1;
10805 point = snapshot.clip_point(point, Bias::Left);
10806 let display_point = point.to_display_point(display_snapshot);
10807 let goal = SelectionGoal::HorizontalPosition(
10808 display_snapshot
10809 .x_for_display_point(display_point, text_layout_details)
10810 .into(),
10811 );
10812 (display_point, goal)
10813 })
10814 });
10815 }
10816 });
10817 }
10818
10819 pub fn select_enclosing_symbol(
10820 &mut self,
10821 _: &SelectEnclosingSymbol,
10822 window: &mut Window,
10823 cx: &mut Context<Self>,
10824 ) {
10825 let buffer = self.buffer.read(cx).snapshot(cx);
10826 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10827
10828 fn update_selection(
10829 selection: &Selection<usize>,
10830 buffer_snap: &MultiBufferSnapshot,
10831 ) -> Option<Selection<usize>> {
10832 let cursor = selection.head();
10833 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10834 for symbol in symbols.iter().rev() {
10835 let start = symbol.range.start.to_offset(buffer_snap);
10836 let end = symbol.range.end.to_offset(buffer_snap);
10837 let new_range = start..end;
10838 if start < selection.start || end > selection.end {
10839 return Some(Selection {
10840 id: selection.id,
10841 start: new_range.start,
10842 end: new_range.end,
10843 goal: SelectionGoal::None,
10844 reversed: selection.reversed,
10845 });
10846 }
10847 }
10848 None
10849 }
10850
10851 let mut selected_larger_symbol = false;
10852 let new_selections = old_selections
10853 .iter()
10854 .map(|selection| match update_selection(selection, &buffer) {
10855 Some(new_selection) => {
10856 if new_selection.range() != selection.range() {
10857 selected_larger_symbol = true;
10858 }
10859 new_selection
10860 }
10861 None => selection.clone(),
10862 })
10863 .collect::<Vec<_>>();
10864
10865 if selected_larger_symbol {
10866 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10867 s.select(new_selections);
10868 });
10869 }
10870 }
10871
10872 pub fn select_larger_syntax_node(
10873 &mut self,
10874 _: &SelectLargerSyntaxNode,
10875 window: &mut Window,
10876 cx: &mut Context<Self>,
10877 ) {
10878 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10879 let buffer = self.buffer.read(cx).snapshot(cx);
10880 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10881
10882 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10883 let mut selected_larger_node = false;
10884 let new_selections = old_selections
10885 .iter()
10886 .map(|selection| {
10887 let old_range = selection.start..selection.end;
10888 let mut new_range = old_range.clone();
10889 let mut new_node = None;
10890 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10891 {
10892 new_node = Some(node);
10893 new_range = match containing_range {
10894 MultiOrSingleBufferOffsetRange::Single(_) => break,
10895 MultiOrSingleBufferOffsetRange::Multi(range) => range,
10896 };
10897 if !display_map.intersects_fold(new_range.start)
10898 && !display_map.intersects_fold(new_range.end)
10899 {
10900 break;
10901 }
10902 }
10903
10904 if let Some(node) = new_node {
10905 // Log the ancestor, to support using this action as a way to explore TreeSitter
10906 // nodes. Parent and grandparent are also logged because this operation will not
10907 // visit nodes that have the same range as their parent.
10908 log::info!("Node: {node:?}");
10909 let parent = node.parent();
10910 log::info!("Parent: {parent:?}");
10911 let grandparent = parent.and_then(|x| x.parent());
10912 log::info!("Grandparent: {grandparent:?}");
10913 }
10914
10915 selected_larger_node |= new_range != old_range;
10916 Selection {
10917 id: selection.id,
10918 start: new_range.start,
10919 end: new_range.end,
10920 goal: SelectionGoal::None,
10921 reversed: selection.reversed,
10922 }
10923 })
10924 .collect::<Vec<_>>();
10925
10926 if selected_larger_node {
10927 stack.push(old_selections);
10928 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10929 s.select(new_selections);
10930 });
10931 }
10932 self.select_larger_syntax_node_stack = stack;
10933 }
10934
10935 pub fn select_smaller_syntax_node(
10936 &mut self,
10937 _: &SelectSmallerSyntaxNode,
10938 window: &mut Window,
10939 cx: &mut Context<Self>,
10940 ) {
10941 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10942 if let Some(selections) = stack.pop() {
10943 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10944 s.select(selections.to_vec());
10945 });
10946 }
10947 self.select_larger_syntax_node_stack = stack;
10948 }
10949
10950 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10951 if !EditorSettings::get_global(cx).gutter.runnables {
10952 self.clear_tasks();
10953 return Task::ready(());
10954 }
10955 let project = self.project.as_ref().map(Entity::downgrade);
10956 cx.spawn_in(window, |this, mut cx| async move {
10957 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10958 let Some(project) = project.and_then(|p| p.upgrade()) else {
10959 return;
10960 };
10961 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10962 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10963 }) else {
10964 return;
10965 };
10966
10967 let hide_runnables = project
10968 .update(&mut cx, |project, cx| {
10969 // Do not display any test indicators in non-dev server remote projects.
10970 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10971 })
10972 .unwrap_or(true);
10973 if hide_runnables {
10974 return;
10975 }
10976 let new_rows =
10977 cx.background_spawn({
10978 let snapshot = display_snapshot.clone();
10979 async move {
10980 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10981 }
10982 })
10983 .await;
10984
10985 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10986 this.update(&mut cx, |this, _| {
10987 this.clear_tasks();
10988 for (key, value) in rows {
10989 this.insert_tasks(key, value);
10990 }
10991 })
10992 .ok();
10993 })
10994 }
10995 fn fetch_runnable_ranges(
10996 snapshot: &DisplaySnapshot,
10997 range: Range<Anchor>,
10998 ) -> Vec<language::RunnableRange> {
10999 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11000 }
11001
11002 fn runnable_rows(
11003 project: Entity<Project>,
11004 snapshot: DisplaySnapshot,
11005 runnable_ranges: Vec<RunnableRange>,
11006 mut cx: AsyncWindowContext,
11007 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11008 runnable_ranges
11009 .into_iter()
11010 .filter_map(|mut runnable| {
11011 let tasks = cx
11012 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11013 .ok()?;
11014 if tasks.is_empty() {
11015 return None;
11016 }
11017
11018 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11019
11020 let row = snapshot
11021 .buffer_snapshot
11022 .buffer_line_for_row(MultiBufferRow(point.row))?
11023 .1
11024 .start
11025 .row;
11026
11027 let context_range =
11028 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11029 Some((
11030 (runnable.buffer_id, row),
11031 RunnableTasks {
11032 templates: tasks,
11033 offset: snapshot
11034 .buffer_snapshot
11035 .anchor_before(runnable.run_range.start),
11036 context_range,
11037 column: point.column,
11038 extra_variables: runnable.extra_captures,
11039 },
11040 ))
11041 })
11042 .collect()
11043 }
11044
11045 fn templates_with_tags(
11046 project: &Entity<Project>,
11047 runnable: &mut Runnable,
11048 cx: &mut App,
11049 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11050 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11051 let (worktree_id, file) = project
11052 .buffer_for_id(runnable.buffer, cx)
11053 .and_then(|buffer| buffer.read(cx).file())
11054 .map(|file| (file.worktree_id(cx), file.clone()))
11055 .unzip();
11056
11057 (
11058 project.task_store().read(cx).task_inventory().cloned(),
11059 worktree_id,
11060 file,
11061 )
11062 });
11063
11064 let tags = mem::take(&mut runnable.tags);
11065 let mut tags: Vec<_> = tags
11066 .into_iter()
11067 .flat_map(|tag| {
11068 let tag = tag.0.clone();
11069 inventory
11070 .as_ref()
11071 .into_iter()
11072 .flat_map(|inventory| {
11073 inventory.read(cx).list_tasks(
11074 file.clone(),
11075 Some(runnable.language.clone()),
11076 worktree_id,
11077 cx,
11078 )
11079 })
11080 .filter(move |(_, template)| {
11081 template.tags.iter().any(|source_tag| source_tag == &tag)
11082 })
11083 })
11084 .sorted_by_key(|(kind, _)| kind.to_owned())
11085 .collect();
11086 if let Some((leading_tag_source, _)) = tags.first() {
11087 // Strongest source wins; if we have worktree tag binding, prefer that to
11088 // global and language bindings;
11089 // if we have a global binding, prefer that to language binding.
11090 let first_mismatch = tags
11091 .iter()
11092 .position(|(tag_source, _)| tag_source != leading_tag_source);
11093 if let Some(index) = first_mismatch {
11094 tags.truncate(index);
11095 }
11096 }
11097
11098 tags
11099 }
11100
11101 pub fn move_to_enclosing_bracket(
11102 &mut self,
11103 _: &MoveToEnclosingBracket,
11104 window: &mut Window,
11105 cx: &mut Context<Self>,
11106 ) {
11107 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11108 s.move_offsets_with(|snapshot, selection| {
11109 let Some(enclosing_bracket_ranges) =
11110 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11111 else {
11112 return;
11113 };
11114
11115 let mut best_length = usize::MAX;
11116 let mut best_inside = false;
11117 let mut best_in_bracket_range = false;
11118 let mut best_destination = None;
11119 for (open, close) in enclosing_bracket_ranges {
11120 let close = close.to_inclusive();
11121 let length = close.end() - open.start;
11122 let inside = selection.start >= open.end && selection.end <= *close.start();
11123 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11124 || close.contains(&selection.head());
11125
11126 // If best is next to a bracket and current isn't, skip
11127 if !in_bracket_range && best_in_bracket_range {
11128 continue;
11129 }
11130
11131 // Prefer smaller lengths unless best is inside and current isn't
11132 if length > best_length && (best_inside || !inside) {
11133 continue;
11134 }
11135
11136 best_length = length;
11137 best_inside = inside;
11138 best_in_bracket_range = in_bracket_range;
11139 best_destination = Some(
11140 if close.contains(&selection.start) && close.contains(&selection.end) {
11141 if inside {
11142 open.end
11143 } else {
11144 open.start
11145 }
11146 } else if inside {
11147 *close.start()
11148 } else {
11149 *close.end()
11150 },
11151 );
11152 }
11153
11154 if let Some(destination) = best_destination {
11155 selection.collapse_to(destination, SelectionGoal::None);
11156 }
11157 })
11158 });
11159 }
11160
11161 pub fn undo_selection(
11162 &mut self,
11163 _: &UndoSelection,
11164 window: &mut Window,
11165 cx: &mut Context<Self>,
11166 ) {
11167 self.end_selection(window, cx);
11168 self.selection_history.mode = SelectionHistoryMode::Undoing;
11169 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11170 self.change_selections(None, window, cx, |s| {
11171 s.select_anchors(entry.selections.to_vec())
11172 });
11173 self.select_next_state = entry.select_next_state;
11174 self.select_prev_state = entry.select_prev_state;
11175 self.add_selections_state = entry.add_selections_state;
11176 self.request_autoscroll(Autoscroll::newest(), cx);
11177 }
11178 self.selection_history.mode = SelectionHistoryMode::Normal;
11179 }
11180
11181 pub fn redo_selection(
11182 &mut self,
11183 _: &RedoSelection,
11184 window: &mut Window,
11185 cx: &mut Context<Self>,
11186 ) {
11187 self.end_selection(window, cx);
11188 self.selection_history.mode = SelectionHistoryMode::Redoing;
11189 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11190 self.change_selections(None, window, cx, |s| {
11191 s.select_anchors(entry.selections.to_vec())
11192 });
11193 self.select_next_state = entry.select_next_state;
11194 self.select_prev_state = entry.select_prev_state;
11195 self.add_selections_state = entry.add_selections_state;
11196 self.request_autoscroll(Autoscroll::newest(), cx);
11197 }
11198 self.selection_history.mode = SelectionHistoryMode::Normal;
11199 }
11200
11201 pub fn expand_excerpts(
11202 &mut self,
11203 action: &ExpandExcerpts,
11204 _: &mut Window,
11205 cx: &mut Context<Self>,
11206 ) {
11207 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11208 }
11209
11210 pub fn expand_excerpts_down(
11211 &mut self,
11212 action: &ExpandExcerptsDown,
11213 _: &mut Window,
11214 cx: &mut Context<Self>,
11215 ) {
11216 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11217 }
11218
11219 pub fn expand_excerpts_up(
11220 &mut self,
11221 action: &ExpandExcerptsUp,
11222 _: &mut Window,
11223 cx: &mut Context<Self>,
11224 ) {
11225 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11226 }
11227
11228 pub fn expand_excerpts_for_direction(
11229 &mut self,
11230 lines: u32,
11231 direction: ExpandExcerptDirection,
11232
11233 cx: &mut Context<Self>,
11234 ) {
11235 let selections = self.selections.disjoint_anchors();
11236
11237 let lines = if lines == 0 {
11238 EditorSettings::get_global(cx).expand_excerpt_lines
11239 } else {
11240 lines
11241 };
11242
11243 self.buffer.update(cx, |buffer, cx| {
11244 let snapshot = buffer.snapshot(cx);
11245 let mut excerpt_ids = selections
11246 .iter()
11247 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11248 .collect::<Vec<_>>();
11249 excerpt_ids.sort();
11250 excerpt_ids.dedup();
11251 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11252 })
11253 }
11254
11255 pub fn expand_excerpt(
11256 &mut self,
11257 excerpt: ExcerptId,
11258 direction: ExpandExcerptDirection,
11259 cx: &mut Context<Self>,
11260 ) {
11261 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11262 self.buffer.update(cx, |buffer, cx| {
11263 buffer.expand_excerpts([excerpt], lines, direction, cx)
11264 })
11265 }
11266
11267 pub fn go_to_singleton_buffer_point(
11268 &mut self,
11269 point: Point,
11270 window: &mut Window,
11271 cx: &mut Context<Self>,
11272 ) {
11273 self.go_to_singleton_buffer_range(point..point, window, cx);
11274 }
11275
11276 pub fn go_to_singleton_buffer_range(
11277 &mut self,
11278 range: Range<Point>,
11279 window: &mut Window,
11280 cx: &mut Context<Self>,
11281 ) {
11282 let multibuffer = self.buffer().read(cx);
11283 let Some(buffer) = multibuffer.as_singleton() else {
11284 return;
11285 };
11286 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11287 return;
11288 };
11289 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11290 return;
11291 };
11292 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11293 s.select_anchor_ranges([start..end])
11294 });
11295 }
11296
11297 fn go_to_diagnostic(
11298 &mut self,
11299 _: &GoToDiagnostic,
11300 window: &mut Window,
11301 cx: &mut Context<Self>,
11302 ) {
11303 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11304 }
11305
11306 fn go_to_prev_diagnostic(
11307 &mut self,
11308 _: &GoToPreviousDiagnostic,
11309 window: &mut Window,
11310 cx: &mut Context<Self>,
11311 ) {
11312 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11313 }
11314
11315 pub fn go_to_diagnostic_impl(
11316 &mut self,
11317 direction: Direction,
11318 window: &mut Window,
11319 cx: &mut Context<Self>,
11320 ) {
11321 let buffer = self.buffer.read(cx).snapshot(cx);
11322 let selection = self.selections.newest::<usize>(cx);
11323
11324 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11325 if direction == Direction::Next {
11326 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11327 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11328 return;
11329 };
11330 self.activate_diagnostics(
11331 buffer_id,
11332 popover.local_diagnostic.diagnostic.group_id,
11333 window,
11334 cx,
11335 );
11336 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11337 let primary_range_start = active_diagnostics.primary_range.start;
11338 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11339 let mut new_selection = s.newest_anchor().clone();
11340 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11341 s.select_anchors(vec![new_selection.clone()]);
11342 });
11343 self.refresh_inline_completion(false, true, window, cx);
11344 }
11345 return;
11346 }
11347 }
11348
11349 let active_group_id = self
11350 .active_diagnostics
11351 .as_ref()
11352 .map(|active_group| active_group.group_id);
11353 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11354 active_diagnostics
11355 .primary_range
11356 .to_offset(&buffer)
11357 .to_inclusive()
11358 });
11359 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11360 if active_primary_range.contains(&selection.head()) {
11361 *active_primary_range.start()
11362 } else {
11363 selection.head()
11364 }
11365 } else {
11366 selection.head()
11367 };
11368
11369 let snapshot = self.snapshot(window, cx);
11370 let primary_diagnostics_before = buffer
11371 .diagnostics_in_range::<usize>(0..search_start)
11372 .filter(|entry| entry.diagnostic.is_primary)
11373 .filter(|entry| entry.range.start != entry.range.end)
11374 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11375 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11376 .collect::<Vec<_>>();
11377 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11378 primary_diagnostics_before
11379 .iter()
11380 .position(|entry| entry.diagnostic.group_id == active_group_id)
11381 });
11382
11383 let primary_diagnostics_after = buffer
11384 .diagnostics_in_range::<usize>(search_start..buffer.len())
11385 .filter(|entry| entry.diagnostic.is_primary)
11386 .filter(|entry| entry.range.start != entry.range.end)
11387 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11388 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11389 .collect::<Vec<_>>();
11390 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11391 primary_diagnostics_after
11392 .iter()
11393 .enumerate()
11394 .rev()
11395 .find_map(|(i, entry)| {
11396 if entry.diagnostic.group_id == active_group_id {
11397 Some(i)
11398 } else {
11399 None
11400 }
11401 })
11402 });
11403
11404 let next_primary_diagnostic = match direction {
11405 Direction::Prev => primary_diagnostics_before
11406 .iter()
11407 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11408 .rev()
11409 .next(),
11410 Direction::Next => primary_diagnostics_after
11411 .iter()
11412 .skip(
11413 last_same_group_diagnostic_after
11414 .map(|index| index + 1)
11415 .unwrap_or(0),
11416 )
11417 .next(),
11418 };
11419
11420 // Cycle around to the start of the buffer, potentially moving back to the start of
11421 // the currently active diagnostic.
11422 let cycle_around = || match direction {
11423 Direction::Prev => primary_diagnostics_after
11424 .iter()
11425 .rev()
11426 .chain(primary_diagnostics_before.iter().rev())
11427 .next(),
11428 Direction::Next => primary_diagnostics_before
11429 .iter()
11430 .chain(primary_diagnostics_after.iter())
11431 .next(),
11432 };
11433
11434 if let Some((primary_range, group_id)) = next_primary_diagnostic
11435 .or_else(cycle_around)
11436 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11437 {
11438 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11439 return;
11440 };
11441 self.activate_diagnostics(buffer_id, group_id, window, cx);
11442 if self.active_diagnostics.is_some() {
11443 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11444 s.select(vec![Selection {
11445 id: selection.id,
11446 start: primary_range.start,
11447 end: primary_range.start,
11448 reversed: false,
11449 goal: SelectionGoal::None,
11450 }]);
11451 });
11452 self.refresh_inline_completion(false, true, window, cx);
11453 }
11454 }
11455 }
11456
11457 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11458 let snapshot = self.snapshot(window, cx);
11459 let selection = self.selections.newest::<Point>(cx);
11460 self.go_to_hunk_before_or_after_position(
11461 &snapshot,
11462 selection.head(),
11463 Direction::Next,
11464 window,
11465 cx,
11466 );
11467 }
11468
11469 fn go_to_hunk_before_or_after_position(
11470 &mut self,
11471 snapshot: &EditorSnapshot,
11472 position: Point,
11473 direction: Direction,
11474 window: &mut Window,
11475 cx: &mut Context<Editor>,
11476 ) {
11477 let row = if direction == Direction::Next {
11478 self.hunk_after_position(snapshot, position)
11479 .map(|hunk| hunk.row_range.start)
11480 } else {
11481 self.hunk_before_position(snapshot, position)
11482 };
11483
11484 if let Some(row) = row {
11485 let destination = Point::new(row.0, 0);
11486 let autoscroll = Autoscroll::center();
11487
11488 self.unfold_ranges(&[destination..destination], false, false, cx);
11489 self.change_selections(Some(autoscroll), window, cx, |s| {
11490 s.select_ranges([destination..destination]);
11491 });
11492 }
11493 }
11494
11495 fn hunk_after_position(
11496 &mut self,
11497 snapshot: &EditorSnapshot,
11498 position: Point,
11499 ) -> Option<MultiBufferDiffHunk> {
11500 snapshot
11501 .buffer_snapshot
11502 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11503 .find(|hunk| hunk.row_range.start.0 > position.row)
11504 .or_else(|| {
11505 snapshot
11506 .buffer_snapshot
11507 .diff_hunks_in_range(Point::zero()..position)
11508 .find(|hunk| hunk.row_range.end.0 < position.row)
11509 })
11510 }
11511
11512 fn go_to_prev_hunk(
11513 &mut self,
11514 _: &GoToPreviousHunk,
11515 window: &mut Window,
11516 cx: &mut Context<Self>,
11517 ) {
11518 let snapshot = self.snapshot(window, cx);
11519 let selection = self.selections.newest::<Point>(cx);
11520 self.go_to_hunk_before_or_after_position(
11521 &snapshot,
11522 selection.head(),
11523 Direction::Prev,
11524 window,
11525 cx,
11526 );
11527 }
11528
11529 fn hunk_before_position(
11530 &mut self,
11531 snapshot: &EditorSnapshot,
11532 position: Point,
11533 ) -> Option<MultiBufferRow> {
11534 snapshot
11535 .buffer_snapshot
11536 .diff_hunk_before(position)
11537 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11538 }
11539
11540 pub fn go_to_definition(
11541 &mut self,
11542 _: &GoToDefinition,
11543 window: &mut Window,
11544 cx: &mut Context<Self>,
11545 ) -> Task<Result<Navigated>> {
11546 let definition =
11547 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11548 cx.spawn_in(window, |editor, mut cx| async move {
11549 if definition.await? == Navigated::Yes {
11550 return Ok(Navigated::Yes);
11551 }
11552 match editor.update_in(&mut cx, |editor, window, cx| {
11553 editor.find_all_references(&FindAllReferences, window, cx)
11554 })? {
11555 Some(references) => references.await,
11556 None => Ok(Navigated::No),
11557 }
11558 })
11559 }
11560
11561 pub fn go_to_declaration(
11562 &mut self,
11563 _: &GoToDeclaration,
11564 window: &mut Window,
11565 cx: &mut Context<Self>,
11566 ) -> Task<Result<Navigated>> {
11567 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11568 }
11569
11570 pub fn go_to_declaration_split(
11571 &mut self,
11572 _: &GoToDeclaration,
11573 window: &mut Window,
11574 cx: &mut Context<Self>,
11575 ) -> Task<Result<Navigated>> {
11576 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11577 }
11578
11579 pub fn go_to_implementation(
11580 &mut self,
11581 _: &GoToImplementation,
11582 window: &mut Window,
11583 cx: &mut Context<Self>,
11584 ) -> Task<Result<Navigated>> {
11585 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11586 }
11587
11588 pub fn go_to_implementation_split(
11589 &mut self,
11590 _: &GoToImplementationSplit,
11591 window: &mut Window,
11592 cx: &mut Context<Self>,
11593 ) -> Task<Result<Navigated>> {
11594 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11595 }
11596
11597 pub fn go_to_type_definition(
11598 &mut self,
11599 _: &GoToTypeDefinition,
11600 window: &mut Window,
11601 cx: &mut Context<Self>,
11602 ) -> Task<Result<Navigated>> {
11603 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11604 }
11605
11606 pub fn go_to_definition_split(
11607 &mut self,
11608 _: &GoToDefinitionSplit,
11609 window: &mut Window,
11610 cx: &mut Context<Self>,
11611 ) -> Task<Result<Navigated>> {
11612 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11613 }
11614
11615 pub fn go_to_type_definition_split(
11616 &mut self,
11617 _: &GoToTypeDefinitionSplit,
11618 window: &mut Window,
11619 cx: &mut Context<Self>,
11620 ) -> Task<Result<Navigated>> {
11621 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11622 }
11623
11624 fn go_to_definition_of_kind(
11625 &mut self,
11626 kind: GotoDefinitionKind,
11627 split: bool,
11628 window: &mut Window,
11629 cx: &mut Context<Self>,
11630 ) -> Task<Result<Navigated>> {
11631 let Some(provider) = self.semantics_provider.clone() else {
11632 return Task::ready(Ok(Navigated::No));
11633 };
11634 let head = self.selections.newest::<usize>(cx).head();
11635 let buffer = self.buffer.read(cx);
11636 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11637 text_anchor
11638 } else {
11639 return Task::ready(Ok(Navigated::No));
11640 };
11641
11642 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11643 return Task::ready(Ok(Navigated::No));
11644 };
11645
11646 cx.spawn_in(window, |editor, mut cx| async move {
11647 let definitions = definitions.await?;
11648 let navigated = editor
11649 .update_in(&mut cx, |editor, window, cx| {
11650 editor.navigate_to_hover_links(
11651 Some(kind),
11652 definitions
11653 .into_iter()
11654 .filter(|location| {
11655 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11656 })
11657 .map(HoverLink::Text)
11658 .collect::<Vec<_>>(),
11659 split,
11660 window,
11661 cx,
11662 )
11663 })?
11664 .await?;
11665 anyhow::Ok(navigated)
11666 })
11667 }
11668
11669 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11670 let selection = self.selections.newest_anchor();
11671 let head = selection.head();
11672 let tail = selection.tail();
11673
11674 let Some((buffer, start_position)) =
11675 self.buffer.read(cx).text_anchor_for_position(head, cx)
11676 else {
11677 return;
11678 };
11679
11680 let end_position = if head != tail {
11681 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11682 return;
11683 };
11684 Some(pos)
11685 } else {
11686 None
11687 };
11688
11689 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11690 let url = if let Some(end_pos) = end_position {
11691 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11692 } else {
11693 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11694 };
11695
11696 if let Some(url) = url {
11697 editor.update(&mut cx, |_, cx| {
11698 cx.open_url(&url);
11699 })
11700 } else {
11701 Ok(())
11702 }
11703 });
11704
11705 url_finder.detach();
11706 }
11707
11708 pub fn open_selected_filename(
11709 &mut self,
11710 _: &OpenSelectedFilename,
11711 window: &mut Window,
11712 cx: &mut Context<Self>,
11713 ) {
11714 let Some(workspace) = self.workspace() else {
11715 return;
11716 };
11717
11718 let position = self.selections.newest_anchor().head();
11719
11720 let Some((buffer, buffer_position)) =
11721 self.buffer.read(cx).text_anchor_for_position(position, cx)
11722 else {
11723 return;
11724 };
11725
11726 let project = self.project.clone();
11727
11728 cx.spawn_in(window, |_, mut cx| async move {
11729 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11730
11731 if let Some((_, path)) = result {
11732 workspace
11733 .update_in(&mut cx, |workspace, window, cx| {
11734 workspace.open_resolved_path(path, window, cx)
11735 })?
11736 .await?;
11737 }
11738 anyhow::Ok(())
11739 })
11740 .detach();
11741 }
11742
11743 pub(crate) fn navigate_to_hover_links(
11744 &mut self,
11745 kind: Option<GotoDefinitionKind>,
11746 mut definitions: Vec<HoverLink>,
11747 split: bool,
11748 window: &mut Window,
11749 cx: &mut Context<Editor>,
11750 ) -> Task<Result<Navigated>> {
11751 // If there is one definition, just open it directly
11752 if definitions.len() == 1 {
11753 let definition = definitions.pop().unwrap();
11754
11755 enum TargetTaskResult {
11756 Location(Option<Location>),
11757 AlreadyNavigated,
11758 }
11759
11760 let target_task = match definition {
11761 HoverLink::Text(link) => {
11762 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11763 }
11764 HoverLink::InlayHint(lsp_location, server_id) => {
11765 let computation =
11766 self.compute_target_location(lsp_location, server_id, window, cx);
11767 cx.background_spawn(async move {
11768 let location = computation.await?;
11769 Ok(TargetTaskResult::Location(location))
11770 })
11771 }
11772 HoverLink::Url(url) => {
11773 cx.open_url(&url);
11774 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11775 }
11776 HoverLink::File(path) => {
11777 if let Some(workspace) = self.workspace() {
11778 cx.spawn_in(window, |_, mut cx| async move {
11779 workspace
11780 .update_in(&mut cx, |workspace, window, cx| {
11781 workspace.open_resolved_path(path, window, cx)
11782 })?
11783 .await
11784 .map(|_| TargetTaskResult::AlreadyNavigated)
11785 })
11786 } else {
11787 Task::ready(Ok(TargetTaskResult::Location(None)))
11788 }
11789 }
11790 };
11791 cx.spawn_in(window, |editor, mut cx| async move {
11792 let target = match target_task.await.context("target resolution task")? {
11793 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11794 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11795 TargetTaskResult::Location(Some(target)) => target,
11796 };
11797
11798 editor.update_in(&mut cx, |editor, window, cx| {
11799 let Some(workspace) = editor.workspace() else {
11800 return Navigated::No;
11801 };
11802 let pane = workspace.read(cx).active_pane().clone();
11803
11804 let range = target.range.to_point(target.buffer.read(cx));
11805 let range = editor.range_for_match(&range);
11806 let range = collapse_multiline_range(range);
11807
11808 if !split
11809 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11810 {
11811 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11812 } else {
11813 window.defer(cx, move |window, cx| {
11814 let target_editor: Entity<Self> =
11815 workspace.update(cx, |workspace, cx| {
11816 let pane = if split {
11817 workspace.adjacent_pane(window, cx)
11818 } else {
11819 workspace.active_pane().clone()
11820 };
11821
11822 workspace.open_project_item(
11823 pane,
11824 target.buffer.clone(),
11825 true,
11826 true,
11827 window,
11828 cx,
11829 )
11830 });
11831 target_editor.update(cx, |target_editor, cx| {
11832 // When selecting a definition in a different buffer, disable the nav history
11833 // to avoid creating a history entry at the previous cursor location.
11834 pane.update(cx, |pane, _| pane.disable_history());
11835 target_editor.go_to_singleton_buffer_range(range, window, cx);
11836 pane.update(cx, |pane, _| pane.enable_history());
11837 });
11838 });
11839 }
11840 Navigated::Yes
11841 })
11842 })
11843 } else if !definitions.is_empty() {
11844 cx.spawn_in(window, |editor, mut cx| async move {
11845 let (title, location_tasks, workspace) = editor
11846 .update_in(&mut cx, |editor, window, cx| {
11847 let tab_kind = match kind {
11848 Some(GotoDefinitionKind::Implementation) => "Implementations",
11849 _ => "Definitions",
11850 };
11851 let title = definitions
11852 .iter()
11853 .find_map(|definition| match definition {
11854 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11855 let buffer = origin.buffer.read(cx);
11856 format!(
11857 "{} for {}",
11858 tab_kind,
11859 buffer
11860 .text_for_range(origin.range.clone())
11861 .collect::<String>()
11862 )
11863 }),
11864 HoverLink::InlayHint(_, _) => None,
11865 HoverLink::Url(_) => None,
11866 HoverLink::File(_) => None,
11867 })
11868 .unwrap_or(tab_kind.to_string());
11869 let location_tasks = definitions
11870 .into_iter()
11871 .map(|definition| match definition {
11872 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11873 HoverLink::InlayHint(lsp_location, server_id) => editor
11874 .compute_target_location(lsp_location, server_id, window, cx),
11875 HoverLink::Url(_) => Task::ready(Ok(None)),
11876 HoverLink::File(_) => Task::ready(Ok(None)),
11877 })
11878 .collect::<Vec<_>>();
11879 (title, location_tasks, editor.workspace().clone())
11880 })
11881 .context("location tasks preparation")?;
11882
11883 let locations = future::join_all(location_tasks)
11884 .await
11885 .into_iter()
11886 .filter_map(|location| location.transpose())
11887 .collect::<Result<_>>()
11888 .context("location tasks")?;
11889
11890 let Some(workspace) = workspace else {
11891 return Ok(Navigated::No);
11892 };
11893 let opened = workspace
11894 .update_in(&mut cx, |workspace, window, cx| {
11895 Self::open_locations_in_multibuffer(
11896 workspace,
11897 locations,
11898 title,
11899 split,
11900 MultibufferSelectionMode::First,
11901 window,
11902 cx,
11903 )
11904 })
11905 .ok();
11906
11907 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11908 })
11909 } else {
11910 Task::ready(Ok(Navigated::No))
11911 }
11912 }
11913
11914 fn compute_target_location(
11915 &self,
11916 lsp_location: lsp::Location,
11917 server_id: LanguageServerId,
11918 window: &mut Window,
11919 cx: &mut Context<Self>,
11920 ) -> Task<anyhow::Result<Option<Location>>> {
11921 let Some(project) = self.project.clone() else {
11922 return Task::ready(Ok(None));
11923 };
11924
11925 cx.spawn_in(window, move |editor, mut cx| async move {
11926 let location_task = editor.update(&mut cx, |_, cx| {
11927 project.update(cx, |project, cx| {
11928 let language_server_name = project
11929 .language_server_statuses(cx)
11930 .find(|(id, _)| server_id == *id)
11931 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11932 language_server_name.map(|language_server_name| {
11933 project.open_local_buffer_via_lsp(
11934 lsp_location.uri.clone(),
11935 server_id,
11936 language_server_name,
11937 cx,
11938 )
11939 })
11940 })
11941 })?;
11942 let location = match location_task {
11943 Some(task) => Some({
11944 let target_buffer_handle = task.await.context("open local buffer")?;
11945 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11946 let target_start = target_buffer
11947 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11948 let target_end = target_buffer
11949 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11950 target_buffer.anchor_after(target_start)
11951 ..target_buffer.anchor_before(target_end)
11952 })?;
11953 Location {
11954 buffer: target_buffer_handle,
11955 range,
11956 }
11957 }),
11958 None => None,
11959 };
11960 Ok(location)
11961 })
11962 }
11963
11964 pub fn find_all_references(
11965 &mut self,
11966 _: &FindAllReferences,
11967 window: &mut Window,
11968 cx: &mut Context<Self>,
11969 ) -> Option<Task<Result<Navigated>>> {
11970 let selection = self.selections.newest::<usize>(cx);
11971 let multi_buffer = self.buffer.read(cx);
11972 let head = selection.head();
11973
11974 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11975 let head_anchor = multi_buffer_snapshot.anchor_at(
11976 head,
11977 if head < selection.tail() {
11978 Bias::Right
11979 } else {
11980 Bias::Left
11981 },
11982 );
11983
11984 match self
11985 .find_all_references_task_sources
11986 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11987 {
11988 Ok(_) => {
11989 log::info!(
11990 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11991 );
11992 return None;
11993 }
11994 Err(i) => {
11995 self.find_all_references_task_sources.insert(i, head_anchor);
11996 }
11997 }
11998
11999 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12000 let workspace = self.workspace()?;
12001 let project = workspace.read(cx).project().clone();
12002 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12003 Some(cx.spawn_in(window, |editor, mut cx| async move {
12004 let _cleanup = defer({
12005 let mut cx = cx.clone();
12006 move || {
12007 let _ = editor.update(&mut cx, |editor, _| {
12008 if let Ok(i) =
12009 editor
12010 .find_all_references_task_sources
12011 .binary_search_by(|anchor| {
12012 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12013 })
12014 {
12015 editor.find_all_references_task_sources.remove(i);
12016 }
12017 });
12018 }
12019 });
12020
12021 let locations = references.await?;
12022 if locations.is_empty() {
12023 return anyhow::Ok(Navigated::No);
12024 }
12025
12026 workspace.update_in(&mut cx, |workspace, window, cx| {
12027 let title = locations
12028 .first()
12029 .as_ref()
12030 .map(|location| {
12031 let buffer = location.buffer.read(cx);
12032 format!(
12033 "References to `{}`",
12034 buffer
12035 .text_for_range(location.range.clone())
12036 .collect::<String>()
12037 )
12038 })
12039 .unwrap();
12040 Self::open_locations_in_multibuffer(
12041 workspace,
12042 locations,
12043 title,
12044 false,
12045 MultibufferSelectionMode::First,
12046 window,
12047 cx,
12048 );
12049 Navigated::Yes
12050 })
12051 }))
12052 }
12053
12054 /// Opens a multibuffer with the given project locations in it
12055 pub fn open_locations_in_multibuffer(
12056 workspace: &mut Workspace,
12057 mut locations: Vec<Location>,
12058 title: String,
12059 split: bool,
12060 multibuffer_selection_mode: MultibufferSelectionMode,
12061 window: &mut Window,
12062 cx: &mut Context<Workspace>,
12063 ) {
12064 // If there are multiple definitions, open them in a multibuffer
12065 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12066 let mut locations = locations.into_iter().peekable();
12067 let mut ranges = Vec::new();
12068 let capability = workspace.project().read(cx).capability();
12069
12070 let excerpt_buffer = cx.new(|cx| {
12071 let mut multibuffer = MultiBuffer::new(capability);
12072 while let Some(location) = locations.next() {
12073 let buffer = location.buffer.read(cx);
12074 let mut ranges_for_buffer = Vec::new();
12075 let range = location.range.to_offset(buffer);
12076 ranges_for_buffer.push(range.clone());
12077
12078 while let Some(next_location) = locations.peek() {
12079 if next_location.buffer == location.buffer {
12080 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12081 locations.next();
12082 } else {
12083 break;
12084 }
12085 }
12086
12087 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12088 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12089 location.buffer.clone(),
12090 ranges_for_buffer,
12091 DEFAULT_MULTIBUFFER_CONTEXT,
12092 cx,
12093 ))
12094 }
12095
12096 multibuffer.with_title(title)
12097 });
12098
12099 let editor = cx.new(|cx| {
12100 Editor::for_multibuffer(
12101 excerpt_buffer,
12102 Some(workspace.project().clone()),
12103 true,
12104 window,
12105 cx,
12106 )
12107 });
12108 editor.update(cx, |editor, cx| {
12109 match multibuffer_selection_mode {
12110 MultibufferSelectionMode::First => {
12111 if let Some(first_range) = ranges.first() {
12112 editor.change_selections(None, window, cx, |selections| {
12113 selections.clear_disjoint();
12114 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12115 });
12116 }
12117 editor.highlight_background::<Self>(
12118 &ranges,
12119 |theme| theme.editor_highlighted_line_background,
12120 cx,
12121 );
12122 }
12123 MultibufferSelectionMode::All => {
12124 editor.change_selections(None, window, cx, |selections| {
12125 selections.clear_disjoint();
12126 selections.select_anchor_ranges(ranges);
12127 });
12128 }
12129 }
12130 editor.register_buffers_with_language_servers(cx);
12131 });
12132
12133 let item = Box::new(editor);
12134 let item_id = item.item_id();
12135
12136 if split {
12137 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12138 } else {
12139 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12140 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12141 pane.close_current_preview_item(window, cx)
12142 } else {
12143 None
12144 }
12145 });
12146 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12147 }
12148 workspace.active_pane().update(cx, |pane, cx| {
12149 pane.set_preview_item_id(Some(item_id), cx);
12150 });
12151 }
12152
12153 pub fn rename(
12154 &mut self,
12155 _: &Rename,
12156 window: &mut Window,
12157 cx: &mut Context<Self>,
12158 ) -> Option<Task<Result<()>>> {
12159 use language::ToOffset as _;
12160
12161 let provider = self.semantics_provider.clone()?;
12162 let selection = self.selections.newest_anchor().clone();
12163 let (cursor_buffer, cursor_buffer_position) = self
12164 .buffer
12165 .read(cx)
12166 .text_anchor_for_position(selection.head(), cx)?;
12167 let (tail_buffer, cursor_buffer_position_end) = self
12168 .buffer
12169 .read(cx)
12170 .text_anchor_for_position(selection.tail(), cx)?;
12171 if tail_buffer != cursor_buffer {
12172 return None;
12173 }
12174
12175 let snapshot = cursor_buffer.read(cx).snapshot();
12176 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12177 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12178 let prepare_rename = provider
12179 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12180 .unwrap_or_else(|| Task::ready(Ok(None)));
12181 drop(snapshot);
12182
12183 Some(cx.spawn_in(window, |this, mut cx| async move {
12184 let rename_range = if let Some(range) = prepare_rename.await? {
12185 Some(range)
12186 } else {
12187 this.update(&mut cx, |this, cx| {
12188 let buffer = this.buffer.read(cx).snapshot(cx);
12189 let mut buffer_highlights = this
12190 .document_highlights_for_position(selection.head(), &buffer)
12191 .filter(|highlight| {
12192 highlight.start.excerpt_id == selection.head().excerpt_id
12193 && highlight.end.excerpt_id == selection.head().excerpt_id
12194 });
12195 buffer_highlights
12196 .next()
12197 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12198 })?
12199 };
12200 if let Some(rename_range) = rename_range {
12201 this.update_in(&mut cx, |this, window, cx| {
12202 let snapshot = cursor_buffer.read(cx).snapshot();
12203 let rename_buffer_range = rename_range.to_offset(&snapshot);
12204 let cursor_offset_in_rename_range =
12205 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12206 let cursor_offset_in_rename_range_end =
12207 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12208
12209 this.take_rename(false, window, cx);
12210 let buffer = this.buffer.read(cx).read(cx);
12211 let cursor_offset = selection.head().to_offset(&buffer);
12212 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12213 let rename_end = rename_start + rename_buffer_range.len();
12214 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12215 let mut old_highlight_id = None;
12216 let old_name: Arc<str> = buffer
12217 .chunks(rename_start..rename_end, true)
12218 .map(|chunk| {
12219 if old_highlight_id.is_none() {
12220 old_highlight_id = chunk.syntax_highlight_id;
12221 }
12222 chunk.text
12223 })
12224 .collect::<String>()
12225 .into();
12226
12227 drop(buffer);
12228
12229 // Position the selection in the rename editor so that it matches the current selection.
12230 this.show_local_selections = false;
12231 let rename_editor = cx.new(|cx| {
12232 let mut editor = Editor::single_line(window, cx);
12233 editor.buffer.update(cx, |buffer, cx| {
12234 buffer.edit([(0..0, old_name.clone())], None, cx)
12235 });
12236 let rename_selection_range = match cursor_offset_in_rename_range
12237 .cmp(&cursor_offset_in_rename_range_end)
12238 {
12239 Ordering::Equal => {
12240 editor.select_all(&SelectAll, window, cx);
12241 return editor;
12242 }
12243 Ordering::Less => {
12244 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12245 }
12246 Ordering::Greater => {
12247 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12248 }
12249 };
12250 if rename_selection_range.end > old_name.len() {
12251 editor.select_all(&SelectAll, window, cx);
12252 } else {
12253 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12254 s.select_ranges([rename_selection_range]);
12255 });
12256 }
12257 editor
12258 });
12259 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12260 if e == &EditorEvent::Focused {
12261 cx.emit(EditorEvent::FocusedIn)
12262 }
12263 })
12264 .detach();
12265
12266 let write_highlights =
12267 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12268 let read_highlights =
12269 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12270 let ranges = write_highlights
12271 .iter()
12272 .flat_map(|(_, ranges)| ranges.iter())
12273 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12274 .cloned()
12275 .collect();
12276
12277 this.highlight_text::<Rename>(
12278 ranges,
12279 HighlightStyle {
12280 fade_out: Some(0.6),
12281 ..Default::default()
12282 },
12283 cx,
12284 );
12285 let rename_focus_handle = rename_editor.focus_handle(cx);
12286 window.focus(&rename_focus_handle);
12287 let block_id = this.insert_blocks(
12288 [BlockProperties {
12289 style: BlockStyle::Flex,
12290 placement: BlockPlacement::Below(range.start),
12291 height: 1,
12292 render: Arc::new({
12293 let rename_editor = rename_editor.clone();
12294 move |cx: &mut BlockContext| {
12295 let mut text_style = cx.editor_style.text.clone();
12296 if let Some(highlight_style) = old_highlight_id
12297 .and_then(|h| h.style(&cx.editor_style.syntax))
12298 {
12299 text_style = text_style.highlight(highlight_style);
12300 }
12301 div()
12302 .block_mouse_down()
12303 .pl(cx.anchor_x)
12304 .child(EditorElement::new(
12305 &rename_editor,
12306 EditorStyle {
12307 background: cx.theme().system().transparent,
12308 local_player: cx.editor_style.local_player,
12309 text: text_style,
12310 scrollbar_width: cx.editor_style.scrollbar_width,
12311 syntax: cx.editor_style.syntax.clone(),
12312 status: cx.editor_style.status.clone(),
12313 inlay_hints_style: HighlightStyle {
12314 font_weight: Some(FontWeight::BOLD),
12315 ..make_inlay_hints_style(cx.app)
12316 },
12317 inline_completion_styles: make_suggestion_styles(
12318 cx.app,
12319 ),
12320 ..EditorStyle::default()
12321 },
12322 ))
12323 .into_any_element()
12324 }
12325 }),
12326 priority: 0,
12327 }],
12328 Some(Autoscroll::fit()),
12329 cx,
12330 )[0];
12331 this.pending_rename = Some(RenameState {
12332 range,
12333 old_name,
12334 editor: rename_editor,
12335 block_id,
12336 });
12337 })?;
12338 }
12339
12340 Ok(())
12341 }))
12342 }
12343
12344 pub fn confirm_rename(
12345 &mut self,
12346 _: &ConfirmRename,
12347 window: &mut Window,
12348 cx: &mut Context<Self>,
12349 ) -> Option<Task<Result<()>>> {
12350 let rename = self.take_rename(false, window, cx)?;
12351 let workspace = self.workspace()?.downgrade();
12352 let (buffer, start) = self
12353 .buffer
12354 .read(cx)
12355 .text_anchor_for_position(rename.range.start, cx)?;
12356 let (end_buffer, _) = self
12357 .buffer
12358 .read(cx)
12359 .text_anchor_for_position(rename.range.end, cx)?;
12360 if buffer != end_buffer {
12361 return None;
12362 }
12363
12364 let old_name = rename.old_name;
12365 let new_name = rename.editor.read(cx).text(cx);
12366
12367 let rename = self.semantics_provider.as_ref()?.perform_rename(
12368 &buffer,
12369 start,
12370 new_name.clone(),
12371 cx,
12372 )?;
12373
12374 Some(cx.spawn_in(window, |editor, mut cx| async move {
12375 let project_transaction = rename.await?;
12376 Self::open_project_transaction(
12377 &editor,
12378 workspace,
12379 project_transaction,
12380 format!("Rename: {} → {}", old_name, new_name),
12381 cx.clone(),
12382 )
12383 .await?;
12384
12385 editor.update(&mut cx, |editor, cx| {
12386 editor.refresh_document_highlights(cx);
12387 })?;
12388 Ok(())
12389 }))
12390 }
12391
12392 fn take_rename(
12393 &mut self,
12394 moving_cursor: bool,
12395 window: &mut Window,
12396 cx: &mut Context<Self>,
12397 ) -> Option<RenameState> {
12398 let rename = self.pending_rename.take()?;
12399 if rename.editor.focus_handle(cx).is_focused(window) {
12400 window.focus(&self.focus_handle);
12401 }
12402
12403 self.remove_blocks(
12404 [rename.block_id].into_iter().collect(),
12405 Some(Autoscroll::fit()),
12406 cx,
12407 );
12408 self.clear_highlights::<Rename>(cx);
12409 self.show_local_selections = true;
12410
12411 if moving_cursor {
12412 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12413 editor.selections.newest::<usize>(cx).head()
12414 });
12415
12416 // Update the selection to match the position of the selection inside
12417 // the rename editor.
12418 let snapshot = self.buffer.read(cx).read(cx);
12419 let rename_range = rename.range.to_offset(&snapshot);
12420 let cursor_in_editor = snapshot
12421 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12422 .min(rename_range.end);
12423 drop(snapshot);
12424
12425 self.change_selections(None, window, cx, |s| {
12426 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12427 });
12428 } else {
12429 self.refresh_document_highlights(cx);
12430 }
12431
12432 Some(rename)
12433 }
12434
12435 pub fn pending_rename(&self) -> Option<&RenameState> {
12436 self.pending_rename.as_ref()
12437 }
12438
12439 fn format(
12440 &mut self,
12441 _: &Format,
12442 window: &mut Window,
12443 cx: &mut Context<Self>,
12444 ) -> Option<Task<Result<()>>> {
12445 let project = match &self.project {
12446 Some(project) => project.clone(),
12447 None => return None,
12448 };
12449
12450 Some(self.perform_format(
12451 project,
12452 FormatTrigger::Manual,
12453 FormatTarget::Buffers,
12454 window,
12455 cx,
12456 ))
12457 }
12458
12459 fn format_selections(
12460 &mut self,
12461 _: &FormatSelections,
12462 window: &mut Window,
12463 cx: &mut Context<Self>,
12464 ) -> Option<Task<Result<()>>> {
12465 let project = match &self.project {
12466 Some(project) => project.clone(),
12467 None => return None,
12468 };
12469
12470 let ranges = self
12471 .selections
12472 .all_adjusted(cx)
12473 .into_iter()
12474 .map(|selection| selection.range())
12475 .collect_vec();
12476
12477 Some(self.perform_format(
12478 project,
12479 FormatTrigger::Manual,
12480 FormatTarget::Ranges(ranges),
12481 window,
12482 cx,
12483 ))
12484 }
12485
12486 fn perform_format(
12487 &mut self,
12488 project: Entity<Project>,
12489 trigger: FormatTrigger,
12490 target: FormatTarget,
12491 window: &mut Window,
12492 cx: &mut Context<Self>,
12493 ) -> Task<Result<()>> {
12494 let buffer = self.buffer.clone();
12495 let (buffers, target) = match target {
12496 FormatTarget::Buffers => {
12497 let mut buffers = buffer.read(cx).all_buffers();
12498 if trigger == FormatTrigger::Save {
12499 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12500 }
12501 (buffers, LspFormatTarget::Buffers)
12502 }
12503 FormatTarget::Ranges(selection_ranges) => {
12504 let multi_buffer = buffer.read(cx);
12505 let snapshot = multi_buffer.read(cx);
12506 let mut buffers = HashSet::default();
12507 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12508 BTreeMap::new();
12509 for selection_range in selection_ranges {
12510 for (buffer, buffer_range, _) in
12511 snapshot.range_to_buffer_ranges(selection_range)
12512 {
12513 let buffer_id = buffer.remote_id();
12514 let start = buffer.anchor_before(buffer_range.start);
12515 let end = buffer.anchor_after(buffer_range.end);
12516 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12517 buffer_id_to_ranges
12518 .entry(buffer_id)
12519 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12520 .or_insert_with(|| vec![start..end]);
12521 }
12522 }
12523 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12524 }
12525 };
12526
12527 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12528 let format = project.update(cx, |project, cx| {
12529 project.format(buffers, target, true, trigger, cx)
12530 });
12531
12532 cx.spawn_in(window, |_, mut cx| async move {
12533 let transaction = futures::select_biased! {
12534 () = timeout => {
12535 log::warn!("timed out waiting for formatting");
12536 None
12537 }
12538 transaction = format.log_err().fuse() => transaction,
12539 };
12540
12541 buffer
12542 .update(&mut cx, |buffer, cx| {
12543 if let Some(transaction) = transaction {
12544 if !buffer.is_singleton() {
12545 buffer.push_transaction(&transaction.0, cx);
12546 }
12547 }
12548 cx.notify();
12549 })
12550 .ok();
12551
12552 Ok(())
12553 })
12554 }
12555
12556 fn organize_imports(
12557 &mut self,
12558 _: &OrganizeImports,
12559 window: &mut Window,
12560 cx: &mut Context<Self>,
12561 ) -> Option<Task<Result<()>>> {
12562 let project = match &self.project {
12563 Some(project) => project.clone(),
12564 None => return None,
12565 };
12566 Some(self.perform_code_action_kind(
12567 project,
12568 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12569 window,
12570 cx,
12571 ))
12572 }
12573
12574 fn perform_code_action_kind(
12575 &mut self,
12576 project: Entity<Project>,
12577 kind: CodeActionKind,
12578 window: &mut Window,
12579 cx: &mut Context<Self>,
12580 ) -> Task<Result<()>> {
12581 let buffer = self.buffer.clone();
12582 let buffers = buffer.read(cx).all_buffers();
12583 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12584 let apply_action = project.update(cx, |project, cx| {
12585 project.apply_code_action_kind(buffers, kind, true, cx)
12586 });
12587 cx.spawn_in(window, |_, mut cx| async move {
12588 let transaction = futures::select_biased! {
12589 () = timeout => {
12590 log::warn!("timed out waiting for executing code action");
12591 None
12592 }
12593 transaction = apply_action.log_err().fuse() => transaction,
12594 };
12595 buffer
12596 .update(&mut cx, |buffer, cx| {
12597 // check if we need this
12598 if let Some(transaction) = transaction {
12599 if !buffer.is_singleton() {
12600 buffer.push_transaction(&transaction.0, cx);
12601 }
12602 }
12603 cx.notify();
12604 })
12605 .ok();
12606 Ok(())
12607 })
12608 }
12609
12610 fn restart_language_server(
12611 &mut self,
12612 _: &RestartLanguageServer,
12613 _: &mut Window,
12614 cx: &mut Context<Self>,
12615 ) {
12616 if let Some(project) = self.project.clone() {
12617 self.buffer.update(cx, |multi_buffer, cx| {
12618 project.update(cx, |project, cx| {
12619 project.restart_language_servers_for_buffers(
12620 multi_buffer.all_buffers().into_iter().collect(),
12621 cx,
12622 );
12623 });
12624 })
12625 }
12626 }
12627
12628 fn cancel_language_server_work(
12629 workspace: &mut Workspace,
12630 _: &actions::CancelLanguageServerWork,
12631 _: &mut Window,
12632 cx: &mut Context<Workspace>,
12633 ) {
12634 let project = workspace.project();
12635 let buffers = workspace
12636 .active_item(cx)
12637 .and_then(|item| item.act_as::<Editor>(cx))
12638 .map_or(HashSet::default(), |editor| {
12639 editor.read(cx).buffer.read(cx).all_buffers()
12640 });
12641 project.update(cx, |project, cx| {
12642 project.cancel_language_server_work_for_buffers(buffers, cx);
12643 });
12644 }
12645
12646 fn show_character_palette(
12647 &mut self,
12648 _: &ShowCharacterPalette,
12649 window: &mut Window,
12650 _: &mut Context<Self>,
12651 ) {
12652 window.show_character_palette();
12653 }
12654
12655 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12656 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12657 let buffer = self.buffer.read(cx).snapshot(cx);
12658 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12659 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12660 let is_valid = buffer
12661 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12662 .any(|entry| {
12663 entry.diagnostic.is_primary
12664 && !entry.range.is_empty()
12665 && entry.range.start == primary_range_start
12666 && entry.diagnostic.message == active_diagnostics.primary_message
12667 });
12668
12669 if is_valid != active_diagnostics.is_valid {
12670 active_diagnostics.is_valid = is_valid;
12671 if is_valid {
12672 let mut new_styles = HashMap::default();
12673 for (block_id, diagnostic) in &active_diagnostics.blocks {
12674 new_styles.insert(
12675 *block_id,
12676 diagnostic_block_renderer(diagnostic.clone(), None, true),
12677 );
12678 }
12679 self.display_map.update(cx, |display_map, _cx| {
12680 display_map.replace_blocks(new_styles);
12681 });
12682 } else {
12683 self.dismiss_diagnostics(cx);
12684 }
12685 }
12686 }
12687 }
12688
12689 fn activate_diagnostics(
12690 &mut self,
12691 buffer_id: BufferId,
12692 group_id: usize,
12693 window: &mut Window,
12694 cx: &mut Context<Self>,
12695 ) {
12696 self.dismiss_diagnostics(cx);
12697 let snapshot = self.snapshot(window, cx);
12698 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12699 let buffer = self.buffer.read(cx).snapshot(cx);
12700
12701 let mut primary_range = None;
12702 let mut primary_message = None;
12703 let diagnostic_group = buffer
12704 .diagnostic_group(buffer_id, group_id)
12705 .filter_map(|entry| {
12706 let start = entry.range.start;
12707 let end = entry.range.end;
12708 if snapshot.is_line_folded(MultiBufferRow(start.row))
12709 && (start.row == end.row
12710 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12711 {
12712 return None;
12713 }
12714 if entry.diagnostic.is_primary {
12715 primary_range = Some(entry.range.clone());
12716 primary_message = Some(entry.diagnostic.message.clone());
12717 }
12718 Some(entry)
12719 })
12720 .collect::<Vec<_>>();
12721 let primary_range = primary_range?;
12722 let primary_message = primary_message?;
12723
12724 let blocks = display_map
12725 .insert_blocks(
12726 diagnostic_group.iter().map(|entry| {
12727 let diagnostic = entry.diagnostic.clone();
12728 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12729 BlockProperties {
12730 style: BlockStyle::Fixed,
12731 placement: BlockPlacement::Below(
12732 buffer.anchor_after(entry.range.start),
12733 ),
12734 height: message_height,
12735 render: diagnostic_block_renderer(diagnostic, None, true),
12736 priority: 0,
12737 }
12738 }),
12739 cx,
12740 )
12741 .into_iter()
12742 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12743 .collect();
12744
12745 Some(ActiveDiagnosticGroup {
12746 primary_range: buffer.anchor_before(primary_range.start)
12747 ..buffer.anchor_after(primary_range.end),
12748 primary_message,
12749 group_id,
12750 blocks,
12751 is_valid: true,
12752 })
12753 });
12754 }
12755
12756 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12757 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12758 self.display_map.update(cx, |display_map, cx| {
12759 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12760 });
12761 cx.notify();
12762 }
12763 }
12764
12765 /// Disable inline diagnostics rendering for this editor.
12766 pub fn disable_inline_diagnostics(&mut self) {
12767 self.inline_diagnostics_enabled = false;
12768 self.inline_diagnostics_update = Task::ready(());
12769 self.inline_diagnostics.clear();
12770 }
12771
12772 pub fn inline_diagnostics_enabled(&self) -> bool {
12773 self.inline_diagnostics_enabled
12774 }
12775
12776 pub fn show_inline_diagnostics(&self) -> bool {
12777 self.show_inline_diagnostics
12778 }
12779
12780 pub fn toggle_inline_diagnostics(
12781 &mut self,
12782 _: &ToggleInlineDiagnostics,
12783 window: &mut Window,
12784 cx: &mut Context<'_, Editor>,
12785 ) {
12786 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12787 self.refresh_inline_diagnostics(false, window, cx);
12788 }
12789
12790 fn refresh_inline_diagnostics(
12791 &mut self,
12792 debounce: bool,
12793 window: &mut Window,
12794 cx: &mut Context<Self>,
12795 ) {
12796 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12797 self.inline_diagnostics_update = Task::ready(());
12798 self.inline_diagnostics.clear();
12799 return;
12800 }
12801
12802 let debounce_ms = ProjectSettings::get_global(cx)
12803 .diagnostics
12804 .inline
12805 .update_debounce_ms;
12806 let debounce = if debounce && debounce_ms > 0 {
12807 Some(Duration::from_millis(debounce_ms))
12808 } else {
12809 None
12810 };
12811 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12812 if let Some(debounce) = debounce {
12813 cx.background_executor().timer(debounce).await;
12814 }
12815 let Some(snapshot) = editor
12816 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12817 .ok()
12818 else {
12819 return;
12820 };
12821
12822 let new_inline_diagnostics = cx
12823 .background_spawn(async move {
12824 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12825 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12826 let message = diagnostic_entry
12827 .diagnostic
12828 .message
12829 .split_once('\n')
12830 .map(|(line, _)| line)
12831 .map(SharedString::new)
12832 .unwrap_or_else(|| {
12833 SharedString::from(diagnostic_entry.diagnostic.message)
12834 });
12835 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12836 let (Ok(i) | Err(i)) = inline_diagnostics
12837 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12838 inline_diagnostics.insert(
12839 i,
12840 (
12841 start_anchor,
12842 InlineDiagnostic {
12843 message,
12844 group_id: diagnostic_entry.diagnostic.group_id,
12845 start: diagnostic_entry.range.start.to_point(&snapshot),
12846 is_primary: diagnostic_entry.diagnostic.is_primary,
12847 severity: diagnostic_entry.diagnostic.severity,
12848 },
12849 ),
12850 );
12851 }
12852 inline_diagnostics
12853 })
12854 .await;
12855
12856 editor
12857 .update(&mut cx, |editor, cx| {
12858 editor.inline_diagnostics = new_inline_diagnostics;
12859 cx.notify();
12860 })
12861 .ok();
12862 });
12863 }
12864
12865 pub fn set_selections_from_remote(
12866 &mut self,
12867 selections: Vec<Selection<Anchor>>,
12868 pending_selection: Option<Selection<Anchor>>,
12869 window: &mut Window,
12870 cx: &mut Context<Self>,
12871 ) {
12872 let old_cursor_position = self.selections.newest_anchor().head();
12873 self.selections.change_with(cx, |s| {
12874 s.select_anchors(selections);
12875 if let Some(pending_selection) = pending_selection {
12876 s.set_pending(pending_selection, SelectMode::Character);
12877 } else {
12878 s.clear_pending();
12879 }
12880 });
12881 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12882 }
12883
12884 fn push_to_selection_history(&mut self) {
12885 self.selection_history.push(SelectionHistoryEntry {
12886 selections: self.selections.disjoint_anchors(),
12887 select_next_state: self.select_next_state.clone(),
12888 select_prev_state: self.select_prev_state.clone(),
12889 add_selections_state: self.add_selections_state.clone(),
12890 });
12891 }
12892
12893 pub fn transact(
12894 &mut self,
12895 window: &mut Window,
12896 cx: &mut Context<Self>,
12897 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12898 ) -> Option<TransactionId> {
12899 self.start_transaction_at(Instant::now(), window, cx);
12900 update(self, window, cx);
12901 self.end_transaction_at(Instant::now(), cx)
12902 }
12903
12904 pub fn start_transaction_at(
12905 &mut self,
12906 now: Instant,
12907 window: &mut Window,
12908 cx: &mut Context<Self>,
12909 ) {
12910 self.end_selection(window, cx);
12911 if let Some(tx_id) = self
12912 .buffer
12913 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12914 {
12915 self.selection_history
12916 .insert_transaction(tx_id, self.selections.disjoint_anchors());
12917 cx.emit(EditorEvent::TransactionBegun {
12918 transaction_id: tx_id,
12919 })
12920 }
12921 }
12922
12923 pub fn end_transaction_at(
12924 &mut self,
12925 now: Instant,
12926 cx: &mut Context<Self>,
12927 ) -> Option<TransactionId> {
12928 if let Some(transaction_id) = self
12929 .buffer
12930 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12931 {
12932 if let Some((_, end_selections)) =
12933 self.selection_history.transaction_mut(transaction_id)
12934 {
12935 *end_selections = Some(self.selections.disjoint_anchors());
12936 } else {
12937 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12938 }
12939
12940 cx.emit(EditorEvent::Edited { transaction_id });
12941 Some(transaction_id)
12942 } else {
12943 None
12944 }
12945 }
12946
12947 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12948 if self.selection_mark_mode {
12949 self.change_selections(None, window, cx, |s| {
12950 s.move_with(|_, sel| {
12951 sel.collapse_to(sel.head(), SelectionGoal::None);
12952 });
12953 })
12954 }
12955 self.selection_mark_mode = true;
12956 cx.notify();
12957 }
12958
12959 pub fn swap_selection_ends(
12960 &mut self,
12961 _: &actions::SwapSelectionEnds,
12962 window: &mut Window,
12963 cx: &mut Context<Self>,
12964 ) {
12965 self.change_selections(None, window, cx, |s| {
12966 s.move_with(|_, sel| {
12967 if sel.start != sel.end {
12968 sel.reversed = !sel.reversed
12969 }
12970 });
12971 });
12972 self.request_autoscroll(Autoscroll::newest(), cx);
12973 cx.notify();
12974 }
12975
12976 pub fn toggle_fold(
12977 &mut self,
12978 _: &actions::ToggleFold,
12979 window: &mut Window,
12980 cx: &mut Context<Self>,
12981 ) {
12982 if self.is_singleton(cx) {
12983 let selection = self.selections.newest::<Point>(cx);
12984
12985 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12986 let range = if selection.is_empty() {
12987 let point = selection.head().to_display_point(&display_map);
12988 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12989 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12990 .to_point(&display_map);
12991 start..end
12992 } else {
12993 selection.range()
12994 };
12995 if display_map.folds_in_range(range).next().is_some() {
12996 self.unfold_lines(&Default::default(), window, cx)
12997 } else {
12998 self.fold(&Default::default(), window, cx)
12999 }
13000 } else {
13001 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13002 let buffer_ids: HashSet<_> = self
13003 .selections
13004 .disjoint_anchor_ranges()
13005 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13006 .collect();
13007
13008 let should_unfold = buffer_ids
13009 .iter()
13010 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13011
13012 for buffer_id in buffer_ids {
13013 if should_unfold {
13014 self.unfold_buffer(buffer_id, cx);
13015 } else {
13016 self.fold_buffer(buffer_id, cx);
13017 }
13018 }
13019 }
13020 }
13021
13022 pub fn toggle_fold_recursive(
13023 &mut self,
13024 _: &actions::ToggleFoldRecursive,
13025 window: &mut Window,
13026 cx: &mut Context<Self>,
13027 ) {
13028 let selection = self.selections.newest::<Point>(cx);
13029
13030 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13031 let range = if selection.is_empty() {
13032 let point = selection.head().to_display_point(&display_map);
13033 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13034 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13035 .to_point(&display_map);
13036 start..end
13037 } else {
13038 selection.range()
13039 };
13040 if display_map.folds_in_range(range).next().is_some() {
13041 self.unfold_recursive(&Default::default(), window, cx)
13042 } else {
13043 self.fold_recursive(&Default::default(), window, cx)
13044 }
13045 }
13046
13047 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13048 if self.is_singleton(cx) {
13049 let mut to_fold = Vec::new();
13050 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13051 let selections = self.selections.all_adjusted(cx);
13052
13053 for selection in selections {
13054 let range = selection.range().sorted();
13055 let buffer_start_row = range.start.row;
13056
13057 if range.start.row != range.end.row {
13058 let mut found = false;
13059 let mut row = range.start.row;
13060 while row <= range.end.row {
13061 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13062 {
13063 found = true;
13064 row = crease.range().end.row + 1;
13065 to_fold.push(crease);
13066 } else {
13067 row += 1
13068 }
13069 }
13070 if found {
13071 continue;
13072 }
13073 }
13074
13075 for row in (0..=range.start.row).rev() {
13076 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13077 if crease.range().end.row >= buffer_start_row {
13078 to_fold.push(crease);
13079 if row <= range.start.row {
13080 break;
13081 }
13082 }
13083 }
13084 }
13085 }
13086
13087 self.fold_creases(to_fold, true, window, cx);
13088 } else {
13089 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13090 let buffer_ids = self
13091 .selections
13092 .disjoint_anchor_ranges()
13093 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13094 .collect::<HashSet<_>>();
13095 for buffer_id in buffer_ids {
13096 self.fold_buffer(buffer_id, cx);
13097 }
13098 }
13099 }
13100
13101 fn fold_at_level(
13102 &mut self,
13103 fold_at: &FoldAtLevel,
13104 window: &mut Window,
13105 cx: &mut Context<Self>,
13106 ) {
13107 if !self.buffer.read(cx).is_singleton() {
13108 return;
13109 }
13110
13111 let fold_at_level = fold_at.0;
13112 let snapshot = self.buffer.read(cx).snapshot(cx);
13113 let mut to_fold = Vec::new();
13114 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13115
13116 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13117 while start_row < end_row {
13118 match self
13119 .snapshot(window, cx)
13120 .crease_for_buffer_row(MultiBufferRow(start_row))
13121 {
13122 Some(crease) => {
13123 let nested_start_row = crease.range().start.row + 1;
13124 let nested_end_row = crease.range().end.row;
13125
13126 if current_level < fold_at_level {
13127 stack.push((nested_start_row, nested_end_row, current_level + 1));
13128 } else if current_level == fold_at_level {
13129 to_fold.push(crease);
13130 }
13131
13132 start_row = nested_end_row + 1;
13133 }
13134 None => start_row += 1,
13135 }
13136 }
13137 }
13138
13139 self.fold_creases(to_fold, true, window, cx);
13140 }
13141
13142 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13143 if self.buffer.read(cx).is_singleton() {
13144 let mut fold_ranges = Vec::new();
13145 let snapshot = self.buffer.read(cx).snapshot(cx);
13146
13147 for row in 0..snapshot.max_row().0 {
13148 if let Some(foldable_range) = self
13149 .snapshot(window, cx)
13150 .crease_for_buffer_row(MultiBufferRow(row))
13151 {
13152 fold_ranges.push(foldable_range);
13153 }
13154 }
13155
13156 self.fold_creases(fold_ranges, true, window, cx);
13157 } else {
13158 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13159 editor
13160 .update_in(&mut cx, |editor, _, cx| {
13161 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13162 editor.fold_buffer(buffer_id, cx);
13163 }
13164 })
13165 .ok();
13166 });
13167 }
13168 }
13169
13170 pub fn fold_function_bodies(
13171 &mut self,
13172 _: &actions::FoldFunctionBodies,
13173 window: &mut Window,
13174 cx: &mut Context<Self>,
13175 ) {
13176 let snapshot = self.buffer.read(cx).snapshot(cx);
13177
13178 let ranges = snapshot
13179 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13180 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13181 .collect::<Vec<_>>();
13182
13183 let creases = ranges
13184 .into_iter()
13185 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13186 .collect();
13187
13188 self.fold_creases(creases, true, window, cx);
13189 }
13190
13191 pub fn fold_recursive(
13192 &mut self,
13193 _: &actions::FoldRecursive,
13194 window: &mut Window,
13195 cx: &mut Context<Self>,
13196 ) {
13197 let mut to_fold = Vec::new();
13198 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13199 let selections = self.selections.all_adjusted(cx);
13200
13201 for selection in selections {
13202 let range = selection.range().sorted();
13203 let buffer_start_row = range.start.row;
13204
13205 if range.start.row != range.end.row {
13206 let mut found = false;
13207 for row in range.start.row..=range.end.row {
13208 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13209 found = true;
13210 to_fold.push(crease);
13211 }
13212 }
13213 if found {
13214 continue;
13215 }
13216 }
13217
13218 for row in (0..=range.start.row).rev() {
13219 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13220 if crease.range().end.row >= buffer_start_row {
13221 to_fold.push(crease);
13222 } else {
13223 break;
13224 }
13225 }
13226 }
13227 }
13228
13229 self.fold_creases(to_fold, true, window, cx);
13230 }
13231
13232 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13233 let buffer_row = fold_at.buffer_row;
13234 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13235
13236 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13237 let autoscroll = self
13238 .selections
13239 .all::<Point>(cx)
13240 .iter()
13241 .any(|selection| crease.range().overlaps(&selection.range()));
13242
13243 self.fold_creases(vec![crease], autoscroll, window, cx);
13244 }
13245 }
13246
13247 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13248 if self.is_singleton(cx) {
13249 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13250 let buffer = &display_map.buffer_snapshot;
13251 let selections = self.selections.all::<Point>(cx);
13252 let ranges = selections
13253 .iter()
13254 .map(|s| {
13255 let range = s.display_range(&display_map).sorted();
13256 let mut start = range.start.to_point(&display_map);
13257 let mut end = range.end.to_point(&display_map);
13258 start.column = 0;
13259 end.column = buffer.line_len(MultiBufferRow(end.row));
13260 start..end
13261 })
13262 .collect::<Vec<_>>();
13263
13264 self.unfold_ranges(&ranges, true, true, cx);
13265 } else {
13266 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13267 let buffer_ids = self
13268 .selections
13269 .disjoint_anchor_ranges()
13270 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13271 .collect::<HashSet<_>>();
13272 for buffer_id in buffer_ids {
13273 self.unfold_buffer(buffer_id, cx);
13274 }
13275 }
13276 }
13277
13278 pub fn unfold_recursive(
13279 &mut self,
13280 _: &UnfoldRecursive,
13281 _window: &mut Window,
13282 cx: &mut Context<Self>,
13283 ) {
13284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13285 let selections = self.selections.all::<Point>(cx);
13286 let ranges = selections
13287 .iter()
13288 .map(|s| {
13289 let mut range = s.display_range(&display_map).sorted();
13290 *range.start.column_mut() = 0;
13291 *range.end.column_mut() = display_map.line_len(range.end.row());
13292 let start = range.start.to_point(&display_map);
13293 let end = range.end.to_point(&display_map);
13294 start..end
13295 })
13296 .collect::<Vec<_>>();
13297
13298 self.unfold_ranges(&ranges, true, true, cx);
13299 }
13300
13301 pub fn unfold_at(
13302 &mut self,
13303 unfold_at: &UnfoldAt,
13304 _window: &mut Window,
13305 cx: &mut Context<Self>,
13306 ) {
13307 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13308
13309 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13310 ..Point::new(
13311 unfold_at.buffer_row.0,
13312 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13313 );
13314
13315 let autoscroll = self
13316 .selections
13317 .all::<Point>(cx)
13318 .iter()
13319 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13320
13321 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13322 }
13323
13324 pub fn unfold_all(
13325 &mut self,
13326 _: &actions::UnfoldAll,
13327 _window: &mut Window,
13328 cx: &mut Context<Self>,
13329 ) {
13330 if self.buffer.read(cx).is_singleton() {
13331 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13332 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13333 } else {
13334 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13335 editor
13336 .update(&mut cx, |editor, cx| {
13337 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13338 editor.unfold_buffer(buffer_id, cx);
13339 }
13340 })
13341 .ok();
13342 });
13343 }
13344 }
13345
13346 pub fn fold_selected_ranges(
13347 &mut self,
13348 _: &FoldSelectedRanges,
13349 window: &mut Window,
13350 cx: &mut Context<Self>,
13351 ) {
13352 let selections = self.selections.all::<Point>(cx);
13353 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13354 let line_mode = self.selections.line_mode;
13355 let ranges = selections
13356 .into_iter()
13357 .map(|s| {
13358 if line_mode {
13359 let start = Point::new(s.start.row, 0);
13360 let end = Point::new(
13361 s.end.row,
13362 display_map
13363 .buffer_snapshot
13364 .line_len(MultiBufferRow(s.end.row)),
13365 );
13366 Crease::simple(start..end, display_map.fold_placeholder.clone())
13367 } else {
13368 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13369 }
13370 })
13371 .collect::<Vec<_>>();
13372 self.fold_creases(ranges, true, window, cx);
13373 }
13374
13375 pub fn fold_ranges<T: ToOffset + Clone>(
13376 &mut self,
13377 ranges: Vec<Range<T>>,
13378 auto_scroll: bool,
13379 window: &mut Window,
13380 cx: &mut Context<Self>,
13381 ) {
13382 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13383 let ranges = ranges
13384 .into_iter()
13385 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13386 .collect::<Vec<_>>();
13387 self.fold_creases(ranges, auto_scroll, window, cx);
13388 }
13389
13390 pub fn fold_creases<T: ToOffset + Clone>(
13391 &mut self,
13392 creases: Vec<Crease<T>>,
13393 auto_scroll: bool,
13394 window: &mut Window,
13395 cx: &mut Context<Self>,
13396 ) {
13397 if creases.is_empty() {
13398 return;
13399 }
13400
13401 let mut buffers_affected = HashSet::default();
13402 let multi_buffer = self.buffer().read(cx);
13403 for crease in &creases {
13404 if let Some((_, buffer, _)) =
13405 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13406 {
13407 buffers_affected.insert(buffer.read(cx).remote_id());
13408 };
13409 }
13410
13411 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13412
13413 if auto_scroll {
13414 self.request_autoscroll(Autoscroll::fit(), cx);
13415 }
13416
13417 cx.notify();
13418
13419 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13420 // Clear diagnostics block when folding a range that contains it.
13421 let snapshot = self.snapshot(window, cx);
13422 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13423 drop(snapshot);
13424 self.active_diagnostics = Some(active_diagnostics);
13425 self.dismiss_diagnostics(cx);
13426 } else {
13427 self.active_diagnostics = Some(active_diagnostics);
13428 }
13429 }
13430
13431 self.scrollbar_marker_state.dirty = true;
13432 }
13433
13434 /// Removes any folds whose ranges intersect any of the given ranges.
13435 pub fn unfold_ranges<T: ToOffset + Clone>(
13436 &mut self,
13437 ranges: &[Range<T>],
13438 inclusive: bool,
13439 auto_scroll: bool,
13440 cx: &mut Context<Self>,
13441 ) {
13442 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13443 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13444 });
13445 }
13446
13447 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13448 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13449 return;
13450 }
13451 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13452 self.display_map.update(cx, |display_map, cx| {
13453 display_map.fold_buffers([buffer_id], cx)
13454 });
13455 cx.emit(EditorEvent::BufferFoldToggled {
13456 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13457 folded: true,
13458 });
13459 cx.notify();
13460 }
13461
13462 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13463 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13464 return;
13465 }
13466 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13467 self.display_map.update(cx, |display_map, cx| {
13468 display_map.unfold_buffers([buffer_id], cx);
13469 });
13470 cx.emit(EditorEvent::BufferFoldToggled {
13471 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13472 folded: false,
13473 });
13474 cx.notify();
13475 }
13476
13477 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13478 self.display_map.read(cx).is_buffer_folded(buffer)
13479 }
13480
13481 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13482 self.display_map.read(cx).folded_buffers()
13483 }
13484
13485 /// Removes any folds with the given ranges.
13486 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13487 &mut self,
13488 ranges: &[Range<T>],
13489 type_id: TypeId,
13490 auto_scroll: bool,
13491 cx: &mut Context<Self>,
13492 ) {
13493 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13494 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13495 });
13496 }
13497
13498 fn remove_folds_with<T: ToOffset + Clone>(
13499 &mut self,
13500 ranges: &[Range<T>],
13501 auto_scroll: bool,
13502 cx: &mut Context<Self>,
13503 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13504 ) {
13505 if ranges.is_empty() {
13506 return;
13507 }
13508
13509 let mut buffers_affected = HashSet::default();
13510 let multi_buffer = self.buffer().read(cx);
13511 for range in ranges {
13512 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13513 buffers_affected.insert(buffer.read(cx).remote_id());
13514 };
13515 }
13516
13517 self.display_map.update(cx, update);
13518
13519 if auto_scroll {
13520 self.request_autoscroll(Autoscroll::fit(), cx);
13521 }
13522
13523 cx.notify();
13524 self.scrollbar_marker_state.dirty = true;
13525 self.active_indent_guides_state.dirty = true;
13526 }
13527
13528 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13529 self.display_map.read(cx).fold_placeholder.clone()
13530 }
13531
13532 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13533 self.buffer.update(cx, |buffer, cx| {
13534 buffer.set_all_diff_hunks_expanded(cx);
13535 });
13536 }
13537
13538 pub fn expand_all_diff_hunks(
13539 &mut self,
13540 _: &ExpandAllDiffHunks,
13541 _window: &mut Window,
13542 cx: &mut Context<Self>,
13543 ) {
13544 self.buffer.update(cx, |buffer, cx| {
13545 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13546 });
13547 }
13548
13549 pub fn toggle_selected_diff_hunks(
13550 &mut self,
13551 _: &ToggleSelectedDiffHunks,
13552 _window: &mut Window,
13553 cx: &mut Context<Self>,
13554 ) {
13555 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13556 self.toggle_diff_hunks_in_ranges(ranges, cx);
13557 }
13558
13559 pub fn diff_hunks_in_ranges<'a>(
13560 &'a self,
13561 ranges: &'a [Range<Anchor>],
13562 buffer: &'a MultiBufferSnapshot,
13563 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13564 ranges.iter().flat_map(move |range| {
13565 let end_excerpt_id = range.end.excerpt_id;
13566 let range = range.to_point(buffer);
13567 let mut peek_end = range.end;
13568 if range.end.row < buffer.max_row().0 {
13569 peek_end = Point::new(range.end.row + 1, 0);
13570 }
13571 buffer
13572 .diff_hunks_in_range(range.start..peek_end)
13573 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13574 })
13575 }
13576
13577 pub fn has_stageable_diff_hunks_in_ranges(
13578 &self,
13579 ranges: &[Range<Anchor>],
13580 snapshot: &MultiBufferSnapshot,
13581 ) -> bool {
13582 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13583 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13584 }
13585
13586 pub fn toggle_staged_selected_diff_hunks(
13587 &mut self,
13588 _: &::git::ToggleStaged,
13589 _: &mut Window,
13590 cx: &mut Context<Self>,
13591 ) {
13592 let snapshot = self.buffer.read(cx).snapshot(cx);
13593 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13594 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13595 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13596 }
13597
13598 pub fn stage_and_next(
13599 &mut self,
13600 _: &::git::StageAndNext,
13601 window: &mut Window,
13602 cx: &mut Context<Self>,
13603 ) {
13604 self.do_stage_or_unstage_and_next(true, window, cx);
13605 }
13606
13607 pub fn unstage_and_next(
13608 &mut self,
13609 _: &::git::UnstageAndNext,
13610 window: &mut Window,
13611 cx: &mut Context<Self>,
13612 ) {
13613 self.do_stage_or_unstage_and_next(false, window, cx);
13614 }
13615
13616 pub fn stage_or_unstage_diff_hunks(
13617 &mut self,
13618 stage: bool,
13619 ranges: Vec<Range<Anchor>>,
13620 cx: &mut Context<Self>,
13621 ) {
13622 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13623 cx.spawn(|this, mut cx| async move {
13624 task.await?;
13625 this.update(&mut cx, |this, cx| {
13626 let snapshot = this.buffer.read(cx).snapshot(cx);
13627 let chunk_by = this
13628 .diff_hunks_in_ranges(&ranges, &snapshot)
13629 .chunk_by(|hunk| hunk.buffer_id);
13630 for (buffer_id, hunks) in &chunk_by {
13631 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13632 }
13633 })
13634 })
13635 .detach_and_log_err(cx);
13636 }
13637
13638 fn save_buffers_for_ranges_if_needed(
13639 &mut self,
13640 ranges: &[Range<Anchor>],
13641 cx: &mut Context<'_, Editor>,
13642 ) -> Task<Result<()>> {
13643 let multibuffer = self.buffer.read(cx);
13644 let snapshot = multibuffer.read(cx);
13645 let buffer_ids: HashSet<_> = ranges
13646 .iter()
13647 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13648 .collect();
13649 drop(snapshot);
13650
13651 let mut buffers = HashSet::default();
13652 for buffer_id in buffer_ids {
13653 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13654 let buffer = buffer_entity.read(cx);
13655 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13656 {
13657 buffers.insert(buffer_entity);
13658 }
13659 }
13660 }
13661
13662 if let Some(project) = &self.project {
13663 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13664 } else {
13665 Task::ready(Ok(()))
13666 }
13667 }
13668
13669 fn do_stage_or_unstage_and_next(
13670 &mut self,
13671 stage: bool,
13672 window: &mut Window,
13673 cx: &mut Context<Self>,
13674 ) {
13675 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13676
13677 if ranges.iter().any(|range| range.start != range.end) {
13678 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13679 return;
13680 }
13681
13682 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13683 let snapshot = self.snapshot(window, cx);
13684 let position = self.selections.newest::<Point>(cx).head();
13685 let mut row = snapshot
13686 .buffer_snapshot
13687 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13688 .find(|hunk| hunk.row_range.start.0 > position.row)
13689 .map(|hunk| hunk.row_range.start);
13690
13691 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
13692 // Outside of the project diff editor, wrap around to the beginning.
13693 if !all_diff_hunks_expanded {
13694 row = row.or_else(|| {
13695 snapshot
13696 .buffer_snapshot
13697 .diff_hunks_in_range(Point::zero()..position)
13698 .find(|hunk| hunk.row_range.end.0 < position.row)
13699 .map(|hunk| hunk.row_range.start)
13700 });
13701 }
13702
13703 if let Some(row) = row {
13704 let destination = Point::new(row.0, 0);
13705 let autoscroll = Autoscroll::center();
13706
13707 self.unfold_ranges(&[destination..destination], false, false, cx);
13708 self.change_selections(Some(autoscroll), window, cx, |s| {
13709 s.select_ranges([destination..destination]);
13710 });
13711 } else if all_diff_hunks_expanded {
13712 window.dispatch_action(::git::ExpandCommitEditor.boxed_clone(), cx);
13713 }
13714 }
13715
13716 fn do_stage_or_unstage(
13717 &self,
13718 stage: bool,
13719 buffer_id: BufferId,
13720 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13721 cx: &mut App,
13722 ) -> Option<()> {
13723 let project = self.project.as_ref()?;
13724 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13725 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13726 let buffer_snapshot = buffer.read(cx).snapshot();
13727 let file_exists = buffer_snapshot
13728 .file()
13729 .is_some_and(|file| file.disk_state().exists());
13730 diff.update(cx, |diff, cx| {
13731 diff.stage_or_unstage_hunks(
13732 stage,
13733 &hunks
13734 .map(|hunk| buffer_diff::DiffHunk {
13735 buffer_range: hunk.buffer_range,
13736 diff_base_byte_range: hunk.diff_base_byte_range,
13737 secondary_status: hunk.secondary_status,
13738 range: Point::zero()..Point::zero(), // unused
13739 })
13740 .collect::<Vec<_>>(),
13741 &buffer_snapshot,
13742 file_exists,
13743 cx,
13744 )
13745 });
13746 None
13747 }
13748
13749 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13750 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13751 self.buffer
13752 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13753 }
13754
13755 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13756 self.buffer.update(cx, |buffer, cx| {
13757 let ranges = vec![Anchor::min()..Anchor::max()];
13758 if !buffer.all_diff_hunks_expanded()
13759 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13760 {
13761 buffer.collapse_diff_hunks(ranges, cx);
13762 true
13763 } else {
13764 false
13765 }
13766 })
13767 }
13768
13769 fn toggle_diff_hunks_in_ranges(
13770 &mut self,
13771 ranges: Vec<Range<Anchor>>,
13772 cx: &mut Context<'_, Editor>,
13773 ) {
13774 self.buffer.update(cx, |buffer, cx| {
13775 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13776 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13777 })
13778 }
13779
13780 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13781 self.buffer.update(cx, |buffer, cx| {
13782 let snapshot = buffer.snapshot(cx);
13783 let excerpt_id = range.end.excerpt_id;
13784 let point_range = range.to_point(&snapshot);
13785 let expand = !buffer.single_hunk_is_expanded(range, cx);
13786 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13787 })
13788 }
13789
13790 pub(crate) fn apply_all_diff_hunks(
13791 &mut self,
13792 _: &ApplyAllDiffHunks,
13793 window: &mut Window,
13794 cx: &mut Context<Self>,
13795 ) {
13796 let buffers = self.buffer.read(cx).all_buffers();
13797 for branch_buffer in buffers {
13798 branch_buffer.update(cx, |branch_buffer, cx| {
13799 branch_buffer.merge_into_base(Vec::new(), cx);
13800 });
13801 }
13802
13803 if let Some(project) = self.project.clone() {
13804 self.save(true, project, window, cx).detach_and_log_err(cx);
13805 }
13806 }
13807
13808 pub(crate) fn apply_selected_diff_hunks(
13809 &mut self,
13810 _: &ApplyDiffHunk,
13811 window: &mut Window,
13812 cx: &mut Context<Self>,
13813 ) {
13814 let snapshot = self.snapshot(window, cx);
13815 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13816 let mut ranges_by_buffer = HashMap::default();
13817 self.transact(window, cx, |editor, _window, cx| {
13818 for hunk in hunks {
13819 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13820 ranges_by_buffer
13821 .entry(buffer.clone())
13822 .or_insert_with(Vec::new)
13823 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13824 }
13825 }
13826
13827 for (buffer, ranges) in ranges_by_buffer {
13828 buffer.update(cx, |buffer, cx| {
13829 buffer.merge_into_base(ranges, cx);
13830 });
13831 }
13832 });
13833
13834 if let Some(project) = self.project.clone() {
13835 self.save(true, project, window, cx).detach_and_log_err(cx);
13836 }
13837 }
13838
13839 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13840 if hovered != self.gutter_hovered {
13841 self.gutter_hovered = hovered;
13842 cx.notify();
13843 }
13844 }
13845
13846 pub fn insert_blocks(
13847 &mut self,
13848 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13849 autoscroll: Option<Autoscroll>,
13850 cx: &mut Context<Self>,
13851 ) -> Vec<CustomBlockId> {
13852 let blocks = self
13853 .display_map
13854 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13855 if let Some(autoscroll) = autoscroll {
13856 self.request_autoscroll(autoscroll, cx);
13857 }
13858 cx.notify();
13859 blocks
13860 }
13861
13862 pub fn resize_blocks(
13863 &mut self,
13864 heights: HashMap<CustomBlockId, u32>,
13865 autoscroll: Option<Autoscroll>,
13866 cx: &mut Context<Self>,
13867 ) {
13868 self.display_map
13869 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13870 if let Some(autoscroll) = autoscroll {
13871 self.request_autoscroll(autoscroll, cx);
13872 }
13873 cx.notify();
13874 }
13875
13876 pub fn replace_blocks(
13877 &mut self,
13878 renderers: HashMap<CustomBlockId, RenderBlock>,
13879 autoscroll: Option<Autoscroll>,
13880 cx: &mut Context<Self>,
13881 ) {
13882 self.display_map
13883 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13884 if let Some(autoscroll) = autoscroll {
13885 self.request_autoscroll(autoscroll, cx);
13886 }
13887 cx.notify();
13888 }
13889
13890 pub fn remove_blocks(
13891 &mut self,
13892 block_ids: HashSet<CustomBlockId>,
13893 autoscroll: Option<Autoscroll>,
13894 cx: &mut Context<Self>,
13895 ) {
13896 self.display_map.update(cx, |display_map, cx| {
13897 display_map.remove_blocks(block_ids, cx)
13898 });
13899 if let Some(autoscroll) = autoscroll {
13900 self.request_autoscroll(autoscroll, cx);
13901 }
13902 cx.notify();
13903 }
13904
13905 pub fn row_for_block(
13906 &self,
13907 block_id: CustomBlockId,
13908 cx: &mut Context<Self>,
13909 ) -> Option<DisplayRow> {
13910 self.display_map
13911 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13912 }
13913
13914 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13915 self.focused_block = Some(focused_block);
13916 }
13917
13918 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13919 self.focused_block.take()
13920 }
13921
13922 pub fn insert_creases(
13923 &mut self,
13924 creases: impl IntoIterator<Item = Crease<Anchor>>,
13925 cx: &mut Context<Self>,
13926 ) -> Vec<CreaseId> {
13927 self.display_map
13928 .update(cx, |map, cx| map.insert_creases(creases, cx))
13929 }
13930
13931 pub fn remove_creases(
13932 &mut self,
13933 ids: impl IntoIterator<Item = CreaseId>,
13934 cx: &mut Context<Self>,
13935 ) {
13936 self.display_map
13937 .update(cx, |map, cx| map.remove_creases(ids, cx));
13938 }
13939
13940 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13941 self.display_map
13942 .update(cx, |map, cx| map.snapshot(cx))
13943 .longest_row()
13944 }
13945
13946 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13947 self.display_map
13948 .update(cx, |map, cx| map.snapshot(cx))
13949 .max_point()
13950 }
13951
13952 pub fn text(&self, cx: &App) -> String {
13953 self.buffer.read(cx).read(cx).text()
13954 }
13955
13956 pub fn is_empty(&self, cx: &App) -> bool {
13957 self.buffer.read(cx).read(cx).is_empty()
13958 }
13959
13960 pub fn text_option(&self, cx: &App) -> Option<String> {
13961 let text = self.text(cx);
13962 let text = text.trim();
13963
13964 if text.is_empty() {
13965 return None;
13966 }
13967
13968 Some(text.to_string())
13969 }
13970
13971 pub fn set_text(
13972 &mut self,
13973 text: impl Into<Arc<str>>,
13974 window: &mut Window,
13975 cx: &mut Context<Self>,
13976 ) {
13977 self.transact(window, cx, |this, _, cx| {
13978 this.buffer
13979 .read(cx)
13980 .as_singleton()
13981 .expect("you can only call set_text on editors for singleton buffers")
13982 .update(cx, |buffer, cx| buffer.set_text(text, cx));
13983 });
13984 }
13985
13986 pub fn display_text(&self, cx: &mut App) -> String {
13987 self.display_map
13988 .update(cx, |map, cx| map.snapshot(cx))
13989 .text()
13990 }
13991
13992 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13993 let mut wrap_guides = smallvec::smallvec![];
13994
13995 if self.show_wrap_guides == Some(false) {
13996 return wrap_guides;
13997 }
13998
13999 let settings = self.buffer.read(cx).settings_at(0, cx);
14000 if settings.show_wrap_guides {
14001 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
14002 wrap_guides.push((soft_wrap as usize, true));
14003 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
14004 wrap_guides.push((soft_wrap as usize, true));
14005 }
14006 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14007 }
14008
14009 wrap_guides
14010 }
14011
14012 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14013 let settings = self.buffer.read(cx).settings_at(0, cx);
14014 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14015 match mode {
14016 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14017 SoftWrap::None
14018 }
14019 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14020 language_settings::SoftWrap::PreferredLineLength => {
14021 SoftWrap::Column(settings.preferred_line_length)
14022 }
14023 language_settings::SoftWrap::Bounded => {
14024 SoftWrap::Bounded(settings.preferred_line_length)
14025 }
14026 }
14027 }
14028
14029 pub fn set_soft_wrap_mode(
14030 &mut self,
14031 mode: language_settings::SoftWrap,
14032
14033 cx: &mut Context<Self>,
14034 ) {
14035 self.soft_wrap_mode_override = Some(mode);
14036 cx.notify();
14037 }
14038
14039 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14040 self.text_style_refinement = Some(style);
14041 }
14042
14043 /// called by the Element so we know what style we were most recently rendered with.
14044 pub(crate) fn set_style(
14045 &mut self,
14046 style: EditorStyle,
14047 window: &mut Window,
14048 cx: &mut Context<Self>,
14049 ) {
14050 let rem_size = window.rem_size();
14051 self.display_map.update(cx, |map, cx| {
14052 map.set_font(
14053 style.text.font(),
14054 style.text.font_size.to_pixels(rem_size),
14055 cx,
14056 )
14057 });
14058 self.style = Some(style);
14059 }
14060
14061 pub fn style(&self) -> Option<&EditorStyle> {
14062 self.style.as_ref()
14063 }
14064
14065 // Called by the element. This method is not designed to be called outside of the editor
14066 // element's layout code because it does not notify when rewrapping is computed synchronously.
14067 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14068 self.display_map
14069 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14070 }
14071
14072 pub fn set_soft_wrap(&mut self) {
14073 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14074 }
14075
14076 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14077 if self.soft_wrap_mode_override.is_some() {
14078 self.soft_wrap_mode_override.take();
14079 } else {
14080 let soft_wrap = match self.soft_wrap_mode(cx) {
14081 SoftWrap::GitDiff => return,
14082 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14083 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14084 language_settings::SoftWrap::None
14085 }
14086 };
14087 self.soft_wrap_mode_override = Some(soft_wrap);
14088 }
14089 cx.notify();
14090 }
14091
14092 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14093 let Some(workspace) = self.workspace() else {
14094 return;
14095 };
14096 let fs = workspace.read(cx).app_state().fs.clone();
14097 let current_show = TabBarSettings::get_global(cx).show;
14098 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14099 setting.show = Some(!current_show);
14100 });
14101 }
14102
14103 pub fn toggle_indent_guides(
14104 &mut self,
14105 _: &ToggleIndentGuides,
14106 _: &mut Window,
14107 cx: &mut Context<Self>,
14108 ) {
14109 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14110 self.buffer
14111 .read(cx)
14112 .settings_at(0, cx)
14113 .indent_guides
14114 .enabled
14115 });
14116 self.show_indent_guides = Some(!currently_enabled);
14117 cx.notify();
14118 }
14119
14120 fn should_show_indent_guides(&self) -> Option<bool> {
14121 self.show_indent_guides
14122 }
14123
14124 pub fn toggle_line_numbers(
14125 &mut self,
14126 _: &ToggleLineNumbers,
14127 _: &mut Window,
14128 cx: &mut Context<Self>,
14129 ) {
14130 let mut editor_settings = EditorSettings::get_global(cx).clone();
14131 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14132 EditorSettings::override_global(editor_settings, cx);
14133 }
14134
14135 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14136 self.use_relative_line_numbers
14137 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14138 }
14139
14140 pub fn toggle_relative_line_numbers(
14141 &mut self,
14142 _: &ToggleRelativeLineNumbers,
14143 _: &mut Window,
14144 cx: &mut Context<Self>,
14145 ) {
14146 let is_relative = self.should_use_relative_line_numbers(cx);
14147 self.set_relative_line_number(Some(!is_relative), cx)
14148 }
14149
14150 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14151 self.use_relative_line_numbers = is_relative;
14152 cx.notify();
14153 }
14154
14155 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14156 self.show_gutter = show_gutter;
14157 cx.notify();
14158 }
14159
14160 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14161 self.show_scrollbars = show_scrollbars;
14162 cx.notify();
14163 }
14164
14165 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14166 self.show_line_numbers = Some(show_line_numbers);
14167 cx.notify();
14168 }
14169
14170 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14171 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14172 cx.notify();
14173 }
14174
14175 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14176 self.show_code_actions = Some(show_code_actions);
14177 cx.notify();
14178 }
14179
14180 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14181 self.show_runnables = Some(show_runnables);
14182 cx.notify();
14183 }
14184
14185 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14186 if self.display_map.read(cx).masked != masked {
14187 self.display_map.update(cx, |map, _| map.masked = masked);
14188 }
14189 cx.notify()
14190 }
14191
14192 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14193 self.show_wrap_guides = Some(show_wrap_guides);
14194 cx.notify();
14195 }
14196
14197 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14198 self.show_indent_guides = Some(show_indent_guides);
14199 cx.notify();
14200 }
14201
14202 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14203 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14204 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14205 if let Some(dir) = file.abs_path(cx).parent() {
14206 return Some(dir.to_owned());
14207 }
14208 }
14209
14210 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14211 return Some(project_path.path.to_path_buf());
14212 }
14213 }
14214
14215 None
14216 }
14217
14218 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14219 self.active_excerpt(cx)?
14220 .1
14221 .read(cx)
14222 .file()
14223 .and_then(|f| f.as_local())
14224 }
14225
14226 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14227 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14228 let buffer = buffer.read(cx);
14229 if let Some(project_path) = buffer.project_path(cx) {
14230 let project = self.project.as_ref()?.read(cx);
14231 project.absolute_path(&project_path, cx)
14232 } else {
14233 buffer
14234 .file()
14235 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14236 }
14237 })
14238 }
14239
14240 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14241 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14242 let project_path = buffer.read(cx).project_path(cx)?;
14243 let project = self.project.as_ref()?.read(cx);
14244 let entry = project.entry_for_path(&project_path, cx)?;
14245 let path = entry.path.to_path_buf();
14246 Some(path)
14247 })
14248 }
14249
14250 pub fn reveal_in_finder(
14251 &mut self,
14252 _: &RevealInFileManager,
14253 _window: &mut Window,
14254 cx: &mut Context<Self>,
14255 ) {
14256 if let Some(target) = self.target_file(cx) {
14257 cx.reveal_path(&target.abs_path(cx));
14258 }
14259 }
14260
14261 pub fn copy_path(
14262 &mut self,
14263 _: &zed_actions::workspace::CopyPath,
14264 _window: &mut Window,
14265 cx: &mut Context<Self>,
14266 ) {
14267 if let Some(path) = self.target_file_abs_path(cx) {
14268 if let Some(path) = path.to_str() {
14269 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14270 }
14271 }
14272 }
14273
14274 pub fn copy_relative_path(
14275 &mut self,
14276 _: &zed_actions::workspace::CopyRelativePath,
14277 _window: &mut Window,
14278 cx: &mut Context<Self>,
14279 ) {
14280 if let Some(path) = self.target_file_path(cx) {
14281 if let Some(path) = path.to_str() {
14282 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14283 }
14284 }
14285 }
14286
14287 pub fn copy_file_name_without_extension(
14288 &mut self,
14289 _: &CopyFileNameWithoutExtension,
14290 _: &mut Window,
14291 cx: &mut Context<Self>,
14292 ) {
14293 if let Some(file) = self.target_file(cx) {
14294 if let Some(file_stem) = file.path().file_stem() {
14295 if let Some(name) = file_stem.to_str() {
14296 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14297 }
14298 }
14299 }
14300 }
14301
14302 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14303 if let Some(file) = self.target_file(cx) {
14304 if let Some(file_name) = file.path().file_name() {
14305 if let Some(name) = file_name.to_str() {
14306 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14307 }
14308 }
14309 }
14310 }
14311
14312 pub fn toggle_git_blame(
14313 &mut self,
14314 _: &ToggleGitBlame,
14315 window: &mut Window,
14316 cx: &mut Context<Self>,
14317 ) {
14318 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14319
14320 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14321 self.start_git_blame(true, window, cx);
14322 }
14323
14324 cx.notify();
14325 }
14326
14327 pub fn toggle_git_blame_inline(
14328 &mut self,
14329 _: &ToggleGitBlameInline,
14330 window: &mut Window,
14331 cx: &mut Context<Self>,
14332 ) {
14333 self.toggle_git_blame_inline_internal(true, window, cx);
14334 cx.notify();
14335 }
14336
14337 pub fn git_blame_inline_enabled(&self) -> bool {
14338 self.git_blame_inline_enabled
14339 }
14340
14341 pub fn toggle_selection_menu(
14342 &mut self,
14343 _: &ToggleSelectionMenu,
14344 _: &mut Window,
14345 cx: &mut Context<Self>,
14346 ) {
14347 self.show_selection_menu = self
14348 .show_selection_menu
14349 .map(|show_selections_menu| !show_selections_menu)
14350 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14351
14352 cx.notify();
14353 }
14354
14355 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14356 self.show_selection_menu
14357 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14358 }
14359
14360 fn start_git_blame(
14361 &mut self,
14362 user_triggered: bool,
14363 window: &mut Window,
14364 cx: &mut Context<Self>,
14365 ) {
14366 if let Some(project) = self.project.as_ref() {
14367 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14368 return;
14369 };
14370
14371 if buffer.read(cx).file().is_none() {
14372 return;
14373 }
14374
14375 let focused = self.focus_handle(cx).contains_focused(window, cx);
14376
14377 let project = project.clone();
14378 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14379 self.blame_subscription =
14380 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14381 self.blame = Some(blame);
14382 }
14383 }
14384
14385 fn toggle_git_blame_inline_internal(
14386 &mut self,
14387 user_triggered: bool,
14388 window: &mut Window,
14389 cx: &mut Context<Self>,
14390 ) {
14391 if self.git_blame_inline_enabled {
14392 self.git_blame_inline_enabled = false;
14393 self.show_git_blame_inline = false;
14394 self.show_git_blame_inline_delay_task.take();
14395 } else {
14396 self.git_blame_inline_enabled = true;
14397 self.start_git_blame_inline(user_triggered, window, cx);
14398 }
14399
14400 cx.notify();
14401 }
14402
14403 fn start_git_blame_inline(
14404 &mut self,
14405 user_triggered: bool,
14406 window: &mut Window,
14407 cx: &mut Context<Self>,
14408 ) {
14409 self.start_git_blame(user_triggered, window, cx);
14410
14411 if ProjectSettings::get_global(cx)
14412 .git
14413 .inline_blame_delay()
14414 .is_some()
14415 {
14416 self.start_inline_blame_timer(window, cx);
14417 } else {
14418 self.show_git_blame_inline = true
14419 }
14420 }
14421
14422 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14423 self.blame.as_ref()
14424 }
14425
14426 pub fn show_git_blame_gutter(&self) -> bool {
14427 self.show_git_blame_gutter
14428 }
14429
14430 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14431 self.show_git_blame_gutter && self.has_blame_entries(cx)
14432 }
14433
14434 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14435 self.show_git_blame_inline
14436 && (self.focus_handle.is_focused(window)
14437 || self
14438 .git_blame_inline_tooltip
14439 .as_ref()
14440 .and_then(|t| t.upgrade())
14441 .is_some())
14442 && !self.newest_selection_head_on_empty_line(cx)
14443 && self.has_blame_entries(cx)
14444 }
14445
14446 fn has_blame_entries(&self, cx: &App) -> bool {
14447 self.blame()
14448 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14449 }
14450
14451 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14452 let cursor_anchor = self.selections.newest_anchor().head();
14453
14454 let snapshot = self.buffer.read(cx).snapshot(cx);
14455 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14456
14457 snapshot.line_len(buffer_row) == 0
14458 }
14459
14460 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14461 let buffer_and_selection = maybe!({
14462 let selection = self.selections.newest::<Point>(cx);
14463 let selection_range = selection.range();
14464
14465 let multi_buffer = self.buffer().read(cx);
14466 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14467 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14468
14469 let (buffer, range, _) = if selection.reversed {
14470 buffer_ranges.first()
14471 } else {
14472 buffer_ranges.last()
14473 }?;
14474
14475 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14476 ..text::ToPoint::to_point(&range.end, &buffer).row;
14477 Some((
14478 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14479 selection,
14480 ))
14481 });
14482
14483 let Some((buffer, selection)) = buffer_and_selection else {
14484 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14485 };
14486
14487 let Some(project) = self.project.as_ref() else {
14488 return Task::ready(Err(anyhow!("editor does not have project")));
14489 };
14490
14491 project.update(cx, |project, cx| {
14492 project.get_permalink_to_line(&buffer, selection, cx)
14493 })
14494 }
14495
14496 pub fn copy_permalink_to_line(
14497 &mut self,
14498 _: &CopyPermalinkToLine,
14499 window: &mut Window,
14500 cx: &mut Context<Self>,
14501 ) {
14502 let permalink_task = self.get_permalink_to_line(cx);
14503 let workspace = self.workspace();
14504
14505 cx.spawn_in(window, |_, mut cx| async move {
14506 match permalink_task.await {
14507 Ok(permalink) => {
14508 cx.update(|_, cx| {
14509 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14510 })
14511 .ok();
14512 }
14513 Err(err) => {
14514 let message = format!("Failed to copy permalink: {err}");
14515
14516 Err::<(), anyhow::Error>(err).log_err();
14517
14518 if let Some(workspace) = workspace {
14519 workspace
14520 .update_in(&mut cx, |workspace, _, cx| {
14521 struct CopyPermalinkToLine;
14522
14523 workspace.show_toast(
14524 Toast::new(
14525 NotificationId::unique::<CopyPermalinkToLine>(),
14526 message,
14527 ),
14528 cx,
14529 )
14530 })
14531 .ok();
14532 }
14533 }
14534 }
14535 })
14536 .detach();
14537 }
14538
14539 pub fn copy_file_location(
14540 &mut self,
14541 _: &CopyFileLocation,
14542 _: &mut Window,
14543 cx: &mut Context<Self>,
14544 ) {
14545 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14546 if let Some(file) = self.target_file(cx) {
14547 if let Some(path) = file.path().to_str() {
14548 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14549 }
14550 }
14551 }
14552
14553 pub fn open_permalink_to_line(
14554 &mut self,
14555 _: &OpenPermalinkToLine,
14556 window: &mut Window,
14557 cx: &mut Context<Self>,
14558 ) {
14559 let permalink_task = self.get_permalink_to_line(cx);
14560 let workspace = self.workspace();
14561
14562 cx.spawn_in(window, |_, mut cx| async move {
14563 match permalink_task.await {
14564 Ok(permalink) => {
14565 cx.update(|_, cx| {
14566 cx.open_url(permalink.as_ref());
14567 })
14568 .ok();
14569 }
14570 Err(err) => {
14571 let message = format!("Failed to open permalink: {err}");
14572
14573 Err::<(), anyhow::Error>(err).log_err();
14574
14575 if let Some(workspace) = workspace {
14576 workspace
14577 .update(&mut cx, |workspace, cx| {
14578 struct OpenPermalinkToLine;
14579
14580 workspace.show_toast(
14581 Toast::new(
14582 NotificationId::unique::<OpenPermalinkToLine>(),
14583 message,
14584 ),
14585 cx,
14586 )
14587 })
14588 .ok();
14589 }
14590 }
14591 }
14592 })
14593 .detach();
14594 }
14595
14596 pub fn insert_uuid_v4(
14597 &mut self,
14598 _: &InsertUuidV4,
14599 window: &mut Window,
14600 cx: &mut Context<Self>,
14601 ) {
14602 self.insert_uuid(UuidVersion::V4, window, cx);
14603 }
14604
14605 pub fn insert_uuid_v7(
14606 &mut self,
14607 _: &InsertUuidV7,
14608 window: &mut Window,
14609 cx: &mut Context<Self>,
14610 ) {
14611 self.insert_uuid(UuidVersion::V7, window, cx);
14612 }
14613
14614 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14615 self.transact(window, cx, |this, window, cx| {
14616 let edits = this
14617 .selections
14618 .all::<Point>(cx)
14619 .into_iter()
14620 .map(|selection| {
14621 let uuid = match version {
14622 UuidVersion::V4 => uuid::Uuid::new_v4(),
14623 UuidVersion::V7 => uuid::Uuid::now_v7(),
14624 };
14625
14626 (selection.range(), uuid.to_string())
14627 });
14628 this.edit(edits, cx);
14629 this.refresh_inline_completion(true, false, window, cx);
14630 });
14631 }
14632
14633 pub fn open_selections_in_multibuffer(
14634 &mut self,
14635 _: &OpenSelectionsInMultibuffer,
14636 window: &mut Window,
14637 cx: &mut Context<Self>,
14638 ) {
14639 let multibuffer = self.buffer.read(cx);
14640
14641 let Some(buffer) = multibuffer.as_singleton() else {
14642 return;
14643 };
14644
14645 let Some(workspace) = self.workspace() else {
14646 return;
14647 };
14648
14649 let locations = self
14650 .selections
14651 .disjoint_anchors()
14652 .iter()
14653 .map(|range| Location {
14654 buffer: buffer.clone(),
14655 range: range.start.text_anchor..range.end.text_anchor,
14656 })
14657 .collect::<Vec<_>>();
14658
14659 let title = multibuffer.title(cx).to_string();
14660
14661 cx.spawn_in(window, |_, mut cx| async move {
14662 workspace.update_in(&mut cx, |workspace, window, cx| {
14663 Self::open_locations_in_multibuffer(
14664 workspace,
14665 locations,
14666 format!("Selections for '{title}'"),
14667 false,
14668 MultibufferSelectionMode::All,
14669 window,
14670 cx,
14671 );
14672 })
14673 })
14674 .detach();
14675 }
14676
14677 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14678 /// last highlight added will be used.
14679 ///
14680 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14681 pub fn highlight_rows<T: 'static>(
14682 &mut self,
14683 range: Range<Anchor>,
14684 color: Hsla,
14685 should_autoscroll: bool,
14686 cx: &mut Context<Self>,
14687 ) {
14688 let snapshot = self.buffer().read(cx).snapshot(cx);
14689 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14690 let ix = row_highlights.binary_search_by(|highlight| {
14691 Ordering::Equal
14692 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14693 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14694 });
14695
14696 if let Err(mut ix) = ix {
14697 let index = post_inc(&mut self.highlight_order);
14698
14699 // If this range intersects with the preceding highlight, then merge it with
14700 // the preceding highlight. Otherwise insert a new highlight.
14701 let mut merged = false;
14702 if ix > 0 {
14703 let prev_highlight = &mut row_highlights[ix - 1];
14704 if prev_highlight
14705 .range
14706 .end
14707 .cmp(&range.start, &snapshot)
14708 .is_ge()
14709 {
14710 ix -= 1;
14711 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14712 prev_highlight.range.end = range.end;
14713 }
14714 merged = true;
14715 prev_highlight.index = index;
14716 prev_highlight.color = color;
14717 prev_highlight.should_autoscroll = should_autoscroll;
14718 }
14719 }
14720
14721 if !merged {
14722 row_highlights.insert(
14723 ix,
14724 RowHighlight {
14725 range: range.clone(),
14726 index,
14727 color,
14728 should_autoscroll,
14729 },
14730 );
14731 }
14732
14733 // If any of the following highlights intersect with this one, merge them.
14734 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14735 let highlight = &row_highlights[ix];
14736 if next_highlight
14737 .range
14738 .start
14739 .cmp(&highlight.range.end, &snapshot)
14740 .is_le()
14741 {
14742 if next_highlight
14743 .range
14744 .end
14745 .cmp(&highlight.range.end, &snapshot)
14746 .is_gt()
14747 {
14748 row_highlights[ix].range.end = next_highlight.range.end;
14749 }
14750 row_highlights.remove(ix + 1);
14751 } else {
14752 break;
14753 }
14754 }
14755 }
14756 }
14757
14758 /// Remove any highlighted row ranges of the given type that intersect the
14759 /// given ranges.
14760 pub fn remove_highlighted_rows<T: 'static>(
14761 &mut self,
14762 ranges_to_remove: Vec<Range<Anchor>>,
14763 cx: &mut Context<Self>,
14764 ) {
14765 let snapshot = self.buffer().read(cx).snapshot(cx);
14766 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14767 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14768 row_highlights.retain(|highlight| {
14769 while let Some(range_to_remove) = ranges_to_remove.peek() {
14770 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14771 Ordering::Less | Ordering::Equal => {
14772 ranges_to_remove.next();
14773 }
14774 Ordering::Greater => {
14775 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14776 Ordering::Less | Ordering::Equal => {
14777 return false;
14778 }
14779 Ordering::Greater => break,
14780 }
14781 }
14782 }
14783 }
14784
14785 true
14786 })
14787 }
14788
14789 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14790 pub fn clear_row_highlights<T: 'static>(&mut self) {
14791 self.highlighted_rows.remove(&TypeId::of::<T>());
14792 }
14793
14794 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14795 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14796 self.highlighted_rows
14797 .get(&TypeId::of::<T>())
14798 .map_or(&[] as &[_], |vec| vec.as_slice())
14799 .iter()
14800 .map(|highlight| (highlight.range.clone(), highlight.color))
14801 }
14802
14803 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14804 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14805 /// Allows to ignore certain kinds of highlights.
14806 pub fn highlighted_display_rows(
14807 &self,
14808 window: &mut Window,
14809 cx: &mut App,
14810 ) -> BTreeMap<DisplayRow, LineHighlight> {
14811 let snapshot = self.snapshot(window, cx);
14812 let mut used_highlight_orders = HashMap::default();
14813 self.highlighted_rows
14814 .iter()
14815 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14816 .fold(
14817 BTreeMap::<DisplayRow, LineHighlight>::new(),
14818 |mut unique_rows, highlight| {
14819 let start = highlight.range.start.to_display_point(&snapshot);
14820 let end = highlight.range.end.to_display_point(&snapshot);
14821 let start_row = start.row().0;
14822 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14823 && end.column() == 0
14824 {
14825 end.row().0.saturating_sub(1)
14826 } else {
14827 end.row().0
14828 };
14829 for row in start_row..=end_row {
14830 let used_index =
14831 used_highlight_orders.entry(row).or_insert(highlight.index);
14832 if highlight.index >= *used_index {
14833 *used_index = highlight.index;
14834 unique_rows.insert(DisplayRow(row), highlight.color.into());
14835 }
14836 }
14837 unique_rows
14838 },
14839 )
14840 }
14841
14842 pub fn highlighted_display_row_for_autoscroll(
14843 &self,
14844 snapshot: &DisplaySnapshot,
14845 ) -> Option<DisplayRow> {
14846 self.highlighted_rows
14847 .values()
14848 .flat_map(|highlighted_rows| highlighted_rows.iter())
14849 .filter_map(|highlight| {
14850 if highlight.should_autoscroll {
14851 Some(highlight.range.start.to_display_point(snapshot).row())
14852 } else {
14853 None
14854 }
14855 })
14856 .min()
14857 }
14858
14859 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14860 self.highlight_background::<SearchWithinRange>(
14861 ranges,
14862 |colors| colors.editor_document_highlight_read_background,
14863 cx,
14864 )
14865 }
14866
14867 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14868 self.breadcrumb_header = Some(new_header);
14869 }
14870
14871 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14872 self.clear_background_highlights::<SearchWithinRange>(cx);
14873 }
14874
14875 pub fn highlight_background<T: 'static>(
14876 &mut self,
14877 ranges: &[Range<Anchor>],
14878 color_fetcher: fn(&ThemeColors) -> Hsla,
14879 cx: &mut Context<Self>,
14880 ) {
14881 self.background_highlights
14882 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14883 self.scrollbar_marker_state.dirty = true;
14884 cx.notify();
14885 }
14886
14887 pub fn clear_background_highlights<T: 'static>(
14888 &mut self,
14889 cx: &mut Context<Self>,
14890 ) -> Option<BackgroundHighlight> {
14891 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14892 if !text_highlights.1.is_empty() {
14893 self.scrollbar_marker_state.dirty = true;
14894 cx.notify();
14895 }
14896 Some(text_highlights)
14897 }
14898
14899 pub fn highlight_gutter<T: 'static>(
14900 &mut self,
14901 ranges: &[Range<Anchor>],
14902 color_fetcher: fn(&App) -> Hsla,
14903 cx: &mut Context<Self>,
14904 ) {
14905 self.gutter_highlights
14906 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14907 cx.notify();
14908 }
14909
14910 pub fn clear_gutter_highlights<T: 'static>(
14911 &mut self,
14912 cx: &mut Context<Self>,
14913 ) -> Option<GutterHighlight> {
14914 cx.notify();
14915 self.gutter_highlights.remove(&TypeId::of::<T>())
14916 }
14917
14918 #[cfg(feature = "test-support")]
14919 pub fn all_text_background_highlights(
14920 &self,
14921 window: &mut Window,
14922 cx: &mut Context<Self>,
14923 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14924 let snapshot = self.snapshot(window, cx);
14925 let buffer = &snapshot.buffer_snapshot;
14926 let start = buffer.anchor_before(0);
14927 let end = buffer.anchor_after(buffer.len());
14928 let theme = cx.theme().colors();
14929 self.background_highlights_in_range(start..end, &snapshot, theme)
14930 }
14931
14932 #[cfg(feature = "test-support")]
14933 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14934 let snapshot = self.buffer().read(cx).snapshot(cx);
14935
14936 let highlights = self
14937 .background_highlights
14938 .get(&TypeId::of::<items::BufferSearchHighlights>());
14939
14940 if let Some((_color, ranges)) = highlights {
14941 ranges
14942 .iter()
14943 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14944 .collect_vec()
14945 } else {
14946 vec![]
14947 }
14948 }
14949
14950 fn document_highlights_for_position<'a>(
14951 &'a self,
14952 position: Anchor,
14953 buffer: &'a MultiBufferSnapshot,
14954 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14955 let read_highlights = self
14956 .background_highlights
14957 .get(&TypeId::of::<DocumentHighlightRead>())
14958 .map(|h| &h.1);
14959 let write_highlights = self
14960 .background_highlights
14961 .get(&TypeId::of::<DocumentHighlightWrite>())
14962 .map(|h| &h.1);
14963 let left_position = position.bias_left(buffer);
14964 let right_position = position.bias_right(buffer);
14965 read_highlights
14966 .into_iter()
14967 .chain(write_highlights)
14968 .flat_map(move |ranges| {
14969 let start_ix = match ranges.binary_search_by(|probe| {
14970 let cmp = probe.end.cmp(&left_position, buffer);
14971 if cmp.is_ge() {
14972 Ordering::Greater
14973 } else {
14974 Ordering::Less
14975 }
14976 }) {
14977 Ok(i) | Err(i) => i,
14978 };
14979
14980 ranges[start_ix..]
14981 .iter()
14982 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14983 })
14984 }
14985
14986 pub fn has_background_highlights<T: 'static>(&self) -> bool {
14987 self.background_highlights
14988 .get(&TypeId::of::<T>())
14989 .map_or(false, |(_, highlights)| !highlights.is_empty())
14990 }
14991
14992 pub fn background_highlights_in_range(
14993 &self,
14994 search_range: Range<Anchor>,
14995 display_snapshot: &DisplaySnapshot,
14996 theme: &ThemeColors,
14997 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14998 let mut results = Vec::new();
14999 for (color_fetcher, ranges) in self.background_highlights.values() {
15000 let color = color_fetcher(theme);
15001 let start_ix = match ranges.binary_search_by(|probe| {
15002 let cmp = probe
15003 .end
15004 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15005 if cmp.is_gt() {
15006 Ordering::Greater
15007 } else {
15008 Ordering::Less
15009 }
15010 }) {
15011 Ok(i) | Err(i) => i,
15012 };
15013 for range in &ranges[start_ix..] {
15014 if range
15015 .start
15016 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15017 .is_ge()
15018 {
15019 break;
15020 }
15021
15022 let start = range.start.to_display_point(display_snapshot);
15023 let end = range.end.to_display_point(display_snapshot);
15024 results.push((start..end, color))
15025 }
15026 }
15027 results
15028 }
15029
15030 pub fn background_highlight_row_ranges<T: 'static>(
15031 &self,
15032 search_range: Range<Anchor>,
15033 display_snapshot: &DisplaySnapshot,
15034 count: usize,
15035 ) -> Vec<RangeInclusive<DisplayPoint>> {
15036 let mut results = Vec::new();
15037 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15038 return vec![];
15039 };
15040
15041 let start_ix = match ranges.binary_search_by(|probe| {
15042 let cmp = probe
15043 .end
15044 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15045 if cmp.is_gt() {
15046 Ordering::Greater
15047 } else {
15048 Ordering::Less
15049 }
15050 }) {
15051 Ok(i) | Err(i) => i,
15052 };
15053 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15054 if let (Some(start_display), Some(end_display)) = (start, end) {
15055 results.push(
15056 start_display.to_display_point(display_snapshot)
15057 ..=end_display.to_display_point(display_snapshot),
15058 );
15059 }
15060 };
15061 let mut start_row: Option<Point> = None;
15062 let mut end_row: Option<Point> = None;
15063 if ranges.len() > count {
15064 return Vec::new();
15065 }
15066 for range in &ranges[start_ix..] {
15067 if range
15068 .start
15069 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15070 .is_ge()
15071 {
15072 break;
15073 }
15074 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15075 if let Some(current_row) = &end_row {
15076 if end.row == current_row.row {
15077 continue;
15078 }
15079 }
15080 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15081 if start_row.is_none() {
15082 assert_eq!(end_row, None);
15083 start_row = Some(start);
15084 end_row = Some(end);
15085 continue;
15086 }
15087 if let Some(current_end) = end_row.as_mut() {
15088 if start.row > current_end.row + 1 {
15089 push_region(start_row, end_row);
15090 start_row = Some(start);
15091 end_row = Some(end);
15092 } else {
15093 // Merge two hunks.
15094 *current_end = end;
15095 }
15096 } else {
15097 unreachable!();
15098 }
15099 }
15100 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15101 push_region(start_row, end_row);
15102 results
15103 }
15104
15105 pub fn gutter_highlights_in_range(
15106 &self,
15107 search_range: Range<Anchor>,
15108 display_snapshot: &DisplaySnapshot,
15109 cx: &App,
15110 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15111 let mut results = Vec::new();
15112 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15113 let color = color_fetcher(cx);
15114 let start_ix = match ranges.binary_search_by(|probe| {
15115 let cmp = probe
15116 .end
15117 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15118 if cmp.is_gt() {
15119 Ordering::Greater
15120 } else {
15121 Ordering::Less
15122 }
15123 }) {
15124 Ok(i) | Err(i) => i,
15125 };
15126 for range in &ranges[start_ix..] {
15127 if range
15128 .start
15129 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15130 .is_ge()
15131 {
15132 break;
15133 }
15134
15135 let start = range.start.to_display_point(display_snapshot);
15136 let end = range.end.to_display_point(display_snapshot);
15137 results.push((start..end, color))
15138 }
15139 }
15140 results
15141 }
15142
15143 /// Get the text ranges corresponding to the redaction query
15144 pub fn redacted_ranges(
15145 &self,
15146 search_range: Range<Anchor>,
15147 display_snapshot: &DisplaySnapshot,
15148 cx: &App,
15149 ) -> Vec<Range<DisplayPoint>> {
15150 display_snapshot
15151 .buffer_snapshot
15152 .redacted_ranges(search_range, |file| {
15153 if let Some(file) = file {
15154 file.is_private()
15155 && EditorSettings::get(
15156 Some(SettingsLocation {
15157 worktree_id: file.worktree_id(cx),
15158 path: file.path().as_ref(),
15159 }),
15160 cx,
15161 )
15162 .redact_private_values
15163 } else {
15164 false
15165 }
15166 })
15167 .map(|range| {
15168 range.start.to_display_point(display_snapshot)
15169 ..range.end.to_display_point(display_snapshot)
15170 })
15171 .collect()
15172 }
15173
15174 pub fn highlight_text<T: 'static>(
15175 &mut self,
15176 ranges: Vec<Range<Anchor>>,
15177 style: HighlightStyle,
15178 cx: &mut Context<Self>,
15179 ) {
15180 self.display_map.update(cx, |map, _| {
15181 map.highlight_text(TypeId::of::<T>(), ranges, style)
15182 });
15183 cx.notify();
15184 }
15185
15186 pub(crate) fn highlight_inlays<T: 'static>(
15187 &mut self,
15188 highlights: Vec<InlayHighlight>,
15189 style: HighlightStyle,
15190 cx: &mut Context<Self>,
15191 ) {
15192 self.display_map.update(cx, |map, _| {
15193 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15194 });
15195 cx.notify();
15196 }
15197
15198 pub fn text_highlights<'a, T: 'static>(
15199 &'a self,
15200 cx: &'a App,
15201 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15202 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15203 }
15204
15205 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15206 let cleared = self
15207 .display_map
15208 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15209 if cleared {
15210 cx.notify();
15211 }
15212 }
15213
15214 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15215 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15216 && self.focus_handle.is_focused(window)
15217 }
15218
15219 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15220 self.show_cursor_when_unfocused = is_enabled;
15221 cx.notify();
15222 }
15223
15224 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15225 cx.notify();
15226 }
15227
15228 fn on_buffer_event(
15229 &mut self,
15230 multibuffer: &Entity<MultiBuffer>,
15231 event: &multi_buffer::Event,
15232 window: &mut Window,
15233 cx: &mut Context<Self>,
15234 ) {
15235 match event {
15236 multi_buffer::Event::Edited {
15237 singleton_buffer_edited,
15238 edited_buffer: buffer_edited,
15239 } => {
15240 self.scrollbar_marker_state.dirty = true;
15241 self.active_indent_guides_state.dirty = true;
15242 self.refresh_active_diagnostics(cx);
15243 self.refresh_code_actions(window, cx);
15244 if self.has_active_inline_completion() {
15245 self.update_visible_inline_completion(window, cx);
15246 }
15247 if let Some(buffer) = buffer_edited {
15248 let buffer_id = buffer.read(cx).remote_id();
15249 if !self.registered_buffers.contains_key(&buffer_id) {
15250 if let Some(project) = self.project.as_ref() {
15251 project.update(cx, |project, cx| {
15252 self.registered_buffers.insert(
15253 buffer_id,
15254 project.register_buffer_with_language_servers(&buffer, cx),
15255 );
15256 })
15257 }
15258 }
15259 }
15260 cx.emit(EditorEvent::BufferEdited);
15261 cx.emit(SearchEvent::MatchesInvalidated);
15262 if *singleton_buffer_edited {
15263 if let Some(project) = &self.project {
15264 #[allow(clippy::mutable_key_type)]
15265 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15266 multibuffer
15267 .all_buffers()
15268 .into_iter()
15269 .filter_map(|buffer| {
15270 buffer.update(cx, |buffer, cx| {
15271 let language = buffer.language()?;
15272 let should_discard = project.update(cx, |project, cx| {
15273 project.is_local()
15274 && !project.has_language_servers_for(buffer, cx)
15275 });
15276 should_discard.not().then_some(language.clone())
15277 })
15278 })
15279 .collect::<HashSet<_>>()
15280 });
15281 if !languages_affected.is_empty() {
15282 self.refresh_inlay_hints(
15283 InlayHintRefreshReason::BufferEdited(languages_affected),
15284 cx,
15285 );
15286 }
15287 }
15288 }
15289
15290 let Some(project) = &self.project else { return };
15291 let (telemetry, is_via_ssh) = {
15292 let project = project.read(cx);
15293 let telemetry = project.client().telemetry().clone();
15294 let is_via_ssh = project.is_via_ssh();
15295 (telemetry, is_via_ssh)
15296 };
15297 refresh_linked_ranges(self, window, cx);
15298 telemetry.log_edit_event("editor", is_via_ssh);
15299 }
15300 multi_buffer::Event::ExcerptsAdded {
15301 buffer,
15302 predecessor,
15303 excerpts,
15304 } => {
15305 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15306 let buffer_id = buffer.read(cx).remote_id();
15307 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15308 if let Some(project) = &self.project {
15309 get_uncommitted_diff_for_buffer(
15310 project,
15311 [buffer.clone()],
15312 self.buffer.clone(),
15313 cx,
15314 )
15315 .detach();
15316 }
15317 }
15318 cx.emit(EditorEvent::ExcerptsAdded {
15319 buffer: buffer.clone(),
15320 predecessor: *predecessor,
15321 excerpts: excerpts.clone(),
15322 });
15323 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15324 }
15325 multi_buffer::Event::ExcerptsRemoved { ids } => {
15326 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15327 let buffer = self.buffer.read(cx);
15328 self.registered_buffers
15329 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15330 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15331 }
15332 multi_buffer::Event::ExcerptsEdited {
15333 excerpt_ids,
15334 buffer_ids,
15335 } => {
15336 self.display_map.update(cx, |map, cx| {
15337 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15338 });
15339 cx.emit(EditorEvent::ExcerptsEdited {
15340 ids: excerpt_ids.clone(),
15341 })
15342 }
15343 multi_buffer::Event::ExcerptsExpanded { ids } => {
15344 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15345 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15346 }
15347 multi_buffer::Event::Reparsed(buffer_id) => {
15348 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15349
15350 cx.emit(EditorEvent::Reparsed(*buffer_id));
15351 }
15352 multi_buffer::Event::DiffHunksToggled => {
15353 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15354 }
15355 multi_buffer::Event::LanguageChanged(buffer_id) => {
15356 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15357 cx.emit(EditorEvent::Reparsed(*buffer_id));
15358 cx.notify();
15359 }
15360 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15361 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15362 multi_buffer::Event::FileHandleChanged
15363 | multi_buffer::Event::Reloaded
15364 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15365 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15366 multi_buffer::Event::DiagnosticsUpdated => {
15367 self.refresh_active_diagnostics(cx);
15368 self.refresh_inline_diagnostics(true, window, cx);
15369 self.scrollbar_marker_state.dirty = true;
15370 cx.notify();
15371 }
15372 _ => {}
15373 };
15374 }
15375
15376 fn on_display_map_changed(
15377 &mut self,
15378 _: Entity<DisplayMap>,
15379 _: &mut Window,
15380 cx: &mut Context<Self>,
15381 ) {
15382 cx.notify();
15383 }
15384
15385 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15386 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15387 self.update_edit_prediction_settings(cx);
15388 self.refresh_inline_completion(true, false, window, cx);
15389 self.refresh_inlay_hints(
15390 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15391 self.selections.newest_anchor().head(),
15392 &self.buffer.read(cx).snapshot(cx),
15393 cx,
15394 )),
15395 cx,
15396 );
15397
15398 let old_cursor_shape = self.cursor_shape;
15399
15400 {
15401 let editor_settings = EditorSettings::get_global(cx);
15402 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15403 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15404 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15405 }
15406
15407 if old_cursor_shape != self.cursor_shape {
15408 cx.emit(EditorEvent::CursorShapeChanged);
15409 }
15410
15411 let project_settings = ProjectSettings::get_global(cx);
15412 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15413
15414 if self.mode == EditorMode::Full {
15415 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15416 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15417 if self.show_inline_diagnostics != show_inline_diagnostics {
15418 self.show_inline_diagnostics = show_inline_diagnostics;
15419 self.refresh_inline_diagnostics(false, window, cx);
15420 }
15421
15422 if self.git_blame_inline_enabled != inline_blame_enabled {
15423 self.toggle_git_blame_inline_internal(false, window, cx);
15424 }
15425 }
15426
15427 cx.notify();
15428 }
15429
15430 pub fn set_searchable(&mut self, searchable: bool) {
15431 self.searchable = searchable;
15432 }
15433
15434 pub fn searchable(&self) -> bool {
15435 self.searchable
15436 }
15437
15438 fn open_proposed_changes_editor(
15439 &mut self,
15440 _: &OpenProposedChangesEditor,
15441 window: &mut Window,
15442 cx: &mut Context<Self>,
15443 ) {
15444 let Some(workspace) = self.workspace() else {
15445 cx.propagate();
15446 return;
15447 };
15448
15449 let selections = self.selections.all::<usize>(cx);
15450 let multi_buffer = self.buffer.read(cx);
15451 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15452 let mut new_selections_by_buffer = HashMap::default();
15453 for selection in selections {
15454 for (buffer, range, _) in
15455 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15456 {
15457 let mut range = range.to_point(buffer);
15458 range.start.column = 0;
15459 range.end.column = buffer.line_len(range.end.row);
15460 new_selections_by_buffer
15461 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15462 .or_insert(Vec::new())
15463 .push(range)
15464 }
15465 }
15466
15467 let proposed_changes_buffers = new_selections_by_buffer
15468 .into_iter()
15469 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15470 .collect::<Vec<_>>();
15471 let proposed_changes_editor = cx.new(|cx| {
15472 ProposedChangesEditor::new(
15473 "Proposed changes",
15474 proposed_changes_buffers,
15475 self.project.clone(),
15476 window,
15477 cx,
15478 )
15479 });
15480
15481 window.defer(cx, move |window, cx| {
15482 workspace.update(cx, |workspace, cx| {
15483 workspace.active_pane().update(cx, |pane, cx| {
15484 pane.add_item(
15485 Box::new(proposed_changes_editor),
15486 true,
15487 true,
15488 None,
15489 window,
15490 cx,
15491 );
15492 });
15493 });
15494 });
15495 }
15496
15497 pub fn open_excerpts_in_split(
15498 &mut self,
15499 _: &OpenExcerptsSplit,
15500 window: &mut Window,
15501 cx: &mut Context<Self>,
15502 ) {
15503 self.open_excerpts_common(None, true, window, cx)
15504 }
15505
15506 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15507 self.open_excerpts_common(None, false, window, cx)
15508 }
15509
15510 fn open_excerpts_common(
15511 &mut self,
15512 jump_data: Option<JumpData>,
15513 split: bool,
15514 window: &mut Window,
15515 cx: &mut Context<Self>,
15516 ) {
15517 let Some(workspace) = self.workspace() else {
15518 cx.propagate();
15519 return;
15520 };
15521
15522 if self.buffer.read(cx).is_singleton() {
15523 cx.propagate();
15524 return;
15525 }
15526
15527 let mut new_selections_by_buffer = HashMap::default();
15528 match &jump_data {
15529 Some(JumpData::MultiBufferPoint {
15530 excerpt_id,
15531 position,
15532 anchor,
15533 line_offset_from_top,
15534 }) => {
15535 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15536 if let Some(buffer) = multi_buffer_snapshot
15537 .buffer_id_for_excerpt(*excerpt_id)
15538 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15539 {
15540 let buffer_snapshot = buffer.read(cx).snapshot();
15541 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15542 language::ToPoint::to_point(anchor, &buffer_snapshot)
15543 } else {
15544 buffer_snapshot.clip_point(*position, Bias::Left)
15545 };
15546 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15547 new_selections_by_buffer.insert(
15548 buffer,
15549 (
15550 vec![jump_to_offset..jump_to_offset],
15551 Some(*line_offset_from_top),
15552 ),
15553 );
15554 }
15555 }
15556 Some(JumpData::MultiBufferRow {
15557 row,
15558 line_offset_from_top,
15559 }) => {
15560 let point = MultiBufferPoint::new(row.0, 0);
15561 if let Some((buffer, buffer_point, _)) =
15562 self.buffer.read(cx).point_to_buffer_point(point, cx)
15563 {
15564 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15565 new_selections_by_buffer
15566 .entry(buffer)
15567 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15568 .0
15569 .push(buffer_offset..buffer_offset)
15570 }
15571 }
15572 None => {
15573 let selections = self.selections.all::<usize>(cx);
15574 let multi_buffer = self.buffer.read(cx);
15575 for selection in selections {
15576 for (snapshot, range, _, anchor) in multi_buffer
15577 .snapshot(cx)
15578 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15579 {
15580 if let Some(anchor) = anchor {
15581 // selection is in a deleted hunk
15582 let Some(buffer_id) = anchor.buffer_id else {
15583 continue;
15584 };
15585 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15586 continue;
15587 };
15588 let offset = text::ToOffset::to_offset(
15589 &anchor.text_anchor,
15590 &buffer_handle.read(cx).snapshot(),
15591 );
15592 let range = offset..offset;
15593 new_selections_by_buffer
15594 .entry(buffer_handle)
15595 .or_insert((Vec::new(), None))
15596 .0
15597 .push(range)
15598 } else {
15599 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15600 else {
15601 continue;
15602 };
15603 new_selections_by_buffer
15604 .entry(buffer_handle)
15605 .or_insert((Vec::new(), None))
15606 .0
15607 .push(range)
15608 }
15609 }
15610 }
15611 }
15612 }
15613
15614 if new_selections_by_buffer.is_empty() {
15615 return;
15616 }
15617
15618 // We defer the pane interaction because we ourselves are a workspace item
15619 // and activating a new item causes the pane to call a method on us reentrantly,
15620 // which panics if we're on the stack.
15621 window.defer(cx, move |window, cx| {
15622 workspace.update(cx, |workspace, cx| {
15623 let pane = if split {
15624 workspace.adjacent_pane(window, cx)
15625 } else {
15626 workspace.active_pane().clone()
15627 };
15628
15629 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15630 let editor = buffer
15631 .read(cx)
15632 .file()
15633 .is_none()
15634 .then(|| {
15635 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15636 // so `workspace.open_project_item` will never find them, always opening a new editor.
15637 // Instead, we try to activate the existing editor in the pane first.
15638 let (editor, pane_item_index) =
15639 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15640 let editor = item.downcast::<Editor>()?;
15641 let singleton_buffer =
15642 editor.read(cx).buffer().read(cx).as_singleton()?;
15643 if singleton_buffer == buffer {
15644 Some((editor, i))
15645 } else {
15646 None
15647 }
15648 })?;
15649 pane.update(cx, |pane, cx| {
15650 pane.activate_item(pane_item_index, true, true, window, cx)
15651 });
15652 Some(editor)
15653 })
15654 .flatten()
15655 .unwrap_or_else(|| {
15656 workspace.open_project_item::<Self>(
15657 pane.clone(),
15658 buffer,
15659 true,
15660 true,
15661 window,
15662 cx,
15663 )
15664 });
15665
15666 editor.update(cx, |editor, cx| {
15667 let autoscroll = match scroll_offset {
15668 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15669 None => Autoscroll::newest(),
15670 };
15671 let nav_history = editor.nav_history.take();
15672 editor.change_selections(Some(autoscroll), window, cx, |s| {
15673 s.select_ranges(ranges);
15674 });
15675 editor.nav_history = nav_history;
15676 });
15677 }
15678 })
15679 });
15680 }
15681
15682 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15683 let snapshot = self.buffer.read(cx).read(cx);
15684 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15685 Some(
15686 ranges
15687 .iter()
15688 .map(move |range| {
15689 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15690 })
15691 .collect(),
15692 )
15693 }
15694
15695 fn selection_replacement_ranges(
15696 &self,
15697 range: Range<OffsetUtf16>,
15698 cx: &mut App,
15699 ) -> Vec<Range<OffsetUtf16>> {
15700 let selections = self.selections.all::<OffsetUtf16>(cx);
15701 let newest_selection = selections
15702 .iter()
15703 .max_by_key(|selection| selection.id)
15704 .unwrap();
15705 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15706 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15707 let snapshot = self.buffer.read(cx).read(cx);
15708 selections
15709 .into_iter()
15710 .map(|mut selection| {
15711 selection.start.0 =
15712 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15713 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15714 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15715 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15716 })
15717 .collect()
15718 }
15719
15720 fn report_editor_event(
15721 &self,
15722 event_type: &'static str,
15723 file_extension: Option<String>,
15724 cx: &App,
15725 ) {
15726 if cfg!(any(test, feature = "test-support")) {
15727 return;
15728 }
15729
15730 let Some(project) = &self.project else { return };
15731
15732 // If None, we are in a file without an extension
15733 let file = self
15734 .buffer
15735 .read(cx)
15736 .as_singleton()
15737 .and_then(|b| b.read(cx).file());
15738 let file_extension = file_extension.or(file
15739 .as_ref()
15740 .and_then(|file| Path::new(file.file_name(cx)).extension())
15741 .and_then(|e| e.to_str())
15742 .map(|a| a.to_string()));
15743
15744 let vim_mode = cx
15745 .global::<SettingsStore>()
15746 .raw_user_settings()
15747 .get("vim_mode")
15748 == Some(&serde_json::Value::Bool(true));
15749
15750 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15751 let copilot_enabled = edit_predictions_provider
15752 == language::language_settings::EditPredictionProvider::Copilot;
15753 let copilot_enabled_for_language = self
15754 .buffer
15755 .read(cx)
15756 .settings_at(0, cx)
15757 .show_edit_predictions;
15758
15759 let project = project.read(cx);
15760 telemetry::event!(
15761 event_type,
15762 file_extension,
15763 vim_mode,
15764 copilot_enabled,
15765 copilot_enabled_for_language,
15766 edit_predictions_provider,
15767 is_via_ssh = project.is_via_ssh(),
15768 );
15769 }
15770
15771 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15772 /// with each line being an array of {text, highlight} objects.
15773 fn copy_highlight_json(
15774 &mut self,
15775 _: &CopyHighlightJson,
15776 window: &mut Window,
15777 cx: &mut Context<Self>,
15778 ) {
15779 #[derive(Serialize)]
15780 struct Chunk<'a> {
15781 text: String,
15782 highlight: Option<&'a str>,
15783 }
15784
15785 let snapshot = self.buffer.read(cx).snapshot(cx);
15786 let range = self
15787 .selected_text_range(false, window, cx)
15788 .and_then(|selection| {
15789 if selection.range.is_empty() {
15790 None
15791 } else {
15792 Some(selection.range)
15793 }
15794 })
15795 .unwrap_or_else(|| 0..snapshot.len());
15796
15797 let chunks = snapshot.chunks(range, true);
15798 let mut lines = Vec::new();
15799 let mut line: VecDeque<Chunk> = VecDeque::new();
15800
15801 let Some(style) = self.style.as_ref() else {
15802 return;
15803 };
15804
15805 for chunk in chunks {
15806 let highlight = chunk
15807 .syntax_highlight_id
15808 .and_then(|id| id.name(&style.syntax));
15809 let mut chunk_lines = chunk.text.split('\n').peekable();
15810 while let Some(text) = chunk_lines.next() {
15811 let mut merged_with_last_token = false;
15812 if let Some(last_token) = line.back_mut() {
15813 if last_token.highlight == highlight {
15814 last_token.text.push_str(text);
15815 merged_with_last_token = true;
15816 }
15817 }
15818
15819 if !merged_with_last_token {
15820 line.push_back(Chunk {
15821 text: text.into(),
15822 highlight,
15823 });
15824 }
15825
15826 if chunk_lines.peek().is_some() {
15827 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15828 line.pop_front();
15829 }
15830 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15831 line.pop_back();
15832 }
15833
15834 lines.push(mem::take(&mut line));
15835 }
15836 }
15837 }
15838
15839 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15840 return;
15841 };
15842 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15843 }
15844
15845 pub fn open_context_menu(
15846 &mut self,
15847 _: &OpenContextMenu,
15848 window: &mut Window,
15849 cx: &mut Context<Self>,
15850 ) {
15851 self.request_autoscroll(Autoscroll::newest(), cx);
15852 let position = self.selections.newest_display(cx).start;
15853 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15854 }
15855
15856 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15857 &self.inlay_hint_cache
15858 }
15859
15860 pub fn replay_insert_event(
15861 &mut self,
15862 text: &str,
15863 relative_utf16_range: Option<Range<isize>>,
15864 window: &mut Window,
15865 cx: &mut Context<Self>,
15866 ) {
15867 if !self.input_enabled {
15868 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15869 return;
15870 }
15871 if let Some(relative_utf16_range) = relative_utf16_range {
15872 let selections = self.selections.all::<OffsetUtf16>(cx);
15873 self.change_selections(None, window, cx, |s| {
15874 let new_ranges = selections.into_iter().map(|range| {
15875 let start = OffsetUtf16(
15876 range
15877 .head()
15878 .0
15879 .saturating_add_signed(relative_utf16_range.start),
15880 );
15881 let end = OffsetUtf16(
15882 range
15883 .head()
15884 .0
15885 .saturating_add_signed(relative_utf16_range.end),
15886 );
15887 start..end
15888 });
15889 s.select_ranges(new_ranges);
15890 });
15891 }
15892
15893 self.handle_input(text, window, cx);
15894 }
15895
15896 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15897 let Some(provider) = self.semantics_provider.as_ref() else {
15898 return false;
15899 };
15900
15901 let mut supports = false;
15902 self.buffer().update(cx, |this, cx| {
15903 this.for_each_buffer(|buffer| {
15904 supports |= provider.supports_inlay_hints(buffer, cx);
15905 });
15906 });
15907
15908 supports
15909 }
15910
15911 pub fn is_focused(&self, window: &Window) -> bool {
15912 self.focus_handle.is_focused(window)
15913 }
15914
15915 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15916 cx.emit(EditorEvent::Focused);
15917
15918 if let Some(descendant) = self
15919 .last_focused_descendant
15920 .take()
15921 .and_then(|descendant| descendant.upgrade())
15922 {
15923 window.focus(&descendant);
15924 } else {
15925 if let Some(blame) = self.blame.as_ref() {
15926 blame.update(cx, GitBlame::focus)
15927 }
15928
15929 self.blink_manager.update(cx, BlinkManager::enable);
15930 self.show_cursor_names(window, cx);
15931 self.buffer.update(cx, |buffer, cx| {
15932 buffer.finalize_last_transaction(cx);
15933 if self.leader_peer_id.is_none() {
15934 buffer.set_active_selections(
15935 &self.selections.disjoint_anchors(),
15936 self.selections.line_mode,
15937 self.cursor_shape,
15938 cx,
15939 );
15940 }
15941 });
15942 }
15943 }
15944
15945 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15946 cx.emit(EditorEvent::FocusedIn)
15947 }
15948
15949 fn handle_focus_out(
15950 &mut self,
15951 event: FocusOutEvent,
15952 _window: &mut Window,
15953 cx: &mut Context<Self>,
15954 ) {
15955 if event.blurred != self.focus_handle {
15956 self.last_focused_descendant = Some(event.blurred);
15957 }
15958 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
15959 }
15960
15961 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15962 self.blink_manager.update(cx, BlinkManager::disable);
15963 self.buffer
15964 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15965
15966 if let Some(blame) = self.blame.as_ref() {
15967 blame.update(cx, GitBlame::blur)
15968 }
15969 if !self.hover_state.focused(window, cx) {
15970 hide_hover(self, cx);
15971 }
15972 if !self
15973 .context_menu
15974 .borrow()
15975 .as_ref()
15976 .is_some_and(|context_menu| context_menu.focused(window, cx))
15977 {
15978 self.hide_context_menu(window, cx);
15979 }
15980 self.discard_inline_completion(false, cx);
15981 cx.emit(EditorEvent::Blurred);
15982 cx.notify();
15983 }
15984
15985 pub fn register_action<A: Action>(
15986 &mut self,
15987 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15988 ) -> Subscription {
15989 let id = self.next_editor_action_id.post_inc();
15990 let listener = Arc::new(listener);
15991 self.editor_actions.borrow_mut().insert(
15992 id,
15993 Box::new(move |window, _| {
15994 let listener = listener.clone();
15995 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15996 let action = action.downcast_ref().unwrap();
15997 if phase == DispatchPhase::Bubble {
15998 listener(action, window, cx)
15999 }
16000 })
16001 }),
16002 );
16003
16004 let editor_actions = self.editor_actions.clone();
16005 Subscription::new(move || {
16006 editor_actions.borrow_mut().remove(&id);
16007 })
16008 }
16009
16010 pub fn file_header_size(&self) -> u32 {
16011 FILE_HEADER_HEIGHT
16012 }
16013
16014 pub fn restore(
16015 &mut self,
16016 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16017 window: &mut Window,
16018 cx: &mut Context<Self>,
16019 ) {
16020 let workspace = self.workspace();
16021 let project = self.project.as_ref();
16022 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16023 let mut tasks = Vec::new();
16024 for (buffer_id, changes) in revert_changes {
16025 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16026 buffer.update(cx, |buffer, cx| {
16027 buffer.edit(
16028 changes
16029 .into_iter()
16030 .map(|(range, text)| (range, text.to_string())),
16031 None,
16032 cx,
16033 );
16034 });
16035
16036 if let Some(project) =
16037 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16038 {
16039 project.update(cx, |project, cx| {
16040 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16041 })
16042 }
16043 }
16044 }
16045 tasks
16046 });
16047 cx.spawn_in(window, |_, mut cx| async move {
16048 for (buffer, task) in save_tasks {
16049 let result = task.await;
16050 if result.is_err() {
16051 let Some(path) = buffer
16052 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16053 .ok()
16054 else {
16055 continue;
16056 };
16057 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16058 let Some(task) = cx
16059 .update_window_entity(&workspace, |workspace, window, cx| {
16060 workspace
16061 .open_path_preview(path, None, false, false, false, window, cx)
16062 })
16063 .ok()
16064 else {
16065 continue;
16066 };
16067 task.await.log_err();
16068 }
16069 }
16070 }
16071 })
16072 .detach();
16073 self.change_selections(None, window, cx, |selections| selections.refresh());
16074 }
16075
16076 pub fn to_pixel_point(
16077 &self,
16078 source: multi_buffer::Anchor,
16079 editor_snapshot: &EditorSnapshot,
16080 window: &mut Window,
16081 ) -> Option<gpui::Point<Pixels>> {
16082 let source_point = source.to_display_point(editor_snapshot);
16083 self.display_to_pixel_point(source_point, editor_snapshot, window)
16084 }
16085
16086 pub fn display_to_pixel_point(
16087 &self,
16088 source: DisplayPoint,
16089 editor_snapshot: &EditorSnapshot,
16090 window: &mut Window,
16091 ) -> Option<gpui::Point<Pixels>> {
16092 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16093 let text_layout_details = self.text_layout_details(window);
16094 let scroll_top = text_layout_details
16095 .scroll_anchor
16096 .scroll_position(editor_snapshot)
16097 .y;
16098
16099 if source.row().as_f32() < scroll_top.floor() {
16100 return None;
16101 }
16102 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16103 let source_y = line_height * (source.row().as_f32() - scroll_top);
16104 Some(gpui::Point::new(source_x, source_y))
16105 }
16106
16107 pub fn has_visible_completions_menu(&self) -> bool {
16108 !self.edit_prediction_preview_is_active()
16109 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16110 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16111 })
16112 }
16113
16114 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16115 self.addons
16116 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16117 }
16118
16119 pub fn unregister_addon<T: Addon>(&mut self) {
16120 self.addons.remove(&std::any::TypeId::of::<T>());
16121 }
16122
16123 pub fn addon<T: Addon>(&self) -> Option<&T> {
16124 let type_id = std::any::TypeId::of::<T>();
16125 self.addons
16126 .get(&type_id)
16127 .and_then(|item| item.to_any().downcast_ref::<T>())
16128 }
16129
16130 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16131 let text_layout_details = self.text_layout_details(window);
16132 let style = &text_layout_details.editor_style;
16133 let font_id = window.text_system().resolve_font(&style.text.font());
16134 let font_size = style.text.font_size.to_pixels(window.rem_size());
16135 let line_height = style.text.line_height_in_pixels(window.rem_size());
16136 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16137
16138 gpui::Size::new(em_width, line_height)
16139 }
16140
16141 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16142 self.load_diff_task.clone()
16143 }
16144
16145 fn read_selections_from_db(
16146 &mut self,
16147 item_id: u64,
16148 workspace_id: WorkspaceId,
16149 window: &mut Window,
16150 cx: &mut Context<Editor>,
16151 ) {
16152 if !self.is_singleton(cx)
16153 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16154 {
16155 return;
16156 }
16157 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16158 return;
16159 };
16160 if selections.is_empty() {
16161 return;
16162 }
16163
16164 let snapshot = self.buffer.read(cx).snapshot(cx);
16165 self.change_selections(None, window, cx, |s| {
16166 s.select_ranges(selections.into_iter().map(|(start, end)| {
16167 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16168 }));
16169 });
16170 }
16171}
16172
16173fn insert_extra_newline_brackets(
16174 buffer: &MultiBufferSnapshot,
16175 range: Range<usize>,
16176 language: &language::LanguageScope,
16177) -> bool {
16178 let leading_whitespace_len = buffer
16179 .reversed_chars_at(range.start)
16180 .take_while(|c| c.is_whitespace() && *c != '\n')
16181 .map(|c| c.len_utf8())
16182 .sum::<usize>();
16183 let trailing_whitespace_len = buffer
16184 .chars_at(range.end)
16185 .take_while(|c| c.is_whitespace() && *c != '\n')
16186 .map(|c| c.len_utf8())
16187 .sum::<usize>();
16188 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16189
16190 language.brackets().any(|(pair, enabled)| {
16191 let pair_start = pair.start.trim_end();
16192 let pair_end = pair.end.trim_start();
16193
16194 enabled
16195 && pair.newline
16196 && buffer.contains_str_at(range.end, pair_end)
16197 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16198 })
16199}
16200
16201fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16202 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16203 [(buffer, range, _)] => (*buffer, range.clone()),
16204 _ => return false,
16205 };
16206 let pair = {
16207 let mut result: Option<BracketMatch> = None;
16208
16209 for pair in buffer
16210 .all_bracket_ranges(range.clone())
16211 .filter(move |pair| {
16212 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16213 })
16214 {
16215 let len = pair.close_range.end - pair.open_range.start;
16216
16217 if let Some(existing) = &result {
16218 let existing_len = existing.close_range.end - existing.open_range.start;
16219 if len > existing_len {
16220 continue;
16221 }
16222 }
16223
16224 result = Some(pair);
16225 }
16226
16227 result
16228 };
16229 let Some(pair) = pair else {
16230 return false;
16231 };
16232 pair.newline_only
16233 && buffer
16234 .chars_for_range(pair.open_range.end..range.start)
16235 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16236 .all(|c| c.is_whitespace() && c != '\n')
16237}
16238
16239fn get_uncommitted_diff_for_buffer(
16240 project: &Entity<Project>,
16241 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16242 buffer: Entity<MultiBuffer>,
16243 cx: &mut App,
16244) -> Task<()> {
16245 let mut tasks = Vec::new();
16246 project.update(cx, |project, cx| {
16247 for buffer in buffers {
16248 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16249 }
16250 });
16251 cx.spawn(|mut cx| async move {
16252 let diffs = future::join_all(tasks).await;
16253 buffer
16254 .update(&mut cx, |buffer, cx| {
16255 for diff in diffs.into_iter().flatten() {
16256 buffer.add_diff(diff, cx);
16257 }
16258 })
16259 .ok();
16260 })
16261}
16262
16263fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16264 let tab_size = tab_size.get() as usize;
16265 let mut width = offset;
16266
16267 for ch in text.chars() {
16268 width += if ch == '\t' {
16269 tab_size - (width % tab_size)
16270 } else {
16271 1
16272 };
16273 }
16274
16275 width - offset
16276}
16277
16278#[cfg(test)]
16279mod tests {
16280 use super::*;
16281
16282 #[test]
16283 fn test_string_size_with_expanded_tabs() {
16284 let nz = |val| NonZeroU32::new(val).unwrap();
16285 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16286 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16287 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16288 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16289 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16290 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16291 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16292 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16293 }
16294}
16295
16296/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16297struct WordBreakingTokenizer<'a> {
16298 input: &'a str,
16299}
16300
16301impl<'a> WordBreakingTokenizer<'a> {
16302 fn new(input: &'a str) -> Self {
16303 Self { input }
16304 }
16305}
16306
16307fn is_char_ideographic(ch: char) -> bool {
16308 use unicode_script::Script::*;
16309 use unicode_script::UnicodeScript;
16310 matches!(ch.script(), Han | Tangut | Yi)
16311}
16312
16313fn is_grapheme_ideographic(text: &str) -> bool {
16314 text.chars().any(is_char_ideographic)
16315}
16316
16317fn is_grapheme_whitespace(text: &str) -> bool {
16318 text.chars().any(|x| x.is_whitespace())
16319}
16320
16321fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16322 text.chars().next().map_or(false, |ch| {
16323 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16324 })
16325}
16326
16327#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16328struct WordBreakToken<'a> {
16329 token: &'a str,
16330 grapheme_len: usize,
16331 is_whitespace: bool,
16332}
16333
16334impl<'a> Iterator for WordBreakingTokenizer<'a> {
16335 /// Yields a span, the count of graphemes in the token, and whether it was
16336 /// whitespace. Note that it also breaks at word boundaries.
16337 type Item = WordBreakToken<'a>;
16338
16339 fn next(&mut self) -> Option<Self::Item> {
16340 use unicode_segmentation::UnicodeSegmentation;
16341 if self.input.is_empty() {
16342 return None;
16343 }
16344
16345 let mut iter = self.input.graphemes(true).peekable();
16346 let mut offset = 0;
16347 let mut graphemes = 0;
16348 if let Some(first_grapheme) = iter.next() {
16349 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16350 offset += first_grapheme.len();
16351 graphemes += 1;
16352 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16353 if let Some(grapheme) = iter.peek().copied() {
16354 if should_stay_with_preceding_ideograph(grapheme) {
16355 offset += grapheme.len();
16356 graphemes += 1;
16357 }
16358 }
16359 } else {
16360 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16361 let mut next_word_bound = words.peek().copied();
16362 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16363 next_word_bound = words.next();
16364 }
16365 while let Some(grapheme) = iter.peek().copied() {
16366 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16367 break;
16368 };
16369 if is_grapheme_whitespace(grapheme) != is_whitespace {
16370 break;
16371 };
16372 offset += grapheme.len();
16373 graphemes += 1;
16374 iter.next();
16375 }
16376 }
16377 let token = &self.input[..offset];
16378 self.input = &self.input[offset..];
16379 if is_whitespace {
16380 Some(WordBreakToken {
16381 token: " ",
16382 grapheme_len: 1,
16383 is_whitespace: true,
16384 })
16385 } else {
16386 Some(WordBreakToken {
16387 token,
16388 grapheme_len: graphemes,
16389 is_whitespace: false,
16390 })
16391 }
16392 } else {
16393 None
16394 }
16395 }
16396}
16397
16398#[test]
16399fn test_word_breaking_tokenizer() {
16400 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16401 ("", &[]),
16402 (" ", &[(" ", 1, true)]),
16403 ("Ʒ", &[("Ʒ", 1, false)]),
16404 ("Ǽ", &[("Ǽ", 1, false)]),
16405 ("⋑", &[("⋑", 1, false)]),
16406 ("⋑⋑", &[("⋑⋑", 2, false)]),
16407 (
16408 "原理,进而",
16409 &[
16410 ("原", 1, false),
16411 ("理,", 2, false),
16412 ("进", 1, false),
16413 ("而", 1, false),
16414 ],
16415 ),
16416 (
16417 "hello world",
16418 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16419 ),
16420 (
16421 "hello, world",
16422 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16423 ),
16424 (
16425 " hello world",
16426 &[
16427 (" ", 1, true),
16428 ("hello", 5, false),
16429 (" ", 1, true),
16430 ("world", 5, false),
16431 ],
16432 ),
16433 (
16434 "这是什么 \n 钢笔",
16435 &[
16436 ("这", 1, false),
16437 ("是", 1, false),
16438 ("什", 1, false),
16439 ("么", 1, false),
16440 (" ", 1, true),
16441 ("钢", 1, false),
16442 ("笔", 1, false),
16443 ],
16444 ),
16445 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16446 ];
16447
16448 for (input, result) in tests {
16449 assert_eq!(
16450 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16451 result
16452 .iter()
16453 .copied()
16454 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16455 token,
16456 grapheme_len,
16457 is_whitespace,
16458 })
16459 .collect::<Vec<_>>()
16460 );
16461 }
16462}
16463
16464fn wrap_with_prefix(
16465 line_prefix: String,
16466 unwrapped_text: String,
16467 wrap_column: usize,
16468 tab_size: NonZeroU32,
16469) -> String {
16470 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16471 let mut wrapped_text = String::new();
16472 let mut current_line = line_prefix.clone();
16473
16474 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16475 let mut current_line_len = line_prefix_len;
16476 for WordBreakToken {
16477 token,
16478 grapheme_len,
16479 is_whitespace,
16480 } in tokenizer
16481 {
16482 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16483 wrapped_text.push_str(current_line.trim_end());
16484 wrapped_text.push('\n');
16485 current_line.truncate(line_prefix.len());
16486 current_line_len = line_prefix_len;
16487 if !is_whitespace {
16488 current_line.push_str(token);
16489 current_line_len += grapheme_len;
16490 }
16491 } else if !is_whitespace {
16492 current_line.push_str(token);
16493 current_line_len += grapheme_len;
16494 } else if current_line_len != line_prefix_len {
16495 current_line.push(' ');
16496 current_line_len += 1;
16497 }
16498 }
16499
16500 if !current_line.is_empty() {
16501 wrapped_text.push_str(¤t_line);
16502 }
16503 wrapped_text
16504}
16505
16506#[test]
16507fn test_wrap_with_prefix() {
16508 assert_eq!(
16509 wrap_with_prefix(
16510 "# ".to_string(),
16511 "abcdefg".to_string(),
16512 4,
16513 NonZeroU32::new(4).unwrap()
16514 ),
16515 "# abcdefg"
16516 );
16517 assert_eq!(
16518 wrap_with_prefix(
16519 "".to_string(),
16520 "\thello world".to_string(),
16521 8,
16522 NonZeroU32::new(4).unwrap()
16523 ),
16524 "hello\nworld"
16525 );
16526 assert_eq!(
16527 wrap_with_prefix(
16528 "// ".to_string(),
16529 "xx \nyy zz aa bb cc".to_string(),
16530 12,
16531 NonZeroU32::new(4).unwrap()
16532 ),
16533 "// xx yy zz\n// aa bb cc"
16534 );
16535 assert_eq!(
16536 wrap_with_prefix(
16537 String::new(),
16538 "这是什么 \n 钢笔".to_string(),
16539 3,
16540 NonZeroU32::new(4).unwrap()
16541 ),
16542 "这是什\n么 钢\n笔"
16543 );
16544}
16545
16546pub trait CollaborationHub {
16547 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16548 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16549 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16550}
16551
16552impl CollaborationHub for Entity<Project> {
16553 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16554 self.read(cx).collaborators()
16555 }
16556
16557 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16558 self.read(cx).user_store().read(cx).participant_indices()
16559 }
16560
16561 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16562 let this = self.read(cx);
16563 let user_ids = this.collaborators().values().map(|c| c.user_id);
16564 this.user_store().read_with(cx, |user_store, cx| {
16565 user_store.participant_names(user_ids, cx)
16566 })
16567 }
16568}
16569
16570pub trait SemanticsProvider {
16571 fn hover(
16572 &self,
16573 buffer: &Entity<Buffer>,
16574 position: text::Anchor,
16575 cx: &mut App,
16576 ) -> Option<Task<Vec<project::Hover>>>;
16577
16578 fn inlay_hints(
16579 &self,
16580 buffer_handle: Entity<Buffer>,
16581 range: Range<text::Anchor>,
16582 cx: &mut App,
16583 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16584
16585 fn resolve_inlay_hint(
16586 &self,
16587 hint: InlayHint,
16588 buffer_handle: Entity<Buffer>,
16589 server_id: LanguageServerId,
16590 cx: &mut App,
16591 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16592
16593 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16594
16595 fn document_highlights(
16596 &self,
16597 buffer: &Entity<Buffer>,
16598 position: text::Anchor,
16599 cx: &mut App,
16600 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16601
16602 fn definitions(
16603 &self,
16604 buffer: &Entity<Buffer>,
16605 position: text::Anchor,
16606 kind: GotoDefinitionKind,
16607 cx: &mut App,
16608 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16609
16610 fn range_for_rename(
16611 &self,
16612 buffer: &Entity<Buffer>,
16613 position: text::Anchor,
16614 cx: &mut App,
16615 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16616
16617 fn perform_rename(
16618 &self,
16619 buffer: &Entity<Buffer>,
16620 position: text::Anchor,
16621 new_name: String,
16622 cx: &mut App,
16623 ) -> Option<Task<Result<ProjectTransaction>>>;
16624}
16625
16626pub trait CompletionProvider {
16627 fn completions(
16628 &self,
16629 buffer: &Entity<Buffer>,
16630 buffer_position: text::Anchor,
16631 trigger: CompletionContext,
16632 window: &mut Window,
16633 cx: &mut Context<Editor>,
16634 ) -> Task<Result<Vec<Completion>>>;
16635
16636 fn resolve_completions(
16637 &self,
16638 buffer: Entity<Buffer>,
16639 completion_indices: Vec<usize>,
16640 completions: Rc<RefCell<Box<[Completion]>>>,
16641 cx: &mut Context<Editor>,
16642 ) -> Task<Result<bool>>;
16643
16644 fn apply_additional_edits_for_completion(
16645 &self,
16646 _buffer: Entity<Buffer>,
16647 _completions: Rc<RefCell<Box<[Completion]>>>,
16648 _completion_index: usize,
16649 _push_to_history: bool,
16650 _cx: &mut Context<Editor>,
16651 ) -> Task<Result<Option<language::Transaction>>> {
16652 Task::ready(Ok(None))
16653 }
16654
16655 fn is_completion_trigger(
16656 &self,
16657 buffer: &Entity<Buffer>,
16658 position: language::Anchor,
16659 text: &str,
16660 trigger_in_words: bool,
16661 cx: &mut Context<Editor>,
16662 ) -> bool;
16663
16664 fn sort_completions(&self) -> bool {
16665 true
16666 }
16667}
16668
16669pub trait CodeActionProvider {
16670 fn id(&self) -> Arc<str>;
16671
16672 fn code_actions(
16673 &self,
16674 buffer: &Entity<Buffer>,
16675 range: Range<text::Anchor>,
16676 window: &mut Window,
16677 cx: &mut App,
16678 ) -> Task<Result<Vec<CodeAction>>>;
16679
16680 fn apply_code_action(
16681 &self,
16682 buffer_handle: Entity<Buffer>,
16683 action: CodeAction,
16684 excerpt_id: ExcerptId,
16685 push_to_history: bool,
16686 window: &mut Window,
16687 cx: &mut App,
16688 ) -> Task<Result<ProjectTransaction>>;
16689}
16690
16691impl CodeActionProvider for Entity<Project> {
16692 fn id(&self) -> Arc<str> {
16693 "project".into()
16694 }
16695
16696 fn code_actions(
16697 &self,
16698 buffer: &Entity<Buffer>,
16699 range: Range<text::Anchor>,
16700 _window: &mut Window,
16701 cx: &mut App,
16702 ) -> Task<Result<Vec<CodeAction>>> {
16703 self.update(cx, |project, cx| {
16704 project.code_actions(buffer, range, None, cx)
16705 })
16706 }
16707
16708 fn apply_code_action(
16709 &self,
16710 buffer_handle: Entity<Buffer>,
16711 action: CodeAction,
16712 _excerpt_id: ExcerptId,
16713 push_to_history: bool,
16714 _window: &mut Window,
16715 cx: &mut App,
16716 ) -> Task<Result<ProjectTransaction>> {
16717 self.update(cx, |project, cx| {
16718 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16719 })
16720 }
16721}
16722
16723fn snippet_completions(
16724 project: &Project,
16725 buffer: &Entity<Buffer>,
16726 buffer_position: text::Anchor,
16727 cx: &mut App,
16728) -> Task<Result<Vec<Completion>>> {
16729 let language = buffer.read(cx).language_at(buffer_position);
16730 let language_name = language.as_ref().map(|language| language.lsp_id());
16731 let snippet_store = project.snippets().read(cx);
16732 let snippets = snippet_store.snippets_for(language_name, cx);
16733
16734 if snippets.is_empty() {
16735 return Task::ready(Ok(vec![]));
16736 }
16737 let snapshot = buffer.read(cx).text_snapshot();
16738 let chars: String = snapshot
16739 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16740 .collect();
16741
16742 let scope = language.map(|language| language.default_scope());
16743 let executor = cx.background_executor().clone();
16744
16745 cx.background_spawn(async move {
16746 let classifier = CharClassifier::new(scope).for_completion(true);
16747 let mut last_word = chars
16748 .chars()
16749 .take_while(|c| classifier.is_word(*c))
16750 .collect::<String>();
16751 last_word = last_word.chars().rev().collect();
16752
16753 if last_word.is_empty() {
16754 return Ok(vec![]);
16755 }
16756
16757 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16758 let to_lsp = |point: &text::Anchor| {
16759 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16760 point_to_lsp(end)
16761 };
16762 let lsp_end = to_lsp(&buffer_position);
16763
16764 let candidates = snippets
16765 .iter()
16766 .enumerate()
16767 .flat_map(|(ix, snippet)| {
16768 snippet
16769 .prefix
16770 .iter()
16771 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16772 })
16773 .collect::<Vec<StringMatchCandidate>>();
16774
16775 let mut matches = fuzzy::match_strings(
16776 &candidates,
16777 &last_word,
16778 last_word.chars().any(|c| c.is_uppercase()),
16779 100,
16780 &Default::default(),
16781 executor,
16782 )
16783 .await;
16784
16785 // Remove all candidates where the query's start does not match the start of any word in the candidate
16786 if let Some(query_start) = last_word.chars().next() {
16787 matches.retain(|string_match| {
16788 split_words(&string_match.string).any(|word| {
16789 // Check that the first codepoint of the word as lowercase matches the first
16790 // codepoint of the query as lowercase
16791 word.chars()
16792 .flat_map(|codepoint| codepoint.to_lowercase())
16793 .zip(query_start.to_lowercase())
16794 .all(|(word_cp, query_cp)| word_cp == query_cp)
16795 })
16796 });
16797 }
16798
16799 let matched_strings = matches
16800 .into_iter()
16801 .map(|m| m.string)
16802 .collect::<HashSet<_>>();
16803
16804 let result: Vec<Completion> = snippets
16805 .into_iter()
16806 .filter_map(|snippet| {
16807 let matching_prefix = snippet
16808 .prefix
16809 .iter()
16810 .find(|prefix| matched_strings.contains(*prefix))?;
16811 let start = as_offset - last_word.len();
16812 let start = snapshot.anchor_before(start);
16813 let range = start..buffer_position;
16814 let lsp_start = to_lsp(&start);
16815 let lsp_range = lsp::Range {
16816 start: lsp_start,
16817 end: lsp_end,
16818 };
16819 Some(Completion {
16820 old_range: range,
16821 new_text: snippet.body.clone(),
16822 resolved: false,
16823 label: CodeLabel {
16824 text: matching_prefix.clone(),
16825 runs: vec![],
16826 filter_range: 0..matching_prefix.len(),
16827 },
16828 server_id: LanguageServerId(usize::MAX),
16829 documentation: snippet
16830 .description
16831 .clone()
16832 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16833 lsp_completion: lsp::CompletionItem {
16834 label: snippet.prefix.first().unwrap().clone(),
16835 kind: Some(CompletionItemKind::SNIPPET),
16836 label_details: snippet.description.as_ref().map(|description| {
16837 lsp::CompletionItemLabelDetails {
16838 detail: Some(description.clone()),
16839 description: None,
16840 }
16841 }),
16842 insert_text_format: Some(InsertTextFormat::SNIPPET),
16843 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16844 lsp::InsertReplaceEdit {
16845 new_text: snippet.body.clone(),
16846 insert: lsp_range,
16847 replace: lsp_range,
16848 },
16849 )),
16850 filter_text: Some(snippet.body.clone()),
16851 sort_text: Some(char::MAX.to_string()),
16852 ..Default::default()
16853 },
16854 confirm: None,
16855 })
16856 })
16857 .collect();
16858
16859 Ok(result)
16860 })
16861}
16862
16863impl CompletionProvider for Entity<Project> {
16864 fn completions(
16865 &self,
16866 buffer: &Entity<Buffer>,
16867 buffer_position: text::Anchor,
16868 options: CompletionContext,
16869 _window: &mut Window,
16870 cx: &mut Context<Editor>,
16871 ) -> Task<Result<Vec<Completion>>> {
16872 self.update(cx, |project, cx| {
16873 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16874 let project_completions = project.completions(buffer, buffer_position, options, cx);
16875 cx.background_spawn(async move {
16876 let mut completions = project_completions.await?;
16877 let snippets_completions = snippets.await?;
16878 completions.extend(snippets_completions);
16879 Ok(completions)
16880 })
16881 })
16882 }
16883
16884 fn resolve_completions(
16885 &self,
16886 buffer: Entity<Buffer>,
16887 completion_indices: Vec<usize>,
16888 completions: Rc<RefCell<Box<[Completion]>>>,
16889 cx: &mut Context<Editor>,
16890 ) -> Task<Result<bool>> {
16891 self.update(cx, |project, cx| {
16892 project.lsp_store().update(cx, |lsp_store, cx| {
16893 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16894 })
16895 })
16896 }
16897
16898 fn apply_additional_edits_for_completion(
16899 &self,
16900 buffer: Entity<Buffer>,
16901 completions: Rc<RefCell<Box<[Completion]>>>,
16902 completion_index: usize,
16903 push_to_history: bool,
16904 cx: &mut Context<Editor>,
16905 ) -> Task<Result<Option<language::Transaction>>> {
16906 self.update(cx, |project, cx| {
16907 project.lsp_store().update(cx, |lsp_store, cx| {
16908 lsp_store.apply_additional_edits_for_completion(
16909 buffer,
16910 completions,
16911 completion_index,
16912 push_to_history,
16913 cx,
16914 )
16915 })
16916 })
16917 }
16918
16919 fn is_completion_trigger(
16920 &self,
16921 buffer: &Entity<Buffer>,
16922 position: language::Anchor,
16923 text: &str,
16924 trigger_in_words: bool,
16925 cx: &mut Context<Editor>,
16926 ) -> bool {
16927 let mut chars = text.chars();
16928 let char = if let Some(char) = chars.next() {
16929 char
16930 } else {
16931 return false;
16932 };
16933 if chars.next().is_some() {
16934 return false;
16935 }
16936
16937 let buffer = buffer.read(cx);
16938 let snapshot = buffer.snapshot();
16939 if !snapshot.settings_at(position, cx).show_completions_on_input {
16940 return false;
16941 }
16942 let classifier = snapshot.char_classifier_at(position).for_completion(true);
16943 if trigger_in_words && classifier.is_word(char) {
16944 return true;
16945 }
16946
16947 buffer.completion_triggers().contains(text)
16948 }
16949}
16950
16951impl SemanticsProvider for Entity<Project> {
16952 fn hover(
16953 &self,
16954 buffer: &Entity<Buffer>,
16955 position: text::Anchor,
16956 cx: &mut App,
16957 ) -> Option<Task<Vec<project::Hover>>> {
16958 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16959 }
16960
16961 fn document_highlights(
16962 &self,
16963 buffer: &Entity<Buffer>,
16964 position: text::Anchor,
16965 cx: &mut App,
16966 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16967 Some(self.update(cx, |project, cx| {
16968 project.document_highlights(buffer, position, cx)
16969 }))
16970 }
16971
16972 fn definitions(
16973 &self,
16974 buffer: &Entity<Buffer>,
16975 position: text::Anchor,
16976 kind: GotoDefinitionKind,
16977 cx: &mut App,
16978 ) -> Option<Task<Result<Vec<LocationLink>>>> {
16979 Some(self.update(cx, |project, cx| match kind {
16980 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16981 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16982 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16983 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16984 }))
16985 }
16986
16987 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16988 // TODO: make this work for remote projects
16989 self.update(cx, |this, cx| {
16990 buffer.update(cx, |buffer, cx| {
16991 this.any_language_server_supports_inlay_hints(buffer, cx)
16992 })
16993 })
16994 }
16995
16996 fn inlay_hints(
16997 &self,
16998 buffer_handle: Entity<Buffer>,
16999 range: Range<text::Anchor>,
17000 cx: &mut App,
17001 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17002 Some(self.update(cx, |project, cx| {
17003 project.inlay_hints(buffer_handle, range, cx)
17004 }))
17005 }
17006
17007 fn resolve_inlay_hint(
17008 &self,
17009 hint: InlayHint,
17010 buffer_handle: Entity<Buffer>,
17011 server_id: LanguageServerId,
17012 cx: &mut App,
17013 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17014 Some(self.update(cx, |project, cx| {
17015 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17016 }))
17017 }
17018
17019 fn range_for_rename(
17020 &self,
17021 buffer: &Entity<Buffer>,
17022 position: text::Anchor,
17023 cx: &mut App,
17024 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17025 Some(self.update(cx, |project, cx| {
17026 let buffer = buffer.clone();
17027 let task = project.prepare_rename(buffer.clone(), position, cx);
17028 cx.spawn(|_, mut cx| async move {
17029 Ok(match task.await? {
17030 PrepareRenameResponse::Success(range) => Some(range),
17031 PrepareRenameResponse::InvalidPosition => None,
17032 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17033 // Fallback on using TreeSitter info to determine identifier range
17034 buffer.update(&mut cx, |buffer, _| {
17035 let snapshot = buffer.snapshot();
17036 let (range, kind) = snapshot.surrounding_word(position);
17037 if kind != Some(CharKind::Word) {
17038 return None;
17039 }
17040 Some(
17041 snapshot.anchor_before(range.start)
17042 ..snapshot.anchor_after(range.end),
17043 )
17044 })?
17045 }
17046 })
17047 })
17048 }))
17049 }
17050
17051 fn perform_rename(
17052 &self,
17053 buffer: &Entity<Buffer>,
17054 position: text::Anchor,
17055 new_name: String,
17056 cx: &mut App,
17057 ) -> Option<Task<Result<ProjectTransaction>>> {
17058 Some(self.update(cx, |project, cx| {
17059 project.perform_rename(buffer.clone(), position, new_name, cx)
17060 }))
17061 }
17062}
17063
17064fn inlay_hint_settings(
17065 location: Anchor,
17066 snapshot: &MultiBufferSnapshot,
17067 cx: &mut Context<Editor>,
17068) -> InlayHintSettings {
17069 let file = snapshot.file_at(location);
17070 let language = snapshot.language_at(location).map(|l| l.name());
17071 language_settings(language, file, cx).inlay_hints
17072}
17073
17074fn consume_contiguous_rows(
17075 contiguous_row_selections: &mut Vec<Selection<Point>>,
17076 selection: &Selection<Point>,
17077 display_map: &DisplaySnapshot,
17078 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17079) -> (MultiBufferRow, MultiBufferRow) {
17080 contiguous_row_selections.push(selection.clone());
17081 let start_row = MultiBufferRow(selection.start.row);
17082 let mut end_row = ending_row(selection, display_map);
17083
17084 while let Some(next_selection) = selections.peek() {
17085 if next_selection.start.row <= end_row.0 {
17086 end_row = ending_row(next_selection, display_map);
17087 contiguous_row_selections.push(selections.next().unwrap().clone());
17088 } else {
17089 break;
17090 }
17091 }
17092 (start_row, end_row)
17093}
17094
17095fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17096 if next_selection.end.column > 0 || next_selection.is_empty() {
17097 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17098 } else {
17099 MultiBufferRow(next_selection.end.row)
17100 }
17101}
17102
17103impl EditorSnapshot {
17104 pub fn remote_selections_in_range<'a>(
17105 &'a self,
17106 range: &'a Range<Anchor>,
17107 collaboration_hub: &dyn CollaborationHub,
17108 cx: &'a App,
17109 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17110 let participant_names = collaboration_hub.user_names(cx);
17111 let participant_indices = collaboration_hub.user_participant_indices(cx);
17112 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17113 let collaborators_by_replica_id = collaborators_by_peer_id
17114 .iter()
17115 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17116 .collect::<HashMap<_, _>>();
17117 self.buffer_snapshot
17118 .selections_in_range(range, false)
17119 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17120 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17121 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17122 let user_name = participant_names.get(&collaborator.user_id).cloned();
17123 Some(RemoteSelection {
17124 replica_id,
17125 selection,
17126 cursor_shape,
17127 line_mode,
17128 participant_index,
17129 peer_id: collaborator.peer_id,
17130 user_name,
17131 })
17132 })
17133 }
17134
17135 pub fn hunks_for_ranges(
17136 &self,
17137 ranges: impl IntoIterator<Item = Range<Point>>,
17138 ) -> Vec<MultiBufferDiffHunk> {
17139 let mut hunks = Vec::new();
17140 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17141 HashMap::default();
17142 for query_range in ranges {
17143 let query_rows =
17144 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17145 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17146 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17147 ) {
17148 // Include deleted hunks that are adjacent to the query range, because
17149 // otherwise they would be missed.
17150 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17151 if hunk.status().is_deleted() {
17152 intersects_range |= hunk.row_range.start == query_rows.end;
17153 intersects_range |= hunk.row_range.end == query_rows.start;
17154 }
17155 if intersects_range {
17156 if !processed_buffer_rows
17157 .entry(hunk.buffer_id)
17158 .or_default()
17159 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17160 {
17161 continue;
17162 }
17163 hunks.push(hunk);
17164 }
17165 }
17166 }
17167
17168 hunks
17169 }
17170
17171 fn display_diff_hunks_for_rows<'a>(
17172 &'a self,
17173 display_rows: Range<DisplayRow>,
17174 folded_buffers: &'a HashSet<BufferId>,
17175 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17176 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17177 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17178
17179 self.buffer_snapshot
17180 .diff_hunks_in_range(buffer_start..buffer_end)
17181 .filter_map(|hunk| {
17182 if folded_buffers.contains(&hunk.buffer_id) {
17183 return None;
17184 }
17185
17186 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17187 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17188
17189 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17190 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17191
17192 let display_hunk = if hunk_display_start.column() != 0 {
17193 DisplayDiffHunk::Folded {
17194 display_row: hunk_display_start.row(),
17195 }
17196 } else {
17197 let mut end_row = hunk_display_end.row();
17198 if hunk_display_end.column() > 0 {
17199 end_row.0 += 1;
17200 }
17201 let is_created_file = hunk.is_created_file();
17202 DisplayDiffHunk::Unfolded {
17203 status: hunk.status(),
17204 diff_base_byte_range: hunk.diff_base_byte_range,
17205 display_row_range: hunk_display_start.row()..end_row,
17206 multi_buffer_range: Anchor::range_in_buffer(
17207 hunk.excerpt_id,
17208 hunk.buffer_id,
17209 hunk.buffer_range,
17210 ),
17211 is_created_file,
17212 }
17213 };
17214
17215 Some(display_hunk)
17216 })
17217 }
17218
17219 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17220 self.display_snapshot.buffer_snapshot.language_at(position)
17221 }
17222
17223 pub fn is_focused(&self) -> bool {
17224 self.is_focused
17225 }
17226
17227 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17228 self.placeholder_text.as_ref()
17229 }
17230
17231 pub fn scroll_position(&self) -> gpui::Point<f32> {
17232 self.scroll_anchor.scroll_position(&self.display_snapshot)
17233 }
17234
17235 fn gutter_dimensions(
17236 &self,
17237 font_id: FontId,
17238 font_size: Pixels,
17239 max_line_number_width: Pixels,
17240 cx: &App,
17241 ) -> Option<GutterDimensions> {
17242 if !self.show_gutter {
17243 return None;
17244 }
17245
17246 let descent = cx.text_system().descent(font_id, font_size);
17247 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17248 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17249
17250 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17251 matches!(
17252 ProjectSettings::get_global(cx).git.git_gutter,
17253 Some(GitGutterSetting::TrackedFiles)
17254 )
17255 });
17256 let gutter_settings = EditorSettings::get_global(cx).gutter;
17257 let show_line_numbers = self
17258 .show_line_numbers
17259 .unwrap_or(gutter_settings.line_numbers);
17260 let line_gutter_width = if show_line_numbers {
17261 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17262 let min_width_for_number_on_gutter = em_advance * 4.0;
17263 max_line_number_width.max(min_width_for_number_on_gutter)
17264 } else {
17265 0.0.into()
17266 };
17267
17268 let show_code_actions = self
17269 .show_code_actions
17270 .unwrap_or(gutter_settings.code_actions);
17271
17272 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17273
17274 let git_blame_entries_width =
17275 self.git_blame_gutter_max_author_length
17276 .map(|max_author_length| {
17277 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17278
17279 /// The number of characters to dedicate to gaps and margins.
17280 const SPACING_WIDTH: usize = 4;
17281
17282 let max_char_count = max_author_length
17283 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17284 + ::git::SHORT_SHA_LENGTH
17285 + MAX_RELATIVE_TIMESTAMP.len()
17286 + SPACING_WIDTH;
17287
17288 em_advance * max_char_count
17289 });
17290
17291 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17292 left_padding += if show_code_actions || show_runnables {
17293 em_width * 3.0
17294 } else if show_git_gutter && show_line_numbers {
17295 em_width * 2.0
17296 } else if show_git_gutter || show_line_numbers {
17297 em_width
17298 } else {
17299 px(0.)
17300 };
17301
17302 let right_padding = if gutter_settings.folds && show_line_numbers {
17303 em_width * 4.0
17304 } else if gutter_settings.folds {
17305 em_width * 3.0
17306 } else if show_line_numbers {
17307 em_width
17308 } else {
17309 px(0.)
17310 };
17311
17312 Some(GutterDimensions {
17313 left_padding,
17314 right_padding,
17315 width: line_gutter_width + left_padding + right_padding,
17316 margin: -descent,
17317 git_blame_entries_width,
17318 })
17319 }
17320
17321 pub fn render_crease_toggle(
17322 &self,
17323 buffer_row: MultiBufferRow,
17324 row_contains_cursor: bool,
17325 editor: Entity<Editor>,
17326 window: &mut Window,
17327 cx: &mut App,
17328 ) -> Option<AnyElement> {
17329 let folded = self.is_line_folded(buffer_row);
17330 let mut is_foldable = false;
17331
17332 if let Some(crease) = self
17333 .crease_snapshot
17334 .query_row(buffer_row, &self.buffer_snapshot)
17335 {
17336 is_foldable = true;
17337 match crease {
17338 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17339 if let Some(render_toggle) = render_toggle {
17340 let toggle_callback =
17341 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17342 if folded {
17343 editor.update(cx, |editor, cx| {
17344 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17345 });
17346 } else {
17347 editor.update(cx, |editor, cx| {
17348 editor.unfold_at(
17349 &crate::UnfoldAt { buffer_row },
17350 window,
17351 cx,
17352 )
17353 });
17354 }
17355 });
17356 return Some((render_toggle)(
17357 buffer_row,
17358 folded,
17359 toggle_callback,
17360 window,
17361 cx,
17362 ));
17363 }
17364 }
17365 }
17366 }
17367
17368 is_foldable |= self.starts_indent(buffer_row);
17369
17370 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17371 Some(
17372 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17373 .toggle_state(folded)
17374 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17375 if folded {
17376 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17377 } else {
17378 this.fold_at(&FoldAt { buffer_row }, window, cx);
17379 }
17380 }))
17381 .into_any_element(),
17382 )
17383 } else {
17384 None
17385 }
17386 }
17387
17388 pub fn render_crease_trailer(
17389 &self,
17390 buffer_row: MultiBufferRow,
17391 window: &mut Window,
17392 cx: &mut App,
17393 ) -> Option<AnyElement> {
17394 let folded = self.is_line_folded(buffer_row);
17395 if let Crease::Inline { render_trailer, .. } = self
17396 .crease_snapshot
17397 .query_row(buffer_row, &self.buffer_snapshot)?
17398 {
17399 let render_trailer = render_trailer.as_ref()?;
17400 Some(render_trailer(buffer_row, folded, window, cx))
17401 } else {
17402 None
17403 }
17404 }
17405}
17406
17407impl Deref for EditorSnapshot {
17408 type Target = DisplaySnapshot;
17409
17410 fn deref(&self) -> &Self::Target {
17411 &self.display_snapshot
17412 }
17413}
17414
17415#[derive(Clone, Debug, PartialEq, Eq)]
17416pub enum EditorEvent {
17417 InputIgnored {
17418 text: Arc<str>,
17419 },
17420 InputHandled {
17421 utf16_range_to_replace: Option<Range<isize>>,
17422 text: Arc<str>,
17423 },
17424 ExcerptsAdded {
17425 buffer: Entity<Buffer>,
17426 predecessor: ExcerptId,
17427 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17428 },
17429 ExcerptsRemoved {
17430 ids: Vec<ExcerptId>,
17431 },
17432 BufferFoldToggled {
17433 ids: Vec<ExcerptId>,
17434 folded: bool,
17435 },
17436 ExcerptsEdited {
17437 ids: Vec<ExcerptId>,
17438 },
17439 ExcerptsExpanded {
17440 ids: Vec<ExcerptId>,
17441 },
17442 BufferEdited,
17443 Edited {
17444 transaction_id: clock::Lamport,
17445 },
17446 Reparsed(BufferId),
17447 Focused,
17448 FocusedIn,
17449 Blurred,
17450 DirtyChanged,
17451 Saved,
17452 TitleChanged,
17453 DiffBaseChanged,
17454 SelectionsChanged {
17455 local: bool,
17456 },
17457 ScrollPositionChanged {
17458 local: bool,
17459 autoscroll: bool,
17460 },
17461 Closed,
17462 TransactionUndone {
17463 transaction_id: clock::Lamport,
17464 },
17465 TransactionBegun {
17466 transaction_id: clock::Lamport,
17467 },
17468 Reloaded,
17469 CursorShapeChanged,
17470}
17471
17472impl EventEmitter<EditorEvent> for Editor {}
17473
17474impl Focusable for Editor {
17475 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17476 self.focus_handle.clone()
17477 }
17478}
17479
17480impl Render for Editor {
17481 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17482 let settings = ThemeSettings::get_global(cx);
17483
17484 let mut text_style = match self.mode {
17485 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17486 color: cx.theme().colors().editor_foreground,
17487 font_family: settings.ui_font.family.clone(),
17488 font_features: settings.ui_font.features.clone(),
17489 font_fallbacks: settings.ui_font.fallbacks.clone(),
17490 font_size: rems(0.875).into(),
17491 font_weight: settings.ui_font.weight,
17492 line_height: relative(settings.buffer_line_height.value()),
17493 ..Default::default()
17494 },
17495 EditorMode::Full => TextStyle {
17496 color: cx.theme().colors().editor_foreground,
17497 font_family: settings.buffer_font.family.clone(),
17498 font_features: settings.buffer_font.features.clone(),
17499 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17500 font_size: settings.buffer_font_size(cx).into(),
17501 font_weight: settings.buffer_font.weight,
17502 line_height: relative(settings.buffer_line_height.value()),
17503 ..Default::default()
17504 },
17505 };
17506 if let Some(text_style_refinement) = &self.text_style_refinement {
17507 text_style.refine(text_style_refinement)
17508 }
17509
17510 let background = match self.mode {
17511 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17512 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17513 EditorMode::Full => cx.theme().colors().editor_background,
17514 };
17515
17516 EditorElement::new(
17517 &cx.entity(),
17518 EditorStyle {
17519 background,
17520 local_player: cx.theme().players().local(),
17521 text: text_style,
17522 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17523 syntax: cx.theme().syntax().clone(),
17524 status: cx.theme().status().clone(),
17525 inlay_hints_style: make_inlay_hints_style(cx),
17526 inline_completion_styles: make_suggestion_styles(cx),
17527 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17528 },
17529 )
17530 }
17531}
17532
17533impl EntityInputHandler for Editor {
17534 fn text_for_range(
17535 &mut self,
17536 range_utf16: Range<usize>,
17537 adjusted_range: &mut Option<Range<usize>>,
17538 _: &mut Window,
17539 cx: &mut Context<Self>,
17540 ) -> Option<String> {
17541 let snapshot = self.buffer.read(cx).read(cx);
17542 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17543 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17544 if (start.0..end.0) != range_utf16 {
17545 adjusted_range.replace(start.0..end.0);
17546 }
17547 Some(snapshot.text_for_range(start..end).collect())
17548 }
17549
17550 fn selected_text_range(
17551 &mut self,
17552 ignore_disabled_input: bool,
17553 _: &mut Window,
17554 cx: &mut Context<Self>,
17555 ) -> Option<UTF16Selection> {
17556 // Prevent the IME menu from appearing when holding down an alphabetic key
17557 // while input is disabled.
17558 if !ignore_disabled_input && !self.input_enabled {
17559 return None;
17560 }
17561
17562 let selection = self.selections.newest::<OffsetUtf16>(cx);
17563 let range = selection.range();
17564
17565 Some(UTF16Selection {
17566 range: range.start.0..range.end.0,
17567 reversed: selection.reversed,
17568 })
17569 }
17570
17571 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17572 let snapshot = self.buffer.read(cx).read(cx);
17573 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17574 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17575 }
17576
17577 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17578 self.clear_highlights::<InputComposition>(cx);
17579 self.ime_transaction.take();
17580 }
17581
17582 fn replace_text_in_range(
17583 &mut self,
17584 range_utf16: Option<Range<usize>>,
17585 text: &str,
17586 window: &mut Window,
17587 cx: &mut Context<Self>,
17588 ) {
17589 if !self.input_enabled {
17590 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17591 return;
17592 }
17593
17594 self.transact(window, cx, |this, window, cx| {
17595 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17596 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17597 Some(this.selection_replacement_ranges(range_utf16, cx))
17598 } else {
17599 this.marked_text_ranges(cx)
17600 };
17601
17602 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17603 let newest_selection_id = this.selections.newest_anchor().id;
17604 this.selections
17605 .all::<OffsetUtf16>(cx)
17606 .iter()
17607 .zip(ranges_to_replace.iter())
17608 .find_map(|(selection, range)| {
17609 if selection.id == newest_selection_id {
17610 Some(
17611 (range.start.0 as isize - selection.head().0 as isize)
17612 ..(range.end.0 as isize - selection.head().0 as isize),
17613 )
17614 } else {
17615 None
17616 }
17617 })
17618 });
17619
17620 cx.emit(EditorEvent::InputHandled {
17621 utf16_range_to_replace: range_to_replace,
17622 text: text.into(),
17623 });
17624
17625 if let Some(new_selected_ranges) = new_selected_ranges {
17626 this.change_selections(None, window, cx, |selections| {
17627 selections.select_ranges(new_selected_ranges)
17628 });
17629 this.backspace(&Default::default(), window, cx);
17630 }
17631
17632 this.handle_input(text, window, cx);
17633 });
17634
17635 if let Some(transaction) = self.ime_transaction {
17636 self.buffer.update(cx, |buffer, cx| {
17637 buffer.group_until_transaction(transaction, cx);
17638 });
17639 }
17640
17641 self.unmark_text(window, cx);
17642 }
17643
17644 fn replace_and_mark_text_in_range(
17645 &mut self,
17646 range_utf16: Option<Range<usize>>,
17647 text: &str,
17648 new_selected_range_utf16: Option<Range<usize>>,
17649 window: &mut Window,
17650 cx: &mut Context<Self>,
17651 ) {
17652 if !self.input_enabled {
17653 return;
17654 }
17655
17656 let transaction = self.transact(window, cx, |this, window, cx| {
17657 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17658 let snapshot = this.buffer.read(cx).read(cx);
17659 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17660 for marked_range in &mut marked_ranges {
17661 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17662 marked_range.start.0 += relative_range_utf16.start;
17663 marked_range.start =
17664 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17665 marked_range.end =
17666 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17667 }
17668 }
17669 Some(marked_ranges)
17670 } else if let Some(range_utf16) = range_utf16 {
17671 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17672 Some(this.selection_replacement_ranges(range_utf16, cx))
17673 } else {
17674 None
17675 };
17676
17677 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17678 let newest_selection_id = this.selections.newest_anchor().id;
17679 this.selections
17680 .all::<OffsetUtf16>(cx)
17681 .iter()
17682 .zip(ranges_to_replace.iter())
17683 .find_map(|(selection, range)| {
17684 if selection.id == newest_selection_id {
17685 Some(
17686 (range.start.0 as isize - selection.head().0 as isize)
17687 ..(range.end.0 as isize - selection.head().0 as isize),
17688 )
17689 } else {
17690 None
17691 }
17692 })
17693 });
17694
17695 cx.emit(EditorEvent::InputHandled {
17696 utf16_range_to_replace: range_to_replace,
17697 text: text.into(),
17698 });
17699
17700 if let Some(ranges) = ranges_to_replace {
17701 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17702 }
17703
17704 let marked_ranges = {
17705 let snapshot = this.buffer.read(cx).read(cx);
17706 this.selections
17707 .disjoint_anchors()
17708 .iter()
17709 .map(|selection| {
17710 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17711 })
17712 .collect::<Vec<_>>()
17713 };
17714
17715 if text.is_empty() {
17716 this.unmark_text(window, cx);
17717 } else {
17718 this.highlight_text::<InputComposition>(
17719 marked_ranges.clone(),
17720 HighlightStyle {
17721 underline: Some(UnderlineStyle {
17722 thickness: px(1.),
17723 color: None,
17724 wavy: false,
17725 }),
17726 ..Default::default()
17727 },
17728 cx,
17729 );
17730 }
17731
17732 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17733 let use_autoclose = this.use_autoclose;
17734 let use_auto_surround = this.use_auto_surround;
17735 this.set_use_autoclose(false);
17736 this.set_use_auto_surround(false);
17737 this.handle_input(text, window, cx);
17738 this.set_use_autoclose(use_autoclose);
17739 this.set_use_auto_surround(use_auto_surround);
17740
17741 if let Some(new_selected_range) = new_selected_range_utf16 {
17742 let snapshot = this.buffer.read(cx).read(cx);
17743 let new_selected_ranges = marked_ranges
17744 .into_iter()
17745 .map(|marked_range| {
17746 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17747 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17748 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17749 snapshot.clip_offset_utf16(new_start, Bias::Left)
17750 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17751 })
17752 .collect::<Vec<_>>();
17753
17754 drop(snapshot);
17755 this.change_selections(None, window, cx, |selections| {
17756 selections.select_ranges(new_selected_ranges)
17757 });
17758 }
17759 });
17760
17761 self.ime_transaction = self.ime_transaction.or(transaction);
17762 if let Some(transaction) = self.ime_transaction {
17763 self.buffer.update(cx, |buffer, cx| {
17764 buffer.group_until_transaction(transaction, cx);
17765 });
17766 }
17767
17768 if self.text_highlights::<InputComposition>(cx).is_none() {
17769 self.ime_transaction.take();
17770 }
17771 }
17772
17773 fn bounds_for_range(
17774 &mut self,
17775 range_utf16: Range<usize>,
17776 element_bounds: gpui::Bounds<Pixels>,
17777 window: &mut Window,
17778 cx: &mut Context<Self>,
17779 ) -> Option<gpui::Bounds<Pixels>> {
17780 let text_layout_details = self.text_layout_details(window);
17781 let gpui::Size {
17782 width: em_width,
17783 height: line_height,
17784 } = self.character_size(window);
17785
17786 let snapshot = self.snapshot(window, cx);
17787 let scroll_position = snapshot.scroll_position();
17788 let scroll_left = scroll_position.x * em_width;
17789
17790 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17791 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17792 + self.gutter_dimensions.width
17793 + self.gutter_dimensions.margin;
17794 let y = line_height * (start.row().as_f32() - scroll_position.y);
17795
17796 Some(Bounds {
17797 origin: element_bounds.origin + point(x, y),
17798 size: size(em_width, line_height),
17799 })
17800 }
17801
17802 fn character_index_for_point(
17803 &mut self,
17804 point: gpui::Point<Pixels>,
17805 _window: &mut Window,
17806 _cx: &mut Context<Self>,
17807 ) -> Option<usize> {
17808 let position_map = self.last_position_map.as_ref()?;
17809 if !position_map.text_hitbox.contains(&point) {
17810 return None;
17811 }
17812 let display_point = position_map.point_for_position(point).previous_valid;
17813 let anchor = position_map
17814 .snapshot
17815 .display_point_to_anchor(display_point, Bias::Left);
17816 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17817 Some(utf16_offset.0)
17818 }
17819}
17820
17821trait SelectionExt {
17822 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17823 fn spanned_rows(
17824 &self,
17825 include_end_if_at_line_start: bool,
17826 map: &DisplaySnapshot,
17827 ) -> Range<MultiBufferRow>;
17828}
17829
17830impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17831 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17832 let start = self
17833 .start
17834 .to_point(&map.buffer_snapshot)
17835 .to_display_point(map);
17836 let end = self
17837 .end
17838 .to_point(&map.buffer_snapshot)
17839 .to_display_point(map);
17840 if self.reversed {
17841 end..start
17842 } else {
17843 start..end
17844 }
17845 }
17846
17847 fn spanned_rows(
17848 &self,
17849 include_end_if_at_line_start: bool,
17850 map: &DisplaySnapshot,
17851 ) -> Range<MultiBufferRow> {
17852 let start = self.start.to_point(&map.buffer_snapshot);
17853 let mut end = self.end.to_point(&map.buffer_snapshot);
17854 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17855 end.row -= 1;
17856 }
17857
17858 let buffer_start = map.prev_line_boundary(start).0;
17859 let buffer_end = map.next_line_boundary(end).0;
17860 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17861 }
17862}
17863
17864impl<T: InvalidationRegion> InvalidationStack<T> {
17865 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17866 where
17867 S: Clone + ToOffset,
17868 {
17869 while let Some(region) = self.last() {
17870 let all_selections_inside_invalidation_ranges =
17871 if selections.len() == region.ranges().len() {
17872 selections
17873 .iter()
17874 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17875 .all(|(selection, invalidation_range)| {
17876 let head = selection.head().to_offset(buffer);
17877 invalidation_range.start <= head && invalidation_range.end >= head
17878 })
17879 } else {
17880 false
17881 };
17882
17883 if all_selections_inside_invalidation_ranges {
17884 break;
17885 } else {
17886 self.pop();
17887 }
17888 }
17889 }
17890}
17891
17892impl<T> Default for InvalidationStack<T> {
17893 fn default() -> Self {
17894 Self(Default::default())
17895 }
17896}
17897
17898impl<T> Deref for InvalidationStack<T> {
17899 type Target = Vec<T>;
17900
17901 fn deref(&self) -> &Self::Target {
17902 &self.0
17903 }
17904}
17905
17906impl<T> DerefMut for InvalidationStack<T> {
17907 fn deref_mut(&mut self) -> &mut Self::Target {
17908 &mut self.0
17909 }
17910}
17911
17912impl InvalidationRegion for SnippetState {
17913 fn ranges(&self) -> &[Range<Anchor>] {
17914 &self.ranges[self.active_index]
17915 }
17916}
17917
17918pub fn diagnostic_block_renderer(
17919 diagnostic: Diagnostic,
17920 max_message_rows: Option<u8>,
17921 allow_closing: bool,
17922) -> RenderBlock {
17923 let (text_without_backticks, code_ranges) =
17924 highlight_diagnostic_message(&diagnostic, max_message_rows);
17925
17926 Arc::new(move |cx: &mut BlockContext| {
17927 let group_id: SharedString = cx.block_id.to_string().into();
17928
17929 let mut text_style = cx.window.text_style().clone();
17930 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17931 let theme_settings = ThemeSettings::get_global(cx);
17932 text_style.font_family = theme_settings.buffer_font.family.clone();
17933 text_style.font_style = theme_settings.buffer_font.style;
17934 text_style.font_features = theme_settings.buffer_font.features.clone();
17935 text_style.font_weight = theme_settings.buffer_font.weight;
17936
17937 let multi_line_diagnostic = diagnostic.message.contains('\n');
17938
17939 let buttons = |diagnostic: &Diagnostic| {
17940 if multi_line_diagnostic {
17941 v_flex()
17942 } else {
17943 h_flex()
17944 }
17945 .when(allow_closing, |div| {
17946 div.children(diagnostic.is_primary.then(|| {
17947 IconButton::new("close-block", IconName::XCircle)
17948 .icon_color(Color::Muted)
17949 .size(ButtonSize::Compact)
17950 .style(ButtonStyle::Transparent)
17951 .visible_on_hover(group_id.clone())
17952 .on_click(move |_click, window, cx| {
17953 window.dispatch_action(Box::new(Cancel), cx)
17954 })
17955 .tooltip(|window, cx| {
17956 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17957 })
17958 }))
17959 })
17960 .child(
17961 IconButton::new("copy-block", IconName::Copy)
17962 .icon_color(Color::Muted)
17963 .size(ButtonSize::Compact)
17964 .style(ButtonStyle::Transparent)
17965 .visible_on_hover(group_id.clone())
17966 .on_click({
17967 let message = diagnostic.message.clone();
17968 move |_click, _, cx| {
17969 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17970 }
17971 })
17972 .tooltip(Tooltip::text("Copy diagnostic message")),
17973 )
17974 };
17975
17976 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17977 AvailableSpace::min_size(),
17978 cx.window,
17979 cx.app,
17980 );
17981
17982 h_flex()
17983 .id(cx.block_id)
17984 .group(group_id.clone())
17985 .relative()
17986 .size_full()
17987 .block_mouse_down()
17988 .pl(cx.gutter_dimensions.width)
17989 .w(cx.max_width - cx.gutter_dimensions.full_width())
17990 .child(
17991 div()
17992 .flex()
17993 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17994 .flex_shrink(),
17995 )
17996 .child(buttons(&diagnostic))
17997 .child(div().flex().flex_shrink_0().child(
17998 StyledText::new(text_without_backticks.clone()).with_default_highlights(
17999 &text_style,
18000 code_ranges.iter().map(|range| {
18001 (
18002 range.clone(),
18003 HighlightStyle {
18004 font_weight: Some(FontWeight::BOLD),
18005 ..Default::default()
18006 },
18007 )
18008 }),
18009 ),
18010 ))
18011 .into_any_element()
18012 })
18013}
18014
18015fn inline_completion_edit_text(
18016 current_snapshot: &BufferSnapshot,
18017 edits: &[(Range<Anchor>, String)],
18018 edit_preview: &EditPreview,
18019 include_deletions: bool,
18020 cx: &App,
18021) -> HighlightedText {
18022 let edits = edits
18023 .iter()
18024 .map(|(anchor, text)| {
18025 (
18026 anchor.start.text_anchor..anchor.end.text_anchor,
18027 text.clone(),
18028 )
18029 })
18030 .collect::<Vec<_>>();
18031
18032 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18033}
18034
18035pub fn highlight_diagnostic_message(
18036 diagnostic: &Diagnostic,
18037 mut max_message_rows: Option<u8>,
18038) -> (SharedString, Vec<Range<usize>>) {
18039 let mut text_without_backticks = String::new();
18040 let mut code_ranges = Vec::new();
18041
18042 if let Some(source) = &diagnostic.source {
18043 text_without_backticks.push_str(source);
18044 code_ranges.push(0..source.len());
18045 text_without_backticks.push_str(": ");
18046 }
18047
18048 let mut prev_offset = 0;
18049 let mut in_code_block = false;
18050 let has_row_limit = max_message_rows.is_some();
18051 let mut newline_indices = diagnostic
18052 .message
18053 .match_indices('\n')
18054 .filter(|_| has_row_limit)
18055 .map(|(ix, _)| ix)
18056 .fuse()
18057 .peekable();
18058
18059 for (quote_ix, _) in diagnostic
18060 .message
18061 .match_indices('`')
18062 .chain([(diagnostic.message.len(), "")])
18063 {
18064 let mut first_newline_ix = None;
18065 let mut last_newline_ix = None;
18066 while let Some(newline_ix) = newline_indices.peek() {
18067 if *newline_ix < quote_ix {
18068 if first_newline_ix.is_none() {
18069 first_newline_ix = Some(*newline_ix);
18070 }
18071 last_newline_ix = Some(*newline_ix);
18072
18073 if let Some(rows_left) = &mut max_message_rows {
18074 if *rows_left == 0 {
18075 break;
18076 } else {
18077 *rows_left -= 1;
18078 }
18079 }
18080 let _ = newline_indices.next();
18081 } else {
18082 break;
18083 }
18084 }
18085 let prev_len = text_without_backticks.len();
18086 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18087 text_without_backticks.push_str(new_text);
18088 if in_code_block {
18089 code_ranges.push(prev_len..text_without_backticks.len());
18090 }
18091 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18092 in_code_block = !in_code_block;
18093 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18094 text_without_backticks.push_str("...");
18095 break;
18096 }
18097 }
18098
18099 (text_without_backticks.into(), code_ranges)
18100}
18101
18102fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18103 match severity {
18104 DiagnosticSeverity::ERROR => colors.error,
18105 DiagnosticSeverity::WARNING => colors.warning,
18106 DiagnosticSeverity::INFORMATION => colors.info,
18107 DiagnosticSeverity::HINT => colors.info,
18108 _ => colors.ignored,
18109 }
18110}
18111
18112pub fn styled_runs_for_code_label<'a>(
18113 label: &'a CodeLabel,
18114 syntax_theme: &'a theme::SyntaxTheme,
18115) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18116 let fade_out = HighlightStyle {
18117 fade_out: Some(0.35),
18118 ..Default::default()
18119 };
18120
18121 let mut prev_end = label.filter_range.end;
18122 label
18123 .runs
18124 .iter()
18125 .enumerate()
18126 .flat_map(move |(ix, (range, highlight_id))| {
18127 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18128 style
18129 } else {
18130 return Default::default();
18131 };
18132 let mut muted_style = style;
18133 muted_style.highlight(fade_out);
18134
18135 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18136 if range.start >= label.filter_range.end {
18137 if range.start > prev_end {
18138 runs.push((prev_end..range.start, fade_out));
18139 }
18140 runs.push((range.clone(), muted_style));
18141 } else if range.end <= label.filter_range.end {
18142 runs.push((range.clone(), style));
18143 } else {
18144 runs.push((range.start..label.filter_range.end, style));
18145 runs.push((label.filter_range.end..range.end, muted_style));
18146 }
18147 prev_end = cmp::max(prev_end, range.end);
18148
18149 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18150 runs.push((prev_end..label.text.len(), fade_out));
18151 }
18152
18153 runs
18154 })
18155}
18156
18157pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18158 let mut prev_index = 0;
18159 let mut prev_codepoint: Option<char> = None;
18160 text.char_indices()
18161 .chain([(text.len(), '\0')])
18162 .filter_map(move |(index, codepoint)| {
18163 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18164 let is_boundary = index == text.len()
18165 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18166 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18167 if is_boundary {
18168 let chunk = &text[prev_index..index];
18169 prev_index = index;
18170 Some(chunk)
18171 } else {
18172 None
18173 }
18174 })
18175}
18176
18177pub trait RangeToAnchorExt: Sized {
18178 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18179
18180 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18181 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18182 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18183 }
18184}
18185
18186impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18187 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18188 let start_offset = self.start.to_offset(snapshot);
18189 let end_offset = self.end.to_offset(snapshot);
18190 if start_offset == end_offset {
18191 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18192 } else {
18193 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18194 }
18195 }
18196}
18197
18198pub trait RowExt {
18199 fn as_f32(&self) -> f32;
18200
18201 fn next_row(&self) -> Self;
18202
18203 fn previous_row(&self) -> Self;
18204
18205 fn minus(&self, other: Self) -> u32;
18206}
18207
18208impl RowExt for DisplayRow {
18209 fn as_f32(&self) -> f32 {
18210 self.0 as f32
18211 }
18212
18213 fn next_row(&self) -> Self {
18214 Self(self.0 + 1)
18215 }
18216
18217 fn previous_row(&self) -> Self {
18218 Self(self.0.saturating_sub(1))
18219 }
18220
18221 fn minus(&self, other: Self) -> u32 {
18222 self.0 - other.0
18223 }
18224}
18225
18226impl RowExt for MultiBufferRow {
18227 fn as_f32(&self) -> f32 {
18228 self.0 as f32
18229 }
18230
18231 fn next_row(&self) -> Self {
18232 Self(self.0 + 1)
18233 }
18234
18235 fn previous_row(&self) -> Self {
18236 Self(self.0.saturating_sub(1))
18237 }
18238
18239 fn minus(&self, other: Self) -> u32 {
18240 self.0 - other.0
18241 }
18242}
18243
18244trait RowRangeExt {
18245 type Row;
18246
18247 fn len(&self) -> usize;
18248
18249 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18250}
18251
18252impl RowRangeExt for Range<MultiBufferRow> {
18253 type Row = MultiBufferRow;
18254
18255 fn len(&self) -> usize {
18256 (self.end.0 - self.start.0) as usize
18257 }
18258
18259 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18260 (self.start.0..self.end.0).map(MultiBufferRow)
18261 }
18262}
18263
18264impl RowRangeExt for Range<DisplayRow> {
18265 type Row = DisplayRow;
18266
18267 fn len(&self) -> usize {
18268 (self.end.0 - self.start.0) as usize
18269 }
18270
18271 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18272 (self.start.0..self.end.0).map(DisplayRow)
18273 }
18274}
18275
18276/// If select range has more than one line, we
18277/// just point the cursor to range.start.
18278fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18279 if range.start.row == range.end.row {
18280 range
18281 } else {
18282 range.start..range.start
18283 }
18284}
18285pub struct KillRing(ClipboardItem);
18286impl Global for KillRing {}
18287
18288const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18289
18290fn all_edits_insertions_or_deletions(
18291 edits: &Vec<(Range<Anchor>, String)>,
18292 snapshot: &MultiBufferSnapshot,
18293) -> bool {
18294 let mut all_insertions = true;
18295 let mut all_deletions = true;
18296
18297 for (range, new_text) in edits.iter() {
18298 let range_is_empty = range.to_offset(&snapshot).is_empty();
18299 let text_is_empty = new_text.is_empty();
18300
18301 if range_is_empty != text_is_empty {
18302 if range_is_empty {
18303 all_deletions = false;
18304 } else {
18305 all_insertions = false;
18306 }
18307 } else {
18308 return false;
18309 }
18310
18311 if !all_insertions && !all_deletions {
18312 return false;
18313 }
18314 }
18315 all_insertions || all_deletions
18316}
18317
18318#[derive(Debug, Clone, Copy, PartialEq)]
18319pub struct LineHighlight {
18320 pub background: Background,
18321 pub border: Option<gpui::Hsla>,
18322}
18323
18324impl From<Hsla> for LineHighlight {
18325 fn from(hsla: Hsla) -> Self {
18326 Self {
18327 background: hsla.into(),
18328 border: None,
18329 }
18330 }
18331}
18332
18333impl From<Background> for LineHighlight {
18334 fn from(background: Background) -> Self {
18335 Self {
18336 background,
18337 border: None,
18338 }
18339 }
18340}