1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::{DiffHunkSecondaryStatus, DiffHunkStatus};
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use ::git::{status::FileStatus, Restore};
77use code_context_menus::{
78 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
79 CompletionsMenu, ContextMenuOrigin,
80};
81use git::blame::GitBlame;
82use gpui::{
83 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
84 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
85 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
86 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
87 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
88 ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task,
89 TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
90 WeakEntity, WeakFocusHandle, Window,
91};
92use highlight_matching_bracket::refresh_matching_bracket_highlights;
93use hover_popover::{hide_hover, HoverState};
94use indent_guides::ActiveIndentGuidesState;
95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
96pub use inline_completion::Direction;
97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
98pub use items::MAX_TAB_TITLE_LEN;
99use itertools::Itertools;
100use language::{
101 language_settings::{
102 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
103 },
104 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
105 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
106 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
107 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
108};
109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
110use linked_editing_ranges::refresh_linked_ranges;
111use mouse_context_menu::MouseContextMenu;
112use persistence::DB;
113pub use proposed_changes_editor::{
114 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
115};
116use smallvec::smallvec;
117use std::iter::Peekable;
118use task::{ResolvedTask, TaskTemplate, TaskVariables};
119
120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
121pub use lsp::CompletionContext;
122use lsp::{
123 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
124 LanguageServerId, LanguageServerName,
125};
126
127use language::BufferSnapshot;
128use movement::TextLayoutDetails;
129pub use multi_buffer::{
130 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
131 ToOffset, ToPoint,
132};
133use multi_buffer::{
134 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
135 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
136};
137use project::{
138 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
139 project_settings::{GitGutterSetting, ProjectSettings},
140 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
141 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
142};
143use rand::prelude::*;
144use rpc::{proto::*, ErrorExt};
145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
146use selections_collection::{
147 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
148};
149use serde::{Deserialize, Serialize};
150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
151use smallvec::SmallVec;
152use snippet::Snippet;
153use std::{
154 any::TypeId,
155 borrow::Cow,
156 cell::RefCell,
157 cmp::{self, Ordering, Reverse},
158 mem,
159 num::NonZeroU32,
160 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
161 path::{Path, PathBuf},
162 rc::Rc,
163 sync::Arc,
164 time::{Duration, Instant},
165};
166pub use sum_tree::Bias;
167use sum_tree::TreeMap;
168use text::{BufferId, OffsetUtf16, Rope};
169use theme::{
170 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
171 ThemeColors, ThemeSettings,
172};
173use ui::{
174 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
175 Tooltip,
176};
177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
178use workspace::{
179 item::{ItemHandle, PreviewTabsSettings},
180 ItemId, RestoreOnStartupBehavior,
181};
182use workspace::{
183 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
184 WorkspaceSettings,
185};
186use workspace::{
187 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
188};
189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
190
191use crate::hover_links::{find_url, find_url_from_range};
192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
193
194pub const FILE_HEADER_HEIGHT: u32 = 2;
195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
199const MAX_LINE_LEN: usize = 1024;
200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
203#[doc(hidden)]
204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
205
206pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
207pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
208
209pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
210pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
211
212const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
213 alt: true,
214 shift: true,
215 control: false,
216 platform: false,
217 function: false,
218};
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
221pub enum InlayId {
222 InlineCompletion(usize),
223 Hint(usize),
224}
225
226impl InlayId {
227 fn id(&self) -> usize {
228 match self {
229 Self::InlineCompletion(id) => *id,
230 Self::Hint(id) => *id,
231 }
232 }
233}
234
235enum DocumentHighlightRead {}
236enum DocumentHighlightWrite {}
237enum InputComposition {}
238enum SelectedTextHighlight {}
239
240#[derive(Debug, Copy, Clone, PartialEq, Eq)]
241pub enum Navigated {
242 Yes,
243 No,
244}
245
246impl Navigated {
247 pub fn from_bool(yes: bool) -> Navigated {
248 if yes {
249 Navigated::Yes
250 } else {
251 Navigated::No
252 }
253 }
254}
255
256#[derive(Debug, Clone, PartialEq, Eq)]
257enum DisplayDiffHunk {
258 Folded {
259 display_row: DisplayRow,
260 },
261 Unfolded {
262 diff_base_byte_range: Range<usize>,
263 display_row_range: Range<DisplayRow>,
264 multi_buffer_range: Range<Anchor>,
265 status: DiffHunkStatus,
266 },
267}
268
269pub fn init_settings(cx: &mut App) {
270 EditorSettings::register(cx);
271}
272
273pub fn init(cx: &mut App) {
274 init_settings(cx);
275
276 workspace::register_project_item::<Editor>(cx);
277 workspace::FollowableViewRegistry::register::<Editor>(cx);
278 workspace::register_serializable_item::<Editor>(cx);
279
280 cx.observe_new(
281 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
282 workspace.register_action(Editor::new_file);
283 workspace.register_action(Editor::new_file_vertical);
284 workspace.register_action(Editor::new_file_horizontal);
285 workspace.register_action(Editor::cancel_language_server_work);
286 },
287 )
288 .detach();
289
290 cx.on_action(move |_: &workspace::NewFile, cx| {
291 let app_state = workspace::AppState::global(cx);
292 if let Some(app_state) = app_state.upgrade() {
293 workspace::open_new(
294 Default::default(),
295 app_state,
296 cx,
297 |workspace, window, cx| {
298 Editor::new_file(workspace, &Default::default(), window, cx)
299 },
300 )
301 .detach();
302 }
303 });
304 cx.on_action(move |_: &workspace::NewWindow, cx| {
305 let app_state = workspace::AppState::global(cx);
306 if let Some(app_state) = app_state.upgrade() {
307 workspace::open_new(
308 Default::default(),
309 app_state,
310 cx,
311 |workspace, window, cx| {
312 cx.activate(true);
313 Editor::new_file(workspace, &Default::default(), window, cx)
314 },
315 )
316 .detach();
317 }
318 });
319}
320
321pub struct SearchWithinRange;
322
323trait InvalidationRegion {
324 fn ranges(&self) -> &[Range<Anchor>];
325}
326
327#[derive(Clone, Debug, PartialEq)]
328pub enum SelectPhase {
329 Begin {
330 position: DisplayPoint,
331 add: bool,
332 click_count: usize,
333 },
334 BeginColumnar {
335 position: DisplayPoint,
336 reset: bool,
337 goal_column: u32,
338 },
339 Extend {
340 position: DisplayPoint,
341 click_count: usize,
342 },
343 Update {
344 position: DisplayPoint,
345 goal_column: u32,
346 scroll_delta: gpui::Point<f32>,
347 },
348 End,
349}
350
351#[derive(Clone, Debug)]
352pub enum SelectMode {
353 Character,
354 Word(Range<Anchor>),
355 Line(Range<Anchor>),
356 All,
357}
358
359#[derive(Copy, Clone, PartialEq, Eq, Debug)]
360pub enum EditorMode {
361 SingleLine { auto_width: bool },
362 AutoHeight { max_lines: usize },
363 Full,
364}
365
366#[derive(Copy, Clone, Debug)]
367pub enum SoftWrap {
368 /// Prefer not to wrap at all.
369 ///
370 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
371 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
372 GitDiff,
373 /// Prefer a single line generally, unless an overly long line is encountered.
374 None,
375 /// Soft wrap lines that exceed the editor width.
376 EditorWidth,
377 /// Soft wrap lines at the preferred line length.
378 Column(u32),
379 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
380 Bounded(u32),
381}
382
383#[derive(Clone)]
384pub struct EditorStyle {
385 pub background: Hsla,
386 pub local_player: PlayerColor,
387 pub text: TextStyle,
388 pub scrollbar_width: Pixels,
389 pub syntax: Arc<SyntaxTheme>,
390 pub status: StatusColors,
391 pub inlay_hints_style: HighlightStyle,
392 pub inline_completion_styles: InlineCompletionStyles,
393 pub unnecessary_code_fade: f32,
394}
395
396impl Default for EditorStyle {
397 fn default() -> Self {
398 Self {
399 background: Hsla::default(),
400 local_player: PlayerColor::default(),
401 text: TextStyle::default(),
402 scrollbar_width: Pixels::default(),
403 syntax: Default::default(),
404 // HACK: Status colors don't have a real default.
405 // We should look into removing the status colors from the editor
406 // style and retrieve them directly from the theme.
407 status: StatusColors::dark(),
408 inlay_hints_style: HighlightStyle::default(),
409 inline_completion_styles: InlineCompletionStyles {
410 insertion: HighlightStyle::default(),
411 whitespace: HighlightStyle::default(),
412 },
413 unnecessary_code_fade: Default::default(),
414 }
415 }
416}
417
418pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
419 let show_background = language_settings::language_settings(None, None, cx)
420 .inlay_hints
421 .show_background;
422
423 HighlightStyle {
424 color: Some(cx.theme().status().hint),
425 background_color: show_background.then(|| cx.theme().status().hint_background),
426 ..HighlightStyle::default()
427 }
428}
429
430pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
431 InlineCompletionStyles {
432 insertion: HighlightStyle {
433 color: Some(cx.theme().status().predictive),
434 ..HighlightStyle::default()
435 },
436 whitespace: HighlightStyle {
437 background_color: Some(cx.theme().status().created_background),
438 ..HighlightStyle::default()
439 },
440 }
441}
442
443type CompletionId = usize;
444
445pub(crate) enum EditDisplayMode {
446 TabAccept,
447 DiffPopover,
448 Inline,
449}
450
451enum InlineCompletion {
452 Edit {
453 edits: Vec<(Range<Anchor>, String)>,
454 edit_preview: Option<EditPreview>,
455 display_mode: EditDisplayMode,
456 snapshot: BufferSnapshot,
457 },
458 Move {
459 target: Anchor,
460 snapshot: BufferSnapshot,
461 },
462}
463
464struct InlineCompletionState {
465 inlay_ids: Vec<InlayId>,
466 completion: InlineCompletion,
467 completion_id: Option<SharedString>,
468 invalidation_range: Range<Anchor>,
469}
470
471enum EditPredictionSettings {
472 Disabled,
473 Enabled {
474 show_in_menu: bool,
475 preview_requires_modifier: bool,
476 },
477}
478
479enum InlineCompletionHighlight {}
480
481#[derive(Debug, Clone)]
482struct InlineDiagnostic {
483 message: SharedString,
484 group_id: usize,
485 is_primary: bool,
486 start: Point,
487 severity: DiagnosticSeverity,
488}
489
490pub enum MenuInlineCompletionsPolicy {
491 Never,
492 ByProvider,
493}
494
495pub enum EditPredictionPreview {
496 /// Modifier is not pressed
497 Inactive { released_too_fast: bool },
498 /// Modifier pressed
499 Active {
500 since: Instant,
501 previous_scroll_position: Option<ScrollAnchor>,
502 },
503}
504
505impl EditPredictionPreview {
506 pub fn released_too_fast(&self) -> bool {
507 match self {
508 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
509 EditPredictionPreview::Active { .. } => false,
510 }
511 }
512
513 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
514 if let EditPredictionPreview::Active {
515 previous_scroll_position,
516 ..
517 } = self
518 {
519 *previous_scroll_position = scroll_position;
520 }
521 }
522}
523
524#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
525struct EditorActionId(usize);
526
527impl EditorActionId {
528 pub fn post_inc(&mut self) -> Self {
529 let answer = self.0;
530
531 *self = Self(answer + 1);
532
533 Self(answer)
534 }
535}
536
537// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
538// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
539
540type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
541type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
542
543#[derive(Default)]
544struct ScrollbarMarkerState {
545 scrollbar_size: Size<Pixels>,
546 dirty: bool,
547 markers: Arc<[PaintQuad]>,
548 pending_refresh: Option<Task<Result<()>>>,
549}
550
551impl ScrollbarMarkerState {
552 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
553 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
554 }
555}
556
557#[derive(Clone, Debug)]
558struct RunnableTasks {
559 templates: Vec<(TaskSourceKind, TaskTemplate)>,
560 offset: multi_buffer::Anchor,
561 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
562 column: u32,
563 // Values of all named captures, including those starting with '_'
564 extra_variables: HashMap<String, String>,
565 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
566 context_range: Range<BufferOffset>,
567}
568
569impl RunnableTasks {
570 fn resolve<'a>(
571 &'a self,
572 cx: &'a task::TaskContext,
573 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
574 self.templates.iter().filter_map(|(kind, template)| {
575 template
576 .resolve_task(&kind.to_id_base(), cx)
577 .map(|task| (kind.clone(), task))
578 })
579 }
580}
581
582#[derive(Clone)]
583struct ResolvedTasks {
584 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
585 position: Anchor,
586}
587#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
588struct BufferOffset(usize);
589
590// Addons allow storing per-editor state in other crates (e.g. Vim)
591pub trait Addon: 'static {
592 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
593
594 fn render_buffer_header_controls(
595 &self,
596 _: &ExcerptInfo,
597 _: &Window,
598 _: &App,
599 ) -> Option<AnyElement> {
600 None
601 }
602
603 fn to_any(&self) -> &dyn std::any::Any;
604}
605
606#[derive(Debug, Copy, Clone, PartialEq, Eq)]
607pub enum IsVimMode {
608 Yes,
609 No,
610}
611
612/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
613///
614/// See the [module level documentation](self) for more information.
615pub struct Editor {
616 focus_handle: FocusHandle,
617 last_focused_descendant: Option<WeakFocusHandle>,
618 /// The text buffer being edited
619 buffer: Entity<MultiBuffer>,
620 /// Map of how text in the buffer should be displayed.
621 /// Handles soft wraps, folds, fake inlay text insertions, etc.
622 pub display_map: Entity<DisplayMap>,
623 pub selections: SelectionsCollection,
624 pub scroll_manager: ScrollManager,
625 /// When inline assist editors are linked, they all render cursors because
626 /// typing enters text into each of them, even the ones that aren't focused.
627 pub(crate) show_cursor_when_unfocused: bool,
628 columnar_selection_tail: Option<Anchor>,
629 add_selections_state: Option<AddSelectionsState>,
630 select_next_state: Option<SelectNextState>,
631 select_prev_state: Option<SelectNextState>,
632 selection_history: SelectionHistory,
633 autoclose_regions: Vec<AutocloseRegion>,
634 snippet_stack: InvalidationStack<SnippetState>,
635 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
636 ime_transaction: Option<TransactionId>,
637 active_diagnostics: Option<ActiveDiagnosticGroup>,
638 show_inline_diagnostics: bool,
639 inline_diagnostics_update: Task<()>,
640 inline_diagnostics_enabled: bool,
641 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
642 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
643
644 // TODO: make this a access method
645 pub project: Option<Entity<Project>>,
646 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
647 completion_provider: Option<Box<dyn CompletionProvider>>,
648 collaboration_hub: Option<Box<dyn CollaborationHub>>,
649 blink_manager: Entity<BlinkManager>,
650 show_cursor_names: bool,
651 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
652 pub show_local_selections: bool,
653 mode: EditorMode,
654 show_breadcrumbs: bool,
655 show_gutter: bool,
656 show_scrollbars: bool,
657 show_line_numbers: Option<bool>,
658 use_relative_line_numbers: Option<bool>,
659 show_git_diff_gutter: Option<bool>,
660 show_code_actions: Option<bool>,
661 show_runnables: Option<bool>,
662 show_wrap_guides: Option<bool>,
663 show_indent_guides: Option<bool>,
664 placeholder_text: Option<Arc<str>>,
665 highlight_order: usize,
666 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
667 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
668 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
669 scrollbar_marker_state: ScrollbarMarkerState,
670 active_indent_guides_state: ActiveIndentGuidesState,
671 nav_history: Option<ItemNavHistory>,
672 context_menu: RefCell<Option<CodeContextMenu>>,
673 mouse_context_menu: Option<MouseContextMenu>,
674 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
675 signature_help_state: SignatureHelpState,
676 auto_signature_help: Option<bool>,
677 find_all_references_task_sources: Vec<Anchor>,
678 next_completion_id: CompletionId,
679 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
680 code_actions_task: Option<Task<Result<()>>>,
681 selection_highlight_task: Option<Task<()>>,
682 document_highlights_task: Option<Task<()>>,
683 linked_editing_range_task: Option<Task<Option<()>>>,
684 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
685 pending_rename: Option<RenameState>,
686 searchable: bool,
687 cursor_shape: CursorShape,
688 current_line_highlight: Option<CurrentLineHighlight>,
689 collapse_matches: bool,
690 autoindent_mode: Option<AutoindentMode>,
691 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
692 input_enabled: bool,
693 use_modal_editing: bool,
694 read_only: bool,
695 leader_peer_id: Option<PeerId>,
696 remote_id: Option<ViewId>,
697 hover_state: HoverState,
698 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
699 gutter_hovered: bool,
700 hovered_link_state: Option<HoveredLinkState>,
701 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
702 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
703 active_inline_completion: Option<InlineCompletionState>,
704 /// Used to prevent flickering as the user types while the menu is open
705 stale_inline_completion_in_menu: Option<InlineCompletionState>,
706 edit_prediction_settings: EditPredictionSettings,
707 inline_completions_hidden_for_vim_mode: bool,
708 show_inline_completions_override: Option<bool>,
709 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
710 edit_prediction_preview: EditPredictionPreview,
711 edit_prediction_indent_conflict: bool,
712 edit_prediction_requires_modifier_in_indent_conflict: bool,
713 inlay_hint_cache: InlayHintCache,
714 next_inlay_id: usize,
715 _subscriptions: Vec<Subscription>,
716 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
717 gutter_dimensions: GutterDimensions,
718 style: Option<EditorStyle>,
719 text_style_refinement: Option<TextStyleRefinement>,
720 next_editor_action_id: EditorActionId,
721 editor_actions:
722 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
723 use_autoclose: bool,
724 use_auto_surround: bool,
725 auto_replace_emoji_shortcode: bool,
726 show_git_blame_gutter: bool,
727 show_git_blame_inline: bool,
728 show_git_blame_inline_delay_task: Option<Task<()>>,
729 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
730 git_blame_inline_enabled: bool,
731 serialize_dirty_buffers: bool,
732 show_selection_menu: Option<bool>,
733 blame: Option<Entity<GitBlame>>,
734 blame_subscription: Option<Subscription>,
735 custom_context_menu: Option<
736 Box<
737 dyn 'static
738 + Fn(
739 &mut Self,
740 DisplayPoint,
741 &mut Window,
742 &mut Context<Self>,
743 ) -> Option<Entity<ui::ContextMenu>>,
744 >,
745 >,
746 last_bounds: Option<Bounds<Pixels>>,
747 last_position_map: Option<Rc<PositionMap>>,
748 expect_bounds_change: Option<Bounds<Pixels>>,
749 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
750 tasks_update_task: Option<Task<()>>,
751 in_project_search: bool,
752 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
753 breadcrumb_header: Option<String>,
754 focused_block: Option<FocusedBlock>,
755 next_scroll_position: NextScrollCursorCenterTopBottom,
756 addons: HashMap<TypeId, Box<dyn Addon>>,
757 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
758 load_diff_task: Option<Shared<Task<()>>>,
759 selection_mark_mode: bool,
760 toggle_fold_multiple_buffers: Task<()>,
761 _scroll_cursor_center_top_bottom_task: Task<()>,
762 serialize_selections: Task<()>,
763}
764
765#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
766enum NextScrollCursorCenterTopBottom {
767 #[default]
768 Center,
769 Top,
770 Bottom,
771}
772
773impl NextScrollCursorCenterTopBottom {
774 fn next(&self) -> Self {
775 match self {
776 Self::Center => Self::Top,
777 Self::Top => Self::Bottom,
778 Self::Bottom => Self::Center,
779 }
780 }
781}
782
783#[derive(Clone)]
784pub struct EditorSnapshot {
785 pub mode: EditorMode,
786 show_gutter: bool,
787 show_line_numbers: Option<bool>,
788 show_git_diff_gutter: Option<bool>,
789 show_code_actions: Option<bool>,
790 show_runnables: Option<bool>,
791 git_blame_gutter_max_author_length: Option<usize>,
792 pub display_snapshot: DisplaySnapshot,
793 pub placeholder_text: Option<Arc<str>>,
794 is_focused: bool,
795 scroll_anchor: ScrollAnchor,
796 ongoing_scroll: OngoingScroll,
797 current_line_highlight: CurrentLineHighlight,
798 gutter_hovered: bool,
799}
800
801const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
802
803#[derive(Default, Debug, Clone, Copy)]
804pub struct GutterDimensions {
805 pub left_padding: Pixels,
806 pub right_padding: Pixels,
807 pub width: Pixels,
808 pub margin: Pixels,
809 pub git_blame_entries_width: Option<Pixels>,
810}
811
812impl GutterDimensions {
813 /// The full width of the space taken up by the gutter.
814 pub fn full_width(&self) -> Pixels {
815 self.margin + self.width
816 }
817
818 /// The width of the space reserved for the fold indicators,
819 /// use alongside 'justify_end' and `gutter_width` to
820 /// right align content with the line numbers
821 pub fn fold_area_width(&self) -> Pixels {
822 self.margin + self.right_padding
823 }
824}
825
826#[derive(Debug)]
827pub struct RemoteSelection {
828 pub replica_id: ReplicaId,
829 pub selection: Selection<Anchor>,
830 pub cursor_shape: CursorShape,
831 pub peer_id: PeerId,
832 pub line_mode: bool,
833 pub participant_index: Option<ParticipantIndex>,
834 pub user_name: Option<SharedString>,
835}
836
837#[derive(Clone, Debug)]
838struct SelectionHistoryEntry {
839 selections: Arc<[Selection<Anchor>]>,
840 select_next_state: Option<SelectNextState>,
841 select_prev_state: Option<SelectNextState>,
842 add_selections_state: Option<AddSelectionsState>,
843}
844
845enum SelectionHistoryMode {
846 Normal,
847 Undoing,
848 Redoing,
849}
850
851#[derive(Clone, PartialEq, Eq, Hash)]
852struct HoveredCursor {
853 replica_id: u16,
854 selection_id: usize,
855}
856
857impl Default for SelectionHistoryMode {
858 fn default() -> Self {
859 Self::Normal
860 }
861}
862
863#[derive(Default)]
864struct SelectionHistory {
865 #[allow(clippy::type_complexity)]
866 selections_by_transaction:
867 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
868 mode: SelectionHistoryMode,
869 undo_stack: VecDeque<SelectionHistoryEntry>,
870 redo_stack: VecDeque<SelectionHistoryEntry>,
871}
872
873impl SelectionHistory {
874 fn insert_transaction(
875 &mut self,
876 transaction_id: TransactionId,
877 selections: Arc<[Selection<Anchor>]>,
878 ) {
879 self.selections_by_transaction
880 .insert(transaction_id, (selections, None));
881 }
882
883 #[allow(clippy::type_complexity)]
884 fn transaction(
885 &self,
886 transaction_id: TransactionId,
887 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
888 self.selections_by_transaction.get(&transaction_id)
889 }
890
891 #[allow(clippy::type_complexity)]
892 fn transaction_mut(
893 &mut self,
894 transaction_id: TransactionId,
895 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
896 self.selections_by_transaction.get_mut(&transaction_id)
897 }
898
899 fn push(&mut self, entry: SelectionHistoryEntry) {
900 if !entry.selections.is_empty() {
901 match self.mode {
902 SelectionHistoryMode::Normal => {
903 self.push_undo(entry);
904 self.redo_stack.clear();
905 }
906 SelectionHistoryMode::Undoing => self.push_redo(entry),
907 SelectionHistoryMode::Redoing => self.push_undo(entry),
908 }
909 }
910 }
911
912 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
913 if self
914 .undo_stack
915 .back()
916 .map_or(true, |e| e.selections != entry.selections)
917 {
918 self.undo_stack.push_back(entry);
919 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
920 self.undo_stack.pop_front();
921 }
922 }
923 }
924
925 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
926 if self
927 .redo_stack
928 .back()
929 .map_or(true, |e| e.selections != entry.selections)
930 {
931 self.redo_stack.push_back(entry);
932 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
933 self.redo_stack.pop_front();
934 }
935 }
936 }
937}
938
939struct RowHighlight {
940 index: usize,
941 range: Range<Anchor>,
942 color: Hsla,
943 should_autoscroll: bool,
944}
945
946#[derive(Clone, Debug)]
947struct AddSelectionsState {
948 above: bool,
949 stack: Vec<usize>,
950}
951
952#[derive(Clone)]
953struct SelectNextState {
954 query: AhoCorasick,
955 wordwise: bool,
956 done: bool,
957}
958
959impl std::fmt::Debug for SelectNextState {
960 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
961 f.debug_struct(std::any::type_name::<Self>())
962 .field("wordwise", &self.wordwise)
963 .field("done", &self.done)
964 .finish()
965 }
966}
967
968#[derive(Debug)]
969struct AutocloseRegion {
970 selection_id: usize,
971 range: Range<Anchor>,
972 pair: BracketPair,
973}
974
975#[derive(Debug)]
976struct SnippetState {
977 ranges: Vec<Vec<Range<Anchor>>>,
978 active_index: usize,
979 choices: Vec<Option<Vec<String>>>,
980}
981
982#[doc(hidden)]
983pub struct RenameState {
984 pub range: Range<Anchor>,
985 pub old_name: Arc<str>,
986 pub editor: Entity<Editor>,
987 block_id: CustomBlockId,
988}
989
990struct InvalidationStack<T>(Vec<T>);
991
992struct RegisteredInlineCompletionProvider {
993 provider: Arc<dyn InlineCompletionProviderHandle>,
994 _subscription: Subscription,
995}
996
997#[derive(Debug)]
998struct ActiveDiagnosticGroup {
999 primary_range: Range<Anchor>,
1000 primary_message: String,
1001 group_id: usize,
1002 blocks: HashMap<CustomBlockId, Diagnostic>,
1003 is_valid: bool,
1004}
1005
1006#[derive(Serialize, Deserialize, Clone, Debug)]
1007pub struct ClipboardSelection {
1008 /// The number of bytes in this selection.
1009 pub len: usize,
1010 /// Whether this was a full-line selection.
1011 pub is_entire_line: bool,
1012 /// The column where this selection originally started.
1013 pub start_column: u32,
1014}
1015
1016#[derive(Debug)]
1017pub(crate) struct NavigationData {
1018 cursor_anchor: Anchor,
1019 cursor_position: Point,
1020 scroll_anchor: ScrollAnchor,
1021 scroll_top_row: u32,
1022}
1023
1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1025pub enum GotoDefinitionKind {
1026 Symbol,
1027 Declaration,
1028 Type,
1029 Implementation,
1030}
1031
1032#[derive(Debug, Clone)]
1033enum InlayHintRefreshReason {
1034 Toggle(bool),
1035 SettingsChange(InlayHintSettings),
1036 NewLinesShown,
1037 BufferEdited(HashSet<Arc<Language>>),
1038 RefreshRequested,
1039 ExcerptsRemoved(Vec<ExcerptId>),
1040}
1041
1042impl InlayHintRefreshReason {
1043 fn description(&self) -> &'static str {
1044 match self {
1045 Self::Toggle(_) => "toggle",
1046 Self::SettingsChange(_) => "settings change",
1047 Self::NewLinesShown => "new lines shown",
1048 Self::BufferEdited(_) => "buffer edited",
1049 Self::RefreshRequested => "refresh requested",
1050 Self::ExcerptsRemoved(_) => "excerpts removed",
1051 }
1052 }
1053}
1054
1055pub enum FormatTarget {
1056 Buffers,
1057 Ranges(Vec<Range<MultiBufferPoint>>),
1058}
1059
1060pub(crate) struct FocusedBlock {
1061 id: BlockId,
1062 focus_handle: WeakFocusHandle,
1063}
1064
1065#[derive(Clone)]
1066enum JumpData {
1067 MultiBufferRow {
1068 row: MultiBufferRow,
1069 line_offset_from_top: u32,
1070 },
1071 MultiBufferPoint {
1072 excerpt_id: ExcerptId,
1073 position: Point,
1074 anchor: text::Anchor,
1075 line_offset_from_top: u32,
1076 },
1077}
1078
1079pub enum MultibufferSelectionMode {
1080 First,
1081 All,
1082}
1083
1084impl Editor {
1085 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1086 let buffer = cx.new(|cx| Buffer::local("", cx));
1087 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1088 Self::new(
1089 EditorMode::SingleLine { auto_width: false },
1090 buffer,
1091 None,
1092 false,
1093 window,
1094 cx,
1095 )
1096 }
1097
1098 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1099 let buffer = cx.new(|cx| Buffer::local("", cx));
1100 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1101 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1102 }
1103
1104 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1105 let buffer = cx.new(|cx| Buffer::local("", cx));
1106 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1107 Self::new(
1108 EditorMode::SingleLine { auto_width: true },
1109 buffer,
1110 None,
1111 false,
1112 window,
1113 cx,
1114 )
1115 }
1116
1117 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1118 let buffer = cx.new(|cx| Buffer::local("", cx));
1119 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1120 Self::new(
1121 EditorMode::AutoHeight { max_lines },
1122 buffer,
1123 None,
1124 false,
1125 window,
1126 cx,
1127 )
1128 }
1129
1130 pub fn for_buffer(
1131 buffer: Entity<Buffer>,
1132 project: Option<Entity<Project>>,
1133 window: &mut Window,
1134 cx: &mut Context<Self>,
1135 ) -> Self {
1136 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1137 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1138 }
1139
1140 pub fn for_multibuffer(
1141 buffer: Entity<MultiBuffer>,
1142 project: Option<Entity<Project>>,
1143 show_excerpt_controls: bool,
1144 window: &mut Window,
1145 cx: &mut Context<Self>,
1146 ) -> Self {
1147 Self::new(
1148 EditorMode::Full,
1149 buffer,
1150 project,
1151 show_excerpt_controls,
1152 window,
1153 cx,
1154 )
1155 }
1156
1157 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1158 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1159 let mut clone = Self::new(
1160 self.mode,
1161 self.buffer.clone(),
1162 self.project.clone(),
1163 show_excerpt_controls,
1164 window,
1165 cx,
1166 );
1167 self.display_map.update(cx, |display_map, cx| {
1168 let snapshot = display_map.snapshot(cx);
1169 clone.display_map.update(cx, |display_map, cx| {
1170 display_map.set_state(&snapshot, cx);
1171 });
1172 });
1173 clone.selections.clone_state(&self.selections);
1174 clone.scroll_manager.clone_state(&self.scroll_manager);
1175 clone.searchable = self.searchable;
1176 clone
1177 }
1178
1179 pub fn new(
1180 mode: EditorMode,
1181 buffer: Entity<MultiBuffer>,
1182 project: Option<Entity<Project>>,
1183 show_excerpt_controls: bool,
1184 window: &mut Window,
1185 cx: &mut Context<Self>,
1186 ) -> Self {
1187 let style = window.text_style();
1188 let font_size = style.font_size.to_pixels(window.rem_size());
1189 let editor = cx.entity().downgrade();
1190 let fold_placeholder = FoldPlaceholder {
1191 constrain_width: true,
1192 render: Arc::new(move |fold_id, fold_range, cx| {
1193 let editor = editor.clone();
1194 div()
1195 .id(fold_id)
1196 .bg(cx.theme().colors().ghost_element_background)
1197 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1198 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1199 .rounded_sm()
1200 .size_full()
1201 .cursor_pointer()
1202 .child("⋯")
1203 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1204 .on_click(move |_, _window, cx| {
1205 editor
1206 .update(cx, |editor, cx| {
1207 editor.unfold_ranges(
1208 &[fold_range.start..fold_range.end],
1209 true,
1210 false,
1211 cx,
1212 );
1213 cx.stop_propagation();
1214 })
1215 .ok();
1216 })
1217 .into_any()
1218 }),
1219 merge_adjacent: true,
1220 ..Default::default()
1221 };
1222 let display_map = cx.new(|cx| {
1223 DisplayMap::new(
1224 buffer.clone(),
1225 style.font(),
1226 font_size,
1227 None,
1228 show_excerpt_controls,
1229 FILE_HEADER_HEIGHT,
1230 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1231 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1232 fold_placeholder,
1233 cx,
1234 )
1235 });
1236
1237 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1238
1239 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1240
1241 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1242 .then(|| language_settings::SoftWrap::None);
1243
1244 let mut project_subscriptions = Vec::new();
1245 if mode == EditorMode::Full {
1246 if let Some(project) = project.as_ref() {
1247 if buffer.read(cx).is_singleton() {
1248 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1249 cx.emit(EditorEvent::TitleChanged);
1250 }));
1251 }
1252 project_subscriptions.push(cx.subscribe_in(
1253 project,
1254 window,
1255 |editor, _, event, window, cx| {
1256 if let project::Event::RefreshInlayHints = event {
1257 editor
1258 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1259 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1260 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1261 let focus_handle = editor.focus_handle(cx);
1262 if focus_handle.is_focused(window) {
1263 let snapshot = buffer.read(cx).snapshot();
1264 for (range, snippet) in snippet_edits {
1265 let editor_range =
1266 language::range_from_lsp(*range).to_offset(&snapshot);
1267 editor
1268 .insert_snippet(
1269 &[editor_range],
1270 snippet.clone(),
1271 window,
1272 cx,
1273 )
1274 .ok();
1275 }
1276 }
1277 }
1278 }
1279 },
1280 ));
1281 if let Some(task_inventory) = project
1282 .read(cx)
1283 .task_store()
1284 .read(cx)
1285 .task_inventory()
1286 .cloned()
1287 {
1288 project_subscriptions.push(cx.observe_in(
1289 &task_inventory,
1290 window,
1291 |editor, _, window, cx| {
1292 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1293 },
1294 ));
1295 }
1296 }
1297 }
1298
1299 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1300
1301 let inlay_hint_settings =
1302 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1303 let focus_handle = cx.focus_handle();
1304 cx.on_focus(&focus_handle, window, Self::handle_focus)
1305 .detach();
1306 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1307 .detach();
1308 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1309 .detach();
1310 cx.on_blur(&focus_handle, window, Self::handle_blur)
1311 .detach();
1312
1313 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1314 Some(false)
1315 } else {
1316 None
1317 };
1318
1319 let mut code_action_providers = Vec::new();
1320 let mut load_uncommitted_diff = None;
1321 if let Some(project) = project.clone() {
1322 load_uncommitted_diff = Some(
1323 get_uncommitted_diff_for_buffer(
1324 &project,
1325 buffer.read(cx).all_buffers(),
1326 buffer.clone(),
1327 cx,
1328 )
1329 .shared(),
1330 );
1331 code_action_providers.push(Rc::new(project) as Rc<_>);
1332 }
1333
1334 let mut this = Self {
1335 focus_handle,
1336 show_cursor_when_unfocused: false,
1337 last_focused_descendant: None,
1338 buffer: buffer.clone(),
1339 display_map: display_map.clone(),
1340 selections,
1341 scroll_manager: ScrollManager::new(cx),
1342 columnar_selection_tail: None,
1343 add_selections_state: None,
1344 select_next_state: None,
1345 select_prev_state: None,
1346 selection_history: Default::default(),
1347 autoclose_regions: Default::default(),
1348 snippet_stack: Default::default(),
1349 select_larger_syntax_node_stack: Vec::new(),
1350 ime_transaction: Default::default(),
1351 active_diagnostics: None,
1352 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1353 inline_diagnostics_update: Task::ready(()),
1354 inline_diagnostics: Vec::new(),
1355 soft_wrap_mode_override,
1356 completion_provider: project.clone().map(|project| Box::new(project) as _),
1357 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1358 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1359 project,
1360 blink_manager: blink_manager.clone(),
1361 show_local_selections: true,
1362 show_scrollbars: true,
1363 mode,
1364 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1365 show_gutter: mode == EditorMode::Full,
1366 show_line_numbers: None,
1367 use_relative_line_numbers: None,
1368 show_git_diff_gutter: None,
1369 show_code_actions: None,
1370 show_runnables: None,
1371 show_wrap_guides: None,
1372 show_indent_guides,
1373 placeholder_text: None,
1374 highlight_order: 0,
1375 highlighted_rows: HashMap::default(),
1376 background_highlights: Default::default(),
1377 gutter_highlights: TreeMap::default(),
1378 scrollbar_marker_state: ScrollbarMarkerState::default(),
1379 active_indent_guides_state: ActiveIndentGuidesState::default(),
1380 nav_history: None,
1381 context_menu: RefCell::new(None),
1382 mouse_context_menu: None,
1383 completion_tasks: Default::default(),
1384 signature_help_state: SignatureHelpState::default(),
1385 auto_signature_help: None,
1386 find_all_references_task_sources: Vec::new(),
1387 next_completion_id: 0,
1388 next_inlay_id: 0,
1389 code_action_providers,
1390 available_code_actions: Default::default(),
1391 code_actions_task: Default::default(),
1392 selection_highlight_task: Default::default(),
1393 document_highlights_task: Default::default(),
1394 linked_editing_range_task: Default::default(),
1395 pending_rename: Default::default(),
1396 searchable: true,
1397 cursor_shape: EditorSettings::get_global(cx)
1398 .cursor_shape
1399 .unwrap_or_default(),
1400 current_line_highlight: None,
1401 autoindent_mode: Some(AutoindentMode::EachLine),
1402 collapse_matches: false,
1403 workspace: None,
1404 input_enabled: true,
1405 use_modal_editing: mode == EditorMode::Full,
1406 read_only: false,
1407 use_autoclose: true,
1408 use_auto_surround: true,
1409 auto_replace_emoji_shortcode: false,
1410 leader_peer_id: None,
1411 remote_id: None,
1412 hover_state: Default::default(),
1413 pending_mouse_down: None,
1414 hovered_link_state: Default::default(),
1415 edit_prediction_provider: None,
1416 active_inline_completion: None,
1417 stale_inline_completion_in_menu: None,
1418 edit_prediction_preview: EditPredictionPreview::Inactive {
1419 released_too_fast: false,
1420 },
1421 inline_diagnostics_enabled: mode == EditorMode::Full,
1422 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1423
1424 gutter_hovered: false,
1425 pixel_position_of_newest_cursor: None,
1426 last_bounds: None,
1427 last_position_map: None,
1428 expect_bounds_change: None,
1429 gutter_dimensions: GutterDimensions::default(),
1430 style: None,
1431 show_cursor_names: false,
1432 hovered_cursors: Default::default(),
1433 next_editor_action_id: EditorActionId::default(),
1434 editor_actions: Rc::default(),
1435 inline_completions_hidden_for_vim_mode: false,
1436 show_inline_completions_override: None,
1437 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1438 edit_prediction_settings: EditPredictionSettings::Disabled,
1439 edit_prediction_indent_conflict: false,
1440 edit_prediction_requires_modifier_in_indent_conflict: true,
1441 custom_context_menu: None,
1442 show_git_blame_gutter: false,
1443 show_git_blame_inline: false,
1444 show_selection_menu: None,
1445 show_git_blame_inline_delay_task: None,
1446 git_blame_inline_tooltip: None,
1447 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1448 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1449 .session
1450 .restore_unsaved_buffers,
1451 blame: None,
1452 blame_subscription: None,
1453 tasks: Default::default(),
1454 _subscriptions: vec![
1455 cx.observe(&buffer, Self::on_buffer_changed),
1456 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1457 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1458 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1459 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1460 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1461 cx.observe_window_activation(window, |editor, window, cx| {
1462 let active = window.is_window_active();
1463 editor.blink_manager.update(cx, |blink_manager, cx| {
1464 if active {
1465 blink_manager.enable(cx);
1466 } else {
1467 blink_manager.disable(cx);
1468 }
1469 });
1470 }),
1471 ],
1472 tasks_update_task: None,
1473 linked_edit_ranges: Default::default(),
1474 in_project_search: false,
1475 previous_search_ranges: None,
1476 breadcrumb_header: None,
1477 focused_block: None,
1478 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1479 addons: HashMap::default(),
1480 registered_buffers: HashMap::default(),
1481 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1482 selection_mark_mode: false,
1483 toggle_fold_multiple_buffers: Task::ready(()),
1484 serialize_selections: Task::ready(()),
1485 text_style_refinement: None,
1486 load_diff_task: load_uncommitted_diff,
1487 };
1488 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1489 this._subscriptions.extend(project_subscriptions);
1490
1491 this.end_selection(window, cx);
1492 this.scroll_manager.show_scrollbar(window, cx);
1493
1494 if mode == EditorMode::Full {
1495 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1496 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1497
1498 if this.git_blame_inline_enabled {
1499 this.git_blame_inline_enabled = true;
1500 this.start_git_blame_inline(false, window, cx);
1501 }
1502
1503 if let Some(buffer) = buffer.read(cx).as_singleton() {
1504 if let Some(project) = this.project.as_ref() {
1505 let handle = project.update(cx, |project, cx| {
1506 project.register_buffer_with_language_servers(&buffer, cx)
1507 });
1508 this.registered_buffers
1509 .insert(buffer.read(cx).remote_id(), handle);
1510 }
1511 }
1512 }
1513
1514 this.report_editor_event("Editor Opened", None, cx);
1515 this
1516 }
1517
1518 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1519 self.mouse_context_menu
1520 .as_ref()
1521 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1522 }
1523
1524 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1525 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1526 }
1527
1528 fn key_context_internal(
1529 &self,
1530 has_active_edit_prediction: bool,
1531 window: &Window,
1532 cx: &App,
1533 ) -> KeyContext {
1534 let mut key_context = KeyContext::new_with_defaults();
1535 key_context.add("Editor");
1536 let mode = match self.mode {
1537 EditorMode::SingleLine { .. } => "single_line",
1538 EditorMode::AutoHeight { .. } => "auto_height",
1539 EditorMode::Full => "full",
1540 };
1541
1542 if EditorSettings::jupyter_enabled(cx) {
1543 key_context.add("jupyter");
1544 }
1545
1546 key_context.set("mode", mode);
1547 if self.pending_rename.is_some() {
1548 key_context.add("renaming");
1549 }
1550
1551 match self.context_menu.borrow().as_ref() {
1552 Some(CodeContextMenu::Completions(_)) => {
1553 key_context.add("menu");
1554 key_context.add("showing_completions");
1555 }
1556 Some(CodeContextMenu::CodeActions(_)) => {
1557 key_context.add("menu");
1558 key_context.add("showing_code_actions")
1559 }
1560 None => {}
1561 }
1562
1563 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1564 if !self.focus_handle(cx).contains_focused(window, cx)
1565 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1566 {
1567 for addon in self.addons.values() {
1568 addon.extend_key_context(&mut key_context, cx)
1569 }
1570 }
1571
1572 if let Some(extension) = self
1573 .buffer
1574 .read(cx)
1575 .as_singleton()
1576 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1577 {
1578 key_context.set("extension", extension.to_string());
1579 }
1580
1581 if has_active_edit_prediction {
1582 if self.edit_prediction_in_conflict() {
1583 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1584 } else {
1585 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1586 key_context.add("copilot_suggestion");
1587 }
1588 }
1589
1590 if self.selection_mark_mode {
1591 key_context.add("selection_mode");
1592 }
1593
1594 key_context
1595 }
1596
1597 pub fn edit_prediction_in_conflict(&self) -> bool {
1598 if !self.show_edit_predictions_in_menu() {
1599 return false;
1600 }
1601
1602 let showing_completions = self
1603 .context_menu
1604 .borrow()
1605 .as_ref()
1606 .map_or(false, |context| {
1607 matches!(context, CodeContextMenu::Completions(_))
1608 });
1609
1610 showing_completions
1611 || self.edit_prediction_requires_modifier()
1612 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1613 // bindings to insert tab characters.
1614 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1615 }
1616
1617 pub fn accept_edit_prediction_keybind(
1618 &self,
1619 window: &Window,
1620 cx: &App,
1621 ) -> AcceptEditPredictionBinding {
1622 let key_context = self.key_context_internal(true, window, cx);
1623 let in_conflict = self.edit_prediction_in_conflict();
1624
1625 AcceptEditPredictionBinding(
1626 window
1627 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1628 .into_iter()
1629 .filter(|binding| {
1630 !in_conflict
1631 || binding
1632 .keystrokes()
1633 .first()
1634 .map_or(false, |keystroke| keystroke.modifiers.modified())
1635 })
1636 .rev()
1637 .min_by_key(|binding| {
1638 binding
1639 .keystrokes()
1640 .first()
1641 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1642 }),
1643 )
1644 }
1645
1646 pub fn new_file(
1647 workspace: &mut Workspace,
1648 _: &workspace::NewFile,
1649 window: &mut Window,
1650 cx: &mut Context<Workspace>,
1651 ) {
1652 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1653 "Failed to create buffer",
1654 window,
1655 cx,
1656 |e, _, _| match e.error_code() {
1657 ErrorCode::RemoteUpgradeRequired => Some(format!(
1658 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1659 e.error_tag("required").unwrap_or("the latest version")
1660 )),
1661 _ => None,
1662 },
1663 );
1664 }
1665
1666 pub fn new_in_workspace(
1667 workspace: &mut Workspace,
1668 window: &mut Window,
1669 cx: &mut Context<Workspace>,
1670 ) -> Task<Result<Entity<Editor>>> {
1671 let project = workspace.project().clone();
1672 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1673
1674 cx.spawn_in(window, |workspace, mut cx| async move {
1675 let buffer = create.await?;
1676 workspace.update_in(&mut cx, |workspace, window, cx| {
1677 let editor =
1678 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1679 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1680 editor
1681 })
1682 })
1683 }
1684
1685 fn new_file_vertical(
1686 workspace: &mut Workspace,
1687 _: &workspace::NewFileSplitVertical,
1688 window: &mut Window,
1689 cx: &mut Context<Workspace>,
1690 ) {
1691 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1692 }
1693
1694 fn new_file_horizontal(
1695 workspace: &mut Workspace,
1696 _: &workspace::NewFileSplitHorizontal,
1697 window: &mut Window,
1698 cx: &mut Context<Workspace>,
1699 ) {
1700 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1701 }
1702
1703 fn new_file_in_direction(
1704 workspace: &mut Workspace,
1705 direction: SplitDirection,
1706 window: &mut Window,
1707 cx: &mut Context<Workspace>,
1708 ) {
1709 let project = workspace.project().clone();
1710 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1711
1712 cx.spawn_in(window, |workspace, mut cx| async move {
1713 let buffer = create.await?;
1714 workspace.update_in(&mut cx, move |workspace, window, cx| {
1715 workspace.split_item(
1716 direction,
1717 Box::new(
1718 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1719 ),
1720 window,
1721 cx,
1722 )
1723 })?;
1724 anyhow::Ok(())
1725 })
1726 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1727 match e.error_code() {
1728 ErrorCode::RemoteUpgradeRequired => Some(format!(
1729 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1730 e.error_tag("required").unwrap_or("the latest version")
1731 )),
1732 _ => None,
1733 }
1734 });
1735 }
1736
1737 pub fn leader_peer_id(&self) -> Option<PeerId> {
1738 self.leader_peer_id
1739 }
1740
1741 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1742 &self.buffer
1743 }
1744
1745 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1746 self.workspace.as_ref()?.0.upgrade()
1747 }
1748
1749 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1750 self.buffer().read(cx).title(cx)
1751 }
1752
1753 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1754 let git_blame_gutter_max_author_length = self
1755 .render_git_blame_gutter(cx)
1756 .then(|| {
1757 if let Some(blame) = self.blame.as_ref() {
1758 let max_author_length =
1759 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1760 Some(max_author_length)
1761 } else {
1762 None
1763 }
1764 })
1765 .flatten();
1766
1767 EditorSnapshot {
1768 mode: self.mode,
1769 show_gutter: self.show_gutter,
1770 show_line_numbers: self.show_line_numbers,
1771 show_git_diff_gutter: self.show_git_diff_gutter,
1772 show_code_actions: self.show_code_actions,
1773 show_runnables: self.show_runnables,
1774 git_blame_gutter_max_author_length,
1775 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1776 scroll_anchor: self.scroll_manager.anchor(),
1777 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1778 placeholder_text: self.placeholder_text.clone(),
1779 is_focused: self.focus_handle.is_focused(window),
1780 current_line_highlight: self
1781 .current_line_highlight
1782 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1783 gutter_hovered: self.gutter_hovered,
1784 }
1785 }
1786
1787 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1788 self.buffer.read(cx).language_at(point, cx)
1789 }
1790
1791 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1792 self.buffer.read(cx).read(cx).file_at(point).cloned()
1793 }
1794
1795 pub fn active_excerpt(
1796 &self,
1797 cx: &App,
1798 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1799 self.buffer
1800 .read(cx)
1801 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1802 }
1803
1804 pub fn mode(&self) -> EditorMode {
1805 self.mode
1806 }
1807
1808 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1809 self.collaboration_hub.as_deref()
1810 }
1811
1812 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1813 self.collaboration_hub = Some(hub);
1814 }
1815
1816 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1817 self.in_project_search = in_project_search;
1818 }
1819
1820 pub fn set_custom_context_menu(
1821 &mut self,
1822 f: impl 'static
1823 + Fn(
1824 &mut Self,
1825 DisplayPoint,
1826 &mut Window,
1827 &mut Context<Self>,
1828 ) -> Option<Entity<ui::ContextMenu>>,
1829 ) {
1830 self.custom_context_menu = Some(Box::new(f))
1831 }
1832
1833 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1834 self.completion_provider = provider;
1835 }
1836
1837 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1838 self.semantics_provider.clone()
1839 }
1840
1841 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1842 self.semantics_provider = provider;
1843 }
1844
1845 pub fn set_edit_prediction_provider<T>(
1846 &mut self,
1847 provider: Option<Entity<T>>,
1848 window: &mut Window,
1849 cx: &mut Context<Self>,
1850 ) where
1851 T: EditPredictionProvider,
1852 {
1853 self.edit_prediction_provider =
1854 provider.map(|provider| RegisteredInlineCompletionProvider {
1855 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1856 if this.focus_handle.is_focused(window) {
1857 this.update_visible_inline_completion(window, cx);
1858 }
1859 }),
1860 provider: Arc::new(provider),
1861 });
1862 self.update_edit_prediction_settings(cx);
1863 self.refresh_inline_completion(false, false, window, cx);
1864 }
1865
1866 pub fn placeholder_text(&self) -> Option<&str> {
1867 self.placeholder_text.as_deref()
1868 }
1869
1870 pub fn set_placeholder_text(
1871 &mut self,
1872 placeholder_text: impl Into<Arc<str>>,
1873 cx: &mut Context<Self>,
1874 ) {
1875 let placeholder_text = Some(placeholder_text.into());
1876 if self.placeholder_text != placeholder_text {
1877 self.placeholder_text = placeholder_text;
1878 cx.notify();
1879 }
1880 }
1881
1882 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1883 self.cursor_shape = cursor_shape;
1884
1885 // Disrupt blink for immediate user feedback that the cursor shape has changed
1886 self.blink_manager.update(cx, BlinkManager::show_cursor);
1887
1888 cx.notify();
1889 }
1890
1891 pub fn set_current_line_highlight(
1892 &mut self,
1893 current_line_highlight: Option<CurrentLineHighlight>,
1894 ) {
1895 self.current_line_highlight = current_line_highlight;
1896 }
1897
1898 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1899 self.collapse_matches = collapse_matches;
1900 }
1901
1902 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1903 let buffers = self.buffer.read(cx).all_buffers();
1904 let Some(project) = self.project.as_ref() else {
1905 return;
1906 };
1907 project.update(cx, |project, cx| {
1908 for buffer in buffers {
1909 self.registered_buffers
1910 .entry(buffer.read(cx).remote_id())
1911 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1912 }
1913 })
1914 }
1915
1916 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1917 if self.collapse_matches {
1918 return range.start..range.start;
1919 }
1920 range.clone()
1921 }
1922
1923 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1924 if self.display_map.read(cx).clip_at_line_ends != clip {
1925 self.display_map
1926 .update(cx, |map, _| map.clip_at_line_ends = clip);
1927 }
1928 }
1929
1930 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1931 self.input_enabled = input_enabled;
1932 }
1933
1934 pub fn set_inline_completions_hidden_for_vim_mode(
1935 &mut self,
1936 hidden: bool,
1937 window: &mut Window,
1938 cx: &mut Context<Self>,
1939 ) {
1940 if hidden != self.inline_completions_hidden_for_vim_mode {
1941 self.inline_completions_hidden_for_vim_mode = hidden;
1942 if hidden {
1943 self.update_visible_inline_completion(window, cx);
1944 } else {
1945 self.refresh_inline_completion(true, false, window, cx);
1946 }
1947 }
1948 }
1949
1950 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1951 self.menu_inline_completions_policy = value;
1952 }
1953
1954 pub fn set_autoindent(&mut self, autoindent: bool) {
1955 if autoindent {
1956 self.autoindent_mode = Some(AutoindentMode::EachLine);
1957 } else {
1958 self.autoindent_mode = None;
1959 }
1960 }
1961
1962 pub fn read_only(&self, cx: &App) -> bool {
1963 self.read_only || self.buffer.read(cx).read_only()
1964 }
1965
1966 pub fn set_read_only(&mut self, read_only: bool) {
1967 self.read_only = read_only;
1968 }
1969
1970 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1971 self.use_autoclose = autoclose;
1972 }
1973
1974 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1975 self.use_auto_surround = auto_surround;
1976 }
1977
1978 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1979 self.auto_replace_emoji_shortcode = auto_replace;
1980 }
1981
1982 pub fn toggle_edit_predictions(
1983 &mut self,
1984 _: &ToggleEditPrediction,
1985 window: &mut Window,
1986 cx: &mut Context<Self>,
1987 ) {
1988 if self.show_inline_completions_override.is_some() {
1989 self.set_show_edit_predictions(None, window, cx);
1990 } else {
1991 let show_edit_predictions = !self.edit_predictions_enabled();
1992 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1993 }
1994 }
1995
1996 pub fn set_show_edit_predictions(
1997 &mut self,
1998 show_edit_predictions: Option<bool>,
1999 window: &mut Window,
2000 cx: &mut Context<Self>,
2001 ) {
2002 self.show_inline_completions_override = show_edit_predictions;
2003 self.update_edit_prediction_settings(cx);
2004
2005 if let Some(false) = show_edit_predictions {
2006 self.discard_inline_completion(false, cx);
2007 } else {
2008 self.refresh_inline_completion(false, true, window, cx);
2009 }
2010 }
2011
2012 fn inline_completions_disabled_in_scope(
2013 &self,
2014 buffer: &Entity<Buffer>,
2015 buffer_position: language::Anchor,
2016 cx: &App,
2017 ) -> bool {
2018 let snapshot = buffer.read(cx).snapshot();
2019 let settings = snapshot.settings_at(buffer_position, cx);
2020
2021 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2022 return false;
2023 };
2024
2025 scope.override_name().map_or(false, |scope_name| {
2026 settings
2027 .edit_predictions_disabled_in
2028 .iter()
2029 .any(|s| s == scope_name)
2030 })
2031 }
2032
2033 pub fn set_use_modal_editing(&mut self, to: bool) {
2034 self.use_modal_editing = to;
2035 }
2036
2037 pub fn use_modal_editing(&self) -> bool {
2038 self.use_modal_editing
2039 }
2040
2041 fn selections_did_change(
2042 &mut self,
2043 local: bool,
2044 old_cursor_position: &Anchor,
2045 show_completions: bool,
2046 window: &mut Window,
2047 cx: &mut Context<Self>,
2048 ) {
2049 window.invalidate_character_coordinates();
2050
2051 // Copy selections to primary selection buffer
2052 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2053 if local {
2054 let selections = self.selections.all::<usize>(cx);
2055 let buffer_handle = self.buffer.read(cx).read(cx);
2056
2057 let mut text = String::new();
2058 for (index, selection) in selections.iter().enumerate() {
2059 let text_for_selection = buffer_handle
2060 .text_for_range(selection.start..selection.end)
2061 .collect::<String>();
2062
2063 text.push_str(&text_for_selection);
2064 if index != selections.len() - 1 {
2065 text.push('\n');
2066 }
2067 }
2068
2069 if !text.is_empty() {
2070 cx.write_to_primary(ClipboardItem::new_string(text));
2071 }
2072 }
2073
2074 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2075 self.buffer.update(cx, |buffer, cx| {
2076 buffer.set_active_selections(
2077 &self.selections.disjoint_anchors(),
2078 self.selections.line_mode,
2079 self.cursor_shape,
2080 cx,
2081 )
2082 });
2083 }
2084 let display_map = self
2085 .display_map
2086 .update(cx, |display_map, cx| display_map.snapshot(cx));
2087 let buffer = &display_map.buffer_snapshot;
2088 self.add_selections_state = None;
2089 self.select_next_state = None;
2090 self.select_prev_state = None;
2091 self.select_larger_syntax_node_stack.clear();
2092 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2093 self.snippet_stack
2094 .invalidate(&self.selections.disjoint_anchors(), buffer);
2095 self.take_rename(false, window, cx);
2096
2097 let new_cursor_position = self.selections.newest_anchor().head();
2098
2099 self.push_to_nav_history(
2100 *old_cursor_position,
2101 Some(new_cursor_position.to_point(buffer)),
2102 cx,
2103 );
2104
2105 if local {
2106 let new_cursor_position = self.selections.newest_anchor().head();
2107 let mut context_menu = self.context_menu.borrow_mut();
2108 let completion_menu = match context_menu.as_ref() {
2109 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2110 _ => {
2111 *context_menu = None;
2112 None
2113 }
2114 };
2115 if let Some(buffer_id) = new_cursor_position.buffer_id {
2116 if !self.registered_buffers.contains_key(&buffer_id) {
2117 if let Some(project) = self.project.as_ref() {
2118 project.update(cx, |project, cx| {
2119 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2120 return;
2121 };
2122 self.registered_buffers.insert(
2123 buffer_id,
2124 project.register_buffer_with_language_servers(&buffer, cx),
2125 );
2126 })
2127 }
2128 }
2129 }
2130
2131 if let Some(completion_menu) = completion_menu {
2132 let cursor_position = new_cursor_position.to_offset(buffer);
2133 let (word_range, kind) =
2134 buffer.surrounding_word(completion_menu.initial_position, true);
2135 if kind == Some(CharKind::Word)
2136 && word_range.to_inclusive().contains(&cursor_position)
2137 {
2138 let mut completion_menu = completion_menu.clone();
2139 drop(context_menu);
2140
2141 let query = Self::completion_query(buffer, cursor_position);
2142 cx.spawn(move |this, mut cx| async move {
2143 completion_menu
2144 .filter(query.as_deref(), cx.background_executor().clone())
2145 .await;
2146
2147 this.update(&mut cx, |this, cx| {
2148 let mut context_menu = this.context_menu.borrow_mut();
2149 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2150 else {
2151 return;
2152 };
2153
2154 if menu.id > completion_menu.id {
2155 return;
2156 }
2157
2158 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2159 drop(context_menu);
2160 cx.notify();
2161 })
2162 })
2163 .detach();
2164
2165 if show_completions {
2166 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2167 }
2168 } else {
2169 drop(context_menu);
2170 self.hide_context_menu(window, cx);
2171 }
2172 } else {
2173 drop(context_menu);
2174 }
2175
2176 hide_hover(self, cx);
2177
2178 if old_cursor_position.to_display_point(&display_map).row()
2179 != new_cursor_position.to_display_point(&display_map).row()
2180 {
2181 self.available_code_actions.take();
2182 }
2183 self.refresh_code_actions(window, cx);
2184 self.refresh_document_highlights(cx);
2185 self.refresh_selected_text_highlights(window, cx);
2186 refresh_matching_bracket_highlights(self, window, cx);
2187 self.update_visible_inline_completion(window, cx);
2188 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2189 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2190 if self.git_blame_inline_enabled {
2191 self.start_inline_blame_timer(window, cx);
2192 }
2193 }
2194
2195 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2196 cx.emit(EditorEvent::SelectionsChanged { local });
2197
2198 let selections = &self.selections.disjoint;
2199 if selections.len() == 1 {
2200 cx.emit(SearchEvent::ActiveMatchChanged)
2201 }
2202 if local
2203 && self.is_singleton(cx)
2204 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2205 {
2206 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2207 let background_executor = cx.background_executor().clone();
2208 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2209 let snapshot = self.buffer().read(cx).snapshot(cx);
2210 let selections = selections.clone();
2211 self.serialize_selections = cx.background_spawn(async move {
2212 background_executor.timer(Duration::from_millis(100)).await;
2213 let selections = selections
2214 .iter()
2215 .map(|selection| {
2216 (
2217 selection.start.to_offset(&snapshot),
2218 selection.end.to_offset(&snapshot),
2219 )
2220 })
2221 .collect();
2222 DB.save_editor_selections(editor_id, workspace_id, selections)
2223 .await
2224 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2225 .log_err();
2226 });
2227 }
2228 }
2229
2230 cx.notify();
2231 }
2232
2233 pub fn change_selections<R>(
2234 &mut self,
2235 autoscroll: Option<Autoscroll>,
2236 window: &mut Window,
2237 cx: &mut Context<Self>,
2238 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2239 ) -> R {
2240 self.change_selections_inner(autoscroll, true, window, cx, change)
2241 }
2242
2243 fn change_selections_inner<R>(
2244 &mut self,
2245 autoscroll: Option<Autoscroll>,
2246 request_completions: bool,
2247 window: &mut Window,
2248 cx: &mut Context<Self>,
2249 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2250 ) -> R {
2251 let old_cursor_position = self.selections.newest_anchor().head();
2252 self.push_to_selection_history();
2253
2254 let (changed, result) = self.selections.change_with(cx, change);
2255
2256 if changed {
2257 if let Some(autoscroll) = autoscroll {
2258 self.request_autoscroll(autoscroll, cx);
2259 }
2260 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2261
2262 if self.should_open_signature_help_automatically(
2263 &old_cursor_position,
2264 self.signature_help_state.backspace_pressed(),
2265 cx,
2266 ) {
2267 self.show_signature_help(&ShowSignatureHelp, window, cx);
2268 }
2269 self.signature_help_state.set_backspace_pressed(false);
2270 }
2271
2272 result
2273 }
2274
2275 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2276 where
2277 I: IntoIterator<Item = (Range<S>, T)>,
2278 S: ToOffset,
2279 T: Into<Arc<str>>,
2280 {
2281 if self.read_only(cx) {
2282 return;
2283 }
2284
2285 self.buffer
2286 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2287 }
2288
2289 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2290 where
2291 I: IntoIterator<Item = (Range<S>, T)>,
2292 S: ToOffset,
2293 T: Into<Arc<str>>,
2294 {
2295 if self.read_only(cx) {
2296 return;
2297 }
2298
2299 self.buffer.update(cx, |buffer, cx| {
2300 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2301 });
2302 }
2303
2304 pub fn edit_with_block_indent<I, S, T>(
2305 &mut self,
2306 edits: I,
2307 original_start_columns: Vec<u32>,
2308 cx: &mut Context<Self>,
2309 ) where
2310 I: IntoIterator<Item = (Range<S>, T)>,
2311 S: ToOffset,
2312 T: Into<Arc<str>>,
2313 {
2314 if self.read_only(cx) {
2315 return;
2316 }
2317
2318 self.buffer.update(cx, |buffer, cx| {
2319 buffer.edit(
2320 edits,
2321 Some(AutoindentMode::Block {
2322 original_start_columns,
2323 }),
2324 cx,
2325 )
2326 });
2327 }
2328
2329 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2330 self.hide_context_menu(window, cx);
2331
2332 match phase {
2333 SelectPhase::Begin {
2334 position,
2335 add,
2336 click_count,
2337 } => self.begin_selection(position, add, click_count, window, cx),
2338 SelectPhase::BeginColumnar {
2339 position,
2340 goal_column,
2341 reset,
2342 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2343 SelectPhase::Extend {
2344 position,
2345 click_count,
2346 } => self.extend_selection(position, click_count, window, cx),
2347 SelectPhase::Update {
2348 position,
2349 goal_column,
2350 scroll_delta,
2351 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2352 SelectPhase::End => self.end_selection(window, cx),
2353 }
2354 }
2355
2356 fn extend_selection(
2357 &mut self,
2358 position: DisplayPoint,
2359 click_count: usize,
2360 window: &mut Window,
2361 cx: &mut Context<Self>,
2362 ) {
2363 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2364 let tail = self.selections.newest::<usize>(cx).tail();
2365 self.begin_selection(position, false, click_count, window, cx);
2366
2367 let position = position.to_offset(&display_map, Bias::Left);
2368 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2369
2370 let mut pending_selection = self
2371 .selections
2372 .pending_anchor()
2373 .expect("extend_selection not called with pending selection");
2374 if position >= tail {
2375 pending_selection.start = tail_anchor;
2376 } else {
2377 pending_selection.end = tail_anchor;
2378 pending_selection.reversed = true;
2379 }
2380
2381 let mut pending_mode = self.selections.pending_mode().unwrap();
2382 match &mut pending_mode {
2383 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2384 _ => {}
2385 }
2386
2387 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2388 s.set_pending(pending_selection, pending_mode)
2389 });
2390 }
2391
2392 fn begin_selection(
2393 &mut self,
2394 position: DisplayPoint,
2395 add: bool,
2396 click_count: usize,
2397 window: &mut Window,
2398 cx: &mut Context<Self>,
2399 ) {
2400 if !self.focus_handle.is_focused(window) {
2401 self.last_focused_descendant = None;
2402 window.focus(&self.focus_handle);
2403 }
2404
2405 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2406 let buffer = &display_map.buffer_snapshot;
2407 let newest_selection = self.selections.newest_anchor().clone();
2408 let position = display_map.clip_point(position, Bias::Left);
2409
2410 let start;
2411 let end;
2412 let mode;
2413 let mut auto_scroll;
2414 match click_count {
2415 1 => {
2416 start = buffer.anchor_before(position.to_point(&display_map));
2417 end = start;
2418 mode = SelectMode::Character;
2419 auto_scroll = true;
2420 }
2421 2 => {
2422 let range = movement::surrounding_word(&display_map, position);
2423 start = buffer.anchor_before(range.start.to_point(&display_map));
2424 end = buffer.anchor_before(range.end.to_point(&display_map));
2425 mode = SelectMode::Word(start..end);
2426 auto_scroll = true;
2427 }
2428 3 => {
2429 let position = display_map
2430 .clip_point(position, Bias::Left)
2431 .to_point(&display_map);
2432 let line_start = display_map.prev_line_boundary(position).0;
2433 let next_line_start = buffer.clip_point(
2434 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2435 Bias::Left,
2436 );
2437 start = buffer.anchor_before(line_start);
2438 end = buffer.anchor_before(next_line_start);
2439 mode = SelectMode::Line(start..end);
2440 auto_scroll = true;
2441 }
2442 _ => {
2443 start = buffer.anchor_before(0);
2444 end = buffer.anchor_before(buffer.len());
2445 mode = SelectMode::All;
2446 auto_scroll = false;
2447 }
2448 }
2449 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2450
2451 let point_to_delete: Option<usize> = {
2452 let selected_points: Vec<Selection<Point>> =
2453 self.selections.disjoint_in_range(start..end, cx);
2454
2455 if !add || click_count > 1 {
2456 None
2457 } else if !selected_points.is_empty() {
2458 Some(selected_points[0].id)
2459 } else {
2460 let clicked_point_already_selected =
2461 self.selections.disjoint.iter().find(|selection| {
2462 selection.start.to_point(buffer) == start.to_point(buffer)
2463 || selection.end.to_point(buffer) == end.to_point(buffer)
2464 });
2465
2466 clicked_point_already_selected.map(|selection| selection.id)
2467 }
2468 };
2469
2470 let selections_count = self.selections.count();
2471
2472 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2473 if let Some(point_to_delete) = point_to_delete {
2474 s.delete(point_to_delete);
2475
2476 if selections_count == 1 {
2477 s.set_pending_anchor_range(start..end, mode);
2478 }
2479 } else {
2480 if !add {
2481 s.clear_disjoint();
2482 } else if click_count > 1 {
2483 s.delete(newest_selection.id)
2484 }
2485
2486 s.set_pending_anchor_range(start..end, mode);
2487 }
2488 });
2489 }
2490
2491 fn begin_columnar_selection(
2492 &mut self,
2493 position: DisplayPoint,
2494 goal_column: u32,
2495 reset: bool,
2496 window: &mut Window,
2497 cx: &mut Context<Self>,
2498 ) {
2499 if !self.focus_handle.is_focused(window) {
2500 self.last_focused_descendant = None;
2501 window.focus(&self.focus_handle);
2502 }
2503
2504 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2505
2506 if reset {
2507 let pointer_position = display_map
2508 .buffer_snapshot
2509 .anchor_before(position.to_point(&display_map));
2510
2511 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2512 s.clear_disjoint();
2513 s.set_pending_anchor_range(
2514 pointer_position..pointer_position,
2515 SelectMode::Character,
2516 );
2517 });
2518 }
2519
2520 let tail = self.selections.newest::<Point>(cx).tail();
2521 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2522
2523 if !reset {
2524 self.select_columns(
2525 tail.to_display_point(&display_map),
2526 position,
2527 goal_column,
2528 &display_map,
2529 window,
2530 cx,
2531 );
2532 }
2533 }
2534
2535 fn update_selection(
2536 &mut self,
2537 position: DisplayPoint,
2538 goal_column: u32,
2539 scroll_delta: gpui::Point<f32>,
2540 window: &mut Window,
2541 cx: &mut Context<Self>,
2542 ) {
2543 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2544
2545 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2546 let tail = tail.to_display_point(&display_map);
2547 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2548 } else if let Some(mut pending) = self.selections.pending_anchor() {
2549 let buffer = self.buffer.read(cx).snapshot(cx);
2550 let head;
2551 let tail;
2552 let mode = self.selections.pending_mode().unwrap();
2553 match &mode {
2554 SelectMode::Character => {
2555 head = position.to_point(&display_map);
2556 tail = pending.tail().to_point(&buffer);
2557 }
2558 SelectMode::Word(original_range) => {
2559 let original_display_range = original_range.start.to_display_point(&display_map)
2560 ..original_range.end.to_display_point(&display_map);
2561 let original_buffer_range = original_display_range.start.to_point(&display_map)
2562 ..original_display_range.end.to_point(&display_map);
2563 if movement::is_inside_word(&display_map, position)
2564 || original_display_range.contains(&position)
2565 {
2566 let word_range = movement::surrounding_word(&display_map, position);
2567 if word_range.start < original_display_range.start {
2568 head = word_range.start.to_point(&display_map);
2569 } else {
2570 head = word_range.end.to_point(&display_map);
2571 }
2572 } else {
2573 head = position.to_point(&display_map);
2574 }
2575
2576 if head <= original_buffer_range.start {
2577 tail = original_buffer_range.end;
2578 } else {
2579 tail = original_buffer_range.start;
2580 }
2581 }
2582 SelectMode::Line(original_range) => {
2583 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2584
2585 let position = display_map
2586 .clip_point(position, Bias::Left)
2587 .to_point(&display_map);
2588 let line_start = display_map.prev_line_boundary(position).0;
2589 let next_line_start = buffer.clip_point(
2590 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2591 Bias::Left,
2592 );
2593
2594 if line_start < original_range.start {
2595 head = line_start
2596 } else {
2597 head = next_line_start
2598 }
2599
2600 if head <= original_range.start {
2601 tail = original_range.end;
2602 } else {
2603 tail = original_range.start;
2604 }
2605 }
2606 SelectMode::All => {
2607 return;
2608 }
2609 };
2610
2611 if head < tail {
2612 pending.start = buffer.anchor_before(head);
2613 pending.end = buffer.anchor_before(tail);
2614 pending.reversed = true;
2615 } else {
2616 pending.start = buffer.anchor_before(tail);
2617 pending.end = buffer.anchor_before(head);
2618 pending.reversed = false;
2619 }
2620
2621 self.change_selections(None, window, cx, |s| {
2622 s.set_pending(pending, mode);
2623 });
2624 } else {
2625 log::error!("update_selection dispatched with no pending selection");
2626 return;
2627 }
2628
2629 self.apply_scroll_delta(scroll_delta, window, cx);
2630 cx.notify();
2631 }
2632
2633 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2634 self.columnar_selection_tail.take();
2635 if self.selections.pending_anchor().is_some() {
2636 let selections = self.selections.all::<usize>(cx);
2637 self.change_selections(None, window, cx, |s| {
2638 s.select(selections);
2639 s.clear_pending();
2640 });
2641 }
2642 }
2643
2644 fn select_columns(
2645 &mut self,
2646 tail: DisplayPoint,
2647 head: DisplayPoint,
2648 goal_column: u32,
2649 display_map: &DisplaySnapshot,
2650 window: &mut Window,
2651 cx: &mut Context<Self>,
2652 ) {
2653 let start_row = cmp::min(tail.row(), head.row());
2654 let end_row = cmp::max(tail.row(), head.row());
2655 let start_column = cmp::min(tail.column(), goal_column);
2656 let end_column = cmp::max(tail.column(), goal_column);
2657 let reversed = start_column < tail.column();
2658
2659 let selection_ranges = (start_row.0..=end_row.0)
2660 .map(DisplayRow)
2661 .filter_map(|row| {
2662 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2663 let start = display_map
2664 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2665 .to_point(display_map);
2666 let end = display_map
2667 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2668 .to_point(display_map);
2669 if reversed {
2670 Some(end..start)
2671 } else {
2672 Some(start..end)
2673 }
2674 } else {
2675 None
2676 }
2677 })
2678 .collect::<Vec<_>>();
2679
2680 self.change_selections(None, window, cx, |s| {
2681 s.select_ranges(selection_ranges);
2682 });
2683 cx.notify();
2684 }
2685
2686 pub fn has_pending_nonempty_selection(&self) -> bool {
2687 let pending_nonempty_selection = match self.selections.pending_anchor() {
2688 Some(Selection { start, end, .. }) => start != end,
2689 None => false,
2690 };
2691
2692 pending_nonempty_selection
2693 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2694 }
2695
2696 pub fn has_pending_selection(&self) -> bool {
2697 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2698 }
2699
2700 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2701 self.selection_mark_mode = false;
2702
2703 if self.clear_expanded_diff_hunks(cx) {
2704 cx.notify();
2705 return;
2706 }
2707 if self.dismiss_menus_and_popups(true, window, cx) {
2708 return;
2709 }
2710
2711 if self.mode == EditorMode::Full
2712 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2713 {
2714 return;
2715 }
2716
2717 cx.propagate();
2718 }
2719
2720 pub fn dismiss_menus_and_popups(
2721 &mut self,
2722 is_user_requested: bool,
2723 window: &mut Window,
2724 cx: &mut Context<Self>,
2725 ) -> bool {
2726 if self.take_rename(false, window, cx).is_some() {
2727 return true;
2728 }
2729
2730 if hide_hover(self, cx) {
2731 return true;
2732 }
2733
2734 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2735 return true;
2736 }
2737
2738 if self.hide_context_menu(window, cx).is_some() {
2739 return true;
2740 }
2741
2742 if self.mouse_context_menu.take().is_some() {
2743 return true;
2744 }
2745
2746 if is_user_requested && self.discard_inline_completion(true, cx) {
2747 return true;
2748 }
2749
2750 if self.snippet_stack.pop().is_some() {
2751 return true;
2752 }
2753
2754 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2755 self.dismiss_diagnostics(cx);
2756 return true;
2757 }
2758
2759 false
2760 }
2761
2762 fn linked_editing_ranges_for(
2763 &self,
2764 selection: Range<text::Anchor>,
2765 cx: &App,
2766 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2767 if self.linked_edit_ranges.is_empty() {
2768 return None;
2769 }
2770 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2771 selection.end.buffer_id.and_then(|end_buffer_id| {
2772 if selection.start.buffer_id != Some(end_buffer_id) {
2773 return None;
2774 }
2775 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2776 let snapshot = buffer.read(cx).snapshot();
2777 self.linked_edit_ranges
2778 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2779 .map(|ranges| (ranges, snapshot, buffer))
2780 })?;
2781 use text::ToOffset as TO;
2782 // find offset from the start of current range to current cursor position
2783 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2784
2785 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2786 let start_difference = start_offset - start_byte_offset;
2787 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2788 let end_difference = end_offset - start_byte_offset;
2789 // Current range has associated linked ranges.
2790 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2791 for range in linked_ranges.iter() {
2792 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2793 let end_offset = start_offset + end_difference;
2794 let start_offset = start_offset + start_difference;
2795 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2796 continue;
2797 }
2798 if self.selections.disjoint_anchor_ranges().any(|s| {
2799 if s.start.buffer_id != selection.start.buffer_id
2800 || s.end.buffer_id != selection.end.buffer_id
2801 {
2802 return false;
2803 }
2804 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2805 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2806 }) {
2807 continue;
2808 }
2809 let start = buffer_snapshot.anchor_after(start_offset);
2810 let end = buffer_snapshot.anchor_after(end_offset);
2811 linked_edits
2812 .entry(buffer.clone())
2813 .or_default()
2814 .push(start..end);
2815 }
2816 Some(linked_edits)
2817 }
2818
2819 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2820 let text: Arc<str> = text.into();
2821
2822 if self.read_only(cx) {
2823 return;
2824 }
2825
2826 let selections = self.selections.all_adjusted(cx);
2827 let mut bracket_inserted = false;
2828 let mut edits = Vec::new();
2829 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2830 let mut new_selections = Vec::with_capacity(selections.len());
2831 let mut new_autoclose_regions = Vec::new();
2832 let snapshot = self.buffer.read(cx).read(cx);
2833
2834 for (selection, autoclose_region) in
2835 self.selections_with_autoclose_regions(selections, &snapshot)
2836 {
2837 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2838 // Determine if the inserted text matches the opening or closing
2839 // bracket of any of this language's bracket pairs.
2840 let mut bracket_pair = None;
2841 let mut is_bracket_pair_start = false;
2842 let mut is_bracket_pair_end = false;
2843 if !text.is_empty() {
2844 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2845 // and they are removing the character that triggered IME popup.
2846 for (pair, enabled) in scope.brackets() {
2847 if !pair.close && !pair.surround {
2848 continue;
2849 }
2850
2851 if enabled && pair.start.ends_with(text.as_ref()) {
2852 let prefix_len = pair.start.len() - text.len();
2853 let preceding_text_matches_prefix = prefix_len == 0
2854 || (selection.start.column >= (prefix_len as u32)
2855 && snapshot.contains_str_at(
2856 Point::new(
2857 selection.start.row,
2858 selection.start.column - (prefix_len as u32),
2859 ),
2860 &pair.start[..prefix_len],
2861 ));
2862 if preceding_text_matches_prefix {
2863 bracket_pair = Some(pair.clone());
2864 is_bracket_pair_start = true;
2865 break;
2866 }
2867 }
2868 if pair.end.as_str() == text.as_ref() {
2869 bracket_pair = Some(pair.clone());
2870 is_bracket_pair_end = true;
2871 break;
2872 }
2873 }
2874 }
2875
2876 if let Some(bracket_pair) = bracket_pair {
2877 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2878 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2879 let auto_surround =
2880 self.use_auto_surround && snapshot_settings.use_auto_surround;
2881 if selection.is_empty() {
2882 if is_bracket_pair_start {
2883 // If the inserted text is a suffix of an opening bracket and the
2884 // selection is preceded by the rest of the opening bracket, then
2885 // insert the closing bracket.
2886 let following_text_allows_autoclose = snapshot
2887 .chars_at(selection.start)
2888 .next()
2889 .map_or(true, |c| scope.should_autoclose_before(c));
2890
2891 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2892 && bracket_pair.start.len() == 1
2893 {
2894 let target = bracket_pair.start.chars().next().unwrap();
2895 let current_line_count = snapshot
2896 .reversed_chars_at(selection.start)
2897 .take_while(|&c| c != '\n')
2898 .filter(|&c| c == target)
2899 .count();
2900 current_line_count % 2 == 1
2901 } else {
2902 false
2903 };
2904
2905 if autoclose
2906 && bracket_pair.close
2907 && following_text_allows_autoclose
2908 && !is_closing_quote
2909 {
2910 let anchor = snapshot.anchor_before(selection.end);
2911 new_selections.push((selection.map(|_| anchor), text.len()));
2912 new_autoclose_regions.push((
2913 anchor,
2914 text.len(),
2915 selection.id,
2916 bracket_pair.clone(),
2917 ));
2918 edits.push((
2919 selection.range(),
2920 format!("{}{}", text, bracket_pair.end).into(),
2921 ));
2922 bracket_inserted = true;
2923 continue;
2924 }
2925 }
2926
2927 if let Some(region) = autoclose_region {
2928 // If the selection is followed by an auto-inserted closing bracket,
2929 // then don't insert that closing bracket again; just move the selection
2930 // past the closing bracket.
2931 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2932 && text.as_ref() == region.pair.end.as_str();
2933 if should_skip {
2934 let anchor = snapshot.anchor_after(selection.end);
2935 new_selections
2936 .push((selection.map(|_| anchor), region.pair.end.len()));
2937 continue;
2938 }
2939 }
2940
2941 let always_treat_brackets_as_autoclosed = snapshot
2942 .settings_at(selection.start, cx)
2943 .always_treat_brackets_as_autoclosed;
2944 if always_treat_brackets_as_autoclosed
2945 && is_bracket_pair_end
2946 && snapshot.contains_str_at(selection.end, text.as_ref())
2947 {
2948 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2949 // and the inserted text is a closing bracket and the selection is followed
2950 // by the closing bracket then move the selection past the closing bracket.
2951 let anchor = snapshot.anchor_after(selection.end);
2952 new_selections.push((selection.map(|_| anchor), text.len()));
2953 continue;
2954 }
2955 }
2956 // If an opening bracket is 1 character long and is typed while
2957 // text is selected, then surround that text with the bracket pair.
2958 else if auto_surround
2959 && bracket_pair.surround
2960 && is_bracket_pair_start
2961 && bracket_pair.start.chars().count() == 1
2962 {
2963 edits.push((selection.start..selection.start, text.clone()));
2964 edits.push((
2965 selection.end..selection.end,
2966 bracket_pair.end.as_str().into(),
2967 ));
2968 bracket_inserted = true;
2969 new_selections.push((
2970 Selection {
2971 id: selection.id,
2972 start: snapshot.anchor_after(selection.start),
2973 end: snapshot.anchor_before(selection.end),
2974 reversed: selection.reversed,
2975 goal: selection.goal,
2976 },
2977 0,
2978 ));
2979 continue;
2980 }
2981 }
2982 }
2983
2984 if self.auto_replace_emoji_shortcode
2985 && selection.is_empty()
2986 && text.as_ref().ends_with(':')
2987 {
2988 if let Some(possible_emoji_short_code) =
2989 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2990 {
2991 if !possible_emoji_short_code.is_empty() {
2992 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2993 let emoji_shortcode_start = Point::new(
2994 selection.start.row,
2995 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2996 );
2997
2998 // Remove shortcode from buffer
2999 edits.push((
3000 emoji_shortcode_start..selection.start,
3001 "".to_string().into(),
3002 ));
3003 new_selections.push((
3004 Selection {
3005 id: selection.id,
3006 start: snapshot.anchor_after(emoji_shortcode_start),
3007 end: snapshot.anchor_before(selection.start),
3008 reversed: selection.reversed,
3009 goal: selection.goal,
3010 },
3011 0,
3012 ));
3013
3014 // Insert emoji
3015 let selection_start_anchor = snapshot.anchor_after(selection.start);
3016 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3017 edits.push((selection.start..selection.end, emoji.to_string().into()));
3018
3019 continue;
3020 }
3021 }
3022 }
3023 }
3024
3025 // If not handling any auto-close operation, then just replace the selected
3026 // text with the given input and move the selection to the end of the
3027 // newly inserted text.
3028 let anchor = snapshot.anchor_after(selection.end);
3029 if !self.linked_edit_ranges.is_empty() {
3030 let start_anchor = snapshot.anchor_before(selection.start);
3031
3032 let is_word_char = text.chars().next().map_or(true, |char| {
3033 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3034 classifier.is_word(char)
3035 });
3036
3037 if is_word_char {
3038 if let Some(ranges) = self
3039 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3040 {
3041 for (buffer, edits) in ranges {
3042 linked_edits
3043 .entry(buffer.clone())
3044 .or_default()
3045 .extend(edits.into_iter().map(|range| (range, text.clone())));
3046 }
3047 }
3048 }
3049 }
3050
3051 new_selections.push((selection.map(|_| anchor), 0));
3052 edits.push((selection.start..selection.end, text.clone()));
3053 }
3054
3055 drop(snapshot);
3056
3057 self.transact(window, cx, |this, window, cx| {
3058 this.buffer.update(cx, |buffer, cx| {
3059 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3060 });
3061 for (buffer, edits) in linked_edits {
3062 buffer.update(cx, |buffer, cx| {
3063 let snapshot = buffer.snapshot();
3064 let edits = edits
3065 .into_iter()
3066 .map(|(range, text)| {
3067 use text::ToPoint as TP;
3068 let end_point = TP::to_point(&range.end, &snapshot);
3069 let start_point = TP::to_point(&range.start, &snapshot);
3070 (start_point..end_point, text)
3071 })
3072 .sorted_by_key(|(range, _)| range.start)
3073 .collect::<Vec<_>>();
3074 buffer.edit(edits, None, cx);
3075 })
3076 }
3077 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3078 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3079 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3080 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3081 .zip(new_selection_deltas)
3082 .map(|(selection, delta)| Selection {
3083 id: selection.id,
3084 start: selection.start + delta,
3085 end: selection.end + delta,
3086 reversed: selection.reversed,
3087 goal: SelectionGoal::None,
3088 })
3089 .collect::<Vec<_>>();
3090
3091 let mut i = 0;
3092 for (position, delta, selection_id, pair) in new_autoclose_regions {
3093 let position = position.to_offset(&map.buffer_snapshot) + delta;
3094 let start = map.buffer_snapshot.anchor_before(position);
3095 let end = map.buffer_snapshot.anchor_after(position);
3096 while let Some(existing_state) = this.autoclose_regions.get(i) {
3097 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3098 Ordering::Less => i += 1,
3099 Ordering::Greater => break,
3100 Ordering::Equal => {
3101 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3102 Ordering::Less => i += 1,
3103 Ordering::Equal => break,
3104 Ordering::Greater => break,
3105 }
3106 }
3107 }
3108 }
3109 this.autoclose_regions.insert(
3110 i,
3111 AutocloseRegion {
3112 selection_id,
3113 range: start..end,
3114 pair,
3115 },
3116 );
3117 }
3118
3119 let had_active_inline_completion = this.has_active_inline_completion();
3120 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3121 s.select(new_selections)
3122 });
3123
3124 if !bracket_inserted {
3125 if let Some(on_type_format_task) =
3126 this.trigger_on_type_formatting(text.to_string(), window, cx)
3127 {
3128 on_type_format_task.detach_and_log_err(cx);
3129 }
3130 }
3131
3132 let editor_settings = EditorSettings::get_global(cx);
3133 if bracket_inserted
3134 && (editor_settings.auto_signature_help
3135 || editor_settings.show_signature_help_after_edits)
3136 {
3137 this.show_signature_help(&ShowSignatureHelp, window, cx);
3138 }
3139
3140 let trigger_in_words =
3141 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3142 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3143 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3144 this.refresh_inline_completion(true, false, window, cx);
3145 });
3146 }
3147
3148 fn find_possible_emoji_shortcode_at_position(
3149 snapshot: &MultiBufferSnapshot,
3150 position: Point,
3151 ) -> Option<String> {
3152 let mut chars = Vec::new();
3153 let mut found_colon = false;
3154 for char in snapshot.reversed_chars_at(position).take(100) {
3155 // Found a possible emoji shortcode in the middle of the buffer
3156 if found_colon {
3157 if char.is_whitespace() {
3158 chars.reverse();
3159 return Some(chars.iter().collect());
3160 }
3161 // If the previous character is not a whitespace, we are in the middle of a word
3162 // and we only want to complete the shortcode if the word is made up of other emojis
3163 let mut containing_word = String::new();
3164 for ch in snapshot
3165 .reversed_chars_at(position)
3166 .skip(chars.len() + 1)
3167 .take(100)
3168 {
3169 if ch.is_whitespace() {
3170 break;
3171 }
3172 containing_word.push(ch);
3173 }
3174 let containing_word = containing_word.chars().rev().collect::<String>();
3175 if util::word_consists_of_emojis(containing_word.as_str()) {
3176 chars.reverse();
3177 return Some(chars.iter().collect());
3178 }
3179 }
3180
3181 if char.is_whitespace() || !char.is_ascii() {
3182 return None;
3183 }
3184 if char == ':' {
3185 found_colon = true;
3186 } else {
3187 chars.push(char);
3188 }
3189 }
3190 // Found a possible emoji shortcode at the beginning of the buffer
3191 chars.reverse();
3192 Some(chars.iter().collect())
3193 }
3194
3195 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3196 self.transact(window, cx, |this, window, cx| {
3197 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3198 let selections = this.selections.all::<usize>(cx);
3199 let multi_buffer = this.buffer.read(cx);
3200 let buffer = multi_buffer.snapshot(cx);
3201 selections
3202 .iter()
3203 .map(|selection| {
3204 let start_point = selection.start.to_point(&buffer);
3205 let mut indent =
3206 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3207 indent.len = cmp::min(indent.len, start_point.column);
3208 let start = selection.start;
3209 let end = selection.end;
3210 let selection_is_empty = start == end;
3211 let language_scope = buffer.language_scope_at(start);
3212 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3213 &language_scope
3214 {
3215 let insert_extra_newline =
3216 insert_extra_newline_brackets(&buffer, start..end, language)
3217 || insert_extra_newline_tree_sitter(&buffer, start..end);
3218
3219 // Comment extension on newline is allowed only for cursor selections
3220 let comment_delimiter = maybe!({
3221 if !selection_is_empty {
3222 return None;
3223 }
3224
3225 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3226 return None;
3227 }
3228
3229 let delimiters = language.line_comment_prefixes();
3230 let max_len_of_delimiter =
3231 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3232 let (snapshot, range) =
3233 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3234
3235 let mut index_of_first_non_whitespace = 0;
3236 let comment_candidate = snapshot
3237 .chars_for_range(range)
3238 .skip_while(|c| {
3239 let should_skip = c.is_whitespace();
3240 if should_skip {
3241 index_of_first_non_whitespace += 1;
3242 }
3243 should_skip
3244 })
3245 .take(max_len_of_delimiter)
3246 .collect::<String>();
3247 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3248 comment_candidate.starts_with(comment_prefix.as_ref())
3249 })?;
3250 let cursor_is_placed_after_comment_marker =
3251 index_of_first_non_whitespace + comment_prefix.len()
3252 <= start_point.column as usize;
3253 if cursor_is_placed_after_comment_marker {
3254 Some(comment_prefix.clone())
3255 } else {
3256 None
3257 }
3258 });
3259 (comment_delimiter, insert_extra_newline)
3260 } else {
3261 (None, false)
3262 };
3263
3264 let capacity_for_delimiter = comment_delimiter
3265 .as_deref()
3266 .map(str::len)
3267 .unwrap_or_default();
3268 let mut new_text =
3269 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3270 new_text.push('\n');
3271 new_text.extend(indent.chars());
3272 if let Some(delimiter) = &comment_delimiter {
3273 new_text.push_str(delimiter);
3274 }
3275 if insert_extra_newline {
3276 new_text = new_text.repeat(2);
3277 }
3278
3279 let anchor = buffer.anchor_after(end);
3280 let new_selection = selection.map(|_| anchor);
3281 (
3282 (start..end, new_text),
3283 (insert_extra_newline, new_selection),
3284 )
3285 })
3286 .unzip()
3287 };
3288
3289 this.edit_with_autoindent(edits, cx);
3290 let buffer = this.buffer.read(cx).snapshot(cx);
3291 let new_selections = selection_fixup_info
3292 .into_iter()
3293 .map(|(extra_newline_inserted, new_selection)| {
3294 let mut cursor = new_selection.end.to_point(&buffer);
3295 if extra_newline_inserted {
3296 cursor.row -= 1;
3297 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3298 }
3299 new_selection.map(|_| cursor)
3300 })
3301 .collect();
3302
3303 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3304 s.select(new_selections)
3305 });
3306 this.refresh_inline_completion(true, false, window, cx);
3307 });
3308 }
3309
3310 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3311 let buffer = self.buffer.read(cx);
3312 let snapshot = buffer.snapshot(cx);
3313
3314 let mut edits = Vec::new();
3315 let mut rows = Vec::new();
3316
3317 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3318 let cursor = selection.head();
3319 let row = cursor.row;
3320
3321 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3322
3323 let newline = "\n".to_string();
3324 edits.push((start_of_line..start_of_line, newline));
3325
3326 rows.push(row + rows_inserted as u32);
3327 }
3328
3329 self.transact(window, cx, |editor, window, cx| {
3330 editor.edit(edits, cx);
3331
3332 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3333 let mut index = 0;
3334 s.move_cursors_with(|map, _, _| {
3335 let row = rows[index];
3336 index += 1;
3337
3338 let point = Point::new(row, 0);
3339 let boundary = map.next_line_boundary(point).1;
3340 let clipped = map.clip_point(boundary, Bias::Left);
3341
3342 (clipped, SelectionGoal::None)
3343 });
3344 });
3345
3346 let mut indent_edits = Vec::new();
3347 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3348 for row in rows {
3349 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3350 for (row, indent) in indents {
3351 if indent.len == 0 {
3352 continue;
3353 }
3354
3355 let text = match indent.kind {
3356 IndentKind::Space => " ".repeat(indent.len as usize),
3357 IndentKind::Tab => "\t".repeat(indent.len as usize),
3358 };
3359 let point = Point::new(row.0, 0);
3360 indent_edits.push((point..point, text));
3361 }
3362 }
3363 editor.edit(indent_edits, cx);
3364 });
3365 }
3366
3367 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3368 let buffer = self.buffer.read(cx);
3369 let snapshot = buffer.snapshot(cx);
3370
3371 let mut edits = Vec::new();
3372 let mut rows = Vec::new();
3373 let mut rows_inserted = 0;
3374
3375 for selection in self.selections.all_adjusted(cx) {
3376 let cursor = selection.head();
3377 let row = cursor.row;
3378
3379 let point = Point::new(row + 1, 0);
3380 let start_of_line = snapshot.clip_point(point, Bias::Left);
3381
3382 let newline = "\n".to_string();
3383 edits.push((start_of_line..start_of_line, newline));
3384
3385 rows_inserted += 1;
3386 rows.push(row + rows_inserted);
3387 }
3388
3389 self.transact(window, cx, |editor, window, cx| {
3390 editor.edit(edits, cx);
3391
3392 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3393 let mut index = 0;
3394 s.move_cursors_with(|map, _, _| {
3395 let row = rows[index];
3396 index += 1;
3397
3398 let point = Point::new(row, 0);
3399 let boundary = map.next_line_boundary(point).1;
3400 let clipped = map.clip_point(boundary, Bias::Left);
3401
3402 (clipped, SelectionGoal::None)
3403 });
3404 });
3405
3406 let mut indent_edits = Vec::new();
3407 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3408 for row in rows {
3409 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3410 for (row, indent) in indents {
3411 if indent.len == 0 {
3412 continue;
3413 }
3414
3415 let text = match indent.kind {
3416 IndentKind::Space => " ".repeat(indent.len as usize),
3417 IndentKind::Tab => "\t".repeat(indent.len as usize),
3418 };
3419 let point = Point::new(row.0, 0);
3420 indent_edits.push((point..point, text));
3421 }
3422 }
3423 editor.edit(indent_edits, cx);
3424 });
3425 }
3426
3427 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3428 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3429 original_start_columns: Vec::new(),
3430 });
3431 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3432 }
3433
3434 fn insert_with_autoindent_mode(
3435 &mut self,
3436 text: &str,
3437 autoindent_mode: Option<AutoindentMode>,
3438 window: &mut Window,
3439 cx: &mut Context<Self>,
3440 ) {
3441 if self.read_only(cx) {
3442 return;
3443 }
3444
3445 let text: Arc<str> = text.into();
3446 self.transact(window, cx, |this, window, cx| {
3447 let old_selections = this.selections.all_adjusted(cx);
3448 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3449 let anchors = {
3450 let snapshot = buffer.read(cx);
3451 old_selections
3452 .iter()
3453 .map(|s| {
3454 let anchor = snapshot.anchor_after(s.head());
3455 s.map(|_| anchor)
3456 })
3457 .collect::<Vec<_>>()
3458 };
3459 buffer.edit(
3460 old_selections
3461 .iter()
3462 .map(|s| (s.start..s.end, text.clone())),
3463 autoindent_mode,
3464 cx,
3465 );
3466 anchors
3467 });
3468
3469 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3470 s.select_anchors(selection_anchors);
3471 });
3472
3473 cx.notify();
3474 });
3475 }
3476
3477 fn trigger_completion_on_input(
3478 &mut self,
3479 text: &str,
3480 trigger_in_words: bool,
3481 window: &mut Window,
3482 cx: &mut Context<Self>,
3483 ) {
3484 if self.is_completion_trigger(text, trigger_in_words, cx) {
3485 self.show_completions(
3486 &ShowCompletions {
3487 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3488 },
3489 window,
3490 cx,
3491 );
3492 } else {
3493 self.hide_context_menu(window, cx);
3494 }
3495 }
3496
3497 fn is_completion_trigger(
3498 &self,
3499 text: &str,
3500 trigger_in_words: bool,
3501 cx: &mut Context<Self>,
3502 ) -> bool {
3503 let position = self.selections.newest_anchor().head();
3504 let multibuffer = self.buffer.read(cx);
3505 let Some(buffer) = position
3506 .buffer_id
3507 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3508 else {
3509 return false;
3510 };
3511
3512 if let Some(completion_provider) = &self.completion_provider {
3513 completion_provider.is_completion_trigger(
3514 &buffer,
3515 position.text_anchor,
3516 text,
3517 trigger_in_words,
3518 cx,
3519 )
3520 } else {
3521 false
3522 }
3523 }
3524
3525 /// If any empty selections is touching the start of its innermost containing autoclose
3526 /// region, expand it to select the brackets.
3527 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3528 let selections = self.selections.all::<usize>(cx);
3529 let buffer = self.buffer.read(cx).read(cx);
3530 let new_selections = self
3531 .selections_with_autoclose_regions(selections, &buffer)
3532 .map(|(mut selection, region)| {
3533 if !selection.is_empty() {
3534 return selection;
3535 }
3536
3537 if let Some(region) = region {
3538 let mut range = region.range.to_offset(&buffer);
3539 if selection.start == range.start && range.start >= region.pair.start.len() {
3540 range.start -= region.pair.start.len();
3541 if buffer.contains_str_at(range.start, ®ion.pair.start)
3542 && buffer.contains_str_at(range.end, ®ion.pair.end)
3543 {
3544 range.end += region.pair.end.len();
3545 selection.start = range.start;
3546 selection.end = range.end;
3547
3548 return selection;
3549 }
3550 }
3551 }
3552
3553 let always_treat_brackets_as_autoclosed = buffer
3554 .settings_at(selection.start, cx)
3555 .always_treat_brackets_as_autoclosed;
3556
3557 if !always_treat_brackets_as_autoclosed {
3558 return selection;
3559 }
3560
3561 if let Some(scope) = buffer.language_scope_at(selection.start) {
3562 for (pair, enabled) in scope.brackets() {
3563 if !enabled || !pair.close {
3564 continue;
3565 }
3566
3567 if buffer.contains_str_at(selection.start, &pair.end) {
3568 let pair_start_len = pair.start.len();
3569 if buffer.contains_str_at(
3570 selection.start.saturating_sub(pair_start_len),
3571 &pair.start,
3572 ) {
3573 selection.start -= pair_start_len;
3574 selection.end += pair.end.len();
3575
3576 return selection;
3577 }
3578 }
3579 }
3580 }
3581
3582 selection
3583 })
3584 .collect();
3585
3586 drop(buffer);
3587 self.change_selections(None, window, cx, |selections| {
3588 selections.select(new_selections)
3589 });
3590 }
3591
3592 /// Iterate the given selections, and for each one, find the smallest surrounding
3593 /// autoclose region. This uses the ordering of the selections and the autoclose
3594 /// regions to avoid repeated comparisons.
3595 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3596 &'a self,
3597 selections: impl IntoIterator<Item = Selection<D>>,
3598 buffer: &'a MultiBufferSnapshot,
3599 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3600 let mut i = 0;
3601 let mut regions = self.autoclose_regions.as_slice();
3602 selections.into_iter().map(move |selection| {
3603 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3604
3605 let mut enclosing = None;
3606 while let Some(pair_state) = regions.get(i) {
3607 if pair_state.range.end.to_offset(buffer) < range.start {
3608 regions = ®ions[i + 1..];
3609 i = 0;
3610 } else if pair_state.range.start.to_offset(buffer) > range.end {
3611 break;
3612 } else {
3613 if pair_state.selection_id == selection.id {
3614 enclosing = Some(pair_state);
3615 }
3616 i += 1;
3617 }
3618 }
3619
3620 (selection, enclosing)
3621 })
3622 }
3623
3624 /// Remove any autoclose regions that no longer contain their selection.
3625 fn invalidate_autoclose_regions(
3626 &mut self,
3627 mut selections: &[Selection<Anchor>],
3628 buffer: &MultiBufferSnapshot,
3629 ) {
3630 self.autoclose_regions.retain(|state| {
3631 let mut i = 0;
3632 while let Some(selection) = selections.get(i) {
3633 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3634 selections = &selections[1..];
3635 continue;
3636 }
3637 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3638 break;
3639 }
3640 if selection.id == state.selection_id {
3641 return true;
3642 } else {
3643 i += 1;
3644 }
3645 }
3646 false
3647 });
3648 }
3649
3650 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3651 let offset = position.to_offset(buffer);
3652 let (word_range, kind) = buffer.surrounding_word(offset, true);
3653 if offset > word_range.start && kind == Some(CharKind::Word) {
3654 Some(
3655 buffer
3656 .text_for_range(word_range.start..offset)
3657 .collect::<String>(),
3658 )
3659 } else {
3660 None
3661 }
3662 }
3663
3664 pub fn toggle_inlay_hints(
3665 &mut self,
3666 _: &ToggleInlayHints,
3667 _: &mut Window,
3668 cx: &mut Context<Self>,
3669 ) {
3670 self.refresh_inlay_hints(
3671 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3672 cx,
3673 );
3674 }
3675
3676 pub fn inlay_hints_enabled(&self) -> bool {
3677 self.inlay_hint_cache.enabled
3678 }
3679
3680 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3681 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3682 return;
3683 }
3684
3685 let reason_description = reason.description();
3686 let ignore_debounce = matches!(
3687 reason,
3688 InlayHintRefreshReason::SettingsChange(_)
3689 | InlayHintRefreshReason::Toggle(_)
3690 | InlayHintRefreshReason::ExcerptsRemoved(_)
3691 );
3692 let (invalidate_cache, required_languages) = match reason {
3693 InlayHintRefreshReason::Toggle(enabled) => {
3694 self.inlay_hint_cache.enabled = enabled;
3695 if enabled {
3696 (InvalidationStrategy::RefreshRequested, None)
3697 } else {
3698 self.inlay_hint_cache.clear();
3699 self.splice_inlays(
3700 &self
3701 .visible_inlay_hints(cx)
3702 .iter()
3703 .map(|inlay| inlay.id)
3704 .collect::<Vec<InlayId>>(),
3705 Vec::new(),
3706 cx,
3707 );
3708 return;
3709 }
3710 }
3711 InlayHintRefreshReason::SettingsChange(new_settings) => {
3712 match self.inlay_hint_cache.update_settings(
3713 &self.buffer,
3714 new_settings,
3715 self.visible_inlay_hints(cx),
3716 cx,
3717 ) {
3718 ControlFlow::Break(Some(InlaySplice {
3719 to_remove,
3720 to_insert,
3721 })) => {
3722 self.splice_inlays(&to_remove, to_insert, cx);
3723 return;
3724 }
3725 ControlFlow::Break(None) => return,
3726 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3727 }
3728 }
3729 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3730 if let Some(InlaySplice {
3731 to_remove,
3732 to_insert,
3733 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3734 {
3735 self.splice_inlays(&to_remove, to_insert, cx);
3736 }
3737 return;
3738 }
3739 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3740 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3741 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3742 }
3743 InlayHintRefreshReason::RefreshRequested => {
3744 (InvalidationStrategy::RefreshRequested, None)
3745 }
3746 };
3747
3748 if let Some(InlaySplice {
3749 to_remove,
3750 to_insert,
3751 }) = self.inlay_hint_cache.spawn_hint_refresh(
3752 reason_description,
3753 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3754 invalidate_cache,
3755 ignore_debounce,
3756 cx,
3757 ) {
3758 self.splice_inlays(&to_remove, to_insert, cx);
3759 }
3760 }
3761
3762 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3763 self.display_map
3764 .read(cx)
3765 .current_inlays()
3766 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3767 .cloned()
3768 .collect()
3769 }
3770
3771 pub fn excerpts_for_inlay_hints_query(
3772 &self,
3773 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3774 cx: &mut Context<Editor>,
3775 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3776 let Some(project) = self.project.as_ref() else {
3777 return HashMap::default();
3778 };
3779 let project = project.read(cx);
3780 let multi_buffer = self.buffer().read(cx);
3781 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3782 let multi_buffer_visible_start = self
3783 .scroll_manager
3784 .anchor()
3785 .anchor
3786 .to_point(&multi_buffer_snapshot);
3787 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3788 multi_buffer_visible_start
3789 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3790 Bias::Left,
3791 );
3792 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3793 multi_buffer_snapshot
3794 .range_to_buffer_ranges(multi_buffer_visible_range)
3795 .into_iter()
3796 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3797 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3798 let buffer_file = project::File::from_dyn(buffer.file())?;
3799 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3800 let worktree_entry = buffer_worktree
3801 .read(cx)
3802 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3803 if worktree_entry.is_ignored {
3804 return None;
3805 }
3806
3807 let language = buffer.language()?;
3808 if let Some(restrict_to_languages) = restrict_to_languages {
3809 if !restrict_to_languages.contains(language) {
3810 return None;
3811 }
3812 }
3813 Some((
3814 excerpt_id,
3815 (
3816 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3817 buffer.version().clone(),
3818 excerpt_visible_range,
3819 ),
3820 ))
3821 })
3822 .collect()
3823 }
3824
3825 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3826 TextLayoutDetails {
3827 text_system: window.text_system().clone(),
3828 editor_style: self.style.clone().unwrap(),
3829 rem_size: window.rem_size(),
3830 scroll_anchor: self.scroll_manager.anchor(),
3831 visible_rows: self.visible_line_count(),
3832 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3833 }
3834 }
3835
3836 pub fn splice_inlays(
3837 &self,
3838 to_remove: &[InlayId],
3839 to_insert: Vec<Inlay>,
3840 cx: &mut Context<Self>,
3841 ) {
3842 self.display_map.update(cx, |display_map, cx| {
3843 display_map.splice_inlays(to_remove, to_insert, cx)
3844 });
3845 cx.notify();
3846 }
3847
3848 fn trigger_on_type_formatting(
3849 &self,
3850 input: String,
3851 window: &mut Window,
3852 cx: &mut Context<Self>,
3853 ) -> Option<Task<Result<()>>> {
3854 if input.len() != 1 {
3855 return None;
3856 }
3857
3858 let project = self.project.as_ref()?;
3859 let position = self.selections.newest_anchor().head();
3860 let (buffer, buffer_position) = self
3861 .buffer
3862 .read(cx)
3863 .text_anchor_for_position(position, cx)?;
3864
3865 let settings = language_settings::language_settings(
3866 buffer
3867 .read(cx)
3868 .language_at(buffer_position)
3869 .map(|l| l.name()),
3870 buffer.read(cx).file(),
3871 cx,
3872 );
3873 if !settings.use_on_type_format {
3874 return None;
3875 }
3876
3877 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3878 // hence we do LSP request & edit on host side only — add formats to host's history.
3879 let push_to_lsp_host_history = true;
3880 // If this is not the host, append its history with new edits.
3881 let push_to_client_history = project.read(cx).is_via_collab();
3882
3883 let on_type_formatting = project.update(cx, |project, cx| {
3884 project.on_type_format(
3885 buffer.clone(),
3886 buffer_position,
3887 input,
3888 push_to_lsp_host_history,
3889 cx,
3890 )
3891 });
3892 Some(cx.spawn_in(window, |editor, mut cx| async move {
3893 if let Some(transaction) = on_type_formatting.await? {
3894 if push_to_client_history {
3895 buffer
3896 .update(&mut cx, |buffer, _| {
3897 buffer.push_transaction(transaction, Instant::now());
3898 })
3899 .ok();
3900 }
3901 editor.update(&mut cx, |editor, cx| {
3902 editor.refresh_document_highlights(cx);
3903 })?;
3904 }
3905 Ok(())
3906 }))
3907 }
3908
3909 pub fn show_completions(
3910 &mut self,
3911 options: &ShowCompletions,
3912 window: &mut Window,
3913 cx: &mut Context<Self>,
3914 ) {
3915 if self.pending_rename.is_some() {
3916 return;
3917 }
3918
3919 let Some(provider) = self.completion_provider.as_ref() else {
3920 return;
3921 };
3922
3923 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3924 return;
3925 }
3926
3927 let position = self.selections.newest_anchor().head();
3928 if position.diff_base_anchor.is_some() {
3929 return;
3930 }
3931 let (buffer, buffer_position) =
3932 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3933 output
3934 } else {
3935 return;
3936 };
3937 let show_completion_documentation = buffer
3938 .read(cx)
3939 .snapshot()
3940 .settings_at(buffer_position, cx)
3941 .show_completion_documentation;
3942
3943 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3944
3945 let trigger_kind = match &options.trigger {
3946 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3947 CompletionTriggerKind::TRIGGER_CHARACTER
3948 }
3949 _ => CompletionTriggerKind::INVOKED,
3950 };
3951 let completion_context = CompletionContext {
3952 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3953 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3954 Some(String::from(trigger))
3955 } else {
3956 None
3957 }
3958 }),
3959 trigger_kind,
3960 };
3961 let completions =
3962 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3963 let sort_completions = provider.sort_completions();
3964
3965 let id = post_inc(&mut self.next_completion_id);
3966 let task = cx.spawn_in(window, |editor, mut cx| {
3967 async move {
3968 editor.update(&mut cx, |this, _| {
3969 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3970 })?;
3971 let completions = completions.await.log_err();
3972 let menu = if let Some(completions) = completions {
3973 let mut menu = CompletionsMenu::new(
3974 id,
3975 sort_completions,
3976 show_completion_documentation,
3977 position,
3978 buffer.clone(),
3979 completions.into(),
3980 );
3981
3982 menu.filter(query.as_deref(), cx.background_executor().clone())
3983 .await;
3984
3985 menu.visible().then_some(menu)
3986 } else {
3987 None
3988 };
3989
3990 editor.update_in(&mut cx, |editor, window, cx| {
3991 match editor.context_menu.borrow().as_ref() {
3992 None => {}
3993 Some(CodeContextMenu::Completions(prev_menu)) => {
3994 if prev_menu.id > id {
3995 return;
3996 }
3997 }
3998 _ => return,
3999 }
4000
4001 if editor.focus_handle.is_focused(window) && menu.is_some() {
4002 let mut menu = menu.unwrap();
4003 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4004
4005 *editor.context_menu.borrow_mut() =
4006 Some(CodeContextMenu::Completions(menu));
4007
4008 if editor.show_edit_predictions_in_menu() {
4009 editor.update_visible_inline_completion(window, cx);
4010 } else {
4011 editor.discard_inline_completion(false, cx);
4012 }
4013
4014 cx.notify();
4015 } else if editor.completion_tasks.len() <= 1 {
4016 // If there are no more completion tasks and the last menu was
4017 // empty, we should hide it.
4018 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4019 // If it was already hidden and we don't show inline
4020 // completions in the menu, we should also show the
4021 // inline-completion when available.
4022 if was_hidden && editor.show_edit_predictions_in_menu() {
4023 editor.update_visible_inline_completion(window, cx);
4024 }
4025 }
4026 })?;
4027
4028 Ok::<_, anyhow::Error>(())
4029 }
4030 .log_err()
4031 });
4032
4033 self.completion_tasks.push((id, task));
4034 }
4035
4036 pub fn confirm_completion(
4037 &mut self,
4038 action: &ConfirmCompletion,
4039 window: &mut Window,
4040 cx: &mut Context<Self>,
4041 ) -> Option<Task<Result<()>>> {
4042 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4043 }
4044
4045 pub fn compose_completion(
4046 &mut self,
4047 action: &ComposeCompletion,
4048 window: &mut Window,
4049 cx: &mut Context<Self>,
4050 ) -> Option<Task<Result<()>>> {
4051 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4052 }
4053
4054 fn do_completion(
4055 &mut self,
4056 item_ix: Option<usize>,
4057 intent: CompletionIntent,
4058 window: &mut Window,
4059 cx: &mut Context<Editor>,
4060 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4061 use language::ToOffset as _;
4062
4063 let completions_menu =
4064 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4065 menu
4066 } else {
4067 return None;
4068 };
4069
4070 let entries = completions_menu.entries.borrow();
4071 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4072 if self.show_edit_predictions_in_menu() {
4073 self.discard_inline_completion(true, cx);
4074 }
4075 let candidate_id = mat.candidate_id;
4076 drop(entries);
4077
4078 let buffer_handle = completions_menu.buffer;
4079 let completion = completions_menu
4080 .completions
4081 .borrow()
4082 .get(candidate_id)?
4083 .clone();
4084 cx.stop_propagation();
4085
4086 let snippet;
4087 let text;
4088
4089 if completion.is_snippet() {
4090 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4091 text = snippet.as_ref().unwrap().text.clone();
4092 } else {
4093 snippet = None;
4094 text = completion.new_text.clone();
4095 };
4096 let selections = self.selections.all::<usize>(cx);
4097 let buffer = buffer_handle.read(cx);
4098 let old_range = completion.old_range.to_offset(buffer);
4099 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4100
4101 let newest_selection = self.selections.newest_anchor();
4102 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4103 return None;
4104 }
4105
4106 let lookbehind = newest_selection
4107 .start
4108 .text_anchor
4109 .to_offset(buffer)
4110 .saturating_sub(old_range.start);
4111 let lookahead = old_range
4112 .end
4113 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4114 let mut common_prefix_len = old_text
4115 .bytes()
4116 .zip(text.bytes())
4117 .take_while(|(a, b)| a == b)
4118 .count();
4119
4120 let snapshot = self.buffer.read(cx).snapshot(cx);
4121 let mut range_to_replace: Option<Range<isize>> = None;
4122 let mut ranges = Vec::new();
4123 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4124 for selection in &selections {
4125 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4126 let start = selection.start.saturating_sub(lookbehind);
4127 let end = selection.end + lookahead;
4128 if selection.id == newest_selection.id {
4129 range_to_replace = Some(
4130 ((start + common_prefix_len) as isize - selection.start as isize)
4131 ..(end as isize - selection.start as isize),
4132 );
4133 }
4134 ranges.push(start + common_prefix_len..end);
4135 } else {
4136 common_prefix_len = 0;
4137 ranges.clear();
4138 ranges.extend(selections.iter().map(|s| {
4139 if s.id == newest_selection.id {
4140 range_to_replace = Some(
4141 old_range.start.to_offset_utf16(&snapshot).0 as isize
4142 - selection.start as isize
4143 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4144 - selection.start as isize,
4145 );
4146 old_range.clone()
4147 } else {
4148 s.start..s.end
4149 }
4150 }));
4151 break;
4152 }
4153 if !self.linked_edit_ranges.is_empty() {
4154 let start_anchor = snapshot.anchor_before(selection.head());
4155 let end_anchor = snapshot.anchor_after(selection.tail());
4156 if let Some(ranges) = self
4157 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4158 {
4159 for (buffer, edits) in ranges {
4160 linked_edits.entry(buffer.clone()).or_default().extend(
4161 edits
4162 .into_iter()
4163 .map(|range| (range, text[common_prefix_len..].to_owned())),
4164 );
4165 }
4166 }
4167 }
4168 }
4169 let text = &text[common_prefix_len..];
4170
4171 cx.emit(EditorEvent::InputHandled {
4172 utf16_range_to_replace: range_to_replace,
4173 text: text.into(),
4174 });
4175
4176 self.transact(window, cx, |this, window, cx| {
4177 if let Some(mut snippet) = snippet {
4178 snippet.text = text.to_string();
4179 for tabstop in snippet
4180 .tabstops
4181 .iter_mut()
4182 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4183 {
4184 tabstop.start -= common_prefix_len as isize;
4185 tabstop.end -= common_prefix_len as isize;
4186 }
4187
4188 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4189 } else {
4190 this.buffer.update(cx, |buffer, cx| {
4191 buffer.edit(
4192 ranges.iter().map(|range| (range.clone(), text)),
4193 this.autoindent_mode.clone(),
4194 cx,
4195 );
4196 });
4197 }
4198 for (buffer, edits) in linked_edits {
4199 buffer.update(cx, |buffer, cx| {
4200 let snapshot = buffer.snapshot();
4201 let edits = edits
4202 .into_iter()
4203 .map(|(range, text)| {
4204 use text::ToPoint as TP;
4205 let end_point = TP::to_point(&range.end, &snapshot);
4206 let start_point = TP::to_point(&range.start, &snapshot);
4207 (start_point..end_point, text)
4208 })
4209 .sorted_by_key(|(range, _)| range.start)
4210 .collect::<Vec<_>>();
4211 buffer.edit(edits, None, cx);
4212 })
4213 }
4214
4215 this.refresh_inline_completion(true, false, window, cx);
4216 });
4217
4218 let show_new_completions_on_confirm = completion
4219 .confirm
4220 .as_ref()
4221 .map_or(false, |confirm| confirm(intent, window, cx));
4222 if show_new_completions_on_confirm {
4223 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4224 }
4225
4226 let provider = self.completion_provider.as_ref()?;
4227 drop(completion);
4228 let apply_edits = provider.apply_additional_edits_for_completion(
4229 buffer_handle,
4230 completions_menu.completions.clone(),
4231 candidate_id,
4232 true,
4233 cx,
4234 );
4235
4236 let editor_settings = EditorSettings::get_global(cx);
4237 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4238 // After the code completion is finished, users often want to know what signatures are needed.
4239 // so we should automatically call signature_help
4240 self.show_signature_help(&ShowSignatureHelp, window, cx);
4241 }
4242
4243 Some(cx.foreground_executor().spawn(async move {
4244 apply_edits.await?;
4245 Ok(())
4246 }))
4247 }
4248
4249 pub fn toggle_code_actions(
4250 &mut self,
4251 action: &ToggleCodeActions,
4252 window: &mut Window,
4253 cx: &mut Context<Self>,
4254 ) {
4255 let mut context_menu = self.context_menu.borrow_mut();
4256 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4257 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4258 // Toggle if we're selecting the same one
4259 *context_menu = None;
4260 cx.notify();
4261 return;
4262 } else {
4263 // Otherwise, clear it and start a new one
4264 *context_menu = None;
4265 cx.notify();
4266 }
4267 }
4268 drop(context_menu);
4269 let snapshot = self.snapshot(window, cx);
4270 let deployed_from_indicator = action.deployed_from_indicator;
4271 let mut task = self.code_actions_task.take();
4272 let action = action.clone();
4273 cx.spawn_in(window, |editor, mut cx| async move {
4274 while let Some(prev_task) = task {
4275 prev_task.await.log_err();
4276 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4277 }
4278
4279 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4280 if editor.focus_handle.is_focused(window) {
4281 let multibuffer_point = action
4282 .deployed_from_indicator
4283 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4284 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4285 let (buffer, buffer_row) = snapshot
4286 .buffer_snapshot
4287 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4288 .and_then(|(buffer_snapshot, range)| {
4289 editor
4290 .buffer
4291 .read(cx)
4292 .buffer(buffer_snapshot.remote_id())
4293 .map(|buffer| (buffer, range.start.row))
4294 })?;
4295 let (_, code_actions) = editor
4296 .available_code_actions
4297 .clone()
4298 .and_then(|(location, code_actions)| {
4299 let snapshot = location.buffer.read(cx).snapshot();
4300 let point_range = location.range.to_point(&snapshot);
4301 let point_range = point_range.start.row..=point_range.end.row;
4302 if point_range.contains(&buffer_row) {
4303 Some((location, code_actions))
4304 } else {
4305 None
4306 }
4307 })
4308 .unzip();
4309 let buffer_id = buffer.read(cx).remote_id();
4310 let tasks = editor
4311 .tasks
4312 .get(&(buffer_id, buffer_row))
4313 .map(|t| Arc::new(t.to_owned()));
4314 if tasks.is_none() && code_actions.is_none() {
4315 return None;
4316 }
4317
4318 editor.completion_tasks.clear();
4319 editor.discard_inline_completion(false, cx);
4320 let task_context =
4321 tasks
4322 .as_ref()
4323 .zip(editor.project.clone())
4324 .map(|(tasks, project)| {
4325 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4326 });
4327
4328 Some(cx.spawn_in(window, |editor, mut cx| async move {
4329 let task_context = match task_context {
4330 Some(task_context) => task_context.await,
4331 None => None,
4332 };
4333 let resolved_tasks =
4334 tasks.zip(task_context).map(|(tasks, task_context)| {
4335 Rc::new(ResolvedTasks {
4336 templates: tasks.resolve(&task_context).collect(),
4337 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4338 multibuffer_point.row,
4339 tasks.column,
4340 )),
4341 })
4342 });
4343 let spawn_straight_away = resolved_tasks
4344 .as_ref()
4345 .map_or(false, |tasks| tasks.templates.len() == 1)
4346 && code_actions
4347 .as_ref()
4348 .map_or(true, |actions| actions.is_empty());
4349 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4350 *editor.context_menu.borrow_mut() =
4351 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4352 buffer,
4353 actions: CodeActionContents {
4354 tasks: resolved_tasks,
4355 actions: code_actions,
4356 },
4357 selected_item: Default::default(),
4358 scroll_handle: UniformListScrollHandle::default(),
4359 deployed_from_indicator,
4360 }));
4361 if spawn_straight_away {
4362 if let Some(task) = editor.confirm_code_action(
4363 &ConfirmCodeAction { item_ix: Some(0) },
4364 window,
4365 cx,
4366 ) {
4367 cx.notify();
4368 return task;
4369 }
4370 }
4371 cx.notify();
4372 Task::ready(Ok(()))
4373 }) {
4374 task.await
4375 } else {
4376 Ok(())
4377 }
4378 }))
4379 } else {
4380 Some(Task::ready(Ok(())))
4381 }
4382 })?;
4383 if let Some(task) = spawned_test_task {
4384 task.await?;
4385 }
4386
4387 Ok::<_, anyhow::Error>(())
4388 })
4389 .detach_and_log_err(cx);
4390 }
4391
4392 pub fn confirm_code_action(
4393 &mut self,
4394 action: &ConfirmCodeAction,
4395 window: &mut Window,
4396 cx: &mut Context<Self>,
4397 ) -> Option<Task<Result<()>>> {
4398 let actions_menu =
4399 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4400 menu
4401 } else {
4402 return None;
4403 };
4404 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4405 let action = actions_menu.actions.get(action_ix)?;
4406 let title = action.label();
4407 let buffer = actions_menu.buffer;
4408 let workspace = self.workspace()?;
4409
4410 match action {
4411 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4412 workspace.update(cx, |workspace, cx| {
4413 workspace::tasks::schedule_resolved_task(
4414 workspace,
4415 task_source_kind,
4416 resolved_task,
4417 false,
4418 cx,
4419 );
4420
4421 Some(Task::ready(Ok(())))
4422 })
4423 }
4424 CodeActionsItem::CodeAction {
4425 excerpt_id,
4426 action,
4427 provider,
4428 } => {
4429 let apply_code_action =
4430 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4431 let workspace = workspace.downgrade();
4432 Some(cx.spawn_in(window, |editor, cx| async move {
4433 let project_transaction = apply_code_action.await?;
4434 Self::open_project_transaction(
4435 &editor,
4436 workspace,
4437 project_transaction,
4438 title,
4439 cx,
4440 )
4441 .await
4442 }))
4443 }
4444 }
4445 }
4446
4447 pub async fn open_project_transaction(
4448 this: &WeakEntity<Editor>,
4449 workspace: WeakEntity<Workspace>,
4450 transaction: ProjectTransaction,
4451 title: String,
4452 mut cx: AsyncWindowContext,
4453 ) -> Result<()> {
4454 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4455 cx.update(|_, cx| {
4456 entries.sort_unstable_by_key(|(buffer, _)| {
4457 buffer.read(cx).file().map(|f| f.path().clone())
4458 });
4459 })?;
4460
4461 // If the project transaction's edits are all contained within this editor, then
4462 // avoid opening a new editor to display them.
4463
4464 if let Some((buffer, transaction)) = entries.first() {
4465 if entries.len() == 1 {
4466 let excerpt = this.update(&mut cx, |editor, cx| {
4467 editor
4468 .buffer()
4469 .read(cx)
4470 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4471 })?;
4472 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4473 if excerpted_buffer == *buffer {
4474 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4475 let excerpt_range = excerpt_range.to_offset(buffer);
4476 buffer
4477 .edited_ranges_for_transaction::<usize>(transaction)
4478 .all(|range| {
4479 excerpt_range.start <= range.start
4480 && excerpt_range.end >= range.end
4481 })
4482 })?;
4483
4484 if all_edits_within_excerpt {
4485 return Ok(());
4486 }
4487 }
4488 }
4489 }
4490 } else {
4491 return Ok(());
4492 }
4493
4494 let mut ranges_to_highlight = Vec::new();
4495 let excerpt_buffer = cx.new(|cx| {
4496 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4497 for (buffer_handle, transaction) in &entries {
4498 let buffer = buffer_handle.read(cx);
4499 ranges_to_highlight.extend(
4500 multibuffer.push_excerpts_with_context_lines(
4501 buffer_handle.clone(),
4502 buffer
4503 .edited_ranges_for_transaction::<usize>(transaction)
4504 .collect(),
4505 DEFAULT_MULTIBUFFER_CONTEXT,
4506 cx,
4507 ),
4508 );
4509 }
4510 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4511 multibuffer
4512 })?;
4513
4514 workspace.update_in(&mut cx, |workspace, window, cx| {
4515 let project = workspace.project().clone();
4516 let editor = cx
4517 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4518 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4519 editor.update(cx, |editor, cx| {
4520 editor.highlight_background::<Self>(
4521 &ranges_to_highlight,
4522 |theme| theme.editor_highlighted_line_background,
4523 cx,
4524 );
4525 });
4526 })?;
4527
4528 Ok(())
4529 }
4530
4531 pub fn clear_code_action_providers(&mut self) {
4532 self.code_action_providers.clear();
4533 self.available_code_actions.take();
4534 }
4535
4536 pub fn add_code_action_provider(
4537 &mut self,
4538 provider: Rc<dyn CodeActionProvider>,
4539 window: &mut Window,
4540 cx: &mut Context<Self>,
4541 ) {
4542 if self
4543 .code_action_providers
4544 .iter()
4545 .any(|existing_provider| existing_provider.id() == provider.id())
4546 {
4547 return;
4548 }
4549
4550 self.code_action_providers.push(provider);
4551 self.refresh_code_actions(window, cx);
4552 }
4553
4554 pub fn remove_code_action_provider(
4555 &mut self,
4556 id: Arc<str>,
4557 window: &mut Window,
4558 cx: &mut Context<Self>,
4559 ) {
4560 self.code_action_providers
4561 .retain(|provider| provider.id() != id);
4562 self.refresh_code_actions(window, cx);
4563 }
4564
4565 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4566 let buffer = self.buffer.read(cx);
4567 let newest_selection = self.selections.newest_anchor().clone();
4568 if newest_selection.head().diff_base_anchor.is_some() {
4569 return None;
4570 }
4571 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4572 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4573 if start_buffer != end_buffer {
4574 return None;
4575 }
4576
4577 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4578 cx.background_executor()
4579 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4580 .await;
4581
4582 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4583 let providers = this.code_action_providers.clone();
4584 let tasks = this
4585 .code_action_providers
4586 .iter()
4587 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4588 .collect::<Vec<_>>();
4589 (providers, tasks)
4590 })?;
4591
4592 let mut actions = Vec::new();
4593 for (provider, provider_actions) in
4594 providers.into_iter().zip(future::join_all(tasks).await)
4595 {
4596 if let Some(provider_actions) = provider_actions.log_err() {
4597 actions.extend(provider_actions.into_iter().map(|action| {
4598 AvailableCodeAction {
4599 excerpt_id: newest_selection.start.excerpt_id,
4600 action,
4601 provider: provider.clone(),
4602 }
4603 }));
4604 }
4605 }
4606
4607 this.update(&mut cx, |this, cx| {
4608 this.available_code_actions = if actions.is_empty() {
4609 None
4610 } else {
4611 Some((
4612 Location {
4613 buffer: start_buffer,
4614 range: start..end,
4615 },
4616 actions.into(),
4617 ))
4618 };
4619 cx.notify();
4620 })
4621 }));
4622 None
4623 }
4624
4625 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4626 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4627 self.show_git_blame_inline = false;
4628
4629 self.show_git_blame_inline_delay_task =
4630 Some(cx.spawn_in(window, |this, mut cx| async move {
4631 cx.background_executor().timer(delay).await;
4632
4633 this.update(&mut cx, |this, cx| {
4634 this.show_git_blame_inline = true;
4635 cx.notify();
4636 })
4637 .log_err();
4638 }));
4639 }
4640 }
4641
4642 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4643 if self.pending_rename.is_some() {
4644 return None;
4645 }
4646
4647 let provider = self.semantics_provider.clone()?;
4648 let buffer = self.buffer.read(cx);
4649 let newest_selection = self.selections.newest_anchor().clone();
4650 let cursor_position = newest_selection.head();
4651 let (cursor_buffer, cursor_buffer_position) =
4652 buffer.text_anchor_for_position(cursor_position, cx)?;
4653 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4654 if cursor_buffer != tail_buffer {
4655 return None;
4656 }
4657 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4658 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4659 cx.background_executor()
4660 .timer(Duration::from_millis(debounce))
4661 .await;
4662
4663 let highlights = if let Some(highlights) = cx
4664 .update(|cx| {
4665 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4666 })
4667 .ok()
4668 .flatten()
4669 {
4670 highlights.await.log_err()
4671 } else {
4672 None
4673 };
4674
4675 if let Some(highlights) = highlights {
4676 this.update(&mut cx, |this, cx| {
4677 if this.pending_rename.is_some() {
4678 return;
4679 }
4680
4681 let buffer_id = cursor_position.buffer_id;
4682 let buffer = this.buffer.read(cx);
4683 if !buffer
4684 .text_anchor_for_position(cursor_position, cx)
4685 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4686 {
4687 return;
4688 }
4689
4690 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4691 let mut write_ranges = Vec::new();
4692 let mut read_ranges = Vec::new();
4693 for highlight in highlights {
4694 for (excerpt_id, excerpt_range) in
4695 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4696 {
4697 let start = highlight
4698 .range
4699 .start
4700 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4701 let end = highlight
4702 .range
4703 .end
4704 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4705 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4706 continue;
4707 }
4708
4709 let range = Anchor {
4710 buffer_id,
4711 excerpt_id,
4712 text_anchor: start,
4713 diff_base_anchor: None,
4714 }..Anchor {
4715 buffer_id,
4716 excerpt_id,
4717 text_anchor: end,
4718 diff_base_anchor: None,
4719 };
4720 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4721 write_ranges.push(range);
4722 } else {
4723 read_ranges.push(range);
4724 }
4725 }
4726 }
4727
4728 this.highlight_background::<DocumentHighlightRead>(
4729 &read_ranges,
4730 |theme| theme.editor_document_highlight_read_background,
4731 cx,
4732 );
4733 this.highlight_background::<DocumentHighlightWrite>(
4734 &write_ranges,
4735 |theme| theme.editor_document_highlight_write_background,
4736 cx,
4737 );
4738 cx.notify();
4739 })
4740 .log_err();
4741 }
4742 }));
4743 None
4744 }
4745
4746 pub fn refresh_selected_text_highlights(
4747 &mut self,
4748 window: &mut Window,
4749 cx: &mut Context<Editor>,
4750 ) {
4751 self.selection_highlight_task.take();
4752 if !EditorSettings::get_global(cx).selection_highlight {
4753 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4754 return;
4755 }
4756 if self.selections.count() != 1 || self.selections.line_mode {
4757 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4758 return;
4759 }
4760 let selection = self.selections.newest::<Point>(cx);
4761 if selection.is_empty() || selection.start.row != selection.end.row {
4762 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4763 return;
4764 }
4765 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4766 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4767 cx.background_executor()
4768 .timer(Duration::from_millis(debounce))
4769 .await;
4770 let Some(Some(matches_task)) = editor
4771 .update_in(&mut cx, |editor, _, cx| {
4772 if editor.selections.count() != 1 || editor.selections.line_mode {
4773 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4774 return None;
4775 }
4776 let selection = editor.selections.newest::<Point>(cx);
4777 if selection.is_empty() || selection.start.row != selection.end.row {
4778 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4779 return None;
4780 }
4781 let buffer = editor.buffer().read(cx).snapshot(cx);
4782 let query = buffer.text_for_range(selection.range()).collect::<String>();
4783 if query.trim().is_empty() {
4784 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4785 return None;
4786 }
4787 Some(cx.background_spawn(async move {
4788 let mut ranges = Vec::new();
4789 let selection_anchors = selection.range().to_anchors(&buffer);
4790 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4791 for (search_buffer, search_range, excerpt_id) in
4792 buffer.range_to_buffer_ranges(range)
4793 {
4794 ranges.extend(
4795 project::search::SearchQuery::text(
4796 query.clone(),
4797 false,
4798 false,
4799 false,
4800 Default::default(),
4801 Default::default(),
4802 None,
4803 )
4804 .unwrap()
4805 .search(search_buffer, Some(search_range.clone()))
4806 .await
4807 .into_iter()
4808 .filter_map(
4809 |match_range| {
4810 let start = search_buffer.anchor_after(
4811 search_range.start + match_range.start,
4812 );
4813 let end = search_buffer.anchor_before(
4814 search_range.start + match_range.end,
4815 );
4816 let range = Anchor::range_in_buffer(
4817 excerpt_id,
4818 search_buffer.remote_id(),
4819 start..end,
4820 );
4821 (range != selection_anchors).then_some(range)
4822 },
4823 ),
4824 );
4825 }
4826 }
4827 ranges
4828 }))
4829 })
4830 .log_err()
4831 else {
4832 return;
4833 };
4834 let matches = matches_task.await;
4835 editor
4836 .update_in(&mut cx, |editor, _, cx| {
4837 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4838 if !matches.is_empty() {
4839 editor.highlight_background::<SelectedTextHighlight>(
4840 &matches,
4841 |theme| theme.editor_document_highlight_bracket_background,
4842 cx,
4843 )
4844 }
4845 })
4846 .log_err();
4847 }));
4848 }
4849
4850 pub fn refresh_inline_completion(
4851 &mut self,
4852 debounce: bool,
4853 user_requested: bool,
4854 window: &mut Window,
4855 cx: &mut Context<Self>,
4856 ) -> Option<()> {
4857 let provider = self.edit_prediction_provider()?;
4858 let cursor = self.selections.newest_anchor().head();
4859 let (buffer, cursor_buffer_position) =
4860 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4861
4862 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4863 self.discard_inline_completion(false, cx);
4864 return None;
4865 }
4866
4867 if !user_requested
4868 && (!self.should_show_edit_predictions()
4869 || !self.is_focused(window)
4870 || buffer.read(cx).is_empty())
4871 {
4872 self.discard_inline_completion(false, cx);
4873 return None;
4874 }
4875
4876 self.update_visible_inline_completion(window, cx);
4877 provider.refresh(
4878 self.project.clone(),
4879 buffer,
4880 cursor_buffer_position,
4881 debounce,
4882 cx,
4883 );
4884 Some(())
4885 }
4886
4887 fn show_edit_predictions_in_menu(&self) -> bool {
4888 match self.edit_prediction_settings {
4889 EditPredictionSettings::Disabled => false,
4890 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4891 }
4892 }
4893
4894 pub fn edit_predictions_enabled(&self) -> bool {
4895 match self.edit_prediction_settings {
4896 EditPredictionSettings::Disabled => false,
4897 EditPredictionSettings::Enabled { .. } => true,
4898 }
4899 }
4900
4901 fn edit_prediction_requires_modifier(&self) -> bool {
4902 match self.edit_prediction_settings {
4903 EditPredictionSettings::Disabled => false,
4904 EditPredictionSettings::Enabled {
4905 preview_requires_modifier,
4906 ..
4907 } => preview_requires_modifier,
4908 }
4909 }
4910
4911 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4912 if self.edit_prediction_provider.is_none() {
4913 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4914 } else {
4915 let selection = self.selections.newest_anchor();
4916 let cursor = selection.head();
4917
4918 if let Some((buffer, cursor_buffer_position)) =
4919 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4920 {
4921 self.edit_prediction_settings =
4922 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
4923 }
4924 }
4925 }
4926
4927 fn edit_prediction_settings_at_position(
4928 &self,
4929 buffer: &Entity<Buffer>,
4930 buffer_position: language::Anchor,
4931 cx: &App,
4932 ) -> EditPredictionSettings {
4933 if self.mode != EditorMode::Full
4934 || !self.show_inline_completions_override.unwrap_or(true)
4935 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
4936 {
4937 return EditPredictionSettings::Disabled;
4938 }
4939
4940 let buffer = buffer.read(cx);
4941
4942 let file = buffer.file();
4943
4944 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
4945 return EditPredictionSettings::Disabled;
4946 };
4947
4948 let by_provider = matches!(
4949 self.menu_inline_completions_policy,
4950 MenuInlineCompletionsPolicy::ByProvider
4951 );
4952
4953 let show_in_menu = by_provider
4954 && self
4955 .edit_prediction_provider
4956 .as_ref()
4957 .map_or(false, |provider| {
4958 provider.provider.show_completions_in_menu()
4959 });
4960
4961 let preview_requires_modifier =
4962 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
4963
4964 EditPredictionSettings::Enabled {
4965 show_in_menu,
4966 preview_requires_modifier,
4967 }
4968 }
4969
4970 fn should_show_edit_predictions(&self) -> bool {
4971 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
4972 }
4973
4974 pub fn edit_prediction_preview_is_active(&self) -> bool {
4975 matches!(
4976 self.edit_prediction_preview,
4977 EditPredictionPreview::Active { .. }
4978 )
4979 }
4980
4981 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
4982 let cursor = self.selections.newest_anchor().head();
4983 if let Some((buffer, cursor_position)) =
4984 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4985 {
4986 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
4987 } else {
4988 false
4989 }
4990 }
4991
4992 fn edit_predictions_enabled_in_buffer(
4993 &self,
4994 buffer: &Entity<Buffer>,
4995 buffer_position: language::Anchor,
4996 cx: &App,
4997 ) -> bool {
4998 maybe!({
4999 let provider = self.edit_prediction_provider()?;
5000 if !provider.is_enabled(&buffer, buffer_position, cx) {
5001 return Some(false);
5002 }
5003 let buffer = buffer.read(cx);
5004 let Some(file) = buffer.file() else {
5005 return Some(true);
5006 };
5007 let settings = all_language_settings(Some(file), cx);
5008 Some(settings.inline_completions_enabled_for_path(file.path()))
5009 })
5010 .unwrap_or(false)
5011 }
5012
5013 fn cycle_inline_completion(
5014 &mut self,
5015 direction: Direction,
5016 window: &mut Window,
5017 cx: &mut Context<Self>,
5018 ) -> Option<()> {
5019 let provider = self.edit_prediction_provider()?;
5020 let cursor = self.selections.newest_anchor().head();
5021 let (buffer, cursor_buffer_position) =
5022 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5023 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5024 return None;
5025 }
5026
5027 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5028 self.update_visible_inline_completion(window, cx);
5029
5030 Some(())
5031 }
5032
5033 pub fn show_inline_completion(
5034 &mut self,
5035 _: &ShowEditPrediction,
5036 window: &mut Window,
5037 cx: &mut Context<Self>,
5038 ) {
5039 if !self.has_active_inline_completion() {
5040 self.refresh_inline_completion(false, true, window, cx);
5041 return;
5042 }
5043
5044 self.update_visible_inline_completion(window, cx);
5045 }
5046
5047 pub fn display_cursor_names(
5048 &mut self,
5049 _: &DisplayCursorNames,
5050 window: &mut Window,
5051 cx: &mut Context<Self>,
5052 ) {
5053 self.show_cursor_names(window, cx);
5054 }
5055
5056 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5057 self.show_cursor_names = true;
5058 cx.notify();
5059 cx.spawn_in(window, |this, mut cx| async move {
5060 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5061 this.update(&mut cx, |this, cx| {
5062 this.show_cursor_names = false;
5063 cx.notify()
5064 })
5065 .ok()
5066 })
5067 .detach();
5068 }
5069
5070 pub fn next_edit_prediction(
5071 &mut self,
5072 _: &NextEditPrediction,
5073 window: &mut Window,
5074 cx: &mut Context<Self>,
5075 ) {
5076 if self.has_active_inline_completion() {
5077 self.cycle_inline_completion(Direction::Next, window, cx);
5078 } else {
5079 let is_copilot_disabled = self
5080 .refresh_inline_completion(false, true, window, cx)
5081 .is_none();
5082 if is_copilot_disabled {
5083 cx.propagate();
5084 }
5085 }
5086 }
5087
5088 pub fn previous_edit_prediction(
5089 &mut self,
5090 _: &PreviousEditPrediction,
5091 window: &mut Window,
5092 cx: &mut Context<Self>,
5093 ) {
5094 if self.has_active_inline_completion() {
5095 self.cycle_inline_completion(Direction::Prev, window, cx);
5096 } else {
5097 let is_copilot_disabled = self
5098 .refresh_inline_completion(false, true, window, cx)
5099 .is_none();
5100 if is_copilot_disabled {
5101 cx.propagate();
5102 }
5103 }
5104 }
5105
5106 pub fn accept_edit_prediction(
5107 &mut self,
5108 _: &AcceptEditPrediction,
5109 window: &mut Window,
5110 cx: &mut Context<Self>,
5111 ) {
5112 if self.show_edit_predictions_in_menu() {
5113 self.hide_context_menu(window, cx);
5114 }
5115
5116 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5117 return;
5118 };
5119
5120 self.report_inline_completion_event(
5121 active_inline_completion.completion_id.clone(),
5122 true,
5123 cx,
5124 );
5125
5126 match &active_inline_completion.completion {
5127 InlineCompletion::Move { target, .. } => {
5128 let target = *target;
5129
5130 if let Some(position_map) = &self.last_position_map {
5131 if position_map
5132 .visible_row_range
5133 .contains(&target.to_display_point(&position_map.snapshot).row())
5134 || !self.edit_prediction_requires_modifier()
5135 {
5136 self.unfold_ranges(&[target..target], true, false, cx);
5137 // Note that this is also done in vim's handler of the Tab action.
5138 self.change_selections(
5139 Some(Autoscroll::newest()),
5140 window,
5141 cx,
5142 |selections| {
5143 selections.select_anchor_ranges([target..target]);
5144 },
5145 );
5146 self.clear_row_highlights::<EditPredictionPreview>();
5147
5148 self.edit_prediction_preview
5149 .set_previous_scroll_position(None);
5150 } else {
5151 self.edit_prediction_preview
5152 .set_previous_scroll_position(Some(
5153 position_map.snapshot.scroll_anchor,
5154 ));
5155
5156 self.highlight_rows::<EditPredictionPreview>(
5157 target..target,
5158 cx.theme().colors().editor_highlighted_line_background,
5159 true,
5160 cx,
5161 );
5162 self.request_autoscroll(Autoscroll::fit(), cx);
5163 }
5164 }
5165 }
5166 InlineCompletion::Edit { edits, .. } => {
5167 if let Some(provider) = self.edit_prediction_provider() {
5168 provider.accept(cx);
5169 }
5170
5171 let snapshot = self.buffer.read(cx).snapshot(cx);
5172 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5173
5174 self.buffer.update(cx, |buffer, cx| {
5175 buffer.edit(edits.iter().cloned(), None, cx)
5176 });
5177
5178 self.change_selections(None, window, cx, |s| {
5179 s.select_anchor_ranges([last_edit_end..last_edit_end])
5180 });
5181
5182 self.update_visible_inline_completion(window, cx);
5183 if self.active_inline_completion.is_none() {
5184 self.refresh_inline_completion(true, true, window, cx);
5185 }
5186
5187 cx.notify();
5188 }
5189 }
5190
5191 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5192 }
5193
5194 pub fn accept_partial_inline_completion(
5195 &mut self,
5196 _: &AcceptPartialEditPrediction,
5197 window: &mut Window,
5198 cx: &mut Context<Self>,
5199 ) {
5200 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5201 return;
5202 };
5203 if self.selections.count() != 1 {
5204 return;
5205 }
5206
5207 self.report_inline_completion_event(
5208 active_inline_completion.completion_id.clone(),
5209 true,
5210 cx,
5211 );
5212
5213 match &active_inline_completion.completion {
5214 InlineCompletion::Move { target, .. } => {
5215 let target = *target;
5216 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5217 selections.select_anchor_ranges([target..target]);
5218 });
5219 }
5220 InlineCompletion::Edit { edits, .. } => {
5221 // Find an insertion that starts at the cursor position.
5222 let snapshot = self.buffer.read(cx).snapshot(cx);
5223 let cursor_offset = self.selections.newest::<usize>(cx).head();
5224 let insertion = edits.iter().find_map(|(range, text)| {
5225 let range = range.to_offset(&snapshot);
5226 if range.is_empty() && range.start == cursor_offset {
5227 Some(text)
5228 } else {
5229 None
5230 }
5231 });
5232
5233 if let Some(text) = insertion {
5234 let mut partial_completion = text
5235 .chars()
5236 .by_ref()
5237 .take_while(|c| c.is_alphabetic())
5238 .collect::<String>();
5239 if partial_completion.is_empty() {
5240 partial_completion = text
5241 .chars()
5242 .by_ref()
5243 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5244 .collect::<String>();
5245 }
5246
5247 cx.emit(EditorEvent::InputHandled {
5248 utf16_range_to_replace: None,
5249 text: partial_completion.clone().into(),
5250 });
5251
5252 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5253
5254 self.refresh_inline_completion(true, true, window, cx);
5255 cx.notify();
5256 } else {
5257 self.accept_edit_prediction(&Default::default(), window, cx);
5258 }
5259 }
5260 }
5261 }
5262
5263 fn discard_inline_completion(
5264 &mut self,
5265 should_report_inline_completion_event: bool,
5266 cx: &mut Context<Self>,
5267 ) -> bool {
5268 if should_report_inline_completion_event {
5269 let completion_id = self
5270 .active_inline_completion
5271 .as_ref()
5272 .and_then(|active_completion| active_completion.completion_id.clone());
5273
5274 self.report_inline_completion_event(completion_id, false, cx);
5275 }
5276
5277 if let Some(provider) = self.edit_prediction_provider() {
5278 provider.discard(cx);
5279 }
5280
5281 self.take_active_inline_completion(cx)
5282 }
5283
5284 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5285 let Some(provider) = self.edit_prediction_provider() else {
5286 return;
5287 };
5288
5289 let Some((_, buffer, _)) = self
5290 .buffer
5291 .read(cx)
5292 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5293 else {
5294 return;
5295 };
5296
5297 let extension = buffer
5298 .read(cx)
5299 .file()
5300 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5301
5302 let event_type = match accepted {
5303 true => "Edit Prediction Accepted",
5304 false => "Edit Prediction Discarded",
5305 };
5306 telemetry::event!(
5307 event_type,
5308 provider = provider.name(),
5309 prediction_id = id,
5310 suggestion_accepted = accepted,
5311 file_extension = extension,
5312 );
5313 }
5314
5315 pub fn has_active_inline_completion(&self) -> bool {
5316 self.active_inline_completion.is_some()
5317 }
5318
5319 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5320 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5321 return false;
5322 };
5323
5324 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5325 self.clear_highlights::<InlineCompletionHighlight>(cx);
5326 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5327 true
5328 }
5329
5330 /// Returns true when we're displaying the edit prediction popover below the cursor
5331 /// like we are not previewing and the LSP autocomplete menu is visible
5332 /// or we are in `when_holding_modifier` mode.
5333 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5334 if self.edit_prediction_preview_is_active()
5335 || !self.show_edit_predictions_in_menu()
5336 || !self.edit_predictions_enabled()
5337 {
5338 return false;
5339 }
5340
5341 if self.has_visible_completions_menu() {
5342 return true;
5343 }
5344
5345 has_completion && self.edit_prediction_requires_modifier()
5346 }
5347
5348 fn handle_modifiers_changed(
5349 &mut self,
5350 modifiers: Modifiers,
5351 position_map: &PositionMap,
5352 window: &mut Window,
5353 cx: &mut Context<Self>,
5354 ) {
5355 if self.show_edit_predictions_in_menu() {
5356 self.update_edit_prediction_preview(&modifiers, window, cx);
5357 }
5358
5359 self.update_selection_mode(&modifiers, position_map, window, cx);
5360
5361 let mouse_position = window.mouse_position();
5362 if !position_map.text_hitbox.is_hovered(window) {
5363 return;
5364 }
5365
5366 self.update_hovered_link(
5367 position_map.point_for_position(mouse_position),
5368 &position_map.snapshot,
5369 modifiers,
5370 window,
5371 cx,
5372 )
5373 }
5374
5375 fn update_selection_mode(
5376 &mut self,
5377 modifiers: &Modifiers,
5378 position_map: &PositionMap,
5379 window: &mut Window,
5380 cx: &mut Context<Self>,
5381 ) {
5382 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5383 return;
5384 }
5385
5386 let mouse_position = window.mouse_position();
5387 let point_for_position = position_map.point_for_position(mouse_position);
5388 let position = point_for_position.previous_valid;
5389
5390 self.select(
5391 SelectPhase::BeginColumnar {
5392 position,
5393 reset: false,
5394 goal_column: point_for_position.exact_unclipped.column(),
5395 },
5396 window,
5397 cx,
5398 );
5399 }
5400
5401 fn update_edit_prediction_preview(
5402 &mut self,
5403 modifiers: &Modifiers,
5404 window: &mut Window,
5405 cx: &mut Context<Self>,
5406 ) {
5407 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5408 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5409 return;
5410 };
5411
5412 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5413 if matches!(
5414 self.edit_prediction_preview,
5415 EditPredictionPreview::Inactive { .. }
5416 ) {
5417 self.edit_prediction_preview = EditPredictionPreview::Active {
5418 previous_scroll_position: None,
5419 since: Instant::now(),
5420 };
5421
5422 self.update_visible_inline_completion(window, cx);
5423 cx.notify();
5424 }
5425 } else if let EditPredictionPreview::Active {
5426 previous_scroll_position,
5427 since,
5428 } = self.edit_prediction_preview
5429 {
5430 if let (Some(previous_scroll_position), Some(position_map)) =
5431 (previous_scroll_position, self.last_position_map.as_ref())
5432 {
5433 self.set_scroll_position(
5434 previous_scroll_position
5435 .scroll_position(&position_map.snapshot.display_snapshot),
5436 window,
5437 cx,
5438 );
5439 }
5440
5441 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5442 released_too_fast: since.elapsed() < Duration::from_millis(200),
5443 };
5444 self.clear_row_highlights::<EditPredictionPreview>();
5445 self.update_visible_inline_completion(window, cx);
5446 cx.notify();
5447 }
5448 }
5449
5450 fn update_visible_inline_completion(
5451 &mut self,
5452 _window: &mut Window,
5453 cx: &mut Context<Self>,
5454 ) -> Option<()> {
5455 let selection = self.selections.newest_anchor();
5456 let cursor = selection.head();
5457 let multibuffer = self.buffer.read(cx).snapshot(cx);
5458 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5459 let excerpt_id = cursor.excerpt_id;
5460
5461 let show_in_menu = self.show_edit_predictions_in_menu();
5462 let completions_menu_has_precedence = !show_in_menu
5463 && (self.context_menu.borrow().is_some()
5464 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5465
5466 if completions_menu_has_precedence
5467 || !offset_selection.is_empty()
5468 || self
5469 .active_inline_completion
5470 .as_ref()
5471 .map_or(false, |completion| {
5472 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5473 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5474 !invalidation_range.contains(&offset_selection.head())
5475 })
5476 {
5477 self.discard_inline_completion(false, cx);
5478 return None;
5479 }
5480
5481 self.take_active_inline_completion(cx);
5482 let Some(provider) = self.edit_prediction_provider() else {
5483 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5484 return None;
5485 };
5486
5487 let (buffer, cursor_buffer_position) =
5488 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5489
5490 self.edit_prediction_settings =
5491 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5492
5493 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5494
5495 if self.edit_prediction_indent_conflict {
5496 let cursor_point = cursor.to_point(&multibuffer);
5497
5498 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5499
5500 if let Some((_, indent)) = indents.iter().next() {
5501 if indent.len == cursor_point.column {
5502 self.edit_prediction_indent_conflict = false;
5503 }
5504 }
5505 }
5506
5507 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5508 let edits = inline_completion
5509 .edits
5510 .into_iter()
5511 .flat_map(|(range, new_text)| {
5512 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5513 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5514 Some((start..end, new_text))
5515 })
5516 .collect::<Vec<_>>();
5517 if edits.is_empty() {
5518 return None;
5519 }
5520
5521 let first_edit_start = edits.first().unwrap().0.start;
5522 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5523 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5524
5525 let last_edit_end = edits.last().unwrap().0.end;
5526 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5527 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5528
5529 let cursor_row = cursor.to_point(&multibuffer).row;
5530
5531 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5532
5533 let mut inlay_ids = Vec::new();
5534 let invalidation_row_range;
5535 let move_invalidation_row_range = if cursor_row < edit_start_row {
5536 Some(cursor_row..edit_end_row)
5537 } else if cursor_row > edit_end_row {
5538 Some(edit_start_row..cursor_row)
5539 } else {
5540 None
5541 };
5542 let is_move =
5543 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5544 let completion = if is_move {
5545 invalidation_row_range =
5546 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5547 let target = first_edit_start;
5548 InlineCompletion::Move { target, snapshot }
5549 } else {
5550 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5551 && !self.inline_completions_hidden_for_vim_mode;
5552
5553 if show_completions_in_buffer {
5554 if edits
5555 .iter()
5556 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5557 {
5558 let mut inlays = Vec::new();
5559 for (range, new_text) in &edits {
5560 let inlay = Inlay::inline_completion(
5561 post_inc(&mut self.next_inlay_id),
5562 range.start,
5563 new_text.as_str(),
5564 );
5565 inlay_ids.push(inlay.id);
5566 inlays.push(inlay);
5567 }
5568
5569 self.splice_inlays(&[], inlays, cx);
5570 } else {
5571 let background_color = cx.theme().status().deleted_background;
5572 self.highlight_text::<InlineCompletionHighlight>(
5573 edits.iter().map(|(range, _)| range.clone()).collect(),
5574 HighlightStyle {
5575 background_color: Some(background_color),
5576 ..Default::default()
5577 },
5578 cx,
5579 );
5580 }
5581 }
5582
5583 invalidation_row_range = edit_start_row..edit_end_row;
5584
5585 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5586 if provider.show_tab_accept_marker() {
5587 EditDisplayMode::TabAccept
5588 } else {
5589 EditDisplayMode::Inline
5590 }
5591 } else {
5592 EditDisplayMode::DiffPopover
5593 };
5594
5595 InlineCompletion::Edit {
5596 edits,
5597 edit_preview: inline_completion.edit_preview,
5598 display_mode,
5599 snapshot,
5600 }
5601 };
5602
5603 let invalidation_range = multibuffer
5604 .anchor_before(Point::new(invalidation_row_range.start, 0))
5605 ..multibuffer.anchor_after(Point::new(
5606 invalidation_row_range.end,
5607 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5608 ));
5609
5610 self.stale_inline_completion_in_menu = None;
5611 self.active_inline_completion = Some(InlineCompletionState {
5612 inlay_ids,
5613 completion,
5614 completion_id: inline_completion.id,
5615 invalidation_range,
5616 });
5617
5618 cx.notify();
5619
5620 Some(())
5621 }
5622
5623 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5624 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5625 }
5626
5627 fn render_code_actions_indicator(
5628 &self,
5629 _style: &EditorStyle,
5630 row: DisplayRow,
5631 is_active: bool,
5632 cx: &mut Context<Self>,
5633 ) -> Option<IconButton> {
5634 if self.available_code_actions.is_some() {
5635 Some(
5636 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5637 .shape(ui::IconButtonShape::Square)
5638 .icon_size(IconSize::XSmall)
5639 .icon_color(Color::Muted)
5640 .toggle_state(is_active)
5641 .tooltip({
5642 let focus_handle = self.focus_handle.clone();
5643 move |window, cx| {
5644 Tooltip::for_action_in(
5645 "Toggle Code Actions",
5646 &ToggleCodeActions {
5647 deployed_from_indicator: None,
5648 },
5649 &focus_handle,
5650 window,
5651 cx,
5652 )
5653 }
5654 })
5655 .on_click(cx.listener(move |editor, _e, window, cx| {
5656 window.focus(&editor.focus_handle(cx));
5657 editor.toggle_code_actions(
5658 &ToggleCodeActions {
5659 deployed_from_indicator: Some(row),
5660 },
5661 window,
5662 cx,
5663 );
5664 })),
5665 )
5666 } else {
5667 None
5668 }
5669 }
5670
5671 fn clear_tasks(&mut self) {
5672 self.tasks.clear()
5673 }
5674
5675 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5676 if self.tasks.insert(key, value).is_some() {
5677 // This case should hopefully be rare, but just in case...
5678 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5679 }
5680 }
5681
5682 fn build_tasks_context(
5683 project: &Entity<Project>,
5684 buffer: &Entity<Buffer>,
5685 buffer_row: u32,
5686 tasks: &Arc<RunnableTasks>,
5687 cx: &mut Context<Self>,
5688 ) -> Task<Option<task::TaskContext>> {
5689 let position = Point::new(buffer_row, tasks.column);
5690 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5691 let location = Location {
5692 buffer: buffer.clone(),
5693 range: range_start..range_start,
5694 };
5695 // Fill in the environmental variables from the tree-sitter captures
5696 let mut captured_task_variables = TaskVariables::default();
5697 for (capture_name, value) in tasks.extra_variables.clone() {
5698 captured_task_variables.insert(
5699 task::VariableName::Custom(capture_name.into()),
5700 value.clone(),
5701 );
5702 }
5703 project.update(cx, |project, cx| {
5704 project.task_store().update(cx, |task_store, cx| {
5705 task_store.task_context_for_location(captured_task_variables, location, cx)
5706 })
5707 })
5708 }
5709
5710 pub fn spawn_nearest_task(
5711 &mut self,
5712 action: &SpawnNearestTask,
5713 window: &mut Window,
5714 cx: &mut Context<Self>,
5715 ) {
5716 let Some((workspace, _)) = self.workspace.clone() else {
5717 return;
5718 };
5719 let Some(project) = self.project.clone() else {
5720 return;
5721 };
5722
5723 // Try to find a closest, enclosing node using tree-sitter that has a
5724 // task
5725 let Some((buffer, buffer_row, tasks)) = self
5726 .find_enclosing_node_task(cx)
5727 // Or find the task that's closest in row-distance.
5728 .or_else(|| self.find_closest_task(cx))
5729 else {
5730 return;
5731 };
5732
5733 let reveal_strategy = action.reveal;
5734 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5735 cx.spawn_in(window, |_, mut cx| async move {
5736 let context = task_context.await?;
5737 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5738
5739 let resolved = resolved_task.resolved.as_mut()?;
5740 resolved.reveal = reveal_strategy;
5741
5742 workspace
5743 .update(&mut cx, |workspace, cx| {
5744 workspace::tasks::schedule_resolved_task(
5745 workspace,
5746 task_source_kind,
5747 resolved_task,
5748 false,
5749 cx,
5750 );
5751 })
5752 .ok()
5753 })
5754 .detach();
5755 }
5756
5757 fn find_closest_task(
5758 &mut self,
5759 cx: &mut Context<Self>,
5760 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5761 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5762
5763 let ((buffer_id, row), tasks) = self
5764 .tasks
5765 .iter()
5766 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5767
5768 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5769 let tasks = Arc::new(tasks.to_owned());
5770 Some((buffer, *row, tasks))
5771 }
5772
5773 fn find_enclosing_node_task(
5774 &mut self,
5775 cx: &mut Context<Self>,
5776 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5777 let snapshot = self.buffer.read(cx).snapshot(cx);
5778 let offset = self.selections.newest::<usize>(cx).head();
5779 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5780 let buffer_id = excerpt.buffer().remote_id();
5781
5782 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5783 let mut cursor = layer.node().walk();
5784
5785 while cursor.goto_first_child_for_byte(offset).is_some() {
5786 if cursor.node().end_byte() == offset {
5787 cursor.goto_next_sibling();
5788 }
5789 }
5790
5791 // Ascend to the smallest ancestor that contains the range and has a task.
5792 loop {
5793 let node = cursor.node();
5794 let node_range = node.byte_range();
5795 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5796
5797 // Check if this node contains our offset
5798 if node_range.start <= offset && node_range.end >= offset {
5799 // If it contains offset, check for task
5800 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5801 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5802 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5803 }
5804 }
5805
5806 if !cursor.goto_parent() {
5807 break;
5808 }
5809 }
5810 None
5811 }
5812
5813 fn render_run_indicator(
5814 &self,
5815 _style: &EditorStyle,
5816 is_active: bool,
5817 row: DisplayRow,
5818 cx: &mut Context<Self>,
5819 ) -> IconButton {
5820 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5821 .shape(ui::IconButtonShape::Square)
5822 .icon_size(IconSize::XSmall)
5823 .icon_color(Color::Muted)
5824 .toggle_state(is_active)
5825 .on_click(cx.listener(move |editor, _e, window, cx| {
5826 window.focus(&editor.focus_handle(cx));
5827 editor.toggle_code_actions(
5828 &ToggleCodeActions {
5829 deployed_from_indicator: Some(row),
5830 },
5831 window,
5832 cx,
5833 );
5834 }))
5835 }
5836
5837 pub fn context_menu_visible(&self) -> bool {
5838 !self.edit_prediction_preview_is_active()
5839 && self
5840 .context_menu
5841 .borrow()
5842 .as_ref()
5843 .map_or(false, |menu| menu.visible())
5844 }
5845
5846 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5847 self.context_menu
5848 .borrow()
5849 .as_ref()
5850 .map(|menu| menu.origin())
5851 }
5852
5853 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5854 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5855
5856 #[allow(clippy::too_many_arguments)]
5857 fn render_edit_prediction_popover(
5858 &mut self,
5859 text_bounds: &Bounds<Pixels>,
5860 content_origin: gpui::Point<Pixels>,
5861 editor_snapshot: &EditorSnapshot,
5862 visible_row_range: Range<DisplayRow>,
5863 scroll_top: f32,
5864 scroll_bottom: f32,
5865 line_layouts: &[LineWithInvisibles],
5866 line_height: Pixels,
5867 scroll_pixel_position: gpui::Point<Pixels>,
5868 newest_selection_head: Option<DisplayPoint>,
5869 editor_width: Pixels,
5870 style: &EditorStyle,
5871 window: &mut Window,
5872 cx: &mut App,
5873 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5874 let active_inline_completion = self.active_inline_completion.as_ref()?;
5875
5876 if self.edit_prediction_visible_in_cursor_popover(true) {
5877 return None;
5878 }
5879
5880 match &active_inline_completion.completion {
5881 InlineCompletion::Move { target, .. } => {
5882 let target_display_point = target.to_display_point(editor_snapshot);
5883
5884 if self.edit_prediction_requires_modifier() {
5885 if !self.edit_prediction_preview_is_active() {
5886 return None;
5887 }
5888
5889 self.render_edit_prediction_modifier_jump_popover(
5890 text_bounds,
5891 content_origin,
5892 visible_row_range,
5893 line_layouts,
5894 line_height,
5895 scroll_pixel_position,
5896 newest_selection_head,
5897 target_display_point,
5898 window,
5899 cx,
5900 )
5901 } else {
5902 self.render_edit_prediction_eager_jump_popover(
5903 text_bounds,
5904 content_origin,
5905 editor_snapshot,
5906 visible_row_range,
5907 scroll_top,
5908 scroll_bottom,
5909 line_height,
5910 scroll_pixel_position,
5911 target_display_point,
5912 editor_width,
5913 window,
5914 cx,
5915 )
5916 }
5917 }
5918 InlineCompletion::Edit {
5919 display_mode: EditDisplayMode::Inline,
5920 ..
5921 } => None,
5922 InlineCompletion::Edit {
5923 display_mode: EditDisplayMode::TabAccept,
5924 edits,
5925 ..
5926 } => {
5927 let range = &edits.first()?.0;
5928 let target_display_point = range.end.to_display_point(editor_snapshot);
5929
5930 self.render_edit_prediction_end_of_line_popover(
5931 "Accept",
5932 editor_snapshot,
5933 visible_row_range,
5934 target_display_point,
5935 line_height,
5936 scroll_pixel_position,
5937 content_origin,
5938 editor_width,
5939 window,
5940 cx,
5941 )
5942 }
5943 InlineCompletion::Edit {
5944 edits,
5945 edit_preview,
5946 display_mode: EditDisplayMode::DiffPopover,
5947 snapshot,
5948 } => self.render_edit_prediction_diff_popover(
5949 text_bounds,
5950 content_origin,
5951 editor_snapshot,
5952 visible_row_range,
5953 line_layouts,
5954 line_height,
5955 scroll_pixel_position,
5956 newest_selection_head,
5957 editor_width,
5958 style,
5959 edits,
5960 edit_preview,
5961 snapshot,
5962 window,
5963 cx,
5964 ),
5965 }
5966 }
5967
5968 #[allow(clippy::too_many_arguments)]
5969 fn render_edit_prediction_modifier_jump_popover(
5970 &mut self,
5971 text_bounds: &Bounds<Pixels>,
5972 content_origin: gpui::Point<Pixels>,
5973 visible_row_range: Range<DisplayRow>,
5974 line_layouts: &[LineWithInvisibles],
5975 line_height: Pixels,
5976 scroll_pixel_position: gpui::Point<Pixels>,
5977 newest_selection_head: Option<DisplayPoint>,
5978 target_display_point: DisplayPoint,
5979 window: &mut Window,
5980 cx: &mut App,
5981 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5982 let scrolled_content_origin =
5983 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
5984
5985 const SCROLL_PADDING_Y: Pixels = px(12.);
5986
5987 if target_display_point.row() < visible_row_range.start {
5988 return self.render_edit_prediction_scroll_popover(
5989 |_| SCROLL_PADDING_Y,
5990 IconName::ArrowUp,
5991 visible_row_range,
5992 line_layouts,
5993 newest_selection_head,
5994 scrolled_content_origin,
5995 window,
5996 cx,
5997 );
5998 } else if target_display_point.row() >= visible_row_range.end {
5999 return self.render_edit_prediction_scroll_popover(
6000 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6001 IconName::ArrowDown,
6002 visible_row_range,
6003 line_layouts,
6004 newest_selection_head,
6005 scrolled_content_origin,
6006 window,
6007 cx,
6008 );
6009 }
6010
6011 const POLE_WIDTH: Pixels = px(2.);
6012
6013 let line_layout =
6014 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6015 let target_column = target_display_point.column() as usize;
6016
6017 let target_x = line_layout.x_for_index(target_column);
6018 let target_y =
6019 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6020
6021 let flag_on_right = target_x < text_bounds.size.width / 2.;
6022
6023 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6024 border_color.l += 0.001;
6025
6026 let mut element = v_flex()
6027 .items_end()
6028 .when(flag_on_right, |el| el.items_start())
6029 .child(if flag_on_right {
6030 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6031 .rounded_bl(px(0.))
6032 .rounded_tl(px(0.))
6033 .border_l_2()
6034 .border_color(border_color)
6035 } else {
6036 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6037 .rounded_br(px(0.))
6038 .rounded_tr(px(0.))
6039 .border_r_2()
6040 .border_color(border_color)
6041 })
6042 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6043 .into_any();
6044
6045 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6046
6047 let mut origin = scrolled_content_origin + point(target_x, target_y)
6048 - point(
6049 if flag_on_right {
6050 POLE_WIDTH
6051 } else {
6052 size.width - POLE_WIDTH
6053 },
6054 size.height - line_height,
6055 );
6056
6057 origin.x = origin.x.max(content_origin.x);
6058
6059 element.prepaint_at(origin, window, cx);
6060
6061 Some((element, origin))
6062 }
6063
6064 #[allow(clippy::too_many_arguments)]
6065 fn render_edit_prediction_scroll_popover(
6066 &mut self,
6067 to_y: impl Fn(Size<Pixels>) -> Pixels,
6068 scroll_icon: IconName,
6069 visible_row_range: Range<DisplayRow>,
6070 line_layouts: &[LineWithInvisibles],
6071 newest_selection_head: Option<DisplayPoint>,
6072 scrolled_content_origin: gpui::Point<Pixels>,
6073 window: &mut Window,
6074 cx: &mut App,
6075 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6076 let mut element = self
6077 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6078 .into_any();
6079
6080 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6081
6082 let cursor = newest_selection_head?;
6083 let cursor_row_layout =
6084 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6085 let cursor_column = cursor.column() as usize;
6086
6087 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6088
6089 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6090
6091 element.prepaint_at(origin, window, cx);
6092 Some((element, origin))
6093 }
6094
6095 #[allow(clippy::too_many_arguments)]
6096 fn render_edit_prediction_eager_jump_popover(
6097 &mut self,
6098 text_bounds: &Bounds<Pixels>,
6099 content_origin: gpui::Point<Pixels>,
6100 editor_snapshot: &EditorSnapshot,
6101 visible_row_range: Range<DisplayRow>,
6102 scroll_top: f32,
6103 scroll_bottom: f32,
6104 line_height: Pixels,
6105 scroll_pixel_position: gpui::Point<Pixels>,
6106 target_display_point: DisplayPoint,
6107 editor_width: Pixels,
6108 window: &mut Window,
6109 cx: &mut App,
6110 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6111 if target_display_point.row().as_f32() < scroll_top {
6112 let mut element = self
6113 .render_edit_prediction_line_popover(
6114 "Jump to Edit",
6115 Some(IconName::ArrowUp),
6116 window,
6117 cx,
6118 )?
6119 .into_any();
6120
6121 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6122 let offset = point(
6123 (text_bounds.size.width - size.width) / 2.,
6124 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6125 );
6126
6127 let origin = text_bounds.origin + offset;
6128 element.prepaint_at(origin, window, cx);
6129 Some((element, origin))
6130 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6131 let mut element = self
6132 .render_edit_prediction_line_popover(
6133 "Jump to Edit",
6134 Some(IconName::ArrowDown),
6135 window,
6136 cx,
6137 )?
6138 .into_any();
6139
6140 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6141 let offset = point(
6142 (text_bounds.size.width - size.width) / 2.,
6143 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6144 );
6145
6146 let origin = text_bounds.origin + offset;
6147 element.prepaint_at(origin, window, cx);
6148 Some((element, origin))
6149 } else {
6150 self.render_edit_prediction_end_of_line_popover(
6151 "Jump to Edit",
6152 editor_snapshot,
6153 visible_row_range,
6154 target_display_point,
6155 line_height,
6156 scroll_pixel_position,
6157 content_origin,
6158 editor_width,
6159 window,
6160 cx,
6161 )
6162 }
6163 }
6164
6165 #[allow(clippy::too_many_arguments)]
6166 fn render_edit_prediction_end_of_line_popover(
6167 self: &mut Editor,
6168 label: &'static str,
6169 editor_snapshot: &EditorSnapshot,
6170 visible_row_range: Range<DisplayRow>,
6171 target_display_point: DisplayPoint,
6172 line_height: Pixels,
6173 scroll_pixel_position: gpui::Point<Pixels>,
6174 content_origin: gpui::Point<Pixels>,
6175 editor_width: Pixels,
6176 window: &mut Window,
6177 cx: &mut App,
6178 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6179 let target_line_end = DisplayPoint::new(
6180 target_display_point.row(),
6181 editor_snapshot.line_len(target_display_point.row()),
6182 );
6183
6184 let mut element = self
6185 .render_edit_prediction_line_popover(label, None, window, cx)?
6186 .into_any();
6187
6188 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6189
6190 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6191
6192 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6193 let mut origin = start_point
6194 + line_origin
6195 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6196 origin.x = origin.x.max(content_origin.x);
6197
6198 let max_x = content_origin.x + editor_width - size.width;
6199
6200 if origin.x > max_x {
6201 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6202
6203 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6204 origin.y += offset;
6205 IconName::ArrowUp
6206 } else {
6207 origin.y -= offset;
6208 IconName::ArrowDown
6209 };
6210
6211 element = self
6212 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6213 .into_any();
6214
6215 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6216
6217 origin.x = content_origin.x + editor_width - size.width - px(2.);
6218 }
6219
6220 element.prepaint_at(origin, window, cx);
6221 Some((element, origin))
6222 }
6223
6224 #[allow(clippy::too_many_arguments)]
6225 fn render_edit_prediction_diff_popover(
6226 self: &Editor,
6227 text_bounds: &Bounds<Pixels>,
6228 content_origin: gpui::Point<Pixels>,
6229 editor_snapshot: &EditorSnapshot,
6230 visible_row_range: Range<DisplayRow>,
6231 line_layouts: &[LineWithInvisibles],
6232 line_height: Pixels,
6233 scroll_pixel_position: gpui::Point<Pixels>,
6234 newest_selection_head: Option<DisplayPoint>,
6235 editor_width: Pixels,
6236 style: &EditorStyle,
6237 edits: &Vec<(Range<Anchor>, String)>,
6238 edit_preview: &Option<language::EditPreview>,
6239 snapshot: &language::BufferSnapshot,
6240 window: &mut Window,
6241 cx: &mut App,
6242 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6243 let edit_start = edits
6244 .first()
6245 .unwrap()
6246 .0
6247 .start
6248 .to_display_point(editor_snapshot);
6249 let edit_end = edits
6250 .last()
6251 .unwrap()
6252 .0
6253 .end
6254 .to_display_point(editor_snapshot);
6255
6256 let is_visible = visible_row_range.contains(&edit_start.row())
6257 || visible_row_range.contains(&edit_end.row());
6258 if !is_visible {
6259 return None;
6260 }
6261
6262 let highlighted_edits =
6263 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6264
6265 let styled_text = highlighted_edits.to_styled_text(&style.text);
6266 let line_count = highlighted_edits.text.lines().count();
6267
6268 const BORDER_WIDTH: Pixels = px(1.);
6269
6270 let mut element = h_flex()
6271 .items_start()
6272 .child(
6273 h_flex()
6274 .bg(cx.theme().colors().editor_background)
6275 .border(BORDER_WIDTH)
6276 .shadow_sm()
6277 .border_color(cx.theme().colors().border)
6278 .rounded_l_lg()
6279 .when(line_count > 1, |el| el.rounded_br_lg())
6280 .pr_1()
6281 .child(styled_text),
6282 )
6283 .child(
6284 h_flex()
6285 .h(line_height + BORDER_WIDTH * px(2.))
6286 .px_1p5()
6287 .gap_1()
6288 // Workaround: For some reason, there's a gap if we don't do this
6289 .ml(-BORDER_WIDTH)
6290 .shadow(smallvec![gpui::BoxShadow {
6291 color: gpui::black().opacity(0.05),
6292 offset: point(px(1.), px(1.)),
6293 blur_radius: px(2.),
6294 spread_radius: px(0.),
6295 }])
6296 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6297 .border(BORDER_WIDTH)
6298 .border_color(cx.theme().colors().border)
6299 .rounded_r_lg()
6300 .children(self.render_edit_prediction_accept_keybind(window, cx)),
6301 )
6302 .into_any();
6303
6304 let longest_row =
6305 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6306 let longest_line_width = if visible_row_range.contains(&longest_row) {
6307 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6308 } else {
6309 layout_line(
6310 longest_row,
6311 editor_snapshot,
6312 style,
6313 editor_width,
6314 |_| false,
6315 window,
6316 cx,
6317 )
6318 .width
6319 };
6320
6321 let viewport_bounds =
6322 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6323 right: -EditorElement::SCROLLBAR_WIDTH,
6324 ..Default::default()
6325 });
6326
6327 let x_after_longest =
6328 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6329 - scroll_pixel_position.x;
6330
6331 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6332
6333 // Fully visible if it can be displayed within the window (allow overlapping other
6334 // panes). However, this is only allowed if the popover starts within text_bounds.
6335 let can_position_to_the_right = x_after_longest < text_bounds.right()
6336 && x_after_longest + element_bounds.width < viewport_bounds.right();
6337
6338 let mut origin = if can_position_to_the_right {
6339 point(
6340 x_after_longest,
6341 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6342 - scroll_pixel_position.y,
6343 )
6344 } else {
6345 let cursor_row = newest_selection_head.map(|head| head.row());
6346 let above_edit = edit_start
6347 .row()
6348 .0
6349 .checked_sub(line_count as u32)
6350 .map(DisplayRow);
6351 let below_edit = Some(edit_end.row() + 1);
6352 let above_cursor =
6353 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6354 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6355
6356 // Place the edit popover adjacent to the edit if there is a location
6357 // available that is onscreen and does not obscure the cursor. Otherwise,
6358 // place it adjacent to the cursor.
6359 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6360 .into_iter()
6361 .flatten()
6362 .find(|&start_row| {
6363 let end_row = start_row + line_count as u32;
6364 visible_row_range.contains(&start_row)
6365 && visible_row_range.contains(&end_row)
6366 && cursor_row.map_or(true, |cursor_row| {
6367 !((start_row..end_row).contains(&cursor_row))
6368 })
6369 })?;
6370
6371 content_origin
6372 + point(
6373 -scroll_pixel_position.x,
6374 row_target.as_f32() * line_height - scroll_pixel_position.y,
6375 )
6376 };
6377
6378 origin.x -= BORDER_WIDTH;
6379
6380 window.defer_draw(element, origin, 1);
6381
6382 // Do not return an element, since it will already be drawn due to defer_draw.
6383 None
6384 }
6385
6386 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6387 px(30.)
6388 }
6389
6390 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6391 if self.read_only(cx) {
6392 cx.theme().players().read_only()
6393 } else {
6394 self.style.as_ref().unwrap().local_player
6395 }
6396 }
6397
6398 fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
6399 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6400 let accept_keystroke = accept_binding.keystroke()?;
6401
6402 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6403
6404 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6405 Color::Accent
6406 } else {
6407 Color::Muted
6408 };
6409
6410 h_flex()
6411 .px_0p5()
6412 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6413 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6414 .text_size(TextSize::XSmall.rems(cx))
6415 .child(h_flex().children(ui::render_modifiers(
6416 &accept_keystroke.modifiers,
6417 PlatformStyle::platform(),
6418 Some(modifiers_color),
6419 Some(IconSize::XSmall.rems().into()),
6420 true,
6421 )))
6422 .when(is_platform_style_mac, |parent| {
6423 parent.child(accept_keystroke.key.clone())
6424 })
6425 .when(!is_platform_style_mac, |parent| {
6426 parent.child(
6427 Key::new(
6428 util::capitalize(&accept_keystroke.key),
6429 Some(Color::Default),
6430 )
6431 .size(Some(IconSize::XSmall.rems().into())),
6432 )
6433 })
6434 .into()
6435 }
6436
6437 fn render_edit_prediction_line_popover(
6438 &self,
6439 label: impl Into<SharedString>,
6440 icon: Option<IconName>,
6441 window: &mut Window,
6442 cx: &App,
6443 ) -> Option<Div> {
6444 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6445
6446 let result = h_flex()
6447 .py_0p5()
6448 .pl_1()
6449 .pr(padding_right)
6450 .gap_1()
6451 .rounded(px(6.))
6452 .border_1()
6453 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6454 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6455 .shadow_sm()
6456 .children(self.render_edit_prediction_accept_keybind(window, cx))
6457 .child(Label::new(label).size(LabelSize::Small))
6458 .when_some(icon, |element, icon| {
6459 element.child(
6460 div()
6461 .mt(px(1.5))
6462 .child(Icon::new(icon).size(IconSize::Small)),
6463 )
6464 });
6465
6466 Some(result)
6467 }
6468
6469 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6470 let accent_color = cx.theme().colors().text_accent;
6471 let editor_bg_color = cx.theme().colors().editor_background;
6472 editor_bg_color.blend(accent_color.opacity(0.1))
6473 }
6474
6475 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6476 let accent_color = cx.theme().colors().text_accent;
6477 let editor_bg_color = cx.theme().colors().editor_background;
6478 editor_bg_color.blend(accent_color.opacity(0.6))
6479 }
6480
6481 #[allow(clippy::too_many_arguments)]
6482 fn render_edit_prediction_cursor_popover(
6483 &self,
6484 min_width: Pixels,
6485 max_width: Pixels,
6486 cursor_point: Point,
6487 style: &EditorStyle,
6488 accept_keystroke: Option<&gpui::Keystroke>,
6489 _window: &Window,
6490 cx: &mut Context<Editor>,
6491 ) -> Option<AnyElement> {
6492 let provider = self.edit_prediction_provider.as_ref()?;
6493
6494 if provider.provider.needs_terms_acceptance(cx) {
6495 return Some(
6496 h_flex()
6497 .min_w(min_width)
6498 .flex_1()
6499 .px_2()
6500 .py_1()
6501 .gap_3()
6502 .elevation_2(cx)
6503 .hover(|style| style.bg(cx.theme().colors().element_hover))
6504 .id("accept-terms")
6505 .cursor_pointer()
6506 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6507 .on_click(cx.listener(|this, _event, window, cx| {
6508 cx.stop_propagation();
6509 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6510 window.dispatch_action(
6511 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6512 cx,
6513 );
6514 }))
6515 .child(
6516 h_flex()
6517 .flex_1()
6518 .gap_2()
6519 .child(Icon::new(IconName::ZedPredict))
6520 .child(Label::new("Accept Terms of Service"))
6521 .child(div().w_full())
6522 .child(
6523 Icon::new(IconName::ArrowUpRight)
6524 .color(Color::Muted)
6525 .size(IconSize::Small),
6526 )
6527 .into_any_element(),
6528 )
6529 .into_any(),
6530 );
6531 }
6532
6533 let is_refreshing = provider.provider.is_refreshing(cx);
6534
6535 fn pending_completion_container() -> Div {
6536 h_flex()
6537 .h_full()
6538 .flex_1()
6539 .gap_2()
6540 .child(Icon::new(IconName::ZedPredict))
6541 }
6542
6543 let completion = match &self.active_inline_completion {
6544 Some(prediction) => {
6545 if !self.has_visible_completions_menu() {
6546 const RADIUS: Pixels = px(6.);
6547 const BORDER_WIDTH: Pixels = px(1.);
6548
6549 return Some(
6550 h_flex()
6551 .elevation_2(cx)
6552 .border(BORDER_WIDTH)
6553 .border_color(cx.theme().colors().border)
6554 .rounded(RADIUS)
6555 .rounded_tl(px(0.))
6556 .overflow_hidden()
6557 .child(div().px_1p5().child(match &prediction.completion {
6558 InlineCompletion::Move { target, snapshot } => {
6559 use text::ToPoint as _;
6560 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6561 {
6562 Icon::new(IconName::ZedPredictDown)
6563 } else {
6564 Icon::new(IconName::ZedPredictUp)
6565 }
6566 }
6567 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6568 }))
6569 .child(
6570 h_flex()
6571 .gap_1()
6572 .py_1()
6573 .px_2()
6574 .rounded_r(RADIUS - BORDER_WIDTH)
6575 .border_l_1()
6576 .border_color(cx.theme().colors().border)
6577 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6578 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6579 el.child(
6580 Label::new("Hold")
6581 .size(LabelSize::Small)
6582 .line_height_style(LineHeightStyle::UiLabel),
6583 )
6584 })
6585 .child(h_flex().children(ui::render_modifiers(
6586 &accept_keystroke?.modifiers,
6587 PlatformStyle::platform(),
6588 Some(Color::Default),
6589 Some(IconSize::XSmall.rems().into()),
6590 false,
6591 ))),
6592 )
6593 .into_any(),
6594 );
6595 }
6596
6597 self.render_edit_prediction_cursor_popover_preview(
6598 prediction,
6599 cursor_point,
6600 style,
6601 cx,
6602 )?
6603 }
6604
6605 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6606 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6607 stale_completion,
6608 cursor_point,
6609 style,
6610 cx,
6611 )?,
6612
6613 None => {
6614 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6615 }
6616 },
6617
6618 None => pending_completion_container().child(Label::new("No Prediction")),
6619 };
6620
6621 let completion = if is_refreshing {
6622 completion
6623 .with_animation(
6624 "loading-completion",
6625 Animation::new(Duration::from_secs(2))
6626 .repeat()
6627 .with_easing(pulsating_between(0.4, 0.8)),
6628 |label, delta| label.opacity(delta),
6629 )
6630 .into_any_element()
6631 } else {
6632 completion.into_any_element()
6633 };
6634
6635 let has_completion = self.active_inline_completion.is_some();
6636
6637 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6638 Some(
6639 h_flex()
6640 .min_w(min_width)
6641 .max_w(max_width)
6642 .flex_1()
6643 .elevation_2(cx)
6644 .border_color(cx.theme().colors().border)
6645 .child(
6646 div()
6647 .flex_1()
6648 .py_1()
6649 .px_2()
6650 .overflow_hidden()
6651 .child(completion),
6652 )
6653 .when_some(accept_keystroke, |el, accept_keystroke| {
6654 if !accept_keystroke.modifiers.modified() {
6655 return el;
6656 }
6657
6658 el.child(
6659 h_flex()
6660 .h_full()
6661 .border_l_1()
6662 .rounded_r_lg()
6663 .border_color(cx.theme().colors().border)
6664 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6665 .gap_1()
6666 .py_1()
6667 .px_2()
6668 .child(
6669 h_flex()
6670 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6671 .when(is_platform_style_mac, |parent| parent.gap_1())
6672 .child(h_flex().children(ui::render_modifiers(
6673 &accept_keystroke.modifiers,
6674 PlatformStyle::platform(),
6675 Some(if !has_completion {
6676 Color::Muted
6677 } else {
6678 Color::Default
6679 }),
6680 None,
6681 false,
6682 ))),
6683 )
6684 .child(Label::new("Preview").into_any_element())
6685 .opacity(if has_completion { 1.0 } else { 0.4 }),
6686 )
6687 })
6688 .into_any(),
6689 )
6690 }
6691
6692 fn render_edit_prediction_cursor_popover_preview(
6693 &self,
6694 completion: &InlineCompletionState,
6695 cursor_point: Point,
6696 style: &EditorStyle,
6697 cx: &mut Context<Editor>,
6698 ) -> Option<Div> {
6699 use text::ToPoint as _;
6700
6701 fn render_relative_row_jump(
6702 prefix: impl Into<String>,
6703 current_row: u32,
6704 target_row: u32,
6705 ) -> Div {
6706 let (row_diff, arrow) = if target_row < current_row {
6707 (current_row - target_row, IconName::ArrowUp)
6708 } else {
6709 (target_row - current_row, IconName::ArrowDown)
6710 };
6711
6712 h_flex()
6713 .child(
6714 Label::new(format!("{}{}", prefix.into(), row_diff))
6715 .color(Color::Muted)
6716 .size(LabelSize::Small),
6717 )
6718 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6719 }
6720
6721 match &completion.completion {
6722 InlineCompletion::Move {
6723 target, snapshot, ..
6724 } => Some(
6725 h_flex()
6726 .px_2()
6727 .gap_2()
6728 .flex_1()
6729 .child(
6730 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6731 Icon::new(IconName::ZedPredictDown)
6732 } else {
6733 Icon::new(IconName::ZedPredictUp)
6734 },
6735 )
6736 .child(Label::new("Jump to Edit")),
6737 ),
6738
6739 InlineCompletion::Edit {
6740 edits,
6741 edit_preview,
6742 snapshot,
6743 display_mode: _,
6744 } => {
6745 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6746
6747 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6748 &snapshot,
6749 &edits,
6750 edit_preview.as_ref()?,
6751 true,
6752 cx,
6753 )
6754 .first_line_preview();
6755
6756 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6757 .with_highlights(&style.text, highlighted_edits.highlights);
6758
6759 let preview = h_flex()
6760 .gap_1()
6761 .min_w_16()
6762 .child(styled_text)
6763 .when(has_more_lines, |parent| parent.child("…"));
6764
6765 let left = if first_edit_row != cursor_point.row {
6766 render_relative_row_jump("", cursor_point.row, first_edit_row)
6767 .into_any_element()
6768 } else {
6769 Icon::new(IconName::ZedPredict).into_any_element()
6770 };
6771
6772 Some(
6773 h_flex()
6774 .h_full()
6775 .flex_1()
6776 .gap_2()
6777 .pr_1()
6778 .overflow_x_hidden()
6779 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6780 .child(left)
6781 .child(preview),
6782 )
6783 }
6784 }
6785 }
6786
6787 fn render_context_menu(
6788 &self,
6789 style: &EditorStyle,
6790 max_height_in_lines: u32,
6791 y_flipped: bool,
6792 window: &mut Window,
6793 cx: &mut Context<Editor>,
6794 ) -> Option<AnyElement> {
6795 let menu = self.context_menu.borrow();
6796 let menu = menu.as_ref()?;
6797 if !menu.visible() {
6798 return None;
6799 };
6800 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6801 }
6802
6803 fn render_context_menu_aside(
6804 &mut self,
6805 max_size: Size<Pixels>,
6806 window: &mut Window,
6807 cx: &mut Context<Editor>,
6808 ) -> Option<AnyElement> {
6809 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6810 if menu.visible() {
6811 menu.render_aside(self, max_size, window, cx)
6812 } else {
6813 None
6814 }
6815 })
6816 }
6817
6818 fn hide_context_menu(
6819 &mut self,
6820 window: &mut Window,
6821 cx: &mut Context<Self>,
6822 ) -> Option<CodeContextMenu> {
6823 cx.notify();
6824 self.completion_tasks.clear();
6825 let context_menu = self.context_menu.borrow_mut().take();
6826 self.stale_inline_completion_in_menu.take();
6827 self.update_visible_inline_completion(window, cx);
6828 context_menu
6829 }
6830
6831 fn show_snippet_choices(
6832 &mut self,
6833 choices: &Vec<String>,
6834 selection: Range<Anchor>,
6835 cx: &mut Context<Self>,
6836 ) {
6837 if selection.start.buffer_id.is_none() {
6838 return;
6839 }
6840 let buffer_id = selection.start.buffer_id.unwrap();
6841 let buffer = self.buffer().read(cx).buffer(buffer_id);
6842 let id = post_inc(&mut self.next_completion_id);
6843
6844 if let Some(buffer) = buffer {
6845 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6846 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6847 ));
6848 }
6849 }
6850
6851 pub fn insert_snippet(
6852 &mut self,
6853 insertion_ranges: &[Range<usize>],
6854 snippet: Snippet,
6855 window: &mut Window,
6856 cx: &mut Context<Self>,
6857 ) -> Result<()> {
6858 struct Tabstop<T> {
6859 is_end_tabstop: bool,
6860 ranges: Vec<Range<T>>,
6861 choices: Option<Vec<String>>,
6862 }
6863
6864 let tabstops = self.buffer.update(cx, |buffer, cx| {
6865 let snippet_text: Arc<str> = snippet.text.clone().into();
6866 buffer.edit(
6867 insertion_ranges
6868 .iter()
6869 .cloned()
6870 .map(|range| (range, snippet_text.clone())),
6871 Some(AutoindentMode::EachLine),
6872 cx,
6873 );
6874
6875 let snapshot = &*buffer.read(cx);
6876 let snippet = &snippet;
6877 snippet
6878 .tabstops
6879 .iter()
6880 .map(|tabstop| {
6881 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
6882 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
6883 });
6884 let mut tabstop_ranges = tabstop
6885 .ranges
6886 .iter()
6887 .flat_map(|tabstop_range| {
6888 let mut delta = 0_isize;
6889 insertion_ranges.iter().map(move |insertion_range| {
6890 let insertion_start = insertion_range.start as isize + delta;
6891 delta +=
6892 snippet.text.len() as isize - insertion_range.len() as isize;
6893
6894 let start = ((insertion_start + tabstop_range.start) as usize)
6895 .min(snapshot.len());
6896 let end = ((insertion_start + tabstop_range.end) as usize)
6897 .min(snapshot.len());
6898 snapshot.anchor_before(start)..snapshot.anchor_after(end)
6899 })
6900 })
6901 .collect::<Vec<_>>();
6902 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
6903
6904 Tabstop {
6905 is_end_tabstop,
6906 ranges: tabstop_ranges,
6907 choices: tabstop.choices.clone(),
6908 }
6909 })
6910 .collect::<Vec<_>>()
6911 });
6912 if let Some(tabstop) = tabstops.first() {
6913 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6914 s.select_ranges(tabstop.ranges.iter().cloned());
6915 });
6916
6917 if let Some(choices) = &tabstop.choices {
6918 if let Some(selection) = tabstop.ranges.first() {
6919 self.show_snippet_choices(choices, selection.clone(), cx)
6920 }
6921 }
6922
6923 // If we're already at the last tabstop and it's at the end of the snippet,
6924 // we're done, we don't need to keep the state around.
6925 if !tabstop.is_end_tabstop {
6926 let choices = tabstops
6927 .iter()
6928 .map(|tabstop| tabstop.choices.clone())
6929 .collect();
6930
6931 let ranges = tabstops
6932 .into_iter()
6933 .map(|tabstop| tabstop.ranges)
6934 .collect::<Vec<_>>();
6935
6936 self.snippet_stack.push(SnippetState {
6937 active_index: 0,
6938 ranges,
6939 choices,
6940 });
6941 }
6942
6943 // Check whether the just-entered snippet ends with an auto-closable bracket.
6944 if self.autoclose_regions.is_empty() {
6945 let snapshot = self.buffer.read(cx).snapshot(cx);
6946 for selection in &mut self.selections.all::<Point>(cx) {
6947 let selection_head = selection.head();
6948 let Some(scope) = snapshot.language_scope_at(selection_head) else {
6949 continue;
6950 };
6951
6952 let mut bracket_pair = None;
6953 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
6954 let prev_chars = snapshot
6955 .reversed_chars_at(selection_head)
6956 .collect::<String>();
6957 for (pair, enabled) in scope.brackets() {
6958 if enabled
6959 && pair.close
6960 && prev_chars.starts_with(pair.start.as_str())
6961 && next_chars.starts_with(pair.end.as_str())
6962 {
6963 bracket_pair = Some(pair.clone());
6964 break;
6965 }
6966 }
6967 if let Some(pair) = bracket_pair {
6968 let start = snapshot.anchor_after(selection_head);
6969 let end = snapshot.anchor_after(selection_head);
6970 self.autoclose_regions.push(AutocloseRegion {
6971 selection_id: selection.id,
6972 range: start..end,
6973 pair,
6974 });
6975 }
6976 }
6977 }
6978 }
6979 Ok(())
6980 }
6981
6982 pub fn move_to_next_snippet_tabstop(
6983 &mut self,
6984 window: &mut Window,
6985 cx: &mut Context<Self>,
6986 ) -> bool {
6987 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6988 }
6989
6990 pub fn move_to_prev_snippet_tabstop(
6991 &mut self,
6992 window: &mut Window,
6993 cx: &mut Context<Self>,
6994 ) -> bool {
6995 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6996 }
6997
6998 pub fn move_to_snippet_tabstop(
6999 &mut self,
7000 bias: Bias,
7001 window: &mut Window,
7002 cx: &mut Context<Self>,
7003 ) -> bool {
7004 if let Some(mut snippet) = self.snippet_stack.pop() {
7005 match bias {
7006 Bias::Left => {
7007 if snippet.active_index > 0 {
7008 snippet.active_index -= 1;
7009 } else {
7010 self.snippet_stack.push(snippet);
7011 return false;
7012 }
7013 }
7014 Bias::Right => {
7015 if snippet.active_index + 1 < snippet.ranges.len() {
7016 snippet.active_index += 1;
7017 } else {
7018 self.snippet_stack.push(snippet);
7019 return false;
7020 }
7021 }
7022 }
7023 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7024 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7025 s.select_anchor_ranges(current_ranges.iter().cloned())
7026 });
7027
7028 if let Some(choices) = &snippet.choices[snippet.active_index] {
7029 if let Some(selection) = current_ranges.first() {
7030 self.show_snippet_choices(&choices, selection.clone(), cx);
7031 }
7032 }
7033
7034 // If snippet state is not at the last tabstop, push it back on the stack
7035 if snippet.active_index + 1 < snippet.ranges.len() {
7036 self.snippet_stack.push(snippet);
7037 }
7038 return true;
7039 }
7040 }
7041
7042 false
7043 }
7044
7045 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7046 self.transact(window, cx, |this, window, cx| {
7047 this.select_all(&SelectAll, window, cx);
7048 this.insert("", window, cx);
7049 });
7050 }
7051
7052 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7053 self.transact(window, cx, |this, window, cx| {
7054 this.select_autoclose_pair(window, cx);
7055 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7056 if !this.linked_edit_ranges.is_empty() {
7057 let selections = this.selections.all::<MultiBufferPoint>(cx);
7058 let snapshot = this.buffer.read(cx).snapshot(cx);
7059
7060 for selection in selections.iter() {
7061 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7062 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7063 if selection_start.buffer_id != selection_end.buffer_id {
7064 continue;
7065 }
7066 if let Some(ranges) =
7067 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7068 {
7069 for (buffer, entries) in ranges {
7070 linked_ranges.entry(buffer).or_default().extend(entries);
7071 }
7072 }
7073 }
7074 }
7075
7076 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7077 if !this.selections.line_mode {
7078 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7079 for selection in &mut selections {
7080 if selection.is_empty() {
7081 let old_head = selection.head();
7082 let mut new_head =
7083 movement::left(&display_map, old_head.to_display_point(&display_map))
7084 .to_point(&display_map);
7085 if let Some((buffer, line_buffer_range)) = display_map
7086 .buffer_snapshot
7087 .buffer_line_for_row(MultiBufferRow(old_head.row))
7088 {
7089 let indent_size =
7090 buffer.indent_size_for_line(line_buffer_range.start.row);
7091 let indent_len = match indent_size.kind {
7092 IndentKind::Space => {
7093 buffer.settings_at(line_buffer_range.start, cx).tab_size
7094 }
7095 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7096 };
7097 if old_head.column <= indent_size.len && old_head.column > 0 {
7098 let indent_len = indent_len.get();
7099 new_head = cmp::min(
7100 new_head,
7101 MultiBufferPoint::new(
7102 old_head.row,
7103 ((old_head.column - 1) / indent_len) * indent_len,
7104 ),
7105 );
7106 }
7107 }
7108
7109 selection.set_head(new_head, SelectionGoal::None);
7110 }
7111 }
7112 }
7113
7114 this.signature_help_state.set_backspace_pressed(true);
7115 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7116 s.select(selections)
7117 });
7118 this.insert("", window, cx);
7119 let empty_str: Arc<str> = Arc::from("");
7120 for (buffer, edits) in linked_ranges {
7121 let snapshot = buffer.read(cx).snapshot();
7122 use text::ToPoint as TP;
7123
7124 let edits = edits
7125 .into_iter()
7126 .map(|range| {
7127 let end_point = TP::to_point(&range.end, &snapshot);
7128 let mut start_point = TP::to_point(&range.start, &snapshot);
7129
7130 if end_point == start_point {
7131 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7132 .saturating_sub(1);
7133 start_point =
7134 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7135 };
7136
7137 (start_point..end_point, empty_str.clone())
7138 })
7139 .sorted_by_key(|(range, _)| range.start)
7140 .collect::<Vec<_>>();
7141 buffer.update(cx, |this, cx| {
7142 this.edit(edits, None, cx);
7143 })
7144 }
7145 this.refresh_inline_completion(true, false, window, cx);
7146 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7147 });
7148 }
7149
7150 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7151 self.transact(window, cx, |this, window, cx| {
7152 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7153 let line_mode = s.line_mode;
7154 s.move_with(|map, selection| {
7155 if selection.is_empty() && !line_mode {
7156 let cursor = movement::right(map, selection.head());
7157 selection.end = cursor;
7158 selection.reversed = true;
7159 selection.goal = SelectionGoal::None;
7160 }
7161 })
7162 });
7163 this.insert("", window, cx);
7164 this.refresh_inline_completion(true, false, window, cx);
7165 });
7166 }
7167
7168 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
7169 if self.move_to_prev_snippet_tabstop(window, cx) {
7170 return;
7171 }
7172
7173 self.outdent(&Outdent, window, cx);
7174 }
7175
7176 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7177 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7178 return;
7179 }
7180
7181 let mut selections = self.selections.all_adjusted(cx);
7182 let buffer = self.buffer.read(cx);
7183 let snapshot = buffer.snapshot(cx);
7184 let rows_iter = selections.iter().map(|s| s.head().row);
7185 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7186
7187 let mut edits = Vec::new();
7188 let mut prev_edited_row = 0;
7189 let mut row_delta = 0;
7190 for selection in &mut selections {
7191 if selection.start.row != prev_edited_row {
7192 row_delta = 0;
7193 }
7194 prev_edited_row = selection.end.row;
7195
7196 // If the selection is non-empty, then increase the indentation of the selected lines.
7197 if !selection.is_empty() {
7198 row_delta =
7199 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7200 continue;
7201 }
7202
7203 // If the selection is empty and the cursor is in the leading whitespace before the
7204 // suggested indentation, then auto-indent the line.
7205 let cursor = selection.head();
7206 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7207 if let Some(suggested_indent) =
7208 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7209 {
7210 if cursor.column < suggested_indent.len
7211 && cursor.column <= current_indent.len
7212 && current_indent.len <= suggested_indent.len
7213 {
7214 selection.start = Point::new(cursor.row, suggested_indent.len);
7215 selection.end = selection.start;
7216 if row_delta == 0 {
7217 edits.extend(Buffer::edit_for_indent_size_adjustment(
7218 cursor.row,
7219 current_indent,
7220 suggested_indent,
7221 ));
7222 row_delta = suggested_indent.len - current_indent.len;
7223 }
7224 continue;
7225 }
7226 }
7227
7228 // Otherwise, insert a hard or soft tab.
7229 let settings = buffer.settings_at(cursor, cx);
7230 let tab_size = if settings.hard_tabs {
7231 IndentSize::tab()
7232 } else {
7233 let tab_size = settings.tab_size.get();
7234 let char_column = snapshot
7235 .text_for_range(Point::new(cursor.row, 0)..cursor)
7236 .flat_map(str::chars)
7237 .count()
7238 + row_delta as usize;
7239 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7240 IndentSize::spaces(chars_to_next_tab_stop)
7241 };
7242 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7243 selection.end = selection.start;
7244 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7245 row_delta += tab_size.len;
7246 }
7247
7248 self.transact(window, cx, |this, window, cx| {
7249 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7250 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7251 s.select(selections)
7252 });
7253 this.refresh_inline_completion(true, false, window, cx);
7254 });
7255 }
7256
7257 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7258 if self.read_only(cx) {
7259 return;
7260 }
7261 let mut selections = self.selections.all::<Point>(cx);
7262 let mut prev_edited_row = 0;
7263 let mut row_delta = 0;
7264 let mut edits = Vec::new();
7265 let buffer = self.buffer.read(cx);
7266 let snapshot = buffer.snapshot(cx);
7267 for selection in &mut selections {
7268 if selection.start.row != prev_edited_row {
7269 row_delta = 0;
7270 }
7271 prev_edited_row = selection.end.row;
7272
7273 row_delta =
7274 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7275 }
7276
7277 self.transact(window, cx, |this, window, cx| {
7278 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7279 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7280 s.select(selections)
7281 });
7282 });
7283 }
7284
7285 fn indent_selection(
7286 buffer: &MultiBuffer,
7287 snapshot: &MultiBufferSnapshot,
7288 selection: &mut Selection<Point>,
7289 edits: &mut Vec<(Range<Point>, String)>,
7290 delta_for_start_row: u32,
7291 cx: &App,
7292 ) -> u32 {
7293 let settings = buffer.settings_at(selection.start, cx);
7294 let tab_size = settings.tab_size.get();
7295 let indent_kind = if settings.hard_tabs {
7296 IndentKind::Tab
7297 } else {
7298 IndentKind::Space
7299 };
7300 let mut start_row = selection.start.row;
7301 let mut end_row = selection.end.row + 1;
7302
7303 // If a selection ends at the beginning of a line, don't indent
7304 // that last line.
7305 if selection.end.column == 0 && selection.end.row > selection.start.row {
7306 end_row -= 1;
7307 }
7308
7309 // Avoid re-indenting a row that has already been indented by a
7310 // previous selection, but still update this selection's column
7311 // to reflect that indentation.
7312 if delta_for_start_row > 0 {
7313 start_row += 1;
7314 selection.start.column += delta_for_start_row;
7315 if selection.end.row == selection.start.row {
7316 selection.end.column += delta_for_start_row;
7317 }
7318 }
7319
7320 let mut delta_for_end_row = 0;
7321 let has_multiple_rows = start_row + 1 != end_row;
7322 for row in start_row..end_row {
7323 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7324 let indent_delta = match (current_indent.kind, indent_kind) {
7325 (IndentKind::Space, IndentKind::Space) => {
7326 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7327 IndentSize::spaces(columns_to_next_tab_stop)
7328 }
7329 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7330 (_, IndentKind::Tab) => IndentSize::tab(),
7331 };
7332
7333 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7334 0
7335 } else {
7336 selection.start.column
7337 };
7338 let row_start = Point::new(row, start);
7339 edits.push((
7340 row_start..row_start,
7341 indent_delta.chars().collect::<String>(),
7342 ));
7343
7344 // Update this selection's endpoints to reflect the indentation.
7345 if row == selection.start.row {
7346 selection.start.column += indent_delta.len;
7347 }
7348 if row == selection.end.row {
7349 selection.end.column += indent_delta.len;
7350 delta_for_end_row = indent_delta.len;
7351 }
7352 }
7353
7354 if selection.start.row == selection.end.row {
7355 delta_for_start_row + delta_for_end_row
7356 } else {
7357 delta_for_end_row
7358 }
7359 }
7360
7361 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7362 if self.read_only(cx) {
7363 return;
7364 }
7365 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7366 let selections = self.selections.all::<Point>(cx);
7367 let mut deletion_ranges = Vec::new();
7368 let mut last_outdent = None;
7369 {
7370 let buffer = self.buffer.read(cx);
7371 let snapshot = buffer.snapshot(cx);
7372 for selection in &selections {
7373 let settings = buffer.settings_at(selection.start, cx);
7374 let tab_size = settings.tab_size.get();
7375 let mut rows = selection.spanned_rows(false, &display_map);
7376
7377 // Avoid re-outdenting a row that has already been outdented by a
7378 // previous selection.
7379 if let Some(last_row) = last_outdent {
7380 if last_row == rows.start {
7381 rows.start = rows.start.next_row();
7382 }
7383 }
7384 let has_multiple_rows = rows.len() > 1;
7385 for row in rows.iter_rows() {
7386 let indent_size = snapshot.indent_size_for_line(row);
7387 if indent_size.len > 0 {
7388 let deletion_len = match indent_size.kind {
7389 IndentKind::Space => {
7390 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7391 if columns_to_prev_tab_stop == 0 {
7392 tab_size
7393 } else {
7394 columns_to_prev_tab_stop
7395 }
7396 }
7397 IndentKind::Tab => 1,
7398 };
7399 let start = if has_multiple_rows
7400 || deletion_len > selection.start.column
7401 || indent_size.len < selection.start.column
7402 {
7403 0
7404 } else {
7405 selection.start.column - deletion_len
7406 };
7407 deletion_ranges.push(
7408 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7409 );
7410 last_outdent = Some(row);
7411 }
7412 }
7413 }
7414 }
7415
7416 self.transact(window, cx, |this, window, cx| {
7417 this.buffer.update(cx, |buffer, cx| {
7418 let empty_str: Arc<str> = Arc::default();
7419 buffer.edit(
7420 deletion_ranges
7421 .into_iter()
7422 .map(|range| (range, empty_str.clone())),
7423 None,
7424 cx,
7425 );
7426 });
7427 let selections = this.selections.all::<usize>(cx);
7428 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7429 s.select(selections)
7430 });
7431 });
7432 }
7433
7434 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7435 if self.read_only(cx) {
7436 return;
7437 }
7438 let selections = self
7439 .selections
7440 .all::<usize>(cx)
7441 .into_iter()
7442 .map(|s| s.range());
7443
7444 self.transact(window, cx, |this, window, cx| {
7445 this.buffer.update(cx, |buffer, cx| {
7446 buffer.autoindent_ranges(selections, cx);
7447 });
7448 let selections = this.selections.all::<usize>(cx);
7449 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7450 s.select(selections)
7451 });
7452 });
7453 }
7454
7455 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7456 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7457 let selections = self.selections.all::<Point>(cx);
7458
7459 let mut new_cursors = Vec::new();
7460 let mut edit_ranges = Vec::new();
7461 let mut selections = selections.iter().peekable();
7462 while let Some(selection) = selections.next() {
7463 let mut rows = selection.spanned_rows(false, &display_map);
7464 let goal_display_column = selection.head().to_display_point(&display_map).column();
7465
7466 // Accumulate contiguous regions of rows that we want to delete.
7467 while let Some(next_selection) = selections.peek() {
7468 let next_rows = next_selection.spanned_rows(false, &display_map);
7469 if next_rows.start <= rows.end {
7470 rows.end = next_rows.end;
7471 selections.next().unwrap();
7472 } else {
7473 break;
7474 }
7475 }
7476
7477 let buffer = &display_map.buffer_snapshot;
7478 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7479 let edit_end;
7480 let cursor_buffer_row;
7481 if buffer.max_point().row >= rows.end.0 {
7482 // If there's a line after the range, delete the \n from the end of the row range
7483 // and position the cursor on the next line.
7484 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7485 cursor_buffer_row = rows.end;
7486 } else {
7487 // If there isn't a line after the range, delete the \n from the line before the
7488 // start of the row range and position the cursor there.
7489 edit_start = edit_start.saturating_sub(1);
7490 edit_end = buffer.len();
7491 cursor_buffer_row = rows.start.previous_row();
7492 }
7493
7494 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7495 *cursor.column_mut() =
7496 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7497
7498 new_cursors.push((
7499 selection.id,
7500 buffer.anchor_after(cursor.to_point(&display_map)),
7501 ));
7502 edit_ranges.push(edit_start..edit_end);
7503 }
7504
7505 self.transact(window, cx, |this, window, cx| {
7506 let buffer = this.buffer.update(cx, |buffer, cx| {
7507 let empty_str: Arc<str> = Arc::default();
7508 buffer.edit(
7509 edit_ranges
7510 .into_iter()
7511 .map(|range| (range, empty_str.clone())),
7512 None,
7513 cx,
7514 );
7515 buffer.snapshot(cx)
7516 });
7517 let new_selections = new_cursors
7518 .into_iter()
7519 .map(|(id, cursor)| {
7520 let cursor = cursor.to_point(&buffer);
7521 Selection {
7522 id,
7523 start: cursor,
7524 end: cursor,
7525 reversed: false,
7526 goal: SelectionGoal::None,
7527 }
7528 })
7529 .collect();
7530
7531 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7532 s.select(new_selections);
7533 });
7534 });
7535 }
7536
7537 pub fn join_lines_impl(
7538 &mut self,
7539 insert_whitespace: bool,
7540 window: &mut Window,
7541 cx: &mut Context<Self>,
7542 ) {
7543 if self.read_only(cx) {
7544 return;
7545 }
7546 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7547 for selection in self.selections.all::<Point>(cx) {
7548 let start = MultiBufferRow(selection.start.row);
7549 // Treat single line selections as if they include the next line. Otherwise this action
7550 // would do nothing for single line selections individual cursors.
7551 let end = if selection.start.row == selection.end.row {
7552 MultiBufferRow(selection.start.row + 1)
7553 } else {
7554 MultiBufferRow(selection.end.row)
7555 };
7556
7557 if let Some(last_row_range) = row_ranges.last_mut() {
7558 if start <= last_row_range.end {
7559 last_row_range.end = end;
7560 continue;
7561 }
7562 }
7563 row_ranges.push(start..end);
7564 }
7565
7566 let snapshot = self.buffer.read(cx).snapshot(cx);
7567 let mut cursor_positions = Vec::new();
7568 for row_range in &row_ranges {
7569 let anchor = snapshot.anchor_before(Point::new(
7570 row_range.end.previous_row().0,
7571 snapshot.line_len(row_range.end.previous_row()),
7572 ));
7573 cursor_positions.push(anchor..anchor);
7574 }
7575
7576 self.transact(window, cx, |this, window, cx| {
7577 for row_range in row_ranges.into_iter().rev() {
7578 for row in row_range.iter_rows().rev() {
7579 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7580 let next_line_row = row.next_row();
7581 let indent = snapshot.indent_size_for_line(next_line_row);
7582 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7583
7584 let replace =
7585 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7586 " "
7587 } else {
7588 ""
7589 };
7590
7591 this.buffer.update(cx, |buffer, cx| {
7592 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7593 });
7594 }
7595 }
7596
7597 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7598 s.select_anchor_ranges(cursor_positions)
7599 });
7600 });
7601 }
7602
7603 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7604 self.join_lines_impl(true, window, cx);
7605 }
7606
7607 pub fn sort_lines_case_sensitive(
7608 &mut self,
7609 _: &SortLinesCaseSensitive,
7610 window: &mut Window,
7611 cx: &mut Context<Self>,
7612 ) {
7613 self.manipulate_lines(window, cx, |lines| lines.sort())
7614 }
7615
7616 pub fn sort_lines_case_insensitive(
7617 &mut self,
7618 _: &SortLinesCaseInsensitive,
7619 window: &mut Window,
7620 cx: &mut Context<Self>,
7621 ) {
7622 self.manipulate_lines(window, cx, |lines| {
7623 lines.sort_by_key(|line| line.to_lowercase())
7624 })
7625 }
7626
7627 pub fn unique_lines_case_insensitive(
7628 &mut self,
7629 _: &UniqueLinesCaseInsensitive,
7630 window: &mut Window,
7631 cx: &mut Context<Self>,
7632 ) {
7633 self.manipulate_lines(window, cx, |lines| {
7634 let mut seen = HashSet::default();
7635 lines.retain(|line| seen.insert(line.to_lowercase()));
7636 })
7637 }
7638
7639 pub fn unique_lines_case_sensitive(
7640 &mut self,
7641 _: &UniqueLinesCaseSensitive,
7642 window: &mut Window,
7643 cx: &mut Context<Self>,
7644 ) {
7645 self.manipulate_lines(window, cx, |lines| {
7646 let mut seen = HashSet::default();
7647 lines.retain(|line| seen.insert(*line));
7648 })
7649 }
7650
7651 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7652 let Some(project) = self.project.clone() else {
7653 return;
7654 };
7655 self.reload(project, window, cx)
7656 .detach_and_notify_err(window, cx);
7657 }
7658
7659 pub fn restore_file(
7660 &mut self,
7661 _: &::git::RestoreFile,
7662 window: &mut Window,
7663 cx: &mut Context<Self>,
7664 ) {
7665 let mut buffer_ids = HashSet::default();
7666 let snapshot = self.buffer().read(cx).snapshot(cx);
7667 for selection in self.selections.all::<usize>(cx) {
7668 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7669 }
7670
7671 let buffer = self.buffer().read(cx);
7672 let ranges = buffer_ids
7673 .into_iter()
7674 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7675 .collect::<Vec<_>>();
7676
7677 self.restore_hunks_in_ranges(ranges, window, cx);
7678 }
7679
7680 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7681 let selections = self
7682 .selections
7683 .all(cx)
7684 .into_iter()
7685 .map(|s| s.range())
7686 .collect();
7687 self.restore_hunks_in_ranges(selections, window, cx);
7688 }
7689
7690 fn restore_hunks_in_ranges(
7691 &mut self,
7692 ranges: Vec<Range<Point>>,
7693 window: &mut Window,
7694 cx: &mut Context<Editor>,
7695 ) {
7696 let mut revert_changes = HashMap::default();
7697 let snapshot = self.buffer.read(cx).snapshot(cx);
7698 let Some(project) = &self.project else {
7699 return;
7700 };
7701
7702 let chunk_by = self
7703 .snapshot(window, cx)
7704 .hunks_for_ranges(ranges.into_iter())
7705 .into_iter()
7706 .chunk_by(|hunk| hunk.buffer_id);
7707 for (buffer_id, hunks) in &chunk_by {
7708 let hunks = hunks.collect::<Vec<_>>();
7709 for hunk in &hunks {
7710 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7711 }
7712 Self::do_stage_or_unstage(project, false, buffer_id, hunks.into_iter(), &snapshot, cx);
7713 }
7714 drop(chunk_by);
7715 if !revert_changes.is_empty() {
7716 self.transact(window, cx, |editor, window, cx| {
7717 editor.revert(revert_changes, window, cx);
7718 });
7719 }
7720 }
7721
7722 pub fn open_active_item_in_terminal(
7723 &mut self,
7724 _: &OpenInTerminal,
7725 window: &mut Window,
7726 cx: &mut Context<Self>,
7727 ) {
7728 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7729 let project_path = buffer.read(cx).project_path(cx)?;
7730 let project = self.project.as_ref()?.read(cx);
7731 let entry = project.entry_for_path(&project_path, cx)?;
7732 let parent = match &entry.canonical_path {
7733 Some(canonical_path) => canonical_path.to_path_buf(),
7734 None => project.absolute_path(&project_path, cx)?,
7735 }
7736 .parent()?
7737 .to_path_buf();
7738 Some(parent)
7739 }) {
7740 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7741 }
7742 }
7743
7744 pub fn prepare_restore_change(
7745 &self,
7746 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7747 hunk: &MultiBufferDiffHunk,
7748 cx: &mut App,
7749 ) -> Option<()> {
7750 let buffer = self.buffer.read(cx);
7751 let diff = buffer.diff_for(hunk.buffer_id)?;
7752 let buffer = buffer.buffer(hunk.buffer_id)?;
7753 let buffer = buffer.read(cx);
7754 let original_text = diff
7755 .read(cx)
7756 .base_text()
7757 .as_ref()?
7758 .as_rope()
7759 .slice(hunk.diff_base_byte_range.clone());
7760 let buffer_snapshot = buffer.snapshot();
7761 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7762 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7763 probe
7764 .0
7765 .start
7766 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7767 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7768 }) {
7769 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7770 Some(())
7771 } else {
7772 None
7773 }
7774 }
7775
7776 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7777 self.manipulate_lines(window, cx, |lines| lines.reverse())
7778 }
7779
7780 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7781 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7782 }
7783
7784 fn manipulate_lines<Fn>(
7785 &mut self,
7786 window: &mut Window,
7787 cx: &mut Context<Self>,
7788 mut callback: Fn,
7789 ) where
7790 Fn: FnMut(&mut Vec<&str>),
7791 {
7792 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7793 let buffer = self.buffer.read(cx).snapshot(cx);
7794
7795 let mut edits = Vec::new();
7796
7797 let selections = self.selections.all::<Point>(cx);
7798 let mut selections = selections.iter().peekable();
7799 let mut contiguous_row_selections = Vec::new();
7800 let mut new_selections = Vec::new();
7801 let mut added_lines = 0;
7802 let mut removed_lines = 0;
7803
7804 while let Some(selection) = selections.next() {
7805 let (start_row, end_row) = consume_contiguous_rows(
7806 &mut contiguous_row_selections,
7807 selection,
7808 &display_map,
7809 &mut selections,
7810 );
7811
7812 let start_point = Point::new(start_row.0, 0);
7813 let end_point = Point::new(
7814 end_row.previous_row().0,
7815 buffer.line_len(end_row.previous_row()),
7816 );
7817 let text = buffer
7818 .text_for_range(start_point..end_point)
7819 .collect::<String>();
7820
7821 let mut lines = text.split('\n').collect_vec();
7822
7823 let lines_before = lines.len();
7824 callback(&mut lines);
7825 let lines_after = lines.len();
7826
7827 edits.push((start_point..end_point, lines.join("\n")));
7828
7829 // Selections must change based on added and removed line count
7830 let start_row =
7831 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7832 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7833 new_selections.push(Selection {
7834 id: selection.id,
7835 start: start_row,
7836 end: end_row,
7837 goal: SelectionGoal::None,
7838 reversed: selection.reversed,
7839 });
7840
7841 if lines_after > lines_before {
7842 added_lines += lines_after - lines_before;
7843 } else if lines_before > lines_after {
7844 removed_lines += lines_before - lines_after;
7845 }
7846 }
7847
7848 self.transact(window, cx, |this, window, cx| {
7849 let buffer = this.buffer.update(cx, |buffer, cx| {
7850 buffer.edit(edits, None, cx);
7851 buffer.snapshot(cx)
7852 });
7853
7854 // Recalculate offsets on newly edited buffer
7855 let new_selections = new_selections
7856 .iter()
7857 .map(|s| {
7858 let start_point = Point::new(s.start.0, 0);
7859 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7860 Selection {
7861 id: s.id,
7862 start: buffer.point_to_offset(start_point),
7863 end: buffer.point_to_offset(end_point),
7864 goal: s.goal,
7865 reversed: s.reversed,
7866 }
7867 })
7868 .collect();
7869
7870 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7871 s.select(new_selections);
7872 });
7873
7874 this.request_autoscroll(Autoscroll::fit(), cx);
7875 });
7876 }
7877
7878 pub fn convert_to_upper_case(
7879 &mut self,
7880 _: &ConvertToUpperCase,
7881 window: &mut Window,
7882 cx: &mut Context<Self>,
7883 ) {
7884 self.manipulate_text(window, cx, |text| text.to_uppercase())
7885 }
7886
7887 pub fn convert_to_lower_case(
7888 &mut self,
7889 _: &ConvertToLowerCase,
7890 window: &mut Window,
7891 cx: &mut Context<Self>,
7892 ) {
7893 self.manipulate_text(window, cx, |text| text.to_lowercase())
7894 }
7895
7896 pub fn convert_to_title_case(
7897 &mut self,
7898 _: &ConvertToTitleCase,
7899 window: &mut Window,
7900 cx: &mut Context<Self>,
7901 ) {
7902 self.manipulate_text(window, cx, |text| {
7903 text.split('\n')
7904 .map(|line| line.to_case(Case::Title))
7905 .join("\n")
7906 })
7907 }
7908
7909 pub fn convert_to_snake_case(
7910 &mut self,
7911 _: &ConvertToSnakeCase,
7912 window: &mut Window,
7913 cx: &mut Context<Self>,
7914 ) {
7915 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
7916 }
7917
7918 pub fn convert_to_kebab_case(
7919 &mut self,
7920 _: &ConvertToKebabCase,
7921 window: &mut Window,
7922 cx: &mut Context<Self>,
7923 ) {
7924 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
7925 }
7926
7927 pub fn convert_to_upper_camel_case(
7928 &mut self,
7929 _: &ConvertToUpperCamelCase,
7930 window: &mut Window,
7931 cx: &mut Context<Self>,
7932 ) {
7933 self.manipulate_text(window, cx, |text| {
7934 text.split('\n')
7935 .map(|line| line.to_case(Case::UpperCamel))
7936 .join("\n")
7937 })
7938 }
7939
7940 pub fn convert_to_lower_camel_case(
7941 &mut self,
7942 _: &ConvertToLowerCamelCase,
7943 window: &mut Window,
7944 cx: &mut Context<Self>,
7945 ) {
7946 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
7947 }
7948
7949 pub fn convert_to_opposite_case(
7950 &mut self,
7951 _: &ConvertToOppositeCase,
7952 window: &mut Window,
7953 cx: &mut Context<Self>,
7954 ) {
7955 self.manipulate_text(window, cx, |text| {
7956 text.chars()
7957 .fold(String::with_capacity(text.len()), |mut t, c| {
7958 if c.is_uppercase() {
7959 t.extend(c.to_lowercase());
7960 } else {
7961 t.extend(c.to_uppercase());
7962 }
7963 t
7964 })
7965 })
7966 }
7967
7968 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
7969 where
7970 Fn: FnMut(&str) -> String,
7971 {
7972 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7973 let buffer = self.buffer.read(cx).snapshot(cx);
7974
7975 let mut new_selections = Vec::new();
7976 let mut edits = Vec::new();
7977 let mut selection_adjustment = 0i32;
7978
7979 for selection in self.selections.all::<usize>(cx) {
7980 let selection_is_empty = selection.is_empty();
7981
7982 let (start, end) = if selection_is_empty {
7983 let word_range = movement::surrounding_word(
7984 &display_map,
7985 selection.start.to_display_point(&display_map),
7986 );
7987 let start = word_range.start.to_offset(&display_map, Bias::Left);
7988 let end = word_range.end.to_offset(&display_map, Bias::Left);
7989 (start, end)
7990 } else {
7991 (selection.start, selection.end)
7992 };
7993
7994 let text = buffer.text_for_range(start..end).collect::<String>();
7995 let old_length = text.len() as i32;
7996 let text = callback(&text);
7997
7998 new_selections.push(Selection {
7999 start: (start as i32 - selection_adjustment) as usize,
8000 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8001 goal: SelectionGoal::None,
8002 ..selection
8003 });
8004
8005 selection_adjustment += old_length - text.len() as i32;
8006
8007 edits.push((start..end, text));
8008 }
8009
8010 self.transact(window, cx, |this, window, cx| {
8011 this.buffer.update(cx, |buffer, cx| {
8012 buffer.edit(edits, None, cx);
8013 });
8014
8015 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8016 s.select(new_selections);
8017 });
8018
8019 this.request_autoscroll(Autoscroll::fit(), cx);
8020 });
8021 }
8022
8023 pub fn duplicate(
8024 &mut self,
8025 upwards: bool,
8026 whole_lines: bool,
8027 window: &mut Window,
8028 cx: &mut Context<Self>,
8029 ) {
8030 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8031 let buffer = &display_map.buffer_snapshot;
8032 let selections = self.selections.all::<Point>(cx);
8033
8034 let mut edits = Vec::new();
8035 let mut selections_iter = selections.iter().peekable();
8036 while let Some(selection) = selections_iter.next() {
8037 let mut rows = selection.spanned_rows(false, &display_map);
8038 // duplicate line-wise
8039 if whole_lines || selection.start == selection.end {
8040 // Avoid duplicating the same lines twice.
8041 while let Some(next_selection) = selections_iter.peek() {
8042 let next_rows = next_selection.spanned_rows(false, &display_map);
8043 if next_rows.start < rows.end {
8044 rows.end = next_rows.end;
8045 selections_iter.next().unwrap();
8046 } else {
8047 break;
8048 }
8049 }
8050
8051 // Copy the text from the selected row region and splice it either at the start
8052 // or end of the region.
8053 let start = Point::new(rows.start.0, 0);
8054 let end = Point::new(
8055 rows.end.previous_row().0,
8056 buffer.line_len(rows.end.previous_row()),
8057 );
8058 let text = buffer
8059 .text_for_range(start..end)
8060 .chain(Some("\n"))
8061 .collect::<String>();
8062 let insert_location = if upwards {
8063 Point::new(rows.end.0, 0)
8064 } else {
8065 start
8066 };
8067 edits.push((insert_location..insert_location, text));
8068 } else {
8069 // duplicate character-wise
8070 let start = selection.start;
8071 let end = selection.end;
8072 let text = buffer.text_for_range(start..end).collect::<String>();
8073 edits.push((selection.end..selection.end, text));
8074 }
8075 }
8076
8077 self.transact(window, cx, |this, _, cx| {
8078 this.buffer.update(cx, |buffer, cx| {
8079 buffer.edit(edits, None, cx);
8080 });
8081
8082 this.request_autoscroll(Autoscroll::fit(), cx);
8083 });
8084 }
8085
8086 pub fn duplicate_line_up(
8087 &mut self,
8088 _: &DuplicateLineUp,
8089 window: &mut Window,
8090 cx: &mut Context<Self>,
8091 ) {
8092 self.duplicate(true, true, window, cx);
8093 }
8094
8095 pub fn duplicate_line_down(
8096 &mut self,
8097 _: &DuplicateLineDown,
8098 window: &mut Window,
8099 cx: &mut Context<Self>,
8100 ) {
8101 self.duplicate(false, true, window, cx);
8102 }
8103
8104 pub fn duplicate_selection(
8105 &mut self,
8106 _: &DuplicateSelection,
8107 window: &mut Window,
8108 cx: &mut Context<Self>,
8109 ) {
8110 self.duplicate(false, false, window, cx);
8111 }
8112
8113 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8114 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8115 let buffer = self.buffer.read(cx).snapshot(cx);
8116
8117 let mut edits = Vec::new();
8118 let mut unfold_ranges = Vec::new();
8119 let mut refold_creases = Vec::new();
8120
8121 let selections = self.selections.all::<Point>(cx);
8122 let mut selections = selections.iter().peekable();
8123 let mut contiguous_row_selections = Vec::new();
8124 let mut new_selections = Vec::new();
8125
8126 while let Some(selection) = selections.next() {
8127 // Find all the selections that span a contiguous row range
8128 let (start_row, end_row) = consume_contiguous_rows(
8129 &mut contiguous_row_selections,
8130 selection,
8131 &display_map,
8132 &mut selections,
8133 );
8134
8135 // Move the text spanned by the row range to be before the line preceding the row range
8136 if start_row.0 > 0 {
8137 let range_to_move = Point::new(
8138 start_row.previous_row().0,
8139 buffer.line_len(start_row.previous_row()),
8140 )
8141 ..Point::new(
8142 end_row.previous_row().0,
8143 buffer.line_len(end_row.previous_row()),
8144 );
8145 let insertion_point = display_map
8146 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8147 .0;
8148
8149 // Don't move lines across excerpts
8150 if buffer
8151 .excerpt_containing(insertion_point..range_to_move.end)
8152 .is_some()
8153 {
8154 let text = buffer
8155 .text_for_range(range_to_move.clone())
8156 .flat_map(|s| s.chars())
8157 .skip(1)
8158 .chain(['\n'])
8159 .collect::<String>();
8160
8161 edits.push((
8162 buffer.anchor_after(range_to_move.start)
8163 ..buffer.anchor_before(range_to_move.end),
8164 String::new(),
8165 ));
8166 let insertion_anchor = buffer.anchor_after(insertion_point);
8167 edits.push((insertion_anchor..insertion_anchor, text));
8168
8169 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8170
8171 // Move selections up
8172 new_selections.extend(contiguous_row_selections.drain(..).map(
8173 |mut selection| {
8174 selection.start.row -= row_delta;
8175 selection.end.row -= row_delta;
8176 selection
8177 },
8178 ));
8179
8180 // Move folds up
8181 unfold_ranges.push(range_to_move.clone());
8182 for fold in display_map.folds_in_range(
8183 buffer.anchor_before(range_to_move.start)
8184 ..buffer.anchor_after(range_to_move.end),
8185 ) {
8186 let mut start = fold.range.start.to_point(&buffer);
8187 let mut end = fold.range.end.to_point(&buffer);
8188 start.row -= row_delta;
8189 end.row -= row_delta;
8190 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8191 }
8192 }
8193 }
8194
8195 // If we didn't move line(s), preserve the existing selections
8196 new_selections.append(&mut contiguous_row_selections);
8197 }
8198
8199 self.transact(window, cx, |this, window, cx| {
8200 this.unfold_ranges(&unfold_ranges, true, true, cx);
8201 this.buffer.update(cx, |buffer, cx| {
8202 for (range, text) in edits {
8203 buffer.edit([(range, text)], None, cx);
8204 }
8205 });
8206 this.fold_creases(refold_creases, true, window, cx);
8207 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8208 s.select(new_selections);
8209 })
8210 });
8211 }
8212
8213 pub fn move_line_down(
8214 &mut self,
8215 _: &MoveLineDown,
8216 window: &mut Window,
8217 cx: &mut Context<Self>,
8218 ) {
8219 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8220 let buffer = self.buffer.read(cx).snapshot(cx);
8221
8222 let mut edits = Vec::new();
8223 let mut unfold_ranges = Vec::new();
8224 let mut refold_creases = Vec::new();
8225
8226 let selections = self.selections.all::<Point>(cx);
8227 let mut selections = selections.iter().peekable();
8228 let mut contiguous_row_selections = Vec::new();
8229 let mut new_selections = Vec::new();
8230
8231 while let Some(selection) = selections.next() {
8232 // Find all the selections that span a contiguous row range
8233 let (start_row, end_row) = consume_contiguous_rows(
8234 &mut contiguous_row_selections,
8235 selection,
8236 &display_map,
8237 &mut selections,
8238 );
8239
8240 // Move the text spanned by the row range to be after the last line of the row range
8241 if end_row.0 <= buffer.max_point().row {
8242 let range_to_move =
8243 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8244 let insertion_point = display_map
8245 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8246 .0;
8247
8248 // Don't move lines across excerpt boundaries
8249 if buffer
8250 .excerpt_containing(range_to_move.start..insertion_point)
8251 .is_some()
8252 {
8253 let mut text = String::from("\n");
8254 text.extend(buffer.text_for_range(range_to_move.clone()));
8255 text.pop(); // Drop trailing newline
8256 edits.push((
8257 buffer.anchor_after(range_to_move.start)
8258 ..buffer.anchor_before(range_to_move.end),
8259 String::new(),
8260 ));
8261 let insertion_anchor = buffer.anchor_after(insertion_point);
8262 edits.push((insertion_anchor..insertion_anchor, text));
8263
8264 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8265
8266 // Move selections down
8267 new_selections.extend(contiguous_row_selections.drain(..).map(
8268 |mut selection| {
8269 selection.start.row += row_delta;
8270 selection.end.row += row_delta;
8271 selection
8272 },
8273 ));
8274
8275 // Move folds down
8276 unfold_ranges.push(range_to_move.clone());
8277 for fold in display_map.folds_in_range(
8278 buffer.anchor_before(range_to_move.start)
8279 ..buffer.anchor_after(range_to_move.end),
8280 ) {
8281 let mut start = fold.range.start.to_point(&buffer);
8282 let mut end = fold.range.end.to_point(&buffer);
8283 start.row += row_delta;
8284 end.row += row_delta;
8285 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8286 }
8287 }
8288 }
8289
8290 // If we didn't move line(s), preserve the existing selections
8291 new_selections.append(&mut contiguous_row_selections);
8292 }
8293
8294 self.transact(window, cx, |this, window, cx| {
8295 this.unfold_ranges(&unfold_ranges, true, true, cx);
8296 this.buffer.update(cx, |buffer, cx| {
8297 for (range, text) in edits {
8298 buffer.edit([(range, text)], None, cx);
8299 }
8300 });
8301 this.fold_creases(refold_creases, true, window, cx);
8302 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8303 s.select(new_selections)
8304 });
8305 });
8306 }
8307
8308 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8309 let text_layout_details = &self.text_layout_details(window);
8310 self.transact(window, cx, |this, window, cx| {
8311 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8312 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8313 let line_mode = s.line_mode;
8314 s.move_with(|display_map, selection| {
8315 if !selection.is_empty() || line_mode {
8316 return;
8317 }
8318
8319 let mut head = selection.head();
8320 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8321 if head.column() == display_map.line_len(head.row()) {
8322 transpose_offset = display_map
8323 .buffer_snapshot
8324 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8325 }
8326
8327 if transpose_offset == 0 {
8328 return;
8329 }
8330
8331 *head.column_mut() += 1;
8332 head = display_map.clip_point(head, Bias::Right);
8333 let goal = SelectionGoal::HorizontalPosition(
8334 display_map
8335 .x_for_display_point(head, text_layout_details)
8336 .into(),
8337 );
8338 selection.collapse_to(head, goal);
8339
8340 let transpose_start = display_map
8341 .buffer_snapshot
8342 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8343 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8344 let transpose_end = display_map
8345 .buffer_snapshot
8346 .clip_offset(transpose_offset + 1, Bias::Right);
8347 if let Some(ch) =
8348 display_map.buffer_snapshot.chars_at(transpose_start).next()
8349 {
8350 edits.push((transpose_start..transpose_offset, String::new()));
8351 edits.push((transpose_end..transpose_end, ch.to_string()));
8352 }
8353 }
8354 });
8355 edits
8356 });
8357 this.buffer
8358 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8359 let selections = this.selections.all::<usize>(cx);
8360 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8361 s.select(selections);
8362 });
8363 });
8364 }
8365
8366 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8367 self.rewrap_impl(IsVimMode::No, cx)
8368 }
8369
8370 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8371 let buffer = self.buffer.read(cx).snapshot(cx);
8372 let selections = self.selections.all::<Point>(cx);
8373 let mut selections = selections.iter().peekable();
8374
8375 let mut edits = Vec::new();
8376 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8377
8378 while let Some(selection) = selections.next() {
8379 let mut start_row = selection.start.row;
8380 let mut end_row = selection.end.row;
8381
8382 // Skip selections that overlap with a range that has already been rewrapped.
8383 let selection_range = start_row..end_row;
8384 if rewrapped_row_ranges
8385 .iter()
8386 .any(|range| range.overlaps(&selection_range))
8387 {
8388 continue;
8389 }
8390
8391 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
8392
8393 // Since not all lines in the selection may be at the same indent
8394 // level, choose the indent size that is the most common between all
8395 // of the lines.
8396 //
8397 // If there is a tie, we use the deepest indent.
8398 let (indent_size, indent_end) = {
8399 let mut indent_size_occurrences = HashMap::default();
8400 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8401
8402 for row in start_row..=end_row {
8403 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8404 rows_by_indent_size.entry(indent).or_default().push(row);
8405 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8406 }
8407
8408 let indent_size = indent_size_occurrences
8409 .into_iter()
8410 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8411 .map(|(indent, _)| indent)
8412 .unwrap_or_default();
8413 let row = rows_by_indent_size[&indent_size][0];
8414 let indent_end = Point::new(row, indent_size.len);
8415
8416 (indent_size, indent_end)
8417 };
8418
8419 let mut line_prefix = indent_size.chars().collect::<String>();
8420
8421 let mut inside_comment = false;
8422 if let Some(comment_prefix) =
8423 buffer
8424 .language_scope_at(selection.head())
8425 .and_then(|language| {
8426 language
8427 .line_comment_prefixes()
8428 .iter()
8429 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8430 .cloned()
8431 })
8432 {
8433 line_prefix.push_str(&comment_prefix);
8434 inside_comment = true;
8435 }
8436
8437 let language_settings = buffer.settings_at(selection.head(), cx);
8438 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8439 RewrapBehavior::InComments => inside_comment,
8440 RewrapBehavior::InSelections => !selection.is_empty(),
8441 RewrapBehavior::Anywhere => true,
8442 };
8443
8444 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8445 if !should_rewrap {
8446 continue;
8447 }
8448
8449 if selection.is_empty() {
8450 'expand_upwards: while start_row > 0 {
8451 let prev_row = start_row - 1;
8452 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8453 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8454 {
8455 start_row = prev_row;
8456 } else {
8457 break 'expand_upwards;
8458 }
8459 }
8460
8461 'expand_downwards: while end_row < buffer.max_point().row {
8462 let next_row = end_row + 1;
8463 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8464 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8465 {
8466 end_row = next_row;
8467 } else {
8468 break 'expand_downwards;
8469 }
8470 }
8471 }
8472
8473 let start = Point::new(start_row, 0);
8474 let start_offset = start.to_offset(&buffer);
8475 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8476 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8477 let Some(lines_without_prefixes) = selection_text
8478 .lines()
8479 .map(|line| {
8480 line.strip_prefix(&line_prefix)
8481 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8482 .ok_or_else(|| {
8483 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8484 })
8485 })
8486 .collect::<Result<Vec<_>, _>>()
8487 .log_err()
8488 else {
8489 continue;
8490 };
8491
8492 let wrap_column = buffer
8493 .settings_at(Point::new(start_row, 0), cx)
8494 .preferred_line_length as usize;
8495 let wrapped_text = wrap_with_prefix(
8496 line_prefix,
8497 lines_without_prefixes.join(" "),
8498 wrap_column,
8499 tab_size,
8500 );
8501
8502 // TODO: should always use char-based diff while still supporting cursor behavior that
8503 // matches vim.
8504 let mut diff_options = DiffOptions::default();
8505 if is_vim_mode == IsVimMode::Yes {
8506 diff_options.max_word_diff_len = 0;
8507 diff_options.max_word_diff_line_count = 0;
8508 } else {
8509 diff_options.max_word_diff_len = usize::MAX;
8510 diff_options.max_word_diff_line_count = usize::MAX;
8511 }
8512
8513 for (old_range, new_text) in
8514 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8515 {
8516 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8517 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8518 edits.push((edit_start..edit_end, new_text));
8519 }
8520
8521 rewrapped_row_ranges.push(start_row..=end_row);
8522 }
8523
8524 self.buffer
8525 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8526 }
8527
8528 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8529 let mut text = String::new();
8530 let buffer = self.buffer.read(cx).snapshot(cx);
8531 let mut selections = self.selections.all::<Point>(cx);
8532 let mut clipboard_selections = Vec::with_capacity(selections.len());
8533 {
8534 let max_point = buffer.max_point();
8535 let mut is_first = true;
8536 for selection in &mut selections {
8537 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8538 if is_entire_line {
8539 selection.start = Point::new(selection.start.row, 0);
8540 if !selection.is_empty() && selection.end.column == 0 {
8541 selection.end = cmp::min(max_point, selection.end);
8542 } else {
8543 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8544 }
8545 selection.goal = SelectionGoal::None;
8546 }
8547 if is_first {
8548 is_first = false;
8549 } else {
8550 text += "\n";
8551 }
8552 let mut len = 0;
8553 for chunk in buffer.text_for_range(selection.start..selection.end) {
8554 text.push_str(chunk);
8555 len += chunk.len();
8556 }
8557 clipboard_selections.push(ClipboardSelection {
8558 len,
8559 is_entire_line,
8560 start_column: selection.start.column,
8561 });
8562 }
8563 }
8564
8565 self.transact(window, cx, |this, window, cx| {
8566 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8567 s.select(selections);
8568 });
8569 this.insert("", window, cx);
8570 });
8571 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8572 }
8573
8574 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8575 let item = self.cut_common(window, cx);
8576 cx.write_to_clipboard(item);
8577 }
8578
8579 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8580 self.change_selections(None, window, cx, |s| {
8581 s.move_with(|snapshot, sel| {
8582 if sel.is_empty() {
8583 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8584 }
8585 });
8586 });
8587 let item = self.cut_common(window, cx);
8588 cx.set_global(KillRing(item))
8589 }
8590
8591 pub fn kill_ring_yank(
8592 &mut self,
8593 _: &KillRingYank,
8594 window: &mut Window,
8595 cx: &mut Context<Self>,
8596 ) {
8597 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8598 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8599 (kill_ring.text().to_string(), kill_ring.metadata_json())
8600 } else {
8601 return;
8602 }
8603 } else {
8604 return;
8605 };
8606 self.do_paste(&text, metadata, false, window, cx);
8607 }
8608
8609 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8610 let selections = self.selections.all::<Point>(cx);
8611 let buffer = self.buffer.read(cx).read(cx);
8612 let mut text = String::new();
8613
8614 let mut clipboard_selections = Vec::with_capacity(selections.len());
8615 {
8616 let max_point = buffer.max_point();
8617 let mut is_first = true;
8618 for selection in selections.iter() {
8619 let mut start = selection.start;
8620 let mut end = selection.end;
8621 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8622 if is_entire_line {
8623 start = Point::new(start.row, 0);
8624 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8625 }
8626 if is_first {
8627 is_first = false;
8628 } else {
8629 text += "\n";
8630 }
8631 let mut len = 0;
8632 for chunk in buffer.text_for_range(start..end) {
8633 text.push_str(chunk);
8634 len += chunk.len();
8635 }
8636 clipboard_selections.push(ClipboardSelection {
8637 len,
8638 is_entire_line,
8639 start_column: start.column,
8640 });
8641 }
8642 }
8643
8644 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8645 text,
8646 clipboard_selections,
8647 ));
8648 }
8649
8650 pub fn do_paste(
8651 &mut self,
8652 text: &String,
8653 clipboard_selections: Option<Vec<ClipboardSelection>>,
8654 handle_entire_lines: bool,
8655 window: &mut Window,
8656 cx: &mut Context<Self>,
8657 ) {
8658 if self.read_only(cx) {
8659 return;
8660 }
8661
8662 let clipboard_text = Cow::Borrowed(text);
8663
8664 self.transact(window, cx, |this, window, cx| {
8665 if let Some(mut clipboard_selections) = clipboard_selections {
8666 let old_selections = this.selections.all::<usize>(cx);
8667 let all_selections_were_entire_line =
8668 clipboard_selections.iter().all(|s| s.is_entire_line);
8669 let first_selection_start_column =
8670 clipboard_selections.first().map(|s| s.start_column);
8671 if clipboard_selections.len() != old_selections.len() {
8672 clipboard_selections.drain(..);
8673 }
8674 let cursor_offset = this.selections.last::<usize>(cx).head();
8675 let mut auto_indent_on_paste = true;
8676
8677 this.buffer.update(cx, |buffer, cx| {
8678 let snapshot = buffer.read(cx);
8679 auto_indent_on_paste =
8680 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
8681
8682 let mut start_offset = 0;
8683 let mut edits = Vec::new();
8684 let mut original_start_columns = Vec::new();
8685 for (ix, selection) in old_selections.iter().enumerate() {
8686 let to_insert;
8687 let entire_line;
8688 let original_start_column;
8689 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8690 let end_offset = start_offset + clipboard_selection.len;
8691 to_insert = &clipboard_text[start_offset..end_offset];
8692 entire_line = clipboard_selection.is_entire_line;
8693 start_offset = end_offset + 1;
8694 original_start_column = Some(clipboard_selection.start_column);
8695 } else {
8696 to_insert = clipboard_text.as_str();
8697 entire_line = all_selections_were_entire_line;
8698 original_start_column = first_selection_start_column
8699 }
8700
8701 // If the corresponding selection was empty when this slice of the
8702 // clipboard text was written, then the entire line containing the
8703 // selection was copied. If this selection is also currently empty,
8704 // then paste the line before the current line of the buffer.
8705 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8706 let column = selection.start.to_point(&snapshot).column as usize;
8707 let line_start = selection.start - column;
8708 line_start..line_start
8709 } else {
8710 selection.range()
8711 };
8712
8713 edits.push((range, to_insert));
8714 original_start_columns.extend(original_start_column);
8715 }
8716 drop(snapshot);
8717
8718 buffer.edit(
8719 edits,
8720 if auto_indent_on_paste {
8721 Some(AutoindentMode::Block {
8722 original_start_columns,
8723 })
8724 } else {
8725 None
8726 },
8727 cx,
8728 );
8729 });
8730
8731 let selections = this.selections.all::<usize>(cx);
8732 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8733 s.select(selections)
8734 });
8735 } else {
8736 this.insert(&clipboard_text, window, cx);
8737 }
8738 });
8739 }
8740
8741 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8742 if let Some(item) = cx.read_from_clipboard() {
8743 let entries = item.entries();
8744
8745 match entries.first() {
8746 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8747 // of all the pasted entries.
8748 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8749 .do_paste(
8750 clipboard_string.text(),
8751 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8752 true,
8753 window,
8754 cx,
8755 ),
8756 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8757 }
8758 }
8759 }
8760
8761 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8762 if self.read_only(cx) {
8763 return;
8764 }
8765
8766 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8767 if let Some((selections, _)) =
8768 self.selection_history.transaction(transaction_id).cloned()
8769 {
8770 self.change_selections(None, window, cx, |s| {
8771 s.select_anchors(selections.to_vec());
8772 });
8773 }
8774 self.request_autoscroll(Autoscroll::fit(), cx);
8775 self.unmark_text(window, cx);
8776 self.refresh_inline_completion(true, false, window, cx);
8777 cx.emit(EditorEvent::Edited { transaction_id });
8778 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8779 }
8780 }
8781
8782 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8783 if self.read_only(cx) {
8784 return;
8785 }
8786
8787 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8788 if let Some((_, Some(selections))) =
8789 self.selection_history.transaction(transaction_id).cloned()
8790 {
8791 self.change_selections(None, window, cx, |s| {
8792 s.select_anchors(selections.to_vec());
8793 });
8794 }
8795 self.request_autoscroll(Autoscroll::fit(), cx);
8796 self.unmark_text(window, cx);
8797 self.refresh_inline_completion(true, false, window, cx);
8798 cx.emit(EditorEvent::Edited { transaction_id });
8799 }
8800 }
8801
8802 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8803 self.buffer
8804 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8805 }
8806
8807 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8808 self.buffer
8809 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8810 }
8811
8812 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8813 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8814 let line_mode = s.line_mode;
8815 s.move_with(|map, selection| {
8816 let cursor = if selection.is_empty() && !line_mode {
8817 movement::left(map, selection.start)
8818 } else {
8819 selection.start
8820 };
8821 selection.collapse_to(cursor, SelectionGoal::None);
8822 });
8823 })
8824 }
8825
8826 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8827 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8828 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8829 })
8830 }
8831
8832 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8833 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8834 let line_mode = s.line_mode;
8835 s.move_with(|map, selection| {
8836 let cursor = if selection.is_empty() && !line_mode {
8837 movement::right(map, selection.end)
8838 } else {
8839 selection.end
8840 };
8841 selection.collapse_to(cursor, SelectionGoal::None)
8842 });
8843 })
8844 }
8845
8846 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8847 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8848 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8849 })
8850 }
8851
8852 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
8853 if self.take_rename(true, window, cx).is_some() {
8854 return;
8855 }
8856
8857 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8858 cx.propagate();
8859 return;
8860 }
8861
8862 let text_layout_details = &self.text_layout_details(window);
8863 let selection_count = self.selections.count();
8864 let first_selection = self.selections.first_anchor();
8865
8866 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8867 let line_mode = s.line_mode;
8868 s.move_with(|map, selection| {
8869 if !selection.is_empty() && !line_mode {
8870 selection.goal = SelectionGoal::None;
8871 }
8872 let (cursor, goal) = movement::up(
8873 map,
8874 selection.start,
8875 selection.goal,
8876 false,
8877 text_layout_details,
8878 );
8879 selection.collapse_to(cursor, goal);
8880 });
8881 });
8882
8883 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8884 {
8885 cx.propagate();
8886 }
8887 }
8888
8889 pub fn move_up_by_lines(
8890 &mut self,
8891 action: &MoveUpByLines,
8892 window: &mut Window,
8893 cx: &mut Context<Self>,
8894 ) {
8895 if self.take_rename(true, window, cx).is_some() {
8896 return;
8897 }
8898
8899 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8900 cx.propagate();
8901 return;
8902 }
8903
8904 let text_layout_details = &self.text_layout_details(window);
8905
8906 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8907 let line_mode = s.line_mode;
8908 s.move_with(|map, selection| {
8909 if !selection.is_empty() && !line_mode {
8910 selection.goal = SelectionGoal::None;
8911 }
8912 let (cursor, goal) = movement::up_by_rows(
8913 map,
8914 selection.start,
8915 action.lines,
8916 selection.goal,
8917 false,
8918 text_layout_details,
8919 );
8920 selection.collapse_to(cursor, goal);
8921 });
8922 })
8923 }
8924
8925 pub fn move_down_by_lines(
8926 &mut self,
8927 action: &MoveDownByLines,
8928 window: &mut Window,
8929 cx: &mut Context<Self>,
8930 ) {
8931 if self.take_rename(true, window, cx).is_some() {
8932 return;
8933 }
8934
8935 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8936 cx.propagate();
8937 return;
8938 }
8939
8940 let text_layout_details = &self.text_layout_details(window);
8941
8942 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8943 let line_mode = s.line_mode;
8944 s.move_with(|map, selection| {
8945 if !selection.is_empty() && !line_mode {
8946 selection.goal = SelectionGoal::None;
8947 }
8948 let (cursor, goal) = movement::down_by_rows(
8949 map,
8950 selection.start,
8951 action.lines,
8952 selection.goal,
8953 false,
8954 text_layout_details,
8955 );
8956 selection.collapse_to(cursor, goal);
8957 });
8958 })
8959 }
8960
8961 pub fn select_down_by_lines(
8962 &mut self,
8963 action: &SelectDownByLines,
8964 window: &mut Window,
8965 cx: &mut Context<Self>,
8966 ) {
8967 let text_layout_details = &self.text_layout_details(window);
8968 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8969 s.move_heads_with(|map, head, goal| {
8970 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
8971 })
8972 })
8973 }
8974
8975 pub fn select_up_by_lines(
8976 &mut self,
8977 action: &SelectUpByLines,
8978 window: &mut Window,
8979 cx: &mut Context<Self>,
8980 ) {
8981 let text_layout_details = &self.text_layout_details(window);
8982 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8983 s.move_heads_with(|map, head, goal| {
8984 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8985 })
8986 })
8987 }
8988
8989 pub fn select_page_up(
8990 &mut self,
8991 _: &SelectPageUp,
8992 window: &mut Window,
8993 cx: &mut Context<Self>,
8994 ) {
8995 let Some(row_count) = self.visible_row_count() else {
8996 return;
8997 };
8998
8999 let text_layout_details = &self.text_layout_details(window);
9000
9001 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9002 s.move_heads_with(|map, head, goal| {
9003 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9004 })
9005 })
9006 }
9007
9008 pub fn move_page_up(
9009 &mut self,
9010 action: &MovePageUp,
9011 window: &mut Window,
9012 cx: &mut Context<Self>,
9013 ) {
9014 if self.take_rename(true, window, cx).is_some() {
9015 return;
9016 }
9017
9018 if self
9019 .context_menu
9020 .borrow_mut()
9021 .as_mut()
9022 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9023 .unwrap_or(false)
9024 {
9025 return;
9026 }
9027
9028 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9029 cx.propagate();
9030 return;
9031 }
9032
9033 let Some(row_count) = self.visible_row_count() else {
9034 return;
9035 };
9036
9037 let autoscroll = if action.center_cursor {
9038 Autoscroll::center()
9039 } else {
9040 Autoscroll::fit()
9041 };
9042
9043 let text_layout_details = &self.text_layout_details(window);
9044
9045 self.change_selections(Some(autoscroll), window, cx, |s| {
9046 let line_mode = s.line_mode;
9047 s.move_with(|map, selection| {
9048 if !selection.is_empty() && !line_mode {
9049 selection.goal = SelectionGoal::None;
9050 }
9051 let (cursor, goal) = movement::up_by_rows(
9052 map,
9053 selection.end,
9054 row_count,
9055 selection.goal,
9056 false,
9057 text_layout_details,
9058 );
9059 selection.collapse_to(cursor, goal);
9060 });
9061 });
9062 }
9063
9064 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9065 let text_layout_details = &self.text_layout_details(window);
9066 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9067 s.move_heads_with(|map, head, goal| {
9068 movement::up(map, head, goal, false, text_layout_details)
9069 })
9070 })
9071 }
9072
9073 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9074 self.take_rename(true, window, cx);
9075
9076 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9077 cx.propagate();
9078 return;
9079 }
9080
9081 let text_layout_details = &self.text_layout_details(window);
9082 let selection_count = self.selections.count();
9083 let first_selection = self.selections.first_anchor();
9084
9085 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9086 let line_mode = s.line_mode;
9087 s.move_with(|map, selection| {
9088 if !selection.is_empty() && !line_mode {
9089 selection.goal = SelectionGoal::None;
9090 }
9091 let (cursor, goal) = movement::down(
9092 map,
9093 selection.end,
9094 selection.goal,
9095 false,
9096 text_layout_details,
9097 );
9098 selection.collapse_to(cursor, goal);
9099 });
9100 });
9101
9102 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9103 {
9104 cx.propagate();
9105 }
9106 }
9107
9108 pub fn select_page_down(
9109 &mut self,
9110 _: &SelectPageDown,
9111 window: &mut Window,
9112 cx: &mut Context<Self>,
9113 ) {
9114 let Some(row_count) = self.visible_row_count() else {
9115 return;
9116 };
9117
9118 let text_layout_details = &self.text_layout_details(window);
9119
9120 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9121 s.move_heads_with(|map, head, goal| {
9122 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9123 })
9124 })
9125 }
9126
9127 pub fn move_page_down(
9128 &mut self,
9129 action: &MovePageDown,
9130 window: &mut Window,
9131 cx: &mut Context<Self>,
9132 ) {
9133 if self.take_rename(true, window, cx).is_some() {
9134 return;
9135 }
9136
9137 if self
9138 .context_menu
9139 .borrow_mut()
9140 .as_mut()
9141 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9142 .unwrap_or(false)
9143 {
9144 return;
9145 }
9146
9147 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9148 cx.propagate();
9149 return;
9150 }
9151
9152 let Some(row_count) = self.visible_row_count() else {
9153 return;
9154 };
9155
9156 let autoscroll = if action.center_cursor {
9157 Autoscroll::center()
9158 } else {
9159 Autoscroll::fit()
9160 };
9161
9162 let text_layout_details = &self.text_layout_details(window);
9163 self.change_selections(Some(autoscroll), window, cx, |s| {
9164 let line_mode = s.line_mode;
9165 s.move_with(|map, selection| {
9166 if !selection.is_empty() && !line_mode {
9167 selection.goal = SelectionGoal::None;
9168 }
9169 let (cursor, goal) = movement::down_by_rows(
9170 map,
9171 selection.end,
9172 row_count,
9173 selection.goal,
9174 false,
9175 text_layout_details,
9176 );
9177 selection.collapse_to(cursor, goal);
9178 });
9179 });
9180 }
9181
9182 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9183 let text_layout_details = &self.text_layout_details(window);
9184 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9185 s.move_heads_with(|map, head, goal| {
9186 movement::down(map, head, goal, false, text_layout_details)
9187 })
9188 });
9189 }
9190
9191 pub fn context_menu_first(
9192 &mut self,
9193 _: &ContextMenuFirst,
9194 _window: &mut Window,
9195 cx: &mut Context<Self>,
9196 ) {
9197 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9198 context_menu.select_first(self.completion_provider.as_deref(), cx);
9199 }
9200 }
9201
9202 pub fn context_menu_prev(
9203 &mut self,
9204 _: &ContextMenuPrev,
9205 _window: &mut Window,
9206 cx: &mut Context<Self>,
9207 ) {
9208 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9209 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9210 }
9211 }
9212
9213 pub fn context_menu_next(
9214 &mut self,
9215 _: &ContextMenuNext,
9216 _window: &mut Window,
9217 cx: &mut Context<Self>,
9218 ) {
9219 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9220 context_menu.select_next(self.completion_provider.as_deref(), cx);
9221 }
9222 }
9223
9224 pub fn context_menu_last(
9225 &mut self,
9226 _: &ContextMenuLast,
9227 _window: &mut Window,
9228 cx: &mut Context<Self>,
9229 ) {
9230 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9231 context_menu.select_last(self.completion_provider.as_deref(), cx);
9232 }
9233 }
9234
9235 pub fn move_to_previous_word_start(
9236 &mut self,
9237 _: &MoveToPreviousWordStart,
9238 window: &mut Window,
9239 cx: &mut Context<Self>,
9240 ) {
9241 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9242 s.move_cursors_with(|map, head, _| {
9243 (
9244 movement::previous_word_start(map, head),
9245 SelectionGoal::None,
9246 )
9247 });
9248 })
9249 }
9250
9251 pub fn move_to_previous_subword_start(
9252 &mut self,
9253 _: &MoveToPreviousSubwordStart,
9254 window: &mut Window,
9255 cx: &mut Context<Self>,
9256 ) {
9257 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9258 s.move_cursors_with(|map, head, _| {
9259 (
9260 movement::previous_subword_start(map, head),
9261 SelectionGoal::None,
9262 )
9263 });
9264 })
9265 }
9266
9267 pub fn select_to_previous_word_start(
9268 &mut self,
9269 _: &SelectToPreviousWordStart,
9270 window: &mut Window,
9271 cx: &mut Context<Self>,
9272 ) {
9273 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9274 s.move_heads_with(|map, head, _| {
9275 (
9276 movement::previous_word_start(map, head),
9277 SelectionGoal::None,
9278 )
9279 });
9280 })
9281 }
9282
9283 pub fn select_to_previous_subword_start(
9284 &mut self,
9285 _: &SelectToPreviousSubwordStart,
9286 window: &mut Window,
9287 cx: &mut Context<Self>,
9288 ) {
9289 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9290 s.move_heads_with(|map, head, _| {
9291 (
9292 movement::previous_subword_start(map, head),
9293 SelectionGoal::None,
9294 )
9295 });
9296 })
9297 }
9298
9299 pub fn delete_to_previous_word_start(
9300 &mut self,
9301 action: &DeleteToPreviousWordStart,
9302 window: &mut Window,
9303 cx: &mut Context<Self>,
9304 ) {
9305 self.transact(window, cx, |this, window, cx| {
9306 this.select_autoclose_pair(window, cx);
9307 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9308 let line_mode = s.line_mode;
9309 s.move_with(|map, selection| {
9310 if selection.is_empty() && !line_mode {
9311 let cursor = if action.ignore_newlines {
9312 movement::previous_word_start(map, selection.head())
9313 } else {
9314 movement::previous_word_start_or_newline(map, selection.head())
9315 };
9316 selection.set_head(cursor, SelectionGoal::None);
9317 }
9318 });
9319 });
9320 this.insert("", window, cx);
9321 });
9322 }
9323
9324 pub fn delete_to_previous_subword_start(
9325 &mut self,
9326 _: &DeleteToPreviousSubwordStart,
9327 window: &mut Window,
9328 cx: &mut Context<Self>,
9329 ) {
9330 self.transact(window, cx, |this, window, cx| {
9331 this.select_autoclose_pair(window, cx);
9332 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9333 let line_mode = s.line_mode;
9334 s.move_with(|map, selection| {
9335 if selection.is_empty() && !line_mode {
9336 let cursor = movement::previous_subword_start(map, selection.head());
9337 selection.set_head(cursor, SelectionGoal::None);
9338 }
9339 });
9340 });
9341 this.insert("", window, cx);
9342 });
9343 }
9344
9345 pub fn move_to_next_word_end(
9346 &mut self,
9347 _: &MoveToNextWordEnd,
9348 window: &mut Window,
9349 cx: &mut Context<Self>,
9350 ) {
9351 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9352 s.move_cursors_with(|map, head, _| {
9353 (movement::next_word_end(map, head), SelectionGoal::None)
9354 });
9355 })
9356 }
9357
9358 pub fn move_to_next_subword_end(
9359 &mut self,
9360 _: &MoveToNextSubwordEnd,
9361 window: &mut Window,
9362 cx: &mut Context<Self>,
9363 ) {
9364 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9365 s.move_cursors_with(|map, head, _| {
9366 (movement::next_subword_end(map, head), SelectionGoal::None)
9367 });
9368 })
9369 }
9370
9371 pub fn select_to_next_word_end(
9372 &mut self,
9373 _: &SelectToNextWordEnd,
9374 window: &mut Window,
9375 cx: &mut Context<Self>,
9376 ) {
9377 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9378 s.move_heads_with(|map, head, _| {
9379 (movement::next_word_end(map, head), SelectionGoal::None)
9380 });
9381 })
9382 }
9383
9384 pub fn select_to_next_subword_end(
9385 &mut self,
9386 _: &SelectToNextSubwordEnd,
9387 window: &mut Window,
9388 cx: &mut Context<Self>,
9389 ) {
9390 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9391 s.move_heads_with(|map, head, _| {
9392 (movement::next_subword_end(map, head), SelectionGoal::None)
9393 });
9394 })
9395 }
9396
9397 pub fn delete_to_next_word_end(
9398 &mut self,
9399 action: &DeleteToNextWordEnd,
9400 window: &mut Window,
9401 cx: &mut Context<Self>,
9402 ) {
9403 self.transact(window, cx, |this, window, cx| {
9404 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9405 let line_mode = s.line_mode;
9406 s.move_with(|map, selection| {
9407 if selection.is_empty() && !line_mode {
9408 let cursor = if action.ignore_newlines {
9409 movement::next_word_end(map, selection.head())
9410 } else {
9411 movement::next_word_end_or_newline(map, selection.head())
9412 };
9413 selection.set_head(cursor, SelectionGoal::None);
9414 }
9415 });
9416 });
9417 this.insert("", window, cx);
9418 });
9419 }
9420
9421 pub fn delete_to_next_subword_end(
9422 &mut self,
9423 _: &DeleteToNextSubwordEnd,
9424 window: &mut Window,
9425 cx: &mut Context<Self>,
9426 ) {
9427 self.transact(window, cx, |this, window, cx| {
9428 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9429 s.move_with(|map, selection| {
9430 if selection.is_empty() {
9431 let cursor = movement::next_subword_end(map, selection.head());
9432 selection.set_head(cursor, SelectionGoal::None);
9433 }
9434 });
9435 });
9436 this.insert("", window, cx);
9437 });
9438 }
9439
9440 pub fn move_to_beginning_of_line(
9441 &mut self,
9442 action: &MoveToBeginningOfLine,
9443 window: &mut Window,
9444 cx: &mut Context<Self>,
9445 ) {
9446 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9447 s.move_cursors_with(|map, head, _| {
9448 (
9449 movement::indented_line_beginning(
9450 map,
9451 head,
9452 action.stop_at_soft_wraps,
9453 action.stop_at_indent,
9454 ),
9455 SelectionGoal::None,
9456 )
9457 });
9458 })
9459 }
9460
9461 pub fn select_to_beginning_of_line(
9462 &mut self,
9463 action: &SelectToBeginningOfLine,
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 (
9470 movement::indented_line_beginning(
9471 map,
9472 head,
9473 action.stop_at_soft_wraps,
9474 action.stop_at_indent,
9475 ),
9476 SelectionGoal::None,
9477 )
9478 });
9479 });
9480 }
9481
9482 pub fn delete_to_beginning_of_line(
9483 &mut self,
9484 _: &DeleteToBeginningOfLine,
9485 window: &mut Window,
9486 cx: &mut Context<Self>,
9487 ) {
9488 self.transact(window, cx, |this, window, cx| {
9489 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9490 s.move_with(|_, selection| {
9491 selection.reversed = true;
9492 });
9493 });
9494
9495 this.select_to_beginning_of_line(
9496 &SelectToBeginningOfLine {
9497 stop_at_soft_wraps: false,
9498 stop_at_indent: false,
9499 },
9500 window,
9501 cx,
9502 );
9503 this.backspace(&Backspace, window, cx);
9504 });
9505 }
9506
9507 pub fn move_to_end_of_line(
9508 &mut self,
9509 action: &MoveToEndOfLine,
9510 window: &mut Window,
9511 cx: &mut Context<Self>,
9512 ) {
9513 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9514 s.move_cursors_with(|map, head, _| {
9515 (
9516 movement::line_end(map, head, action.stop_at_soft_wraps),
9517 SelectionGoal::None,
9518 )
9519 });
9520 })
9521 }
9522
9523 pub fn select_to_end_of_line(
9524 &mut self,
9525 action: &SelectToEndOfLine,
9526 window: &mut Window,
9527 cx: &mut Context<Self>,
9528 ) {
9529 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9530 s.move_heads_with(|map, head, _| {
9531 (
9532 movement::line_end(map, head, action.stop_at_soft_wraps),
9533 SelectionGoal::None,
9534 )
9535 });
9536 })
9537 }
9538
9539 pub fn delete_to_end_of_line(
9540 &mut self,
9541 _: &DeleteToEndOfLine,
9542 window: &mut Window,
9543 cx: &mut Context<Self>,
9544 ) {
9545 self.transact(window, cx, |this, window, cx| {
9546 this.select_to_end_of_line(
9547 &SelectToEndOfLine {
9548 stop_at_soft_wraps: false,
9549 },
9550 window,
9551 cx,
9552 );
9553 this.delete(&Delete, window, cx);
9554 });
9555 }
9556
9557 pub fn cut_to_end_of_line(
9558 &mut self,
9559 _: &CutToEndOfLine,
9560 window: &mut Window,
9561 cx: &mut Context<Self>,
9562 ) {
9563 self.transact(window, cx, |this, window, cx| {
9564 this.select_to_end_of_line(
9565 &SelectToEndOfLine {
9566 stop_at_soft_wraps: false,
9567 },
9568 window,
9569 cx,
9570 );
9571 this.cut(&Cut, window, cx);
9572 });
9573 }
9574
9575 pub fn move_to_start_of_paragraph(
9576 &mut self,
9577 _: &MoveToStartOfParagraph,
9578 window: &mut Window,
9579 cx: &mut Context<Self>,
9580 ) {
9581 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9582 cx.propagate();
9583 return;
9584 }
9585
9586 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9587 s.move_with(|map, selection| {
9588 selection.collapse_to(
9589 movement::start_of_paragraph(map, selection.head(), 1),
9590 SelectionGoal::None,
9591 )
9592 });
9593 })
9594 }
9595
9596 pub fn move_to_end_of_paragraph(
9597 &mut self,
9598 _: &MoveToEndOfParagraph,
9599 window: &mut Window,
9600 cx: &mut Context<Self>,
9601 ) {
9602 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9603 cx.propagate();
9604 return;
9605 }
9606
9607 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9608 s.move_with(|map, selection| {
9609 selection.collapse_to(
9610 movement::end_of_paragraph(map, selection.head(), 1),
9611 SelectionGoal::None,
9612 )
9613 });
9614 })
9615 }
9616
9617 pub fn select_to_start_of_paragraph(
9618 &mut self,
9619 _: &SelectToStartOfParagraph,
9620 window: &mut Window,
9621 cx: &mut Context<Self>,
9622 ) {
9623 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9624 cx.propagate();
9625 return;
9626 }
9627
9628 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9629 s.move_heads_with(|map, head, _| {
9630 (
9631 movement::start_of_paragraph(map, head, 1),
9632 SelectionGoal::None,
9633 )
9634 });
9635 })
9636 }
9637
9638 pub fn select_to_end_of_paragraph(
9639 &mut self,
9640 _: &SelectToEndOfParagraph,
9641 window: &mut Window,
9642 cx: &mut Context<Self>,
9643 ) {
9644 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9645 cx.propagate();
9646 return;
9647 }
9648
9649 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9650 s.move_heads_with(|map, head, _| {
9651 (
9652 movement::end_of_paragraph(map, head, 1),
9653 SelectionGoal::None,
9654 )
9655 });
9656 })
9657 }
9658
9659 pub fn move_to_start_of_excerpt(
9660 &mut self,
9661 _: &MoveToStartOfExcerpt,
9662 window: &mut Window,
9663 cx: &mut Context<Self>,
9664 ) {
9665 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9666 cx.propagate();
9667 return;
9668 }
9669
9670 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9671 s.move_with(|map, selection| {
9672 selection.collapse_to(
9673 movement::start_of_excerpt(
9674 map,
9675 selection.head(),
9676 workspace::searchable::Direction::Prev,
9677 ),
9678 SelectionGoal::None,
9679 )
9680 });
9681 })
9682 }
9683
9684 pub fn move_to_end_of_excerpt(
9685 &mut self,
9686 _: &MoveToEndOfExcerpt,
9687 window: &mut Window,
9688 cx: &mut Context<Self>,
9689 ) {
9690 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9691 cx.propagate();
9692 return;
9693 }
9694
9695 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9696 s.move_with(|map, selection| {
9697 selection.collapse_to(
9698 movement::end_of_excerpt(
9699 map,
9700 selection.head(),
9701 workspace::searchable::Direction::Next,
9702 ),
9703 SelectionGoal::None,
9704 )
9705 });
9706 })
9707 }
9708
9709 pub fn select_to_start_of_excerpt(
9710 &mut self,
9711 _: &SelectToStartOfExcerpt,
9712 window: &mut Window,
9713 cx: &mut Context<Self>,
9714 ) {
9715 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9716 cx.propagate();
9717 return;
9718 }
9719
9720 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9721 s.move_heads_with(|map, head, _| {
9722 (
9723 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9724 SelectionGoal::None,
9725 )
9726 });
9727 })
9728 }
9729
9730 pub fn select_to_end_of_excerpt(
9731 &mut self,
9732 _: &SelectToEndOfExcerpt,
9733 window: &mut Window,
9734 cx: &mut Context<Self>,
9735 ) {
9736 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9737 cx.propagate();
9738 return;
9739 }
9740
9741 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9742 s.move_heads_with(|map, head, _| {
9743 (
9744 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9745 SelectionGoal::None,
9746 )
9747 });
9748 })
9749 }
9750
9751 pub fn move_to_beginning(
9752 &mut self,
9753 _: &MoveToBeginning,
9754 window: &mut Window,
9755 cx: &mut Context<Self>,
9756 ) {
9757 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9758 cx.propagate();
9759 return;
9760 }
9761
9762 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9763 s.select_ranges(vec![0..0]);
9764 });
9765 }
9766
9767 pub fn select_to_beginning(
9768 &mut self,
9769 _: &SelectToBeginning,
9770 window: &mut Window,
9771 cx: &mut Context<Self>,
9772 ) {
9773 let mut selection = self.selections.last::<Point>(cx);
9774 selection.set_head(Point::zero(), SelectionGoal::None);
9775
9776 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9777 s.select(vec![selection]);
9778 });
9779 }
9780
9781 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9782 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9783 cx.propagate();
9784 return;
9785 }
9786
9787 let cursor = self.buffer.read(cx).read(cx).len();
9788 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9789 s.select_ranges(vec![cursor..cursor])
9790 });
9791 }
9792
9793 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9794 self.nav_history = nav_history;
9795 }
9796
9797 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9798 self.nav_history.as_ref()
9799 }
9800
9801 fn push_to_nav_history(
9802 &mut self,
9803 cursor_anchor: Anchor,
9804 new_position: Option<Point>,
9805 cx: &mut Context<Self>,
9806 ) {
9807 if let Some(nav_history) = self.nav_history.as_mut() {
9808 let buffer = self.buffer.read(cx).read(cx);
9809 let cursor_position = cursor_anchor.to_point(&buffer);
9810 let scroll_state = self.scroll_manager.anchor();
9811 let scroll_top_row = scroll_state.top_row(&buffer);
9812 drop(buffer);
9813
9814 if let Some(new_position) = new_position {
9815 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9816 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9817 return;
9818 }
9819 }
9820
9821 nav_history.push(
9822 Some(NavigationData {
9823 cursor_anchor,
9824 cursor_position,
9825 scroll_anchor: scroll_state,
9826 scroll_top_row,
9827 }),
9828 cx,
9829 );
9830 }
9831 }
9832
9833 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9834 let buffer = self.buffer.read(cx).snapshot(cx);
9835 let mut selection = self.selections.first::<usize>(cx);
9836 selection.set_head(buffer.len(), SelectionGoal::None);
9837 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9838 s.select(vec![selection]);
9839 });
9840 }
9841
9842 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9843 let end = self.buffer.read(cx).read(cx).len();
9844 self.change_selections(None, window, cx, |s| {
9845 s.select_ranges(vec![0..end]);
9846 });
9847 }
9848
9849 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9850 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9851 let mut selections = self.selections.all::<Point>(cx);
9852 let max_point = display_map.buffer_snapshot.max_point();
9853 for selection in &mut selections {
9854 let rows = selection.spanned_rows(true, &display_map);
9855 selection.start = Point::new(rows.start.0, 0);
9856 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
9857 selection.reversed = false;
9858 }
9859 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9860 s.select(selections);
9861 });
9862 }
9863
9864 pub fn split_selection_into_lines(
9865 &mut self,
9866 _: &SplitSelectionIntoLines,
9867 window: &mut Window,
9868 cx: &mut Context<Self>,
9869 ) {
9870 let selections = self
9871 .selections
9872 .all::<Point>(cx)
9873 .into_iter()
9874 .map(|selection| selection.start..selection.end)
9875 .collect::<Vec<_>>();
9876 self.unfold_ranges(&selections, true, true, cx);
9877
9878 let mut new_selection_ranges = Vec::new();
9879 {
9880 let buffer = self.buffer.read(cx).read(cx);
9881 for selection in selections {
9882 for row in selection.start.row..selection.end.row {
9883 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
9884 new_selection_ranges.push(cursor..cursor);
9885 }
9886
9887 let is_multiline_selection = selection.start.row != selection.end.row;
9888 // Don't insert last one if it's a multi-line selection ending at the start of a line,
9889 // so this action feels more ergonomic when paired with other selection operations
9890 let should_skip_last = is_multiline_selection && selection.end.column == 0;
9891 if !should_skip_last {
9892 new_selection_ranges.push(selection.end..selection.end);
9893 }
9894 }
9895 }
9896 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9897 s.select_ranges(new_selection_ranges);
9898 });
9899 }
9900
9901 pub fn add_selection_above(
9902 &mut self,
9903 _: &AddSelectionAbove,
9904 window: &mut Window,
9905 cx: &mut Context<Self>,
9906 ) {
9907 self.add_selection(true, window, cx);
9908 }
9909
9910 pub fn add_selection_below(
9911 &mut self,
9912 _: &AddSelectionBelow,
9913 window: &mut Window,
9914 cx: &mut Context<Self>,
9915 ) {
9916 self.add_selection(false, window, cx);
9917 }
9918
9919 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
9920 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9921 let mut selections = self.selections.all::<Point>(cx);
9922 let text_layout_details = self.text_layout_details(window);
9923 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
9924 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
9925 let range = oldest_selection.display_range(&display_map).sorted();
9926
9927 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
9928 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
9929 let positions = start_x.min(end_x)..start_x.max(end_x);
9930
9931 selections.clear();
9932 let mut stack = Vec::new();
9933 for row in range.start.row().0..=range.end.row().0 {
9934 if let Some(selection) = self.selections.build_columnar_selection(
9935 &display_map,
9936 DisplayRow(row),
9937 &positions,
9938 oldest_selection.reversed,
9939 &text_layout_details,
9940 ) {
9941 stack.push(selection.id);
9942 selections.push(selection);
9943 }
9944 }
9945
9946 if above {
9947 stack.reverse();
9948 }
9949
9950 AddSelectionsState { above, stack }
9951 });
9952
9953 let last_added_selection = *state.stack.last().unwrap();
9954 let mut new_selections = Vec::new();
9955 if above == state.above {
9956 let end_row = if above {
9957 DisplayRow(0)
9958 } else {
9959 display_map.max_point().row()
9960 };
9961
9962 'outer: for selection in selections {
9963 if selection.id == last_added_selection {
9964 let range = selection.display_range(&display_map).sorted();
9965 debug_assert_eq!(range.start.row(), range.end.row());
9966 let mut row = range.start.row();
9967 let positions =
9968 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
9969 px(start)..px(end)
9970 } else {
9971 let start_x =
9972 display_map.x_for_display_point(range.start, &text_layout_details);
9973 let end_x =
9974 display_map.x_for_display_point(range.end, &text_layout_details);
9975 start_x.min(end_x)..start_x.max(end_x)
9976 };
9977
9978 while row != end_row {
9979 if above {
9980 row.0 -= 1;
9981 } else {
9982 row.0 += 1;
9983 }
9984
9985 if let Some(new_selection) = self.selections.build_columnar_selection(
9986 &display_map,
9987 row,
9988 &positions,
9989 selection.reversed,
9990 &text_layout_details,
9991 ) {
9992 state.stack.push(new_selection.id);
9993 if above {
9994 new_selections.push(new_selection);
9995 new_selections.push(selection);
9996 } else {
9997 new_selections.push(selection);
9998 new_selections.push(new_selection);
9999 }
10000
10001 continue 'outer;
10002 }
10003 }
10004 }
10005
10006 new_selections.push(selection);
10007 }
10008 } else {
10009 new_selections = selections;
10010 new_selections.retain(|s| s.id != last_added_selection);
10011 state.stack.pop();
10012 }
10013
10014 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10015 s.select(new_selections);
10016 });
10017 if state.stack.len() > 1 {
10018 self.add_selections_state = Some(state);
10019 }
10020 }
10021
10022 pub fn select_next_match_internal(
10023 &mut self,
10024 display_map: &DisplaySnapshot,
10025 replace_newest: bool,
10026 autoscroll: Option<Autoscroll>,
10027 window: &mut Window,
10028 cx: &mut Context<Self>,
10029 ) -> Result<()> {
10030 fn select_next_match_ranges(
10031 this: &mut Editor,
10032 range: Range<usize>,
10033 replace_newest: bool,
10034 auto_scroll: Option<Autoscroll>,
10035 window: &mut Window,
10036 cx: &mut Context<Editor>,
10037 ) {
10038 this.unfold_ranges(&[range.clone()], false, true, cx);
10039 this.change_selections(auto_scroll, window, cx, |s| {
10040 if replace_newest {
10041 s.delete(s.newest_anchor().id);
10042 }
10043 s.insert_range(range.clone());
10044 });
10045 }
10046
10047 let buffer = &display_map.buffer_snapshot;
10048 let mut selections = self.selections.all::<usize>(cx);
10049 if let Some(mut select_next_state) = self.select_next_state.take() {
10050 let query = &select_next_state.query;
10051 if !select_next_state.done {
10052 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10053 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10054 let mut next_selected_range = None;
10055
10056 let bytes_after_last_selection =
10057 buffer.bytes_in_range(last_selection.end..buffer.len());
10058 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10059 let query_matches = query
10060 .stream_find_iter(bytes_after_last_selection)
10061 .map(|result| (last_selection.end, result))
10062 .chain(
10063 query
10064 .stream_find_iter(bytes_before_first_selection)
10065 .map(|result| (0, result)),
10066 );
10067
10068 for (start_offset, query_match) in query_matches {
10069 let query_match = query_match.unwrap(); // can only fail due to I/O
10070 let offset_range =
10071 start_offset + query_match.start()..start_offset + query_match.end();
10072 let display_range = offset_range.start.to_display_point(display_map)
10073 ..offset_range.end.to_display_point(display_map);
10074
10075 if !select_next_state.wordwise
10076 || (!movement::is_inside_word(display_map, display_range.start)
10077 && !movement::is_inside_word(display_map, display_range.end))
10078 {
10079 // TODO: This is n^2, because we might check all the selections
10080 if !selections
10081 .iter()
10082 .any(|selection| selection.range().overlaps(&offset_range))
10083 {
10084 next_selected_range = Some(offset_range);
10085 break;
10086 }
10087 }
10088 }
10089
10090 if let Some(next_selected_range) = next_selected_range {
10091 select_next_match_ranges(
10092 self,
10093 next_selected_range,
10094 replace_newest,
10095 autoscroll,
10096 window,
10097 cx,
10098 );
10099 } else {
10100 select_next_state.done = true;
10101 }
10102 }
10103
10104 self.select_next_state = Some(select_next_state);
10105 } else {
10106 let mut only_carets = true;
10107 let mut same_text_selected = true;
10108 let mut selected_text = None;
10109
10110 let mut selections_iter = selections.iter().peekable();
10111 while let Some(selection) = selections_iter.next() {
10112 if selection.start != selection.end {
10113 only_carets = false;
10114 }
10115
10116 if same_text_selected {
10117 if selected_text.is_none() {
10118 selected_text =
10119 Some(buffer.text_for_range(selection.range()).collect::<String>());
10120 }
10121
10122 if let Some(next_selection) = selections_iter.peek() {
10123 if next_selection.range().len() == selection.range().len() {
10124 let next_selected_text = buffer
10125 .text_for_range(next_selection.range())
10126 .collect::<String>();
10127 if Some(next_selected_text) != selected_text {
10128 same_text_selected = false;
10129 selected_text = None;
10130 }
10131 } else {
10132 same_text_selected = false;
10133 selected_text = None;
10134 }
10135 }
10136 }
10137 }
10138
10139 if only_carets {
10140 for selection in &mut selections {
10141 let word_range = movement::surrounding_word(
10142 display_map,
10143 selection.start.to_display_point(display_map),
10144 );
10145 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10146 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10147 selection.goal = SelectionGoal::None;
10148 selection.reversed = false;
10149 select_next_match_ranges(
10150 self,
10151 selection.start..selection.end,
10152 replace_newest,
10153 autoscroll,
10154 window,
10155 cx,
10156 );
10157 }
10158
10159 if selections.len() == 1 {
10160 let selection = selections
10161 .last()
10162 .expect("ensured that there's only one selection");
10163 let query = buffer
10164 .text_for_range(selection.start..selection.end)
10165 .collect::<String>();
10166 let is_empty = query.is_empty();
10167 let select_state = SelectNextState {
10168 query: AhoCorasick::new(&[query])?,
10169 wordwise: true,
10170 done: is_empty,
10171 };
10172 self.select_next_state = Some(select_state);
10173 } else {
10174 self.select_next_state = None;
10175 }
10176 } else if let Some(selected_text) = selected_text {
10177 self.select_next_state = Some(SelectNextState {
10178 query: AhoCorasick::new(&[selected_text])?,
10179 wordwise: false,
10180 done: false,
10181 });
10182 self.select_next_match_internal(
10183 display_map,
10184 replace_newest,
10185 autoscroll,
10186 window,
10187 cx,
10188 )?;
10189 }
10190 }
10191 Ok(())
10192 }
10193
10194 pub fn select_all_matches(
10195 &mut self,
10196 _action: &SelectAllMatches,
10197 window: &mut Window,
10198 cx: &mut Context<Self>,
10199 ) -> Result<()> {
10200 self.push_to_selection_history();
10201 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10202
10203 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10204 let Some(select_next_state) = self.select_next_state.as_mut() else {
10205 return Ok(());
10206 };
10207 if select_next_state.done {
10208 return Ok(());
10209 }
10210
10211 let mut new_selections = self.selections.all::<usize>(cx);
10212
10213 let buffer = &display_map.buffer_snapshot;
10214 let query_matches = select_next_state
10215 .query
10216 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10217
10218 for query_match in query_matches {
10219 let query_match = query_match.unwrap(); // can only fail due to I/O
10220 let offset_range = query_match.start()..query_match.end();
10221 let display_range = offset_range.start.to_display_point(&display_map)
10222 ..offset_range.end.to_display_point(&display_map);
10223
10224 if !select_next_state.wordwise
10225 || (!movement::is_inside_word(&display_map, display_range.start)
10226 && !movement::is_inside_word(&display_map, display_range.end))
10227 {
10228 self.selections.change_with(cx, |selections| {
10229 new_selections.push(Selection {
10230 id: selections.new_selection_id(),
10231 start: offset_range.start,
10232 end: offset_range.end,
10233 reversed: false,
10234 goal: SelectionGoal::None,
10235 });
10236 });
10237 }
10238 }
10239
10240 new_selections.sort_by_key(|selection| selection.start);
10241 let mut ix = 0;
10242 while ix + 1 < new_selections.len() {
10243 let current_selection = &new_selections[ix];
10244 let next_selection = &new_selections[ix + 1];
10245 if current_selection.range().overlaps(&next_selection.range()) {
10246 if current_selection.id < next_selection.id {
10247 new_selections.remove(ix + 1);
10248 } else {
10249 new_selections.remove(ix);
10250 }
10251 } else {
10252 ix += 1;
10253 }
10254 }
10255
10256 let reversed = self.selections.oldest::<usize>(cx).reversed;
10257
10258 for selection in new_selections.iter_mut() {
10259 selection.reversed = reversed;
10260 }
10261
10262 select_next_state.done = true;
10263 self.unfold_ranges(
10264 &new_selections
10265 .iter()
10266 .map(|selection| selection.range())
10267 .collect::<Vec<_>>(),
10268 false,
10269 false,
10270 cx,
10271 );
10272 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10273 selections.select(new_selections)
10274 });
10275
10276 Ok(())
10277 }
10278
10279 pub fn select_next(
10280 &mut self,
10281 action: &SelectNext,
10282 window: &mut Window,
10283 cx: &mut Context<Self>,
10284 ) -> Result<()> {
10285 self.push_to_selection_history();
10286 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10287 self.select_next_match_internal(
10288 &display_map,
10289 action.replace_newest,
10290 Some(Autoscroll::newest()),
10291 window,
10292 cx,
10293 )?;
10294 Ok(())
10295 }
10296
10297 pub fn select_previous(
10298 &mut self,
10299 action: &SelectPrevious,
10300 window: &mut Window,
10301 cx: &mut Context<Self>,
10302 ) -> Result<()> {
10303 self.push_to_selection_history();
10304 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10305 let buffer = &display_map.buffer_snapshot;
10306 let mut selections = self.selections.all::<usize>(cx);
10307 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10308 let query = &select_prev_state.query;
10309 if !select_prev_state.done {
10310 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10311 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10312 let mut next_selected_range = None;
10313 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10314 let bytes_before_last_selection =
10315 buffer.reversed_bytes_in_range(0..last_selection.start);
10316 let bytes_after_first_selection =
10317 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10318 let query_matches = query
10319 .stream_find_iter(bytes_before_last_selection)
10320 .map(|result| (last_selection.start, result))
10321 .chain(
10322 query
10323 .stream_find_iter(bytes_after_first_selection)
10324 .map(|result| (buffer.len(), result)),
10325 );
10326 for (end_offset, query_match) in query_matches {
10327 let query_match = query_match.unwrap(); // can only fail due to I/O
10328 let offset_range =
10329 end_offset - query_match.end()..end_offset - query_match.start();
10330 let display_range = offset_range.start.to_display_point(&display_map)
10331 ..offset_range.end.to_display_point(&display_map);
10332
10333 if !select_prev_state.wordwise
10334 || (!movement::is_inside_word(&display_map, display_range.start)
10335 && !movement::is_inside_word(&display_map, display_range.end))
10336 {
10337 next_selected_range = Some(offset_range);
10338 break;
10339 }
10340 }
10341
10342 if let Some(next_selected_range) = next_selected_range {
10343 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10344 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10345 if action.replace_newest {
10346 s.delete(s.newest_anchor().id);
10347 }
10348 s.insert_range(next_selected_range);
10349 });
10350 } else {
10351 select_prev_state.done = true;
10352 }
10353 }
10354
10355 self.select_prev_state = Some(select_prev_state);
10356 } else {
10357 let mut only_carets = true;
10358 let mut same_text_selected = true;
10359 let mut selected_text = None;
10360
10361 let mut selections_iter = selections.iter().peekable();
10362 while let Some(selection) = selections_iter.next() {
10363 if selection.start != selection.end {
10364 only_carets = false;
10365 }
10366
10367 if same_text_selected {
10368 if selected_text.is_none() {
10369 selected_text =
10370 Some(buffer.text_for_range(selection.range()).collect::<String>());
10371 }
10372
10373 if let Some(next_selection) = selections_iter.peek() {
10374 if next_selection.range().len() == selection.range().len() {
10375 let next_selected_text = buffer
10376 .text_for_range(next_selection.range())
10377 .collect::<String>();
10378 if Some(next_selected_text) != selected_text {
10379 same_text_selected = false;
10380 selected_text = None;
10381 }
10382 } else {
10383 same_text_selected = false;
10384 selected_text = None;
10385 }
10386 }
10387 }
10388 }
10389
10390 if only_carets {
10391 for selection in &mut selections {
10392 let word_range = movement::surrounding_word(
10393 &display_map,
10394 selection.start.to_display_point(&display_map),
10395 );
10396 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10397 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10398 selection.goal = SelectionGoal::None;
10399 selection.reversed = false;
10400 }
10401 if selections.len() == 1 {
10402 let selection = selections
10403 .last()
10404 .expect("ensured that there's only one selection");
10405 let query = buffer
10406 .text_for_range(selection.start..selection.end)
10407 .collect::<String>();
10408 let is_empty = query.is_empty();
10409 let select_state = SelectNextState {
10410 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10411 wordwise: true,
10412 done: is_empty,
10413 };
10414 self.select_prev_state = Some(select_state);
10415 } else {
10416 self.select_prev_state = None;
10417 }
10418
10419 self.unfold_ranges(
10420 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10421 false,
10422 true,
10423 cx,
10424 );
10425 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10426 s.select(selections);
10427 });
10428 } else if let Some(selected_text) = selected_text {
10429 self.select_prev_state = Some(SelectNextState {
10430 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10431 wordwise: false,
10432 done: false,
10433 });
10434 self.select_previous(action, window, cx)?;
10435 }
10436 }
10437 Ok(())
10438 }
10439
10440 pub fn toggle_comments(
10441 &mut self,
10442 action: &ToggleComments,
10443 window: &mut Window,
10444 cx: &mut Context<Self>,
10445 ) {
10446 if self.read_only(cx) {
10447 return;
10448 }
10449 let text_layout_details = &self.text_layout_details(window);
10450 self.transact(window, cx, |this, window, cx| {
10451 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10452 let mut edits = Vec::new();
10453 let mut selection_edit_ranges = Vec::new();
10454 let mut last_toggled_row = None;
10455 let snapshot = this.buffer.read(cx).read(cx);
10456 let empty_str: Arc<str> = Arc::default();
10457 let mut suffixes_inserted = Vec::new();
10458 let ignore_indent = action.ignore_indent;
10459
10460 fn comment_prefix_range(
10461 snapshot: &MultiBufferSnapshot,
10462 row: MultiBufferRow,
10463 comment_prefix: &str,
10464 comment_prefix_whitespace: &str,
10465 ignore_indent: bool,
10466 ) -> Range<Point> {
10467 let indent_size = if ignore_indent {
10468 0
10469 } else {
10470 snapshot.indent_size_for_line(row).len
10471 };
10472
10473 let start = Point::new(row.0, indent_size);
10474
10475 let mut line_bytes = snapshot
10476 .bytes_in_range(start..snapshot.max_point())
10477 .flatten()
10478 .copied();
10479
10480 // If this line currently begins with the line comment prefix, then record
10481 // the range containing the prefix.
10482 if line_bytes
10483 .by_ref()
10484 .take(comment_prefix.len())
10485 .eq(comment_prefix.bytes())
10486 {
10487 // Include any whitespace that matches the comment prefix.
10488 let matching_whitespace_len = line_bytes
10489 .zip(comment_prefix_whitespace.bytes())
10490 .take_while(|(a, b)| a == b)
10491 .count() as u32;
10492 let end = Point::new(
10493 start.row,
10494 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10495 );
10496 start..end
10497 } else {
10498 start..start
10499 }
10500 }
10501
10502 fn comment_suffix_range(
10503 snapshot: &MultiBufferSnapshot,
10504 row: MultiBufferRow,
10505 comment_suffix: &str,
10506 comment_suffix_has_leading_space: bool,
10507 ) -> Range<Point> {
10508 let end = Point::new(row.0, snapshot.line_len(row));
10509 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10510
10511 let mut line_end_bytes = snapshot
10512 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10513 .flatten()
10514 .copied();
10515
10516 let leading_space_len = if suffix_start_column > 0
10517 && line_end_bytes.next() == Some(b' ')
10518 && comment_suffix_has_leading_space
10519 {
10520 1
10521 } else {
10522 0
10523 };
10524
10525 // If this line currently begins with the line comment prefix, then record
10526 // the range containing the prefix.
10527 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10528 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10529 start..end
10530 } else {
10531 end..end
10532 }
10533 }
10534
10535 // TODO: Handle selections that cross excerpts
10536 for selection in &mut selections {
10537 let start_column = snapshot
10538 .indent_size_for_line(MultiBufferRow(selection.start.row))
10539 .len;
10540 let language = if let Some(language) =
10541 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10542 {
10543 language
10544 } else {
10545 continue;
10546 };
10547
10548 selection_edit_ranges.clear();
10549
10550 // If multiple selections contain a given row, avoid processing that
10551 // row more than once.
10552 let mut start_row = MultiBufferRow(selection.start.row);
10553 if last_toggled_row == Some(start_row) {
10554 start_row = start_row.next_row();
10555 }
10556 let end_row =
10557 if selection.end.row > selection.start.row && selection.end.column == 0 {
10558 MultiBufferRow(selection.end.row - 1)
10559 } else {
10560 MultiBufferRow(selection.end.row)
10561 };
10562 last_toggled_row = Some(end_row);
10563
10564 if start_row > end_row {
10565 continue;
10566 }
10567
10568 // If the language has line comments, toggle those.
10569 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10570
10571 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10572 if ignore_indent {
10573 full_comment_prefixes = full_comment_prefixes
10574 .into_iter()
10575 .map(|s| Arc::from(s.trim_end()))
10576 .collect();
10577 }
10578
10579 if !full_comment_prefixes.is_empty() {
10580 let first_prefix = full_comment_prefixes
10581 .first()
10582 .expect("prefixes is non-empty");
10583 let prefix_trimmed_lengths = full_comment_prefixes
10584 .iter()
10585 .map(|p| p.trim_end_matches(' ').len())
10586 .collect::<SmallVec<[usize; 4]>>();
10587
10588 let mut all_selection_lines_are_comments = true;
10589
10590 for row in start_row.0..=end_row.0 {
10591 let row = MultiBufferRow(row);
10592 if start_row < end_row && snapshot.is_line_blank(row) {
10593 continue;
10594 }
10595
10596 let prefix_range = full_comment_prefixes
10597 .iter()
10598 .zip(prefix_trimmed_lengths.iter().copied())
10599 .map(|(prefix, trimmed_prefix_len)| {
10600 comment_prefix_range(
10601 snapshot.deref(),
10602 row,
10603 &prefix[..trimmed_prefix_len],
10604 &prefix[trimmed_prefix_len..],
10605 ignore_indent,
10606 )
10607 })
10608 .max_by_key(|range| range.end.column - range.start.column)
10609 .expect("prefixes is non-empty");
10610
10611 if prefix_range.is_empty() {
10612 all_selection_lines_are_comments = false;
10613 }
10614
10615 selection_edit_ranges.push(prefix_range);
10616 }
10617
10618 if all_selection_lines_are_comments {
10619 edits.extend(
10620 selection_edit_ranges
10621 .iter()
10622 .cloned()
10623 .map(|range| (range, empty_str.clone())),
10624 );
10625 } else {
10626 let min_column = selection_edit_ranges
10627 .iter()
10628 .map(|range| range.start.column)
10629 .min()
10630 .unwrap_or(0);
10631 edits.extend(selection_edit_ranges.iter().map(|range| {
10632 let position = Point::new(range.start.row, min_column);
10633 (position..position, first_prefix.clone())
10634 }));
10635 }
10636 } else if let Some((full_comment_prefix, comment_suffix)) =
10637 language.block_comment_delimiters()
10638 {
10639 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10640 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10641 let prefix_range = comment_prefix_range(
10642 snapshot.deref(),
10643 start_row,
10644 comment_prefix,
10645 comment_prefix_whitespace,
10646 ignore_indent,
10647 );
10648 let suffix_range = comment_suffix_range(
10649 snapshot.deref(),
10650 end_row,
10651 comment_suffix.trim_start_matches(' '),
10652 comment_suffix.starts_with(' '),
10653 );
10654
10655 if prefix_range.is_empty() || suffix_range.is_empty() {
10656 edits.push((
10657 prefix_range.start..prefix_range.start,
10658 full_comment_prefix.clone(),
10659 ));
10660 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10661 suffixes_inserted.push((end_row, comment_suffix.len()));
10662 } else {
10663 edits.push((prefix_range, empty_str.clone()));
10664 edits.push((suffix_range, empty_str.clone()));
10665 }
10666 } else {
10667 continue;
10668 }
10669 }
10670
10671 drop(snapshot);
10672 this.buffer.update(cx, |buffer, cx| {
10673 buffer.edit(edits, None, cx);
10674 });
10675
10676 // Adjust selections so that they end before any comment suffixes that
10677 // were inserted.
10678 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10679 let mut selections = this.selections.all::<Point>(cx);
10680 let snapshot = this.buffer.read(cx).read(cx);
10681 for selection in &mut selections {
10682 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10683 match row.cmp(&MultiBufferRow(selection.end.row)) {
10684 Ordering::Less => {
10685 suffixes_inserted.next();
10686 continue;
10687 }
10688 Ordering::Greater => break,
10689 Ordering::Equal => {
10690 if selection.end.column == snapshot.line_len(row) {
10691 if selection.is_empty() {
10692 selection.start.column -= suffix_len as u32;
10693 }
10694 selection.end.column -= suffix_len as u32;
10695 }
10696 break;
10697 }
10698 }
10699 }
10700 }
10701
10702 drop(snapshot);
10703 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10704 s.select(selections)
10705 });
10706
10707 let selections = this.selections.all::<Point>(cx);
10708 let selections_on_single_row = selections.windows(2).all(|selections| {
10709 selections[0].start.row == selections[1].start.row
10710 && selections[0].end.row == selections[1].end.row
10711 && selections[0].start.row == selections[0].end.row
10712 });
10713 let selections_selecting = selections
10714 .iter()
10715 .any(|selection| selection.start != selection.end);
10716 let advance_downwards = action.advance_downwards
10717 && selections_on_single_row
10718 && !selections_selecting
10719 && !matches!(this.mode, EditorMode::SingleLine { .. });
10720
10721 if advance_downwards {
10722 let snapshot = this.buffer.read(cx).snapshot(cx);
10723
10724 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10725 s.move_cursors_with(|display_snapshot, display_point, _| {
10726 let mut point = display_point.to_point(display_snapshot);
10727 point.row += 1;
10728 point = snapshot.clip_point(point, Bias::Left);
10729 let display_point = point.to_display_point(display_snapshot);
10730 let goal = SelectionGoal::HorizontalPosition(
10731 display_snapshot
10732 .x_for_display_point(display_point, text_layout_details)
10733 .into(),
10734 );
10735 (display_point, goal)
10736 })
10737 });
10738 }
10739 });
10740 }
10741
10742 pub fn select_enclosing_symbol(
10743 &mut self,
10744 _: &SelectEnclosingSymbol,
10745 window: &mut Window,
10746 cx: &mut Context<Self>,
10747 ) {
10748 let buffer = self.buffer.read(cx).snapshot(cx);
10749 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10750
10751 fn update_selection(
10752 selection: &Selection<usize>,
10753 buffer_snap: &MultiBufferSnapshot,
10754 ) -> Option<Selection<usize>> {
10755 let cursor = selection.head();
10756 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10757 for symbol in symbols.iter().rev() {
10758 let start = symbol.range.start.to_offset(buffer_snap);
10759 let end = symbol.range.end.to_offset(buffer_snap);
10760 let new_range = start..end;
10761 if start < selection.start || end > selection.end {
10762 return Some(Selection {
10763 id: selection.id,
10764 start: new_range.start,
10765 end: new_range.end,
10766 goal: SelectionGoal::None,
10767 reversed: selection.reversed,
10768 });
10769 }
10770 }
10771 None
10772 }
10773
10774 let mut selected_larger_symbol = false;
10775 let new_selections = old_selections
10776 .iter()
10777 .map(|selection| match update_selection(selection, &buffer) {
10778 Some(new_selection) => {
10779 if new_selection.range() != selection.range() {
10780 selected_larger_symbol = true;
10781 }
10782 new_selection
10783 }
10784 None => selection.clone(),
10785 })
10786 .collect::<Vec<_>>();
10787
10788 if selected_larger_symbol {
10789 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10790 s.select(new_selections);
10791 });
10792 }
10793 }
10794
10795 pub fn select_larger_syntax_node(
10796 &mut self,
10797 _: &SelectLargerSyntaxNode,
10798 window: &mut Window,
10799 cx: &mut Context<Self>,
10800 ) {
10801 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10802 let buffer = self.buffer.read(cx).snapshot(cx);
10803 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10804
10805 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10806 let mut selected_larger_node = false;
10807 let new_selections = old_selections
10808 .iter()
10809 .map(|selection| {
10810 let old_range = selection.start..selection.end;
10811 let mut new_range = old_range.clone();
10812 let mut new_node = None;
10813 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10814 {
10815 new_node = Some(node);
10816 new_range = match containing_range {
10817 MultiOrSingleBufferOffsetRange::Single(_) => break,
10818 MultiOrSingleBufferOffsetRange::Multi(range) => range,
10819 };
10820 if !display_map.intersects_fold(new_range.start)
10821 && !display_map.intersects_fold(new_range.end)
10822 {
10823 break;
10824 }
10825 }
10826
10827 if let Some(node) = new_node {
10828 // Log the ancestor, to support using this action as a way to explore TreeSitter
10829 // nodes. Parent and grandparent are also logged because this operation will not
10830 // visit nodes that have the same range as their parent.
10831 log::info!("Node: {node:?}");
10832 let parent = node.parent();
10833 log::info!("Parent: {parent:?}");
10834 let grandparent = parent.and_then(|x| x.parent());
10835 log::info!("Grandparent: {grandparent:?}");
10836 }
10837
10838 selected_larger_node |= new_range != old_range;
10839 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 .collect::<Vec<_>>();
10848
10849 if selected_larger_node {
10850 stack.push(old_selections);
10851 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10852 s.select(new_selections);
10853 });
10854 }
10855 self.select_larger_syntax_node_stack = stack;
10856 }
10857
10858 pub fn select_smaller_syntax_node(
10859 &mut self,
10860 _: &SelectSmallerSyntaxNode,
10861 window: &mut Window,
10862 cx: &mut Context<Self>,
10863 ) {
10864 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10865 if let Some(selections) = stack.pop() {
10866 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10867 s.select(selections.to_vec());
10868 });
10869 }
10870 self.select_larger_syntax_node_stack = stack;
10871 }
10872
10873 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10874 if !EditorSettings::get_global(cx).gutter.runnables {
10875 self.clear_tasks();
10876 return Task::ready(());
10877 }
10878 let project = self.project.as_ref().map(Entity::downgrade);
10879 cx.spawn_in(window, |this, mut cx| async move {
10880 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10881 let Some(project) = project.and_then(|p| p.upgrade()) else {
10882 return;
10883 };
10884 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10885 this.display_map.update(cx, |map, cx| map.snapshot(cx))
10886 }) else {
10887 return;
10888 };
10889
10890 let hide_runnables = project
10891 .update(&mut cx, |project, cx| {
10892 // Do not display any test indicators in non-dev server remote projects.
10893 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10894 })
10895 .unwrap_or(true);
10896 if hide_runnables {
10897 return;
10898 }
10899 let new_rows =
10900 cx.background_spawn({
10901 let snapshot = display_snapshot.clone();
10902 async move {
10903 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10904 }
10905 })
10906 .await;
10907
10908 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10909 this.update(&mut cx, |this, _| {
10910 this.clear_tasks();
10911 for (key, value) in rows {
10912 this.insert_tasks(key, value);
10913 }
10914 })
10915 .ok();
10916 })
10917 }
10918 fn fetch_runnable_ranges(
10919 snapshot: &DisplaySnapshot,
10920 range: Range<Anchor>,
10921 ) -> Vec<language::RunnableRange> {
10922 snapshot.buffer_snapshot.runnable_ranges(range).collect()
10923 }
10924
10925 fn runnable_rows(
10926 project: Entity<Project>,
10927 snapshot: DisplaySnapshot,
10928 runnable_ranges: Vec<RunnableRange>,
10929 mut cx: AsyncWindowContext,
10930 ) -> Vec<((BufferId, u32), RunnableTasks)> {
10931 runnable_ranges
10932 .into_iter()
10933 .filter_map(|mut runnable| {
10934 let tasks = cx
10935 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10936 .ok()?;
10937 if tasks.is_empty() {
10938 return None;
10939 }
10940
10941 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10942
10943 let row = snapshot
10944 .buffer_snapshot
10945 .buffer_line_for_row(MultiBufferRow(point.row))?
10946 .1
10947 .start
10948 .row;
10949
10950 let context_range =
10951 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10952 Some((
10953 (runnable.buffer_id, row),
10954 RunnableTasks {
10955 templates: tasks,
10956 offset: snapshot
10957 .buffer_snapshot
10958 .anchor_before(runnable.run_range.start),
10959 context_range,
10960 column: point.column,
10961 extra_variables: runnable.extra_captures,
10962 },
10963 ))
10964 })
10965 .collect()
10966 }
10967
10968 fn templates_with_tags(
10969 project: &Entity<Project>,
10970 runnable: &mut Runnable,
10971 cx: &mut App,
10972 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10973 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10974 let (worktree_id, file) = project
10975 .buffer_for_id(runnable.buffer, cx)
10976 .and_then(|buffer| buffer.read(cx).file())
10977 .map(|file| (file.worktree_id(cx), file.clone()))
10978 .unzip();
10979
10980 (
10981 project.task_store().read(cx).task_inventory().cloned(),
10982 worktree_id,
10983 file,
10984 )
10985 });
10986
10987 let tags = mem::take(&mut runnable.tags);
10988 let mut tags: Vec<_> = tags
10989 .into_iter()
10990 .flat_map(|tag| {
10991 let tag = tag.0.clone();
10992 inventory
10993 .as_ref()
10994 .into_iter()
10995 .flat_map(|inventory| {
10996 inventory.read(cx).list_tasks(
10997 file.clone(),
10998 Some(runnable.language.clone()),
10999 worktree_id,
11000 cx,
11001 )
11002 })
11003 .filter(move |(_, template)| {
11004 template.tags.iter().any(|source_tag| source_tag == &tag)
11005 })
11006 })
11007 .sorted_by_key(|(kind, _)| kind.to_owned())
11008 .collect();
11009 if let Some((leading_tag_source, _)) = tags.first() {
11010 // Strongest source wins; if we have worktree tag binding, prefer that to
11011 // global and language bindings;
11012 // if we have a global binding, prefer that to language binding.
11013 let first_mismatch = tags
11014 .iter()
11015 .position(|(tag_source, _)| tag_source != leading_tag_source);
11016 if let Some(index) = first_mismatch {
11017 tags.truncate(index);
11018 }
11019 }
11020
11021 tags
11022 }
11023
11024 pub fn move_to_enclosing_bracket(
11025 &mut self,
11026 _: &MoveToEnclosingBracket,
11027 window: &mut Window,
11028 cx: &mut Context<Self>,
11029 ) {
11030 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11031 s.move_offsets_with(|snapshot, selection| {
11032 let Some(enclosing_bracket_ranges) =
11033 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11034 else {
11035 return;
11036 };
11037
11038 let mut best_length = usize::MAX;
11039 let mut best_inside = false;
11040 let mut best_in_bracket_range = false;
11041 let mut best_destination = None;
11042 for (open, close) in enclosing_bracket_ranges {
11043 let close = close.to_inclusive();
11044 let length = close.end() - open.start;
11045 let inside = selection.start >= open.end && selection.end <= *close.start();
11046 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11047 || close.contains(&selection.head());
11048
11049 // If best is next to a bracket and current isn't, skip
11050 if !in_bracket_range && best_in_bracket_range {
11051 continue;
11052 }
11053
11054 // Prefer smaller lengths unless best is inside and current isn't
11055 if length > best_length && (best_inside || !inside) {
11056 continue;
11057 }
11058
11059 best_length = length;
11060 best_inside = inside;
11061 best_in_bracket_range = in_bracket_range;
11062 best_destination = Some(
11063 if close.contains(&selection.start) && close.contains(&selection.end) {
11064 if inside {
11065 open.end
11066 } else {
11067 open.start
11068 }
11069 } else if inside {
11070 *close.start()
11071 } else {
11072 *close.end()
11073 },
11074 );
11075 }
11076
11077 if let Some(destination) = best_destination {
11078 selection.collapse_to(destination, SelectionGoal::None);
11079 }
11080 })
11081 });
11082 }
11083
11084 pub fn undo_selection(
11085 &mut self,
11086 _: &UndoSelection,
11087 window: &mut Window,
11088 cx: &mut Context<Self>,
11089 ) {
11090 self.end_selection(window, cx);
11091 self.selection_history.mode = SelectionHistoryMode::Undoing;
11092 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11093 self.change_selections(None, window, cx, |s| {
11094 s.select_anchors(entry.selections.to_vec())
11095 });
11096 self.select_next_state = entry.select_next_state;
11097 self.select_prev_state = entry.select_prev_state;
11098 self.add_selections_state = entry.add_selections_state;
11099 self.request_autoscroll(Autoscroll::newest(), cx);
11100 }
11101 self.selection_history.mode = SelectionHistoryMode::Normal;
11102 }
11103
11104 pub fn redo_selection(
11105 &mut self,
11106 _: &RedoSelection,
11107 window: &mut Window,
11108 cx: &mut Context<Self>,
11109 ) {
11110 self.end_selection(window, cx);
11111 self.selection_history.mode = SelectionHistoryMode::Redoing;
11112 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11113 self.change_selections(None, window, cx, |s| {
11114 s.select_anchors(entry.selections.to_vec())
11115 });
11116 self.select_next_state = entry.select_next_state;
11117 self.select_prev_state = entry.select_prev_state;
11118 self.add_selections_state = entry.add_selections_state;
11119 self.request_autoscroll(Autoscroll::newest(), cx);
11120 }
11121 self.selection_history.mode = SelectionHistoryMode::Normal;
11122 }
11123
11124 pub fn expand_excerpts(
11125 &mut self,
11126 action: &ExpandExcerpts,
11127 _: &mut Window,
11128 cx: &mut Context<Self>,
11129 ) {
11130 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11131 }
11132
11133 pub fn expand_excerpts_down(
11134 &mut self,
11135 action: &ExpandExcerptsDown,
11136 _: &mut Window,
11137 cx: &mut Context<Self>,
11138 ) {
11139 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11140 }
11141
11142 pub fn expand_excerpts_up(
11143 &mut self,
11144 action: &ExpandExcerptsUp,
11145 _: &mut Window,
11146 cx: &mut Context<Self>,
11147 ) {
11148 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11149 }
11150
11151 pub fn expand_excerpts_for_direction(
11152 &mut self,
11153 lines: u32,
11154 direction: ExpandExcerptDirection,
11155
11156 cx: &mut Context<Self>,
11157 ) {
11158 let selections = self.selections.disjoint_anchors();
11159
11160 let lines = if lines == 0 {
11161 EditorSettings::get_global(cx).expand_excerpt_lines
11162 } else {
11163 lines
11164 };
11165
11166 self.buffer.update(cx, |buffer, cx| {
11167 let snapshot = buffer.snapshot(cx);
11168 let mut excerpt_ids = selections
11169 .iter()
11170 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11171 .collect::<Vec<_>>();
11172 excerpt_ids.sort();
11173 excerpt_ids.dedup();
11174 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11175 })
11176 }
11177
11178 pub fn expand_excerpt(
11179 &mut self,
11180 excerpt: ExcerptId,
11181 direction: ExpandExcerptDirection,
11182 cx: &mut Context<Self>,
11183 ) {
11184 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11185 self.buffer.update(cx, |buffer, cx| {
11186 buffer.expand_excerpts([excerpt], lines, direction, cx)
11187 })
11188 }
11189
11190 pub fn go_to_singleton_buffer_point(
11191 &mut self,
11192 point: Point,
11193 window: &mut Window,
11194 cx: &mut Context<Self>,
11195 ) {
11196 self.go_to_singleton_buffer_range(point..point, window, cx);
11197 }
11198
11199 pub fn go_to_singleton_buffer_range(
11200 &mut self,
11201 range: Range<Point>,
11202 window: &mut Window,
11203 cx: &mut Context<Self>,
11204 ) {
11205 let multibuffer = self.buffer().read(cx);
11206 let Some(buffer) = multibuffer.as_singleton() else {
11207 return;
11208 };
11209 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11210 return;
11211 };
11212 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11213 return;
11214 };
11215 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11216 s.select_anchor_ranges([start..end])
11217 });
11218 }
11219
11220 fn go_to_diagnostic(
11221 &mut self,
11222 _: &GoToDiagnostic,
11223 window: &mut Window,
11224 cx: &mut Context<Self>,
11225 ) {
11226 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11227 }
11228
11229 fn go_to_prev_diagnostic(
11230 &mut self,
11231 _: &GoToPrevDiagnostic,
11232 window: &mut Window,
11233 cx: &mut Context<Self>,
11234 ) {
11235 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11236 }
11237
11238 pub fn go_to_diagnostic_impl(
11239 &mut self,
11240 direction: Direction,
11241 window: &mut Window,
11242 cx: &mut Context<Self>,
11243 ) {
11244 let buffer = self.buffer.read(cx).snapshot(cx);
11245 let selection = self.selections.newest::<usize>(cx);
11246
11247 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11248 if direction == Direction::Next {
11249 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11250 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11251 return;
11252 };
11253 self.activate_diagnostics(
11254 buffer_id,
11255 popover.local_diagnostic.diagnostic.group_id,
11256 window,
11257 cx,
11258 );
11259 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11260 let primary_range_start = active_diagnostics.primary_range.start;
11261 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11262 let mut new_selection = s.newest_anchor().clone();
11263 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11264 s.select_anchors(vec![new_selection.clone()]);
11265 });
11266 self.refresh_inline_completion(false, true, window, cx);
11267 }
11268 return;
11269 }
11270 }
11271
11272 let active_group_id = self
11273 .active_diagnostics
11274 .as_ref()
11275 .map(|active_group| active_group.group_id);
11276 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11277 active_diagnostics
11278 .primary_range
11279 .to_offset(&buffer)
11280 .to_inclusive()
11281 });
11282 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11283 if active_primary_range.contains(&selection.head()) {
11284 *active_primary_range.start()
11285 } else {
11286 selection.head()
11287 }
11288 } else {
11289 selection.head()
11290 };
11291
11292 let snapshot = self.snapshot(window, cx);
11293 let primary_diagnostics_before = buffer
11294 .diagnostics_in_range::<usize>(0..search_start)
11295 .filter(|entry| entry.diagnostic.is_primary)
11296 .filter(|entry| entry.range.start != entry.range.end)
11297 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11298 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11299 .collect::<Vec<_>>();
11300 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11301 primary_diagnostics_before
11302 .iter()
11303 .position(|entry| entry.diagnostic.group_id == active_group_id)
11304 });
11305
11306 let primary_diagnostics_after = buffer
11307 .diagnostics_in_range::<usize>(search_start..buffer.len())
11308 .filter(|entry| entry.diagnostic.is_primary)
11309 .filter(|entry| entry.range.start != entry.range.end)
11310 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11311 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11312 .collect::<Vec<_>>();
11313 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11314 primary_diagnostics_after
11315 .iter()
11316 .enumerate()
11317 .rev()
11318 .find_map(|(i, entry)| {
11319 if entry.diagnostic.group_id == active_group_id {
11320 Some(i)
11321 } else {
11322 None
11323 }
11324 })
11325 });
11326
11327 let next_primary_diagnostic = match direction {
11328 Direction::Prev => primary_diagnostics_before
11329 .iter()
11330 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11331 .rev()
11332 .next(),
11333 Direction::Next => primary_diagnostics_after
11334 .iter()
11335 .skip(
11336 last_same_group_diagnostic_after
11337 .map(|index| index + 1)
11338 .unwrap_or(0),
11339 )
11340 .next(),
11341 };
11342
11343 // Cycle around to the start of the buffer, potentially moving back to the start of
11344 // the currently active diagnostic.
11345 let cycle_around = || match direction {
11346 Direction::Prev => primary_diagnostics_after
11347 .iter()
11348 .rev()
11349 .chain(primary_diagnostics_before.iter().rev())
11350 .next(),
11351 Direction::Next => primary_diagnostics_before
11352 .iter()
11353 .chain(primary_diagnostics_after.iter())
11354 .next(),
11355 };
11356
11357 if let Some((primary_range, group_id)) = next_primary_diagnostic
11358 .or_else(cycle_around)
11359 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11360 {
11361 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11362 return;
11363 };
11364 self.activate_diagnostics(buffer_id, group_id, window, cx);
11365 if self.active_diagnostics.is_some() {
11366 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11367 s.select(vec![Selection {
11368 id: selection.id,
11369 start: primary_range.start,
11370 end: primary_range.start,
11371 reversed: false,
11372 goal: SelectionGoal::None,
11373 }]);
11374 });
11375 self.refresh_inline_completion(false, true, window, cx);
11376 }
11377 }
11378 }
11379
11380 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11381 let snapshot = self.snapshot(window, cx);
11382 let selection = self.selections.newest::<Point>(cx);
11383 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
11384 }
11385
11386 fn go_to_hunk_after_position(
11387 &mut self,
11388 snapshot: &EditorSnapshot,
11389 position: Point,
11390 window: &mut Window,
11391 cx: &mut Context<Editor>,
11392 ) -> Option<MultiBufferDiffHunk> {
11393 let mut hunk = snapshot
11394 .buffer_snapshot
11395 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11396 .find(|hunk| hunk.row_range.start.0 > position.row);
11397 if hunk.is_none() {
11398 hunk = snapshot
11399 .buffer_snapshot
11400 .diff_hunks_in_range(Point::zero()..position)
11401 .find(|hunk| hunk.row_range.end.0 < position.row)
11402 }
11403 if let Some(hunk) = &hunk {
11404 let destination = Point::new(hunk.row_range.start.0, 0);
11405 self.unfold_ranges(&[destination..destination], false, false, cx);
11406 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11407 s.select_ranges(vec![destination..destination]);
11408 });
11409 }
11410
11411 hunk
11412 }
11413
11414 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
11415 let snapshot = self.snapshot(window, cx);
11416 let selection = self.selections.newest::<Point>(cx);
11417 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
11418 }
11419
11420 fn go_to_hunk_before_position(
11421 &mut self,
11422 snapshot: &EditorSnapshot,
11423 position: Point,
11424 window: &mut Window,
11425 cx: &mut Context<Editor>,
11426 ) -> Option<MultiBufferDiffHunk> {
11427 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
11428 if hunk.is_none() {
11429 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
11430 }
11431 if let Some(hunk) = &hunk {
11432 let destination = Point::new(hunk.row_range.start.0, 0);
11433 self.unfold_ranges(&[destination..destination], false, false, cx);
11434 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11435 s.select_ranges(vec![destination..destination]);
11436 });
11437 }
11438
11439 hunk
11440 }
11441
11442 pub fn go_to_definition(
11443 &mut self,
11444 _: &GoToDefinition,
11445 window: &mut Window,
11446 cx: &mut Context<Self>,
11447 ) -> Task<Result<Navigated>> {
11448 let definition =
11449 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11450 cx.spawn_in(window, |editor, mut cx| async move {
11451 if definition.await? == Navigated::Yes {
11452 return Ok(Navigated::Yes);
11453 }
11454 match editor.update_in(&mut cx, |editor, window, cx| {
11455 editor.find_all_references(&FindAllReferences, window, cx)
11456 })? {
11457 Some(references) => references.await,
11458 None => Ok(Navigated::No),
11459 }
11460 })
11461 }
11462
11463 pub fn go_to_declaration(
11464 &mut self,
11465 _: &GoToDeclaration,
11466 window: &mut Window,
11467 cx: &mut Context<Self>,
11468 ) -> Task<Result<Navigated>> {
11469 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11470 }
11471
11472 pub fn go_to_declaration_split(
11473 &mut self,
11474 _: &GoToDeclaration,
11475 window: &mut Window,
11476 cx: &mut Context<Self>,
11477 ) -> Task<Result<Navigated>> {
11478 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11479 }
11480
11481 pub fn go_to_implementation(
11482 &mut self,
11483 _: &GoToImplementation,
11484 window: &mut Window,
11485 cx: &mut Context<Self>,
11486 ) -> Task<Result<Navigated>> {
11487 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11488 }
11489
11490 pub fn go_to_implementation_split(
11491 &mut self,
11492 _: &GoToImplementationSplit,
11493 window: &mut Window,
11494 cx: &mut Context<Self>,
11495 ) -> Task<Result<Navigated>> {
11496 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11497 }
11498
11499 pub fn go_to_type_definition(
11500 &mut self,
11501 _: &GoToTypeDefinition,
11502 window: &mut Window,
11503 cx: &mut Context<Self>,
11504 ) -> Task<Result<Navigated>> {
11505 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11506 }
11507
11508 pub fn go_to_definition_split(
11509 &mut self,
11510 _: &GoToDefinitionSplit,
11511 window: &mut Window,
11512 cx: &mut Context<Self>,
11513 ) -> Task<Result<Navigated>> {
11514 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11515 }
11516
11517 pub fn go_to_type_definition_split(
11518 &mut self,
11519 _: &GoToTypeDefinitionSplit,
11520 window: &mut Window,
11521 cx: &mut Context<Self>,
11522 ) -> Task<Result<Navigated>> {
11523 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11524 }
11525
11526 fn go_to_definition_of_kind(
11527 &mut self,
11528 kind: GotoDefinitionKind,
11529 split: bool,
11530 window: &mut Window,
11531 cx: &mut Context<Self>,
11532 ) -> Task<Result<Navigated>> {
11533 let Some(provider) = self.semantics_provider.clone() else {
11534 return Task::ready(Ok(Navigated::No));
11535 };
11536 let head = self.selections.newest::<usize>(cx).head();
11537 let buffer = self.buffer.read(cx);
11538 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11539 text_anchor
11540 } else {
11541 return Task::ready(Ok(Navigated::No));
11542 };
11543
11544 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11545 return Task::ready(Ok(Navigated::No));
11546 };
11547
11548 cx.spawn_in(window, |editor, mut cx| async move {
11549 let definitions = definitions.await?;
11550 let navigated = editor
11551 .update_in(&mut cx, |editor, window, cx| {
11552 editor.navigate_to_hover_links(
11553 Some(kind),
11554 definitions
11555 .into_iter()
11556 .filter(|location| {
11557 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11558 })
11559 .map(HoverLink::Text)
11560 .collect::<Vec<_>>(),
11561 split,
11562 window,
11563 cx,
11564 )
11565 })?
11566 .await?;
11567 anyhow::Ok(navigated)
11568 })
11569 }
11570
11571 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11572 let selection = self.selections.newest_anchor();
11573 let head = selection.head();
11574 let tail = selection.tail();
11575
11576 let Some((buffer, start_position)) =
11577 self.buffer.read(cx).text_anchor_for_position(head, cx)
11578 else {
11579 return;
11580 };
11581
11582 let end_position = if head != tail {
11583 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11584 return;
11585 };
11586 Some(pos)
11587 } else {
11588 None
11589 };
11590
11591 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11592 let url = if let Some(end_pos) = end_position {
11593 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11594 } else {
11595 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11596 };
11597
11598 if let Some(url) = url {
11599 editor.update(&mut cx, |_, cx| {
11600 cx.open_url(&url);
11601 })
11602 } else {
11603 Ok(())
11604 }
11605 });
11606
11607 url_finder.detach();
11608 }
11609
11610 pub fn open_selected_filename(
11611 &mut self,
11612 _: &OpenSelectedFilename,
11613 window: &mut Window,
11614 cx: &mut Context<Self>,
11615 ) {
11616 let Some(workspace) = self.workspace() else {
11617 return;
11618 };
11619
11620 let position = self.selections.newest_anchor().head();
11621
11622 let Some((buffer, buffer_position)) =
11623 self.buffer.read(cx).text_anchor_for_position(position, cx)
11624 else {
11625 return;
11626 };
11627
11628 let project = self.project.clone();
11629
11630 cx.spawn_in(window, |_, mut cx| async move {
11631 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11632
11633 if let Some((_, path)) = result {
11634 workspace
11635 .update_in(&mut cx, |workspace, window, cx| {
11636 workspace.open_resolved_path(path, window, cx)
11637 })?
11638 .await?;
11639 }
11640 anyhow::Ok(())
11641 })
11642 .detach();
11643 }
11644
11645 pub(crate) fn navigate_to_hover_links(
11646 &mut self,
11647 kind: Option<GotoDefinitionKind>,
11648 mut definitions: Vec<HoverLink>,
11649 split: bool,
11650 window: &mut Window,
11651 cx: &mut Context<Editor>,
11652 ) -> Task<Result<Navigated>> {
11653 // If there is one definition, just open it directly
11654 if definitions.len() == 1 {
11655 let definition = definitions.pop().unwrap();
11656
11657 enum TargetTaskResult {
11658 Location(Option<Location>),
11659 AlreadyNavigated,
11660 }
11661
11662 let target_task = match definition {
11663 HoverLink::Text(link) => {
11664 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11665 }
11666 HoverLink::InlayHint(lsp_location, server_id) => {
11667 let computation =
11668 self.compute_target_location(lsp_location, server_id, window, cx);
11669 cx.background_spawn(async move {
11670 let location = computation.await?;
11671 Ok(TargetTaskResult::Location(location))
11672 })
11673 }
11674 HoverLink::Url(url) => {
11675 cx.open_url(&url);
11676 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11677 }
11678 HoverLink::File(path) => {
11679 if let Some(workspace) = self.workspace() {
11680 cx.spawn_in(window, |_, mut cx| async move {
11681 workspace
11682 .update_in(&mut cx, |workspace, window, cx| {
11683 workspace.open_resolved_path(path, window, cx)
11684 })?
11685 .await
11686 .map(|_| TargetTaskResult::AlreadyNavigated)
11687 })
11688 } else {
11689 Task::ready(Ok(TargetTaskResult::Location(None)))
11690 }
11691 }
11692 };
11693 cx.spawn_in(window, |editor, mut cx| async move {
11694 let target = match target_task.await.context("target resolution task")? {
11695 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11696 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11697 TargetTaskResult::Location(Some(target)) => target,
11698 };
11699
11700 editor.update_in(&mut cx, |editor, window, cx| {
11701 let Some(workspace) = editor.workspace() else {
11702 return Navigated::No;
11703 };
11704 let pane = workspace.read(cx).active_pane().clone();
11705
11706 let range = target.range.to_point(target.buffer.read(cx));
11707 let range = editor.range_for_match(&range);
11708 let range = collapse_multiline_range(range);
11709
11710 if !split
11711 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11712 {
11713 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11714 } else {
11715 window.defer(cx, move |window, cx| {
11716 let target_editor: Entity<Self> =
11717 workspace.update(cx, |workspace, cx| {
11718 let pane = if split {
11719 workspace.adjacent_pane(window, cx)
11720 } else {
11721 workspace.active_pane().clone()
11722 };
11723
11724 workspace.open_project_item(
11725 pane,
11726 target.buffer.clone(),
11727 true,
11728 true,
11729 window,
11730 cx,
11731 )
11732 });
11733 target_editor.update(cx, |target_editor, cx| {
11734 // When selecting a definition in a different buffer, disable the nav history
11735 // to avoid creating a history entry at the previous cursor location.
11736 pane.update(cx, |pane, _| pane.disable_history());
11737 target_editor.go_to_singleton_buffer_range(range, window, cx);
11738 pane.update(cx, |pane, _| pane.enable_history());
11739 });
11740 });
11741 }
11742 Navigated::Yes
11743 })
11744 })
11745 } else if !definitions.is_empty() {
11746 cx.spawn_in(window, |editor, mut cx| async move {
11747 let (title, location_tasks, workspace) = editor
11748 .update_in(&mut cx, |editor, window, cx| {
11749 let tab_kind = match kind {
11750 Some(GotoDefinitionKind::Implementation) => "Implementations",
11751 _ => "Definitions",
11752 };
11753 let title = definitions
11754 .iter()
11755 .find_map(|definition| match definition {
11756 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11757 let buffer = origin.buffer.read(cx);
11758 format!(
11759 "{} for {}",
11760 tab_kind,
11761 buffer
11762 .text_for_range(origin.range.clone())
11763 .collect::<String>()
11764 )
11765 }),
11766 HoverLink::InlayHint(_, _) => None,
11767 HoverLink::Url(_) => None,
11768 HoverLink::File(_) => None,
11769 })
11770 .unwrap_or(tab_kind.to_string());
11771 let location_tasks = definitions
11772 .into_iter()
11773 .map(|definition| match definition {
11774 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11775 HoverLink::InlayHint(lsp_location, server_id) => editor
11776 .compute_target_location(lsp_location, server_id, window, cx),
11777 HoverLink::Url(_) => Task::ready(Ok(None)),
11778 HoverLink::File(_) => Task::ready(Ok(None)),
11779 })
11780 .collect::<Vec<_>>();
11781 (title, location_tasks, editor.workspace().clone())
11782 })
11783 .context("location tasks preparation")?;
11784
11785 let locations = future::join_all(location_tasks)
11786 .await
11787 .into_iter()
11788 .filter_map(|location| location.transpose())
11789 .collect::<Result<_>>()
11790 .context("location tasks")?;
11791
11792 let Some(workspace) = workspace else {
11793 return Ok(Navigated::No);
11794 };
11795 let opened = workspace
11796 .update_in(&mut cx, |workspace, window, cx| {
11797 Self::open_locations_in_multibuffer(
11798 workspace,
11799 locations,
11800 title,
11801 split,
11802 MultibufferSelectionMode::First,
11803 window,
11804 cx,
11805 )
11806 })
11807 .ok();
11808
11809 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11810 })
11811 } else {
11812 Task::ready(Ok(Navigated::No))
11813 }
11814 }
11815
11816 fn compute_target_location(
11817 &self,
11818 lsp_location: lsp::Location,
11819 server_id: LanguageServerId,
11820 window: &mut Window,
11821 cx: &mut Context<Self>,
11822 ) -> Task<anyhow::Result<Option<Location>>> {
11823 let Some(project) = self.project.clone() else {
11824 return Task::ready(Ok(None));
11825 };
11826
11827 cx.spawn_in(window, move |editor, mut cx| async move {
11828 let location_task = editor.update(&mut cx, |_, cx| {
11829 project.update(cx, |project, cx| {
11830 let language_server_name = project
11831 .language_server_statuses(cx)
11832 .find(|(id, _)| server_id == *id)
11833 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11834 language_server_name.map(|language_server_name| {
11835 project.open_local_buffer_via_lsp(
11836 lsp_location.uri.clone(),
11837 server_id,
11838 language_server_name,
11839 cx,
11840 )
11841 })
11842 })
11843 })?;
11844 let location = match location_task {
11845 Some(task) => Some({
11846 let target_buffer_handle = task.await.context("open local buffer")?;
11847 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11848 let target_start = target_buffer
11849 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11850 let target_end = target_buffer
11851 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11852 target_buffer.anchor_after(target_start)
11853 ..target_buffer.anchor_before(target_end)
11854 })?;
11855 Location {
11856 buffer: target_buffer_handle,
11857 range,
11858 }
11859 }),
11860 None => None,
11861 };
11862 Ok(location)
11863 })
11864 }
11865
11866 pub fn find_all_references(
11867 &mut self,
11868 _: &FindAllReferences,
11869 window: &mut Window,
11870 cx: &mut Context<Self>,
11871 ) -> Option<Task<Result<Navigated>>> {
11872 let selection = self.selections.newest::<usize>(cx);
11873 let multi_buffer = self.buffer.read(cx);
11874 let head = selection.head();
11875
11876 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11877 let head_anchor = multi_buffer_snapshot.anchor_at(
11878 head,
11879 if head < selection.tail() {
11880 Bias::Right
11881 } else {
11882 Bias::Left
11883 },
11884 );
11885
11886 match self
11887 .find_all_references_task_sources
11888 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11889 {
11890 Ok(_) => {
11891 log::info!(
11892 "Ignoring repeated FindAllReferences invocation with the position of already running task"
11893 );
11894 return None;
11895 }
11896 Err(i) => {
11897 self.find_all_references_task_sources.insert(i, head_anchor);
11898 }
11899 }
11900
11901 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11902 let workspace = self.workspace()?;
11903 let project = workspace.read(cx).project().clone();
11904 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11905 Some(cx.spawn_in(window, |editor, mut cx| async move {
11906 let _cleanup = defer({
11907 let mut cx = cx.clone();
11908 move || {
11909 let _ = editor.update(&mut cx, |editor, _| {
11910 if let Ok(i) =
11911 editor
11912 .find_all_references_task_sources
11913 .binary_search_by(|anchor| {
11914 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11915 })
11916 {
11917 editor.find_all_references_task_sources.remove(i);
11918 }
11919 });
11920 }
11921 });
11922
11923 let locations = references.await?;
11924 if locations.is_empty() {
11925 return anyhow::Ok(Navigated::No);
11926 }
11927
11928 workspace.update_in(&mut cx, |workspace, window, cx| {
11929 let title = locations
11930 .first()
11931 .as_ref()
11932 .map(|location| {
11933 let buffer = location.buffer.read(cx);
11934 format!(
11935 "References to `{}`",
11936 buffer
11937 .text_for_range(location.range.clone())
11938 .collect::<String>()
11939 )
11940 })
11941 .unwrap();
11942 Self::open_locations_in_multibuffer(
11943 workspace,
11944 locations,
11945 title,
11946 false,
11947 MultibufferSelectionMode::First,
11948 window,
11949 cx,
11950 );
11951 Navigated::Yes
11952 })
11953 }))
11954 }
11955
11956 /// Opens a multibuffer with the given project locations in it
11957 pub fn open_locations_in_multibuffer(
11958 workspace: &mut Workspace,
11959 mut locations: Vec<Location>,
11960 title: String,
11961 split: bool,
11962 multibuffer_selection_mode: MultibufferSelectionMode,
11963 window: &mut Window,
11964 cx: &mut Context<Workspace>,
11965 ) {
11966 // If there are multiple definitions, open them in a multibuffer
11967 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11968 let mut locations = locations.into_iter().peekable();
11969 let mut ranges = Vec::new();
11970 let capability = workspace.project().read(cx).capability();
11971
11972 let excerpt_buffer = cx.new(|cx| {
11973 let mut multibuffer = MultiBuffer::new(capability);
11974 while let Some(location) = locations.next() {
11975 let buffer = location.buffer.read(cx);
11976 let mut ranges_for_buffer = Vec::new();
11977 let range = location.range.to_offset(buffer);
11978 ranges_for_buffer.push(range.clone());
11979
11980 while let Some(next_location) = locations.peek() {
11981 if next_location.buffer == location.buffer {
11982 ranges_for_buffer.push(next_location.range.to_offset(buffer));
11983 locations.next();
11984 } else {
11985 break;
11986 }
11987 }
11988
11989 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11990 ranges.extend(multibuffer.push_excerpts_with_context_lines(
11991 location.buffer.clone(),
11992 ranges_for_buffer,
11993 DEFAULT_MULTIBUFFER_CONTEXT,
11994 cx,
11995 ))
11996 }
11997
11998 multibuffer.with_title(title)
11999 });
12000
12001 let editor = cx.new(|cx| {
12002 Editor::for_multibuffer(
12003 excerpt_buffer,
12004 Some(workspace.project().clone()),
12005 true,
12006 window,
12007 cx,
12008 )
12009 });
12010 editor.update(cx, |editor, cx| {
12011 match multibuffer_selection_mode {
12012 MultibufferSelectionMode::First => {
12013 if let Some(first_range) = ranges.first() {
12014 editor.change_selections(None, window, cx, |selections| {
12015 selections.clear_disjoint();
12016 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12017 });
12018 }
12019 editor.highlight_background::<Self>(
12020 &ranges,
12021 |theme| theme.editor_highlighted_line_background,
12022 cx,
12023 );
12024 }
12025 MultibufferSelectionMode::All => {
12026 editor.change_selections(None, window, cx, |selections| {
12027 selections.clear_disjoint();
12028 selections.select_anchor_ranges(ranges);
12029 });
12030 }
12031 }
12032 editor.register_buffers_with_language_servers(cx);
12033 });
12034
12035 let item = Box::new(editor);
12036 let item_id = item.item_id();
12037
12038 if split {
12039 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12040 } else {
12041 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12042 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12043 pane.close_current_preview_item(window, cx)
12044 } else {
12045 None
12046 }
12047 });
12048 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12049 }
12050 workspace.active_pane().update(cx, |pane, cx| {
12051 pane.set_preview_item_id(Some(item_id), cx);
12052 });
12053 }
12054
12055 pub fn rename(
12056 &mut self,
12057 _: &Rename,
12058 window: &mut Window,
12059 cx: &mut Context<Self>,
12060 ) -> Option<Task<Result<()>>> {
12061 use language::ToOffset as _;
12062
12063 let provider = self.semantics_provider.clone()?;
12064 let selection = self.selections.newest_anchor().clone();
12065 let (cursor_buffer, cursor_buffer_position) = self
12066 .buffer
12067 .read(cx)
12068 .text_anchor_for_position(selection.head(), cx)?;
12069 let (tail_buffer, cursor_buffer_position_end) = self
12070 .buffer
12071 .read(cx)
12072 .text_anchor_for_position(selection.tail(), cx)?;
12073 if tail_buffer != cursor_buffer {
12074 return None;
12075 }
12076
12077 let snapshot = cursor_buffer.read(cx).snapshot();
12078 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12079 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12080 let prepare_rename = provider
12081 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12082 .unwrap_or_else(|| Task::ready(Ok(None)));
12083 drop(snapshot);
12084
12085 Some(cx.spawn_in(window, |this, mut cx| async move {
12086 let rename_range = if let Some(range) = prepare_rename.await? {
12087 Some(range)
12088 } else {
12089 this.update(&mut cx, |this, cx| {
12090 let buffer = this.buffer.read(cx).snapshot(cx);
12091 let mut buffer_highlights = this
12092 .document_highlights_for_position(selection.head(), &buffer)
12093 .filter(|highlight| {
12094 highlight.start.excerpt_id == selection.head().excerpt_id
12095 && highlight.end.excerpt_id == selection.head().excerpt_id
12096 });
12097 buffer_highlights
12098 .next()
12099 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12100 })?
12101 };
12102 if let Some(rename_range) = rename_range {
12103 this.update_in(&mut cx, |this, window, cx| {
12104 let snapshot = cursor_buffer.read(cx).snapshot();
12105 let rename_buffer_range = rename_range.to_offset(&snapshot);
12106 let cursor_offset_in_rename_range =
12107 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12108 let cursor_offset_in_rename_range_end =
12109 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12110
12111 this.take_rename(false, window, cx);
12112 let buffer = this.buffer.read(cx).read(cx);
12113 let cursor_offset = selection.head().to_offset(&buffer);
12114 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12115 let rename_end = rename_start + rename_buffer_range.len();
12116 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12117 let mut old_highlight_id = None;
12118 let old_name: Arc<str> = buffer
12119 .chunks(rename_start..rename_end, true)
12120 .map(|chunk| {
12121 if old_highlight_id.is_none() {
12122 old_highlight_id = chunk.syntax_highlight_id;
12123 }
12124 chunk.text
12125 })
12126 .collect::<String>()
12127 .into();
12128
12129 drop(buffer);
12130
12131 // Position the selection in the rename editor so that it matches the current selection.
12132 this.show_local_selections = false;
12133 let rename_editor = cx.new(|cx| {
12134 let mut editor = Editor::single_line(window, cx);
12135 editor.buffer.update(cx, |buffer, cx| {
12136 buffer.edit([(0..0, old_name.clone())], None, cx)
12137 });
12138 let rename_selection_range = match cursor_offset_in_rename_range
12139 .cmp(&cursor_offset_in_rename_range_end)
12140 {
12141 Ordering::Equal => {
12142 editor.select_all(&SelectAll, window, cx);
12143 return editor;
12144 }
12145 Ordering::Less => {
12146 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12147 }
12148 Ordering::Greater => {
12149 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12150 }
12151 };
12152 if rename_selection_range.end > old_name.len() {
12153 editor.select_all(&SelectAll, window, cx);
12154 } else {
12155 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12156 s.select_ranges([rename_selection_range]);
12157 });
12158 }
12159 editor
12160 });
12161 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12162 if e == &EditorEvent::Focused {
12163 cx.emit(EditorEvent::FocusedIn)
12164 }
12165 })
12166 .detach();
12167
12168 let write_highlights =
12169 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12170 let read_highlights =
12171 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12172 let ranges = write_highlights
12173 .iter()
12174 .flat_map(|(_, ranges)| ranges.iter())
12175 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12176 .cloned()
12177 .collect();
12178
12179 this.highlight_text::<Rename>(
12180 ranges,
12181 HighlightStyle {
12182 fade_out: Some(0.6),
12183 ..Default::default()
12184 },
12185 cx,
12186 );
12187 let rename_focus_handle = rename_editor.focus_handle(cx);
12188 window.focus(&rename_focus_handle);
12189 let block_id = this.insert_blocks(
12190 [BlockProperties {
12191 style: BlockStyle::Flex,
12192 placement: BlockPlacement::Below(range.start),
12193 height: 1,
12194 render: Arc::new({
12195 let rename_editor = rename_editor.clone();
12196 move |cx: &mut BlockContext| {
12197 let mut text_style = cx.editor_style.text.clone();
12198 if let Some(highlight_style) = old_highlight_id
12199 .and_then(|h| h.style(&cx.editor_style.syntax))
12200 {
12201 text_style = text_style.highlight(highlight_style);
12202 }
12203 div()
12204 .block_mouse_down()
12205 .pl(cx.anchor_x)
12206 .child(EditorElement::new(
12207 &rename_editor,
12208 EditorStyle {
12209 background: cx.theme().system().transparent,
12210 local_player: cx.editor_style.local_player,
12211 text: text_style,
12212 scrollbar_width: cx.editor_style.scrollbar_width,
12213 syntax: cx.editor_style.syntax.clone(),
12214 status: cx.editor_style.status.clone(),
12215 inlay_hints_style: HighlightStyle {
12216 font_weight: Some(FontWeight::BOLD),
12217 ..make_inlay_hints_style(cx.app)
12218 },
12219 inline_completion_styles: make_suggestion_styles(
12220 cx.app,
12221 ),
12222 ..EditorStyle::default()
12223 },
12224 ))
12225 .into_any_element()
12226 }
12227 }),
12228 priority: 0,
12229 }],
12230 Some(Autoscroll::fit()),
12231 cx,
12232 )[0];
12233 this.pending_rename = Some(RenameState {
12234 range,
12235 old_name,
12236 editor: rename_editor,
12237 block_id,
12238 });
12239 })?;
12240 }
12241
12242 Ok(())
12243 }))
12244 }
12245
12246 pub fn confirm_rename(
12247 &mut self,
12248 _: &ConfirmRename,
12249 window: &mut Window,
12250 cx: &mut Context<Self>,
12251 ) -> Option<Task<Result<()>>> {
12252 let rename = self.take_rename(false, window, cx)?;
12253 let workspace = self.workspace()?.downgrade();
12254 let (buffer, start) = self
12255 .buffer
12256 .read(cx)
12257 .text_anchor_for_position(rename.range.start, cx)?;
12258 let (end_buffer, _) = self
12259 .buffer
12260 .read(cx)
12261 .text_anchor_for_position(rename.range.end, cx)?;
12262 if buffer != end_buffer {
12263 return None;
12264 }
12265
12266 let old_name = rename.old_name;
12267 let new_name = rename.editor.read(cx).text(cx);
12268
12269 let rename = self.semantics_provider.as_ref()?.perform_rename(
12270 &buffer,
12271 start,
12272 new_name.clone(),
12273 cx,
12274 )?;
12275
12276 Some(cx.spawn_in(window, |editor, mut cx| async move {
12277 let project_transaction = rename.await?;
12278 Self::open_project_transaction(
12279 &editor,
12280 workspace,
12281 project_transaction,
12282 format!("Rename: {} → {}", old_name, new_name),
12283 cx.clone(),
12284 )
12285 .await?;
12286
12287 editor.update(&mut cx, |editor, cx| {
12288 editor.refresh_document_highlights(cx);
12289 })?;
12290 Ok(())
12291 }))
12292 }
12293
12294 fn take_rename(
12295 &mut self,
12296 moving_cursor: bool,
12297 window: &mut Window,
12298 cx: &mut Context<Self>,
12299 ) -> Option<RenameState> {
12300 let rename = self.pending_rename.take()?;
12301 if rename.editor.focus_handle(cx).is_focused(window) {
12302 window.focus(&self.focus_handle);
12303 }
12304
12305 self.remove_blocks(
12306 [rename.block_id].into_iter().collect(),
12307 Some(Autoscroll::fit()),
12308 cx,
12309 );
12310 self.clear_highlights::<Rename>(cx);
12311 self.show_local_selections = true;
12312
12313 if moving_cursor {
12314 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12315 editor.selections.newest::<usize>(cx).head()
12316 });
12317
12318 // Update the selection to match the position of the selection inside
12319 // the rename editor.
12320 let snapshot = self.buffer.read(cx).read(cx);
12321 let rename_range = rename.range.to_offset(&snapshot);
12322 let cursor_in_editor = snapshot
12323 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12324 .min(rename_range.end);
12325 drop(snapshot);
12326
12327 self.change_selections(None, window, cx, |s| {
12328 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12329 });
12330 } else {
12331 self.refresh_document_highlights(cx);
12332 }
12333
12334 Some(rename)
12335 }
12336
12337 pub fn pending_rename(&self) -> Option<&RenameState> {
12338 self.pending_rename.as_ref()
12339 }
12340
12341 fn format(
12342 &mut self,
12343 _: &Format,
12344 window: &mut Window,
12345 cx: &mut Context<Self>,
12346 ) -> Option<Task<Result<()>>> {
12347 let project = match &self.project {
12348 Some(project) => project.clone(),
12349 None => return None,
12350 };
12351
12352 Some(self.perform_format(
12353 project,
12354 FormatTrigger::Manual,
12355 FormatTarget::Buffers,
12356 window,
12357 cx,
12358 ))
12359 }
12360
12361 fn format_selections(
12362 &mut self,
12363 _: &FormatSelections,
12364 window: &mut Window,
12365 cx: &mut Context<Self>,
12366 ) -> Option<Task<Result<()>>> {
12367 let project = match &self.project {
12368 Some(project) => project.clone(),
12369 None => return None,
12370 };
12371
12372 let ranges = self
12373 .selections
12374 .all_adjusted(cx)
12375 .into_iter()
12376 .map(|selection| selection.range())
12377 .collect_vec();
12378
12379 Some(self.perform_format(
12380 project,
12381 FormatTrigger::Manual,
12382 FormatTarget::Ranges(ranges),
12383 window,
12384 cx,
12385 ))
12386 }
12387
12388 fn perform_format(
12389 &mut self,
12390 project: Entity<Project>,
12391 trigger: FormatTrigger,
12392 target: FormatTarget,
12393 window: &mut Window,
12394 cx: &mut Context<Self>,
12395 ) -> Task<Result<()>> {
12396 let buffer = self.buffer.clone();
12397 let (buffers, target) = match target {
12398 FormatTarget::Buffers => {
12399 let mut buffers = buffer.read(cx).all_buffers();
12400 if trigger == FormatTrigger::Save {
12401 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12402 }
12403 (buffers, LspFormatTarget::Buffers)
12404 }
12405 FormatTarget::Ranges(selection_ranges) => {
12406 let multi_buffer = buffer.read(cx);
12407 let snapshot = multi_buffer.read(cx);
12408 let mut buffers = HashSet::default();
12409 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12410 BTreeMap::new();
12411 for selection_range in selection_ranges {
12412 for (buffer, buffer_range, _) in
12413 snapshot.range_to_buffer_ranges(selection_range)
12414 {
12415 let buffer_id = buffer.remote_id();
12416 let start = buffer.anchor_before(buffer_range.start);
12417 let end = buffer.anchor_after(buffer_range.end);
12418 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12419 buffer_id_to_ranges
12420 .entry(buffer_id)
12421 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12422 .or_insert_with(|| vec![start..end]);
12423 }
12424 }
12425 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12426 }
12427 };
12428
12429 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12430 let format = project.update(cx, |project, cx| {
12431 project.format(buffers, target, true, trigger, cx)
12432 });
12433
12434 cx.spawn_in(window, |_, mut cx| async move {
12435 let transaction = futures::select_biased! {
12436 () = timeout => {
12437 log::warn!("timed out waiting for formatting");
12438 None
12439 }
12440 transaction = format.log_err().fuse() => transaction,
12441 };
12442
12443 buffer
12444 .update(&mut cx, |buffer, cx| {
12445 if let Some(transaction) = transaction {
12446 if !buffer.is_singleton() {
12447 buffer.push_transaction(&transaction.0, cx);
12448 }
12449 }
12450
12451 cx.notify();
12452 })
12453 .ok();
12454
12455 Ok(())
12456 })
12457 }
12458
12459 fn restart_language_server(
12460 &mut self,
12461 _: &RestartLanguageServer,
12462 _: &mut Window,
12463 cx: &mut Context<Self>,
12464 ) {
12465 if let Some(project) = self.project.clone() {
12466 self.buffer.update(cx, |multi_buffer, cx| {
12467 project.update(cx, |project, cx| {
12468 project.restart_language_servers_for_buffers(
12469 multi_buffer.all_buffers().into_iter().collect(),
12470 cx,
12471 );
12472 });
12473 })
12474 }
12475 }
12476
12477 fn cancel_language_server_work(
12478 workspace: &mut Workspace,
12479 _: &actions::CancelLanguageServerWork,
12480 _: &mut Window,
12481 cx: &mut Context<Workspace>,
12482 ) {
12483 let project = workspace.project();
12484 let buffers = workspace
12485 .active_item(cx)
12486 .and_then(|item| item.act_as::<Editor>(cx))
12487 .map_or(HashSet::default(), |editor| {
12488 editor.read(cx).buffer.read(cx).all_buffers()
12489 });
12490 project.update(cx, |project, cx| {
12491 project.cancel_language_server_work_for_buffers(buffers, cx);
12492 });
12493 }
12494
12495 fn show_character_palette(
12496 &mut self,
12497 _: &ShowCharacterPalette,
12498 window: &mut Window,
12499 _: &mut Context<Self>,
12500 ) {
12501 window.show_character_palette();
12502 }
12503
12504 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12505 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12506 let buffer = self.buffer.read(cx).snapshot(cx);
12507 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12508 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12509 let is_valid = buffer
12510 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12511 .any(|entry| {
12512 entry.diagnostic.is_primary
12513 && !entry.range.is_empty()
12514 && entry.range.start == primary_range_start
12515 && entry.diagnostic.message == active_diagnostics.primary_message
12516 });
12517
12518 if is_valid != active_diagnostics.is_valid {
12519 active_diagnostics.is_valid = is_valid;
12520 let mut new_styles = HashMap::default();
12521 for (block_id, diagnostic) in &active_diagnostics.blocks {
12522 new_styles.insert(
12523 *block_id,
12524 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
12525 );
12526 }
12527 self.display_map.update(cx, |display_map, _cx| {
12528 display_map.replace_blocks(new_styles)
12529 });
12530 }
12531 }
12532 }
12533
12534 fn activate_diagnostics(
12535 &mut self,
12536 buffer_id: BufferId,
12537 group_id: usize,
12538 window: &mut Window,
12539 cx: &mut Context<Self>,
12540 ) {
12541 self.dismiss_diagnostics(cx);
12542 let snapshot = self.snapshot(window, cx);
12543 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12544 let buffer = self.buffer.read(cx).snapshot(cx);
12545
12546 let mut primary_range = None;
12547 let mut primary_message = None;
12548 let diagnostic_group = buffer
12549 .diagnostic_group(buffer_id, group_id)
12550 .filter_map(|entry| {
12551 let start = entry.range.start;
12552 let end = entry.range.end;
12553 if snapshot.is_line_folded(MultiBufferRow(start.row))
12554 && (start.row == end.row
12555 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12556 {
12557 return None;
12558 }
12559 if entry.diagnostic.is_primary {
12560 primary_range = Some(entry.range.clone());
12561 primary_message = Some(entry.diagnostic.message.clone());
12562 }
12563 Some(entry)
12564 })
12565 .collect::<Vec<_>>();
12566 let primary_range = primary_range?;
12567 let primary_message = primary_message?;
12568
12569 let blocks = display_map
12570 .insert_blocks(
12571 diagnostic_group.iter().map(|entry| {
12572 let diagnostic = entry.diagnostic.clone();
12573 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12574 BlockProperties {
12575 style: BlockStyle::Fixed,
12576 placement: BlockPlacement::Below(
12577 buffer.anchor_after(entry.range.start),
12578 ),
12579 height: message_height,
12580 render: diagnostic_block_renderer(diagnostic, None, true, true),
12581 priority: 0,
12582 }
12583 }),
12584 cx,
12585 )
12586 .into_iter()
12587 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12588 .collect();
12589
12590 Some(ActiveDiagnosticGroup {
12591 primary_range: buffer.anchor_before(primary_range.start)
12592 ..buffer.anchor_after(primary_range.end),
12593 primary_message,
12594 group_id,
12595 blocks,
12596 is_valid: true,
12597 })
12598 });
12599 }
12600
12601 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12602 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12603 self.display_map.update(cx, |display_map, cx| {
12604 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12605 });
12606 cx.notify();
12607 }
12608 }
12609
12610 /// Disable inline diagnostics rendering for this editor.
12611 pub fn disable_inline_diagnostics(&mut self) {
12612 self.inline_diagnostics_enabled = false;
12613 self.inline_diagnostics_update = Task::ready(());
12614 self.inline_diagnostics.clear();
12615 }
12616
12617 pub fn inline_diagnostics_enabled(&self) -> bool {
12618 self.inline_diagnostics_enabled
12619 }
12620
12621 pub fn show_inline_diagnostics(&self) -> bool {
12622 self.show_inline_diagnostics
12623 }
12624
12625 pub fn toggle_inline_diagnostics(
12626 &mut self,
12627 _: &ToggleInlineDiagnostics,
12628 window: &mut Window,
12629 cx: &mut Context<'_, Editor>,
12630 ) {
12631 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12632 self.refresh_inline_diagnostics(false, window, cx);
12633 }
12634
12635 fn refresh_inline_diagnostics(
12636 &mut self,
12637 debounce: bool,
12638 window: &mut Window,
12639 cx: &mut Context<Self>,
12640 ) {
12641 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12642 self.inline_diagnostics_update = Task::ready(());
12643 self.inline_diagnostics.clear();
12644 return;
12645 }
12646
12647 let debounce_ms = ProjectSettings::get_global(cx)
12648 .diagnostics
12649 .inline
12650 .update_debounce_ms;
12651 let debounce = if debounce && debounce_ms > 0 {
12652 Some(Duration::from_millis(debounce_ms))
12653 } else {
12654 None
12655 };
12656 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12657 if let Some(debounce) = debounce {
12658 cx.background_executor().timer(debounce).await;
12659 }
12660 let Some(snapshot) = editor
12661 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12662 .ok()
12663 else {
12664 return;
12665 };
12666
12667 let new_inline_diagnostics = cx
12668 .background_spawn(async move {
12669 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12670 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12671 let message = diagnostic_entry
12672 .diagnostic
12673 .message
12674 .split_once('\n')
12675 .map(|(line, _)| line)
12676 .map(SharedString::new)
12677 .unwrap_or_else(|| {
12678 SharedString::from(diagnostic_entry.diagnostic.message)
12679 });
12680 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12681 let (Ok(i) | Err(i)) = inline_diagnostics
12682 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12683 inline_diagnostics.insert(
12684 i,
12685 (
12686 start_anchor,
12687 InlineDiagnostic {
12688 message,
12689 group_id: diagnostic_entry.diagnostic.group_id,
12690 start: diagnostic_entry.range.start.to_point(&snapshot),
12691 is_primary: diagnostic_entry.diagnostic.is_primary,
12692 severity: diagnostic_entry.diagnostic.severity,
12693 },
12694 ),
12695 );
12696 }
12697 inline_diagnostics
12698 })
12699 .await;
12700
12701 editor
12702 .update(&mut cx, |editor, cx| {
12703 editor.inline_diagnostics = new_inline_diagnostics;
12704 cx.notify();
12705 })
12706 .ok();
12707 });
12708 }
12709
12710 pub fn set_selections_from_remote(
12711 &mut self,
12712 selections: Vec<Selection<Anchor>>,
12713 pending_selection: Option<Selection<Anchor>>,
12714 window: &mut Window,
12715 cx: &mut Context<Self>,
12716 ) {
12717 let old_cursor_position = self.selections.newest_anchor().head();
12718 self.selections.change_with(cx, |s| {
12719 s.select_anchors(selections);
12720 if let Some(pending_selection) = pending_selection {
12721 s.set_pending(pending_selection, SelectMode::Character);
12722 } else {
12723 s.clear_pending();
12724 }
12725 });
12726 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12727 }
12728
12729 fn push_to_selection_history(&mut self) {
12730 self.selection_history.push(SelectionHistoryEntry {
12731 selections: self.selections.disjoint_anchors(),
12732 select_next_state: self.select_next_state.clone(),
12733 select_prev_state: self.select_prev_state.clone(),
12734 add_selections_state: self.add_selections_state.clone(),
12735 });
12736 }
12737
12738 pub fn transact(
12739 &mut self,
12740 window: &mut Window,
12741 cx: &mut Context<Self>,
12742 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12743 ) -> Option<TransactionId> {
12744 self.start_transaction_at(Instant::now(), window, cx);
12745 update(self, window, cx);
12746 self.end_transaction_at(Instant::now(), cx)
12747 }
12748
12749 pub fn start_transaction_at(
12750 &mut self,
12751 now: Instant,
12752 window: &mut Window,
12753 cx: &mut Context<Self>,
12754 ) {
12755 self.end_selection(window, cx);
12756 if let Some(tx_id) = self
12757 .buffer
12758 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12759 {
12760 self.selection_history
12761 .insert_transaction(tx_id, self.selections.disjoint_anchors());
12762 cx.emit(EditorEvent::TransactionBegun {
12763 transaction_id: tx_id,
12764 })
12765 }
12766 }
12767
12768 pub fn end_transaction_at(
12769 &mut self,
12770 now: Instant,
12771 cx: &mut Context<Self>,
12772 ) -> Option<TransactionId> {
12773 if let Some(transaction_id) = self
12774 .buffer
12775 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12776 {
12777 if let Some((_, end_selections)) =
12778 self.selection_history.transaction_mut(transaction_id)
12779 {
12780 *end_selections = Some(self.selections.disjoint_anchors());
12781 } else {
12782 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12783 }
12784
12785 cx.emit(EditorEvent::Edited { transaction_id });
12786 Some(transaction_id)
12787 } else {
12788 None
12789 }
12790 }
12791
12792 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12793 if self.selection_mark_mode {
12794 self.change_selections(None, window, cx, |s| {
12795 s.move_with(|_, sel| {
12796 sel.collapse_to(sel.head(), SelectionGoal::None);
12797 });
12798 })
12799 }
12800 self.selection_mark_mode = true;
12801 cx.notify();
12802 }
12803
12804 pub fn swap_selection_ends(
12805 &mut self,
12806 _: &actions::SwapSelectionEnds,
12807 window: &mut Window,
12808 cx: &mut Context<Self>,
12809 ) {
12810 self.change_selections(None, window, cx, |s| {
12811 s.move_with(|_, sel| {
12812 if sel.start != sel.end {
12813 sel.reversed = !sel.reversed
12814 }
12815 });
12816 });
12817 self.request_autoscroll(Autoscroll::newest(), cx);
12818 cx.notify();
12819 }
12820
12821 pub fn toggle_fold(
12822 &mut self,
12823 _: &actions::ToggleFold,
12824 window: &mut Window,
12825 cx: &mut Context<Self>,
12826 ) {
12827 if self.is_singleton(cx) {
12828 let selection = self.selections.newest::<Point>(cx);
12829
12830 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12831 let range = if selection.is_empty() {
12832 let point = selection.head().to_display_point(&display_map);
12833 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12834 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12835 .to_point(&display_map);
12836 start..end
12837 } else {
12838 selection.range()
12839 };
12840 if display_map.folds_in_range(range).next().is_some() {
12841 self.unfold_lines(&Default::default(), window, cx)
12842 } else {
12843 self.fold(&Default::default(), window, cx)
12844 }
12845 } else {
12846 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12847 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12848 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12849 .map(|(snapshot, _, _)| snapshot.remote_id())
12850 .collect();
12851
12852 for buffer_id in buffer_ids {
12853 if self.is_buffer_folded(buffer_id, cx) {
12854 self.unfold_buffer(buffer_id, cx);
12855 } else {
12856 self.fold_buffer(buffer_id, cx);
12857 }
12858 }
12859 }
12860 }
12861
12862 pub fn toggle_fold_recursive(
12863 &mut self,
12864 _: &actions::ToggleFoldRecursive,
12865 window: &mut Window,
12866 cx: &mut Context<Self>,
12867 ) {
12868 let selection = self.selections.newest::<Point>(cx);
12869
12870 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12871 let range = if selection.is_empty() {
12872 let point = selection.head().to_display_point(&display_map);
12873 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12874 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12875 .to_point(&display_map);
12876 start..end
12877 } else {
12878 selection.range()
12879 };
12880 if display_map.folds_in_range(range).next().is_some() {
12881 self.unfold_recursive(&Default::default(), window, cx)
12882 } else {
12883 self.fold_recursive(&Default::default(), window, cx)
12884 }
12885 }
12886
12887 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12888 if self.is_singleton(cx) {
12889 let mut to_fold = Vec::new();
12890 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12891 let selections = self.selections.all_adjusted(cx);
12892
12893 for selection in selections {
12894 let range = selection.range().sorted();
12895 let buffer_start_row = range.start.row;
12896
12897 if range.start.row != range.end.row {
12898 let mut found = false;
12899 let mut row = range.start.row;
12900 while row <= range.end.row {
12901 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12902 {
12903 found = true;
12904 row = crease.range().end.row + 1;
12905 to_fold.push(crease);
12906 } else {
12907 row += 1
12908 }
12909 }
12910 if found {
12911 continue;
12912 }
12913 }
12914
12915 for row in (0..=range.start.row).rev() {
12916 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12917 if crease.range().end.row >= buffer_start_row {
12918 to_fold.push(crease);
12919 if row <= range.start.row {
12920 break;
12921 }
12922 }
12923 }
12924 }
12925 }
12926
12927 self.fold_creases(to_fold, true, window, cx);
12928 } else {
12929 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12930
12931 let buffer_ids: HashSet<_> = multi_buffer_snapshot
12932 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12933 .map(|(snapshot, _, _)| snapshot.remote_id())
12934 .collect();
12935 for buffer_id in buffer_ids {
12936 self.fold_buffer(buffer_id, cx);
12937 }
12938 }
12939 }
12940
12941 fn fold_at_level(
12942 &mut self,
12943 fold_at: &FoldAtLevel,
12944 window: &mut Window,
12945 cx: &mut Context<Self>,
12946 ) {
12947 if !self.buffer.read(cx).is_singleton() {
12948 return;
12949 }
12950
12951 let fold_at_level = fold_at.0;
12952 let snapshot = self.buffer.read(cx).snapshot(cx);
12953 let mut to_fold = Vec::new();
12954 let mut stack = vec![(0, snapshot.max_row().0, 1)];
12955
12956 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12957 while start_row < end_row {
12958 match self
12959 .snapshot(window, cx)
12960 .crease_for_buffer_row(MultiBufferRow(start_row))
12961 {
12962 Some(crease) => {
12963 let nested_start_row = crease.range().start.row + 1;
12964 let nested_end_row = crease.range().end.row;
12965
12966 if current_level < fold_at_level {
12967 stack.push((nested_start_row, nested_end_row, current_level + 1));
12968 } else if current_level == fold_at_level {
12969 to_fold.push(crease);
12970 }
12971
12972 start_row = nested_end_row + 1;
12973 }
12974 None => start_row += 1,
12975 }
12976 }
12977 }
12978
12979 self.fold_creases(to_fold, true, window, cx);
12980 }
12981
12982 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12983 if self.buffer.read(cx).is_singleton() {
12984 let mut fold_ranges = Vec::new();
12985 let snapshot = self.buffer.read(cx).snapshot(cx);
12986
12987 for row in 0..snapshot.max_row().0 {
12988 if let Some(foldable_range) = self
12989 .snapshot(window, cx)
12990 .crease_for_buffer_row(MultiBufferRow(row))
12991 {
12992 fold_ranges.push(foldable_range);
12993 }
12994 }
12995
12996 self.fold_creases(fold_ranges, true, window, cx);
12997 } else {
12998 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12999 editor
13000 .update_in(&mut cx, |editor, _, cx| {
13001 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13002 editor.fold_buffer(buffer_id, cx);
13003 }
13004 })
13005 .ok();
13006 });
13007 }
13008 }
13009
13010 pub fn fold_function_bodies(
13011 &mut self,
13012 _: &actions::FoldFunctionBodies,
13013 window: &mut Window,
13014 cx: &mut Context<Self>,
13015 ) {
13016 let snapshot = self.buffer.read(cx).snapshot(cx);
13017
13018 let ranges = snapshot
13019 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13020 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13021 .collect::<Vec<_>>();
13022
13023 let creases = ranges
13024 .into_iter()
13025 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13026 .collect();
13027
13028 self.fold_creases(creases, true, window, cx);
13029 }
13030
13031 pub fn fold_recursive(
13032 &mut self,
13033 _: &actions::FoldRecursive,
13034 window: &mut Window,
13035 cx: &mut Context<Self>,
13036 ) {
13037 let mut to_fold = Vec::new();
13038 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13039 let selections = self.selections.all_adjusted(cx);
13040
13041 for selection in selections {
13042 let range = selection.range().sorted();
13043 let buffer_start_row = range.start.row;
13044
13045 if range.start.row != range.end.row {
13046 let mut found = false;
13047 for row in range.start.row..=range.end.row {
13048 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13049 found = true;
13050 to_fold.push(crease);
13051 }
13052 }
13053 if found {
13054 continue;
13055 }
13056 }
13057
13058 for row in (0..=range.start.row).rev() {
13059 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13060 if crease.range().end.row >= buffer_start_row {
13061 to_fold.push(crease);
13062 } else {
13063 break;
13064 }
13065 }
13066 }
13067 }
13068
13069 self.fold_creases(to_fold, true, window, cx);
13070 }
13071
13072 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13073 let buffer_row = fold_at.buffer_row;
13074 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13075
13076 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13077 let autoscroll = self
13078 .selections
13079 .all::<Point>(cx)
13080 .iter()
13081 .any(|selection| crease.range().overlaps(&selection.range()));
13082
13083 self.fold_creases(vec![crease], autoscroll, window, cx);
13084 }
13085 }
13086
13087 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13088 if self.is_singleton(cx) {
13089 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13090 let buffer = &display_map.buffer_snapshot;
13091 let selections = self.selections.all::<Point>(cx);
13092 let ranges = selections
13093 .iter()
13094 .map(|s| {
13095 let range = s.display_range(&display_map).sorted();
13096 let mut start = range.start.to_point(&display_map);
13097 let mut end = range.end.to_point(&display_map);
13098 start.column = 0;
13099 end.column = buffer.line_len(MultiBufferRow(end.row));
13100 start..end
13101 })
13102 .collect::<Vec<_>>();
13103
13104 self.unfold_ranges(&ranges, true, true, cx);
13105 } else {
13106 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13107 let buffer_ids: HashSet<_> = multi_buffer_snapshot
13108 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
13109 .map(|(snapshot, _, _)| snapshot.remote_id())
13110 .collect();
13111 for buffer_id in buffer_ids {
13112 self.unfold_buffer(buffer_id, cx);
13113 }
13114 }
13115 }
13116
13117 pub fn unfold_recursive(
13118 &mut self,
13119 _: &UnfoldRecursive,
13120 _window: &mut Window,
13121 cx: &mut Context<Self>,
13122 ) {
13123 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13124 let selections = self.selections.all::<Point>(cx);
13125 let ranges = selections
13126 .iter()
13127 .map(|s| {
13128 let mut range = s.display_range(&display_map).sorted();
13129 *range.start.column_mut() = 0;
13130 *range.end.column_mut() = display_map.line_len(range.end.row());
13131 let start = range.start.to_point(&display_map);
13132 let end = range.end.to_point(&display_map);
13133 start..end
13134 })
13135 .collect::<Vec<_>>();
13136
13137 self.unfold_ranges(&ranges, true, true, cx);
13138 }
13139
13140 pub fn unfold_at(
13141 &mut self,
13142 unfold_at: &UnfoldAt,
13143 _window: &mut Window,
13144 cx: &mut Context<Self>,
13145 ) {
13146 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13147
13148 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13149 ..Point::new(
13150 unfold_at.buffer_row.0,
13151 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13152 );
13153
13154 let autoscroll = self
13155 .selections
13156 .all::<Point>(cx)
13157 .iter()
13158 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13159
13160 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13161 }
13162
13163 pub fn unfold_all(
13164 &mut self,
13165 _: &actions::UnfoldAll,
13166 _window: &mut Window,
13167 cx: &mut Context<Self>,
13168 ) {
13169 if self.buffer.read(cx).is_singleton() {
13170 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13171 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13172 } else {
13173 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13174 editor
13175 .update(&mut cx, |editor, cx| {
13176 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13177 editor.unfold_buffer(buffer_id, cx);
13178 }
13179 })
13180 .ok();
13181 });
13182 }
13183 }
13184
13185 pub fn fold_selected_ranges(
13186 &mut self,
13187 _: &FoldSelectedRanges,
13188 window: &mut Window,
13189 cx: &mut Context<Self>,
13190 ) {
13191 let selections = self.selections.all::<Point>(cx);
13192 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13193 let line_mode = self.selections.line_mode;
13194 let ranges = selections
13195 .into_iter()
13196 .map(|s| {
13197 if line_mode {
13198 let start = Point::new(s.start.row, 0);
13199 let end = Point::new(
13200 s.end.row,
13201 display_map
13202 .buffer_snapshot
13203 .line_len(MultiBufferRow(s.end.row)),
13204 );
13205 Crease::simple(start..end, display_map.fold_placeholder.clone())
13206 } else {
13207 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13208 }
13209 })
13210 .collect::<Vec<_>>();
13211 self.fold_creases(ranges, true, window, cx);
13212 }
13213
13214 pub fn fold_ranges<T: ToOffset + Clone>(
13215 &mut self,
13216 ranges: Vec<Range<T>>,
13217 auto_scroll: bool,
13218 window: &mut Window,
13219 cx: &mut Context<Self>,
13220 ) {
13221 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13222 let ranges = ranges
13223 .into_iter()
13224 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13225 .collect::<Vec<_>>();
13226 self.fold_creases(ranges, auto_scroll, window, cx);
13227 }
13228
13229 pub fn fold_creases<T: ToOffset + Clone>(
13230 &mut self,
13231 creases: Vec<Crease<T>>,
13232 auto_scroll: bool,
13233 window: &mut Window,
13234 cx: &mut Context<Self>,
13235 ) {
13236 if creases.is_empty() {
13237 return;
13238 }
13239
13240 let mut buffers_affected = HashSet::default();
13241 let multi_buffer = self.buffer().read(cx);
13242 for crease in &creases {
13243 if let Some((_, buffer, _)) =
13244 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13245 {
13246 buffers_affected.insert(buffer.read(cx).remote_id());
13247 };
13248 }
13249
13250 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13251
13252 if auto_scroll {
13253 self.request_autoscroll(Autoscroll::fit(), cx);
13254 }
13255
13256 cx.notify();
13257
13258 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13259 // Clear diagnostics block when folding a range that contains it.
13260 let snapshot = self.snapshot(window, cx);
13261 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13262 drop(snapshot);
13263 self.active_diagnostics = Some(active_diagnostics);
13264 self.dismiss_diagnostics(cx);
13265 } else {
13266 self.active_diagnostics = Some(active_diagnostics);
13267 }
13268 }
13269
13270 self.scrollbar_marker_state.dirty = true;
13271 }
13272
13273 /// Removes any folds whose ranges intersect any of the given ranges.
13274 pub fn unfold_ranges<T: ToOffset + Clone>(
13275 &mut self,
13276 ranges: &[Range<T>],
13277 inclusive: bool,
13278 auto_scroll: bool,
13279 cx: &mut Context<Self>,
13280 ) {
13281 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13282 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13283 });
13284 }
13285
13286 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13287 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13288 return;
13289 }
13290 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13291 self.display_map
13292 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
13293 cx.emit(EditorEvent::BufferFoldToggled {
13294 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13295 folded: true,
13296 });
13297 cx.notify();
13298 }
13299
13300 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13301 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13302 return;
13303 }
13304 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13305 self.display_map.update(cx, |display_map, cx| {
13306 display_map.unfold_buffer(buffer_id, cx);
13307 });
13308 cx.emit(EditorEvent::BufferFoldToggled {
13309 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13310 folded: false,
13311 });
13312 cx.notify();
13313 }
13314
13315 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13316 self.display_map.read(cx).is_buffer_folded(buffer)
13317 }
13318
13319 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13320 self.display_map.read(cx).folded_buffers()
13321 }
13322
13323 /// Removes any folds with the given ranges.
13324 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13325 &mut self,
13326 ranges: &[Range<T>],
13327 type_id: TypeId,
13328 auto_scroll: bool,
13329 cx: &mut Context<Self>,
13330 ) {
13331 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13332 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13333 });
13334 }
13335
13336 fn remove_folds_with<T: ToOffset + Clone>(
13337 &mut self,
13338 ranges: &[Range<T>],
13339 auto_scroll: bool,
13340 cx: &mut Context<Self>,
13341 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13342 ) {
13343 if ranges.is_empty() {
13344 return;
13345 }
13346
13347 let mut buffers_affected = HashSet::default();
13348 let multi_buffer = self.buffer().read(cx);
13349 for range in ranges {
13350 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13351 buffers_affected.insert(buffer.read(cx).remote_id());
13352 };
13353 }
13354
13355 self.display_map.update(cx, update);
13356
13357 if auto_scroll {
13358 self.request_autoscroll(Autoscroll::fit(), cx);
13359 }
13360
13361 cx.notify();
13362 self.scrollbar_marker_state.dirty = true;
13363 self.active_indent_guides_state.dirty = true;
13364 }
13365
13366 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13367 self.display_map.read(cx).fold_placeholder.clone()
13368 }
13369
13370 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13371 self.buffer.update(cx, |buffer, cx| {
13372 buffer.set_all_diff_hunks_expanded(cx);
13373 });
13374 }
13375
13376 pub fn expand_all_diff_hunks(
13377 &mut self,
13378 _: &ExpandAllDiffHunks,
13379 _window: &mut Window,
13380 cx: &mut Context<Self>,
13381 ) {
13382 self.buffer.update(cx, |buffer, cx| {
13383 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13384 });
13385 }
13386
13387 pub fn toggle_selected_diff_hunks(
13388 &mut self,
13389 _: &ToggleSelectedDiffHunks,
13390 _window: &mut Window,
13391 cx: &mut Context<Self>,
13392 ) {
13393 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13394 self.toggle_diff_hunks_in_ranges(ranges, cx);
13395 }
13396
13397 pub fn diff_hunks_in_ranges<'a>(
13398 &'a self,
13399 ranges: &'a [Range<Anchor>],
13400 buffer: &'a MultiBufferSnapshot,
13401 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13402 ranges.iter().flat_map(move |range| {
13403 let end_excerpt_id = range.end.excerpt_id;
13404 let range = range.to_point(buffer);
13405 let mut peek_end = range.end;
13406 if range.end.row < buffer.max_row().0 {
13407 peek_end = Point::new(range.end.row + 1, 0);
13408 }
13409 buffer
13410 .diff_hunks_in_range(range.start..peek_end)
13411 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13412 })
13413 }
13414
13415 pub fn has_stageable_diff_hunks_in_ranges(
13416 &self,
13417 ranges: &[Range<Anchor>],
13418 snapshot: &MultiBufferSnapshot,
13419 ) -> bool {
13420 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13421 hunks.any(|hunk| hunk.secondary_status != DiffHunkSecondaryStatus::None)
13422 }
13423
13424 pub fn toggle_staged_selected_diff_hunks(
13425 &mut self,
13426 _: &::git::ToggleStaged,
13427 _window: &mut Window,
13428 cx: &mut Context<Self>,
13429 ) {
13430 let snapshot = self.buffer.read(cx).snapshot(cx);
13431 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13432 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13433 self.stage_or_unstage_diff_hunks(stage, &ranges, cx);
13434 }
13435
13436 pub fn stage_and_next(
13437 &mut self,
13438 _: &::git::StageAndNext,
13439 window: &mut Window,
13440 cx: &mut Context<Self>,
13441 ) {
13442 self.do_stage_or_unstage_and_next(true, window, cx);
13443 }
13444
13445 pub fn unstage_and_next(
13446 &mut self,
13447 _: &::git::UnstageAndNext,
13448 window: &mut Window,
13449 cx: &mut Context<Self>,
13450 ) {
13451 self.do_stage_or_unstage_and_next(false, window, cx);
13452 }
13453
13454 pub fn stage_or_unstage_diff_hunks(
13455 &mut self,
13456 stage: bool,
13457 ranges: &[Range<Anchor>],
13458 cx: &mut Context<Self>,
13459 ) {
13460 let snapshot = self.buffer.read(cx).snapshot(cx);
13461 let Some(project) = &self.project else {
13462 return;
13463 };
13464
13465 let chunk_by = self
13466 .diff_hunks_in_ranges(&ranges, &snapshot)
13467 .chunk_by(|hunk| hunk.buffer_id);
13468 for (buffer_id, hunks) in &chunk_by {
13469 Self::do_stage_or_unstage(project, stage, buffer_id, hunks, &snapshot, cx);
13470 }
13471 }
13472
13473 fn do_stage_or_unstage_and_next(
13474 &mut self,
13475 stage: bool,
13476 window: &mut Window,
13477 cx: &mut Context<Self>,
13478 ) {
13479 let mut ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13480 if ranges.iter().any(|range| range.start != range.end) {
13481 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13482 return;
13483 }
13484
13485 if !self.buffer().read(cx).is_singleton() {
13486 if let Some((excerpt_id, buffer, range)) = self.active_excerpt(cx) {
13487 if buffer.read(cx).is_empty() {
13488 let buffer = buffer.read(cx);
13489 let Some(file) = buffer.file() else {
13490 return;
13491 };
13492 let project_path = project::ProjectPath {
13493 worktree_id: file.worktree_id(cx),
13494 path: file.path().clone(),
13495 };
13496 let Some(project) = self.project.as_ref() else {
13497 return;
13498 };
13499 let project = project.read(cx);
13500
13501 let Some(repo) = project.git_store().read(cx).active_repository() else {
13502 return;
13503 };
13504
13505 repo.update(cx, |repo, cx| {
13506 let Some(repo_path) = repo.project_path_to_repo_path(&project_path) else {
13507 return;
13508 };
13509 let Some(status) = repo.repository_entry.status_for_path(&repo_path) else {
13510 return;
13511 };
13512 if stage && status.status == FileStatus::Untracked {
13513 repo.stage_entries(vec![repo_path], cx)
13514 .detach_and_log_err(cx);
13515 return;
13516 }
13517 })
13518 }
13519 ranges = vec![multi_buffer::Anchor::range_in_buffer(
13520 excerpt_id,
13521 buffer.read(cx).remote_id(),
13522 range,
13523 )];
13524 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13525 let snapshot = self.buffer().read(cx).snapshot(cx);
13526 let mut point = ranges.last().unwrap().end.to_point(&snapshot);
13527 if point.row < snapshot.max_row().0 {
13528 point.row += 1;
13529 point.column = 0;
13530 point = snapshot.clip_point(point, Bias::Right);
13531 self.change_selections(Some(Autoscroll::top_relative(6)), window, cx, |s| {
13532 s.select_ranges([point..point]);
13533 })
13534 }
13535 return;
13536 }
13537 }
13538 self.stage_or_unstage_diff_hunks(stage, &ranges[..], cx);
13539 self.go_to_next_hunk(&Default::default(), window, cx);
13540 }
13541
13542 fn do_stage_or_unstage(
13543 project: &Entity<Project>,
13544 stage: bool,
13545 buffer_id: BufferId,
13546 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13547 snapshot: &MultiBufferSnapshot,
13548 cx: &mut App,
13549 ) {
13550 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
13551 log::debug!("no buffer for id");
13552 return;
13553 };
13554 let buffer_snapshot = buffer.read(cx).snapshot();
13555 let file_exists = buffer_snapshot
13556 .file()
13557 .is_some_and(|file| file.disk_state().exists());
13558 let Some((repo, path)) = project
13559 .read(cx)
13560 .repository_and_path_for_buffer_id(buffer_id, cx)
13561 else {
13562 log::debug!("no git repo for buffer id");
13563 return;
13564 };
13565 let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
13566 log::debug!("no diff for buffer id");
13567 return;
13568 };
13569
13570 let new_index_text = if !stage && diff.is_single_insertion || stage && !file_exists {
13571 log::debug!("removing from index");
13572 None
13573 } else {
13574 diff.new_secondary_text_for_stage_or_unstage(
13575 stage,
13576 hunks.filter_map(|hunk| {
13577 if stage && hunk.secondary_status == DiffHunkSecondaryStatus::None {
13578 return None;
13579 } else if !stage
13580 && hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
13581 {
13582 return None;
13583 }
13584 Some((hunk.buffer_range.clone(), hunk.diff_base_byte_range.clone()))
13585 }),
13586 &buffer_snapshot,
13587 cx,
13588 )
13589 };
13590
13591 if file_exists {
13592 let buffer_store = project.read(cx).buffer_store().clone();
13593 buffer_store
13594 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
13595 .detach_and_log_err(cx);
13596 }
13597
13598 cx.background_spawn(
13599 repo.read(cx)
13600 .set_index_text(&path, new_index_text.map(|rope| rope.to_string()))
13601 .log_err(),
13602 )
13603 .detach();
13604 }
13605
13606 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13607 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13608 self.buffer
13609 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13610 }
13611
13612 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13613 self.buffer.update(cx, |buffer, cx| {
13614 let ranges = vec![Anchor::min()..Anchor::max()];
13615 if !buffer.all_diff_hunks_expanded()
13616 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13617 {
13618 buffer.collapse_diff_hunks(ranges, cx);
13619 true
13620 } else {
13621 false
13622 }
13623 })
13624 }
13625
13626 fn toggle_diff_hunks_in_ranges(
13627 &mut self,
13628 ranges: Vec<Range<Anchor>>,
13629 cx: &mut Context<'_, Editor>,
13630 ) {
13631 self.buffer.update(cx, |buffer, cx| {
13632 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13633 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13634 })
13635 }
13636
13637 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13638 self.buffer.update(cx, |buffer, cx| {
13639 let snapshot = buffer.snapshot(cx);
13640 let excerpt_id = range.end.excerpt_id;
13641 let point_range = range.to_point(&snapshot);
13642 let expand = !buffer.single_hunk_is_expanded(range, cx);
13643 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13644 })
13645 }
13646
13647 pub(crate) fn apply_all_diff_hunks(
13648 &mut self,
13649 _: &ApplyAllDiffHunks,
13650 window: &mut Window,
13651 cx: &mut Context<Self>,
13652 ) {
13653 let buffers = self.buffer.read(cx).all_buffers();
13654 for branch_buffer in buffers {
13655 branch_buffer.update(cx, |branch_buffer, cx| {
13656 branch_buffer.merge_into_base(Vec::new(), cx);
13657 });
13658 }
13659
13660 if let Some(project) = self.project.clone() {
13661 self.save(true, project, window, cx).detach_and_log_err(cx);
13662 }
13663 }
13664
13665 pub(crate) fn apply_selected_diff_hunks(
13666 &mut self,
13667 _: &ApplyDiffHunk,
13668 window: &mut Window,
13669 cx: &mut Context<Self>,
13670 ) {
13671 let snapshot = self.snapshot(window, cx);
13672 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
13673 let mut ranges_by_buffer = HashMap::default();
13674 self.transact(window, cx, |editor, _window, cx| {
13675 for hunk in hunks {
13676 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13677 ranges_by_buffer
13678 .entry(buffer.clone())
13679 .or_insert_with(Vec::new)
13680 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13681 }
13682 }
13683
13684 for (buffer, ranges) in ranges_by_buffer {
13685 buffer.update(cx, |buffer, cx| {
13686 buffer.merge_into_base(ranges, cx);
13687 });
13688 }
13689 });
13690
13691 if let Some(project) = self.project.clone() {
13692 self.save(true, project, window, cx).detach_and_log_err(cx);
13693 }
13694 }
13695
13696 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13697 if hovered != self.gutter_hovered {
13698 self.gutter_hovered = hovered;
13699 cx.notify();
13700 }
13701 }
13702
13703 pub fn insert_blocks(
13704 &mut self,
13705 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13706 autoscroll: Option<Autoscroll>,
13707 cx: &mut Context<Self>,
13708 ) -> Vec<CustomBlockId> {
13709 let blocks = self
13710 .display_map
13711 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13712 if let Some(autoscroll) = autoscroll {
13713 self.request_autoscroll(autoscroll, cx);
13714 }
13715 cx.notify();
13716 blocks
13717 }
13718
13719 pub fn resize_blocks(
13720 &mut self,
13721 heights: HashMap<CustomBlockId, u32>,
13722 autoscroll: Option<Autoscroll>,
13723 cx: &mut Context<Self>,
13724 ) {
13725 self.display_map
13726 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13727 if let Some(autoscroll) = autoscroll {
13728 self.request_autoscroll(autoscroll, cx);
13729 }
13730 cx.notify();
13731 }
13732
13733 pub fn replace_blocks(
13734 &mut self,
13735 renderers: HashMap<CustomBlockId, RenderBlock>,
13736 autoscroll: Option<Autoscroll>,
13737 cx: &mut Context<Self>,
13738 ) {
13739 self.display_map
13740 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13741 if let Some(autoscroll) = autoscroll {
13742 self.request_autoscroll(autoscroll, cx);
13743 }
13744 cx.notify();
13745 }
13746
13747 pub fn remove_blocks(
13748 &mut self,
13749 block_ids: HashSet<CustomBlockId>,
13750 autoscroll: Option<Autoscroll>,
13751 cx: &mut Context<Self>,
13752 ) {
13753 self.display_map.update(cx, |display_map, cx| {
13754 display_map.remove_blocks(block_ids, cx)
13755 });
13756 if let Some(autoscroll) = autoscroll {
13757 self.request_autoscroll(autoscroll, cx);
13758 }
13759 cx.notify();
13760 }
13761
13762 pub fn row_for_block(
13763 &self,
13764 block_id: CustomBlockId,
13765 cx: &mut Context<Self>,
13766 ) -> Option<DisplayRow> {
13767 self.display_map
13768 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13769 }
13770
13771 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13772 self.focused_block = Some(focused_block);
13773 }
13774
13775 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13776 self.focused_block.take()
13777 }
13778
13779 pub fn insert_creases(
13780 &mut self,
13781 creases: impl IntoIterator<Item = Crease<Anchor>>,
13782 cx: &mut Context<Self>,
13783 ) -> Vec<CreaseId> {
13784 self.display_map
13785 .update(cx, |map, cx| map.insert_creases(creases, cx))
13786 }
13787
13788 pub fn remove_creases(
13789 &mut self,
13790 ids: impl IntoIterator<Item = CreaseId>,
13791 cx: &mut Context<Self>,
13792 ) {
13793 self.display_map
13794 .update(cx, |map, cx| map.remove_creases(ids, cx));
13795 }
13796
13797 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13798 self.display_map
13799 .update(cx, |map, cx| map.snapshot(cx))
13800 .longest_row()
13801 }
13802
13803 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
13804 self.display_map
13805 .update(cx, |map, cx| map.snapshot(cx))
13806 .max_point()
13807 }
13808
13809 pub fn text(&self, cx: &App) -> String {
13810 self.buffer.read(cx).read(cx).text()
13811 }
13812
13813 pub fn is_empty(&self, cx: &App) -> bool {
13814 self.buffer.read(cx).read(cx).is_empty()
13815 }
13816
13817 pub fn text_option(&self, cx: &App) -> Option<String> {
13818 let text = self.text(cx);
13819 let text = text.trim();
13820
13821 if text.is_empty() {
13822 return None;
13823 }
13824
13825 Some(text.to_string())
13826 }
13827
13828 pub fn set_text(
13829 &mut self,
13830 text: impl Into<Arc<str>>,
13831 window: &mut Window,
13832 cx: &mut Context<Self>,
13833 ) {
13834 self.transact(window, cx, |this, _, cx| {
13835 this.buffer
13836 .read(cx)
13837 .as_singleton()
13838 .expect("you can only call set_text on editors for singleton buffers")
13839 .update(cx, |buffer, cx| buffer.set_text(text, cx));
13840 });
13841 }
13842
13843 pub fn display_text(&self, cx: &mut App) -> String {
13844 self.display_map
13845 .update(cx, |map, cx| map.snapshot(cx))
13846 .text()
13847 }
13848
13849 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
13850 let mut wrap_guides = smallvec::smallvec![];
13851
13852 if self.show_wrap_guides == Some(false) {
13853 return wrap_guides;
13854 }
13855
13856 let settings = self.buffer.read(cx).settings_at(0, cx);
13857 if settings.show_wrap_guides {
13858 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
13859 wrap_guides.push((soft_wrap as usize, true));
13860 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13861 wrap_guides.push((soft_wrap as usize, true));
13862 }
13863 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13864 }
13865
13866 wrap_guides
13867 }
13868
13869 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13870 let settings = self.buffer.read(cx).settings_at(0, cx);
13871 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13872 match mode {
13873 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13874 SoftWrap::None
13875 }
13876 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13877 language_settings::SoftWrap::PreferredLineLength => {
13878 SoftWrap::Column(settings.preferred_line_length)
13879 }
13880 language_settings::SoftWrap::Bounded => {
13881 SoftWrap::Bounded(settings.preferred_line_length)
13882 }
13883 }
13884 }
13885
13886 pub fn set_soft_wrap_mode(
13887 &mut self,
13888 mode: language_settings::SoftWrap,
13889
13890 cx: &mut Context<Self>,
13891 ) {
13892 self.soft_wrap_mode_override = Some(mode);
13893 cx.notify();
13894 }
13895
13896 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13897 self.text_style_refinement = Some(style);
13898 }
13899
13900 /// called by the Element so we know what style we were most recently rendered with.
13901 pub(crate) fn set_style(
13902 &mut self,
13903 style: EditorStyle,
13904 window: &mut Window,
13905 cx: &mut Context<Self>,
13906 ) {
13907 let rem_size = window.rem_size();
13908 self.display_map.update(cx, |map, cx| {
13909 map.set_font(
13910 style.text.font(),
13911 style.text.font_size.to_pixels(rem_size),
13912 cx,
13913 )
13914 });
13915 self.style = Some(style);
13916 }
13917
13918 pub fn style(&self) -> Option<&EditorStyle> {
13919 self.style.as_ref()
13920 }
13921
13922 // Called by the element. This method is not designed to be called outside of the editor
13923 // element's layout code because it does not notify when rewrapping is computed synchronously.
13924 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13925 self.display_map
13926 .update(cx, |map, cx| map.set_wrap_width(width, cx))
13927 }
13928
13929 pub fn set_soft_wrap(&mut self) {
13930 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13931 }
13932
13933 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13934 if self.soft_wrap_mode_override.is_some() {
13935 self.soft_wrap_mode_override.take();
13936 } else {
13937 let soft_wrap = match self.soft_wrap_mode(cx) {
13938 SoftWrap::GitDiff => return,
13939 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13940 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13941 language_settings::SoftWrap::None
13942 }
13943 };
13944 self.soft_wrap_mode_override = Some(soft_wrap);
13945 }
13946 cx.notify();
13947 }
13948
13949 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13950 let Some(workspace) = self.workspace() else {
13951 return;
13952 };
13953 let fs = workspace.read(cx).app_state().fs.clone();
13954 let current_show = TabBarSettings::get_global(cx).show;
13955 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13956 setting.show = Some(!current_show);
13957 });
13958 }
13959
13960 pub fn toggle_indent_guides(
13961 &mut self,
13962 _: &ToggleIndentGuides,
13963 _: &mut Window,
13964 cx: &mut Context<Self>,
13965 ) {
13966 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13967 self.buffer
13968 .read(cx)
13969 .settings_at(0, cx)
13970 .indent_guides
13971 .enabled
13972 });
13973 self.show_indent_guides = Some(!currently_enabled);
13974 cx.notify();
13975 }
13976
13977 fn should_show_indent_guides(&self) -> Option<bool> {
13978 self.show_indent_guides
13979 }
13980
13981 pub fn toggle_line_numbers(
13982 &mut self,
13983 _: &ToggleLineNumbers,
13984 _: &mut Window,
13985 cx: &mut Context<Self>,
13986 ) {
13987 let mut editor_settings = EditorSettings::get_global(cx).clone();
13988 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13989 EditorSettings::override_global(editor_settings, cx);
13990 }
13991
13992 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13993 self.use_relative_line_numbers
13994 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13995 }
13996
13997 pub fn toggle_relative_line_numbers(
13998 &mut self,
13999 _: &ToggleRelativeLineNumbers,
14000 _: &mut Window,
14001 cx: &mut Context<Self>,
14002 ) {
14003 let is_relative = self.should_use_relative_line_numbers(cx);
14004 self.set_relative_line_number(Some(!is_relative), cx)
14005 }
14006
14007 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14008 self.use_relative_line_numbers = is_relative;
14009 cx.notify();
14010 }
14011
14012 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14013 self.show_gutter = show_gutter;
14014 cx.notify();
14015 }
14016
14017 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14018 self.show_scrollbars = show_scrollbars;
14019 cx.notify();
14020 }
14021
14022 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14023 self.show_line_numbers = Some(show_line_numbers);
14024 cx.notify();
14025 }
14026
14027 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14028 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14029 cx.notify();
14030 }
14031
14032 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14033 self.show_code_actions = Some(show_code_actions);
14034 cx.notify();
14035 }
14036
14037 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14038 self.show_runnables = Some(show_runnables);
14039 cx.notify();
14040 }
14041
14042 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14043 if self.display_map.read(cx).masked != masked {
14044 self.display_map.update(cx, |map, _| map.masked = masked);
14045 }
14046 cx.notify()
14047 }
14048
14049 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14050 self.show_wrap_guides = Some(show_wrap_guides);
14051 cx.notify();
14052 }
14053
14054 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14055 self.show_indent_guides = Some(show_indent_guides);
14056 cx.notify();
14057 }
14058
14059 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14060 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14061 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14062 if let Some(dir) = file.abs_path(cx).parent() {
14063 return Some(dir.to_owned());
14064 }
14065 }
14066
14067 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14068 return Some(project_path.path.to_path_buf());
14069 }
14070 }
14071
14072 None
14073 }
14074
14075 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14076 self.active_excerpt(cx)?
14077 .1
14078 .read(cx)
14079 .file()
14080 .and_then(|f| f.as_local())
14081 }
14082
14083 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14084 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14085 let buffer = buffer.read(cx);
14086 if let Some(project_path) = buffer.project_path(cx) {
14087 let project = self.project.as_ref()?.read(cx);
14088 project.absolute_path(&project_path, cx)
14089 } else {
14090 buffer
14091 .file()
14092 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14093 }
14094 })
14095 }
14096
14097 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14098 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14099 let project_path = buffer.read(cx).project_path(cx)?;
14100 let project = self.project.as_ref()?.read(cx);
14101 let entry = project.entry_for_path(&project_path, cx)?;
14102 let path = entry.path.to_path_buf();
14103 Some(path)
14104 })
14105 }
14106
14107 pub fn reveal_in_finder(
14108 &mut self,
14109 _: &RevealInFileManager,
14110 _window: &mut Window,
14111 cx: &mut Context<Self>,
14112 ) {
14113 if let Some(target) = self.target_file(cx) {
14114 cx.reveal_path(&target.abs_path(cx));
14115 }
14116 }
14117
14118 pub fn copy_path(
14119 &mut self,
14120 _: &zed_actions::workspace::CopyPath,
14121 _window: &mut Window,
14122 cx: &mut Context<Self>,
14123 ) {
14124 if let Some(path) = self.target_file_abs_path(cx) {
14125 if let Some(path) = path.to_str() {
14126 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14127 }
14128 }
14129 }
14130
14131 pub fn copy_relative_path(
14132 &mut self,
14133 _: &zed_actions::workspace::CopyRelativePath,
14134 _window: &mut Window,
14135 cx: &mut Context<Self>,
14136 ) {
14137 if let Some(path) = self.target_file_path(cx) {
14138 if let Some(path) = path.to_str() {
14139 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14140 }
14141 }
14142 }
14143
14144 pub fn copy_file_name_without_extension(
14145 &mut self,
14146 _: &CopyFileNameWithoutExtension,
14147 _: &mut Window,
14148 cx: &mut Context<Self>,
14149 ) {
14150 if let Some(file) = self.target_file(cx) {
14151 if let Some(file_stem) = file.path().file_stem() {
14152 if let Some(name) = file_stem.to_str() {
14153 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14154 }
14155 }
14156 }
14157 }
14158
14159 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14160 if let Some(file) = self.target_file(cx) {
14161 if let Some(file_name) = file.path().file_name() {
14162 if let Some(name) = file_name.to_str() {
14163 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14164 }
14165 }
14166 }
14167 }
14168
14169 pub fn toggle_git_blame(
14170 &mut self,
14171 _: &ToggleGitBlame,
14172 window: &mut Window,
14173 cx: &mut Context<Self>,
14174 ) {
14175 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14176
14177 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14178 self.start_git_blame(true, window, cx);
14179 }
14180
14181 cx.notify();
14182 }
14183
14184 pub fn toggle_git_blame_inline(
14185 &mut self,
14186 _: &ToggleGitBlameInline,
14187 window: &mut Window,
14188 cx: &mut Context<Self>,
14189 ) {
14190 self.toggle_git_blame_inline_internal(true, window, cx);
14191 cx.notify();
14192 }
14193
14194 pub fn git_blame_inline_enabled(&self) -> bool {
14195 self.git_blame_inline_enabled
14196 }
14197
14198 pub fn toggle_selection_menu(
14199 &mut self,
14200 _: &ToggleSelectionMenu,
14201 _: &mut Window,
14202 cx: &mut Context<Self>,
14203 ) {
14204 self.show_selection_menu = self
14205 .show_selection_menu
14206 .map(|show_selections_menu| !show_selections_menu)
14207 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14208
14209 cx.notify();
14210 }
14211
14212 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14213 self.show_selection_menu
14214 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14215 }
14216
14217 fn start_git_blame(
14218 &mut self,
14219 user_triggered: bool,
14220 window: &mut Window,
14221 cx: &mut Context<Self>,
14222 ) {
14223 if let Some(project) = self.project.as_ref() {
14224 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14225 return;
14226 };
14227
14228 if buffer.read(cx).file().is_none() {
14229 return;
14230 }
14231
14232 let focused = self.focus_handle(cx).contains_focused(window, cx);
14233
14234 let project = project.clone();
14235 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14236 self.blame_subscription =
14237 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14238 self.blame = Some(blame);
14239 }
14240 }
14241
14242 fn toggle_git_blame_inline_internal(
14243 &mut self,
14244 user_triggered: bool,
14245 window: &mut Window,
14246 cx: &mut Context<Self>,
14247 ) {
14248 if self.git_blame_inline_enabled {
14249 self.git_blame_inline_enabled = false;
14250 self.show_git_blame_inline = false;
14251 self.show_git_blame_inline_delay_task.take();
14252 } else {
14253 self.git_blame_inline_enabled = true;
14254 self.start_git_blame_inline(user_triggered, window, cx);
14255 }
14256
14257 cx.notify();
14258 }
14259
14260 fn start_git_blame_inline(
14261 &mut self,
14262 user_triggered: bool,
14263 window: &mut Window,
14264 cx: &mut Context<Self>,
14265 ) {
14266 self.start_git_blame(user_triggered, window, cx);
14267
14268 if ProjectSettings::get_global(cx)
14269 .git
14270 .inline_blame_delay()
14271 .is_some()
14272 {
14273 self.start_inline_blame_timer(window, cx);
14274 } else {
14275 self.show_git_blame_inline = true
14276 }
14277 }
14278
14279 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14280 self.blame.as_ref()
14281 }
14282
14283 pub fn show_git_blame_gutter(&self) -> bool {
14284 self.show_git_blame_gutter
14285 }
14286
14287 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14288 self.show_git_blame_gutter && self.has_blame_entries(cx)
14289 }
14290
14291 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14292 self.show_git_blame_inline
14293 && (self.focus_handle.is_focused(window)
14294 || self
14295 .git_blame_inline_tooltip
14296 .as_ref()
14297 .and_then(|t| t.upgrade())
14298 .is_some())
14299 && !self.newest_selection_head_on_empty_line(cx)
14300 && self.has_blame_entries(cx)
14301 }
14302
14303 fn has_blame_entries(&self, cx: &App) -> bool {
14304 self.blame()
14305 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14306 }
14307
14308 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14309 let cursor_anchor = self.selections.newest_anchor().head();
14310
14311 let snapshot = self.buffer.read(cx).snapshot(cx);
14312 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14313
14314 snapshot.line_len(buffer_row) == 0
14315 }
14316
14317 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14318 let buffer_and_selection = maybe!({
14319 let selection = self.selections.newest::<Point>(cx);
14320 let selection_range = selection.range();
14321
14322 let multi_buffer = self.buffer().read(cx);
14323 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14324 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14325
14326 let (buffer, range, _) = if selection.reversed {
14327 buffer_ranges.first()
14328 } else {
14329 buffer_ranges.last()
14330 }?;
14331
14332 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14333 ..text::ToPoint::to_point(&range.end, &buffer).row;
14334 Some((
14335 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14336 selection,
14337 ))
14338 });
14339
14340 let Some((buffer, selection)) = buffer_and_selection else {
14341 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14342 };
14343
14344 let Some(project) = self.project.as_ref() else {
14345 return Task::ready(Err(anyhow!("editor does not have project")));
14346 };
14347
14348 project.update(cx, |project, cx| {
14349 project.get_permalink_to_line(&buffer, selection, cx)
14350 })
14351 }
14352
14353 pub fn copy_permalink_to_line(
14354 &mut self,
14355 _: &CopyPermalinkToLine,
14356 window: &mut Window,
14357 cx: &mut Context<Self>,
14358 ) {
14359 let permalink_task = self.get_permalink_to_line(cx);
14360 let workspace = self.workspace();
14361
14362 cx.spawn_in(window, |_, mut cx| async move {
14363 match permalink_task.await {
14364 Ok(permalink) => {
14365 cx.update(|_, cx| {
14366 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14367 })
14368 .ok();
14369 }
14370 Err(err) => {
14371 let message = format!("Failed to copy permalink: {err}");
14372
14373 Err::<(), anyhow::Error>(err).log_err();
14374
14375 if let Some(workspace) = workspace {
14376 workspace
14377 .update_in(&mut cx, |workspace, _, cx| {
14378 struct CopyPermalinkToLine;
14379
14380 workspace.show_toast(
14381 Toast::new(
14382 NotificationId::unique::<CopyPermalinkToLine>(),
14383 message,
14384 ),
14385 cx,
14386 )
14387 })
14388 .ok();
14389 }
14390 }
14391 }
14392 })
14393 .detach();
14394 }
14395
14396 pub fn copy_file_location(
14397 &mut self,
14398 _: &CopyFileLocation,
14399 _: &mut Window,
14400 cx: &mut Context<Self>,
14401 ) {
14402 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14403 if let Some(file) = self.target_file(cx) {
14404 if let Some(path) = file.path().to_str() {
14405 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14406 }
14407 }
14408 }
14409
14410 pub fn open_permalink_to_line(
14411 &mut self,
14412 _: &OpenPermalinkToLine,
14413 window: &mut Window,
14414 cx: &mut Context<Self>,
14415 ) {
14416 let permalink_task = self.get_permalink_to_line(cx);
14417 let workspace = self.workspace();
14418
14419 cx.spawn_in(window, |_, mut cx| async move {
14420 match permalink_task.await {
14421 Ok(permalink) => {
14422 cx.update(|_, cx| {
14423 cx.open_url(permalink.as_ref());
14424 })
14425 .ok();
14426 }
14427 Err(err) => {
14428 let message = format!("Failed to open permalink: {err}");
14429
14430 Err::<(), anyhow::Error>(err).log_err();
14431
14432 if let Some(workspace) = workspace {
14433 workspace
14434 .update(&mut cx, |workspace, cx| {
14435 struct OpenPermalinkToLine;
14436
14437 workspace.show_toast(
14438 Toast::new(
14439 NotificationId::unique::<OpenPermalinkToLine>(),
14440 message,
14441 ),
14442 cx,
14443 )
14444 })
14445 .ok();
14446 }
14447 }
14448 }
14449 })
14450 .detach();
14451 }
14452
14453 pub fn insert_uuid_v4(
14454 &mut self,
14455 _: &InsertUuidV4,
14456 window: &mut Window,
14457 cx: &mut Context<Self>,
14458 ) {
14459 self.insert_uuid(UuidVersion::V4, window, cx);
14460 }
14461
14462 pub fn insert_uuid_v7(
14463 &mut self,
14464 _: &InsertUuidV7,
14465 window: &mut Window,
14466 cx: &mut Context<Self>,
14467 ) {
14468 self.insert_uuid(UuidVersion::V7, window, cx);
14469 }
14470
14471 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14472 self.transact(window, cx, |this, window, cx| {
14473 let edits = this
14474 .selections
14475 .all::<Point>(cx)
14476 .into_iter()
14477 .map(|selection| {
14478 let uuid = match version {
14479 UuidVersion::V4 => uuid::Uuid::new_v4(),
14480 UuidVersion::V7 => uuid::Uuid::now_v7(),
14481 };
14482
14483 (selection.range(), uuid.to_string())
14484 });
14485 this.edit(edits, cx);
14486 this.refresh_inline_completion(true, false, window, cx);
14487 });
14488 }
14489
14490 pub fn open_selections_in_multibuffer(
14491 &mut self,
14492 _: &OpenSelectionsInMultibuffer,
14493 window: &mut Window,
14494 cx: &mut Context<Self>,
14495 ) {
14496 let multibuffer = self.buffer.read(cx);
14497
14498 let Some(buffer) = multibuffer.as_singleton() else {
14499 return;
14500 };
14501
14502 let Some(workspace) = self.workspace() else {
14503 return;
14504 };
14505
14506 let locations = self
14507 .selections
14508 .disjoint_anchors()
14509 .iter()
14510 .map(|range| Location {
14511 buffer: buffer.clone(),
14512 range: range.start.text_anchor..range.end.text_anchor,
14513 })
14514 .collect::<Vec<_>>();
14515
14516 let title = multibuffer.title(cx).to_string();
14517
14518 cx.spawn_in(window, |_, mut cx| async move {
14519 workspace.update_in(&mut cx, |workspace, window, cx| {
14520 Self::open_locations_in_multibuffer(
14521 workspace,
14522 locations,
14523 format!("Selections for '{title}'"),
14524 false,
14525 MultibufferSelectionMode::All,
14526 window,
14527 cx,
14528 );
14529 })
14530 })
14531 .detach();
14532 }
14533
14534 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14535 /// last highlight added will be used.
14536 ///
14537 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14538 pub fn highlight_rows<T: 'static>(
14539 &mut self,
14540 range: Range<Anchor>,
14541 color: Hsla,
14542 should_autoscroll: bool,
14543 cx: &mut Context<Self>,
14544 ) {
14545 let snapshot = self.buffer().read(cx).snapshot(cx);
14546 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14547 let ix = row_highlights.binary_search_by(|highlight| {
14548 Ordering::Equal
14549 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14550 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14551 });
14552
14553 if let Err(mut ix) = ix {
14554 let index = post_inc(&mut self.highlight_order);
14555
14556 // If this range intersects with the preceding highlight, then merge it with
14557 // the preceding highlight. Otherwise insert a new highlight.
14558 let mut merged = false;
14559 if ix > 0 {
14560 let prev_highlight = &mut row_highlights[ix - 1];
14561 if prev_highlight
14562 .range
14563 .end
14564 .cmp(&range.start, &snapshot)
14565 .is_ge()
14566 {
14567 ix -= 1;
14568 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14569 prev_highlight.range.end = range.end;
14570 }
14571 merged = true;
14572 prev_highlight.index = index;
14573 prev_highlight.color = color;
14574 prev_highlight.should_autoscroll = should_autoscroll;
14575 }
14576 }
14577
14578 if !merged {
14579 row_highlights.insert(
14580 ix,
14581 RowHighlight {
14582 range: range.clone(),
14583 index,
14584 color,
14585 should_autoscroll,
14586 },
14587 );
14588 }
14589
14590 // If any of the following highlights intersect with this one, merge them.
14591 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14592 let highlight = &row_highlights[ix];
14593 if next_highlight
14594 .range
14595 .start
14596 .cmp(&highlight.range.end, &snapshot)
14597 .is_le()
14598 {
14599 if next_highlight
14600 .range
14601 .end
14602 .cmp(&highlight.range.end, &snapshot)
14603 .is_gt()
14604 {
14605 row_highlights[ix].range.end = next_highlight.range.end;
14606 }
14607 row_highlights.remove(ix + 1);
14608 } else {
14609 break;
14610 }
14611 }
14612 }
14613 }
14614
14615 /// Remove any highlighted row ranges of the given type that intersect the
14616 /// given ranges.
14617 pub fn remove_highlighted_rows<T: 'static>(
14618 &mut self,
14619 ranges_to_remove: Vec<Range<Anchor>>,
14620 cx: &mut Context<Self>,
14621 ) {
14622 let snapshot = self.buffer().read(cx).snapshot(cx);
14623 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14624 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14625 row_highlights.retain(|highlight| {
14626 while let Some(range_to_remove) = ranges_to_remove.peek() {
14627 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14628 Ordering::Less | Ordering::Equal => {
14629 ranges_to_remove.next();
14630 }
14631 Ordering::Greater => {
14632 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14633 Ordering::Less | Ordering::Equal => {
14634 return false;
14635 }
14636 Ordering::Greater => break,
14637 }
14638 }
14639 }
14640 }
14641
14642 true
14643 })
14644 }
14645
14646 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14647 pub fn clear_row_highlights<T: 'static>(&mut self) {
14648 self.highlighted_rows.remove(&TypeId::of::<T>());
14649 }
14650
14651 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14652 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14653 self.highlighted_rows
14654 .get(&TypeId::of::<T>())
14655 .map_or(&[] as &[_], |vec| vec.as_slice())
14656 .iter()
14657 .map(|highlight| (highlight.range.clone(), highlight.color))
14658 }
14659
14660 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14661 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14662 /// Allows to ignore certain kinds of highlights.
14663 pub fn highlighted_display_rows(
14664 &self,
14665 window: &mut Window,
14666 cx: &mut App,
14667 ) -> BTreeMap<DisplayRow, Background> {
14668 let snapshot = self.snapshot(window, cx);
14669 let mut used_highlight_orders = HashMap::default();
14670 self.highlighted_rows
14671 .iter()
14672 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14673 .fold(
14674 BTreeMap::<DisplayRow, Background>::new(),
14675 |mut unique_rows, highlight| {
14676 let start = highlight.range.start.to_display_point(&snapshot);
14677 let end = highlight.range.end.to_display_point(&snapshot);
14678 let start_row = start.row().0;
14679 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14680 && end.column() == 0
14681 {
14682 end.row().0.saturating_sub(1)
14683 } else {
14684 end.row().0
14685 };
14686 for row in start_row..=end_row {
14687 let used_index =
14688 used_highlight_orders.entry(row).or_insert(highlight.index);
14689 if highlight.index >= *used_index {
14690 *used_index = highlight.index;
14691 unique_rows.insert(DisplayRow(row), highlight.color.into());
14692 }
14693 }
14694 unique_rows
14695 },
14696 )
14697 }
14698
14699 pub fn highlighted_display_row_for_autoscroll(
14700 &self,
14701 snapshot: &DisplaySnapshot,
14702 ) -> Option<DisplayRow> {
14703 self.highlighted_rows
14704 .values()
14705 .flat_map(|highlighted_rows| highlighted_rows.iter())
14706 .filter_map(|highlight| {
14707 if highlight.should_autoscroll {
14708 Some(highlight.range.start.to_display_point(snapshot).row())
14709 } else {
14710 None
14711 }
14712 })
14713 .min()
14714 }
14715
14716 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14717 self.highlight_background::<SearchWithinRange>(
14718 ranges,
14719 |colors| colors.editor_document_highlight_read_background,
14720 cx,
14721 )
14722 }
14723
14724 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14725 self.breadcrumb_header = Some(new_header);
14726 }
14727
14728 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14729 self.clear_background_highlights::<SearchWithinRange>(cx);
14730 }
14731
14732 pub fn highlight_background<T: 'static>(
14733 &mut self,
14734 ranges: &[Range<Anchor>],
14735 color_fetcher: fn(&ThemeColors) -> Hsla,
14736 cx: &mut Context<Self>,
14737 ) {
14738 self.background_highlights
14739 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14740 self.scrollbar_marker_state.dirty = true;
14741 cx.notify();
14742 }
14743
14744 pub fn clear_background_highlights<T: 'static>(
14745 &mut self,
14746 cx: &mut Context<Self>,
14747 ) -> Option<BackgroundHighlight> {
14748 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14749 if !text_highlights.1.is_empty() {
14750 self.scrollbar_marker_state.dirty = true;
14751 cx.notify();
14752 }
14753 Some(text_highlights)
14754 }
14755
14756 pub fn highlight_gutter<T: 'static>(
14757 &mut self,
14758 ranges: &[Range<Anchor>],
14759 color_fetcher: fn(&App) -> Hsla,
14760 cx: &mut Context<Self>,
14761 ) {
14762 self.gutter_highlights
14763 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14764 cx.notify();
14765 }
14766
14767 pub fn clear_gutter_highlights<T: 'static>(
14768 &mut self,
14769 cx: &mut Context<Self>,
14770 ) -> Option<GutterHighlight> {
14771 cx.notify();
14772 self.gutter_highlights.remove(&TypeId::of::<T>())
14773 }
14774
14775 #[cfg(feature = "test-support")]
14776 pub fn all_text_background_highlights(
14777 &self,
14778 window: &mut Window,
14779 cx: &mut Context<Self>,
14780 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14781 let snapshot = self.snapshot(window, cx);
14782 let buffer = &snapshot.buffer_snapshot;
14783 let start = buffer.anchor_before(0);
14784 let end = buffer.anchor_after(buffer.len());
14785 let theme = cx.theme().colors();
14786 self.background_highlights_in_range(start..end, &snapshot, theme)
14787 }
14788
14789 #[cfg(feature = "test-support")]
14790 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14791 let snapshot = self.buffer().read(cx).snapshot(cx);
14792
14793 let highlights = self
14794 .background_highlights
14795 .get(&TypeId::of::<items::BufferSearchHighlights>());
14796
14797 if let Some((_color, ranges)) = highlights {
14798 ranges
14799 .iter()
14800 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
14801 .collect_vec()
14802 } else {
14803 vec![]
14804 }
14805 }
14806
14807 fn document_highlights_for_position<'a>(
14808 &'a self,
14809 position: Anchor,
14810 buffer: &'a MultiBufferSnapshot,
14811 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
14812 let read_highlights = self
14813 .background_highlights
14814 .get(&TypeId::of::<DocumentHighlightRead>())
14815 .map(|h| &h.1);
14816 let write_highlights = self
14817 .background_highlights
14818 .get(&TypeId::of::<DocumentHighlightWrite>())
14819 .map(|h| &h.1);
14820 let left_position = position.bias_left(buffer);
14821 let right_position = position.bias_right(buffer);
14822 read_highlights
14823 .into_iter()
14824 .chain(write_highlights)
14825 .flat_map(move |ranges| {
14826 let start_ix = match ranges.binary_search_by(|probe| {
14827 let cmp = probe.end.cmp(&left_position, buffer);
14828 if cmp.is_ge() {
14829 Ordering::Greater
14830 } else {
14831 Ordering::Less
14832 }
14833 }) {
14834 Ok(i) | Err(i) => i,
14835 };
14836
14837 ranges[start_ix..]
14838 .iter()
14839 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
14840 })
14841 }
14842
14843 pub fn has_background_highlights<T: 'static>(&self) -> bool {
14844 self.background_highlights
14845 .get(&TypeId::of::<T>())
14846 .map_or(false, |(_, highlights)| !highlights.is_empty())
14847 }
14848
14849 pub fn background_highlights_in_range(
14850 &self,
14851 search_range: Range<Anchor>,
14852 display_snapshot: &DisplaySnapshot,
14853 theme: &ThemeColors,
14854 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14855 let mut results = Vec::new();
14856 for (color_fetcher, ranges) in self.background_highlights.values() {
14857 let color = color_fetcher(theme);
14858 let start_ix = match ranges.binary_search_by(|probe| {
14859 let cmp = probe
14860 .end
14861 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14862 if cmp.is_gt() {
14863 Ordering::Greater
14864 } else {
14865 Ordering::Less
14866 }
14867 }) {
14868 Ok(i) | Err(i) => i,
14869 };
14870 for range in &ranges[start_ix..] {
14871 if range
14872 .start
14873 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14874 .is_ge()
14875 {
14876 break;
14877 }
14878
14879 let start = range.start.to_display_point(display_snapshot);
14880 let end = range.end.to_display_point(display_snapshot);
14881 results.push((start..end, color))
14882 }
14883 }
14884 results
14885 }
14886
14887 pub fn background_highlight_row_ranges<T: 'static>(
14888 &self,
14889 search_range: Range<Anchor>,
14890 display_snapshot: &DisplaySnapshot,
14891 count: usize,
14892 ) -> Vec<RangeInclusive<DisplayPoint>> {
14893 let mut results = Vec::new();
14894 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14895 return vec![];
14896 };
14897
14898 let start_ix = match ranges.binary_search_by(|probe| {
14899 let cmp = probe
14900 .end
14901 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14902 if cmp.is_gt() {
14903 Ordering::Greater
14904 } else {
14905 Ordering::Less
14906 }
14907 }) {
14908 Ok(i) | Err(i) => i,
14909 };
14910 let mut push_region = |start: Option<Point>, end: Option<Point>| {
14911 if let (Some(start_display), Some(end_display)) = (start, end) {
14912 results.push(
14913 start_display.to_display_point(display_snapshot)
14914 ..=end_display.to_display_point(display_snapshot),
14915 );
14916 }
14917 };
14918 let mut start_row: Option<Point> = None;
14919 let mut end_row: Option<Point> = None;
14920 if ranges.len() > count {
14921 return Vec::new();
14922 }
14923 for range in &ranges[start_ix..] {
14924 if range
14925 .start
14926 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14927 .is_ge()
14928 {
14929 break;
14930 }
14931 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14932 if let Some(current_row) = &end_row {
14933 if end.row == current_row.row {
14934 continue;
14935 }
14936 }
14937 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14938 if start_row.is_none() {
14939 assert_eq!(end_row, None);
14940 start_row = Some(start);
14941 end_row = Some(end);
14942 continue;
14943 }
14944 if let Some(current_end) = end_row.as_mut() {
14945 if start.row > current_end.row + 1 {
14946 push_region(start_row, end_row);
14947 start_row = Some(start);
14948 end_row = Some(end);
14949 } else {
14950 // Merge two hunks.
14951 *current_end = end;
14952 }
14953 } else {
14954 unreachable!();
14955 }
14956 }
14957 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14958 push_region(start_row, end_row);
14959 results
14960 }
14961
14962 pub fn gutter_highlights_in_range(
14963 &self,
14964 search_range: Range<Anchor>,
14965 display_snapshot: &DisplaySnapshot,
14966 cx: &App,
14967 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14968 let mut results = Vec::new();
14969 for (color_fetcher, ranges) in self.gutter_highlights.values() {
14970 let color = color_fetcher(cx);
14971 let start_ix = match ranges.binary_search_by(|probe| {
14972 let cmp = probe
14973 .end
14974 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14975 if cmp.is_gt() {
14976 Ordering::Greater
14977 } else {
14978 Ordering::Less
14979 }
14980 }) {
14981 Ok(i) | Err(i) => i,
14982 };
14983 for range in &ranges[start_ix..] {
14984 if range
14985 .start
14986 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14987 .is_ge()
14988 {
14989 break;
14990 }
14991
14992 let start = range.start.to_display_point(display_snapshot);
14993 let end = range.end.to_display_point(display_snapshot);
14994 results.push((start..end, color))
14995 }
14996 }
14997 results
14998 }
14999
15000 /// Get the text ranges corresponding to the redaction query
15001 pub fn redacted_ranges(
15002 &self,
15003 search_range: Range<Anchor>,
15004 display_snapshot: &DisplaySnapshot,
15005 cx: &App,
15006 ) -> Vec<Range<DisplayPoint>> {
15007 display_snapshot
15008 .buffer_snapshot
15009 .redacted_ranges(search_range, |file| {
15010 if let Some(file) = file {
15011 file.is_private()
15012 && EditorSettings::get(
15013 Some(SettingsLocation {
15014 worktree_id: file.worktree_id(cx),
15015 path: file.path().as_ref(),
15016 }),
15017 cx,
15018 )
15019 .redact_private_values
15020 } else {
15021 false
15022 }
15023 })
15024 .map(|range| {
15025 range.start.to_display_point(display_snapshot)
15026 ..range.end.to_display_point(display_snapshot)
15027 })
15028 .collect()
15029 }
15030
15031 pub fn highlight_text<T: 'static>(
15032 &mut self,
15033 ranges: Vec<Range<Anchor>>,
15034 style: HighlightStyle,
15035 cx: &mut Context<Self>,
15036 ) {
15037 self.display_map.update(cx, |map, _| {
15038 map.highlight_text(TypeId::of::<T>(), ranges, style)
15039 });
15040 cx.notify();
15041 }
15042
15043 pub(crate) fn highlight_inlays<T: 'static>(
15044 &mut self,
15045 highlights: Vec<InlayHighlight>,
15046 style: HighlightStyle,
15047 cx: &mut Context<Self>,
15048 ) {
15049 self.display_map.update(cx, |map, _| {
15050 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15051 });
15052 cx.notify();
15053 }
15054
15055 pub fn text_highlights<'a, T: 'static>(
15056 &'a self,
15057 cx: &'a App,
15058 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15059 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15060 }
15061
15062 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15063 let cleared = self
15064 .display_map
15065 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15066 if cleared {
15067 cx.notify();
15068 }
15069 }
15070
15071 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15072 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15073 && self.focus_handle.is_focused(window)
15074 }
15075
15076 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15077 self.show_cursor_when_unfocused = is_enabled;
15078 cx.notify();
15079 }
15080
15081 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15082 cx.notify();
15083 }
15084
15085 fn on_buffer_event(
15086 &mut self,
15087 multibuffer: &Entity<MultiBuffer>,
15088 event: &multi_buffer::Event,
15089 window: &mut Window,
15090 cx: &mut Context<Self>,
15091 ) {
15092 match event {
15093 multi_buffer::Event::Edited {
15094 singleton_buffer_edited,
15095 edited_buffer: buffer_edited,
15096 } => {
15097 self.scrollbar_marker_state.dirty = true;
15098 self.active_indent_guides_state.dirty = true;
15099 self.refresh_active_diagnostics(cx);
15100 self.refresh_code_actions(window, cx);
15101 if self.has_active_inline_completion() {
15102 self.update_visible_inline_completion(window, cx);
15103 }
15104 if let Some(buffer) = buffer_edited {
15105 let buffer_id = buffer.read(cx).remote_id();
15106 if !self.registered_buffers.contains_key(&buffer_id) {
15107 if let Some(project) = self.project.as_ref() {
15108 project.update(cx, |project, cx| {
15109 self.registered_buffers.insert(
15110 buffer_id,
15111 project.register_buffer_with_language_servers(&buffer, cx),
15112 );
15113 })
15114 }
15115 }
15116 }
15117 cx.emit(EditorEvent::BufferEdited);
15118 cx.emit(SearchEvent::MatchesInvalidated);
15119 if *singleton_buffer_edited {
15120 if let Some(project) = &self.project {
15121 #[allow(clippy::mutable_key_type)]
15122 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15123 multibuffer
15124 .all_buffers()
15125 .into_iter()
15126 .filter_map(|buffer| {
15127 buffer.update(cx, |buffer, cx| {
15128 let language = buffer.language()?;
15129 let should_discard = project.update(cx, |project, cx| {
15130 project.is_local()
15131 && !project.has_language_servers_for(buffer, cx)
15132 });
15133 should_discard.not().then_some(language.clone())
15134 })
15135 })
15136 .collect::<HashSet<_>>()
15137 });
15138 if !languages_affected.is_empty() {
15139 self.refresh_inlay_hints(
15140 InlayHintRefreshReason::BufferEdited(languages_affected),
15141 cx,
15142 );
15143 }
15144 }
15145 }
15146
15147 let Some(project) = &self.project else { return };
15148 let (telemetry, is_via_ssh) = {
15149 let project = project.read(cx);
15150 let telemetry = project.client().telemetry().clone();
15151 let is_via_ssh = project.is_via_ssh();
15152 (telemetry, is_via_ssh)
15153 };
15154 refresh_linked_ranges(self, window, cx);
15155 telemetry.log_edit_event("editor", is_via_ssh);
15156 }
15157 multi_buffer::Event::ExcerptsAdded {
15158 buffer,
15159 predecessor,
15160 excerpts,
15161 } => {
15162 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15163 let buffer_id = buffer.read(cx).remote_id();
15164 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15165 if let Some(project) = &self.project {
15166 get_uncommitted_diff_for_buffer(
15167 project,
15168 [buffer.clone()],
15169 self.buffer.clone(),
15170 cx,
15171 )
15172 .detach();
15173 }
15174 }
15175 cx.emit(EditorEvent::ExcerptsAdded {
15176 buffer: buffer.clone(),
15177 predecessor: *predecessor,
15178 excerpts: excerpts.clone(),
15179 });
15180 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15181 }
15182 multi_buffer::Event::ExcerptsRemoved { ids } => {
15183 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15184 let buffer = self.buffer.read(cx);
15185 self.registered_buffers
15186 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15187 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15188 }
15189 multi_buffer::Event::ExcerptsEdited { ids } => {
15190 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
15191 }
15192 multi_buffer::Event::ExcerptsExpanded { ids } => {
15193 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15194 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15195 }
15196 multi_buffer::Event::Reparsed(buffer_id) => {
15197 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15198
15199 cx.emit(EditorEvent::Reparsed(*buffer_id));
15200 }
15201 multi_buffer::Event::DiffHunksToggled => {
15202 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15203 }
15204 multi_buffer::Event::LanguageChanged(buffer_id) => {
15205 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15206 cx.emit(EditorEvent::Reparsed(*buffer_id));
15207 cx.notify();
15208 }
15209 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15210 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15211 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15212 cx.emit(EditorEvent::TitleChanged)
15213 }
15214 // multi_buffer::Event::DiffBaseChanged => {
15215 // self.scrollbar_marker_state.dirty = true;
15216 // cx.emit(EditorEvent::DiffBaseChanged);
15217 // cx.notify();
15218 // }
15219 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15220 multi_buffer::Event::DiagnosticsUpdated => {
15221 self.refresh_active_diagnostics(cx);
15222 self.refresh_inline_diagnostics(true, window, cx);
15223 self.scrollbar_marker_state.dirty = true;
15224 cx.notify();
15225 }
15226 _ => {}
15227 };
15228 }
15229
15230 fn on_display_map_changed(
15231 &mut self,
15232 _: Entity<DisplayMap>,
15233 _: &mut Window,
15234 cx: &mut Context<Self>,
15235 ) {
15236 cx.notify();
15237 }
15238
15239 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15240 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15241 self.update_edit_prediction_settings(cx);
15242 self.refresh_inline_completion(true, false, window, cx);
15243 self.refresh_inlay_hints(
15244 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15245 self.selections.newest_anchor().head(),
15246 &self.buffer.read(cx).snapshot(cx),
15247 cx,
15248 )),
15249 cx,
15250 );
15251
15252 let old_cursor_shape = self.cursor_shape;
15253
15254 {
15255 let editor_settings = EditorSettings::get_global(cx);
15256 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15257 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15258 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15259 }
15260
15261 if old_cursor_shape != self.cursor_shape {
15262 cx.emit(EditorEvent::CursorShapeChanged);
15263 }
15264
15265 let project_settings = ProjectSettings::get_global(cx);
15266 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15267
15268 if self.mode == EditorMode::Full {
15269 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15270 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15271 if self.show_inline_diagnostics != show_inline_diagnostics {
15272 self.show_inline_diagnostics = show_inline_diagnostics;
15273 self.refresh_inline_diagnostics(false, window, cx);
15274 }
15275
15276 if self.git_blame_inline_enabled != inline_blame_enabled {
15277 self.toggle_git_blame_inline_internal(false, window, cx);
15278 }
15279 }
15280
15281 cx.notify();
15282 }
15283
15284 pub fn set_searchable(&mut self, searchable: bool) {
15285 self.searchable = searchable;
15286 }
15287
15288 pub fn searchable(&self) -> bool {
15289 self.searchable
15290 }
15291
15292 fn open_proposed_changes_editor(
15293 &mut self,
15294 _: &OpenProposedChangesEditor,
15295 window: &mut Window,
15296 cx: &mut Context<Self>,
15297 ) {
15298 let Some(workspace) = self.workspace() else {
15299 cx.propagate();
15300 return;
15301 };
15302
15303 let selections = self.selections.all::<usize>(cx);
15304 let multi_buffer = self.buffer.read(cx);
15305 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15306 let mut new_selections_by_buffer = HashMap::default();
15307 for selection in selections {
15308 for (buffer, range, _) in
15309 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15310 {
15311 let mut range = range.to_point(buffer);
15312 range.start.column = 0;
15313 range.end.column = buffer.line_len(range.end.row);
15314 new_selections_by_buffer
15315 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15316 .or_insert(Vec::new())
15317 .push(range)
15318 }
15319 }
15320
15321 let proposed_changes_buffers = new_selections_by_buffer
15322 .into_iter()
15323 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15324 .collect::<Vec<_>>();
15325 let proposed_changes_editor = cx.new(|cx| {
15326 ProposedChangesEditor::new(
15327 "Proposed changes",
15328 proposed_changes_buffers,
15329 self.project.clone(),
15330 window,
15331 cx,
15332 )
15333 });
15334
15335 window.defer(cx, move |window, cx| {
15336 workspace.update(cx, |workspace, cx| {
15337 workspace.active_pane().update(cx, |pane, cx| {
15338 pane.add_item(
15339 Box::new(proposed_changes_editor),
15340 true,
15341 true,
15342 None,
15343 window,
15344 cx,
15345 );
15346 });
15347 });
15348 });
15349 }
15350
15351 pub fn open_excerpts_in_split(
15352 &mut self,
15353 _: &OpenExcerptsSplit,
15354 window: &mut Window,
15355 cx: &mut Context<Self>,
15356 ) {
15357 self.open_excerpts_common(None, true, window, cx)
15358 }
15359
15360 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15361 self.open_excerpts_common(None, false, window, cx)
15362 }
15363
15364 fn open_excerpts_common(
15365 &mut self,
15366 jump_data: Option<JumpData>,
15367 split: bool,
15368 window: &mut Window,
15369 cx: &mut Context<Self>,
15370 ) {
15371 let Some(workspace) = self.workspace() else {
15372 cx.propagate();
15373 return;
15374 };
15375
15376 if self.buffer.read(cx).is_singleton() {
15377 cx.propagate();
15378 return;
15379 }
15380
15381 let mut new_selections_by_buffer = HashMap::default();
15382 match &jump_data {
15383 Some(JumpData::MultiBufferPoint {
15384 excerpt_id,
15385 position,
15386 anchor,
15387 line_offset_from_top,
15388 }) => {
15389 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15390 if let Some(buffer) = multi_buffer_snapshot
15391 .buffer_id_for_excerpt(*excerpt_id)
15392 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15393 {
15394 let buffer_snapshot = buffer.read(cx).snapshot();
15395 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15396 language::ToPoint::to_point(anchor, &buffer_snapshot)
15397 } else {
15398 buffer_snapshot.clip_point(*position, Bias::Left)
15399 };
15400 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15401 new_selections_by_buffer.insert(
15402 buffer,
15403 (
15404 vec![jump_to_offset..jump_to_offset],
15405 Some(*line_offset_from_top),
15406 ),
15407 );
15408 }
15409 }
15410 Some(JumpData::MultiBufferRow {
15411 row,
15412 line_offset_from_top,
15413 }) => {
15414 let point = MultiBufferPoint::new(row.0, 0);
15415 if let Some((buffer, buffer_point, _)) =
15416 self.buffer.read(cx).point_to_buffer_point(point, cx)
15417 {
15418 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15419 new_selections_by_buffer
15420 .entry(buffer)
15421 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15422 .0
15423 .push(buffer_offset..buffer_offset)
15424 }
15425 }
15426 None => {
15427 let selections = self.selections.all::<usize>(cx);
15428 let multi_buffer = self.buffer.read(cx);
15429 for selection in selections {
15430 for (snapshot, range, _, anchor) in multi_buffer
15431 .snapshot(cx)
15432 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15433 {
15434 if let Some(anchor) = anchor {
15435 // selection is in a deleted hunk
15436 let Some(buffer_id) = anchor.buffer_id else {
15437 continue;
15438 };
15439 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15440 continue;
15441 };
15442 let offset = text::ToOffset::to_offset(
15443 &anchor.text_anchor,
15444 &buffer_handle.read(cx).snapshot(),
15445 );
15446 let range = offset..offset;
15447 new_selections_by_buffer
15448 .entry(buffer_handle)
15449 .or_insert((Vec::new(), None))
15450 .0
15451 .push(range)
15452 } else {
15453 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15454 else {
15455 continue;
15456 };
15457 new_selections_by_buffer
15458 .entry(buffer_handle)
15459 .or_insert((Vec::new(), None))
15460 .0
15461 .push(range)
15462 }
15463 }
15464 }
15465 }
15466 }
15467
15468 if new_selections_by_buffer.is_empty() {
15469 return;
15470 }
15471
15472 // We defer the pane interaction because we ourselves are a workspace item
15473 // and activating a new item causes the pane to call a method on us reentrantly,
15474 // which panics if we're on the stack.
15475 window.defer(cx, move |window, cx| {
15476 workspace.update(cx, |workspace, cx| {
15477 let pane = if split {
15478 workspace.adjacent_pane(window, cx)
15479 } else {
15480 workspace.active_pane().clone()
15481 };
15482
15483 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15484 let editor = buffer
15485 .read(cx)
15486 .file()
15487 .is_none()
15488 .then(|| {
15489 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15490 // so `workspace.open_project_item` will never find them, always opening a new editor.
15491 // Instead, we try to activate the existing editor in the pane first.
15492 let (editor, pane_item_index) =
15493 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15494 let editor = item.downcast::<Editor>()?;
15495 let singleton_buffer =
15496 editor.read(cx).buffer().read(cx).as_singleton()?;
15497 if singleton_buffer == buffer {
15498 Some((editor, i))
15499 } else {
15500 None
15501 }
15502 })?;
15503 pane.update(cx, |pane, cx| {
15504 pane.activate_item(pane_item_index, true, true, window, cx)
15505 });
15506 Some(editor)
15507 })
15508 .flatten()
15509 .unwrap_or_else(|| {
15510 workspace.open_project_item::<Self>(
15511 pane.clone(),
15512 buffer,
15513 true,
15514 true,
15515 window,
15516 cx,
15517 )
15518 });
15519
15520 editor.update(cx, |editor, cx| {
15521 let autoscroll = match scroll_offset {
15522 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15523 None => Autoscroll::newest(),
15524 };
15525 let nav_history = editor.nav_history.take();
15526 editor.change_selections(Some(autoscroll), window, cx, |s| {
15527 s.select_ranges(ranges);
15528 });
15529 editor.nav_history = nav_history;
15530 });
15531 }
15532 })
15533 });
15534 }
15535
15536 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15537 let snapshot = self.buffer.read(cx).read(cx);
15538 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15539 Some(
15540 ranges
15541 .iter()
15542 .map(move |range| {
15543 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15544 })
15545 .collect(),
15546 )
15547 }
15548
15549 fn selection_replacement_ranges(
15550 &self,
15551 range: Range<OffsetUtf16>,
15552 cx: &mut App,
15553 ) -> Vec<Range<OffsetUtf16>> {
15554 let selections = self.selections.all::<OffsetUtf16>(cx);
15555 let newest_selection = selections
15556 .iter()
15557 .max_by_key(|selection| selection.id)
15558 .unwrap();
15559 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15560 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15561 let snapshot = self.buffer.read(cx).read(cx);
15562 selections
15563 .into_iter()
15564 .map(|mut selection| {
15565 selection.start.0 =
15566 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15567 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15568 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15569 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15570 })
15571 .collect()
15572 }
15573
15574 fn report_editor_event(
15575 &self,
15576 event_type: &'static str,
15577 file_extension: Option<String>,
15578 cx: &App,
15579 ) {
15580 if cfg!(any(test, feature = "test-support")) {
15581 return;
15582 }
15583
15584 let Some(project) = &self.project else { return };
15585
15586 // If None, we are in a file without an extension
15587 let file = self
15588 .buffer
15589 .read(cx)
15590 .as_singleton()
15591 .and_then(|b| b.read(cx).file());
15592 let file_extension = file_extension.or(file
15593 .as_ref()
15594 .and_then(|file| Path::new(file.file_name(cx)).extension())
15595 .and_then(|e| e.to_str())
15596 .map(|a| a.to_string()));
15597
15598 let vim_mode = cx
15599 .global::<SettingsStore>()
15600 .raw_user_settings()
15601 .get("vim_mode")
15602 == Some(&serde_json::Value::Bool(true));
15603
15604 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15605 let copilot_enabled = edit_predictions_provider
15606 == language::language_settings::EditPredictionProvider::Copilot;
15607 let copilot_enabled_for_language = self
15608 .buffer
15609 .read(cx)
15610 .settings_at(0, cx)
15611 .show_edit_predictions;
15612
15613 let project = project.read(cx);
15614 telemetry::event!(
15615 event_type,
15616 file_extension,
15617 vim_mode,
15618 copilot_enabled,
15619 copilot_enabled_for_language,
15620 edit_predictions_provider,
15621 is_via_ssh = project.is_via_ssh(),
15622 );
15623 }
15624
15625 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15626 /// with each line being an array of {text, highlight} objects.
15627 fn copy_highlight_json(
15628 &mut self,
15629 _: &CopyHighlightJson,
15630 window: &mut Window,
15631 cx: &mut Context<Self>,
15632 ) {
15633 #[derive(Serialize)]
15634 struct Chunk<'a> {
15635 text: String,
15636 highlight: Option<&'a str>,
15637 }
15638
15639 let snapshot = self.buffer.read(cx).snapshot(cx);
15640 let range = self
15641 .selected_text_range(false, window, cx)
15642 .and_then(|selection| {
15643 if selection.range.is_empty() {
15644 None
15645 } else {
15646 Some(selection.range)
15647 }
15648 })
15649 .unwrap_or_else(|| 0..snapshot.len());
15650
15651 let chunks = snapshot.chunks(range, true);
15652 let mut lines = Vec::new();
15653 let mut line: VecDeque<Chunk> = VecDeque::new();
15654
15655 let Some(style) = self.style.as_ref() else {
15656 return;
15657 };
15658
15659 for chunk in chunks {
15660 let highlight = chunk
15661 .syntax_highlight_id
15662 .and_then(|id| id.name(&style.syntax));
15663 let mut chunk_lines = chunk.text.split('\n').peekable();
15664 while let Some(text) = chunk_lines.next() {
15665 let mut merged_with_last_token = false;
15666 if let Some(last_token) = line.back_mut() {
15667 if last_token.highlight == highlight {
15668 last_token.text.push_str(text);
15669 merged_with_last_token = true;
15670 }
15671 }
15672
15673 if !merged_with_last_token {
15674 line.push_back(Chunk {
15675 text: text.into(),
15676 highlight,
15677 });
15678 }
15679
15680 if chunk_lines.peek().is_some() {
15681 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15682 line.pop_front();
15683 }
15684 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15685 line.pop_back();
15686 }
15687
15688 lines.push(mem::take(&mut line));
15689 }
15690 }
15691 }
15692
15693 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15694 return;
15695 };
15696 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15697 }
15698
15699 pub fn open_context_menu(
15700 &mut self,
15701 _: &OpenContextMenu,
15702 window: &mut Window,
15703 cx: &mut Context<Self>,
15704 ) {
15705 self.request_autoscroll(Autoscroll::newest(), cx);
15706 let position = self.selections.newest_display(cx).start;
15707 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15708 }
15709
15710 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15711 &self.inlay_hint_cache
15712 }
15713
15714 pub fn replay_insert_event(
15715 &mut self,
15716 text: &str,
15717 relative_utf16_range: Option<Range<isize>>,
15718 window: &mut Window,
15719 cx: &mut Context<Self>,
15720 ) {
15721 if !self.input_enabled {
15722 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15723 return;
15724 }
15725 if let Some(relative_utf16_range) = relative_utf16_range {
15726 let selections = self.selections.all::<OffsetUtf16>(cx);
15727 self.change_selections(None, window, cx, |s| {
15728 let new_ranges = selections.into_iter().map(|range| {
15729 let start = OffsetUtf16(
15730 range
15731 .head()
15732 .0
15733 .saturating_add_signed(relative_utf16_range.start),
15734 );
15735 let end = OffsetUtf16(
15736 range
15737 .head()
15738 .0
15739 .saturating_add_signed(relative_utf16_range.end),
15740 );
15741 start..end
15742 });
15743 s.select_ranges(new_ranges);
15744 });
15745 }
15746
15747 self.handle_input(text, window, cx);
15748 }
15749
15750 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15751 let Some(provider) = self.semantics_provider.as_ref() else {
15752 return false;
15753 };
15754
15755 let mut supports = false;
15756 self.buffer().update(cx, |this, cx| {
15757 this.for_each_buffer(|buffer| {
15758 supports |= provider.supports_inlay_hints(buffer, cx);
15759 });
15760 });
15761
15762 supports
15763 }
15764
15765 pub fn is_focused(&self, window: &Window) -> bool {
15766 self.focus_handle.is_focused(window)
15767 }
15768
15769 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15770 cx.emit(EditorEvent::Focused);
15771
15772 if let Some(descendant) = self
15773 .last_focused_descendant
15774 .take()
15775 .and_then(|descendant| descendant.upgrade())
15776 {
15777 window.focus(&descendant);
15778 } else {
15779 if let Some(blame) = self.blame.as_ref() {
15780 blame.update(cx, GitBlame::focus)
15781 }
15782
15783 self.blink_manager.update(cx, BlinkManager::enable);
15784 self.show_cursor_names(window, cx);
15785 self.buffer.update(cx, |buffer, cx| {
15786 buffer.finalize_last_transaction(cx);
15787 if self.leader_peer_id.is_none() {
15788 buffer.set_active_selections(
15789 &self.selections.disjoint_anchors(),
15790 self.selections.line_mode,
15791 self.cursor_shape,
15792 cx,
15793 );
15794 }
15795 });
15796 }
15797 }
15798
15799 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15800 cx.emit(EditorEvent::FocusedIn)
15801 }
15802
15803 fn handle_focus_out(
15804 &mut self,
15805 event: FocusOutEvent,
15806 _window: &mut Window,
15807 _cx: &mut Context<Self>,
15808 ) {
15809 if event.blurred != self.focus_handle {
15810 self.last_focused_descendant = Some(event.blurred);
15811 }
15812 }
15813
15814 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15815 self.blink_manager.update(cx, BlinkManager::disable);
15816 self.buffer
15817 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
15818
15819 if let Some(blame) = self.blame.as_ref() {
15820 blame.update(cx, GitBlame::blur)
15821 }
15822 if !self.hover_state.focused(window, cx) {
15823 hide_hover(self, cx);
15824 }
15825 if !self
15826 .context_menu
15827 .borrow()
15828 .as_ref()
15829 .is_some_and(|context_menu| context_menu.focused(window, cx))
15830 {
15831 self.hide_context_menu(window, cx);
15832 }
15833 self.discard_inline_completion(false, cx);
15834 cx.emit(EditorEvent::Blurred);
15835 cx.notify();
15836 }
15837
15838 pub fn register_action<A: Action>(
15839 &mut self,
15840 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
15841 ) -> Subscription {
15842 let id = self.next_editor_action_id.post_inc();
15843 let listener = Arc::new(listener);
15844 self.editor_actions.borrow_mut().insert(
15845 id,
15846 Box::new(move |window, _| {
15847 let listener = listener.clone();
15848 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
15849 let action = action.downcast_ref().unwrap();
15850 if phase == DispatchPhase::Bubble {
15851 listener(action, window, cx)
15852 }
15853 })
15854 }),
15855 );
15856
15857 let editor_actions = self.editor_actions.clone();
15858 Subscription::new(move || {
15859 editor_actions.borrow_mut().remove(&id);
15860 })
15861 }
15862
15863 pub fn file_header_size(&self) -> u32 {
15864 FILE_HEADER_HEIGHT
15865 }
15866
15867 pub fn revert(
15868 &mut self,
15869 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
15870 window: &mut Window,
15871 cx: &mut Context<Self>,
15872 ) {
15873 self.buffer().update(cx, |multi_buffer, cx| {
15874 for (buffer_id, changes) in revert_changes {
15875 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
15876 buffer.update(cx, |buffer, cx| {
15877 buffer.edit(
15878 changes.into_iter().map(|(range, text)| {
15879 (range, text.to_string().map(Arc::<str>::from))
15880 }),
15881 None,
15882 cx,
15883 );
15884 });
15885 }
15886 }
15887 });
15888 self.change_selections(None, window, cx, |selections| selections.refresh());
15889 }
15890
15891 pub fn to_pixel_point(
15892 &self,
15893 source: multi_buffer::Anchor,
15894 editor_snapshot: &EditorSnapshot,
15895 window: &mut Window,
15896 ) -> Option<gpui::Point<Pixels>> {
15897 let source_point = source.to_display_point(editor_snapshot);
15898 self.display_to_pixel_point(source_point, editor_snapshot, window)
15899 }
15900
15901 pub fn display_to_pixel_point(
15902 &self,
15903 source: DisplayPoint,
15904 editor_snapshot: &EditorSnapshot,
15905 window: &mut Window,
15906 ) -> Option<gpui::Point<Pixels>> {
15907 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15908 let text_layout_details = self.text_layout_details(window);
15909 let scroll_top = text_layout_details
15910 .scroll_anchor
15911 .scroll_position(editor_snapshot)
15912 .y;
15913
15914 if source.row().as_f32() < scroll_top.floor() {
15915 return None;
15916 }
15917 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15918 let source_y = line_height * (source.row().as_f32() - scroll_top);
15919 Some(gpui::Point::new(source_x, source_y))
15920 }
15921
15922 pub fn has_visible_completions_menu(&self) -> bool {
15923 !self.edit_prediction_preview_is_active()
15924 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15925 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15926 })
15927 }
15928
15929 pub fn register_addon<T: Addon>(&mut self, instance: T) {
15930 self.addons
15931 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15932 }
15933
15934 pub fn unregister_addon<T: Addon>(&mut self) {
15935 self.addons.remove(&std::any::TypeId::of::<T>());
15936 }
15937
15938 pub fn addon<T: Addon>(&self) -> Option<&T> {
15939 let type_id = std::any::TypeId::of::<T>();
15940 self.addons
15941 .get(&type_id)
15942 .and_then(|item| item.to_any().downcast_ref::<T>())
15943 }
15944
15945 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15946 let text_layout_details = self.text_layout_details(window);
15947 let style = &text_layout_details.editor_style;
15948 let font_id = window.text_system().resolve_font(&style.text.font());
15949 let font_size = style.text.font_size.to_pixels(window.rem_size());
15950 let line_height = style.text.line_height_in_pixels(window.rem_size());
15951 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15952
15953 gpui::Size::new(em_width, line_height)
15954 }
15955
15956 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15957 self.load_diff_task.clone()
15958 }
15959
15960 fn read_selections_from_db(
15961 &mut self,
15962 item_id: u64,
15963 workspace_id: WorkspaceId,
15964 window: &mut Window,
15965 cx: &mut Context<Editor>,
15966 ) {
15967 if !self.is_singleton(cx)
15968 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15969 {
15970 return;
15971 }
15972 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15973 return;
15974 };
15975 if selections.is_empty() {
15976 return;
15977 }
15978
15979 let snapshot = self.buffer.read(cx).snapshot(cx);
15980 self.change_selections(None, window, cx, |s| {
15981 s.select_ranges(selections.into_iter().map(|(start, end)| {
15982 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15983 }));
15984 });
15985 }
15986}
15987
15988fn insert_extra_newline_brackets(
15989 buffer: &MultiBufferSnapshot,
15990 range: Range<usize>,
15991 language: &language::LanguageScope,
15992) -> bool {
15993 let leading_whitespace_len = buffer
15994 .reversed_chars_at(range.start)
15995 .take_while(|c| c.is_whitespace() && *c != '\n')
15996 .map(|c| c.len_utf8())
15997 .sum::<usize>();
15998 let trailing_whitespace_len = buffer
15999 .chars_at(range.end)
16000 .take_while(|c| c.is_whitespace() && *c != '\n')
16001 .map(|c| c.len_utf8())
16002 .sum::<usize>();
16003 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16004
16005 language.brackets().any(|(pair, enabled)| {
16006 let pair_start = pair.start.trim_end();
16007 let pair_end = pair.end.trim_start();
16008
16009 enabled
16010 && pair.newline
16011 && buffer.contains_str_at(range.end, pair_end)
16012 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16013 })
16014}
16015
16016fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16017 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16018 [(buffer, range, _)] => (*buffer, range.clone()),
16019 _ => return false,
16020 };
16021 let pair = {
16022 let mut result: Option<BracketMatch> = None;
16023
16024 for pair in buffer
16025 .all_bracket_ranges(range.clone())
16026 .filter(move |pair| {
16027 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16028 })
16029 {
16030 let len = pair.close_range.end - pair.open_range.start;
16031
16032 if let Some(existing) = &result {
16033 let existing_len = existing.close_range.end - existing.open_range.start;
16034 if len > existing_len {
16035 continue;
16036 }
16037 }
16038
16039 result = Some(pair);
16040 }
16041
16042 result
16043 };
16044 let Some(pair) = pair else {
16045 return false;
16046 };
16047 pair.newline_only
16048 && buffer
16049 .chars_for_range(pair.open_range.end..range.start)
16050 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16051 .all(|c| c.is_whitespace() && c != '\n')
16052}
16053
16054fn get_uncommitted_diff_for_buffer(
16055 project: &Entity<Project>,
16056 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16057 buffer: Entity<MultiBuffer>,
16058 cx: &mut App,
16059) -> Task<()> {
16060 let mut tasks = Vec::new();
16061 project.update(cx, |project, cx| {
16062 for buffer in buffers {
16063 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16064 }
16065 });
16066 cx.spawn(|mut cx| async move {
16067 let diffs = futures::future::join_all(tasks).await;
16068 buffer
16069 .update(&mut cx, |buffer, cx| {
16070 for diff in diffs.into_iter().flatten() {
16071 buffer.add_diff(diff, cx);
16072 }
16073 })
16074 .ok();
16075 })
16076}
16077
16078fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16079 let tab_size = tab_size.get() as usize;
16080 let mut width = offset;
16081
16082 for ch in text.chars() {
16083 width += if ch == '\t' {
16084 tab_size - (width % tab_size)
16085 } else {
16086 1
16087 };
16088 }
16089
16090 width - offset
16091}
16092
16093#[cfg(test)]
16094mod tests {
16095 use super::*;
16096
16097 #[test]
16098 fn test_string_size_with_expanded_tabs() {
16099 let nz = |val| NonZeroU32::new(val).unwrap();
16100 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16101 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16102 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16103 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16104 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16105 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16106 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16107 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16108 }
16109}
16110
16111/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16112struct WordBreakingTokenizer<'a> {
16113 input: &'a str,
16114}
16115
16116impl<'a> WordBreakingTokenizer<'a> {
16117 fn new(input: &'a str) -> Self {
16118 Self { input }
16119 }
16120}
16121
16122fn is_char_ideographic(ch: char) -> bool {
16123 use unicode_script::Script::*;
16124 use unicode_script::UnicodeScript;
16125 matches!(ch.script(), Han | Tangut | Yi)
16126}
16127
16128fn is_grapheme_ideographic(text: &str) -> bool {
16129 text.chars().any(is_char_ideographic)
16130}
16131
16132fn is_grapheme_whitespace(text: &str) -> bool {
16133 text.chars().any(|x| x.is_whitespace())
16134}
16135
16136fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16137 text.chars().next().map_or(false, |ch| {
16138 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16139 })
16140}
16141
16142#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16143struct WordBreakToken<'a> {
16144 token: &'a str,
16145 grapheme_len: usize,
16146 is_whitespace: bool,
16147}
16148
16149impl<'a> Iterator for WordBreakingTokenizer<'a> {
16150 /// Yields a span, the count of graphemes in the token, and whether it was
16151 /// whitespace. Note that it also breaks at word boundaries.
16152 type Item = WordBreakToken<'a>;
16153
16154 fn next(&mut self) -> Option<Self::Item> {
16155 use unicode_segmentation::UnicodeSegmentation;
16156 if self.input.is_empty() {
16157 return None;
16158 }
16159
16160 let mut iter = self.input.graphemes(true).peekable();
16161 let mut offset = 0;
16162 let mut graphemes = 0;
16163 if let Some(first_grapheme) = iter.next() {
16164 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16165 offset += first_grapheme.len();
16166 graphemes += 1;
16167 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16168 if let Some(grapheme) = iter.peek().copied() {
16169 if should_stay_with_preceding_ideograph(grapheme) {
16170 offset += grapheme.len();
16171 graphemes += 1;
16172 }
16173 }
16174 } else {
16175 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16176 let mut next_word_bound = words.peek().copied();
16177 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16178 next_word_bound = words.next();
16179 }
16180 while let Some(grapheme) = iter.peek().copied() {
16181 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16182 break;
16183 };
16184 if is_grapheme_whitespace(grapheme) != is_whitespace {
16185 break;
16186 };
16187 offset += grapheme.len();
16188 graphemes += 1;
16189 iter.next();
16190 }
16191 }
16192 let token = &self.input[..offset];
16193 self.input = &self.input[offset..];
16194 if is_whitespace {
16195 Some(WordBreakToken {
16196 token: " ",
16197 grapheme_len: 1,
16198 is_whitespace: true,
16199 })
16200 } else {
16201 Some(WordBreakToken {
16202 token,
16203 grapheme_len: graphemes,
16204 is_whitespace: false,
16205 })
16206 }
16207 } else {
16208 None
16209 }
16210 }
16211}
16212
16213#[test]
16214fn test_word_breaking_tokenizer() {
16215 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16216 ("", &[]),
16217 (" ", &[(" ", 1, true)]),
16218 ("Ʒ", &[("Ʒ", 1, false)]),
16219 ("Ǽ", &[("Ǽ", 1, false)]),
16220 ("⋑", &[("⋑", 1, false)]),
16221 ("⋑⋑", &[("⋑⋑", 2, false)]),
16222 (
16223 "原理,进而",
16224 &[
16225 ("原", 1, false),
16226 ("理,", 2, false),
16227 ("进", 1, false),
16228 ("而", 1, false),
16229 ],
16230 ),
16231 (
16232 "hello world",
16233 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16234 ),
16235 (
16236 "hello, world",
16237 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16238 ),
16239 (
16240 " hello world",
16241 &[
16242 (" ", 1, true),
16243 ("hello", 5, false),
16244 (" ", 1, true),
16245 ("world", 5, false),
16246 ],
16247 ),
16248 (
16249 "这是什么 \n 钢笔",
16250 &[
16251 ("这", 1, false),
16252 ("是", 1, false),
16253 ("什", 1, false),
16254 ("么", 1, false),
16255 (" ", 1, true),
16256 ("钢", 1, false),
16257 ("笔", 1, false),
16258 ],
16259 ),
16260 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16261 ];
16262
16263 for (input, result) in tests {
16264 assert_eq!(
16265 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16266 result
16267 .iter()
16268 .copied()
16269 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16270 token,
16271 grapheme_len,
16272 is_whitespace,
16273 })
16274 .collect::<Vec<_>>()
16275 );
16276 }
16277}
16278
16279fn wrap_with_prefix(
16280 line_prefix: String,
16281 unwrapped_text: String,
16282 wrap_column: usize,
16283 tab_size: NonZeroU32,
16284) -> String {
16285 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16286 let mut wrapped_text = String::new();
16287 let mut current_line = line_prefix.clone();
16288
16289 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16290 let mut current_line_len = line_prefix_len;
16291 for WordBreakToken {
16292 token,
16293 grapheme_len,
16294 is_whitespace,
16295 } in tokenizer
16296 {
16297 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16298 wrapped_text.push_str(current_line.trim_end());
16299 wrapped_text.push('\n');
16300 current_line.truncate(line_prefix.len());
16301 current_line_len = line_prefix_len;
16302 if !is_whitespace {
16303 current_line.push_str(token);
16304 current_line_len += grapheme_len;
16305 }
16306 } else if !is_whitespace {
16307 current_line.push_str(token);
16308 current_line_len += grapheme_len;
16309 } else if current_line_len != line_prefix_len {
16310 current_line.push(' ');
16311 current_line_len += 1;
16312 }
16313 }
16314
16315 if !current_line.is_empty() {
16316 wrapped_text.push_str(¤t_line);
16317 }
16318 wrapped_text
16319}
16320
16321#[test]
16322fn test_wrap_with_prefix() {
16323 assert_eq!(
16324 wrap_with_prefix(
16325 "# ".to_string(),
16326 "abcdefg".to_string(),
16327 4,
16328 NonZeroU32::new(4).unwrap()
16329 ),
16330 "# abcdefg"
16331 );
16332 assert_eq!(
16333 wrap_with_prefix(
16334 "".to_string(),
16335 "\thello world".to_string(),
16336 8,
16337 NonZeroU32::new(4).unwrap()
16338 ),
16339 "hello\nworld"
16340 );
16341 assert_eq!(
16342 wrap_with_prefix(
16343 "// ".to_string(),
16344 "xx \nyy zz aa bb cc".to_string(),
16345 12,
16346 NonZeroU32::new(4).unwrap()
16347 ),
16348 "// xx yy zz\n// aa bb cc"
16349 );
16350 assert_eq!(
16351 wrap_with_prefix(
16352 String::new(),
16353 "这是什么 \n 钢笔".to_string(),
16354 3,
16355 NonZeroU32::new(4).unwrap()
16356 ),
16357 "这是什\n么 钢\n笔"
16358 );
16359}
16360
16361pub trait CollaborationHub {
16362 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16363 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16364 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16365}
16366
16367impl CollaborationHub for Entity<Project> {
16368 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16369 self.read(cx).collaborators()
16370 }
16371
16372 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16373 self.read(cx).user_store().read(cx).participant_indices()
16374 }
16375
16376 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16377 let this = self.read(cx);
16378 let user_ids = this.collaborators().values().map(|c| c.user_id);
16379 this.user_store().read_with(cx, |user_store, cx| {
16380 user_store.participant_names(user_ids, cx)
16381 })
16382 }
16383}
16384
16385pub trait SemanticsProvider {
16386 fn hover(
16387 &self,
16388 buffer: &Entity<Buffer>,
16389 position: text::Anchor,
16390 cx: &mut App,
16391 ) -> Option<Task<Vec<project::Hover>>>;
16392
16393 fn inlay_hints(
16394 &self,
16395 buffer_handle: Entity<Buffer>,
16396 range: Range<text::Anchor>,
16397 cx: &mut App,
16398 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16399
16400 fn resolve_inlay_hint(
16401 &self,
16402 hint: InlayHint,
16403 buffer_handle: Entity<Buffer>,
16404 server_id: LanguageServerId,
16405 cx: &mut App,
16406 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16407
16408 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16409
16410 fn document_highlights(
16411 &self,
16412 buffer: &Entity<Buffer>,
16413 position: text::Anchor,
16414 cx: &mut App,
16415 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16416
16417 fn definitions(
16418 &self,
16419 buffer: &Entity<Buffer>,
16420 position: text::Anchor,
16421 kind: GotoDefinitionKind,
16422 cx: &mut App,
16423 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16424
16425 fn range_for_rename(
16426 &self,
16427 buffer: &Entity<Buffer>,
16428 position: text::Anchor,
16429 cx: &mut App,
16430 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16431
16432 fn perform_rename(
16433 &self,
16434 buffer: &Entity<Buffer>,
16435 position: text::Anchor,
16436 new_name: String,
16437 cx: &mut App,
16438 ) -> Option<Task<Result<ProjectTransaction>>>;
16439}
16440
16441pub trait CompletionProvider {
16442 fn completions(
16443 &self,
16444 buffer: &Entity<Buffer>,
16445 buffer_position: text::Anchor,
16446 trigger: CompletionContext,
16447 window: &mut Window,
16448 cx: &mut Context<Editor>,
16449 ) -> Task<Result<Vec<Completion>>>;
16450
16451 fn resolve_completions(
16452 &self,
16453 buffer: Entity<Buffer>,
16454 completion_indices: Vec<usize>,
16455 completions: Rc<RefCell<Box<[Completion]>>>,
16456 cx: &mut Context<Editor>,
16457 ) -> Task<Result<bool>>;
16458
16459 fn apply_additional_edits_for_completion(
16460 &self,
16461 _buffer: Entity<Buffer>,
16462 _completions: Rc<RefCell<Box<[Completion]>>>,
16463 _completion_index: usize,
16464 _push_to_history: bool,
16465 _cx: &mut Context<Editor>,
16466 ) -> Task<Result<Option<language::Transaction>>> {
16467 Task::ready(Ok(None))
16468 }
16469
16470 fn is_completion_trigger(
16471 &self,
16472 buffer: &Entity<Buffer>,
16473 position: language::Anchor,
16474 text: &str,
16475 trigger_in_words: bool,
16476 cx: &mut Context<Editor>,
16477 ) -> bool;
16478
16479 fn sort_completions(&self) -> bool {
16480 true
16481 }
16482}
16483
16484pub trait CodeActionProvider {
16485 fn id(&self) -> Arc<str>;
16486
16487 fn code_actions(
16488 &self,
16489 buffer: &Entity<Buffer>,
16490 range: Range<text::Anchor>,
16491 window: &mut Window,
16492 cx: &mut App,
16493 ) -> Task<Result<Vec<CodeAction>>>;
16494
16495 fn apply_code_action(
16496 &self,
16497 buffer_handle: Entity<Buffer>,
16498 action: CodeAction,
16499 excerpt_id: ExcerptId,
16500 push_to_history: bool,
16501 window: &mut Window,
16502 cx: &mut App,
16503 ) -> Task<Result<ProjectTransaction>>;
16504}
16505
16506impl CodeActionProvider for Entity<Project> {
16507 fn id(&self) -> Arc<str> {
16508 "project".into()
16509 }
16510
16511 fn code_actions(
16512 &self,
16513 buffer: &Entity<Buffer>,
16514 range: Range<text::Anchor>,
16515 _window: &mut Window,
16516 cx: &mut App,
16517 ) -> Task<Result<Vec<CodeAction>>> {
16518 self.update(cx, |project, cx| {
16519 project.code_actions(buffer, range, None, cx)
16520 })
16521 }
16522
16523 fn apply_code_action(
16524 &self,
16525 buffer_handle: Entity<Buffer>,
16526 action: CodeAction,
16527 _excerpt_id: ExcerptId,
16528 push_to_history: bool,
16529 _window: &mut Window,
16530 cx: &mut App,
16531 ) -> Task<Result<ProjectTransaction>> {
16532 self.update(cx, |project, cx| {
16533 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16534 })
16535 }
16536}
16537
16538fn snippet_completions(
16539 project: &Project,
16540 buffer: &Entity<Buffer>,
16541 buffer_position: text::Anchor,
16542 cx: &mut App,
16543) -> Task<Result<Vec<Completion>>> {
16544 let language = buffer.read(cx).language_at(buffer_position);
16545 let language_name = language.as_ref().map(|language| language.lsp_id());
16546 let snippet_store = project.snippets().read(cx);
16547 let snippets = snippet_store.snippets_for(language_name, cx);
16548
16549 if snippets.is_empty() {
16550 return Task::ready(Ok(vec![]));
16551 }
16552 let snapshot = buffer.read(cx).text_snapshot();
16553 let chars: String = snapshot
16554 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16555 .collect();
16556
16557 let scope = language.map(|language| language.default_scope());
16558 let executor = cx.background_executor().clone();
16559
16560 cx.background_spawn(async move {
16561 let classifier = CharClassifier::new(scope).for_completion(true);
16562 let mut last_word = chars
16563 .chars()
16564 .take_while(|c| classifier.is_word(*c))
16565 .collect::<String>();
16566 last_word = last_word.chars().rev().collect();
16567
16568 if last_word.is_empty() {
16569 return Ok(vec![]);
16570 }
16571
16572 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16573 let to_lsp = |point: &text::Anchor| {
16574 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16575 point_to_lsp(end)
16576 };
16577 let lsp_end = to_lsp(&buffer_position);
16578
16579 let candidates = snippets
16580 .iter()
16581 .enumerate()
16582 .flat_map(|(ix, snippet)| {
16583 snippet
16584 .prefix
16585 .iter()
16586 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16587 })
16588 .collect::<Vec<StringMatchCandidate>>();
16589
16590 let mut matches = fuzzy::match_strings(
16591 &candidates,
16592 &last_word,
16593 last_word.chars().any(|c| c.is_uppercase()),
16594 100,
16595 &Default::default(),
16596 executor,
16597 )
16598 .await;
16599
16600 // Remove all candidates where the query's start does not match the start of any word in the candidate
16601 if let Some(query_start) = last_word.chars().next() {
16602 matches.retain(|string_match| {
16603 split_words(&string_match.string).any(|word| {
16604 // Check that the first codepoint of the word as lowercase matches the first
16605 // codepoint of the query as lowercase
16606 word.chars()
16607 .flat_map(|codepoint| codepoint.to_lowercase())
16608 .zip(query_start.to_lowercase())
16609 .all(|(word_cp, query_cp)| word_cp == query_cp)
16610 })
16611 });
16612 }
16613
16614 let matched_strings = matches
16615 .into_iter()
16616 .map(|m| m.string)
16617 .collect::<HashSet<_>>();
16618
16619 let result: Vec<Completion> = snippets
16620 .into_iter()
16621 .filter_map(|snippet| {
16622 let matching_prefix = snippet
16623 .prefix
16624 .iter()
16625 .find(|prefix| matched_strings.contains(*prefix))?;
16626 let start = as_offset - last_word.len();
16627 let start = snapshot.anchor_before(start);
16628 let range = start..buffer_position;
16629 let lsp_start = to_lsp(&start);
16630 let lsp_range = lsp::Range {
16631 start: lsp_start,
16632 end: lsp_end,
16633 };
16634 Some(Completion {
16635 old_range: range,
16636 new_text: snippet.body.clone(),
16637 resolved: false,
16638 label: CodeLabel {
16639 text: matching_prefix.clone(),
16640 runs: vec![],
16641 filter_range: 0..matching_prefix.len(),
16642 },
16643 server_id: LanguageServerId(usize::MAX),
16644 documentation: snippet
16645 .description
16646 .clone()
16647 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16648 lsp_completion: lsp::CompletionItem {
16649 label: snippet.prefix.first().unwrap().clone(),
16650 kind: Some(CompletionItemKind::SNIPPET),
16651 label_details: snippet.description.as_ref().map(|description| {
16652 lsp::CompletionItemLabelDetails {
16653 detail: Some(description.clone()),
16654 description: None,
16655 }
16656 }),
16657 insert_text_format: Some(InsertTextFormat::SNIPPET),
16658 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16659 lsp::InsertReplaceEdit {
16660 new_text: snippet.body.clone(),
16661 insert: lsp_range,
16662 replace: lsp_range,
16663 },
16664 )),
16665 filter_text: Some(snippet.body.clone()),
16666 sort_text: Some(char::MAX.to_string()),
16667 ..Default::default()
16668 },
16669 confirm: None,
16670 })
16671 })
16672 .collect();
16673
16674 Ok(result)
16675 })
16676}
16677
16678impl CompletionProvider for Entity<Project> {
16679 fn completions(
16680 &self,
16681 buffer: &Entity<Buffer>,
16682 buffer_position: text::Anchor,
16683 options: CompletionContext,
16684 _window: &mut Window,
16685 cx: &mut Context<Editor>,
16686 ) -> Task<Result<Vec<Completion>>> {
16687 self.update(cx, |project, cx| {
16688 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16689 let project_completions = project.completions(buffer, buffer_position, options, cx);
16690 cx.background_spawn(async move {
16691 let mut completions = project_completions.await?;
16692 let snippets_completions = snippets.await?;
16693 completions.extend(snippets_completions);
16694 Ok(completions)
16695 })
16696 })
16697 }
16698
16699 fn resolve_completions(
16700 &self,
16701 buffer: Entity<Buffer>,
16702 completion_indices: Vec<usize>,
16703 completions: Rc<RefCell<Box<[Completion]>>>,
16704 cx: &mut Context<Editor>,
16705 ) -> Task<Result<bool>> {
16706 self.update(cx, |project, cx| {
16707 project.lsp_store().update(cx, |lsp_store, cx| {
16708 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16709 })
16710 })
16711 }
16712
16713 fn apply_additional_edits_for_completion(
16714 &self,
16715 buffer: Entity<Buffer>,
16716 completions: Rc<RefCell<Box<[Completion]>>>,
16717 completion_index: usize,
16718 push_to_history: bool,
16719 cx: &mut Context<Editor>,
16720 ) -> Task<Result<Option<language::Transaction>>> {
16721 self.update(cx, |project, cx| {
16722 project.lsp_store().update(cx, |lsp_store, cx| {
16723 lsp_store.apply_additional_edits_for_completion(
16724 buffer,
16725 completions,
16726 completion_index,
16727 push_to_history,
16728 cx,
16729 )
16730 })
16731 })
16732 }
16733
16734 fn is_completion_trigger(
16735 &self,
16736 buffer: &Entity<Buffer>,
16737 position: language::Anchor,
16738 text: &str,
16739 trigger_in_words: bool,
16740 cx: &mut Context<Editor>,
16741 ) -> bool {
16742 let mut chars = text.chars();
16743 let char = if let Some(char) = chars.next() {
16744 char
16745 } else {
16746 return false;
16747 };
16748 if chars.next().is_some() {
16749 return false;
16750 }
16751
16752 let buffer = buffer.read(cx);
16753 let snapshot = buffer.snapshot();
16754 if !snapshot.settings_at(position, cx).show_completions_on_input {
16755 return false;
16756 }
16757 let classifier = snapshot.char_classifier_at(position).for_completion(true);
16758 if trigger_in_words && classifier.is_word(char) {
16759 return true;
16760 }
16761
16762 buffer.completion_triggers().contains(text)
16763 }
16764}
16765
16766impl SemanticsProvider for Entity<Project> {
16767 fn hover(
16768 &self,
16769 buffer: &Entity<Buffer>,
16770 position: text::Anchor,
16771 cx: &mut App,
16772 ) -> Option<Task<Vec<project::Hover>>> {
16773 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
16774 }
16775
16776 fn document_highlights(
16777 &self,
16778 buffer: &Entity<Buffer>,
16779 position: text::Anchor,
16780 cx: &mut App,
16781 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
16782 Some(self.update(cx, |project, cx| {
16783 project.document_highlights(buffer, position, cx)
16784 }))
16785 }
16786
16787 fn definitions(
16788 &self,
16789 buffer: &Entity<Buffer>,
16790 position: text::Anchor,
16791 kind: GotoDefinitionKind,
16792 cx: &mut App,
16793 ) -> Option<Task<Result<Vec<LocationLink>>>> {
16794 Some(self.update(cx, |project, cx| match kind {
16795 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
16796 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
16797 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
16798 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
16799 }))
16800 }
16801
16802 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
16803 // TODO: make this work for remote projects
16804 self.update(cx, |this, cx| {
16805 buffer.update(cx, |buffer, cx| {
16806 this.any_language_server_supports_inlay_hints(buffer, cx)
16807 })
16808 })
16809 }
16810
16811 fn inlay_hints(
16812 &self,
16813 buffer_handle: Entity<Buffer>,
16814 range: Range<text::Anchor>,
16815 cx: &mut App,
16816 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
16817 Some(self.update(cx, |project, cx| {
16818 project.inlay_hints(buffer_handle, range, cx)
16819 }))
16820 }
16821
16822 fn resolve_inlay_hint(
16823 &self,
16824 hint: InlayHint,
16825 buffer_handle: Entity<Buffer>,
16826 server_id: LanguageServerId,
16827 cx: &mut App,
16828 ) -> Option<Task<anyhow::Result<InlayHint>>> {
16829 Some(self.update(cx, |project, cx| {
16830 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
16831 }))
16832 }
16833
16834 fn range_for_rename(
16835 &self,
16836 buffer: &Entity<Buffer>,
16837 position: text::Anchor,
16838 cx: &mut App,
16839 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
16840 Some(self.update(cx, |project, cx| {
16841 let buffer = buffer.clone();
16842 let task = project.prepare_rename(buffer.clone(), position, cx);
16843 cx.spawn(|_, mut cx| async move {
16844 Ok(match task.await? {
16845 PrepareRenameResponse::Success(range) => Some(range),
16846 PrepareRenameResponse::InvalidPosition => None,
16847 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
16848 // Fallback on using TreeSitter info to determine identifier range
16849 buffer.update(&mut cx, |buffer, _| {
16850 let snapshot = buffer.snapshot();
16851 let (range, kind) = snapshot.surrounding_word(position);
16852 if kind != Some(CharKind::Word) {
16853 return None;
16854 }
16855 Some(
16856 snapshot.anchor_before(range.start)
16857 ..snapshot.anchor_after(range.end),
16858 )
16859 })?
16860 }
16861 })
16862 })
16863 }))
16864 }
16865
16866 fn perform_rename(
16867 &self,
16868 buffer: &Entity<Buffer>,
16869 position: text::Anchor,
16870 new_name: String,
16871 cx: &mut App,
16872 ) -> Option<Task<Result<ProjectTransaction>>> {
16873 Some(self.update(cx, |project, cx| {
16874 project.perform_rename(buffer.clone(), position, new_name, cx)
16875 }))
16876 }
16877}
16878
16879fn inlay_hint_settings(
16880 location: Anchor,
16881 snapshot: &MultiBufferSnapshot,
16882 cx: &mut Context<Editor>,
16883) -> InlayHintSettings {
16884 let file = snapshot.file_at(location);
16885 let language = snapshot.language_at(location).map(|l| l.name());
16886 language_settings(language, file, cx).inlay_hints
16887}
16888
16889fn consume_contiguous_rows(
16890 contiguous_row_selections: &mut Vec<Selection<Point>>,
16891 selection: &Selection<Point>,
16892 display_map: &DisplaySnapshot,
16893 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
16894) -> (MultiBufferRow, MultiBufferRow) {
16895 contiguous_row_selections.push(selection.clone());
16896 let start_row = MultiBufferRow(selection.start.row);
16897 let mut end_row = ending_row(selection, display_map);
16898
16899 while let Some(next_selection) = selections.peek() {
16900 if next_selection.start.row <= end_row.0 {
16901 end_row = ending_row(next_selection, display_map);
16902 contiguous_row_selections.push(selections.next().unwrap().clone());
16903 } else {
16904 break;
16905 }
16906 }
16907 (start_row, end_row)
16908}
16909
16910fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
16911 if next_selection.end.column > 0 || next_selection.is_empty() {
16912 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
16913 } else {
16914 MultiBufferRow(next_selection.end.row)
16915 }
16916}
16917
16918impl EditorSnapshot {
16919 pub fn remote_selections_in_range<'a>(
16920 &'a self,
16921 range: &'a Range<Anchor>,
16922 collaboration_hub: &dyn CollaborationHub,
16923 cx: &'a App,
16924 ) -> impl 'a + Iterator<Item = RemoteSelection> {
16925 let participant_names = collaboration_hub.user_names(cx);
16926 let participant_indices = collaboration_hub.user_participant_indices(cx);
16927 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
16928 let collaborators_by_replica_id = collaborators_by_peer_id
16929 .iter()
16930 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
16931 .collect::<HashMap<_, _>>();
16932 self.buffer_snapshot
16933 .selections_in_range(range, false)
16934 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
16935 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
16936 let participant_index = participant_indices.get(&collaborator.user_id).copied();
16937 let user_name = participant_names.get(&collaborator.user_id).cloned();
16938 Some(RemoteSelection {
16939 replica_id,
16940 selection,
16941 cursor_shape,
16942 line_mode,
16943 participant_index,
16944 peer_id: collaborator.peer_id,
16945 user_name,
16946 })
16947 })
16948 }
16949
16950 pub fn hunks_for_ranges(
16951 &self,
16952 ranges: impl Iterator<Item = Range<Point>>,
16953 ) -> Vec<MultiBufferDiffHunk> {
16954 let mut hunks = Vec::new();
16955 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16956 HashMap::default();
16957 for query_range in ranges {
16958 let query_rows =
16959 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16960 for hunk in self.buffer_snapshot.diff_hunks_in_range(
16961 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16962 ) {
16963 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16964 // when the caret is just above or just below the deleted hunk.
16965 let allow_adjacent = hunk.status().is_deleted();
16966 let related_to_selection = if allow_adjacent {
16967 hunk.row_range.overlaps(&query_rows)
16968 || hunk.row_range.start == query_rows.end
16969 || hunk.row_range.end == query_rows.start
16970 } else {
16971 hunk.row_range.overlaps(&query_rows)
16972 };
16973 if related_to_selection {
16974 if !processed_buffer_rows
16975 .entry(hunk.buffer_id)
16976 .or_default()
16977 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16978 {
16979 continue;
16980 }
16981 hunks.push(hunk);
16982 }
16983 }
16984 }
16985
16986 hunks
16987 }
16988
16989 fn display_diff_hunks_for_rows<'a>(
16990 &'a self,
16991 display_rows: Range<DisplayRow>,
16992 folded_buffers: &'a HashSet<BufferId>,
16993 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
16994 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
16995 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
16996
16997 self.buffer_snapshot
16998 .diff_hunks_in_range(buffer_start..buffer_end)
16999 .filter_map(|hunk| {
17000 if folded_buffers.contains(&hunk.buffer_id) {
17001 return None;
17002 }
17003
17004 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17005 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17006
17007 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17008 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17009
17010 let display_hunk = if hunk_display_start.column() != 0 {
17011 DisplayDiffHunk::Folded {
17012 display_row: hunk_display_start.row(),
17013 }
17014 } else {
17015 let mut end_row = hunk_display_end.row();
17016 if hunk_display_end.column() > 0 {
17017 end_row.0 += 1;
17018 }
17019 DisplayDiffHunk::Unfolded {
17020 status: hunk.status(),
17021 diff_base_byte_range: hunk.diff_base_byte_range,
17022 display_row_range: hunk_display_start.row()..end_row,
17023 multi_buffer_range: Anchor::range_in_buffer(
17024 hunk.excerpt_id,
17025 hunk.buffer_id,
17026 hunk.buffer_range,
17027 ),
17028 }
17029 };
17030
17031 Some(display_hunk)
17032 })
17033 }
17034
17035 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17036 self.display_snapshot.buffer_snapshot.language_at(position)
17037 }
17038
17039 pub fn is_focused(&self) -> bool {
17040 self.is_focused
17041 }
17042
17043 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17044 self.placeholder_text.as_ref()
17045 }
17046
17047 pub fn scroll_position(&self) -> gpui::Point<f32> {
17048 self.scroll_anchor.scroll_position(&self.display_snapshot)
17049 }
17050
17051 fn gutter_dimensions(
17052 &self,
17053 font_id: FontId,
17054 font_size: Pixels,
17055 max_line_number_width: Pixels,
17056 cx: &App,
17057 ) -> Option<GutterDimensions> {
17058 if !self.show_gutter {
17059 return None;
17060 }
17061
17062 let descent = cx.text_system().descent(font_id, font_size);
17063 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17064 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17065
17066 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17067 matches!(
17068 ProjectSettings::get_global(cx).git.git_gutter,
17069 Some(GitGutterSetting::TrackedFiles)
17070 )
17071 });
17072 let gutter_settings = EditorSettings::get_global(cx).gutter;
17073 let show_line_numbers = self
17074 .show_line_numbers
17075 .unwrap_or(gutter_settings.line_numbers);
17076 let line_gutter_width = if show_line_numbers {
17077 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17078 let min_width_for_number_on_gutter = em_advance * 4.0;
17079 max_line_number_width.max(min_width_for_number_on_gutter)
17080 } else {
17081 0.0.into()
17082 };
17083
17084 let show_code_actions = self
17085 .show_code_actions
17086 .unwrap_or(gutter_settings.code_actions);
17087
17088 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17089
17090 let git_blame_entries_width =
17091 self.git_blame_gutter_max_author_length
17092 .map(|max_author_length| {
17093 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17094
17095 /// The number of characters to dedicate to gaps and margins.
17096 const SPACING_WIDTH: usize = 4;
17097
17098 let max_char_count = max_author_length
17099 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17100 + ::git::SHORT_SHA_LENGTH
17101 + MAX_RELATIVE_TIMESTAMP.len()
17102 + SPACING_WIDTH;
17103
17104 em_advance * max_char_count
17105 });
17106
17107 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17108 left_padding += if show_code_actions || show_runnables {
17109 em_width * 3.0
17110 } else if show_git_gutter && show_line_numbers {
17111 em_width * 2.0
17112 } else if show_git_gutter || show_line_numbers {
17113 em_width
17114 } else {
17115 px(0.)
17116 };
17117
17118 let right_padding = if gutter_settings.folds && show_line_numbers {
17119 em_width * 4.0
17120 } else if gutter_settings.folds {
17121 em_width * 3.0
17122 } else if show_line_numbers {
17123 em_width
17124 } else {
17125 px(0.)
17126 };
17127
17128 Some(GutterDimensions {
17129 left_padding,
17130 right_padding,
17131 width: line_gutter_width + left_padding + right_padding,
17132 margin: -descent,
17133 git_blame_entries_width,
17134 })
17135 }
17136
17137 pub fn render_crease_toggle(
17138 &self,
17139 buffer_row: MultiBufferRow,
17140 row_contains_cursor: bool,
17141 editor: Entity<Editor>,
17142 window: &mut Window,
17143 cx: &mut App,
17144 ) -> Option<AnyElement> {
17145 let folded = self.is_line_folded(buffer_row);
17146 let mut is_foldable = false;
17147
17148 if let Some(crease) = self
17149 .crease_snapshot
17150 .query_row(buffer_row, &self.buffer_snapshot)
17151 {
17152 is_foldable = true;
17153 match crease {
17154 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17155 if let Some(render_toggle) = render_toggle {
17156 let toggle_callback =
17157 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17158 if folded {
17159 editor.update(cx, |editor, cx| {
17160 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17161 });
17162 } else {
17163 editor.update(cx, |editor, cx| {
17164 editor.unfold_at(
17165 &crate::UnfoldAt { buffer_row },
17166 window,
17167 cx,
17168 )
17169 });
17170 }
17171 });
17172 return Some((render_toggle)(
17173 buffer_row,
17174 folded,
17175 toggle_callback,
17176 window,
17177 cx,
17178 ));
17179 }
17180 }
17181 }
17182 }
17183
17184 is_foldable |= self.starts_indent(buffer_row);
17185
17186 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17187 Some(
17188 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17189 .toggle_state(folded)
17190 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17191 if folded {
17192 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17193 } else {
17194 this.fold_at(&FoldAt { buffer_row }, window, cx);
17195 }
17196 }))
17197 .into_any_element(),
17198 )
17199 } else {
17200 None
17201 }
17202 }
17203
17204 pub fn render_crease_trailer(
17205 &self,
17206 buffer_row: MultiBufferRow,
17207 window: &mut Window,
17208 cx: &mut App,
17209 ) -> Option<AnyElement> {
17210 let folded = self.is_line_folded(buffer_row);
17211 if let Crease::Inline { render_trailer, .. } = self
17212 .crease_snapshot
17213 .query_row(buffer_row, &self.buffer_snapshot)?
17214 {
17215 let render_trailer = render_trailer.as_ref()?;
17216 Some(render_trailer(buffer_row, folded, window, cx))
17217 } else {
17218 None
17219 }
17220 }
17221}
17222
17223impl Deref for EditorSnapshot {
17224 type Target = DisplaySnapshot;
17225
17226 fn deref(&self) -> &Self::Target {
17227 &self.display_snapshot
17228 }
17229}
17230
17231#[derive(Clone, Debug, PartialEq, Eq)]
17232pub enum EditorEvent {
17233 InputIgnored {
17234 text: Arc<str>,
17235 },
17236 InputHandled {
17237 utf16_range_to_replace: Option<Range<isize>>,
17238 text: Arc<str>,
17239 },
17240 ExcerptsAdded {
17241 buffer: Entity<Buffer>,
17242 predecessor: ExcerptId,
17243 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17244 },
17245 ExcerptsRemoved {
17246 ids: Vec<ExcerptId>,
17247 },
17248 BufferFoldToggled {
17249 ids: Vec<ExcerptId>,
17250 folded: bool,
17251 },
17252 ExcerptsEdited {
17253 ids: Vec<ExcerptId>,
17254 },
17255 ExcerptsExpanded {
17256 ids: Vec<ExcerptId>,
17257 },
17258 BufferEdited,
17259 Edited {
17260 transaction_id: clock::Lamport,
17261 },
17262 Reparsed(BufferId),
17263 Focused,
17264 FocusedIn,
17265 Blurred,
17266 DirtyChanged,
17267 Saved,
17268 TitleChanged,
17269 DiffBaseChanged,
17270 SelectionsChanged {
17271 local: bool,
17272 },
17273 ScrollPositionChanged {
17274 local: bool,
17275 autoscroll: bool,
17276 },
17277 Closed,
17278 TransactionUndone {
17279 transaction_id: clock::Lamport,
17280 },
17281 TransactionBegun {
17282 transaction_id: clock::Lamport,
17283 },
17284 Reloaded,
17285 CursorShapeChanged,
17286}
17287
17288impl EventEmitter<EditorEvent> for Editor {}
17289
17290impl Focusable for Editor {
17291 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17292 self.focus_handle.clone()
17293 }
17294}
17295
17296impl Render for Editor {
17297 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
17298 let settings = ThemeSettings::get_global(cx);
17299
17300 let mut text_style = match self.mode {
17301 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17302 color: cx.theme().colors().editor_foreground,
17303 font_family: settings.ui_font.family.clone(),
17304 font_features: settings.ui_font.features.clone(),
17305 font_fallbacks: settings.ui_font.fallbacks.clone(),
17306 font_size: rems(0.875).into(),
17307 font_weight: settings.ui_font.weight,
17308 line_height: relative(settings.buffer_line_height.value()),
17309 ..Default::default()
17310 },
17311 EditorMode::Full => TextStyle {
17312 color: cx.theme().colors().editor_foreground,
17313 font_family: settings.buffer_font.family.clone(),
17314 font_features: settings.buffer_font.features.clone(),
17315 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17316 font_size: settings.buffer_font_size(cx).into(),
17317 font_weight: settings.buffer_font.weight,
17318 line_height: relative(settings.buffer_line_height.value()),
17319 ..Default::default()
17320 },
17321 };
17322 if let Some(text_style_refinement) = &self.text_style_refinement {
17323 text_style.refine(text_style_refinement)
17324 }
17325
17326 let background = match self.mode {
17327 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17328 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17329 EditorMode::Full => cx.theme().colors().editor_background,
17330 };
17331
17332 EditorElement::new(
17333 &cx.entity(),
17334 EditorStyle {
17335 background,
17336 local_player: cx.theme().players().local(),
17337 text: text_style,
17338 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17339 syntax: cx.theme().syntax().clone(),
17340 status: cx.theme().status().clone(),
17341 inlay_hints_style: make_inlay_hints_style(cx),
17342 inline_completion_styles: make_suggestion_styles(cx),
17343 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17344 },
17345 )
17346 }
17347}
17348
17349impl EntityInputHandler for Editor {
17350 fn text_for_range(
17351 &mut self,
17352 range_utf16: Range<usize>,
17353 adjusted_range: &mut Option<Range<usize>>,
17354 _: &mut Window,
17355 cx: &mut Context<Self>,
17356 ) -> Option<String> {
17357 let snapshot = self.buffer.read(cx).read(cx);
17358 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17359 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17360 if (start.0..end.0) != range_utf16 {
17361 adjusted_range.replace(start.0..end.0);
17362 }
17363 Some(snapshot.text_for_range(start..end).collect())
17364 }
17365
17366 fn selected_text_range(
17367 &mut self,
17368 ignore_disabled_input: bool,
17369 _: &mut Window,
17370 cx: &mut Context<Self>,
17371 ) -> Option<UTF16Selection> {
17372 // Prevent the IME menu from appearing when holding down an alphabetic key
17373 // while input is disabled.
17374 if !ignore_disabled_input && !self.input_enabled {
17375 return None;
17376 }
17377
17378 let selection = self.selections.newest::<OffsetUtf16>(cx);
17379 let range = selection.range();
17380
17381 Some(UTF16Selection {
17382 range: range.start.0..range.end.0,
17383 reversed: selection.reversed,
17384 })
17385 }
17386
17387 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17388 let snapshot = self.buffer.read(cx).read(cx);
17389 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17390 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17391 }
17392
17393 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17394 self.clear_highlights::<InputComposition>(cx);
17395 self.ime_transaction.take();
17396 }
17397
17398 fn replace_text_in_range(
17399 &mut self,
17400 range_utf16: Option<Range<usize>>,
17401 text: &str,
17402 window: &mut Window,
17403 cx: &mut Context<Self>,
17404 ) {
17405 if !self.input_enabled {
17406 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17407 return;
17408 }
17409
17410 self.transact(window, cx, |this, window, cx| {
17411 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17412 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17413 Some(this.selection_replacement_ranges(range_utf16, cx))
17414 } else {
17415 this.marked_text_ranges(cx)
17416 };
17417
17418 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17419 let newest_selection_id = this.selections.newest_anchor().id;
17420 this.selections
17421 .all::<OffsetUtf16>(cx)
17422 .iter()
17423 .zip(ranges_to_replace.iter())
17424 .find_map(|(selection, range)| {
17425 if selection.id == newest_selection_id {
17426 Some(
17427 (range.start.0 as isize - selection.head().0 as isize)
17428 ..(range.end.0 as isize - selection.head().0 as isize),
17429 )
17430 } else {
17431 None
17432 }
17433 })
17434 });
17435
17436 cx.emit(EditorEvent::InputHandled {
17437 utf16_range_to_replace: range_to_replace,
17438 text: text.into(),
17439 });
17440
17441 if let Some(new_selected_ranges) = new_selected_ranges {
17442 this.change_selections(None, window, cx, |selections| {
17443 selections.select_ranges(new_selected_ranges)
17444 });
17445 this.backspace(&Default::default(), window, cx);
17446 }
17447
17448 this.handle_input(text, window, cx);
17449 });
17450
17451 if let Some(transaction) = self.ime_transaction {
17452 self.buffer.update(cx, |buffer, cx| {
17453 buffer.group_until_transaction(transaction, cx);
17454 });
17455 }
17456
17457 self.unmark_text(window, cx);
17458 }
17459
17460 fn replace_and_mark_text_in_range(
17461 &mut self,
17462 range_utf16: Option<Range<usize>>,
17463 text: &str,
17464 new_selected_range_utf16: Option<Range<usize>>,
17465 window: &mut Window,
17466 cx: &mut Context<Self>,
17467 ) {
17468 if !self.input_enabled {
17469 return;
17470 }
17471
17472 let transaction = self.transact(window, cx, |this, window, cx| {
17473 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17474 let snapshot = this.buffer.read(cx).read(cx);
17475 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17476 for marked_range in &mut marked_ranges {
17477 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17478 marked_range.start.0 += relative_range_utf16.start;
17479 marked_range.start =
17480 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17481 marked_range.end =
17482 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17483 }
17484 }
17485 Some(marked_ranges)
17486 } else if let Some(range_utf16) = range_utf16 {
17487 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17488 Some(this.selection_replacement_ranges(range_utf16, cx))
17489 } else {
17490 None
17491 };
17492
17493 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17494 let newest_selection_id = this.selections.newest_anchor().id;
17495 this.selections
17496 .all::<OffsetUtf16>(cx)
17497 .iter()
17498 .zip(ranges_to_replace.iter())
17499 .find_map(|(selection, range)| {
17500 if selection.id == newest_selection_id {
17501 Some(
17502 (range.start.0 as isize - selection.head().0 as isize)
17503 ..(range.end.0 as isize - selection.head().0 as isize),
17504 )
17505 } else {
17506 None
17507 }
17508 })
17509 });
17510
17511 cx.emit(EditorEvent::InputHandled {
17512 utf16_range_to_replace: range_to_replace,
17513 text: text.into(),
17514 });
17515
17516 if let Some(ranges) = ranges_to_replace {
17517 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17518 }
17519
17520 let marked_ranges = {
17521 let snapshot = this.buffer.read(cx).read(cx);
17522 this.selections
17523 .disjoint_anchors()
17524 .iter()
17525 .map(|selection| {
17526 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17527 })
17528 .collect::<Vec<_>>()
17529 };
17530
17531 if text.is_empty() {
17532 this.unmark_text(window, cx);
17533 } else {
17534 this.highlight_text::<InputComposition>(
17535 marked_ranges.clone(),
17536 HighlightStyle {
17537 underline: Some(UnderlineStyle {
17538 thickness: px(1.),
17539 color: None,
17540 wavy: false,
17541 }),
17542 ..Default::default()
17543 },
17544 cx,
17545 );
17546 }
17547
17548 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17549 let use_autoclose = this.use_autoclose;
17550 let use_auto_surround = this.use_auto_surround;
17551 this.set_use_autoclose(false);
17552 this.set_use_auto_surround(false);
17553 this.handle_input(text, window, cx);
17554 this.set_use_autoclose(use_autoclose);
17555 this.set_use_auto_surround(use_auto_surround);
17556
17557 if let Some(new_selected_range) = new_selected_range_utf16 {
17558 let snapshot = this.buffer.read(cx).read(cx);
17559 let new_selected_ranges = marked_ranges
17560 .into_iter()
17561 .map(|marked_range| {
17562 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17563 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17564 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17565 snapshot.clip_offset_utf16(new_start, Bias::Left)
17566 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17567 })
17568 .collect::<Vec<_>>();
17569
17570 drop(snapshot);
17571 this.change_selections(None, window, cx, |selections| {
17572 selections.select_ranges(new_selected_ranges)
17573 });
17574 }
17575 });
17576
17577 self.ime_transaction = self.ime_transaction.or(transaction);
17578 if let Some(transaction) = self.ime_transaction {
17579 self.buffer.update(cx, |buffer, cx| {
17580 buffer.group_until_transaction(transaction, cx);
17581 });
17582 }
17583
17584 if self.text_highlights::<InputComposition>(cx).is_none() {
17585 self.ime_transaction.take();
17586 }
17587 }
17588
17589 fn bounds_for_range(
17590 &mut self,
17591 range_utf16: Range<usize>,
17592 element_bounds: gpui::Bounds<Pixels>,
17593 window: &mut Window,
17594 cx: &mut Context<Self>,
17595 ) -> Option<gpui::Bounds<Pixels>> {
17596 let text_layout_details = self.text_layout_details(window);
17597 let gpui::Size {
17598 width: em_width,
17599 height: line_height,
17600 } = self.character_size(window);
17601
17602 let snapshot = self.snapshot(window, cx);
17603 let scroll_position = snapshot.scroll_position();
17604 let scroll_left = scroll_position.x * em_width;
17605
17606 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17607 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17608 + self.gutter_dimensions.width
17609 + self.gutter_dimensions.margin;
17610 let y = line_height * (start.row().as_f32() - scroll_position.y);
17611
17612 Some(Bounds {
17613 origin: element_bounds.origin + point(x, y),
17614 size: size(em_width, line_height),
17615 })
17616 }
17617
17618 fn character_index_for_point(
17619 &mut self,
17620 point: gpui::Point<Pixels>,
17621 _window: &mut Window,
17622 _cx: &mut Context<Self>,
17623 ) -> Option<usize> {
17624 let position_map = self.last_position_map.as_ref()?;
17625 if !position_map.text_hitbox.contains(&point) {
17626 return None;
17627 }
17628 let display_point = position_map.point_for_position(point).previous_valid;
17629 let anchor = position_map
17630 .snapshot
17631 .display_point_to_anchor(display_point, Bias::Left);
17632 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17633 Some(utf16_offset.0)
17634 }
17635}
17636
17637trait SelectionExt {
17638 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17639 fn spanned_rows(
17640 &self,
17641 include_end_if_at_line_start: bool,
17642 map: &DisplaySnapshot,
17643 ) -> Range<MultiBufferRow>;
17644}
17645
17646impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17647 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17648 let start = self
17649 .start
17650 .to_point(&map.buffer_snapshot)
17651 .to_display_point(map);
17652 let end = self
17653 .end
17654 .to_point(&map.buffer_snapshot)
17655 .to_display_point(map);
17656 if self.reversed {
17657 end..start
17658 } else {
17659 start..end
17660 }
17661 }
17662
17663 fn spanned_rows(
17664 &self,
17665 include_end_if_at_line_start: bool,
17666 map: &DisplaySnapshot,
17667 ) -> Range<MultiBufferRow> {
17668 let start = self.start.to_point(&map.buffer_snapshot);
17669 let mut end = self.end.to_point(&map.buffer_snapshot);
17670 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17671 end.row -= 1;
17672 }
17673
17674 let buffer_start = map.prev_line_boundary(start).0;
17675 let buffer_end = map.next_line_boundary(end).0;
17676 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17677 }
17678}
17679
17680impl<T: InvalidationRegion> InvalidationStack<T> {
17681 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17682 where
17683 S: Clone + ToOffset,
17684 {
17685 while let Some(region) = self.last() {
17686 let all_selections_inside_invalidation_ranges =
17687 if selections.len() == region.ranges().len() {
17688 selections
17689 .iter()
17690 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17691 .all(|(selection, invalidation_range)| {
17692 let head = selection.head().to_offset(buffer);
17693 invalidation_range.start <= head && invalidation_range.end >= head
17694 })
17695 } else {
17696 false
17697 };
17698
17699 if all_selections_inside_invalidation_ranges {
17700 break;
17701 } else {
17702 self.pop();
17703 }
17704 }
17705 }
17706}
17707
17708impl<T> Default for InvalidationStack<T> {
17709 fn default() -> Self {
17710 Self(Default::default())
17711 }
17712}
17713
17714impl<T> Deref for InvalidationStack<T> {
17715 type Target = Vec<T>;
17716
17717 fn deref(&self) -> &Self::Target {
17718 &self.0
17719 }
17720}
17721
17722impl<T> DerefMut for InvalidationStack<T> {
17723 fn deref_mut(&mut self) -> &mut Self::Target {
17724 &mut self.0
17725 }
17726}
17727
17728impl InvalidationRegion for SnippetState {
17729 fn ranges(&self) -> &[Range<Anchor>] {
17730 &self.ranges[self.active_index]
17731 }
17732}
17733
17734pub fn diagnostic_block_renderer(
17735 diagnostic: Diagnostic,
17736 max_message_rows: Option<u8>,
17737 allow_closing: bool,
17738 _is_valid: bool,
17739) -> RenderBlock {
17740 let (text_without_backticks, code_ranges) =
17741 highlight_diagnostic_message(&diagnostic, max_message_rows);
17742
17743 Arc::new(move |cx: &mut BlockContext| {
17744 let group_id: SharedString = cx.block_id.to_string().into();
17745
17746 let mut text_style = cx.window.text_style().clone();
17747 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17748 let theme_settings = ThemeSettings::get_global(cx);
17749 text_style.font_family = theme_settings.buffer_font.family.clone();
17750 text_style.font_style = theme_settings.buffer_font.style;
17751 text_style.font_features = theme_settings.buffer_font.features.clone();
17752 text_style.font_weight = theme_settings.buffer_font.weight;
17753
17754 let multi_line_diagnostic = diagnostic.message.contains('\n');
17755
17756 let buttons = |diagnostic: &Diagnostic| {
17757 if multi_line_diagnostic {
17758 v_flex()
17759 } else {
17760 h_flex()
17761 }
17762 .when(allow_closing, |div| {
17763 div.children(diagnostic.is_primary.then(|| {
17764 IconButton::new("close-block", IconName::XCircle)
17765 .icon_color(Color::Muted)
17766 .size(ButtonSize::Compact)
17767 .style(ButtonStyle::Transparent)
17768 .visible_on_hover(group_id.clone())
17769 .on_click(move |_click, window, cx| {
17770 window.dispatch_action(Box::new(Cancel), cx)
17771 })
17772 .tooltip(|window, cx| {
17773 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
17774 })
17775 }))
17776 })
17777 .child(
17778 IconButton::new("copy-block", IconName::Copy)
17779 .icon_color(Color::Muted)
17780 .size(ButtonSize::Compact)
17781 .style(ButtonStyle::Transparent)
17782 .visible_on_hover(group_id.clone())
17783 .on_click({
17784 let message = diagnostic.message.clone();
17785 move |_click, _, cx| {
17786 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
17787 }
17788 })
17789 .tooltip(Tooltip::text("Copy diagnostic message")),
17790 )
17791 };
17792
17793 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
17794 AvailableSpace::min_size(),
17795 cx.window,
17796 cx.app,
17797 );
17798
17799 h_flex()
17800 .id(cx.block_id)
17801 .group(group_id.clone())
17802 .relative()
17803 .size_full()
17804 .block_mouse_down()
17805 .pl(cx.gutter_dimensions.width)
17806 .w(cx.max_width - cx.gutter_dimensions.full_width())
17807 .child(
17808 div()
17809 .flex()
17810 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
17811 .flex_shrink(),
17812 )
17813 .child(buttons(&diagnostic))
17814 .child(div().flex().flex_shrink_0().child(
17815 StyledText::new(text_without_backticks.clone()).with_highlights(
17816 &text_style,
17817 code_ranges.iter().map(|range| {
17818 (
17819 range.clone(),
17820 HighlightStyle {
17821 font_weight: Some(FontWeight::BOLD),
17822 ..Default::default()
17823 },
17824 )
17825 }),
17826 ),
17827 ))
17828 .into_any_element()
17829 })
17830}
17831
17832fn inline_completion_edit_text(
17833 current_snapshot: &BufferSnapshot,
17834 edits: &[(Range<Anchor>, String)],
17835 edit_preview: &EditPreview,
17836 include_deletions: bool,
17837 cx: &App,
17838) -> HighlightedText {
17839 let edits = edits
17840 .iter()
17841 .map(|(anchor, text)| {
17842 (
17843 anchor.start.text_anchor..anchor.end.text_anchor,
17844 text.clone(),
17845 )
17846 })
17847 .collect::<Vec<_>>();
17848
17849 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
17850}
17851
17852pub fn highlight_diagnostic_message(
17853 diagnostic: &Diagnostic,
17854 mut max_message_rows: Option<u8>,
17855) -> (SharedString, Vec<Range<usize>>) {
17856 let mut text_without_backticks = String::new();
17857 let mut code_ranges = Vec::new();
17858
17859 if let Some(source) = &diagnostic.source {
17860 text_without_backticks.push_str(source);
17861 code_ranges.push(0..source.len());
17862 text_without_backticks.push_str(": ");
17863 }
17864
17865 let mut prev_offset = 0;
17866 let mut in_code_block = false;
17867 let has_row_limit = max_message_rows.is_some();
17868 let mut newline_indices = diagnostic
17869 .message
17870 .match_indices('\n')
17871 .filter(|_| has_row_limit)
17872 .map(|(ix, _)| ix)
17873 .fuse()
17874 .peekable();
17875
17876 for (quote_ix, _) in diagnostic
17877 .message
17878 .match_indices('`')
17879 .chain([(diagnostic.message.len(), "")])
17880 {
17881 let mut first_newline_ix = None;
17882 let mut last_newline_ix = None;
17883 while let Some(newline_ix) = newline_indices.peek() {
17884 if *newline_ix < quote_ix {
17885 if first_newline_ix.is_none() {
17886 first_newline_ix = Some(*newline_ix);
17887 }
17888 last_newline_ix = Some(*newline_ix);
17889
17890 if let Some(rows_left) = &mut max_message_rows {
17891 if *rows_left == 0 {
17892 break;
17893 } else {
17894 *rows_left -= 1;
17895 }
17896 }
17897 let _ = newline_indices.next();
17898 } else {
17899 break;
17900 }
17901 }
17902 let prev_len = text_without_backticks.len();
17903 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
17904 text_without_backticks.push_str(new_text);
17905 if in_code_block {
17906 code_ranges.push(prev_len..text_without_backticks.len());
17907 }
17908 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
17909 in_code_block = !in_code_block;
17910 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
17911 text_without_backticks.push_str("...");
17912 break;
17913 }
17914 }
17915
17916 (text_without_backticks.into(), code_ranges)
17917}
17918
17919fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
17920 match severity {
17921 DiagnosticSeverity::ERROR => colors.error,
17922 DiagnosticSeverity::WARNING => colors.warning,
17923 DiagnosticSeverity::INFORMATION => colors.info,
17924 DiagnosticSeverity::HINT => colors.info,
17925 _ => colors.ignored,
17926 }
17927}
17928
17929pub fn styled_runs_for_code_label<'a>(
17930 label: &'a CodeLabel,
17931 syntax_theme: &'a theme::SyntaxTheme,
17932) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
17933 let fade_out = HighlightStyle {
17934 fade_out: Some(0.35),
17935 ..Default::default()
17936 };
17937
17938 let mut prev_end = label.filter_range.end;
17939 label
17940 .runs
17941 .iter()
17942 .enumerate()
17943 .flat_map(move |(ix, (range, highlight_id))| {
17944 let style = if let Some(style) = highlight_id.style(syntax_theme) {
17945 style
17946 } else {
17947 return Default::default();
17948 };
17949 let mut muted_style = style;
17950 muted_style.highlight(fade_out);
17951
17952 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
17953 if range.start >= label.filter_range.end {
17954 if range.start > prev_end {
17955 runs.push((prev_end..range.start, fade_out));
17956 }
17957 runs.push((range.clone(), muted_style));
17958 } else if range.end <= label.filter_range.end {
17959 runs.push((range.clone(), style));
17960 } else {
17961 runs.push((range.start..label.filter_range.end, style));
17962 runs.push((label.filter_range.end..range.end, muted_style));
17963 }
17964 prev_end = cmp::max(prev_end, range.end);
17965
17966 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
17967 runs.push((prev_end..label.text.len(), fade_out));
17968 }
17969
17970 runs
17971 })
17972}
17973
17974pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
17975 let mut prev_index = 0;
17976 let mut prev_codepoint: Option<char> = None;
17977 text.char_indices()
17978 .chain([(text.len(), '\0')])
17979 .filter_map(move |(index, codepoint)| {
17980 let prev_codepoint = prev_codepoint.replace(codepoint)?;
17981 let is_boundary = index == text.len()
17982 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
17983 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
17984 if is_boundary {
17985 let chunk = &text[prev_index..index];
17986 prev_index = index;
17987 Some(chunk)
17988 } else {
17989 None
17990 }
17991 })
17992}
17993
17994pub trait RangeToAnchorExt: Sized {
17995 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
17996
17997 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17998 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17999 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18000 }
18001}
18002
18003impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18004 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18005 let start_offset = self.start.to_offset(snapshot);
18006 let end_offset = self.end.to_offset(snapshot);
18007 if start_offset == end_offset {
18008 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18009 } else {
18010 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18011 }
18012 }
18013}
18014
18015pub trait RowExt {
18016 fn as_f32(&self) -> f32;
18017
18018 fn next_row(&self) -> Self;
18019
18020 fn previous_row(&self) -> Self;
18021
18022 fn minus(&self, other: Self) -> u32;
18023}
18024
18025impl RowExt for DisplayRow {
18026 fn as_f32(&self) -> f32 {
18027 self.0 as f32
18028 }
18029
18030 fn next_row(&self) -> Self {
18031 Self(self.0 + 1)
18032 }
18033
18034 fn previous_row(&self) -> Self {
18035 Self(self.0.saturating_sub(1))
18036 }
18037
18038 fn minus(&self, other: Self) -> u32 {
18039 self.0 - other.0
18040 }
18041}
18042
18043impl RowExt for MultiBufferRow {
18044 fn as_f32(&self) -> f32 {
18045 self.0 as f32
18046 }
18047
18048 fn next_row(&self) -> Self {
18049 Self(self.0 + 1)
18050 }
18051
18052 fn previous_row(&self) -> Self {
18053 Self(self.0.saturating_sub(1))
18054 }
18055
18056 fn minus(&self, other: Self) -> u32 {
18057 self.0 - other.0
18058 }
18059}
18060
18061trait RowRangeExt {
18062 type Row;
18063
18064 fn len(&self) -> usize;
18065
18066 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18067}
18068
18069impl RowRangeExt for Range<MultiBufferRow> {
18070 type Row = MultiBufferRow;
18071
18072 fn len(&self) -> usize {
18073 (self.end.0 - self.start.0) as usize
18074 }
18075
18076 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18077 (self.start.0..self.end.0).map(MultiBufferRow)
18078 }
18079}
18080
18081impl RowRangeExt for Range<DisplayRow> {
18082 type Row = DisplayRow;
18083
18084 fn len(&self) -> usize {
18085 (self.end.0 - self.start.0) as usize
18086 }
18087
18088 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18089 (self.start.0..self.end.0).map(DisplayRow)
18090 }
18091}
18092
18093/// If select range has more than one line, we
18094/// just point the cursor to range.start.
18095fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18096 if range.start.row == range.end.row {
18097 range
18098 } else {
18099 range.start..range.start
18100 }
18101}
18102pub struct KillRing(ClipboardItem);
18103impl Global for KillRing {}
18104
18105const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18106
18107fn all_edits_insertions_or_deletions(
18108 edits: &Vec<(Range<Anchor>, String)>,
18109 snapshot: &MultiBufferSnapshot,
18110) -> bool {
18111 let mut all_insertions = true;
18112 let mut all_deletions = true;
18113
18114 for (range, new_text) in edits.iter() {
18115 let range_is_empty = range.to_offset(&snapshot).is_empty();
18116 let text_is_empty = new_text.is_empty();
18117
18118 if range_is_empty != text_is_empty {
18119 if range_is_empty {
18120 all_deletions = false;
18121 } else {
18122 all_insertions = false;
18123 }
18124 } else {
18125 return false;
18126 }
18127
18128 if !all_insertions && !all_deletions {
18129 return false;
18130 }
18131 }
18132 all_insertions || all_deletions
18133}