1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{
71 future::{self, Shared},
72 FutureExt,
73};
74use fuzzy::StringMatchCandidate;
75
76use ::git::Restore;
77use code_context_menus::{
78 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
79 CompletionsMenu, ContextMenuOrigin,
80};
81use git::blame::GitBlame;
82use gpui::{
83 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
84 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
85 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
86 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
87 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
88 ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
89 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
90 WeakEntity, WeakFocusHandle, Window,
91};
92use highlight_matching_bracket::refresh_matching_bracket_highlights;
93use hover_popover::{hide_hover, HoverState};
94use indent_guides::ActiveIndentGuidesState;
95use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
96pub use inline_completion::Direction;
97use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
98pub use items::MAX_TAB_TITLE_LEN;
99use itertools::Itertools;
100use language::{
101 language_settings::{
102 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
103 },
104 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
105 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
106 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
107 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
108};
109use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
110use linked_editing_ranges::refresh_linked_ranges;
111use mouse_context_menu::MouseContextMenu;
112use persistence::DB;
113pub use proposed_changes_editor::{
114 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
115};
116use smallvec::smallvec;
117use std::iter::Peekable;
118use task::{ResolvedTask, TaskTemplate, TaskVariables};
119
120use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
121pub use lsp::CompletionContext;
122use lsp::{
123 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
124 InsertTextFormat, LanguageServerId, LanguageServerName,
125};
126
127use language::BufferSnapshot;
128use movement::TextLayoutDetails;
129pub use multi_buffer::{
130 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
131 ToOffset, ToPoint,
132};
133use multi_buffer::{
134 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
135 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
136};
137use project::{
138 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
139 project_settings::{GitGutterSetting, ProjectSettings},
140 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
141 PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
142};
143use rand::prelude::*;
144use rpc::{proto::*, ErrorExt};
145use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
146use selections_collection::{
147 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
148};
149use serde::{Deserialize, Serialize};
150use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
151use smallvec::SmallVec;
152use snippet::Snippet;
153use std::{
154 any::TypeId,
155 borrow::Cow,
156 cell::RefCell,
157 cmp::{self, Ordering, Reverse},
158 mem,
159 num::NonZeroU32,
160 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
161 path::{Path, PathBuf},
162 rc::Rc,
163 sync::Arc,
164 time::{Duration, Instant},
165};
166pub use sum_tree::Bias;
167use sum_tree::TreeMap;
168use text::{BufferId, OffsetUtf16, Rope};
169use theme::{
170 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
171 ThemeColors, ThemeSettings,
172};
173use ui::{
174 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
175 Tooltip,
176};
177use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
178use workspace::{
179 item::{ItemHandle, PreviewTabsSettings},
180 ItemId, RestoreOnStartupBehavior,
181};
182use workspace::{
183 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
184 WorkspaceSettings,
185};
186use workspace::{
187 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
188};
189use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
190
191use crate::hover_links::{find_url, find_url_from_range};
192use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
193
194pub const FILE_HEADER_HEIGHT: u32 = 2;
195pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
196pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
197pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
198const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
199const MAX_LINE_LEN: usize = 1024;
200const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
201const MAX_SELECTION_HISTORY_LEN: usize = 1024;
202pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
203#[doc(hidden)]
204pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
205
206pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
207pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
208pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
209
210pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
211pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
212
213const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
214 alt: true,
215 shift: true,
216 control: false,
217 platform: false,
218 function: false,
219};
220
221#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
222pub enum InlayId {
223 InlineCompletion(usize),
224 Hint(usize),
225}
226
227impl InlayId {
228 fn id(&self) -> usize {
229 match self {
230 Self::InlineCompletion(id) => *id,
231 Self::Hint(id) => *id,
232 }
233 }
234}
235
236enum DocumentHighlightRead {}
237enum DocumentHighlightWrite {}
238enum InputComposition {}
239enum SelectedTextHighlight {}
240
241#[derive(Debug, Copy, Clone, PartialEq, Eq)]
242pub enum Navigated {
243 Yes,
244 No,
245}
246
247impl Navigated {
248 pub fn from_bool(yes: bool) -> Navigated {
249 if yes {
250 Navigated::Yes
251 } else {
252 Navigated::No
253 }
254 }
255}
256
257#[derive(Debug, Clone, PartialEq, Eq)]
258enum DisplayDiffHunk {
259 Folded {
260 display_row: DisplayRow,
261 },
262 Unfolded {
263 diff_base_byte_range: Range<usize>,
264 display_row_range: Range<DisplayRow>,
265 multi_buffer_range: Range<Anchor>,
266 status: DiffHunkStatus,
267 },
268}
269
270pub fn init_settings(cx: &mut App) {
271 EditorSettings::register(cx);
272}
273
274pub fn init(cx: &mut App) {
275 init_settings(cx);
276
277 workspace::register_project_item::<Editor>(cx);
278 workspace::FollowableViewRegistry::register::<Editor>(cx);
279 workspace::register_serializable_item::<Editor>(cx);
280
281 cx.observe_new(
282 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
283 workspace.register_action(Editor::new_file);
284 workspace.register_action(Editor::new_file_vertical);
285 workspace.register_action(Editor::new_file_horizontal);
286 workspace.register_action(Editor::cancel_language_server_work);
287 },
288 )
289 .detach();
290
291 cx.on_action(move |_: &workspace::NewFile, cx| {
292 let app_state = workspace::AppState::global(cx);
293 if let Some(app_state) = app_state.upgrade() {
294 workspace::open_new(
295 Default::default(),
296 app_state,
297 cx,
298 |workspace, window, cx| {
299 Editor::new_file(workspace, &Default::default(), window, cx)
300 },
301 )
302 .detach();
303 }
304 });
305 cx.on_action(move |_: &workspace::NewWindow, cx| {
306 let app_state = workspace::AppState::global(cx);
307 if let Some(app_state) = app_state.upgrade() {
308 workspace::open_new(
309 Default::default(),
310 app_state,
311 cx,
312 |workspace, window, cx| {
313 cx.activate(true);
314 Editor::new_file(workspace, &Default::default(), window, cx)
315 },
316 )
317 .detach();
318 }
319 });
320}
321
322pub struct SearchWithinRange;
323
324trait InvalidationRegion {
325 fn ranges(&self) -> &[Range<Anchor>];
326}
327
328#[derive(Clone, Debug, PartialEq)]
329pub enum SelectPhase {
330 Begin {
331 position: DisplayPoint,
332 add: bool,
333 click_count: usize,
334 },
335 BeginColumnar {
336 position: DisplayPoint,
337 reset: bool,
338 goal_column: u32,
339 },
340 Extend {
341 position: DisplayPoint,
342 click_count: usize,
343 },
344 Update {
345 position: DisplayPoint,
346 goal_column: u32,
347 scroll_delta: gpui::Point<f32>,
348 },
349 End,
350}
351
352#[derive(Clone, Debug)]
353pub enum SelectMode {
354 Character,
355 Word(Range<Anchor>),
356 Line(Range<Anchor>),
357 All,
358}
359
360#[derive(Copy, Clone, PartialEq, Eq, Debug)]
361pub enum EditorMode {
362 SingleLine { auto_width: bool },
363 AutoHeight { max_lines: usize },
364 Full,
365}
366
367#[derive(Copy, Clone, Debug)]
368pub enum SoftWrap {
369 /// Prefer not to wrap at all.
370 ///
371 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
372 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
373 GitDiff,
374 /// Prefer a single line generally, unless an overly long line is encountered.
375 None,
376 /// Soft wrap lines that exceed the editor width.
377 EditorWidth,
378 /// Soft wrap lines at the preferred line length.
379 Column(u32),
380 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
381 Bounded(u32),
382}
383
384#[derive(Clone)]
385pub struct EditorStyle {
386 pub background: Hsla,
387 pub local_player: PlayerColor,
388 pub text: TextStyle,
389 pub scrollbar_width: Pixels,
390 pub syntax: Arc<SyntaxTheme>,
391 pub status: StatusColors,
392 pub inlay_hints_style: HighlightStyle,
393 pub inline_completion_styles: InlineCompletionStyles,
394 pub unnecessary_code_fade: f32,
395}
396
397impl Default for EditorStyle {
398 fn default() -> Self {
399 Self {
400 background: Hsla::default(),
401 local_player: PlayerColor::default(),
402 text: TextStyle::default(),
403 scrollbar_width: Pixels::default(),
404 syntax: Default::default(),
405 // HACK: Status colors don't have a real default.
406 // We should look into removing the status colors from the editor
407 // style and retrieve them directly from the theme.
408 status: StatusColors::dark(),
409 inlay_hints_style: HighlightStyle::default(),
410 inline_completion_styles: InlineCompletionStyles {
411 insertion: HighlightStyle::default(),
412 whitespace: HighlightStyle::default(),
413 },
414 unnecessary_code_fade: Default::default(),
415 }
416 }
417}
418
419pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
420 let show_background = language_settings::language_settings(None, None, cx)
421 .inlay_hints
422 .show_background;
423
424 HighlightStyle {
425 color: Some(cx.theme().status().hint),
426 background_color: show_background.then(|| cx.theme().status().hint_background),
427 ..HighlightStyle::default()
428 }
429}
430
431pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
432 InlineCompletionStyles {
433 insertion: HighlightStyle {
434 color: Some(cx.theme().status().predictive),
435 ..HighlightStyle::default()
436 },
437 whitespace: HighlightStyle {
438 background_color: Some(cx.theme().status().created_background),
439 ..HighlightStyle::default()
440 },
441 }
442}
443
444type CompletionId = usize;
445
446pub(crate) enum EditDisplayMode {
447 TabAccept,
448 DiffPopover,
449 Inline,
450}
451
452enum InlineCompletion {
453 Edit {
454 edits: Vec<(Range<Anchor>, String)>,
455 edit_preview: Option<EditPreview>,
456 display_mode: EditDisplayMode,
457 snapshot: BufferSnapshot,
458 },
459 Move {
460 target: Anchor,
461 snapshot: BufferSnapshot,
462 },
463}
464
465struct InlineCompletionState {
466 inlay_ids: Vec<InlayId>,
467 completion: InlineCompletion,
468 completion_id: Option<SharedString>,
469 invalidation_range: Range<Anchor>,
470}
471
472enum EditPredictionSettings {
473 Disabled,
474 Enabled {
475 show_in_menu: bool,
476 preview_requires_modifier: bool,
477 },
478}
479
480enum InlineCompletionHighlight {}
481
482#[derive(Debug, Clone)]
483struct InlineDiagnostic {
484 message: SharedString,
485 group_id: usize,
486 is_primary: bool,
487 start: Point,
488 severity: DiagnosticSeverity,
489}
490
491pub enum MenuInlineCompletionsPolicy {
492 Never,
493 ByProvider,
494}
495
496pub enum EditPredictionPreview {
497 /// Modifier is not pressed
498 Inactive { released_too_fast: bool },
499 /// Modifier pressed
500 Active {
501 since: Instant,
502 previous_scroll_position: Option<ScrollAnchor>,
503 },
504}
505
506impl EditPredictionPreview {
507 pub fn released_too_fast(&self) -> bool {
508 match self {
509 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
510 EditPredictionPreview::Active { .. } => false,
511 }
512 }
513
514 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
515 if let EditPredictionPreview::Active {
516 previous_scroll_position,
517 ..
518 } = self
519 {
520 *previous_scroll_position = scroll_position;
521 }
522 }
523}
524
525#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
526struct EditorActionId(usize);
527
528impl EditorActionId {
529 pub fn post_inc(&mut self) -> Self {
530 let answer = self.0;
531
532 *self = Self(answer + 1);
533
534 Self(answer)
535 }
536}
537
538// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
539// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
540
541type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
542type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
543
544#[derive(Default)]
545struct ScrollbarMarkerState {
546 scrollbar_size: Size<Pixels>,
547 dirty: bool,
548 markers: Arc<[PaintQuad]>,
549 pending_refresh: Option<Task<Result<()>>>,
550}
551
552impl ScrollbarMarkerState {
553 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
554 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
555 }
556}
557
558#[derive(Clone, Debug)]
559struct RunnableTasks {
560 templates: Vec<(TaskSourceKind, TaskTemplate)>,
561 offset: multi_buffer::Anchor,
562 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
563 column: u32,
564 // Values of all named captures, including those starting with '_'
565 extra_variables: HashMap<String, String>,
566 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
567 context_range: Range<BufferOffset>,
568}
569
570impl RunnableTasks {
571 fn resolve<'a>(
572 &'a self,
573 cx: &'a task::TaskContext,
574 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
575 self.templates.iter().filter_map(|(kind, template)| {
576 template
577 .resolve_task(&kind.to_id_base(), cx)
578 .map(|task| (kind.clone(), task))
579 })
580 }
581}
582
583#[derive(Clone)]
584struct ResolvedTasks {
585 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
586 position: Anchor,
587}
588#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
589struct BufferOffset(usize);
590
591// Addons allow storing per-editor state in other crates (e.g. Vim)
592pub trait Addon: 'static {
593 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
594
595 fn render_buffer_header_controls(
596 &self,
597 _: &ExcerptInfo,
598 _: &Window,
599 _: &App,
600 ) -> Option<AnyElement> {
601 None
602 }
603
604 fn to_any(&self) -> &dyn std::any::Any;
605}
606
607#[derive(Debug, Copy, Clone, PartialEq, Eq)]
608pub enum IsVimMode {
609 Yes,
610 No,
611}
612
613/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
614///
615/// See the [module level documentation](self) for more information.
616pub struct Editor {
617 focus_handle: FocusHandle,
618 last_focused_descendant: Option<WeakFocusHandle>,
619 /// The text buffer being edited
620 buffer: Entity<MultiBuffer>,
621 /// Map of how text in the buffer should be displayed.
622 /// Handles soft wraps, folds, fake inlay text insertions, etc.
623 pub display_map: Entity<DisplayMap>,
624 pub selections: SelectionsCollection,
625 pub scroll_manager: ScrollManager,
626 /// When inline assist editors are linked, they all render cursors because
627 /// typing enters text into each of them, even the ones that aren't focused.
628 pub(crate) show_cursor_when_unfocused: bool,
629 columnar_selection_tail: Option<Anchor>,
630 add_selections_state: Option<AddSelectionsState>,
631 select_next_state: Option<SelectNextState>,
632 select_prev_state: Option<SelectNextState>,
633 selection_history: SelectionHistory,
634 autoclose_regions: Vec<AutocloseRegion>,
635 snippet_stack: InvalidationStack<SnippetState>,
636 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
637 ime_transaction: Option<TransactionId>,
638 active_diagnostics: Option<ActiveDiagnosticGroup>,
639 show_inline_diagnostics: bool,
640 inline_diagnostics_update: Task<()>,
641 inline_diagnostics_enabled: bool,
642 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
643 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
644
645 // TODO: make this a access method
646 pub project: Option<Entity<Project>>,
647 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
648 completion_provider: Option<Box<dyn CompletionProvider>>,
649 collaboration_hub: Option<Box<dyn CollaborationHub>>,
650 blink_manager: Entity<BlinkManager>,
651 show_cursor_names: bool,
652 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
653 pub show_local_selections: bool,
654 mode: EditorMode,
655 show_breadcrumbs: bool,
656 show_gutter: bool,
657 show_scrollbars: bool,
658 show_line_numbers: Option<bool>,
659 use_relative_line_numbers: Option<bool>,
660 show_git_diff_gutter: Option<bool>,
661 show_code_actions: Option<bool>,
662 show_runnables: Option<bool>,
663 show_wrap_guides: Option<bool>,
664 show_indent_guides: Option<bool>,
665 placeholder_text: Option<Arc<str>>,
666 highlight_order: usize,
667 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
668 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
669 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
670 scrollbar_marker_state: ScrollbarMarkerState,
671 active_indent_guides_state: ActiveIndentGuidesState,
672 nav_history: Option<ItemNavHistory>,
673 context_menu: RefCell<Option<CodeContextMenu>>,
674 mouse_context_menu: Option<MouseContextMenu>,
675 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
676 signature_help_state: SignatureHelpState,
677 auto_signature_help: Option<bool>,
678 find_all_references_task_sources: Vec<Anchor>,
679 next_completion_id: CompletionId,
680 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
681 code_actions_task: Option<Task<Result<()>>>,
682 selection_highlight_task: Option<Task<()>>,
683 document_highlights_task: Option<Task<()>>,
684 linked_editing_range_task: Option<Task<Option<()>>>,
685 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
686 pending_rename: Option<RenameState>,
687 searchable: bool,
688 cursor_shape: CursorShape,
689 current_line_highlight: Option<CurrentLineHighlight>,
690 collapse_matches: bool,
691 autoindent_mode: Option<AutoindentMode>,
692 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
693 input_enabled: bool,
694 use_modal_editing: bool,
695 read_only: bool,
696 leader_peer_id: Option<PeerId>,
697 remote_id: Option<ViewId>,
698 hover_state: HoverState,
699 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
700 gutter_hovered: bool,
701 hovered_link_state: Option<HoveredLinkState>,
702 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
703 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
704 active_inline_completion: Option<InlineCompletionState>,
705 /// Used to prevent flickering as the user types while the menu is open
706 stale_inline_completion_in_menu: Option<InlineCompletionState>,
707 edit_prediction_settings: EditPredictionSettings,
708 inline_completions_hidden_for_vim_mode: bool,
709 show_inline_completions_override: Option<bool>,
710 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
711 edit_prediction_preview: EditPredictionPreview,
712 edit_prediction_indent_conflict: bool,
713 edit_prediction_requires_modifier_in_indent_conflict: bool,
714 inlay_hint_cache: InlayHintCache,
715 next_inlay_id: usize,
716 _subscriptions: Vec<Subscription>,
717 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
718 gutter_dimensions: GutterDimensions,
719 style: Option<EditorStyle>,
720 text_style_refinement: Option<TextStyleRefinement>,
721 next_editor_action_id: EditorActionId,
722 editor_actions:
723 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
724 use_autoclose: bool,
725 use_auto_surround: bool,
726 auto_replace_emoji_shortcode: bool,
727 show_git_blame_gutter: bool,
728 show_git_blame_inline: bool,
729 show_git_blame_inline_delay_task: Option<Task<()>>,
730 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
731 git_blame_inline_enabled: bool,
732 serialize_dirty_buffers: bool,
733 show_selection_menu: Option<bool>,
734 blame: Option<Entity<GitBlame>>,
735 blame_subscription: Option<Subscription>,
736 custom_context_menu: Option<
737 Box<
738 dyn 'static
739 + Fn(
740 &mut Self,
741 DisplayPoint,
742 &mut Window,
743 &mut Context<Self>,
744 ) -> Option<Entity<ui::ContextMenu>>,
745 >,
746 >,
747 last_bounds: Option<Bounds<Pixels>>,
748 last_position_map: Option<Rc<PositionMap>>,
749 expect_bounds_change: Option<Bounds<Pixels>>,
750 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
751 tasks_update_task: Option<Task<()>>,
752 in_project_search: bool,
753 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
754 breadcrumb_header: Option<String>,
755 focused_block: Option<FocusedBlock>,
756 next_scroll_position: NextScrollCursorCenterTopBottom,
757 addons: HashMap<TypeId, Box<dyn Addon>>,
758 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
759 load_diff_task: Option<Shared<Task<()>>>,
760 selection_mark_mode: bool,
761 toggle_fold_multiple_buffers: Task<()>,
762 _scroll_cursor_center_top_bottom_task: Task<()>,
763 serialize_selections: Task<()>,
764}
765
766#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
767enum NextScrollCursorCenterTopBottom {
768 #[default]
769 Center,
770 Top,
771 Bottom,
772}
773
774impl NextScrollCursorCenterTopBottom {
775 fn next(&self) -> Self {
776 match self {
777 Self::Center => Self::Top,
778 Self::Top => Self::Bottom,
779 Self::Bottom => Self::Center,
780 }
781 }
782}
783
784#[derive(Clone)]
785pub struct EditorSnapshot {
786 pub mode: EditorMode,
787 show_gutter: bool,
788 show_line_numbers: Option<bool>,
789 show_git_diff_gutter: Option<bool>,
790 show_code_actions: Option<bool>,
791 show_runnables: Option<bool>,
792 git_blame_gutter_max_author_length: Option<usize>,
793 pub display_snapshot: DisplaySnapshot,
794 pub placeholder_text: Option<Arc<str>>,
795 is_focused: bool,
796 scroll_anchor: ScrollAnchor,
797 ongoing_scroll: OngoingScroll,
798 current_line_highlight: CurrentLineHighlight,
799 gutter_hovered: bool,
800}
801
802const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
803
804#[derive(Default, Debug, Clone, Copy)]
805pub struct GutterDimensions {
806 pub left_padding: Pixels,
807 pub right_padding: Pixels,
808 pub width: Pixels,
809 pub margin: Pixels,
810 pub git_blame_entries_width: Option<Pixels>,
811}
812
813impl GutterDimensions {
814 /// The full width of the space taken up by the gutter.
815 pub fn full_width(&self) -> Pixels {
816 self.margin + self.width
817 }
818
819 /// The width of the space reserved for the fold indicators,
820 /// use alongside 'justify_end' and `gutter_width` to
821 /// right align content with the line numbers
822 pub fn fold_area_width(&self) -> Pixels {
823 self.margin + self.right_padding
824 }
825}
826
827#[derive(Debug)]
828pub struct RemoteSelection {
829 pub replica_id: ReplicaId,
830 pub selection: Selection<Anchor>,
831 pub cursor_shape: CursorShape,
832 pub peer_id: PeerId,
833 pub line_mode: bool,
834 pub participant_index: Option<ParticipantIndex>,
835 pub user_name: Option<SharedString>,
836}
837
838#[derive(Clone, Debug)]
839struct SelectionHistoryEntry {
840 selections: Arc<[Selection<Anchor>]>,
841 select_next_state: Option<SelectNextState>,
842 select_prev_state: Option<SelectNextState>,
843 add_selections_state: Option<AddSelectionsState>,
844}
845
846enum SelectionHistoryMode {
847 Normal,
848 Undoing,
849 Redoing,
850}
851
852#[derive(Clone, PartialEq, Eq, Hash)]
853struct HoveredCursor {
854 replica_id: u16,
855 selection_id: usize,
856}
857
858impl Default for SelectionHistoryMode {
859 fn default() -> Self {
860 Self::Normal
861 }
862}
863
864#[derive(Default)]
865struct SelectionHistory {
866 #[allow(clippy::type_complexity)]
867 selections_by_transaction:
868 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
869 mode: SelectionHistoryMode,
870 undo_stack: VecDeque<SelectionHistoryEntry>,
871 redo_stack: VecDeque<SelectionHistoryEntry>,
872}
873
874impl SelectionHistory {
875 fn insert_transaction(
876 &mut self,
877 transaction_id: TransactionId,
878 selections: Arc<[Selection<Anchor>]>,
879 ) {
880 self.selections_by_transaction
881 .insert(transaction_id, (selections, None));
882 }
883
884 #[allow(clippy::type_complexity)]
885 fn transaction(
886 &self,
887 transaction_id: TransactionId,
888 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
889 self.selections_by_transaction.get(&transaction_id)
890 }
891
892 #[allow(clippy::type_complexity)]
893 fn transaction_mut(
894 &mut self,
895 transaction_id: TransactionId,
896 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
897 self.selections_by_transaction.get_mut(&transaction_id)
898 }
899
900 fn push(&mut self, entry: SelectionHistoryEntry) {
901 if !entry.selections.is_empty() {
902 match self.mode {
903 SelectionHistoryMode::Normal => {
904 self.push_undo(entry);
905 self.redo_stack.clear();
906 }
907 SelectionHistoryMode::Undoing => self.push_redo(entry),
908 SelectionHistoryMode::Redoing => self.push_undo(entry),
909 }
910 }
911 }
912
913 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
914 if self
915 .undo_stack
916 .back()
917 .map_or(true, |e| e.selections != entry.selections)
918 {
919 self.undo_stack.push_back(entry);
920 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
921 self.undo_stack.pop_front();
922 }
923 }
924 }
925
926 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
927 if self
928 .redo_stack
929 .back()
930 .map_or(true, |e| e.selections != entry.selections)
931 {
932 self.redo_stack.push_back(entry);
933 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
934 self.redo_stack.pop_front();
935 }
936 }
937 }
938}
939
940struct RowHighlight {
941 index: usize,
942 range: Range<Anchor>,
943 color: Hsla,
944 should_autoscroll: bool,
945}
946
947#[derive(Clone, Debug)]
948struct AddSelectionsState {
949 above: bool,
950 stack: Vec<usize>,
951}
952
953#[derive(Clone)]
954struct SelectNextState {
955 query: AhoCorasick,
956 wordwise: bool,
957 done: bool,
958}
959
960impl std::fmt::Debug for SelectNextState {
961 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
962 f.debug_struct(std::any::type_name::<Self>())
963 .field("wordwise", &self.wordwise)
964 .field("done", &self.done)
965 .finish()
966 }
967}
968
969#[derive(Debug)]
970struct AutocloseRegion {
971 selection_id: usize,
972 range: Range<Anchor>,
973 pair: BracketPair,
974}
975
976#[derive(Debug)]
977struct SnippetState {
978 ranges: Vec<Vec<Range<Anchor>>>,
979 active_index: usize,
980 choices: Vec<Option<Vec<String>>>,
981}
982
983#[doc(hidden)]
984pub struct RenameState {
985 pub range: Range<Anchor>,
986 pub old_name: Arc<str>,
987 pub editor: Entity<Editor>,
988 block_id: CustomBlockId,
989}
990
991struct InvalidationStack<T>(Vec<T>);
992
993struct RegisteredInlineCompletionProvider {
994 provider: Arc<dyn InlineCompletionProviderHandle>,
995 _subscription: Subscription,
996}
997
998#[derive(Debug, PartialEq, Eq)]
999struct ActiveDiagnosticGroup {
1000 primary_range: Range<Anchor>,
1001 primary_message: String,
1002 group_id: usize,
1003 blocks: HashMap<CustomBlockId, Diagnostic>,
1004 is_valid: bool,
1005}
1006
1007#[derive(Serialize, Deserialize, Clone, Debug)]
1008pub struct ClipboardSelection {
1009 /// The number of bytes in this selection.
1010 pub len: usize,
1011 /// Whether this was a full-line selection.
1012 pub is_entire_line: bool,
1013 /// The column where this selection originally started.
1014 pub start_column: u32,
1015}
1016
1017#[derive(Debug)]
1018pub(crate) struct NavigationData {
1019 cursor_anchor: Anchor,
1020 cursor_position: Point,
1021 scroll_anchor: ScrollAnchor,
1022 scroll_top_row: u32,
1023}
1024
1025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1026pub enum GotoDefinitionKind {
1027 Symbol,
1028 Declaration,
1029 Type,
1030 Implementation,
1031}
1032
1033#[derive(Debug, Clone)]
1034enum InlayHintRefreshReason {
1035 ModifiersChanged(bool),
1036 Toggle(bool),
1037 SettingsChange(InlayHintSettings),
1038 NewLinesShown,
1039 BufferEdited(HashSet<Arc<Language>>),
1040 RefreshRequested,
1041 ExcerptsRemoved(Vec<ExcerptId>),
1042}
1043
1044impl InlayHintRefreshReason {
1045 fn description(&self) -> &'static str {
1046 match self {
1047 Self::ModifiersChanged(_) => "modifiers changed",
1048 Self::Toggle(_) => "toggle",
1049 Self::SettingsChange(_) => "settings change",
1050 Self::NewLinesShown => "new lines shown",
1051 Self::BufferEdited(_) => "buffer edited",
1052 Self::RefreshRequested => "refresh requested",
1053 Self::ExcerptsRemoved(_) => "excerpts removed",
1054 }
1055 }
1056}
1057
1058pub enum FormatTarget {
1059 Buffers,
1060 Ranges(Vec<Range<MultiBufferPoint>>),
1061}
1062
1063pub(crate) struct FocusedBlock {
1064 id: BlockId,
1065 focus_handle: WeakFocusHandle,
1066}
1067
1068#[derive(Clone)]
1069enum JumpData {
1070 MultiBufferRow {
1071 row: MultiBufferRow,
1072 line_offset_from_top: u32,
1073 },
1074 MultiBufferPoint {
1075 excerpt_id: ExcerptId,
1076 position: Point,
1077 anchor: text::Anchor,
1078 line_offset_from_top: u32,
1079 },
1080}
1081
1082pub enum MultibufferSelectionMode {
1083 First,
1084 All,
1085}
1086
1087impl Editor {
1088 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1089 let buffer = cx.new(|cx| Buffer::local("", cx));
1090 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1091 Self::new(
1092 EditorMode::SingleLine { auto_width: false },
1093 buffer,
1094 None,
1095 false,
1096 window,
1097 cx,
1098 )
1099 }
1100
1101 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1102 let buffer = cx.new(|cx| Buffer::local("", cx));
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1105 }
1106
1107 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1108 let buffer = cx.new(|cx| Buffer::local("", cx));
1109 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1110 Self::new(
1111 EditorMode::SingleLine { auto_width: true },
1112 buffer,
1113 None,
1114 false,
1115 window,
1116 cx,
1117 )
1118 }
1119
1120 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1121 let buffer = cx.new(|cx| Buffer::local("", cx));
1122 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1123 Self::new(
1124 EditorMode::AutoHeight { max_lines },
1125 buffer,
1126 None,
1127 false,
1128 window,
1129 cx,
1130 )
1131 }
1132
1133 pub fn for_buffer(
1134 buffer: Entity<Buffer>,
1135 project: Option<Entity<Project>>,
1136 window: &mut Window,
1137 cx: &mut Context<Self>,
1138 ) -> Self {
1139 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1140 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1141 }
1142
1143 pub fn for_multibuffer(
1144 buffer: Entity<MultiBuffer>,
1145 project: Option<Entity<Project>>,
1146 show_excerpt_controls: bool,
1147 window: &mut Window,
1148 cx: &mut Context<Self>,
1149 ) -> Self {
1150 Self::new(
1151 EditorMode::Full,
1152 buffer,
1153 project,
1154 show_excerpt_controls,
1155 window,
1156 cx,
1157 )
1158 }
1159
1160 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1161 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1162 let mut clone = Self::new(
1163 self.mode,
1164 self.buffer.clone(),
1165 self.project.clone(),
1166 show_excerpt_controls,
1167 window,
1168 cx,
1169 );
1170 self.display_map.update(cx, |display_map, cx| {
1171 let snapshot = display_map.snapshot(cx);
1172 clone.display_map.update(cx, |display_map, cx| {
1173 display_map.set_state(&snapshot, cx);
1174 });
1175 });
1176 clone.selections.clone_state(&self.selections);
1177 clone.scroll_manager.clone_state(&self.scroll_manager);
1178 clone.searchable = self.searchable;
1179 clone
1180 }
1181
1182 pub fn new(
1183 mode: EditorMode,
1184 buffer: Entity<MultiBuffer>,
1185 project: Option<Entity<Project>>,
1186 show_excerpt_controls: bool,
1187 window: &mut Window,
1188 cx: &mut Context<Self>,
1189 ) -> Self {
1190 let style = window.text_style();
1191 let font_size = style.font_size.to_pixels(window.rem_size());
1192 let editor = cx.entity().downgrade();
1193 let fold_placeholder = FoldPlaceholder {
1194 constrain_width: true,
1195 render: Arc::new(move |fold_id, fold_range, cx| {
1196 let editor = editor.clone();
1197 div()
1198 .id(fold_id)
1199 .bg(cx.theme().colors().ghost_element_background)
1200 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1201 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1202 .rounded_sm()
1203 .size_full()
1204 .cursor_pointer()
1205 .child("⋯")
1206 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1207 .on_click(move |_, _window, cx| {
1208 editor
1209 .update(cx, |editor, cx| {
1210 editor.unfold_ranges(
1211 &[fold_range.start..fold_range.end],
1212 true,
1213 false,
1214 cx,
1215 );
1216 cx.stop_propagation();
1217 })
1218 .ok();
1219 })
1220 .into_any()
1221 }),
1222 merge_adjacent: true,
1223 ..Default::default()
1224 };
1225 let display_map = cx.new(|cx| {
1226 DisplayMap::new(
1227 buffer.clone(),
1228 style.font(),
1229 font_size,
1230 None,
1231 show_excerpt_controls,
1232 FILE_HEADER_HEIGHT,
1233 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1234 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1235 fold_placeholder,
1236 cx,
1237 )
1238 });
1239
1240 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1241
1242 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1243
1244 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1245 .then(|| language_settings::SoftWrap::None);
1246
1247 let mut project_subscriptions = Vec::new();
1248 if mode == EditorMode::Full {
1249 if let Some(project) = project.as_ref() {
1250 if buffer.read(cx).is_singleton() {
1251 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1252 cx.emit(EditorEvent::TitleChanged);
1253 }));
1254 }
1255 project_subscriptions.push(cx.subscribe_in(
1256 project,
1257 window,
1258 |editor, _, event, window, cx| {
1259 if let project::Event::RefreshInlayHints = event {
1260 editor
1261 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1262 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1263 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1264 let focus_handle = editor.focus_handle(cx);
1265 if focus_handle.is_focused(window) {
1266 let snapshot = buffer.read(cx).snapshot();
1267 for (range, snippet) in snippet_edits {
1268 let editor_range =
1269 language::range_from_lsp(*range).to_offset(&snapshot);
1270 editor
1271 .insert_snippet(
1272 &[editor_range],
1273 snippet.clone(),
1274 window,
1275 cx,
1276 )
1277 .ok();
1278 }
1279 }
1280 }
1281 }
1282 },
1283 ));
1284 if let Some(task_inventory) = project
1285 .read(cx)
1286 .task_store()
1287 .read(cx)
1288 .task_inventory()
1289 .cloned()
1290 {
1291 project_subscriptions.push(cx.observe_in(
1292 &task_inventory,
1293 window,
1294 |editor, _, window, cx| {
1295 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1296 },
1297 ));
1298 }
1299 }
1300 }
1301
1302 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1303
1304 let inlay_hint_settings =
1305 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1306 let focus_handle = cx.focus_handle();
1307 cx.on_focus(&focus_handle, window, Self::handle_focus)
1308 .detach();
1309 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1310 .detach();
1311 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1312 .detach();
1313 cx.on_blur(&focus_handle, window, Self::handle_blur)
1314 .detach();
1315
1316 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1317 Some(false)
1318 } else {
1319 None
1320 };
1321
1322 let mut code_action_providers = Vec::new();
1323 let mut load_uncommitted_diff = None;
1324 if let Some(project) = project.clone() {
1325 load_uncommitted_diff = Some(
1326 get_uncommitted_diff_for_buffer(
1327 &project,
1328 buffer.read(cx).all_buffers(),
1329 buffer.clone(),
1330 cx,
1331 )
1332 .shared(),
1333 );
1334 code_action_providers.push(Rc::new(project) as Rc<_>);
1335 }
1336
1337 let mut this = Self {
1338 focus_handle,
1339 show_cursor_when_unfocused: false,
1340 last_focused_descendant: None,
1341 buffer: buffer.clone(),
1342 display_map: display_map.clone(),
1343 selections,
1344 scroll_manager: ScrollManager::new(cx),
1345 columnar_selection_tail: None,
1346 add_selections_state: None,
1347 select_next_state: None,
1348 select_prev_state: None,
1349 selection_history: Default::default(),
1350 autoclose_regions: Default::default(),
1351 snippet_stack: Default::default(),
1352 select_larger_syntax_node_stack: Vec::new(),
1353 ime_transaction: Default::default(),
1354 active_diagnostics: None,
1355 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1356 inline_diagnostics_update: Task::ready(()),
1357 inline_diagnostics: Vec::new(),
1358 soft_wrap_mode_override,
1359 completion_provider: project.clone().map(|project| Box::new(project) as _),
1360 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1361 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1362 project,
1363 blink_manager: blink_manager.clone(),
1364 show_local_selections: true,
1365 show_scrollbars: true,
1366 mode,
1367 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1368 show_gutter: mode == EditorMode::Full,
1369 show_line_numbers: None,
1370 use_relative_line_numbers: None,
1371 show_git_diff_gutter: None,
1372 show_code_actions: None,
1373 show_runnables: None,
1374 show_wrap_guides: None,
1375 show_indent_guides,
1376 placeholder_text: None,
1377 highlight_order: 0,
1378 highlighted_rows: HashMap::default(),
1379 background_highlights: Default::default(),
1380 gutter_highlights: TreeMap::default(),
1381 scrollbar_marker_state: ScrollbarMarkerState::default(),
1382 active_indent_guides_state: ActiveIndentGuidesState::default(),
1383 nav_history: None,
1384 context_menu: RefCell::new(None),
1385 mouse_context_menu: None,
1386 completion_tasks: Default::default(),
1387 signature_help_state: SignatureHelpState::default(),
1388 auto_signature_help: None,
1389 find_all_references_task_sources: Vec::new(),
1390 next_completion_id: 0,
1391 next_inlay_id: 0,
1392 code_action_providers,
1393 available_code_actions: Default::default(),
1394 code_actions_task: Default::default(),
1395 selection_highlight_task: Default::default(),
1396 document_highlights_task: Default::default(),
1397 linked_editing_range_task: Default::default(),
1398 pending_rename: Default::default(),
1399 searchable: true,
1400 cursor_shape: EditorSettings::get_global(cx)
1401 .cursor_shape
1402 .unwrap_or_default(),
1403 current_line_highlight: None,
1404 autoindent_mode: Some(AutoindentMode::EachLine),
1405 collapse_matches: false,
1406 workspace: None,
1407 input_enabled: true,
1408 use_modal_editing: mode == EditorMode::Full,
1409 read_only: false,
1410 use_autoclose: true,
1411 use_auto_surround: true,
1412 auto_replace_emoji_shortcode: false,
1413 leader_peer_id: None,
1414 remote_id: None,
1415 hover_state: Default::default(),
1416 pending_mouse_down: None,
1417 hovered_link_state: Default::default(),
1418 edit_prediction_provider: None,
1419 active_inline_completion: None,
1420 stale_inline_completion_in_menu: None,
1421 edit_prediction_preview: EditPredictionPreview::Inactive {
1422 released_too_fast: false,
1423 },
1424 inline_diagnostics_enabled: mode == EditorMode::Full,
1425 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1426
1427 gutter_hovered: false,
1428 pixel_position_of_newest_cursor: None,
1429 last_bounds: None,
1430 last_position_map: None,
1431 expect_bounds_change: None,
1432 gutter_dimensions: GutterDimensions::default(),
1433 style: None,
1434 show_cursor_names: false,
1435 hovered_cursors: Default::default(),
1436 next_editor_action_id: EditorActionId::default(),
1437 editor_actions: Rc::default(),
1438 inline_completions_hidden_for_vim_mode: false,
1439 show_inline_completions_override: None,
1440 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1441 edit_prediction_settings: EditPredictionSettings::Disabled,
1442 edit_prediction_indent_conflict: false,
1443 edit_prediction_requires_modifier_in_indent_conflict: true,
1444 custom_context_menu: None,
1445 show_git_blame_gutter: false,
1446 show_git_blame_inline: false,
1447 show_selection_menu: None,
1448 show_git_blame_inline_delay_task: None,
1449 git_blame_inline_tooltip: None,
1450 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1451 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1452 .session
1453 .restore_unsaved_buffers,
1454 blame: None,
1455 blame_subscription: None,
1456 tasks: Default::default(),
1457 _subscriptions: vec![
1458 cx.observe(&buffer, Self::on_buffer_changed),
1459 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1460 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1461 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1462 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1463 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1464 cx.observe_window_activation(window, |editor, window, cx| {
1465 let active = window.is_window_active();
1466 editor.blink_manager.update(cx, |blink_manager, cx| {
1467 if active {
1468 blink_manager.enable(cx);
1469 } else {
1470 blink_manager.disable(cx);
1471 }
1472 });
1473 }),
1474 ],
1475 tasks_update_task: None,
1476 linked_edit_ranges: Default::default(),
1477 in_project_search: false,
1478 previous_search_ranges: None,
1479 breadcrumb_header: None,
1480 focused_block: None,
1481 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1482 addons: HashMap::default(),
1483 registered_buffers: HashMap::default(),
1484 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1485 selection_mark_mode: false,
1486 toggle_fold_multiple_buffers: Task::ready(()),
1487 serialize_selections: Task::ready(()),
1488 text_style_refinement: None,
1489 load_diff_task: load_uncommitted_diff,
1490 };
1491 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1492 this._subscriptions.extend(project_subscriptions);
1493
1494 this.end_selection(window, cx);
1495 this.scroll_manager.show_scrollbar(window, cx);
1496
1497 if mode == EditorMode::Full {
1498 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1499 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1500
1501 if this.git_blame_inline_enabled {
1502 this.git_blame_inline_enabled = true;
1503 this.start_git_blame_inline(false, window, cx);
1504 }
1505
1506 if let Some(buffer) = buffer.read(cx).as_singleton() {
1507 if let Some(project) = this.project.as_ref() {
1508 let handle = project.update(cx, |project, cx| {
1509 project.register_buffer_with_language_servers(&buffer, cx)
1510 });
1511 this.registered_buffers
1512 .insert(buffer.read(cx).remote_id(), handle);
1513 }
1514 }
1515 }
1516
1517 this.report_editor_event("Editor Opened", None, cx);
1518 this
1519 }
1520
1521 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1522 self.mouse_context_menu
1523 .as_ref()
1524 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1525 }
1526
1527 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1528 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1529 }
1530
1531 fn key_context_internal(
1532 &self,
1533 has_active_edit_prediction: bool,
1534 window: &Window,
1535 cx: &App,
1536 ) -> KeyContext {
1537 let mut key_context = KeyContext::new_with_defaults();
1538 key_context.add("Editor");
1539 let mode = match self.mode {
1540 EditorMode::SingleLine { .. } => "single_line",
1541 EditorMode::AutoHeight { .. } => "auto_height",
1542 EditorMode::Full => "full",
1543 };
1544
1545 if EditorSettings::jupyter_enabled(cx) {
1546 key_context.add("jupyter");
1547 }
1548
1549 key_context.set("mode", mode);
1550 if self.pending_rename.is_some() {
1551 key_context.add("renaming");
1552 }
1553
1554 match self.context_menu.borrow().as_ref() {
1555 Some(CodeContextMenu::Completions(_)) => {
1556 key_context.add("menu");
1557 key_context.add("showing_completions");
1558 }
1559 Some(CodeContextMenu::CodeActions(_)) => {
1560 key_context.add("menu");
1561 key_context.add("showing_code_actions")
1562 }
1563 None => {}
1564 }
1565
1566 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1567 if !self.focus_handle(cx).contains_focused(window, cx)
1568 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1569 {
1570 for addon in self.addons.values() {
1571 addon.extend_key_context(&mut key_context, cx)
1572 }
1573 }
1574
1575 if let Some(extension) = self
1576 .buffer
1577 .read(cx)
1578 .as_singleton()
1579 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1580 {
1581 key_context.set("extension", extension.to_string());
1582 }
1583
1584 if has_active_edit_prediction {
1585 if self.edit_prediction_in_conflict() {
1586 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1587 } else {
1588 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1589 key_context.add("copilot_suggestion");
1590 }
1591 }
1592
1593 if self.selection_mark_mode {
1594 key_context.add("selection_mode");
1595 }
1596
1597 key_context
1598 }
1599
1600 pub fn edit_prediction_in_conflict(&self) -> bool {
1601 if !self.show_edit_predictions_in_menu() {
1602 return false;
1603 }
1604
1605 let showing_completions = self
1606 .context_menu
1607 .borrow()
1608 .as_ref()
1609 .map_or(false, |context| {
1610 matches!(context, CodeContextMenu::Completions(_))
1611 });
1612
1613 showing_completions
1614 || self.edit_prediction_requires_modifier()
1615 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1616 // bindings to insert tab characters.
1617 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1618 }
1619
1620 pub fn accept_edit_prediction_keybind(
1621 &self,
1622 window: &Window,
1623 cx: &App,
1624 ) -> AcceptEditPredictionBinding {
1625 let key_context = self.key_context_internal(true, window, cx);
1626 let in_conflict = self.edit_prediction_in_conflict();
1627
1628 AcceptEditPredictionBinding(
1629 window
1630 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1631 .into_iter()
1632 .filter(|binding| {
1633 !in_conflict
1634 || binding
1635 .keystrokes()
1636 .first()
1637 .map_or(false, |keystroke| keystroke.modifiers.modified())
1638 })
1639 .rev()
1640 .min_by_key(|binding| {
1641 binding
1642 .keystrokes()
1643 .first()
1644 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1645 }),
1646 )
1647 }
1648
1649 pub fn new_file(
1650 workspace: &mut Workspace,
1651 _: &workspace::NewFile,
1652 window: &mut Window,
1653 cx: &mut Context<Workspace>,
1654 ) {
1655 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1656 "Failed to create buffer",
1657 window,
1658 cx,
1659 |e, _, _| match e.error_code() {
1660 ErrorCode::RemoteUpgradeRequired => Some(format!(
1661 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1662 e.error_tag("required").unwrap_or("the latest version")
1663 )),
1664 _ => None,
1665 },
1666 );
1667 }
1668
1669 pub fn new_in_workspace(
1670 workspace: &mut Workspace,
1671 window: &mut Window,
1672 cx: &mut Context<Workspace>,
1673 ) -> Task<Result<Entity<Editor>>> {
1674 let project = workspace.project().clone();
1675 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1676
1677 cx.spawn_in(window, |workspace, mut cx| async move {
1678 let buffer = create.await?;
1679 workspace.update_in(&mut cx, |workspace, window, cx| {
1680 let editor =
1681 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1682 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1683 editor
1684 })
1685 })
1686 }
1687
1688 fn new_file_vertical(
1689 workspace: &mut Workspace,
1690 _: &workspace::NewFileSplitVertical,
1691 window: &mut Window,
1692 cx: &mut Context<Workspace>,
1693 ) {
1694 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1695 }
1696
1697 fn new_file_horizontal(
1698 workspace: &mut Workspace,
1699 _: &workspace::NewFileSplitHorizontal,
1700 window: &mut Window,
1701 cx: &mut Context<Workspace>,
1702 ) {
1703 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1704 }
1705
1706 fn new_file_in_direction(
1707 workspace: &mut Workspace,
1708 direction: SplitDirection,
1709 window: &mut Window,
1710 cx: &mut Context<Workspace>,
1711 ) {
1712 let project = workspace.project().clone();
1713 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1714
1715 cx.spawn_in(window, |workspace, mut cx| async move {
1716 let buffer = create.await?;
1717 workspace.update_in(&mut cx, move |workspace, window, cx| {
1718 workspace.split_item(
1719 direction,
1720 Box::new(
1721 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1722 ),
1723 window,
1724 cx,
1725 )
1726 })?;
1727 anyhow::Ok(())
1728 })
1729 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1730 match e.error_code() {
1731 ErrorCode::RemoteUpgradeRequired => Some(format!(
1732 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1733 e.error_tag("required").unwrap_or("the latest version")
1734 )),
1735 _ => None,
1736 }
1737 });
1738 }
1739
1740 pub fn leader_peer_id(&self) -> Option<PeerId> {
1741 self.leader_peer_id
1742 }
1743
1744 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1745 &self.buffer
1746 }
1747
1748 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1749 self.workspace.as_ref()?.0.upgrade()
1750 }
1751
1752 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1753 self.buffer().read(cx).title(cx)
1754 }
1755
1756 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1757 let git_blame_gutter_max_author_length = self
1758 .render_git_blame_gutter(cx)
1759 .then(|| {
1760 if let Some(blame) = self.blame.as_ref() {
1761 let max_author_length =
1762 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1763 Some(max_author_length)
1764 } else {
1765 None
1766 }
1767 })
1768 .flatten();
1769
1770 EditorSnapshot {
1771 mode: self.mode,
1772 show_gutter: self.show_gutter,
1773 show_line_numbers: self.show_line_numbers,
1774 show_git_diff_gutter: self.show_git_diff_gutter,
1775 show_code_actions: self.show_code_actions,
1776 show_runnables: self.show_runnables,
1777 git_blame_gutter_max_author_length,
1778 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1779 scroll_anchor: self.scroll_manager.anchor(),
1780 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1781 placeholder_text: self.placeholder_text.clone(),
1782 is_focused: self.focus_handle.is_focused(window),
1783 current_line_highlight: self
1784 .current_line_highlight
1785 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1786 gutter_hovered: self.gutter_hovered,
1787 }
1788 }
1789
1790 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1791 self.buffer.read(cx).language_at(point, cx)
1792 }
1793
1794 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1795 self.buffer.read(cx).read(cx).file_at(point).cloned()
1796 }
1797
1798 pub fn active_excerpt(
1799 &self,
1800 cx: &App,
1801 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1802 self.buffer
1803 .read(cx)
1804 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1805 }
1806
1807 pub fn mode(&self) -> EditorMode {
1808 self.mode
1809 }
1810
1811 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1812 self.collaboration_hub.as_deref()
1813 }
1814
1815 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1816 self.collaboration_hub = Some(hub);
1817 }
1818
1819 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1820 self.in_project_search = in_project_search;
1821 }
1822
1823 pub fn set_custom_context_menu(
1824 &mut self,
1825 f: impl 'static
1826 + Fn(
1827 &mut Self,
1828 DisplayPoint,
1829 &mut Window,
1830 &mut Context<Self>,
1831 ) -> Option<Entity<ui::ContextMenu>>,
1832 ) {
1833 self.custom_context_menu = Some(Box::new(f))
1834 }
1835
1836 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1837 self.completion_provider = provider;
1838 }
1839
1840 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1841 self.semantics_provider.clone()
1842 }
1843
1844 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1845 self.semantics_provider = provider;
1846 }
1847
1848 pub fn set_edit_prediction_provider<T>(
1849 &mut self,
1850 provider: Option<Entity<T>>,
1851 window: &mut Window,
1852 cx: &mut Context<Self>,
1853 ) where
1854 T: EditPredictionProvider,
1855 {
1856 self.edit_prediction_provider =
1857 provider.map(|provider| RegisteredInlineCompletionProvider {
1858 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1859 if this.focus_handle.is_focused(window) {
1860 this.update_visible_inline_completion(window, cx);
1861 }
1862 }),
1863 provider: Arc::new(provider),
1864 });
1865 self.update_edit_prediction_settings(cx);
1866 self.refresh_inline_completion(false, false, window, cx);
1867 }
1868
1869 pub fn placeholder_text(&self) -> Option<&str> {
1870 self.placeholder_text.as_deref()
1871 }
1872
1873 pub fn set_placeholder_text(
1874 &mut self,
1875 placeholder_text: impl Into<Arc<str>>,
1876 cx: &mut Context<Self>,
1877 ) {
1878 let placeholder_text = Some(placeholder_text.into());
1879 if self.placeholder_text != placeholder_text {
1880 self.placeholder_text = placeholder_text;
1881 cx.notify();
1882 }
1883 }
1884
1885 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1886 self.cursor_shape = cursor_shape;
1887
1888 // Disrupt blink for immediate user feedback that the cursor shape has changed
1889 self.blink_manager.update(cx, BlinkManager::show_cursor);
1890
1891 cx.notify();
1892 }
1893
1894 pub fn set_current_line_highlight(
1895 &mut self,
1896 current_line_highlight: Option<CurrentLineHighlight>,
1897 ) {
1898 self.current_line_highlight = current_line_highlight;
1899 }
1900
1901 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1902 self.collapse_matches = collapse_matches;
1903 }
1904
1905 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1906 let buffers = self.buffer.read(cx).all_buffers();
1907 let Some(project) = self.project.as_ref() else {
1908 return;
1909 };
1910 project.update(cx, |project, cx| {
1911 for buffer in buffers {
1912 self.registered_buffers
1913 .entry(buffer.read(cx).remote_id())
1914 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1915 }
1916 })
1917 }
1918
1919 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1920 if self.collapse_matches {
1921 return range.start..range.start;
1922 }
1923 range.clone()
1924 }
1925
1926 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1927 if self.display_map.read(cx).clip_at_line_ends != clip {
1928 self.display_map
1929 .update(cx, |map, _| map.clip_at_line_ends = clip);
1930 }
1931 }
1932
1933 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1934 self.input_enabled = input_enabled;
1935 }
1936
1937 pub fn set_inline_completions_hidden_for_vim_mode(
1938 &mut self,
1939 hidden: bool,
1940 window: &mut Window,
1941 cx: &mut Context<Self>,
1942 ) {
1943 if hidden != self.inline_completions_hidden_for_vim_mode {
1944 self.inline_completions_hidden_for_vim_mode = hidden;
1945 if hidden {
1946 self.update_visible_inline_completion(window, cx);
1947 } else {
1948 self.refresh_inline_completion(true, false, window, cx);
1949 }
1950 }
1951 }
1952
1953 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1954 self.menu_inline_completions_policy = value;
1955 }
1956
1957 pub fn set_autoindent(&mut self, autoindent: bool) {
1958 if autoindent {
1959 self.autoindent_mode = Some(AutoindentMode::EachLine);
1960 } else {
1961 self.autoindent_mode = None;
1962 }
1963 }
1964
1965 pub fn read_only(&self, cx: &App) -> bool {
1966 self.read_only || self.buffer.read(cx).read_only()
1967 }
1968
1969 pub fn set_read_only(&mut self, read_only: bool) {
1970 self.read_only = read_only;
1971 }
1972
1973 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1974 self.use_autoclose = autoclose;
1975 }
1976
1977 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1978 self.use_auto_surround = auto_surround;
1979 }
1980
1981 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1982 self.auto_replace_emoji_shortcode = auto_replace;
1983 }
1984
1985 pub fn toggle_edit_predictions(
1986 &mut self,
1987 _: &ToggleEditPrediction,
1988 window: &mut Window,
1989 cx: &mut Context<Self>,
1990 ) {
1991 if self.show_inline_completions_override.is_some() {
1992 self.set_show_edit_predictions(None, window, cx);
1993 } else {
1994 let show_edit_predictions = !self.edit_predictions_enabled();
1995 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1996 }
1997 }
1998
1999 pub fn set_show_edit_predictions(
2000 &mut self,
2001 show_edit_predictions: Option<bool>,
2002 window: &mut Window,
2003 cx: &mut Context<Self>,
2004 ) {
2005 self.show_inline_completions_override = show_edit_predictions;
2006 self.update_edit_prediction_settings(cx);
2007
2008 if let Some(false) = show_edit_predictions {
2009 self.discard_inline_completion(false, cx);
2010 } else {
2011 self.refresh_inline_completion(false, true, window, cx);
2012 }
2013 }
2014
2015 fn inline_completions_disabled_in_scope(
2016 &self,
2017 buffer: &Entity<Buffer>,
2018 buffer_position: language::Anchor,
2019 cx: &App,
2020 ) -> bool {
2021 let snapshot = buffer.read(cx).snapshot();
2022 let settings = snapshot.settings_at(buffer_position, cx);
2023
2024 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2025 return false;
2026 };
2027
2028 scope.override_name().map_or(false, |scope_name| {
2029 settings
2030 .edit_predictions_disabled_in
2031 .iter()
2032 .any(|s| s == scope_name)
2033 })
2034 }
2035
2036 pub fn set_use_modal_editing(&mut self, to: bool) {
2037 self.use_modal_editing = to;
2038 }
2039
2040 pub fn use_modal_editing(&self) -> bool {
2041 self.use_modal_editing
2042 }
2043
2044 fn selections_did_change(
2045 &mut self,
2046 local: bool,
2047 old_cursor_position: &Anchor,
2048 show_completions: bool,
2049 window: &mut Window,
2050 cx: &mut Context<Self>,
2051 ) {
2052 window.invalidate_character_coordinates();
2053
2054 // Copy selections to primary selection buffer
2055 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2056 if local {
2057 let selections = self.selections.all::<usize>(cx);
2058 let buffer_handle = self.buffer.read(cx).read(cx);
2059
2060 let mut text = String::new();
2061 for (index, selection) in selections.iter().enumerate() {
2062 let text_for_selection = buffer_handle
2063 .text_for_range(selection.start..selection.end)
2064 .collect::<String>();
2065
2066 text.push_str(&text_for_selection);
2067 if index != selections.len() - 1 {
2068 text.push('\n');
2069 }
2070 }
2071
2072 if !text.is_empty() {
2073 cx.write_to_primary(ClipboardItem::new_string(text));
2074 }
2075 }
2076
2077 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2078 self.buffer.update(cx, |buffer, cx| {
2079 buffer.set_active_selections(
2080 &self.selections.disjoint_anchors(),
2081 self.selections.line_mode,
2082 self.cursor_shape,
2083 cx,
2084 )
2085 });
2086 }
2087 let display_map = self
2088 .display_map
2089 .update(cx, |display_map, cx| display_map.snapshot(cx));
2090 let buffer = &display_map.buffer_snapshot;
2091 self.add_selections_state = None;
2092 self.select_next_state = None;
2093 self.select_prev_state = None;
2094 self.select_larger_syntax_node_stack.clear();
2095 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2096 self.snippet_stack
2097 .invalidate(&self.selections.disjoint_anchors(), buffer);
2098 self.take_rename(false, window, cx);
2099
2100 let new_cursor_position = self.selections.newest_anchor().head();
2101
2102 self.push_to_nav_history(
2103 *old_cursor_position,
2104 Some(new_cursor_position.to_point(buffer)),
2105 cx,
2106 );
2107
2108 if local {
2109 let new_cursor_position = self.selections.newest_anchor().head();
2110 let mut context_menu = self.context_menu.borrow_mut();
2111 let completion_menu = match context_menu.as_ref() {
2112 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2113 _ => {
2114 *context_menu = None;
2115 None
2116 }
2117 };
2118 if let Some(buffer_id) = new_cursor_position.buffer_id {
2119 if !self.registered_buffers.contains_key(&buffer_id) {
2120 if let Some(project) = self.project.as_ref() {
2121 project.update(cx, |project, cx| {
2122 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2123 return;
2124 };
2125 self.registered_buffers.insert(
2126 buffer_id,
2127 project.register_buffer_with_language_servers(&buffer, cx),
2128 );
2129 })
2130 }
2131 }
2132 }
2133
2134 if let Some(completion_menu) = completion_menu {
2135 let cursor_position = new_cursor_position.to_offset(buffer);
2136 let (word_range, kind) =
2137 buffer.surrounding_word(completion_menu.initial_position, true);
2138 if kind == Some(CharKind::Word)
2139 && word_range.to_inclusive().contains(&cursor_position)
2140 {
2141 let mut completion_menu = completion_menu.clone();
2142 drop(context_menu);
2143
2144 let query = Self::completion_query(buffer, cursor_position);
2145 cx.spawn(move |this, mut cx| async move {
2146 completion_menu
2147 .filter(query.as_deref(), cx.background_executor().clone())
2148 .await;
2149
2150 this.update(&mut cx, |this, cx| {
2151 let mut context_menu = this.context_menu.borrow_mut();
2152 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2153 else {
2154 return;
2155 };
2156
2157 if menu.id > completion_menu.id {
2158 return;
2159 }
2160
2161 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2162 drop(context_menu);
2163 cx.notify();
2164 })
2165 })
2166 .detach();
2167
2168 if show_completions {
2169 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2170 }
2171 } else {
2172 drop(context_menu);
2173 self.hide_context_menu(window, cx);
2174 }
2175 } else {
2176 drop(context_menu);
2177 }
2178
2179 hide_hover(self, cx);
2180
2181 if old_cursor_position.to_display_point(&display_map).row()
2182 != new_cursor_position.to_display_point(&display_map).row()
2183 {
2184 self.available_code_actions.take();
2185 }
2186 self.refresh_code_actions(window, cx);
2187 self.refresh_document_highlights(cx);
2188 self.refresh_selected_text_highlights(window, cx);
2189 refresh_matching_bracket_highlights(self, window, cx);
2190 self.update_visible_inline_completion(window, cx);
2191 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2192 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2193 if self.git_blame_inline_enabled {
2194 self.start_inline_blame_timer(window, cx);
2195 }
2196 }
2197
2198 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2199 cx.emit(EditorEvent::SelectionsChanged { local });
2200
2201 let selections = &self.selections.disjoint;
2202 if selections.len() == 1 {
2203 cx.emit(SearchEvent::ActiveMatchChanged)
2204 }
2205 if local
2206 && self.is_singleton(cx)
2207 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2208 {
2209 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2210 let background_executor = cx.background_executor().clone();
2211 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2212 let snapshot = self.buffer().read(cx).snapshot(cx);
2213 let selections = selections.clone();
2214 self.serialize_selections = cx.background_spawn(async move {
2215 background_executor.timer(Duration::from_millis(100)).await;
2216 let selections = selections
2217 .iter()
2218 .map(|selection| {
2219 (
2220 selection.start.to_offset(&snapshot),
2221 selection.end.to_offset(&snapshot),
2222 )
2223 })
2224 .collect();
2225 DB.save_editor_selections(editor_id, workspace_id, selections)
2226 .await
2227 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2228 .log_err();
2229 });
2230 }
2231 }
2232
2233 cx.notify();
2234 }
2235
2236 pub fn sync_selections(
2237 &mut self,
2238 other: Entity<Editor>,
2239 cx: &mut Context<Self>,
2240 ) -> gpui::Subscription {
2241 let other_selections = other.read(cx).selections.disjoint.to_vec();
2242 self.selections.change_with(cx, |selections| {
2243 selections.select_anchors(other_selections);
2244 });
2245
2246 let other_subscription =
2247 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2248 EditorEvent::SelectionsChanged { local: true } => {
2249 let other_selections = other.read(cx).selections.disjoint.to_vec();
2250 this.selections.change_with(cx, |selections| {
2251 selections.select_anchors(other_selections);
2252 });
2253 }
2254 _ => {}
2255 });
2256
2257 let this_subscription =
2258 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2259 EditorEvent::SelectionsChanged { local: true } => {
2260 let these_selections = this.selections.disjoint.to_vec();
2261 other.update(cx, |other_editor, cx| {
2262 other_editor.selections.change_with(cx, |selections| {
2263 selections.select_anchors(these_selections);
2264 })
2265 });
2266 }
2267 _ => {}
2268 });
2269
2270 Subscription::join(other_subscription, this_subscription)
2271 }
2272
2273 pub fn change_selections<R>(
2274 &mut self,
2275 autoscroll: Option<Autoscroll>,
2276 window: &mut Window,
2277 cx: &mut Context<Self>,
2278 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2279 ) -> R {
2280 self.change_selections_inner(autoscroll, true, window, cx, change)
2281 }
2282
2283 fn change_selections_inner<R>(
2284 &mut self,
2285 autoscroll: Option<Autoscroll>,
2286 request_completions: bool,
2287 window: &mut Window,
2288 cx: &mut Context<Self>,
2289 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2290 ) -> R {
2291 let old_cursor_position = self.selections.newest_anchor().head();
2292 self.push_to_selection_history();
2293
2294 let (changed, result) = self.selections.change_with(cx, change);
2295
2296 if changed {
2297 if let Some(autoscroll) = autoscroll {
2298 self.request_autoscroll(autoscroll, cx);
2299 }
2300 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2301
2302 if self.should_open_signature_help_automatically(
2303 &old_cursor_position,
2304 self.signature_help_state.backspace_pressed(),
2305 cx,
2306 ) {
2307 self.show_signature_help(&ShowSignatureHelp, window, cx);
2308 }
2309 self.signature_help_state.set_backspace_pressed(false);
2310 }
2311
2312 result
2313 }
2314
2315 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2316 where
2317 I: IntoIterator<Item = (Range<S>, T)>,
2318 S: ToOffset,
2319 T: Into<Arc<str>>,
2320 {
2321 if self.read_only(cx) {
2322 return;
2323 }
2324
2325 self.buffer
2326 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2327 }
2328
2329 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2330 where
2331 I: IntoIterator<Item = (Range<S>, T)>,
2332 S: ToOffset,
2333 T: Into<Arc<str>>,
2334 {
2335 if self.read_only(cx) {
2336 return;
2337 }
2338
2339 self.buffer.update(cx, |buffer, cx| {
2340 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2341 });
2342 }
2343
2344 pub fn edit_with_block_indent<I, S, T>(
2345 &mut self,
2346 edits: I,
2347 original_start_columns: Vec<u32>,
2348 cx: &mut Context<Self>,
2349 ) where
2350 I: IntoIterator<Item = (Range<S>, T)>,
2351 S: ToOffset,
2352 T: Into<Arc<str>>,
2353 {
2354 if self.read_only(cx) {
2355 return;
2356 }
2357
2358 self.buffer.update(cx, |buffer, cx| {
2359 buffer.edit(
2360 edits,
2361 Some(AutoindentMode::Block {
2362 original_start_columns,
2363 }),
2364 cx,
2365 )
2366 });
2367 }
2368
2369 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2370 self.hide_context_menu(window, cx);
2371
2372 match phase {
2373 SelectPhase::Begin {
2374 position,
2375 add,
2376 click_count,
2377 } => self.begin_selection(position, add, click_count, window, cx),
2378 SelectPhase::BeginColumnar {
2379 position,
2380 goal_column,
2381 reset,
2382 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2383 SelectPhase::Extend {
2384 position,
2385 click_count,
2386 } => self.extend_selection(position, click_count, window, cx),
2387 SelectPhase::Update {
2388 position,
2389 goal_column,
2390 scroll_delta,
2391 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2392 SelectPhase::End => self.end_selection(window, cx),
2393 }
2394 }
2395
2396 fn extend_selection(
2397 &mut self,
2398 position: DisplayPoint,
2399 click_count: usize,
2400 window: &mut Window,
2401 cx: &mut Context<Self>,
2402 ) {
2403 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2404 let tail = self.selections.newest::<usize>(cx).tail();
2405 self.begin_selection(position, false, click_count, window, cx);
2406
2407 let position = position.to_offset(&display_map, Bias::Left);
2408 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2409
2410 let mut pending_selection = self
2411 .selections
2412 .pending_anchor()
2413 .expect("extend_selection not called with pending selection");
2414 if position >= tail {
2415 pending_selection.start = tail_anchor;
2416 } else {
2417 pending_selection.end = tail_anchor;
2418 pending_selection.reversed = true;
2419 }
2420
2421 let mut pending_mode = self.selections.pending_mode().unwrap();
2422 match &mut pending_mode {
2423 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2424 _ => {}
2425 }
2426
2427 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2428 s.set_pending(pending_selection, pending_mode)
2429 });
2430 }
2431
2432 fn begin_selection(
2433 &mut self,
2434 position: DisplayPoint,
2435 add: bool,
2436 click_count: usize,
2437 window: &mut Window,
2438 cx: &mut Context<Self>,
2439 ) {
2440 if !self.focus_handle.is_focused(window) {
2441 self.last_focused_descendant = None;
2442 window.focus(&self.focus_handle);
2443 }
2444
2445 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2446 let buffer = &display_map.buffer_snapshot;
2447 let newest_selection = self.selections.newest_anchor().clone();
2448 let position = display_map.clip_point(position, Bias::Left);
2449
2450 let start;
2451 let end;
2452 let mode;
2453 let mut auto_scroll;
2454 match click_count {
2455 1 => {
2456 start = buffer.anchor_before(position.to_point(&display_map));
2457 end = start;
2458 mode = SelectMode::Character;
2459 auto_scroll = true;
2460 }
2461 2 => {
2462 let range = movement::surrounding_word(&display_map, position);
2463 start = buffer.anchor_before(range.start.to_point(&display_map));
2464 end = buffer.anchor_before(range.end.to_point(&display_map));
2465 mode = SelectMode::Word(start..end);
2466 auto_scroll = true;
2467 }
2468 3 => {
2469 let position = display_map
2470 .clip_point(position, Bias::Left)
2471 .to_point(&display_map);
2472 let line_start = display_map.prev_line_boundary(position).0;
2473 let next_line_start = buffer.clip_point(
2474 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2475 Bias::Left,
2476 );
2477 start = buffer.anchor_before(line_start);
2478 end = buffer.anchor_before(next_line_start);
2479 mode = SelectMode::Line(start..end);
2480 auto_scroll = true;
2481 }
2482 _ => {
2483 start = buffer.anchor_before(0);
2484 end = buffer.anchor_before(buffer.len());
2485 mode = SelectMode::All;
2486 auto_scroll = false;
2487 }
2488 }
2489 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2490
2491 let point_to_delete: Option<usize> = {
2492 let selected_points: Vec<Selection<Point>> =
2493 self.selections.disjoint_in_range(start..end, cx);
2494
2495 if !add || click_count > 1 {
2496 None
2497 } else if !selected_points.is_empty() {
2498 Some(selected_points[0].id)
2499 } else {
2500 let clicked_point_already_selected =
2501 self.selections.disjoint.iter().find(|selection| {
2502 selection.start.to_point(buffer) == start.to_point(buffer)
2503 || selection.end.to_point(buffer) == end.to_point(buffer)
2504 });
2505
2506 clicked_point_already_selected.map(|selection| selection.id)
2507 }
2508 };
2509
2510 let selections_count = self.selections.count();
2511
2512 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2513 if let Some(point_to_delete) = point_to_delete {
2514 s.delete(point_to_delete);
2515
2516 if selections_count == 1 {
2517 s.set_pending_anchor_range(start..end, mode);
2518 }
2519 } else {
2520 if !add {
2521 s.clear_disjoint();
2522 } else if click_count > 1 {
2523 s.delete(newest_selection.id)
2524 }
2525
2526 s.set_pending_anchor_range(start..end, mode);
2527 }
2528 });
2529 }
2530
2531 fn begin_columnar_selection(
2532 &mut self,
2533 position: DisplayPoint,
2534 goal_column: u32,
2535 reset: bool,
2536 window: &mut Window,
2537 cx: &mut Context<Self>,
2538 ) {
2539 if !self.focus_handle.is_focused(window) {
2540 self.last_focused_descendant = None;
2541 window.focus(&self.focus_handle);
2542 }
2543
2544 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2545
2546 if reset {
2547 let pointer_position = display_map
2548 .buffer_snapshot
2549 .anchor_before(position.to_point(&display_map));
2550
2551 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2552 s.clear_disjoint();
2553 s.set_pending_anchor_range(
2554 pointer_position..pointer_position,
2555 SelectMode::Character,
2556 );
2557 });
2558 }
2559
2560 let tail = self.selections.newest::<Point>(cx).tail();
2561 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2562
2563 if !reset {
2564 self.select_columns(
2565 tail.to_display_point(&display_map),
2566 position,
2567 goal_column,
2568 &display_map,
2569 window,
2570 cx,
2571 );
2572 }
2573 }
2574
2575 fn update_selection(
2576 &mut self,
2577 position: DisplayPoint,
2578 goal_column: u32,
2579 scroll_delta: gpui::Point<f32>,
2580 window: &mut Window,
2581 cx: &mut Context<Self>,
2582 ) {
2583 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2584
2585 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2586 let tail = tail.to_display_point(&display_map);
2587 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2588 } else if let Some(mut pending) = self.selections.pending_anchor() {
2589 let buffer = self.buffer.read(cx).snapshot(cx);
2590 let head;
2591 let tail;
2592 let mode = self.selections.pending_mode().unwrap();
2593 match &mode {
2594 SelectMode::Character => {
2595 head = position.to_point(&display_map);
2596 tail = pending.tail().to_point(&buffer);
2597 }
2598 SelectMode::Word(original_range) => {
2599 let original_display_range = original_range.start.to_display_point(&display_map)
2600 ..original_range.end.to_display_point(&display_map);
2601 let original_buffer_range = original_display_range.start.to_point(&display_map)
2602 ..original_display_range.end.to_point(&display_map);
2603 if movement::is_inside_word(&display_map, position)
2604 || original_display_range.contains(&position)
2605 {
2606 let word_range = movement::surrounding_word(&display_map, position);
2607 if word_range.start < original_display_range.start {
2608 head = word_range.start.to_point(&display_map);
2609 } else {
2610 head = word_range.end.to_point(&display_map);
2611 }
2612 } else {
2613 head = position.to_point(&display_map);
2614 }
2615
2616 if head <= original_buffer_range.start {
2617 tail = original_buffer_range.end;
2618 } else {
2619 tail = original_buffer_range.start;
2620 }
2621 }
2622 SelectMode::Line(original_range) => {
2623 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2624
2625 let position = display_map
2626 .clip_point(position, Bias::Left)
2627 .to_point(&display_map);
2628 let line_start = display_map.prev_line_boundary(position).0;
2629 let next_line_start = buffer.clip_point(
2630 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2631 Bias::Left,
2632 );
2633
2634 if line_start < original_range.start {
2635 head = line_start
2636 } else {
2637 head = next_line_start
2638 }
2639
2640 if head <= original_range.start {
2641 tail = original_range.end;
2642 } else {
2643 tail = original_range.start;
2644 }
2645 }
2646 SelectMode::All => {
2647 return;
2648 }
2649 };
2650
2651 if head < tail {
2652 pending.start = buffer.anchor_before(head);
2653 pending.end = buffer.anchor_before(tail);
2654 pending.reversed = true;
2655 } else {
2656 pending.start = buffer.anchor_before(tail);
2657 pending.end = buffer.anchor_before(head);
2658 pending.reversed = false;
2659 }
2660
2661 self.change_selections(None, window, cx, |s| {
2662 s.set_pending(pending, mode);
2663 });
2664 } else {
2665 log::error!("update_selection dispatched with no pending selection");
2666 return;
2667 }
2668
2669 self.apply_scroll_delta(scroll_delta, window, cx);
2670 cx.notify();
2671 }
2672
2673 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2674 self.columnar_selection_tail.take();
2675 if self.selections.pending_anchor().is_some() {
2676 let selections = self.selections.all::<usize>(cx);
2677 self.change_selections(None, window, cx, |s| {
2678 s.select(selections);
2679 s.clear_pending();
2680 });
2681 }
2682 }
2683
2684 fn select_columns(
2685 &mut self,
2686 tail: DisplayPoint,
2687 head: DisplayPoint,
2688 goal_column: u32,
2689 display_map: &DisplaySnapshot,
2690 window: &mut Window,
2691 cx: &mut Context<Self>,
2692 ) {
2693 let start_row = cmp::min(tail.row(), head.row());
2694 let end_row = cmp::max(tail.row(), head.row());
2695 let start_column = cmp::min(tail.column(), goal_column);
2696 let end_column = cmp::max(tail.column(), goal_column);
2697 let reversed = start_column < tail.column();
2698
2699 let selection_ranges = (start_row.0..=end_row.0)
2700 .map(DisplayRow)
2701 .filter_map(|row| {
2702 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2703 let start = display_map
2704 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2705 .to_point(display_map);
2706 let end = display_map
2707 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2708 .to_point(display_map);
2709 if reversed {
2710 Some(end..start)
2711 } else {
2712 Some(start..end)
2713 }
2714 } else {
2715 None
2716 }
2717 })
2718 .collect::<Vec<_>>();
2719
2720 self.change_selections(None, window, cx, |s| {
2721 s.select_ranges(selection_ranges);
2722 });
2723 cx.notify();
2724 }
2725
2726 pub fn has_pending_nonempty_selection(&self) -> bool {
2727 let pending_nonempty_selection = match self.selections.pending_anchor() {
2728 Some(Selection { start, end, .. }) => start != end,
2729 None => false,
2730 };
2731
2732 pending_nonempty_selection
2733 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2734 }
2735
2736 pub fn has_pending_selection(&self) -> bool {
2737 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2738 }
2739
2740 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2741 self.selection_mark_mode = false;
2742
2743 if self.clear_expanded_diff_hunks(cx) {
2744 cx.notify();
2745 return;
2746 }
2747 if self.dismiss_menus_and_popups(true, window, cx) {
2748 return;
2749 }
2750
2751 if self.mode == EditorMode::Full
2752 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2753 {
2754 return;
2755 }
2756
2757 cx.propagate();
2758 }
2759
2760 pub fn dismiss_menus_and_popups(
2761 &mut self,
2762 is_user_requested: bool,
2763 window: &mut Window,
2764 cx: &mut Context<Self>,
2765 ) -> bool {
2766 if self.take_rename(false, window, cx).is_some() {
2767 return true;
2768 }
2769
2770 if hide_hover(self, cx) {
2771 return true;
2772 }
2773
2774 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2775 return true;
2776 }
2777
2778 if self.hide_context_menu(window, cx).is_some() {
2779 return true;
2780 }
2781
2782 if self.mouse_context_menu.take().is_some() {
2783 return true;
2784 }
2785
2786 if is_user_requested && self.discard_inline_completion(true, cx) {
2787 return true;
2788 }
2789
2790 if self.snippet_stack.pop().is_some() {
2791 return true;
2792 }
2793
2794 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2795 self.dismiss_diagnostics(cx);
2796 return true;
2797 }
2798
2799 false
2800 }
2801
2802 fn linked_editing_ranges_for(
2803 &self,
2804 selection: Range<text::Anchor>,
2805 cx: &App,
2806 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2807 if self.linked_edit_ranges.is_empty() {
2808 return None;
2809 }
2810 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2811 selection.end.buffer_id.and_then(|end_buffer_id| {
2812 if selection.start.buffer_id != Some(end_buffer_id) {
2813 return None;
2814 }
2815 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2816 let snapshot = buffer.read(cx).snapshot();
2817 self.linked_edit_ranges
2818 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2819 .map(|ranges| (ranges, snapshot, buffer))
2820 })?;
2821 use text::ToOffset as TO;
2822 // find offset from the start of current range to current cursor position
2823 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2824
2825 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2826 let start_difference = start_offset - start_byte_offset;
2827 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2828 let end_difference = end_offset - start_byte_offset;
2829 // Current range has associated linked ranges.
2830 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2831 for range in linked_ranges.iter() {
2832 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2833 let end_offset = start_offset + end_difference;
2834 let start_offset = start_offset + start_difference;
2835 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2836 continue;
2837 }
2838 if self.selections.disjoint_anchor_ranges().any(|s| {
2839 if s.start.buffer_id != selection.start.buffer_id
2840 || s.end.buffer_id != selection.end.buffer_id
2841 {
2842 return false;
2843 }
2844 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2845 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2846 }) {
2847 continue;
2848 }
2849 let start = buffer_snapshot.anchor_after(start_offset);
2850 let end = buffer_snapshot.anchor_after(end_offset);
2851 linked_edits
2852 .entry(buffer.clone())
2853 .or_default()
2854 .push(start..end);
2855 }
2856 Some(linked_edits)
2857 }
2858
2859 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2860 let text: Arc<str> = text.into();
2861
2862 if self.read_only(cx) {
2863 return;
2864 }
2865
2866 let selections = self.selections.all_adjusted(cx);
2867 let mut bracket_inserted = false;
2868 let mut edits = Vec::new();
2869 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2870 let mut new_selections = Vec::with_capacity(selections.len());
2871 let mut new_autoclose_regions = Vec::new();
2872 let snapshot = self.buffer.read(cx).read(cx);
2873
2874 for (selection, autoclose_region) in
2875 self.selections_with_autoclose_regions(selections, &snapshot)
2876 {
2877 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2878 // Determine if the inserted text matches the opening or closing
2879 // bracket of any of this language's bracket pairs.
2880 let mut bracket_pair = None;
2881 let mut is_bracket_pair_start = false;
2882 let mut is_bracket_pair_end = false;
2883 if !text.is_empty() {
2884 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2885 // and they are removing the character that triggered IME popup.
2886 for (pair, enabled) in scope.brackets() {
2887 if !pair.close && !pair.surround {
2888 continue;
2889 }
2890
2891 if enabled && pair.start.ends_with(text.as_ref()) {
2892 let prefix_len = pair.start.len() - text.len();
2893 let preceding_text_matches_prefix = prefix_len == 0
2894 || (selection.start.column >= (prefix_len as u32)
2895 && snapshot.contains_str_at(
2896 Point::new(
2897 selection.start.row,
2898 selection.start.column - (prefix_len as u32),
2899 ),
2900 &pair.start[..prefix_len],
2901 ));
2902 if preceding_text_matches_prefix {
2903 bracket_pair = Some(pair.clone());
2904 is_bracket_pair_start = true;
2905 break;
2906 }
2907 }
2908 if pair.end.as_str() == text.as_ref() {
2909 bracket_pair = Some(pair.clone());
2910 is_bracket_pair_end = true;
2911 break;
2912 }
2913 }
2914 }
2915
2916 if let Some(bracket_pair) = bracket_pair {
2917 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
2918 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2919 let auto_surround =
2920 self.use_auto_surround && snapshot_settings.use_auto_surround;
2921 if selection.is_empty() {
2922 if is_bracket_pair_start {
2923 // If the inserted text is a suffix of an opening bracket and the
2924 // selection is preceded by the rest of the opening bracket, then
2925 // insert the closing bracket.
2926 let following_text_allows_autoclose = snapshot
2927 .chars_at(selection.start)
2928 .next()
2929 .map_or(true, |c| scope.should_autoclose_before(c));
2930
2931 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2932 && bracket_pair.start.len() == 1
2933 {
2934 let target = bracket_pair.start.chars().next().unwrap();
2935 let current_line_count = snapshot
2936 .reversed_chars_at(selection.start)
2937 .take_while(|&c| c != '\n')
2938 .filter(|&c| c == target)
2939 .count();
2940 current_line_count % 2 == 1
2941 } else {
2942 false
2943 };
2944
2945 if autoclose
2946 && bracket_pair.close
2947 && following_text_allows_autoclose
2948 && !is_closing_quote
2949 {
2950 let anchor = snapshot.anchor_before(selection.end);
2951 new_selections.push((selection.map(|_| anchor), text.len()));
2952 new_autoclose_regions.push((
2953 anchor,
2954 text.len(),
2955 selection.id,
2956 bracket_pair.clone(),
2957 ));
2958 edits.push((
2959 selection.range(),
2960 format!("{}{}", text, bracket_pair.end).into(),
2961 ));
2962 bracket_inserted = true;
2963 continue;
2964 }
2965 }
2966
2967 if let Some(region) = autoclose_region {
2968 // If the selection is followed by an auto-inserted closing bracket,
2969 // then don't insert that closing bracket again; just move the selection
2970 // past the closing bracket.
2971 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2972 && text.as_ref() == region.pair.end.as_str();
2973 if should_skip {
2974 let anchor = snapshot.anchor_after(selection.end);
2975 new_selections
2976 .push((selection.map(|_| anchor), region.pair.end.len()));
2977 continue;
2978 }
2979 }
2980
2981 let always_treat_brackets_as_autoclosed = snapshot
2982 .language_settings_at(selection.start, cx)
2983 .always_treat_brackets_as_autoclosed;
2984 if always_treat_brackets_as_autoclosed
2985 && is_bracket_pair_end
2986 && snapshot.contains_str_at(selection.end, text.as_ref())
2987 {
2988 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2989 // and the inserted text is a closing bracket and the selection is followed
2990 // by the closing bracket then move the selection past the closing bracket.
2991 let anchor = snapshot.anchor_after(selection.end);
2992 new_selections.push((selection.map(|_| anchor), text.len()));
2993 continue;
2994 }
2995 }
2996 // If an opening bracket is 1 character long and is typed while
2997 // text is selected, then surround that text with the bracket pair.
2998 else if auto_surround
2999 && bracket_pair.surround
3000 && is_bracket_pair_start
3001 && bracket_pair.start.chars().count() == 1
3002 {
3003 edits.push((selection.start..selection.start, text.clone()));
3004 edits.push((
3005 selection.end..selection.end,
3006 bracket_pair.end.as_str().into(),
3007 ));
3008 bracket_inserted = true;
3009 new_selections.push((
3010 Selection {
3011 id: selection.id,
3012 start: snapshot.anchor_after(selection.start),
3013 end: snapshot.anchor_before(selection.end),
3014 reversed: selection.reversed,
3015 goal: selection.goal,
3016 },
3017 0,
3018 ));
3019 continue;
3020 }
3021 }
3022 }
3023
3024 if self.auto_replace_emoji_shortcode
3025 && selection.is_empty()
3026 && text.as_ref().ends_with(':')
3027 {
3028 if let Some(possible_emoji_short_code) =
3029 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3030 {
3031 if !possible_emoji_short_code.is_empty() {
3032 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3033 let emoji_shortcode_start = Point::new(
3034 selection.start.row,
3035 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3036 );
3037
3038 // Remove shortcode from buffer
3039 edits.push((
3040 emoji_shortcode_start..selection.start,
3041 "".to_string().into(),
3042 ));
3043 new_selections.push((
3044 Selection {
3045 id: selection.id,
3046 start: snapshot.anchor_after(emoji_shortcode_start),
3047 end: snapshot.anchor_before(selection.start),
3048 reversed: selection.reversed,
3049 goal: selection.goal,
3050 },
3051 0,
3052 ));
3053
3054 // Insert emoji
3055 let selection_start_anchor = snapshot.anchor_after(selection.start);
3056 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3057 edits.push((selection.start..selection.end, emoji.to_string().into()));
3058
3059 continue;
3060 }
3061 }
3062 }
3063 }
3064
3065 // If not handling any auto-close operation, then just replace the selected
3066 // text with the given input and move the selection to the end of the
3067 // newly inserted text.
3068 let anchor = snapshot.anchor_after(selection.end);
3069 if !self.linked_edit_ranges.is_empty() {
3070 let start_anchor = snapshot.anchor_before(selection.start);
3071
3072 let is_word_char = text.chars().next().map_or(true, |char| {
3073 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3074 classifier.is_word(char)
3075 });
3076
3077 if is_word_char {
3078 if let Some(ranges) = self
3079 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3080 {
3081 for (buffer, edits) in ranges {
3082 linked_edits
3083 .entry(buffer.clone())
3084 .or_default()
3085 .extend(edits.into_iter().map(|range| (range, text.clone())));
3086 }
3087 }
3088 }
3089 }
3090
3091 new_selections.push((selection.map(|_| anchor), 0));
3092 edits.push((selection.start..selection.end, text.clone()));
3093 }
3094
3095 drop(snapshot);
3096
3097 self.transact(window, cx, |this, window, cx| {
3098 this.buffer.update(cx, |buffer, cx| {
3099 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3100 });
3101 for (buffer, edits) in linked_edits {
3102 buffer.update(cx, |buffer, cx| {
3103 let snapshot = buffer.snapshot();
3104 let edits = edits
3105 .into_iter()
3106 .map(|(range, text)| {
3107 use text::ToPoint as TP;
3108 let end_point = TP::to_point(&range.end, &snapshot);
3109 let start_point = TP::to_point(&range.start, &snapshot);
3110 (start_point..end_point, text)
3111 })
3112 .sorted_by_key(|(range, _)| range.start)
3113 .collect::<Vec<_>>();
3114 buffer.edit(edits, None, cx);
3115 })
3116 }
3117 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3118 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3119 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3120 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3121 .zip(new_selection_deltas)
3122 .map(|(selection, delta)| Selection {
3123 id: selection.id,
3124 start: selection.start + delta,
3125 end: selection.end + delta,
3126 reversed: selection.reversed,
3127 goal: SelectionGoal::None,
3128 })
3129 .collect::<Vec<_>>();
3130
3131 let mut i = 0;
3132 for (position, delta, selection_id, pair) in new_autoclose_regions {
3133 let position = position.to_offset(&map.buffer_snapshot) + delta;
3134 let start = map.buffer_snapshot.anchor_before(position);
3135 let end = map.buffer_snapshot.anchor_after(position);
3136 while let Some(existing_state) = this.autoclose_regions.get(i) {
3137 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3138 Ordering::Less => i += 1,
3139 Ordering::Greater => break,
3140 Ordering::Equal => {
3141 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3142 Ordering::Less => i += 1,
3143 Ordering::Equal => break,
3144 Ordering::Greater => break,
3145 }
3146 }
3147 }
3148 }
3149 this.autoclose_regions.insert(
3150 i,
3151 AutocloseRegion {
3152 selection_id,
3153 range: start..end,
3154 pair,
3155 },
3156 );
3157 }
3158
3159 let had_active_inline_completion = this.has_active_inline_completion();
3160 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3161 s.select(new_selections)
3162 });
3163
3164 if !bracket_inserted {
3165 if let Some(on_type_format_task) =
3166 this.trigger_on_type_formatting(text.to_string(), window, cx)
3167 {
3168 on_type_format_task.detach_and_log_err(cx);
3169 }
3170 }
3171
3172 let editor_settings = EditorSettings::get_global(cx);
3173 if bracket_inserted
3174 && (editor_settings.auto_signature_help
3175 || editor_settings.show_signature_help_after_edits)
3176 {
3177 this.show_signature_help(&ShowSignatureHelp, window, cx);
3178 }
3179
3180 let trigger_in_words =
3181 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3182 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3183 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3184 this.refresh_inline_completion(true, false, window, cx);
3185 });
3186 }
3187
3188 fn find_possible_emoji_shortcode_at_position(
3189 snapshot: &MultiBufferSnapshot,
3190 position: Point,
3191 ) -> Option<String> {
3192 let mut chars = Vec::new();
3193 let mut found_colon = false;
3194 for char in snapshot.reversed_chars_at(position).take(100) {
3195 // Found a possible emoji shortcode in the middle of the buffer
3196 if found_colon {
3197 if char.is_whitespace() {
3198 chars.reverse();
3199 return Some(chars.iter().collect());
3200 }
3201 // If the previous character is not a whitespace, we are in the middle of a word
3202 // and we only want to complete the shortcode if the word is made up of other emojis
3203 let mut containing_word = String::new();
3204 for ch in snapshot
3205 .reversed_chars_at(position)
3206 .skip(chars.len() + 1)
3207 .take(100)
3208 {
3209 if ch.is_whitespace() {
3210 break;
3211 }
3212 containing_word.push(ch);
3213 }
3214 let containing_word = containing_word.chars().rev().collect::<String>();
3215 if util::word_consists_of_emojis(containing_word.as_str()) {
3216 chars.reverse();
3217 return Some(chars.iter().collect());
3218 }
3219 }
3220
3221 if char.is_whitespace() || !char.is_ascii() {
3222 return None;
3223 }
3224 if char == ':' {
3225 found_colon = true;
3226 } else {
3227 chars.push(char);
3228 }
3229 }
3230 // Found a possible emoji shortcode at the beginning of the buffer
3231 chars.reverse();
3232 Some(chars.iter().collect())
3233 }
3234
3235 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3236 self.transact(window, cx, |this, window, cx| {
3237 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3238 let selections = this.selections.all::<usize>(cx);
3239 let multi_buffer = this.buffer.read(cx);
3240 let buffer = multi_buffer.snapshot(cx);
3241 selections
3242 .iter()
3243 .map(|selection| {
3244 let start_point = selection.start.to_point(&buffer);
3245 let mut indent =
3246 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3247 indent.len = cmp::min(indent.len, start_point.column);
3248 let start = selection.start;
3249 let end = selection.end;
3250 let selection_is_empty = start == end;
3251 let language_scope = buffer.language_scope_at(start);
3252 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3253 &language_scope
3254 {
3255 let insert_extra_newline =
3256 insert_extra_newline_brackets(&buffer, start..end, language)
3257 || insert_extra_newline_tree_sitter(&buffer, start..end);
3258
3259 // Comment extension on newline is allowed only for cursor selections
3260 let comment_delimiter = maybe!({
3261 if !selection_is_empty {
3262 return None;
3263 }
3264
3265 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3266 return None;
3267 }
3268
3269 let delimiters = language.line_comment_prefixes();
3270 let max_len_of_delimiter =
3271 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3272 let (snapshot, range) =
3273 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3274
3275 let mut index_of_first_non_whitespace = 0;
3276 let comment_candidate = snapshot
3277 .chars_for_range(range)
3278 .skip_while(|c| {
3279 let should_skip = c.is_whitespace();
3280 if should_skip {
3281 index_of_first_non_whitespace += 1;
3282 }
3283 should_skip
3284 })
3285 .take(max_len_of_delimiter)
3286 .collect::<String>();
3287 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3288 comment_candidate.starts_with(comment_prefix.as_ref())
3289 })?;
3290 let cursor_is_placed_after_comment_marker =
3291 index_of_first_non_whitespace + comment_prefix.len()
3292 <= start_point.column as usize;
3293 if cursor_is_placed_after_comment_marker {
3294 Some(comment_prefix.clone())
3295 } else {
3296 None
3297 }
3298 });
3299 (comment_delimiter, insert_extra_newline)
3300 } else {
3301 (None, false)
3302 };
3303
3304 let capacity_for_delimiter = comment_delimiter
3305 .as_deref()
3306 .map(str::len)
3307 .unwrap_or_default();
3308 let mut new_text =
3309 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3310 new_text.push('\n');
3311 new_text.extend(indent.chars());
3312 if let Some(delimiter) = &comment_delimiter {
3313 new_text.push_str(delimiter);
3314 }
3315 if insert_extra_newline {
3316 new_text = new_text.repeat(2);
3317 }
3318
3319 let anchor = buffer.anchor_after(end);
3320 let new_selection = selection.map(|_| anchor);
3321 (
3322 (start..end, new_text),
3323 (insert_extra_newline, new_selection),
3324 )
3325 })
3326 .unzip()
3327 };
3328
3329 this.edit_with_autoindent(edits, cx);
3330 let buffer = this.buffer.read(cx).snapshot(cx);
3331 let new_selections = selection_fixup_info
3332 .into_iter()
3333 .map(|(extra_newline_inserted, new_selection)| {
3334 let mut cursor = new_selection.end.to_point(&buffer);
3335 if extra_newline_inserted {
3336 cursor.row -= 1;
3337 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3338 }
3339 new_selection.map(|_| cursor)
3340 })
3341 .collect();
3342
3343 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3344 s.select(new_selections)
3345 });
3346 this.refresh_inline_completion(true, false, window, cx);
3347 });
3348 }
3349
3350 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3351 let buffer = self.buffer.read(cx);
3352 let snapshot = buffer.snapshot(cx);
3353
3354 let mut edits = Vec::new();
3355 let mut rows = Vec::new();
3356
3357 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3358 let cursor = selection.head();
3359 let row = cursor.row;
3360
3361 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3362
3363 let newline = "\n".to_string();
3364 edits.push((start_of_line..start_of_line, newline));
3365
3366 rows.push(row + rows_inserted as u32);
3367 }
3368
3369 self.transact(window, cx, |editor, window, cx| {
3370 editor.edit(edits, cx);
3371
3372 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3373 let mut index = 0;
3374 s.move_cursors_with(|map, _, _| {
3375 let row = rows[index];
3376 index += 1;
3377
3378 let point = Point::new(row, 0);
3379 let boundary = map.next_line_boundary(point).1;
3380 let clipped = map.clip_point(boundary, Bias::Left);
3381
3382 (clipped, SelectionGoal::None)
3383 });
3384 });
3385
3386 let mut indent_edits = Vec::new();
3387 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3388 for row in rows {
3389 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3390 for (row, indent) in indents {
3391 if indent.len == 0 {
3392 continue;
3393 }
3394
3395 let text = match indent.kind {
3396 IndentKind::Space => " ".repeat(indent.len as usize),
3397 IndentKind::Tab => "\t".repeat(indent.len as usize),
3398 };
3399 let point = Point::new(row.0, 0);
3400 indent_edits.push((point..point, text));
3401 }
3402 }
3403 editor.edit(indent_edits, cx);
3404 });
3405 }
3406
3407 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3408 let buffer = self.buffer.read(cx);
3409 let snapshot = buffer.snapshot(cx);
3410
3411 let mut edits = Vec::new();
3412 let mut rows = Vec::new();
3413 let mut rows_inserted = 0;
3414
3415 for selection in self.selections.all_adjusted(cx) {
3416 let cursor = selection.head();
3417 let row = cursor.row;
3418
3419 let point = Point::new(row + 1, 0);
3420 let start_of_line = snapshot.clip_point(point, Bias::Left);
3421
3422 let newline = "\n".to_string();
3423 edits.push((start_of_line..start_of_line, newline));
3424
3425 rows_inserted += 1;
3426 rows.push(row + rows_inserted);
3427 }
3428
3429 self.transact(window, cx, |editor, window, cx| {
3430 editor.edit(edits, cx);
3431
3432 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3433 let mut index = 0;
3434 s.move_cursors_with(|map, _, _| {
3435 let row = rows[index];
3436 index += 1;
3437
3438 let point = Point::new(row, 0);
3439 let boundary = map.next_line_boundary(point).1;
3440 let clipped = map.clip_point(boundary, Bias::Left);
3441
3442 (clipped, SelectionGoal::None)
3443 });
3444 });
3445
3446 let mut indent_edits = Vec::new();
3447 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3448 for row in rows {
3449 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3450 for (row, indent) in indents {
3451 if indent.len == 0 {
3452 continue;
3453 }
3454
3455 let text = match indent.kind {
3456 IndentKind::Space => " ".repeat(indent.len as usize),
3457 IndentKind::Tab => "\t".repeat(indent.len as usize),
3458 };
3459 let point = Point::new(row.0, 0);
3460 indent_edits.push((point..point, text));
3461 }
3462 }
3463 editor.edit(indent_edits, cx);
3464 });
3465 }
3466
3467 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3468 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3469 original_start_columns: Vec::new(),
3470 });
3471 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3472 }
3473
3474 fn insert_with_autoindent_mode(
3475 &mut self,
3476 text: &str,
3477 autoindent_mode: Option<AutoindentMode>,
3478 window: &mut Window,
3479 cx: &mut Context<Self>,
3480 ) {
3481 if self.read_only(cx) {
3482 return;
3483 }
3484
3485 let text: Arc<str> = text.into();
3486 self.transact(window, cx, |this, window, cx| {
3487 let old_selections = this.selections.all_adjusted(cx);
3488 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3489 let anchors = {
3490 let snapshot = buffer.read(cx);
3491 old_selections
3492 .iter()
3493 .map(|s| {
3494 let anchor = snapshot.anchor_after(s.head());
3495 s.map(|_| anchor)
3496 })
3497 .collect::<Vec<_>>()
3498 };
3499 buffer.edit(
3500 old_selections
3501 .iter()
3502 .map(|s| (s.start..s.end, text.clone())),
3503 autoindent_mode,
3504 cx,
3505 );
3506 anchors
3507 });
3508
3509 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3510 s.select_anchors(selection_anchors);
3511 });
3512
3513 cx.notify();
3514 });
3515 }
3516
3517 fn trigger_completion_on_input(
3518 &mut self,
3519 text: &str,
3520 trigger_in_words: bool,
3521 window: &mut Window,
3522 cx: &mut Context<Self>,
3523 ) {
3524 if self.is_completion_trigger(text, trigger_in_words, cx) {
3525 self.show_completions(
3526 &ShowCompletions {
3527 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3528 },
3529 window,
3530 cx,
3531 );
3532 } else {
3533 self.hide_context_menu(window, cx);
3534 }
3535 }
3536
3537 fn is_completion_trigger(
3538 &self,
3539 text: &str,
3540 trigger_in_words: bool,
3541 cx: &mut Context<Self>,
3542 ) -> bool {
3543 let position = self.selections.newest_anchor().head();
3544 let multibuffer = self.buffer.read(cx);
3545 let Some(buffer) = position
3546 .buffer_id
3547 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3548 else {
3549 return false;
3550 };
3551
3552 if let Some(completion_provider) = &self.completion_provider {
3553 completion_provider.is_completion_trigger(
3554 &buffer,
3555 position.text_anchor,
3556 text,
3557 trigger_in_words,
3558 cx,
3559 )
3560 } else {
3561 false
3562 }
3563 }
3564
3565 /// If any empty selections is touching the start of its innermost containing autoclose
3566 /// region, expand it to select the brackets.
3567 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3568 let selections = self.selections.all::<usize>(cx);
3569 let buffer = self.buffer.read(cx).read(cx);
3570 let new_selections = self
3571 .selections_with_autoclose_regions(selections, &buffer)
3572 .map(|(mut selection, region)| {
3573 if !selection.is_empty() {
3574 return selection;
3575 }
3576
3577 if let Some(region) = region {
3578 let mut range = region.range.to_offset(&buffer);
3579 if selection.start == range.start && range.start >= region.pair.start.len() {
3580 range.start -= region.pair.start.len();
3581 if buffer.contains_str_at(range.start, ®ion.pair.start)
3582 && buffer.contains_str_at(range.end, ®ion.pair.end)
3583 {
3584 range.end += region.pair.end.len();
3585 selection.start = range.start;
3586 selection.end = range.end;
3587
3588 return selection;
3589 }
3590 }
3591 }
3592
3593 let always_treat_brackets_as_autoclosed = buffer
3594 .language_settings_at(selection.start, cx)
3595 .always_treat_brackets_as_autoclosed;
3596
3597 if !always_treat_brackets_as_autoclosed {
3598 return selection;
3599 }
3600
3601 if let Some(scope) = buffer.language_scope_at(selection.start) {
3602 for (pair, enabled) in scope.brackets() {
3603 if !enabled || !pair.close {
3604 continue;
3605 }
3606
3607 if buffer.contains_str_at(selection.start, &pair.end) {
3608 let pair_start_len = pair.start.len();
3609 if buffer.contains_str_at(
3610 selection.start.saturating_sub(pair_start_len),
3611 &pair.start,
3612 ) {
3613 selection.start -= pair_start_len;
3614 selection.end += pair.end.len();
3615
3616 return selection;
3617 }
3618 }
3619 }
3620 }
3621
3622 selection
3623 })
3624 .collect();
3625
3626 drop(buffer);
3627 self.change_selections(None, window, cx, |selections| {
3628 selections.select(new_selections)
3629 });
3630 }
3631
3632 /// Iterate the given selections, and for each one, find the smallest surrounding
3633 /// autoclose region. This uses the ordering of the selections and the autoclose
3634 /// regions to avoid repeated comparisons.
3635 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3636 &'a self,
3637 selections: impl IntoIterator<Item = Selection<D>>,
3638 buffer: &'a MultiBufferSnapshot,
3639 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3640 let mut i = 0;
3641 let mut regions = self.autoclose_regions.as_slice();
3642 selections.into_iter().map(move |selection| {
3643 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3644
3645 let mut enclosing = None;
3646 while let Some(pair_state) = regions.get(i) {
3647 if pair_state.range.end.to_offset(buffer) < range.start {
3648 regions = ®ions[i + 1..];
3649 i = 0;
3650 } else if pair_state.range.start.to_offset(buffer) > range.end {
3651 break;
3652 } else {
3653 if pair_state.selection_id == selection.id {
3654 enclosing = Some(pair_state);
3655 }
3656 i += 1;
3657 }
3658 }
3659
3660 (selection, enclosing)
3661 })
3662 }
3663
3664 /// Remove any autoclose regions that no longer contain their selection.
3665 fn invalidate_autoclose_regions(
3666 &mut self,
3667 mut selections: &[Selection<Anchor>],
3668 buffer: &MultiBufferSnapshot,
3669 ) {
3670 self.autoclose_regions.retain(|state| {
3671 let mut i = 0;
3672 while let Some(selection) = selections.get(i) {
3673 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3674 selections = &selections[1..];
3675 continue;
3676 }
3677 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3678 break;
3679 }
3680 if selection.id == state.selection_id {
3681 return true;
3682 } else {
3683 i += 1;
3684 }
3685 }
3686 false
3687 });
3688 }
3689
3690 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3691 let offset = position.to_offset(buffer);
3692 let (word_range, kind) = buffer.surrounding_word(offset, true);
3693 if offset > word_range.start && kind == Some(CharKind::Word) {
3694 Some(
3695 buffer
3696 .text_for_range(word_range.start..offset)
3697 .collect::<String>(),
3698 )
3699 } else {
3700 None
3701 }
3702 }
3703
3704 pub fn toggle_inlay_hints(
3705 &mut self,
3706 _: &ToggleInlayHints,
3707 _: &mut Window,
3708 cx: &mut Context<Self>,
3709 ) {
3710 self.refresh_inlay_hints(
3711 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3712 cx,
3713 );
3714 }
3715
3716 pub fn inlay_hints_enabled(&self) -> bool {
3717 self.inlay_hint_cache.enabled
3718 }
3719
3720 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3721 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3722 return;
3723 }
3724
3725 let reason_description = reason.description();
3726 let ignore_debounce = matches!(
3727 reason,
3728 InlayHintRefreshReason::SettingsChange(_)
3729 | InlayHintRefreshReason::Toggle(_)
3730 | InlayHintRefreshReason::ExcerptsRemoved(_)
3731 | InlayHintRefreshReason::ModifiersChanged(_)
3732 );
3733 let (invalidate_cache, required_languages) = match reason {
3734 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3735 match self.inlay_hint_cache.modifiers_override(enabled) {
3736 Some(enabled) => {
3737 if enabled {
3738 (InvalidationStrategy::RefreshRequested, None)
3739 } else {
3740 self.splice_inlays(
3741 &self
3742 .visible_inlay_hints(cx)
3743 .iter()
3744 .map(|inlay| inlay.id)
3745 .collect::<Vec<InlayId>>(),
3746 Vec::new(),
3747 cx,
3748 );
3749 return;
3750 }
3751 }
3752 None => return,
3753 }
3754 }
3755 InlayHintRefreshReason::Toggle(enabled) => {
3756 if self.inlay_hint_cache.toggle(enabled) {
3757 if enabled {
3758 (InvalidationStrategy::RefreshRequested, None)
3759 } else {
3760 self.splice_inlays(
3761 &self
3762 .visible_inlay_hints(cx)
3763 .iter()
3764 .map(|inlay| inlay.id)
3765 .collect::<Vec<InlayId>>(),
3766 Vec::new(),
3767 cx,
3768 );
3769 return;
3770 }
3771 } else {
3772 return;
3773 }
3774 }
3775 InlayHintRefreshReason::SettingsChange(new_settings) => {
3776 match self.inlay_hint_cache.update_settings(
3777 &self.buffer,
3778 new_settings,
3779 self.visible_inlay_hints(cx),
3780 cx,
3781 ) {
3782 ControlFlow::Break(Some(InlaySplice {
3783 to_remove,
3784 to_insert,
3785 })) => {
3786 self.splice_inlays(&to_remove, to_insert, cx);
3787 return;
3788 }
3789 ControlFlow::Break(None) => return,
3790 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3791 }
3792 }
3793 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3794 if let Some(InlaySplice {
3795 to_remove,
3796 to_insert,
3797 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3798 {
3799 self.splice_inlays(&to_remove, to_insert, cx);
3800 }
3801 return;
3802 }
3803 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3804 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3805 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3806 }
3807 InlayHintRefreshReason::RefreshRequested => {
3808 (InvalidationStrategy::RefreshRequested, None)
3809 }
3810 };
3811
3812 if let Some(InlaySplice {
3813 to_remove,
3814 to_insert,
3815 }) = self.inlay_hint_cache.spawn_hint_refresh(
3816 reason_description,
3817 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3818 invalidate_cache,
3819 ignore_debounce,
3820 cx,
3821 ) {
3822 self.splice_inlays(&to_remove, to_insert, cx);
3823 }
3824 }
3825
3826 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3827 self.display_map
3828 .read(cx)
3829 .current_inlays()
3830 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3831 .cloned()
3832 .collect()
3833 }
3834
3835 pub fn excerpts_for_inlay_hints_query(
3836 &self,
3837 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3838 cx: &mut Context<Editor>,
3839 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3840 let Some(project) = self.project.as_ref() else {
3841 return HashMap::default();
3842 };
3843 let project = project.read(cx);
3844 let multi_buffer = self.buffer().read(cx);
3845 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3846 let multi_buffer_visible_start = self
3847 .scroll_manager
3848 .anchor()
3849 .anchor
3850 .to_point(&multi_buffer_snapshot);
3851 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3852 multi_buffer_visible_start
3853 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3854 Bias::Left,
3855 );
3856 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3857 multi_buffer_snapshot
3858 .range_to_buffer_ranges(multi_buffer_visible_range)
3859 .into_iter()
3860 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3861 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3862 let buffer_file = project::File::from_dyn(buffer.file())?;
3863 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3864 let worktree_entry = buffer_worktree
3865 .read(cx)
3866 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3867 if worktree_entry.is_ignored {
3868 return None;
3869 }
3870
3871 let language = buffer.language()?;
3872 if let Some(restrict_to_languages) = restrict_to_languages {
3873 if !restrict_to_languages.contains(language) {
3874 return None;
3875 }
3876 }
3877 Some((
3878 excerpt_id,
3879 (
3880 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3881 buffer.version().clone(),
3882 excerpt_visible_range,
3883 ),
3884 ))
3885 })
3886 .collect()
3887 }
3888
3889 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3890 TextLayoutDetails {
3891 text_system: window.text_system().clone(),
3892 editor_style: self.style.clone().unwrap(),
3893 rem_size: window.rem_size(),
3894 scroll_anchor: self.scroll_manager.anchor(),
3895 visible_rows: self.visible_line_count(),
3896 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3897 }
3898 }
3899
3900 pub fn splice_inlays(
3901 &self,
3902 to_remove: &[InlayId],
3903 to_insert: Vec<Inlay>,
3904 cx: &mut Context<Self>,
3905 ) {
3906 self.display_map.update(cx, |display_map, cx| {
3907 display_map.splice_inlays(to_remove, to_insert, cx)
3908 });
3909 cx.notify();
3910 }
3911
3912 fn trigger_on_type_formatting(
3913 &self,
3914 input: String,
3915 window: &mut Window,
3916 cx: &mut Context<Self>,
3917 ) -> Option<Task<Result<()>>> {
3918 if input.len() != 1 {
3919 return None;
3920 }
3921
3922 let project = self.project.as_ref()?;
3923 let position = self.selections.newest_anchor().head();
3924 let (buffer, buffer_position) = self
3925 .buffer
3926 .read(cx)
3927 .text_anchor_for_position(position, cx)?;
3928
3929 let settings = language_settings::language_settings(
3930 buffer
3931 .read(cx)
3932 .language_at(buffer_position)
3933 .map(|l| l.name()),
3934 buffer.read(cx).file(),
3935 cx,
3936 );
3937 if !settings.use_on_type_format {
3938 return None;
3939 }
3940
3941 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3942 // hence we do LSP request & edit on host side only — add formats to host's history.
3943 let push_to_lsp_host_history = true;
3944 // If this is not the host, append its history with new edits.
3945 let push_to_client_history = project.read(cx).is_via_collab();
3946
3947 let on_type_formatting = project.update(cx, |project, cx| {
3948 project.on_type_format(
3949 buffer.clone(),
3950 buffer_position,
3951 input,
3952 push_to_lsp_host_history,
3953 cx,
3954 )
3955 });
3956 Some(cx.spawn_in(window, |editor, mut cx| async move {
3957 if let Some(transaction) = on_type_formatting.await? {
3958 if push_to_client_history {
3959 buffer
3960 .update(&mut cx, |buffer, _| {
3961 buffer.push_transaction(transaction, Instant::now());
3962 })
3963 .ok();
3964 }
3965 editor.update(&mut cx, |editor, cx| {
3966 editor.refresh_document_highlights(cx);
3967 })?;
3968 }
3969 Ok(())
3970 }))
3971 }
3972
3973 pub fn show_completions(
3974 &mut self,
3975 options: &ShowCompletions,
3976 window: &mut Window,
3977 cx: &mut Context<Self>,
3978 ) {
3979 if self.pending_rename.is_some() {
3980 return;
3981 }
3982
3983 let Some(provider) = self.completion_provider.as_ref() else {
3984 return;
3985 };
3986
3987 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3988 return;
3989 }
3990
3991 let position = self.selections.newest_anchor().head();
3992 if position.diff_base_anchor.is_some() {
3993 return;
3994 }
3995 let (buffer, buffer_position) =
3996 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3997 output
3998 } else {
3999 return;
4000 };
4001 let show_completion_documentation = buffer
4002 .read(cx)
4003 .snapshot()
4004 .settings_at(buffer_position, cx)
4005 .show_completion_documentation;
4006
4007 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4008
4009 let trigger_kind = match &options.trigger {
4010 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4011 CompletionTriggerKind::TRIGGER_CHARACTER
4012 }
4013 _ => CompletionTriggerKind::INVOKED,
4014 };
4015 let completion_context = CompletionContext {
4016 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4017 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4018 Some(String::from(trigger))
4019 } else {
4020 None
4021 }
4022 }),
4023 trigger_kind,
4024 };
4025 let completions =
4026 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4027 let sort_completions = provider.sort_completions();
4028
4029 let id = post_inc(&mut self.next_completion_id);
4030 let task = cx.spawn_in(window, |editor, mut cx| {
4031 async move {
4032 editor.update(&mut cx, |this, _| {
4033 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4034 })?;
4035 let completions = completions.await.log_err();
4036 let menu = if let Some(completions) = completions {
4037 let mut menu = CompletionsMenu::new(
4038 id,
4039 sort_completions,
4040 show_completion_documentation,
4041 position,
4042 buffer.clone(),
4043 completions.into(),
4044 );
4045
4046 menu.filter(query.as_deref(), cx.background_executor().clone())
4047 .await;
4048
4049 menu.visible().then_some(menu)
4050 } else {
4051 None
4052 };
4053
4054 editor.update_in(&mut cx, |editor, window, cx| {
4055 match editor.context_menu.borrow().as_ref() {
4056 None => {}
4057 Some(CodeContextMenu::Completions(prev_menu)) => {
4058 if prev_menu.id > id {
4059 return;
4060 }
4061 }
4062 _ => return,
4063 }
4064
4065 if editor.focus_handle.is_focused(window) && menu.is_some() {
4066 let mut menu = menu.unwrap();
4067 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4068
4069 *editor.context_menu.borrow_mut() =
4070 Some(CodeContextMenu::Completions(menu));
4071
4072 if editor.show_edit_predictions_in_menu() {
4073 editor.update_visible_inline_completion(window, cx);
4074 } else {
4075 editor.discard_inline_completion(false, cx);
4076 }
4077
4078 cx.notify();
4079 } else if editor.completion_tasks.len() <= 1 {
4080 // If there are no more completion tasks and the last menu was
4081 // empty, we should hide it.
4082 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4083 // If it was already hidden and we don't show inline
4084 // completions in the menu, we should also show the
4085 // inline-completion when available.
4086 if was_hidden && editor.show_edit_predictions_in_menu() {
4087 editor.update_visible_inline_completion(window, cx);
4088 }
4089 }
4090 })?;
4091
4092 Ok::<_, anyhow::Error>(())
4093 }
4094 .log_err()
4095 });
4096
4097 self.completion_tasks.push((id, task));
4098 }
4099
4100 pub fn confirm_completion(
4101 &mut self,
4102 action: &ConfirmCompletion,
4103 window: &mut Window,
4104 cx: &mut Context<Self>,
4105 ) -> Option<Task<Result<()>>> {
4106 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4107 }
4108
4109 pub fn compose_completion(
4110 &mut self,
4111 action: &ComposeCompletion,
4112 window: &mut Window,
4113 cx: &mut Context<Self>,
4114 ) -> Option<Task<Result<()>>> {
4115 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4116 }
4117
4118 fn do_completion(
4119 &mut self,
4120 item_ix: Option<usize>,
4121 intent: CompletionIntent,
4122 window: &mut Window,
4123 cx: &mut Context<Editor>,
4124 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4125 use language::ToOffset as _;
4126
4127 let completions_menu =
4128 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4129 menu
4130 } else {
4131 return None;
4132 };
4133
4134 let entries = completions_menu.entries.borrow();
4135 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4136 if self.show_edit_predictions_in_menu() {
4137 self.discard_inline_completion(true, cx);
4138 }
4139 let candidate_id = mat.candidate_id;
4140 drop(entries);
4141
4142 let buffer_handle = completions_menu.buffer;
4143 let completion = completions_menu
4144 .completions
4145 .borrow()
4146 .get(candidate_id)?
4147 .clone();
4148 cx.stop_propagation();
4149
4150 let snippet;
4151 let text;
4152
4153 if completion.is_snippet() {
4154 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4155 text = snippet.as_ref().unwrap().text.clone();
4156 } else {
4157 snippet = None;
4158 text = completion.new_text.clone();
4159 };
4160 let selections = self.selections.all::<usize>(cx);
4161 let buffer = buffer_handle.read(cx);
4162 let old_range = completion.old_range.to_offset(buffer);
4163 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4164
4165 let newest_selection = self.selections.newest_anchor();
4166 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4167 return None;
4168 }
4169
4170 let lookbehind = newest_selection
4171 .start
4172 .text_anchor
4173 .to_offset(buffer)
4174 .saturating_sub(old_range.start);
4175 let lookahead = old_range
4176 .end
4177 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4178 let mut common_prefix_len = old_text
4179 .bytes()
4180 .zip(text.bytes())
4181 .take_while(|(a, b)| a == b)
4182 .count();
4183
4184 let snapshot = self.buffer.read(cx).snapshot(cx);
4185 let mut range_to_replace: Option<Range<isize>> = None;
4186 let mut ranges = Vec::new();
4187 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4188 for selection in &selections {
4189 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4190 let start = selection.start.saturating_sub(lookbehind);
4191 let end = selection.end + lookahead;
4192 if selection.id == newest_selection.id {
4193 range_to_replace = Some(
4194 ((start + common_prefix_len) as isize - selection.start as isize)
4195 ..(end as isize - selection.start as isize),
4196 );
4197 }
4198 ranges.push(start + common_prefix_len..end);
4199 } else {
4200 common_prefix_len = 0;
4201 ranges.clear();
4202 ranges.extend(selections.iter().map(|s| {
4203 if s.id == newest_selection.id {
4204 range_to_replace = Some(
4205 old_range.start.to_offset_utf16(&snapshot).0 as isize
4206 - selection.start as isize
4207 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4208 - selection.start as isize,
4209 );
4210 old_range.clone()
4211 } else {
4212 s.start..s.end
4213 }
4214 }));
4215 break;
4216 }
4217 if !self.linked_edit_ranges.is_empty() {
4218 let start_anchor = snapshot.anchor_before(selection.head());
4219 let end_anchor = snapshot.anchor_after(selection.tail());
4220 if let Some(ranges) = self
4221 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4222 {
4223 for (buffer, edits) in ranges {
4224 linked_edits.entry(buffer.clone()).or_default().extend(
4225 edits
4226 .into_iter()
4227 .map(|range| (range, text[common_prefix_len..].to_owned())),
4228 );
4229 }
4230 }
4231 }
4232 }
4233 let text = &text[common_prefix_len..];
4234
4235 cx.emit(EditorEvent::InputHandled {
4236 utf16_range_to_replace: range_to_replace,
4237 text: text.into(),
4238 });
4239
4240 self.transact(window, cx, |this, window, cx| {
4241 if let Some(mut snippet) = snippet {
4242 snippet.text = text.to_string();
4243 for tabstop in snippet
4244 .tabstops
4245 .iter_mut()
4246 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4247 {
4248 tabstop.start -= common_prefix_len as isize;
4249 tabstop.end -= common_prefix_len as isize;
4250 }
4251
4252 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4253 } else {
4254 this.buffer.update(cx, |buffer, cx| {
4255 buffer.edit(
4256 ranges.iter().map(|range| (range.clone(), text)),
4257 this.autoindent_mode.clone(),
4258 cx,
4259 );
4260 });
4261 }
4262 for (buffer, edits) in linked_edits {
4263 buffer.update(cx, |buffer, cx| {
4264 let snapshot = buffer.snapshot();
4265 let edits = edits
4266 .into_iter()
4267 .map(|(range, text)| {
4268 use text::ToPoint as TP;
4269 let end_point = TP::to_point(&range.end, &snapshot);
4270 let start_point = TP::to_point(&range.start, &snapshot);
4271 (start_point..end_point, text)
4272 })
4273 .sorted_by_key(|(range, _)| range.start)
4274 .collect::<Vec<_>>();
4275 buffer.edit(edits, None, cx);
4276 })
4277 }
4278
4279 this.refresh_inline_completion(true, false, window, cx);
4280 });
4281
4282 let show_new_completions_on_confirm = completion
4283 .confirm
4284 .as_ref()
4285 .map_or(false, |confirm| confirm(intent, window, cx));
4286 if show_new_completions_on_confirm {
4287 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4288 }
4289
4290 let provider = self.completion_provider.as_ref()?;
4291 drop(completion);
4292 let apply_edits = provider.apply_additional_edits_for_completion(
4293 buffer_handle,
4294 completions_menu.completions.clone(),
4295 candidate_id,
4296 true,
4297 cx,
4298 );
4299
4300 let editor_settings = EditorSettings::get_global(cx);
4301 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4302 // After the code completion is finished, users often want to know what signatures are needed.
4303 // so we should automatically call signature_help
4304 self.show_signature_help(&ShowSignatureHelp, window, cx);
4305 }
4306
4307 Some(cx.foreground_executor().spawn(async move {
4308 apply_edits.await?;
4309 Ok(())
4310 }))
4311 }
4312
4313 pub fn toggle_code_actions(
4314 &mut self,
4315 action: &ToggleCodeActions,
4316 window: &mut Window,
4317 cx: &mut Context<Self>,
4318 ) {
4319 let mut context_menu = self.context_menu.borrow_mut();
4320 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4321 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4322 // Toggle if we're selecting the same one
4323 *context_menu = None;
4324 cx.notify();
4325 return;
4326 } else {
4327 // Otherwise, clear it and start a new one
4328 *context_menu = None;
4329 cx.notify();
4330 }
4331 }
4332 drop(context_menu);
4333 let snapshot = self.snapshot(window, cx);
4334 let deployed_from_indicator = action.deployed_from_indicator;
4335 let mut task = self.code_actions_task.take();
4336 let action = action.clone();
4337 cx.spawn_in(window, |editor, mut cx| async move {
4338 while let Some(prev_task) = task {
4339 prev_task.await.log_err();
4340 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4341 }
4342
4343 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4344 if editor.focus_handle.is_focused(window) {
4345 let multibuffer_point = action
4346 .deployed_from_indicator
4347 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4348 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4349 let (buffer, buffer_row) = snapshot
4350 .buffer_snapshot
4351 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4352 .and_then(|(buffer_snapshot, range)| {
4353 editor
4354 .buffer
4355 .read(cx)
4356 .buffer(buffer_snapshot.remote_id())
4357 .map(|buffer| (buffer, range.start.row))
4358 })?;
4359 let (_, code_actions) = editor
4360 .available_code_actions
4361 .clone()
4362 .and_then(|(location, code_actions)| {
4363 let snapshot = location.buffer.read(cx).snapshot();
4364 let point_range = location.range.to_point(&snapshot);
4365 let point_range = point_range.start.row..=point_range.end.row;
4366 if point_range.contains(&buffer_row) {
4367 Some((location, code_actions))
4368 } else {
4369 None
4370 }
4371 })
4372 .unzip();
4373 let buffer_id = buffer.read(cx).remote_id();
4374 let tasks = editor
4375 .tasks
4376 .get(&(buffer_id, buffer_row))
4377 .map(|t| Arc::new(t.to_owned()));
4378 if tasks.is_none() && code_actions.is_none() {
4379 return None;
4380 }
4381
4382 editor.completion_tasks.clear();
4383 editor.discard_inline_completion(false, cx);
4384 let task_context =
4385 tasks
4386 .as_ref()
4387 .zip(editor.project.clone())
4388 .map(|(tasks, project)| {
4389 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4390 });
4391
4392 Some(cx.spawn_in(window, |editor, mut cx| async move {
4393 let task_context = match task_context {
4394 Some(task_context) => task_context.await,
4395 None => None,
4396 };
4397 let resolved_tasks =
4398 tasks.zip(task_context).map(|(tasks, task_context)| {
4399 Rc::new(ResolvedTasks {
4400 templates: tasks.resolve(&task_context).collect(),
4401 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4402 multibuffer_point.row,
4403 tasks.column,
4404 )),
4405 })
4406 });
4407 let spawn_straight_away = resolved_tasks
4408 .as_ref()
4409 .map_or(false, |tasks| tasks.templates.len() == 1)
4410 && code_actions
4411 .as_ref()
4412 .map_or(true, |actions| actions.is_empty());
4413 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4414 *editor.context_menu.borrow_mut() =
4415 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4416 buffer,
4417 actions: CodeActionContents {
4418 tasks: resolved_tasks,
4419 actions: code_actions,
4420 },
4421 selected_item: Default::default(),
4422 scroll_handle: UniformListScrollHandle::default(),
4423 deployed_from_indicator,
4424 }));
4425 if spawn_straight_away {
4426 if let Some(task) = editor.confirm_code_action(
4427 &ConfirmCodeAction { item_ix: Some(0) },
4428 window,
4429 cx,
4430 ) {
4431 cx.notify();
4432 return task;
4433 }
4434 }
4435 cx.notify();
4436 Task::ready(Ok(()))
4437 }) {
4438 task.await
4439 } else {
4440 Ok(())
4441 }
4442 }))
4443 } else {
4444 Some(Task::ready(Ok(())))
4445 }
4446 })?;
4447 if let Some(task) = spawned_test_task {
4448 task.await?;
4449 }
4450
4451 Ok::<_, anyhow::Error>(())
4452 })
4453 .detach_and_log_err(cx);
4454 }
4455
4456 pub fn confirm_code_action(
4457 &mut self,
4458 action: &ConfirmCodeAction,
4459 window: &mut Window,
4460 cx: &mut Context<Self>,
4461 ) -> Option<Task<Result<()>>> {
4462 let actions_menu =
4463 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4464 menu
4465 } else {
4466 return None;
4467 };
4468 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4469 let action = actions_menu.actions.get(action_ix)?;
4470 let title = action.label();
4471 let buffer = actions_menu.buffer;
4472 let workspace = self.workspace()?;
4473
4474 match action {
4475 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4476 workspace.update(cx, |workspace, cx| {
4477 workspace::tasks::schedule_resolved_task(
4478 workspace,
4479 task_source_kind,
4480 resolved_task,
4481 false,
4482 cx,
4483 );
4484
4485 Some(Task::ready(Ok(())))
4486 })
4487 }
4488 CodeActionsItem::CodeAction {
4489 excerpt_id,
4490 action,
4491 provider,
4492 } => {
4493 let apply_code_action =
4494 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4495 let workspace = workspace.downgrade();
4496 Some(cx.spawn_in(window, |editor, cx| async move {
4497 let project_transaction = apply_code_action.await?;
4498 Self::open_project_transaction(
4499 &editor,
4500 workspace,
4501 project_transaction,
4502 title,
4503 cx,
4504 )
4505 .await
4506 }))
4507 }
4508 }
4509 }
4510
4511 pub async fn open_project_transaction(
4512 this: &WeakEntity<Editor>,
4513 workspace: WeakEntity<Workspace>,
4514 transaction: ProjectTransaction,
4515 title: String,
4516 mut cx: AsyncWindowContext,
4517 ) -> Result<()> {
4518 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4519 cx.update(|_, cx| {
4520 entries.sort_unstable_by_key(|(buffer, _)| {
4521 buffer.read(cx).file().map(|f| f.path().clone())
4522 });
4523 })?;
4524
4525 // If the project transaction's edits are all contained within this editor, then
4526 // avoid opening a new editor to display them.
4527
4528 if let Some((buffer, transaction)) = entries.first() {
4529 if entries.len() == 1 {
4530 let excerpt = this.update(&mut cx, |editor, cx| {
4531 editor
4532 .buffer()
4533 .read(cx)
4534 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4535 })?;
4536 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4537 if excerpted_buffer == *buffer {
4538 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4539 let excerpt_range = excerpt_range.to_offset(buffer);
4540 buffer
4541 .edited_ranges_for_transaction::<usize>(transaction)
4542 .all(|range| {
4543 excerpt_range.start <= range.start
4544 && excerpt_range.end >= range.end
4545 })
4546 })?;
4547
4548 if all_edits_within_excerpt {
4549 return Ok(());
4550 }
4551 }
4552 }
4553 }
4554 } else {
4555 return Ok(());
4556 }
4557
4558 let mut ranges_to_highlight = Vec::new();
4559 let excerpt_buffer = cx.new(|cx| {
4560 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4561 for (buffer_handle, transaction) in &entries {
4562 let buffer = buffer_handle.read(cx);
4563 ranges_to_highlight.extend(
4564 multibuffer.push_excerpts_with_context_lines(
4565 buffer_handle.clone(),
4566 buffer
4567 .edited_ranges_for_transaction::<usize>(transaction)
4568 .collect(),
4569 DEFAULT_MULTIBUFFER_CONTEXT,
4570 cx,
4571 ),
4572 );
4573 }
4574 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4575 multibuffer
4576 })?;
4577
4578 workspace.update_in(&mut cx, |workspace, window, cx| {
4579 let project = workspace.project().clone();
4580 let editor = cx
4581 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4582 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4583 editor.update(cx, |editor, cx| {
4584 editor.highlight_background::<Self>(
4585 &ranges_to_highlight,
4586 |theme| theme.editor_highlighted_line_background,
4587 cx,
4588 );
4589 });
4590 })?;
4591
4592 Ok(())
4593 }
4594
4595 pub fn clear_code_action_providers(&mut self) {
4596 self.code_action_providers.clear();
4597 self.available_code_actions.take();
4598 }
4599
4600 pub fn add_code_action_provider(
4601 &mut self,
4602 provider: Rc<dyn CodeActionProvider>,
4603 window: &mut Window,
4604 cx: &mut Context<Self>,
4605 ) {
4606 if self
4607 .code_action_providers
4608 .iter()
4609 .any(|existing_provider| existing_provider.id() == provider.id())
4610 {
4611 return;
4612 }
4613
4614 self.code_action_providers.push(provider);
4615 self.refresh_code_actions(window, cx);
4616 }
4617
4618 pub fn remove_code_action_provider(
4619 &mut self,
4620 id: Arc<str>,
4621 window: &mut Window,
4622 cx: &mut Context<Self>,
4623 ) {
4624 self.code_action_providers
4625 .retain(|provider| provider.id() != id);
4626 self.refresh_code_actions(window, cx);
4627 }
4628
4629 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4630 let buffer = self.buffer.read(cx);
4631 let newest_selection = self.selections.newest_anchor().clone();
4632 if newest_selection.head().diff_base_anchor.is_some() {
4633 return None;
4634 }
4635 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4636 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4637 if start_buffer != end_buffer {
4638 return None;
4639 }
4640
4641 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4642 cx.background_executor()
4643 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4644 .await;
4645
4646 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4647 let providers = this.code_action_providers.clone();
4648 let tasks = this
4649 .code_action_providers
4650 .iter()
4651 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4652 .collect::<Vec<_>>();
4653 (providers, tasks)
4654 })?;
4655
4656 let mut actions = Vec::new();
4657 for (provider, provider_actions) in
4658 providers.into_iter().zip(future::join_all(tasks).await)
4659 {
4660 if let Some(provider_actions) = provider_actions.log_err() {
4661 actions.extend(provider_actions.into_iter().map(|action| {
4662 AvailableCodeAction {
4663 excerpt_id: newest_selection.start.excerpt_id,
4664 action,
4665 provider: provider.clone(),
4666 }
4667 }));
4668 }
4669 }
4670
4671 this.update(&mut cx, |this, cx| {
4672 this.available_code_actions = if actions.is_empty() {
4673 None
4674 } else {
4675 Some((
4676 Location {
4677 buffer: start_buffer,
4678 range: start..end,
4679 },
4680 actions.into(),
4681 ))
4682 };
4683 cx.notify();
4684 })
4685 }));
4686 None
4687 }
4688
4689 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4690 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4691 self.show_git_blame_inline = false;
4692
4693 self.show_git_blame_inline_delay_task =
4694 Some(cx.spawn_in(window, |this, mut cx| async move {
4695 cx.background_executor().timer(delay).await;
4696
4697 this.update(&mut cx, |this, cx| {
4698 this.show_git_blame_inline = true;
4699 cx.notify();
4700 })
4701 .log_err();
4702 }));
4703 }
4704 }
4705
4706 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4707 if self.pending_rename.is_some() {
4708 return None;
4709 }
4710
4711 let provider = self.semantics_provider.clone()?;
4712 let buffer = self.buffer.read(cx);
4713 let newest_selection = self.selections.newest_anchor().clone();
4714 let cursor_position = newest_selection.head();
4715 let (cursor_buffer, cursor_buffer_position) =
4716 buffer.text_anchor_for_position(cursor_position, cx)?;
4717 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4718 if cursor_buffer != tail_buffer {
4719 return None;
4720 }
4721 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4722 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4723 cx.background_executor()
4724 .timer(Duration::from_millis(debounce))
4725 .await;
4726
4727 let highlights = if let Some(highlights) = cx
4728 .update(|cx| {
4729 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4730 })
4731 .ok()
4732 .flatten()
4733 {
4734 highlights.await.log_err()
4735 } else {
4736 None
4737 };
4738
4739 if let Some(highlights) = highlights {
4740 this.update(&mut cx, |this, cx| {
4741 if this.pending_rename.is_some() {
4742 return;
4743 }
4744
4745 let buffer_id = cursor_position.buffer_id;
4746 let buffer = this.buffer.read(cx);
4747 if !buffer
4748 .text_anchor_for_position(cursor_position, cx)
4749 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4750 {
4751 return;
4752 }
4753
4754 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4755 let mut write_ranges = Vec::new();
4756 let mut read_ranges = Vec::new();
4757 for highlight in highlights {
4758 for (excerpt_id, excerpt_range) in
4759 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4760 {
4761 let start = highlight
4762 .range
4763 .start
4764 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4765 let end = highlight
4766 .range
4767 .end
4768 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4769 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4770 continue;
4771 }
4772
4773 let range = Anchor {
4774 buffer_id,
4775 excerpt_id,
4776 text_anchor: start,
4777 diff_base_anchor: None,
4778 }..Anchor {
4779 buffer_id,
4780 excerpt_id,
4781 text_anchor: end,
4782 diff_base_anchor: None,
4783 };
4784 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4785 write_ranges.push(range);
4786 } else {
4787 read_ranges.push(range);
4788 }
4789 }
4790 }
4791
4792 this.highlight_background::<DocumentHighlightRead>(
4793 &read_ranges,
4794 |theme| theme.editor_document_highlight_read_background,
4795 cx,
4796 );
4797 this.highlight_background::<DocumentHighlightWrite>(
4798 &write_ranges,
4799 |theme| theme.editor_document_highlight_write_background,
4800 cx,
4801 );
4802 cx.notify();
4803 })
4804 .log_err();
4805 }
4806 }));
4807 None
4808 }
4809
4810 pub fn refresh_selected_text_highlights(
4811 &mut self,
4812 window: &mut Window,
4813 cx: &mut Context<Editor>,
4814 ) {
4815 self.selection_highlight_task.take();
4816 if !EditorSettings::get_global(cx).selection_highlight {
4817 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4818 return;
4819 }
4820 if self.selections.count() != 1 || self.selections.line_mode {
4821 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4822 return;
4823 }
4824 let selection = self.selections.newest::<Point>(cx);
4825 if selection.is_empty() || selection.start.row != selection.end.row {
4826 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4827 return;
4828 }
4829 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4830 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4831 cx.background_executor()
4832 .timer(Duration::from_millis(debounce))
4833 .await;
4834 let Some(Some(matches_task)) = editor
4835 .update_in(&mut cx, |editor, _, cx| {
4836 if editor.selections.count() != 1 || editor.selections.line_mode {
4837 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4838 return None;
4839 }
4840 let selection = editor.selections.newest::<Point>(cx);
4841 if selection.is_empty() || selection.start.row != selection.end.row {
4842 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4843 return None;
4844 }
4845 let buffer = editor.buffer().read(cx).snapshot(cx);
4846 let query = buffer.text_for_range(selection.range()).collect::<String>();
4847 if query.trim().is_empty() {
4848 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4849 return None;
4850 }
4851 Some(cx.background_spawn(async move {
4852 let mut ranges = Vec::new();
4853 let selection_anchors = selection.range().to_anchors(&buffer);
4854 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4855 for (search_buffer, search_range, excerpt_id) in
4856 buffer.range_to_buffer_ranges(range)
4857 {
4858 ranges.extend(
4859 project::search::SearchQuery::text(
4860 query.clone(),
4861 false,
4862 false,
4863 false,
4864 Default::default(),
4865 Default::default(),
4866 None,
4867 )
4868 .unwrap()
4869 .search(search_buffer, Some(search_range.clone()))
4870 .await
4871 .into_iter()
4872 .filter_map(
4873 |match_range| {
4874 let start = search_buffer.anchor_after(
4875 search_range.start + match_range.start,
4876 );
4877 let end = search_buffer.anchor_before(
4878 search_range.start + match_range.end,
4879 );
4880 let range = Anchor::range_in_buffer(
4881 excerpt_id,
4882 search_buffer.remote_id(),
4883 start..end,
4884 );
4885 (range != selection_anchors).then_some(range)
4886 },
4887 ),
4888 );
4889 }
4890 }
4891 ranges
4892 }))
4893 })
4894 .log_err()
4895 else {
4896 return;
4897 };
4898 let matches = matches_task.await;
4899 editor
4900 .update_in(&mut cx, |editor, _, cx| {
4901 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4902 if !matches.is_empty() {
4903 editor.highlight_background::<SelectedTextHighlight>(
4904 &matches,
4905 |theme| theme.editor_document_highlight_bracket_background,
4906 cx,
4907 )
4908 }
4909 })
4910 .log_err();
4911 }));
4912 }
4913
4914 pub fn refresh_inline_completion(
4915 &mut self,
4916 debounce: bool,
4917 user_requested: bool,
4918 window: &mut Window,
4919 cx: &mut Context<Self>,
4920 ) -> Option<()> {
4921 let provider = self.edit_prediction_provider()?;
4922 let cursor = self.selections.newest_anchor().head();
4923 let (buffer, cursor_buffer_position) =
4924 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4925
4926 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4927 self.discard_inline_completion(false, cx);
4928 return None;
4929 }
4930
4931 if !user_requested
4932 && (!self.should_show_edit_predictions()
4933 || !self.is_focused(window)
4934 || buffer.read(cx).is_empty())
4935 {
4936 self.discard_inline_completion(false, cx);
4937 return None;
4938 }
4939
4940 self.update_visible_inline_completion(window, cx);
4941 provider.refresh(
4942 self.project.clone(),
4943 buffer,
4944 cursor_buffer_position,
4945 debounce,
4946 cx,
4947 );
4948 Some(())
4949 }
4950
4951 fn show_edit_predictions_in_menu(&self) -> bool {
4952 match self.edit_prediction_settings {
4953 EditPredictionSettings::Disabled => false,
4954 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4955 }
4956 }
4957
4958 pub fn edit_predictions_enabled(&self) -> bool {
4959 match self.edit_prediction_settings {
4960 EditPredictionSettings::Disabled => false,
4961 EditPredictionSettings::Enabled { .. } => true,
4962 }
4963 }
4964
4965 fn edit_prediction_requires_modifier(&self) -> bool {
4966 match self.edit_prediction_settings {
4967 EditPredictionSettings::Disabled => false,
4968 EditPredictionSettings::Enabled {
4969 preview_requires_modifier,
4970 ..
4971 } => preview_requires_modifier,
4972 }
4973 }
4974
4975 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4976 if self.edit_prediction_provider.is_none() {
4977 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4978 } else {
4979 let selection = self.selections.newest_anchor();
4980 let cursor = selection.head();
4981
4982 if let Some((buffer, cursor_buffer_position)) =
4983 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4984 {
4985 self.edit_prediction_settings =
4986 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
4987 }
4988 }
4989 }
4990
4991 fn edit_prediction_settings_at_position(
4992 &self,
4993 buffer: &Entity<Buffer>,
4994 buffer_position: language::Anchor,
4995 cx: &App,
4996 ) -> EditPredictionSettings {
4997 if self.mode != EditorMode::Full
4998 || !self.show_inline_completions_override.unwrap_or(true)
4999 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5000 {
5001 return EditPredictionSettings::Disabled;
5002 }
5003
5004 let buffer = buffer.read(cx);
5005
5006 let file = buffer.file();
5007
5008 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5009 return EditPredictionSettings::Disabled;
5010 };
5011
5012 let by_provider = matches!(
5013 self.menu_inline_completions_policy,
5014 MenuInlineCompletionsPolicy::ByProvider
5015 );
5016
5017 let show_in_menu = by_provider
5018 && self
5019 .edit_prediction_provider
5020 .as_ref()
5021 .map_or(false, |provider| {
5022 provider.provider.show_completions_in_menu()
5023 });
5024
5025 let preview_requires_modifier =
5026 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5027
5028 EditPredictionSettings::Enabled {
5029 show_in_menu,
5030 preview_requires_modifier,
5031 }
5032 }
5033
5034 fn should_show_edit_predictions(&self) -> bool {
5035 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5036 }
5037
5038 pub fn edit_prediction_preview_is_active(&self) -> bool {
5039 matches!(
5040 self.edit_prediction_preview,
5041 EditPredictionPreview::Active { .. }
5042 )
5043 }
5044
5045 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5046 let cursor = self.selections.newest_anchor().head();
5047 if let Some((buffer, cursor_position)) =
5048 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5049 {
5050 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5051 } else {
5052 false
5053 }
5054 }
5055
5056 fn edit_predictions_enabled_in_buffer(
5057 &self,
5058 buffer: &Entity<Buffer>,
5059 buffer_position: language::Anchor,
5060 cx: &App,
5061 ) -> bool {
5062 maybe!({
5063 let provider = self.edit_prediction_provider()?;
5064 if !provider.is_enabled(&buffer, buffer_position, cx) {
5065 return Some(false);
5066 }
5067 let buffer = buffer.read(cx);
5068 let Some(file) = buffer.file() else {
5069 return Some(true);
5070 };
5071 let settings = all_language_settings(Some(file), cx);
5072 Some(settings.edit_predictions_enabled_for_file(file, cx))
5073 })
5074 .unwrap_or(false)
5075 }
5076
5077 fn cycle_inline_completion(
5078 &mut self,
5079 direction: Direction,
5080 window: &mut Window,
5081 cx: &mut Context<Self>,
5082 ) -> Option<()> {
5083 let provider = self.edit_prediction_provider()?;
5084 let cursor = self.selections.newest_anchor().head();
5085 let (buffer, cursor_buffer_position) =
5086 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5087 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5088 return None;
5089 }
5090
5091 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5092 self.update_visible_inline_completion(window, cx);
5093
5094 Some(())
5095 }
5096
5097 pub fn show_inline_completion(
5098 &mut self,
5099 _: &ShowEditPrediction,
5100 window: &mut Window,
5101 cx: &mut Context<Self>,
5102 ) {
5103 if !self.has_active_inline_completion() {
5104 self.refresh_inline_completion(false, true, window, cx);
5105 return;
5106 }
5107
5108 self.update_visible_inline_completion(window, cx);
5109 }
5110
5111 pub fn display_cursor_names(
5112 &mut self,
5113 _: &DisplayCursorNames,
5114 window: &mut Window,
5115 cx: &mut Context<Self>,
5116 ) {
5117 self.show_cursor_names(window, cx);
5118 }
5119
5120 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5121 self.show_cursor_names = true;
5122 cx.notify();
5123 cx.spawn_in(window, |this, mut cx| async move {
5124 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5125 this.update(&mut cx, |this, cx| {
5126 this.show_cursor_names = false;
5127 cx.notify()
5128 })
5129 .ok()
5130 })
5131 .detach();
5132 }
5133
5134 pub fn next_edit_prediction(
5135 &mut self,
5136 _: &NextEditPrediction,
5137 window: &mut Window,
5138 cx: &mut Context<Self>,
5139 ) {
5140 if self.has_active_inline_completion() {
5141 self.cycle_inline_completion(Direction::Next, window, cx);
5142 } else {
5143 let is_copilot_disabled = self
5144 .refresh_inline_completion(false, true, window, cx)
5145 .is_none();
5146 if is_copilot_disabled {
5147 cx.propagate();
5148 }
5149 }
5150 }
5151
5152 pub fn previous_edit_prediction(
5153 &mut self,
5154 _: &PreviousEditPrediction,
5155 window: &mut Window,
5156 cx: &mut Context<Self>,
5157 ) {
5158 if self.has_active_inline_completion() {
5159 self.cycle_inline_completion(Direction::Prev, window, cx);
5160 } else {
5161 let is_copilot_disabled = self
5162 .refresh_inline_completion(false, true, window, cx)
5163 .is_none();
5164 if is_copilot_disabled {
5165 cx.propagate();
5166 }
5167 }
5168 }
5169
5170 pub fn accept_edit_prediction(
5171 &mut self,
5172 _: &AcceptEditPrediction,
5173 window: &mut Window,
5174 cx: &mut Context<Self>,
5175 ) {
5176 if self.show_edit_predictions_in_menu() {
5177 self.hide_context_menu(window, cx);
5178 }
5179
5180 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5181 return;
5182 };
5183
5184 self.report_inline_completion_event(
5185 active_inline_completion.completion_id.clone(),
5186 true,
5187 cx,
5188 );
5189
5190 match &active_inline_completion.completion {
5191 InlineCompletion::Move { target, .. } => {
5192 let target = *target;
5193
5194 if let Some(position_map) = &self.last_position_map {
5195 if position_map
5196 .visible_row_range
5197 .contains(&target.to_display_point(&position_map.snapshot).row())
5198 || !self.edit_prediction_requires_modifier()
5199 {
5200 self.unfold_ranges(&[target..target], true, false, cx);
5201 // Note that this is also done in vim's handler of the Tab action.
5202 self.change_selections(
5203 Some(Autoscroll::newest()),
5204 window,
5205 cx,
5206 |selections| {
5207 selections.select_anchor_ranges([target..target]);
5208 },
5209 );
5210 self.clear_row_highlights::<EditPredictionPreview>();
5211
5212 self.edit_prediction_preview
5213 .set_previous_scroll_position(None);
5214 } else {
5215 self.edit_prediction_preview
5216 .set_previous_scroll_position(Some(
5217 position_map.snapshot.scroll_anchor,
5218 ));
5219
5220 self.highlight_rows::<EditPredictionPreview>(
5221 target..target,
5222 cx.theme().colors().editor_highlighted_line_background,
5223 true,
5224 cx,
5225 );
5226 self.request_autoscroll(Autoscroll::fit(), cx);
5227 }
5228 }
5229 }
5230 InlineCompletion::Edit { edits, .. } => {
5231 if let Some(provider) = self.edit_prediction_provider() {
5232 provider.accept(cx);
5233 }
5234
5235 let snapshot = self.buffer.read(cx).snapshot(cx);
5236 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5237
5238 self.buffer.update(cx, |buffer, cx| {
5239 buffer.edit(edits.iter().cloned(), None, cx)
5240 });
5241
5242 self.change_selections(None, window, cx, |s| {
5243 s.select_anchor_ranges([last_edit_end..last_edit_end])
5244 });
5245
5246 self.update_visible_inline_completion(window, cx);
5247 if self.active_inline_completion.is_none() {
5248 self.refresh_inline_completion(true, true, window, cx);
5249 }
5250
5251 cx.notify();
5252 }
5253 }
5254
5255 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5256 }
5257
5258 pub fn accept_partial_inline_completion(
5259 &mut self,
5260 _: &AcceptPartialEditPrediction,
5261 window: &mut Window,
5262 cx: &mut Context<Self>,
5263 ) {
5264 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5265 return;
5266 };
5267 if self.selections.count() != 1 {
5268 return;
5269 }
5270
5271 self.report_inline_completion_event(
5272 active_inline_completion.completion_id.clone(),
5273 true,
5274 cx,
5275 );
5276
5277 match &active_inline_completion.completion {
5278 InlineCompletion::Move { target, .. } => {
5279 let target = *target;
5280 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5281 selections.select_anchor_ranges([target..target]);
5282 });
5283 }
5284 InlineCompletion::Edit { edits, .. } => {
5285 // Find an insertion that starts at the cursor position.
5286 let snapshot = self.buffer.read(cx).snapshot(cx);
5287 let cursor_offset = self.selections.newest::<usize>(cx).head();
5288 let insertion = edits.iter().find_map(|(range, text)| {
5289 let range = range.to_offset(&snapshot);
5290 if range.is_empty() && range.start == cursor_offset {
5291 Some(text)
5292 } else {
5293 None
5294 }
5295 });
5296
5297 if let Some(text) = insertion {
5298 let mut partial_completion = text
5299 .chars()
5300 .by_ref()
5301 .take_while(|c| c.is_alphabetic())
5302 .collect::<String>();
5303 if partial_completion.is_empty() {
5304 partial_completion = text
5305 .chars()
5306 .by_ref()
5307 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5308 .collect::<String>();
5309 }
5310
5311 cx.emit(EditorEvent::InputHandled {
5312 utf16_range_to_replace: None,
5313 text: partial_completion.clone().into(),
5314 });
5315
5316 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5317
5318 self.refresh_inline_completion(true, true, window, cx);
5319 cx.notify();
5320 } else {
5321 self.accept_edit_prediction(&Default::default(), window, cx);
5322 }
5323 }
5324 }
5325 }
5326
5327 fn discard_inline_completion(
5328 &mut self,
5329 should_report_inline_completion_event: bool,
5330 cx: &mut Context<Self>,
5331 ) -> bool {
5332 if should_report_inline_completion_event {
5333 let completion_id = self
5334 .active_inline_completion
5335 .as_ref()
5336 .and_then(|active_completion| active_completion.completion_id.clone());
5337
5338 self.report_inline_completion_event(completion_id, false, cx);
5339 }
5340
5341 if let Some(provider) = self.edit_prediction_provider() {
5342 provider.discard(cx);
5343 }
5344
5345 self.take_active_inline_completion(cx)
5346 }
5347
5348 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5349 let Some(provider) = self.edit_prediction_provider() else {
5350 return;
5351 };
5352
5353 let Some((_, buffer, _)) = self
5354 .buffer
5355 .read(cx)
5356 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5357 else {
5358 return;
5359 };
5360
5361 let extension = buffer
5362 .read(cx)
5363 .file()
5364 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5365
5366 let event_type = match accepted {
5367 true => "Edit Prediction Accepted",
5368 false => "Edit Prediction Discarded",
5369 };
5370 telemetry::event!(
5371 event_type,
5372 provider = provider.name(),
5373 prediction_id = id,
5374 suggestion_accepted = accepted,
5375 file_extension = extension,
5376 );
5377 }
5378
5379 pub fn has_active_inline_completion(&self) -> bool {
5380 self.active_inline_completion.is_some()
5381 }
5382
5383 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5384 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5385 return false;
5386 };
5387
5388 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5389 self.clear_highlights::<InlineCompletionHighlight>(cx);
5390 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5391 true
5392 }
5393
5394 /// Returns true when we're displaying the edit prediction popover below the cursor
5395 /// like we are not previewing and the LSP autocomplete menu is visible
5396 /// or we are in `when_holding_modifier` mode.
5397 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5398 if self.edit_prediction_preview_is_active()
5399 || !self.show_edit_predictions_in_menu()
5400 || !self.edit_predictions_enabled()
5401 {
5402 return false;
5403 }
5404
5405 if self.has_visible_completions_menu() {
5406 return true;
5407 }
5408
5409 has_completion && self.edit_prediction_requires_modifier()
5410 }
5411
5412 fn handle_modifiers_changed(
5413 &mut self,
5414 modifiers: Modifiers,
5415 position_map: &PositionMap,
5416 window: &mut Window,
5417 cx: &mut Context<Self>,
5418 ) {
5419 if self.show_edit_predictions_in_menu() {
5420 self.update_edit_prediction_preview(&modifiers, window, cx);
5421 }
5422
5423 self.update_selection_mode(&modifiers, position_map, window, cx);
5424
5425 let mouse_position = window.mouse_position();
5426 if !position_map.text_hitbox.is_hovered(window) {
5427 return;
5428 }
5429
5430 self.update_hovered_link(
5431 position_map.point_for_position(mouse_position),
5432 &position_map.snapshot,
5433 modifiers,
5434 window,
5435 cx,
5436 )
5437 }
5438
5439 fn update_selection_mode(
5440 &mut self,
5441 modifiers: &Modifiers,
5442 position_map: &PositionMap,
5443 window: &mut Window,
5444 cx: &mut Context<Self>,
5445 ) {
5446 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5447 return;
5448 }
5449
5450 let mouse_position = window.mouse_position();
5451 let point_for_position = position_map.point_for_position(mouse_position);
5452 let position = point_for_position.previous_valid;
5453
5454 self.select(
5455 SelectPhase::BeginColumnar {
5456 position,
5457 reset: false,
5458 goal_column: point_for_position.exact_unclipped.column(),
5459 },
5460 window,
5461 cx,
5462 );
5463 }
5464
5465 fn update_edit_prediction_preview(
5466 &mut self,
5467 modifiers: &Modifiers,
5468 window: &mut Window,
5469 cx: &mut Context<Self>,
5470 ) {
5471 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5472 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5473 return;
5474 };
5475
5476 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5477 if matches!(
5478 self.edit_prediction_preview,
5479 EditPredictionPreview::Inactive { .. }
5480 ) {
5481 self.edit_prediction_preview = EditPredictionPreview::Active {
5482 previous_scroll_position: None,
5483 since: Instant::now(),
5484 };
5485
5486 self.update_visible_inline_completion(window, cx);
5487 cx.notify();
5488 }
5489 } else if let EditPredictionPreview::Active {
5490 previous_scroll_position,
5491 since,
5492 } = self.edit_prediction_preview
5493 {
5494 if let (Some(previous_scroll_position), Some(position_map)) =
5495 (previous_scroll_position, self.last_position_map.as_ref())
5496 {
5497 self.set_scroll_position(
5498 previous_scroll_position
5499 .scroll_position(&position_map.snapshot.display_snapshot),
5500 window,
5501 cx,
5502 );
5503 }
5504
5505 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5506 released_too_fast: since.elapsed() < Duration::from_millis(200),
5507 };
5508 self.clear_row_highlights::<EditPredictionPreview>();
5509 self.update_visible_inline_completion(window, cx);
5510 cx.notify();
5511 }
5512 }
5513
5514 fn update_visible_inline_completion(
5515 &mut self,
5516 _window: &mut Window,
5517 cx: &mut Context<Self>,
5518 ) -> Option<()> {
5519 let selection = self.selections.newest_anchor();
5520 let cursor = selection.head();
5521 let multibuffer = self.buffer.read(cx).snapshot(cx);
5522 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5523 let excerpt_id = cursor.excerpt_id;
5524
5525 let show_in_menu = self.show_edit_predictions_in_menu();
5526 let completions_menu_has_precedence = !show_in_menu
5527 && (self.context_menu.borrow().is_some()
5528 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5529
5530 if completions_menu_has_precedence
5531 || !offset_selection.is_empty()
5532 || self
5533 .active_inline_completion
5534 .as_ref()
5535 .map_or(false, |completion| {
5536 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5537 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5538 !invalidation_range.contains(&offset_selection.head())
5539 })
5540 {
5541 self.discard_inline_completion(false, cx);
5542 return None;
5543 }
5544
5545 self.take_active_inline_completion(cx);
5546 let Some(provider) = self.edit_prediction_provider() else {
5547 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5548 return None;
5549 };
5550
5551 let (buffer, cursor_buffer_position) =
5552 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5553
5554 self.edit_prediction_settings =
5555 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5556
5557 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5558
5559 if self.edit_prediction_indent_conflict {
5560 let cursor_point = cursor.to_point(&multibuffer);
5561
5562 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5563
5564 if let Some((_, indent)) = indents.iter().next() {
5565 if indent.len == cursor_point.column {
5566 self.edit_prediction_indent_conflict = false;
5567 }
5568 }
5569 }
5570
5571 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5572 let edits = inline_completion
5573 .edits
5574 .into_iter()
5575 .flat_map(|(range, new_text)| {
5576 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5577 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5578 Some((start..end, new_text))
5579 })
5580 .collect::<Vec<_>>();
5581 if edits.is_empty() {
5582 return None;
5583 }
5584
5585 let first_edit_start = edits.first().unwrap().0.start;
5586 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5587 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5588
5589 let last_edit_end = edits.last().unwrap().0.end;
5590 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5591 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5592
5593 let cursor_row = cursor.to_point(&multibuffer).row;
5594
5595 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5596
5597 let mut inlay_ids = Vec::new();
5598 let invalidation_row_range;
5599 let move_invalidation_row_range = if cursor_row < edit_start_row {
5600 Some(cursor_row..edit_end_row)
5601 } else if cursor_row > edit_end_row {
5602 Some(edit_start_row..cursor_row)
5603 } else {
5604 None
5605 };
5606 let is_move =
5607 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5608 let completion = if is_move {
5609 invalidation_row_range =
5610 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5611 let target = first_edit_start;
5612 InlineCompletion::Move { target, snapshot }
5613 } else {
5614 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5615 && !self.inline_completions_hidden_for_vim_mode;
5616
5617 if show_completions_in_buffer {
5618 if edits
5619 .iter()
5620 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5621 {
5622 let mut inlays = Vec::new();
5623 for (range, new_text) in &edits {
5624 let inlay = Inlay::inline_completion(
5625 post_inc(&mut self.next_inlay_id),
5626 range.start,
5627 new_text.as_str(),
5628 );
5629 inlay_ids.push(inlay.id);
5630 inlays.push(inlay);
5631 }
5632
5633 self.splice_inlays(&[], inlays, cx);
5634 } else {
5635 let background_color = cx.theme().status().deleted_background;
5636 self.highlight_text::<InlineCompletionHighlight>(
5637 edits.iter().map(|(range, _)| range.clone()).collect(),
5638 HighlightStyle {
5639 background_color: Some(background_color),
5640 ..Default::default()
5641 },
5642 cx,
5643 );
5644 }
5645 }
5646
5647 invalidation_row_range = edit_start_row..edit_end_row;
5648
5649 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5650 if provider.show_tab_accept_marker() {
5651 EditDisplayMode::TabAccept
5652 } else {
5653 EditDisplayMode::Inline
5654 }
5655 } else {
5656 EditDisplayMode::DiffPopover
5657 };
5658
5659 InlineCompletion::Edit {
5660 edits,
5661 edit_preview: inline_completion.edit_preview,
5662 display_mode,
5663 snapshot,
5664 }
5665 };
5666
5667 let invalidation_range = multibuffer
5668 .anchor_before(Point::new(invalidation_row_range.start, 0))
5669 ..multibuffer.anchor_after(Point::new(
5670 invalidation_row_range.end,
5671 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5672 ));
5673
5674 self.stale_inline_completion_in_menu = None;
5675 self.active_inline_completion = Some(InlineCompletionState {
5676 inlay_ids,
5677 completion,
5678 completion_id: inline_completion.id,
5679 invalidation_range,
5680 });
5681
5682 cx.notify();
5683
5684 Some(())
5685 }
5686
5687 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5688 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5689 }
5690
5691 fn render_code_actions_indicator(
5692 &self,
5693 _style: &EditorStyle,
5694 row: DisplayRow,
5695 is_active: bool,
5696 cx: &mut Context<Self>,
5697 ) -> Option<IconButton> {
5698 if self.available_code_actions.is_some() {
5699 Some(
5700 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5701 .shape(ui::IconButtonShape::Square)
5702 .icon_size(IconSize::XSmall)
5703 .icon_color(Color::Muted)
5704 .toggle_state(is_active)
5705 .tooltip({
5706 let focus_handle = self.focus_handle.clone();
5707 move |window, cx| {
5708 Tooltip::for_action_in(
5709 "Toggle Code Actions",
5710 &ToggleCodeActions {
5711 deployed_from_indicator: None,
5712 },
5713 &focus_handle,
5714 window,
5715 cx,
5716 )
5717 }
5718 })
5719 .on_click(cx.listener(move |editor, _e, window, cx| {
5720 window.focus(&editor.focus_handle(cx));
5721 editor.toggle_code_actions(
5722 &ToggleCodeActions {
5723 deployed_from_indicator: Some(row),
5724 },
5725 window,
5726 cx,
5727 );
5728 })),
5729 )
5730 } else {
5731 None
5732 }
5733 }
5734
5735 fn clear_tasks(&mut self) {
5736 self.tasks.clear()
5737 }
5738
5739 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5740 if self.tasks.insert(key, value).is_some() {
5741 // This case should hopefully be rare, but just in case...
5742 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5743 }
5744 }
5745
5746 fn build_tasks_context(
5747 project: &Entity<Project>,
5748 buffer: &Entity<Buffer>,
5749 buffer_row: u32,
5750 tasks: &Arc<RunnableTasks>,
5751 cx: &mut Context<Self>,
5752 ) -> Task<Option<task::TaskContext>> {
5753 let position = Point::new(buffer_row, tasks.column);
5754 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5755 let location = Location {
5756 buffer: buffer.clone(),
5757 range: range_start..range_start,
5758 };
5759 // Fill in the environmental variables from the tree-sitter captures
5760 let mut captured_task_variables = TaskVariables::default();
5761 for (capture_name, value) in tasks.extra_variables.clone() {
5762 captured_task_variables.insert(
5763 task::VariableName::Custom(capture_name.into()),
5764 value.clone(),
5765 );
5766 }
5767 project.update(cx, |project, cx| {
5768 project.task_store().update(cx, |task_store, cx| {
5769 task_store.task_context_for_location(captured_task_variables, location, cx)
5770 })
5771 })
5772 }
5773
5774 pub fn spawn_nearest_task(
5775 &mut self,
5776 action: &SpawnNearestTask,
5777 window: &mut Window,
5778 cx: &mut Context<Self>,
5779 ) {
5780 let Some((workspace, _)) = self.workspace.clone() else {
5781 return;
5782 };
5783 let Some(project) = self.project.clone() else {
5784 return;
5785 };
5786
5787 // Try to find a closest, enclosing node using tree-sitter that has a
5788 // task
5789 let Some((buffer, buffer_row, tasks)) = self
5790 .find_enclosing_node_task(cx)
5791 // Or find the task that's closest in row-distance.
5792 .or_else(|| self.find_closest_task(cx))
5793 else {
5794 return;
5795 };
5796
5797 let reveal_strategy = action.reveal;
5798 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5799 cx.spawn_in(window, |_, mut cx| async move {
5800 let context = task_context.await?;
5801 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5802
5803 let resolved = resolved_task.resolved.as_mut()?;
5804 resolved.reveal = reveal_strategy;
5805
5806 workspace
5807 .update(&mut cx, |workspace, cx| {
5808 workspace::tasks::schedule_resolved_task(
5809 workspace,
5810 task_source_kind,
5811 resolved_task,
5812 false,
5813 cx,
5814 );
5815 })
5816 .ok()
5817 })
5818 .detach();
5819 }
5820
5821 fn find_closest_task(
5822 &mut self,
5823 cx: &mut Context<Self>,
5824 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5825 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5826
5827 let ((buffer_id, row), tasks) = self
5828 .tasks
5829 .iter()
5830 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5831
5832 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5833 let tasks = Arc::new(tasks.to_owned());
5834 Some((buffer, *row, tasks))
5835 }
5836
5837 fn find_enclosing_node_task(
5838 &mut self,
5839 cx: &mut Context<Self>,
5840 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5841 let snapshot = self.buffer.read(cx).snapshot(cx);
5842 let offset = self.selections.newest::<usize>(cx).head();
5843 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5844 let buffer_id = excerpt.buffer().remote_id();
5845
5846 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5847 let mut cursor = layer.node().walk();
5848
5849 while cursor.goto_first_child_for_byte(offset).is_some() {
5850 if cursor.node().end_byte() == offset {
5851 cursor.goto_next_sibling();
5852 }
5853 }
5854
5855 // Ascend to the smallest ancestor that contains the range and has a task.
5856 loop {
5857 let node = cursor.node();
5858 let node_range = node.byte_range();
5859 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5860
5861 // Check if this node contains our offset
5862 if node_range.start <= offset && node_range.end >= offset {
5863 // If it contains offset, check for task
5864 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5865 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5866 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5867 }
5868 }
5869
5870 if !cursor.goto_parent() {
5871 break;
5872 }
5873 }
5874 None
5875 }
5876
5877 fn render_run_indicator(
5878 &self,
5879 _style: &EditorStyle,
5880 is_active: bool,
5881 row: DisplayRow,
5882 cx: &mut Context<Self>,
5883 ) -> IconButton {
5884 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5885 .shape(ui::IconButtonShape::Square)
5886 .icon_size(IconSize::XSmall)
5887 .icon_color(Color::Muted)
5888 .toggle_state(is_active)
5889 .on_click(cx.listener(move |editor, _e, window, cx| {
5890 window.focus(&editor.focus_handle(cx));
5891 editor.toggle_code_actions(
5892 &ToggleCodeActions {
5893 deployed_from_indicator: Some(row),
5894 },
5895 window,
5896 cx,
5897 );
5898 }))
5899 }
5900
5901 pub fn context_menu_visible(&self) -> bool {
5902 !self.edit_prediction_preview_is_active()
5903 && self
5904 .context_menu
5905 .borrow()
5906 .as_ref()
5907 .map_or(false, |menu| menu.visible())
5908 }
5909
5910 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5911 self.context_menu
5912 .borrow()
5913 .as_ref()
5914 .map(|menu| menu.origin())
5915 }
5916
5917 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5918 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5919
5920 #[allow(clippy::too_many_arguments)]
5921 fn render_edit_prediction_popover(
5922 &mut self,
5923 text_bounds: &Bounds<Pixels>,
5924 content_origin: gpui::Point<Pixels>,
5925 editor_snapshot: &EditorSnapshot,
5926 visible_row_range: Range<DisplayRow>,
5927 scroll_top: f32,
5928 scroll_bottom: f32,
5929 line_layouts: &[LineWithInvisibles],
5930 line_height: Pixels,
5931 scroll_pixel_position: gpui::Point<Pixels>,
5932 newest_selection_head: Option<DisplayPoint>,
5933 editor_width: Pixels,
5934 style: &EditorStyle,
5935 window: &mut Window,
5936 cx: &mut App,
5937 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5938 let active_inline_completion = self.active_inline_completion.as_ref()?;
5939
5940 if self.edit_prediction_visible_in_cursor_popover(true) {
5941 return None;
5942 }
5943
5944 match &active_inline_completion.completion {
5945 InlineCompletion::Move { target, .. } => {
5946 let target_display_point = target.to_display_point(editor_snapshot);
5947
5948 if self.edit_prediction_requires_modifier() {
5949 if !self.edit_prediction_preview_is_active() {
5950 return None;
5951 }
5952
5953 self.render_edit_prediction_modifier_jump_popover(
5954 text_bounds,
5955 content_origin,
5956 visible_row_range,
5957 line_layouts,
5958 line_height,
5959 scroll_pixel_position,
5960 newest_selection_head,
5961 target_display_point,
5962 window,
5963 cx,
5964 )
5965 } else {
5966 self.render_edit_prediction_eager_jump_popover(
5967 text_bounds,
5968 content_origin,
5969 editor_snapshot,
5970 visible_row_range,
5971 scroll_top,
5972 scroll_bottom,
5973 line_height,
5974 scroll_pixel_position,
5975 target_display_point,
5976 editor_width,
5977 window,
5978 cx,
5979 )
5980 }
5981 }
5982 InlineCompletion::Edit {
5983 display_mode: EditDisplayMode::Inline,
5984 ..
5985 } => None,
5986 InlineCompletion::Edit {
5987 display_mode: EditDisplayMode::TabAccept,
5988 edits,
5989 ..
5990 } => {
5991 let range = &edits.first()?.0;
5992 let target_display_point = range.end.to_display_point(editor_snapshot);
5993
5994 self.render_edit_prediction_end_of_line_popover(
5995 "Accept",
5996 editor_snapshot,
5997 visible_row_range,
5998 target_display_point,
5999 line_height,
6000 scroll_pixel_position,
6001 content_origin,
6002 editor_width,
6003 window,
6004 cx,
6005 )
6006 }
6007 InlineCompletion::Edit {
6008 edits,
6009 edit_preview,
6010 display_mode: EditDisplayMode::DiffPopover,
6011 snapshot,
6012 } => self.render_edit_prediction_diff_popover(
6013 text_bounds,
6014 content_origin,
6015 editor_snapshot,
6016 visible_row_range,
6017 line_layouts,
6018 line_height,
6019 scroll_pixel_position,
6020 newest_selection_head,
6021 editor_width,
6022 style,
6023 edits,
6024 edit_preview,
6025 snapshot,
6026 window,
6027 cx,
6028 ),
6029 }
6030 }
6031
6032 #[allow(clippy::too_many_arguments)]
6033 fn render_edit_prediction_modifier_jump_popover(
6034 &mut self,
6035 text_bounds: &Bounds<Pixels>,
6036 content_origin: gpui::Point<Pixels>,
6037 visible_row_range: Range<DisplayRow>,
6038 line_layouts: &[LineWithInvisibles],
6039 line_height: Pixels,
6040 scroll_pixel_position: gpui::Point<Pixels>,
6041 newest_selection_head: Option<DisplayPoint>,
6042 target_display_point: DisplayPoint,
6043 window: &mut Window,
6044 cx: &mut App,
6045 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6046 let scrolled_content_origin =
6047 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6048
6049 const SCROLL_PADDING_Y: Pixels = px(12.);
6050
6051 if target_display_point.row() < visible_row_range.start {
6052 return self.render_edit_prediction_scroll_popover(
6053 |_| SCROLL_PADDING_Y,
6054 IconName::ArrowUp,
6055 visible_row_range,
6056 line_layouts,
6057 newest_selection_head,
6058 scrolled_content_origin,
6059 window,
6060 cx,
6061 );
6062 } else if target_display_point.row() >= visible_row_range.end {
6063 return self.render_edit_prediction_scroll_popover(
6064 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6065 IconName::ArrowDown,
6066 visible_row_range,
6067 line_layouts,
6068 newest_selection_head,
6069 scrolled_content_origin,
6070 window,
6071 cx,
6072 );
6073 }
6074
6075 const POLE_WIDTH: Pixels = px(2.);
6076
6077 let line_layout =
6078 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6079 let target_column = target_display_point.column() as usize;
6080
6081 let target_x = line_layout.x_for_index(target_column);
6082 let target_y =
6083 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6084
6085 let flag_on_right = target_x < text_bounds.size.width / 2.;
6086
6087 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6088 border_color.l += 0.001;
6089
6090 let mut element = v_flex()
6091 .items_end()
6092 .when(flag_on_right, |el| el.items_start())
6093 .child(if flag_on_right {
6094 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6095 .rounded_bl(px(0.))
6096 .rounded_tl(px(0.))
6097 .border_l_2()
6098 .border_color(border_color)
6099 } else {
6100 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6101 .rounded_br(px(0.))
6102 .rounded_tr(px(0.))
6103 .border_r_2()
6104 .border_color(border_color)
6105 })
6106 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6107 .into_any();
6108
6109 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6110
6111 let mut origin = scrolled_content_origin + point(target_x, target_y)
6112 - point(
6113 if flag_on_right {
6114 POLE_WIDTH
6115 } else {
6116 size.width - POLE_WIDTH
6117 },
6118 size.height - line_height,
6119 );
6120
6121 origin.x = origin.x.max(content_origin.x);
6122
6123 element.prepaint_at(origin, window, cx);
6124
6125 Some((element, origin))
6126 }
6127
6128 #[allow(clippy::too_many_arguments)]
6129 fn render_edit_prediction_scroll_popover(
6130 &mut self,
6131 to_y: impl Fn(Size<Pixels>) -> Pixels,
6132 scroll_icon: IconName,
6133 visible_row_range: Range<DisplayRow>,
6134 line_layouts: &[LineWithInvisibles],
6135 newest_selection_head: Option<DisplayPoint>,
6136 scrolled_content_origin: gpui::Point<Pixels>,
6137 window: &mut Window,
6138 cx: &mut App,
6139 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6140 let mut element = self
6141 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6142 .into_any();
6143
6144 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6145
6146 let cursor = newest_selection_head?;
6147 let cursor_row_layout =
6148 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6149 let cursor_column = cursor.column() as usize;
6150
6151 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6152
6153 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6154
6155 element.prepaint_at(origin, window, cx);
6156 Some((element, origin))
6157 }
6158
6159 #[allow(clippy::too_many_arguments)]
6160 fn render_edit_prediction_eager_jump_popover(
6161 &mut self,
6162 text_bounds: &Bounds<Pixels>,
6163 content_origin: gpui::Point<Pixels>,
6164 editor_snapshot: &EditorSnapshot,
6165 visible_row_range: Range<DisplayRow>,
6166 scroll_top: f32,
6167 scroll_bottom: f32,
6168 line_height: Pixels,
6169 scroll_pixel_position: gpui::Point<Pixels>,
6170 target_display_point: DisplayPoint,
6171 editor_width: Pixels,
6172 window: &mut Window,
6173 cx: &mut App,
6174 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6175 if target_display_point.row().as_f32() < scroll_top {
6176 let mut element = self
6177 .render_edit_prediction_line_popover(
6178 "Jump to Edit",
6179 Some(IconName::ArrowUp),
6180 window,
6181 cx,
6182 )?
6183 .into_any();
6184
6185 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6186 let offset = point(
6187 (text_bounds.size.width - size.width) / 2.,
6188 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6189 );
6190
6191 let origin = text_bounds.origin + offset;
6192 element.prepaint_at(origin, window, cx);
6193 Some((element, origin))
6194 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6195 let mut element = self
6196 .render_edit_prediction_line_popover(
6197 "Jump to Edit",
6198 Some(IconName::ArrowDown),
6199 window,
6200 cx,
6201 )?
6202 .into_any();
6203
6204 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6205 let offset = point(
6206 (text_bounds.size.width - size.width) / 2.,
6207 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6208 );
6209
6210 let origin = text_bounds.origin + offset;
6211 element.prepaint_at(origin, window, cx);
6212 Some((element, origin))
6213 } else {
6214 self.render_edit_prediction_end_of_line_popover(
6215 "Jump to Edit",
6216 editor_snapshot,
6217 visible_row_range,
6218 target_display_point,
6219 line_height,
6220 scroll_pixel_position,
6221 content_origin,
6222 editor_width,
6223 window,
6224 cx,
6225 )
6226 }
6227 }
6228
6229 #[allow(clippy::too_many_arguments)]
6230 fn render_edit_prediction_end_of_line_popover(
6231 self: &mut Editor,
6232 label: &'static str,
6233 editor_snapshot: &EditorSnapshot,
6234 visible_row_range: Range<DisplayRow>,
6235 target_display_point: DisplayPoint,
6236 line_height: Pixels,
6237 scroll_pixel_position: gpui::Point<Pixels>,
6238 content_origin: gpui::Point<Pixels>,
6239 editor_width: Pixels,
6240 window: &mut Window,
6241 cx: &mut App,
6242 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6243 let target_line_end = DisplayPoint::new(
6244 target_display_point.row(),
6245 editor_snapshot.line_len(target_display_point.row()),
6246 );
6247
6248 let mut element = self
6249 .render_edit_prediction_line_popover(label, None, window, cx)?
6250 .into_any();
6251
6252 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6253
6254 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6255
6256 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6257 let mut origin = start_point
6258 + line_origin
6259 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6260 origin.x = origin.x.max(content_origin.x);
6261
6262 let max_x = content_origin.x + editor_width - size.width;
6263
6264 if origin.x > max_x {
6265 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6266
6267 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6268 origin.y += offset;
6269 IconName::ArrowUp
6270 } else {
6271 origin.y -= offset;
6272 IconName::ArrowDown
6273 };
6274
6275 element = self
6276 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6277 .into_any();
6278
6279 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6280
6281 origin.x = content_origin.x + editor_width - size.width - px(2.);
6282 }
6283
6284 element.prepaint_at(origin, window, cx);
6285 Some((element, origin))
6286 }
6287
6288 #[allow(clippy::too_many_arguments)]
6289 fn render_edit_prediction_diff_popover(
6290 self: &Editor,
6291 text_bounds: &Bounds<Pixels>,
6292 content_origin: gpui::Point<Pixels>,
6293 editor_snapshot: &EditorSnapshot,
6294 visible_row_range: Range<DisplayRow>,
6295 line_layouts: &[LineWithInvisibles],
6296 line_height: Pixels,
6297 scroll_pixel_position: gpui::Point<Pixels>,
6298 newest_selection_head: Option<DisplayPoint>,
6299 editor_width: Pixels,
6300 style: &EditorStyle,
6301 edits: &Vec<(Range<Anchor>, String)>,
6302 edit_preview: &Option<language::EditPreview>,
6303 snapshot: &language::BufferSnapshot,
6304 window: &mut Window,
6305 cx: &mut App,
6306 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6307 let edit_start = edits
6308 .first()
6309 .unwrap()
6310 .0
6311 .start
6312 .to_display_point(editor_snapshot);
6313 let edit_end = edits
6314 .last()
6315 .unwrap()
6316 .0
6317 .end
6318 .to_display_point(editor_snapshot);
6319
6320 let is_visible = visible_row_range.contains(&edit_start.row())
6321 || visible_row_range.contains(&edit_end.row());
6322 if !is_visible {
6323 return None;
6324 }
6325
6326 let highlighted_edits =
6327 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6328
6329 let styled_text = highlighted_edits.to_styled_text(&style.text);
6330 let line_count = highlighted_edits.text.lines().count();
6331
6332 const BORDER_WIDTH: Pixels = px(1.);
6333
6334 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6335 let has_keybind = keybind.is_some();
6336
6337 let mut element = h_flex()
6338 .items_start()
6339 .child(
6340 h_flex()
6341 .bg(cx.theme().colors().editor_background)
6342 .border(BORDER_WIDTH)
6343 .shadow_sm()
6344 .border_color(cx.theme().colors().border)
6345 .rounded_l_lg()
6346 .when(line_count > 1, |el| el.rounded_br_lg())
6347 .pr_1()
6348 .child(styled_text),
6349 )
6350 .child(
6351 h_flex()
6352 .h(line_height + BORDER_WIDTH * px(2.))
6353 .px_1p5()
6354 .gap_1()
6355 // Workaround: For some reason, there's a gap if we don't do this
6356 .ml(-BORDER_WIDTH)
6357 .shadow(smallvec![gpui::BoxShadow {
6358 color: gpui::black().opacity(0.05),
6359 offset: point(px(1.), px(1.)),
6360 blur_radius: px(2.),
6361 spread_radius: px(0.),
6362 }])
6363 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6364 .border(BORDER_WIDTH)
6365 .border_color(cx.theme().colors().border)
6366 .rounded_r_lg()
6367 .id("edit_prediction_diff_popover_keybind")
6368 .when(!has_keybind, |el| {
6369 let status_colors = cx.theme().status();
6370
6371 el.bg(status_colors.error_background)
6372 .border_color(status_colors.error.opacity(0.6))
6373 .child(Icon::new(IconName::Info).color(Color::Error))
6374 .cursor_default()
6375 .hoverable_tooltip(move |_window, cx| {
6376 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6377 })
6378 })
6379 .children(keybind),
6380 )
6381 .into_any();
6382
6383 let longest_row =
6384 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6385 let longest_line_width = if visible_row_range.contains(&longest_row) {
6386 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6387 } else {
6388 layout_line(
6389 longest_row,
6390 editor_snapshot,
6391 style,
6392 editor_width,
6393 |_| false,
6394 window,
6395 cx,
6396 )
6397 .width
6398 };
6399
6400 let viewport_bounds =
6401 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6402 right: -EditorElement::SCROLLBAR_WIDTH,
6403 ..Default::default()
6404 });
6405
6406 let x_after_longest =
6407 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6408 - scroll_pixel_position.x;
6409
6410 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6411
6412 // Fully visible if it can be displayed within the window (allow overlapping other
6413 // panes). However, this is only allowed if the popover starts within text_bounds.
6414 let can_position_to_the_right = x_after_longest < text_bounds.right()
6415 && x_after_longest + element_bounds.width < viewport_bounds.right();
6416
6417 let mut origin = if can_position_to_the_right {
6418 point(
6419 x_after_longest,
6420 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6421 - scroll_pixel_position.y,
6422 )
6423 } else {
6424 let cursor_row = newest_selection_head.map(|head| head.row());
6425 let above_edit = edit_start
6426 .row()
6427 .0
6428 .checked_sub(line_count as u32)
6429 .map(DisplayRow);
6430 let below_edit = Some(edit_end.row() + 1);
6431 let above_cursor =
6432 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6433 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6434
6435 // Place the edit popover adjacent to the edit if there is a location
6436 // available that is onscreen and does not obscure the cursor. Otherwise,
6437 // place it adjacent to the cursor.
6438 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6439 .into_iter()
6440 .flatten()
6441 .find(|&start_row| {
6442 let end_row = start_row + line_count as u32;
6443 visible_row_range.contains(&start_row)
6444 && visible_row_range.contains(&end_row)
6445 && cursor_row.map_or(true, |cursor_row| {
6446 !((start_row..end_row).contains(&cursor_row))
6447 })
6448 })?;
6449
6450 content_origin
6451 + point(
6452 -scroll_pixel_position.x,
6453 row_target.as_f32() * line_height - scroll_pixel_position.y,
6454 )
6455 };
6456
6457 origin.x -= BORDER_WIDTH;
6458
6459 window.defer_draw(element, origin, 1);
6460
6461 // Do not return an element, since it will already be drawn due to defer_draw.
6462 None
6463 }
6464
6465 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6466 px(30.)
6467 }
6468
6469 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6470 if self.read_only(cx) {
6471 cx.theme().players().read_only()
6472 } else {
6473 self.style.as_ref().unwrap().local_player
6474 }
6475 }
6476
6477 fn render_edit_prediction_accept_keybind(
6478 &self,
6479 window: &mut Window,
6480 cx: &App,
6481 ) -> Option<AnyElement> {
6482 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6483 let accept_keystroke = accept_binding.keystroke()?;
6484
6485 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6486
6487 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6488 Color::Accent
6489 } else {
6490 Color::Muted
6491 };
6492
6493 h_flex()
6494 .px_0p5()
6495 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6496 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6497 .text_size(TextSize::XSmall.rems(cx))
6498 .child(h_flex().children(ui::render_modifiers(
6499 &accept_keystroke.modifiers,
6500 PlatformStyle::platform(),
6501 Some(modifiers_color),
6502 Some(IconSize::XSmall.rems().into()),
6503 true,
6504 )))
6505 .when(is_platform_style_mac, |parent| {
6506 parent.child(accept_keystroke.key.clone())
6507 })
6508 .when(!is_platform_style_mac, |parent| {
6509 parent.child(
6510 Key::new(
6511 util::capitalize(&accept_keystroke.key),
6512 Some(Color::Default),
6513 )
6514 .size(Some(IconSize::XSmall.rems().into())),
6515 )
6516 })
6517 .into_any()
6518 .into()
6519 }
6520
6521 fn render_edit_prediction_line_popover(
6522 &self,
6523 label: impl Into<SharedString>,
6524 icon: Option<IconName>,
6525 window: &mut Window,
6526 cx: &App,
6527 ) -> Option<Stateful<Div>> {
6528 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6529
6530 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6531 let has_keybind = keybind.is_some();
6532
6533 let result = h_flex()
6534 .id("ep-line-popover")
6535 .py_0p5()
6536 .pl_1()
6537 .pr(padding_right)
6538 .gap_1()
6539 .rounded(px(6.))
6540 .border_1()
6541 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6542 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6543 .shadow_sm()
6544 .when(!has_keybind, |el| {
6545 let status_colors = cx.theme().status();
6546
6547 el.bg(status_colors.error_background)
6548 .border_color(status_colors.error.opacity(0.6))
6549 .pl_2()
6550 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
6551 .cursor_default()
6552 .hoverable_tooltip(move |_window, cx| {
6553 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6554 })
6555 })
6556 .children(keybind)
6557 .child(
6558 Label::new(label)
6559 .size(LabelSize::Small)
6560 .when(!has_keybind, |el| {
6561 el.color(cx.theme().status().error.into()).strikethrough()
6562 }),
6563 )
6564 .when(!has_keybind, |el| {
6565 el.child(
6566 h_flex().ml_1().child(
6567 Icon::new(IconName::Info)
6568 .size(IconSize::Small)
6569 .color(cx.theme().status().error.into()),
6570 ),
6571 )
6572 })
6573 .when_some(icon, |element, icon| {
6574 element.child(
6575 div()
6576 .mt(px(1.5))
6577 .child(Icon::new(icon).size(IconSize::Small)),
6578 )
6579 });
6580
6581 Some(result)
6582 }
6583
6584 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6585 let accent_color = cx.theme().colors().text_accent;
6586 let editor_bg_color = cx.theme().colors().editor_background;
6587 editor_bg_color.blend(accent_color.opacity(0.1))
6588 }
6589
6590 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6591 let accent_color = cx.theme().colors().text_accent;
6592 let editor_bg_color = cx.theme().colors().editor_background;
6593 editor_bg_color.blend(accent_color.opacity(0.6))
6594 }
6595
6596 #[allow(clippy::too_many_arguments)]
6597 fn render_edit_prediction_cursor_popover(
6598 &self,
6599 min_width: Pixels,
6600 max_width: Pixels,
6601 cursor_point: Point,
6602 style: &EditorStyle,
6603 accept_keystroke: Option<&gpui::Keystroke>,
6604 _window: &Window,
6605 cx: &mut Context<Editor>,
6606 ) -> Option<AnyElement> {
6607 let provider = self.edit_prediction_provider.as_ref()?;
6608
6609 if provider.provider.needs_terms_acceptance(cx) {
6610 return Some(
6611 h_flex()
6612 .min_w(min_width)
6613 .flex_1()
6614 .px_2()
6615 .py_1()
6616 .gap_3()
6617 .elevation_2(cx)
6618 .hover(|style| style.bg(cx.theme().colors().element_hover))
6619 .id("accept-terms")
6620 .cursor_pointer()
6621 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6622 .on_click(cx.listener(|this, _event, window, cx| {
6623 cx.stop_propagation();
6624 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6625 window.dispatch_action(
6626 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6627 cx,
6628 );
6629 }))
6630 .child(
6631 h_flex()
6632 .flex_1()
6633 .gap_2()
6634 .child(Icon::new(IconName::ZedPredict))
6635 .child(Label::new("Accept Terms of Service"))
6636 .child(div().w_full())
6637 .child(
6638 Icon::new(IconName::ArrowUpRight)
6639 .color(Color::Muted)
6640 .size(IconSize::Small),
6641 )
6642 .into_any_element(),
6643 )
6644 .into_any(),
6645 );
6646 }
6647
6648 let is_refreshing = provider.provider.is_refreshing(cx);
6649
6650 fn pending_completion_container() -> Div {
6651 h_flex()
6652 .h_full()
6653 .flex_1()
6654 .gap_2()
6655 .child(Icon::new(IconName::ZedPredict))
6656 }
6657
6658 let completion = match &self.active_inline_completion {
6659 Some(prediction) => {
6660 if !self.has_visible_completions_menu() {
6661 const RADIUS: Pixels = px(6.);
6662 const BORDER_WIDTH: Pixels = px(1.);
6663
6664 return Some(
6665 h_flex()
6666 .elevation_2(cx)
6667 .border(BORDER_WIDTH)
6668 .border_color(cx.theme().colors().border)
6669 .when(accept_keystroke.is_none(), |el| {
6670 el.border_color(cx.theme().status().error)
6671 })
6672 .rounded(RADIUS)
6673 .rounded_tl(px(0.))
6674 .overflow_hidden()
6675 .child(div().px_1p5().child(match &prediction.completion {
6676 InlineCompletion::Move { target, snapshot } => {
6677 use text::ToPoint as _;
6678 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6679 {
6680 Icon::new(IconName::ZedPredictDown)
6681 } else {
6682 Icon::new(IconName::ZedPredictUp)
6683 }
6684 }
6685 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6686 }))
6687 .child(
6688 h_flex()
6689 .gap_1()
6690 .py_1()
6691 .px_2()
6692 .rounded_r(RADIUS - BORDER_WIDTH)
6693 .border_l_1()
6694 .border_color(cx.theme().colors().border)
6695 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6696 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6697 el.child(
6698 Label::new("Hold")
6699 .size(LabelSize::Small)
6700 .when(accept_keystroke.is_none(), |el| {
6701 el.strikethrough()
6702 })
6703 .line_height_style(LineHeightStyle::UiLabel),
6704 )
6705 })
6706 .id("edit_prediction_cursor_popover_keybind")
6707 .when(accept_keystroke.is_none(), |el| {
6708 let status_colors = cx.theme().status();
6709
6710 el.bg(status_colors.error_background)
6711 .border_color(status_colors.error.opacity(0.6))
6712 .child(Icon::new(IconName::Info).color(Color::Error))
6713 .cursor_default()
6714 .hoverable_tooltip(move |_window, cx| {
6715 cx.new(|_| MissingEditPredictionKeybindingTooltip)
6716 .into()
6717 })
6718 })
6719 .when_some(
6720 accept_keystroke.as_ref(),
6721 |el, accept_keystroke| {
6722 el.child(h_flex().children(ui::render_modifiers(
6723 &accept_keystroke.modifiers,
6724 PlatformStyle::platform(),
6725 Some(Color::Default),
6726 Some(IconSize::XSmall.rems().into()),
6727 false,
6728 )))
6729 },
6730 ),
6731 )
6732 .into_any(),
6733 );
6734 }
6735
6736 self.render_edit_prediction_cursor_popover_preview(
6737 prediction,
6738 cursor_point,
6739 style,
6740 cx,
6741 )?
6742 }
6743
6744 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6745 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6746 stale_completion,
6747 cursor_point,
6748 style,
6749 cx,
6750 )?,
6751
6752 None => {
6753 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6754 }
6755 },
6756
6757 None => pending_completion_container().child(Label::new("No Prediction")),
6758 };
6759
6760 let completion = if is_refreshing {
6761 completion
6762 .with_animation(
6763 "loading-completion",
6764 Animation::new(Duration::from_secs(2))
6765 .repeat()
6766 .with_easing(pulsating_between(0.4, 0.8)),
6767 |label, delta| label.opacity(delta),
6768 )
6769 .into_any_element()
6770 } else {
6771 completion.into_any_element()
6772 };
6773
6774 let has_completion = self.active_inline_completion.is_some();
6775
6776 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6777 Some(
6778 h_flex()
6779 .min_w(min_width)
6780 .max_w(max_width)
6781 .flex_1()
6782 .elevation_2(cx)
6783 .border_color(cx.theme().colors().border)
6784 .child(
6785 div()
6786 .flex_1()
6787 .py_1()
6788 .px_2()
6789 .overflow_hidden()
6790 .child(completion),
6791 )
6792 .when_some(accept_keystroke, |el, accept_keystroke| {
6793 if !accept_keystroke.modifiers.modified() {
6794 return el;
6795 }
6796
6797 el.child(
6798 h_flex()
6799 .h_full()
6800 .border_l_1()
6801 .rounded_r_lg()
6802 .border_color(cx.theme().colors().border)
6803 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6804 .gap_1()
6805 .py_1()
6806 .px_2()
6807 .child(
6808 h_flex()
6809 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6810 .when(is_platform_style_mac, |parent| parent.gap_1())
6811 .child(h_flex().children(ui::render_modifiers(
6812 &accept_keystroke.modifiers,
6813 PlatformStyle::platform(),
6814 Some(if !has_completion {
6815 Color::Muted
6816 } else {
6817 Color::Default
6818 }),
6819 None,
6820 false,
6821 ))),
6822 )
6823 .child(Label::new("Preview").into_any_element())
6824 .opacity(if has_completion { 1.0 } else { 0.4 }),
6825 )
6826 })
6827 .into_any(),
6828 )
6829 }
6830
6831 fn render_edit_prediction_cursor_popover_preview(
6832 &self,
6833 completion: &InlineCompletionState,
6834 cursor_point: Point,
6835 style: &EditorStyle,
6836 cx: &mut Context<Editor>,
6837 ) -> Option<Div> {
6838 use text::ToPoint as _;
6839
6840 fn render_relative_row_jump(
6841 prefix: impl Into<String>,
6842 current_row: u32,
6843 target_row: u32,
6844 ) -> Div {
6845 let (row_diff, arrow) = if target_row < current_row {
6846 (current_row - target_row, IconName::ArrowUp)
6847 } else {
6848 (target_row - current_row, IconName::ArrowDown)
6849 };
6850
6851 h_flex()
6852 .child(
6853 Label::new(format!("{}{}", prefix.into(), row_diff))
6854 .color(Color::Muted)
6855 .size(LabelSize::Small),
6856 )
6857 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6858 }
6859
6860 match &completion.completion {
6861 InlineCompletion::Move {
6862 target, snapshot, ..
6863 } => Some(
6864 h_flex()
6865 .px_2()
6866 .gap_2()
6867 .flex_1()
6868 .child(
6869 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6870 Icon::new(IconName::ZedPredictDown)
6871 } else {
6872 Icon::new(IconName::ZedPredictUp)
6873 },
6874 )
6875 .child(Label::new("Jump to Edit")),
6876 ),
6877
6878 InlineCompletion::Edit {
6879 edits,
6880 edit_preview,
6881 snapshot,
6882 display_mode: _,
6883 } => {
6884 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6885
6886 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6887 &snapshot,
6888 &edits,
6889 edit_preview.as_ref()?,
6890 true,
6891 cx,
6892 )
6893 .first_line_preview();
6894
6895 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6896 .with_default_highlights(&style.text, highlighted_edits.highlights);
6897
6898 let preview = h_flex()
6899 .gap_1()
6900 .min_w_16()
6901 .child(styled_text)
6902 .when(has_more_lines, |parent| parent.child("…"));
6903
6904 let left = if first_edit_row != cursor_point.row {
6905 render_relative_row_jump("", cursor_point.row, first_edit_row)
6906 .into_any_element()
6907 } else {
6908 Icon::new(IconName::ZedPredict).into_any_element()
6909 };
6910
6911 Some(
6912 h_flex()
6913 .h_full()
6914 .flex_1()
6915 .gap_2()
6916 .pr_1()
6917 .overflow_x_hidden()
6918 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6919 .child(left)
6920 .child(preview),
6921 )
6922 }
6923 }
6924 }
6925
6926 fn render_context_menu(
6927 &self,
6928 style: &EditorStyle,
6929 max_height_in_lines: u32,
6930 y_flipped: bool,
6931 window: &mut Window,
6932 cx: &mut Context<Editor>,
6933 ) -> Option<AnyElement> {
6934 let menu = self.context_menu.borrow();
6935 let menu = menu.as_ref()?;
6936 if !menu.visible() {
6937 return None;
6938 };
6939 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6940 }
6941
6942 fn render_context_menu_aside(
6943 &mut self,
6944 max_size: Size<Pixels>,
6945 window: &mut Window,
6946 cx: &mut Context<Editor>,
6947 ) -> Option<AnyElement> {
6948 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6949 if menu.visible() {
6950 menu.render_aside(self, max_size, window, cx)
6951 } else {
6952 None
6953 }
6954 })
6955 }
6956
6957 fn hide_context_menu(
6958 &mut self,
6959 window: &mut Window,
6960 cx: &mut Context<Self>,
6961 ) -> Option<CodeContextMenu> {
6962 cx.notify();
6963 self.completion_tasks.clear();
6964 let context_menu = self.context_menu.borrow_mut().take();
6965 self.stale_inline_completion_in_menu.take();
6966 self.update_visible_inline_completion(window, cx);
6967 context_menu
6968 }
6969
6970 fn show_snippet_choices(
6971 &mut self,
6972 choices: &Vec<String>,
6973 selection: Range<Anchor>,
6974 cx: &mut Context<Self>,
6975 ) {
6976 if selection.start.buffer_id.is_none() {
6977 return;
6978 }
6979 let buffer_id = selection.start.buffer_id.unwrap();
6980 let buffer = self.buffer().read(cx).buffer(buffer_id);
6981 let id = post_inc(&mut self.next_completion_id);
6982
6983 if let Some(buffer) = buffer {
6984 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6985 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6986 ));
6987 }
6988 }
6989
6990 pub fn insert_snippet(
6991 &mut self,
6992 insertion_ranges: &[Range<usize>],
6993 snippet: Snippet,
6994 window: &mut Window,
6995 cx: &mut Context<Self>,
6996 ) -> Result<()> {
6997 struct Tabstop<T> {
6998 is_end_tabstop: bool,
6999 ranges: Vec<Range<T>>,
7000 choices: Option<Vec<String>>,
7001 }
7002
7003 let tabstops = self.buffer.update(cx, |buffer, cx| {
7004 let snippet_text: Arc<str> = snippet.text.clone().into();
7005 buffer.edit(
7006 insertion_ranges
7007 .iter()
7008 .cloned()
7009 .map(|range| (range, snippet_text.clone())),
7010 Some(AutoindentMode::EachLine),
7011 cx,
7012 );
7013
7014 let snapshot = &*buffer.read(cx);
7015 let snippet = &snippet;
7016 snippet
7017 .tabstops
7018 .iter()
7019 .map(|tabstop| {
7020 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7021 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7022 });
7023 let mut tabstop_ranges = tabstop
7024 .ranges
7025 .iter()
7026 .flat_map(|tabstop_range| {
7027 let mut delta = 0_isize;
7028 insertion_ranges.iter().map(move |insertion_range| {
7029 let insertion_start = insertion_range.start as isize + delta;
7030 delta +=
7031 snippet.text.len() as isize - insertion_range.len() as isize;
7032
7033 let start = ((insertion_start + tabstop_range.start) as usize)
7034 .min(snapshot.len());
7035 let end = ((insertion_start + tabstop_range.end) as usize)
7036 .min(snapshot.len());
7037 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7038 })
7039 })
7040 .collect::<Vec<_>>();
7041 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7042
7043 Tabstop {
7044 is_end_tabstop,
7045 ranges: tabstop_ranges,
7046 choices: tabstop.choices.clone(),
7047 }
7048 })
7049 .collect::<Vec<_>>()
7050 });
7051 if let Some(tabstop) = tabstops.first() {
7052 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7053 s.select_ranges(tabstop.ranges.iter().cloned());
7054 });
7055
7056 if let Some(choices) = &tabstop.choices {
7057 if let Some(selection) = tabstop.ranges.first() {
7058 self.show_snippet_choices(choices, selection.clone(), cx)
7059 }
7060 }
7061
7062 // If we're already at the last tabstop and it's at the end of the snippet,
7063 // we're done, we don't need to keep the state around.
7064 if !tabstop.is_end_tabstop {
7065 let choices = tabstops
7066 .iter()
7067 .map(|tabstop| tabstop.choices.clone())
7068 .collect();
7069
7070 let ranges = tabstops
7071 .into_iter()
7072 .map(|tabstop| tabstop.ranges)
7073 .collect::<Vec<_>>();
7074
7075 self.snippet_stack.push(SnippetState {
7076 active_index: 0,
7077 ranges,
7078 choices,
7079 });
7080 }
7081
7082 // Check whether the just-entered snippet ends with an auto-closable bracket.
7083 if self.autoclose_regions.is_empty() {
7084 let snapshot = self.buffer.read(cx).snapshot(cx);
7085 for selection in &mut self.selections.all::<Point>(cx) {
7086 let selection_head = selection.head();
7087 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7088 continue;
7089 };
7090
7091 let mut bracket_pair = None;
7092 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7093 let prev_chars = snapshot
7094 .reversed_chars_at(selection_head)
7095 .collect::<String>();
7096 for (pair, enabled) in scope.brackets() {
7097 if enabled
7098 && pair.close
7099 && prev_chars.starts_with(pair.start.as_str())
7100 && next_chars.starts_with(pair.end.as_str())
7101 {
7102 bracket_pair = Some(pair.clone());
7103 break;
7104 }
7105 }
7106 if let Some(pair) = bracket_pair {
7107 let start = snapshot.anchor_after(selection_head);
7108 let end = snapshot.anchor_after(selection_head);
7109 self.autoclose_regions.push(AutocloseRegion {
7110 selection_id: selection.id,
7111 range: start..end,
7112 pair,
7113 });
7114 }
7115 }
7116 }
7117 }
7118 Ok(())
7119 }
7120
7121 pub fn move_to_next_snippet_tabstop(
7122 &mut self,
7123 window: &mut Window,
7124 cx: &mut Context<Self>,
7125 ) -> bool {
7126 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7127 }
7128
7129 pub fn move_to_prev_snippet_tabstop(
7130 &mut self,
7131 window: &mut Window,
7132 cx: &mut Context<Self>,
7133 ) -> bool {
7134 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7135 }
7136
7137 pub fn move_to_snippet_tabstop(
7138 &mut self,
7139 bias: Bias,
7140 window: &mut Window,
7141 cx: &mut Context<Self>,
7142 ) -> bool {
7143 if let Some(mut snippet) = self.snippet_stack.pop() {
7144 match bias {
7145 Bias::Left => {
7146 if snippet.active_index > 0 {
7147 snippet.active_index -= 1;
7148 } else {
7149 self.snippet_stack.push(snippet);
7150 return false;
7151 }
7152 }
7153 Bias::Right => {
7154 if snippet.active_index + 1 < snippet.ranges.len() {
7155 snippet.active_index += 1;
7156 } else {
7157 self.snippet_stack.push(snippet);
7158 return false;
7159 }
7160 }
7161 }
7162 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7163 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7164 s.select_anchor_ranges(current_ranges.iter().cloned())
7165 });
7166
7167 if let Some(choices) = &snippet.choices[snippet.active_index] {
7168 if let Some(selection) = current_ranges.first() {
7169 self.show_snippet_choices(&choices, selection.clone(), cx);
7170 }
7171 }
7172
7173 // If snippet state is not at the last tabstop, push it back on the stack
7174 if snippet.active_index + 1 < snippet.ranges.len() {
7175 self.snippet_stack.push(snippet);
7176 }
7177 return true;
7178 }
7179 }
7180
7181 false
7182 }
7183
7184 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7185 self.transact(window, cx, |this, window, cx| {
7186 this.select_all(&SelectAll, window, cx);
7187 this.insert("", window, cx);
7188 });
7189 }
7190
7191 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7192 self.transact(window, cx, |this, window, cx| {
7193 this.select_autoclose_pair(window, cx);
7194 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7195 if !this.linked_edit_ranges.is_empty() {
7196 let selections = this.selections.all::<MultiBufferPoint>(cx);
7197 let snapshot = this.buffer.read(cx).snapshot(cx);
7198
7199 for selection in selections.iter() {
7200 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7201 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7202 if selection_start.buffer_id != selection_end.buffer_id {
7203 continue;
7204 }
7205 if let Some(ranges) =
7206 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7207 {
7208 for (buffer, entries) in ranges {
7209 linked_ranges.entry(buffer).or_default().extend(entries);
7210 }
7211 }
7212 }
7213 }
7214
7215 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7216 if !this.selections.line_mode {
7217 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7218 for selection in &mut selections {
7219 if selection.is_empty() {
7220 let old_head = selection.head();
7221 let mut new_head =
7222 movement::left(&display_map, old_head.to_display_point(&display_map))
7223 .to_point(&display_map);
7224 if let Some((buffer, line_buffer_range)) = display_map
7225 .buffer_snapshot
7226 .buffer_line_for_row(MultiBufferRow(old_head.row))
7227 {
7228 let indent_size =
7229 buffer.indent_size_for_line(line_buffer_range.start.row);
7230 let indent_len = match indent_size.kind {
7231 IndentKind::Space => {
7232 buffer.settings_at(line_buffer_range.start, cx).tab_size
7233 }
7234 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7235 };
7236 if old_head.column <= indent_size.len && old_head.column > 0 {
7237 let indent_len = indent_len.get();
7238 new_head = cmp::min(
7239 new_head,
7240 MultiBufferPoint::new(
7241 old_head.row,
7242 ((old_head.column - 1) / indent_len) * indent_len,
7243 ),
7244 );
7245 }
7246 }
7247
7248 selection.set_head(new_head, SelectionGoal::None);
7249 }
7250 }
7251 }
7252
7253 this.signature_help_state.set_backspace_pressed(true);
7254 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7255 s.select(selections)
7256 });
7257 this.insert("", window, cx);
7258 let empty_str: Arc<str> = Arc::from("");
7259 for (buffer, edits) in linked_ranges {
7260 let snapshot = buffer.read(cx).snapshot();
7261 use text::ToPoint as TP;
7262
7263 let edits = edits
7264 .into_iter()
7265 .map(|range| {
7266 let end_point = TP::to_point(&range.end, &snapshot);
7267 let mut start_point = TP::to_point(&range.start, &snapshot);
7268
7269 if end_point == start_point {
7270 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7271 .saturating_sub(1);
7272 start_point =
7273 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7274 };
7275
7276 (start_point..end_point, empty_str.clone())
7277 })
7278 .sorted_by_key(|(range, _)| range.start)
7279 .collect::<Vec<_>>();
7280 buffer.update(cx, |this, cx| {
7281 this.edit(edits, None, cx);
7282 })
7283 }
7284 this.refresh_inline_completion(true, false, window, cx);
7285 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7286 });
7287 }
7288
7289 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7290 self.transact(window, cx, |this, window, cx| {
7291 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7292 let line_mode = s.line_mode;
7293 s.move_with(|map, selection| {
7294 if selection.is_empty() && !line_mode {
7295 let cursor = movement::right(map, selection.head());
7296 selection.end = cursor;
7297 selection.reversed = true;
7298 selection.goal = SelectionGoal::None;
7299 }
7300 })
7301 });
7302 this.insert("", window, cx);
7303 this.refresh_inline_completion(true, false, window, cx);
7304 });
7305 }
7306
7307 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7308 if self.move_to_prev_snippet_tabstop(window, cx) {
7309 return;
7310 }
7311
7312 self.outdent(&Outdent, window, cx);
7313 }
7314
7315 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7316 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7317 return;
7318 }
7319
7320 let mut selections = self.selections.all_adjusted(cx);
7321 let buffer = self.buffer.read(cx);
7322 let snapshot = buffer.snapshot(cx);
7323 let rows_iter = selections.iter().map(|s| s.head().row);
7324 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7325
7326 let mut edits = Vec::new();
7327 let mut prev_edited_row = 0;
7328 let mut row_delta = 0;
7329 for selection in &mut selections {
7330 if selection.start.row != prev_edited_row {
7331 row_delta = 0;
7332 }
7333 prev_edited_row = selection.end.row;
7334
7335 // If the selection is non-empty, then increase the indentation of the selected lines.
7336 if !selection.is_empty() {
7337 row_delta =
7338 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7339 continue;
7340 }
7341
7342 // If the selection is empty and the cursor is in the leading whitespace before the
7343 // suggested indentation, then auto-indent the line.
7344 let cursor = selection.head();
7345 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7346 if let Some(suggested_indent) =
7347 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7348 {
7349 if cursor.column < suggested_indent.len
7350 && cursor.column <= current_indent.len
7351 && current_indent.len <= suggested_indent.len
7352 {
7353 selection.start = Point::new(cursor.row, suggested_indent.len);
7354 selection.end = selection.start;
7355 if row_delta == 0 {
7356 edits.extend(Buffer::edit_for_indent_size_adjustment(
7357 cursor.row,
7358 current_indent,
7359 suggested_indent,
7360 ));
7361 row_delta = suggested_indent.len - current_indent.len;
7362 }
7363 continue;
7364 }
7365 }
7366
7367 // Otherwise, insert a hard or soft tab.
7368 let settings = buffer.language_settings_at(cursor, cx);
7369 let tab_size = if settings.hard_tabs {
7370 IndentSize::tab()
7371 } else {
7372 let tab_size = settings.tab_size.get();
7373 let char_column = snapshot
7374 .text_for_range(Point::new(cursor.row, 0)..cursor)
7375 .flat_map(str::chars)
7376 .count()
7377 + row_delta as usize;
7378 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7379 IndentSize::spaces(chars_to_next_tab_stop)
7380 };
7381 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7382 selection.end = selection.start;
7383 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7384 row_delta += tab_size.len;
7385 }
7386
7387 self.transact(window, cx, |this, window, cx| {
7388 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7389 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7390 s.select(selections)
7391 });
7392 this.refresh_inline_completion(true, false, window, cx);
7393 });
7394 }
7395
7396 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7397 if self.read_only(cx) {
7398 return;
7399 }
7400 let mut selections = self.selections.all::<Point>(cx);
7401 let mut prev_edited_row = 0;
7402 let mut row_delta = 0;
7403 let mut edits = Vec::new();
7404 let buffer = self.buffer.read(cx);
7405 let snapshot = buffer.snapshot(cx);
7406 for selection in &mut selections {
7407 if selection.start.row != prev_edited_row {
7408 row_delta = 0;
7409 }
7410 prev_edited_row = selection.end.row;
7411
7412 row_delta =
7413 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7414 }
7415
7416 self.transact(window, cx, |this, window, cx| {
7417 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7418 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7419 s.select(selections)
7420 });
7421 });
7422 }
7423
7424 fn indent_selection(
7425 buffer: &MultiBuffer,
7426 snapshot: &MultiBufferSnapshot,
7427 selection: &mut Selection<Point>,
7428 edits: &mut Vec<(Range<Point>, String)>,
7429 delta_for_start_row: u32,
7430 cx: &App,
7431 ) -> u32 {
7432 let settings = buffer.language_settings_at(selection.start, cx);
7433 let tab_size = settings.tab_size.get();
7434 let indent_kind = if settings.hard_tabs {
7435 IndentKind::Tab
7436 } else {
7437 IndentKind::Space
7438 };
7439 let mut start_row = selection.start.row;
7440 let mut end_row = selection.end.row + 1;
7441
7442 // If a selection ends at the beginning of a line, don't indent
7443 // that last line.
7444 if selection.end.column == 0 && selection.end.row > selection.start.row {
7445 end_row -= 1;
7446 }
7447
7448 // Avoid re-indenting a row that has already been indented by a
7449 // previous selection, but still update this selection's column
7450 // to reflect that indentation.
7451 if delta_for_start_row > 0 {
7452 start_row += 1;
7453 selection.start.column += delta_for_start_row;
7454 if selection.end.row == selection.start.row {
7455 selection.end.column += delta_for_start_row;
7456 }
7457 }
7458
7459 let mut delta_for_end_row = 0;
7460 let has_multiple_rows = start_row + 1 != end_row;
7461 for row in start_row..end_row {
7462 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7463 let indent_delta = match (current_indent.kind, indent_kind) {
7464 (IndentKind::Space, IndentKind::Space) => {
7465 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7466 IndentSize::spaces(columns_to_next_tab_stop)
7467 }
7468 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7469 (_, IndentKind::Tab) => IndentSize::tab(),
7470 };
7471
7472 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7473 0
7474 } else {
7475 selection.start.column
7476 };
7477 let row_start = Point::new(row, start);
7478 edits.push((
7479 row_start..row_start,
7480 indent_delta.chars().collect::<String>(),
7481 ));
7482
7483 // Update this selection's endpoints to reflect the indentation.
7484 if row == selection.start.row {
7485 selection.start.column += indent_delta.len;
7486 }
7487 if row == selection.end.row {
7488 selection.end.column += indent_delta.len;
7489 delta_for_end_row = indent_delta.len;
7490 }
7491 }
7492
7493 if selection.start.row == selection.end.row {
7494 delta_for_start_row + delta_for_end_row
7495 } else {
7496 delta_for_end_row
7497 }
7498 }
7499
7500 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7501 if self.read_only(cx) {
7502 return;
7503 }
7504 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7505 let selections = self.selections.all::<Point>(cx);
7506 let mut deletion_ranges = Vec::new();
7507 let mut last_outdent = None;
7508 {
7509 let buffer = self.buffer.read(cx);
7510 let snapshot = buffer.snapshot(cx);
7511 for selection in &selections {
7512 let settings = buffer.language_settings_at(selection.start, cx);
7513 let tab_size = settings.tab_size.get();
7514 let mut rows = selection.spanned_rows(false, &display_map);
7515
7516 // Avoid re-outdenting a row that has already been outdented by a
7517 // previous selection.
7518 if let Some(last_row) = last_outdent {
7519 if last_row == rows.start {
7520 rows.start = rows.start.next_row();
7521 }
7522 }
7523 let has_multiple_rows = rows.len() > 1;
7524 for row in rows.iter_rows() {
7525 let indent_size = snapshot.indent_size_for_line(row);
7526 if indent_size.len > 0 {
7527 let deletion_len = match indent_size.kind {
7528 IndentKind::Space => {
7529 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7530 if columns_to_prev_tab_stop == 0 {
7531 tab_size
7532 } else {
7533 columns_to_prev_tab_stop
7534 }
7535 }
7536 IndentKind::Tab => 1,
7537 };
7538 let start = if has_multiple_rows
7539 || deletion_len > selection.start.column
7540 || indent_size.len < selection.start.column
7541 {
7542 0
7543 } else {
7544 selection.start.column - deletion_len
7545 };
7546 deletion_ranges.push(
7547 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7548 );
7549 last_outdent = Some(row);
7550 }
7551 }
7552 }
7553 }
7554
7555 self.transact(window, cx, |this, window, cx| {
7556 this.buffer.update(cx, |buffer, cx| {
7557 let empty_str: Arc<str> = Arc::default();
7558 buffer.edit(
7559 deletion_ranges
7560 .into_iter()
7561 .map(|range| (range, empty_str.clone())),
7562 None,
7563 cx,
7564 );
7565 });
7566 let selections = this.selections.all::<usize>(cx);
7567 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7568 s.select(selections)
7569 });
7570 });
7571 }
7572
7573 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7574 if self.read_only(cx) {
7575 return;
7576 }
7577 let selections = self
7578 .selections
7579 .all::<usize>(cx)
7580 .into_iter()
7581 .map(|s| s.range());
7582
7583 self.transact(window, cx, |this, window, cx| {
7584 this.buffer.update(cx, |buffer, cx| {
7585 buffer.autoindent_ranges(selections, cx);
7586 });
7587 let selections = this.selections.all::<usize>(cx);
7588 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7589 s.select(selections)
7590 });
7591 });
7592 }
7593
7594 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7595 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7596 let selections = self.selections.all::<Point>(cx);
7597
7598 let mut new_cursors = Vec::new();
7599 let mut edit_ranges = Vec::new();
7600 let mut selections = selections.iter().peekable();
7601 while let Some(selection) = selections.next() {
7602 let mut rows = selection.spanned_rows(false, &display_map);
7603 let goal_display_column = selection.head().to_display_point(&display_map).column();
7604
7605 // Accumulate contiguous regions of rows that we want to delete.
7606 while let Some(next_selection) = selections.peek() {
7607 let next_rows = next_selection.spanned_rows(false, &display_map);
7608 if next_rows.start <= rows.end {
7609 rows.end = next_rows.end;
7610 selections.next().unwrap();
7611 } else {
7612 break;
7613 }
7614 }
7615
7616 let buffer = &display_map.buffer_snapshot;
7617 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7618 let edit_end;
7619 let cursor_buffer_row;
7620 if buffer.max_point().row >= rows.end.0 {
7621 // If there's a line after the range, delete the \n from the end of the row range
7622 // and position the cursor on the next line.
7623 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7624 cursor_buffer_row = rows.end;
7625 } else {
7626 // If there isn't a line after the range, delete the \n from the line before the
7627 // start of the row range and position the cursor there.
7628 edit_start = edit_start.saturating_sub(1);
7629 edit_end = buffer.len();
7630 cursor_buffer_row = rows.start.previous_row();
7631 }
7632
7633 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7634 *cursor.column_mut() =
7635 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7636
7637 new_cursors.push((
7638 selection.id,
7639 buffer.anchor_after(cursor.to_point(&display_map)),
7640 ));
7641 edit_ranges.push(edit_start..edit_end);
7642 }
7643
7644 self.transact(window, cx, |this, window, cx| {
7645 let buffer = this.buffer.update(cx, |buffer, cx| {
7646 let empty_str: Arc<str> = Arc::default();
7647 buffer.edit(
7648 edit_ranges
7649 .into_iter()
7650 .map(|range| (range, empty_str.clone())),
7651 None,
7652 cx,
7653 );
7654 buffer.snapshot(cx)
7655 });
7656 let new_selections = new_cursors
7657 .into_iter()
7658 .map(|(id, cursor)| {
7659 let cursor = cursor.to_point(&buffer);
7660 Selection {
7661 id,
7662 start: cursor,
7663 end: cursor,
7664 reversed: false,
7665 goal: SelectionGoal::None,
7666 }
7667 })
7668 .collect();
7669
7670 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7671 s.select(new_selections);
7672 });
7673 });
7674 }
7675
7676 pub fn join_lines_impl(
7677 &mut self,
7678 insert_whitespace: bool,
7679 window: &mut Window,
7680 cx: &mut Context<Self>,
7681 ) {
7682 if self.read_only(cx) {
7683 return;
7684 }
7685 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7686 for selection in self.selections.all::<Point>(cx) {
7687 let start = MultiBufferRow(selection.start.row);
7688 // Treat single line selections as if they include the next line. Otherwise this action
7689 // would do nothing for single line selections individual cursors.
7690 let end = if selection.start.row == selection.end.row {
7691 MultiBufferRow(selection.start.row + 1)
7692 } else {
7693 MultiBufferRow(selection.end.row)
7694 };
7695
7696 if let Some(last_row_range) = row_ranges.last_mut() {
7697 if start <= last_row_range.end {
7698 last_row_range.end = end;
7699 continue;
7700 }
7701 }
7702 row_ranges.push(start..end);
7703 }
7704
7705 let snapshot = self.buffer.read(cx).snapshot(cx);
7706 let mut cursor_positions = Vec::new();
7707 for row_range in &row_ranges {
7708 let anchor = snapshot.anchor_before(Point::new(
7709 row_range.end.previous_row().0,
7710 snapshot.line_len(row_range.end.previous_row()),
7711 ));
7712 cursor_positions.push(anchor..anchor);
7713 }
7714
7715 self.transact(window, cx, |this, window, cx| {
7716 for row_range in row_ranges.into_iter().rev() {
7717 for row in row_range.iter_rows().rev() {
7718 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7719 let next_line_row = row.next_row();
7720 let indent = snapshot.indent_size_for_line(next_line_row);
7721 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7722
7723 let replace =
7724 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7725 " "
7726 } else {
7727 ""
7728 };
7729
7730 this.buffer.update(cx, |buffer, cx| {
7731 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7732 });
7733 }
7734 }
7735
7736 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7737 s.select_anchor_ranges(cursor_positions)
7738 });
7739 });
7740 }
7741
7742 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7743 self.join_lines_impl(true, window, cx);
7744 }
7745
7746 pub fn sort_lines_case_sensitive(
7747 &mut self,
7748 _: &SortLinesCaseSensitive,
7749 window: &mut Window,
7750 cx: &mut Context<Self>,
7751 ) {
7752 self.manipulate_lines(window, cx, |lines| lines.sort())
7753 }
7754
7755 pub fn sort_lines_case_insensitive(
7756 &mut self,
7757 _: &SortLinesCaseInsensitive,
7758 window: &mut Window,
7759 cx: &mut Context<Self>,
7760 ) {
7761 self.manipulate_lines(window, cx, |lines| {
7762 lines.sort_by_key(|line| line.to_lowercase())
7763 })
7764 }
7765
7766 pub fn unique_lines_case_insensitive(
7767 &mut self,
7768 _: &UniqueLinesCaseInsensitive,
7769 window: &mut Window,
7770 cx: &mut Context<Self>,
7771 ) {
7772 self.manipulate_lines(window, cx, |lines| {
7773 let mut seen = HashSet::default();
7774 lines.retain(|line| seen.insert(line.to_lowercase()));
7775 })
7776 }
7777
7778 pub fn unique_lines_case_sensitive(
7779 &mut self,
7780 _: &UniqueLinesCaseSensitive,
7781 window: &mut Window,
7782 cx: &mut Context<Self>,
7783 ) {
7784 self.manipulate_lines(window, cx, |lines| {
7785 let mut seen = HashSet::default();
7786 lines.retain(|line| seen.insert(*line));
7787 })
7788 }
7789
7790 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7791 let Some(project) = self.project.clone() else {
7792 return;
7793 };
7794 self.reload(project, window, cx)
7795 .detach_and_notify_err(window, cx);
7796 }
7797
7798 pub fn restore_file(
7799 &mut self,
7800 _: &::git::RestoreFile,
7801 window: &mut Window,
7802 cx: &mut Context<Self>,
7803 ) {
7804 let mut buffer_ids = HashSet::default();
7805 let snapshot = self.buffer().read(cx).snapshot(cx);
7806 for selection in self.selections.all::<usize>(cx) {
7807 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7808 }
7809
7810 let buffer = self.buffer().read(cx);
7811 let ranges = buffer_ids
7812 .into_iter()
7813 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7814 .collect::<Vec<_>>();
7815
7816 self.restore_hunks_in_ranges(ranges, window, cx);
7817 }
7818
7819 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7820 let selections = self
7821 .selections
7822 .all(cx)
7823 .into_iter()
7824 .map(|s| s.range())
7825 .collect();
7826 self.restore_hunks_in_ranges(selections, window, cx);
7827 }
7828
7829 fn restore_hunks_in_ranges(
7830 &mut self,
7831 ranges: Vec<Range<Point>>,
7832 window: &mut Window,
7833 cx: &mut Context<Editor>,
7834 ) {
7835 let mut revert_changes = HashMap::default();
7836 let chunk_by = self
7837 .snapshot(window, cx)
7838 .hunks_for_ranges(ranges)
7839 .into_iter()
7840 .chunk_by(|hunk| hunk.buffer_id);
7841 for (buffer_id, hunks) in &chunk_by {
7842 let hunks = hunks.collect::<Vec<_>>();
7843 for hunk in &hunks {
7844 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7845 }
7846 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7847 }
7848 drop(chunk_by);
7849 if !revert_changes.is_empty() {
7850 self.transact(window, cx, |editor, window, cx| {
7851 editor.restore(revert_changes, window, cx);
7852 });
7853 }
7854 }
7855
7856 pub fn open_active_item_in_terminal(
7857 &mut self,
7858 _: &OpenInTerminal,
7859 window: &mut Window,
7860 cx: &mut Context<Self>,
7861 ) {
7862 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7863 let project_path = buffer.read(cx).project_path(cx)?;
7864 let project = self.project.as_ref()?.read(cx);
7865 let entry = project.entry_for_path(&project_path, cx)?;
7866 let parent = match &entry.canonical_path {
7867 Some(canonical_path) => canonical_path.to_path_buf(),
7868 None => project.absolute_path(&project_path, cx)?,
7869 }
7870 .parent()?
7871 .to_path_buf();
7872 Some(parent)
7873 }) {
7874 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7875 }
7876 }
7877
7878 pub fn prepare_restore_change(
7879 &self,
7880 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7881 hunk: &MultiBufferDiffHunk,
7882 cx: &mut App,
7883 ) -> Option<()> {
7884 let buffer = self.buffer.read(cx);
7885 let diff = buffer.diff_for(hunk.buffer_id)?;
7886 let buffer = buffer.buffer(hunk.buffer_id)?;
7887 let buffer = buffer.read(cx);
7888 let original_text = diff
7889 .read(cx)
7890 .base_text()
7891 .as_rope()
7892 .slice(hunk.diff_base_byte_range.clone());
7893 let buffer_snapshot = buffer.snapshot();
7894 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7895 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7896 probe
7897 .0
7898 .start
7899 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7900 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7901 }) {
7902 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7903 Some(())
7904 } else {
7905 None
7906 }
7907 }
7908
7909 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7910 self.manipulate_lines(window, cx, |lines| lines.reverse())
7911 }
7912
7913 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7914 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7915 }
7916
7917 fn manipulate_lines<Fn>(
7918 &mut self,
7919 window: &mut Window,
7920 cx: &mut Context<Self>,
7921 mut callback: Fn,
7922 ) where
7923 Fn: FnMut(&mut Vec<&str>),
7924 {
7925 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7926 let buffer = self.buffer.read(cx).snapshot(cx);
7927
7928 let mut edits = Vec::new();
7929
7930 let selections = self.selections.all::<Point>(cx);
7931 let mut selections = selections.iter().peekable();
7932 let mut contiguous_row_selections = Vec::new();
7933 let mut new_selections = Vec::new();
7934 let mut added_lines = 0;
7935 let mut removed_lines = 0;
7936
7937 while let Some(selection) = selections.next() {
7938 let (start_row, end_row) = consume_contiguous_rows(
7939 &mut contiguous_row_selections,
7940 selection,
7941 &display_map,
7942 &mut selections,
7943 );
7944
7945 let start_point = Point::new(start_row.0, 0);
7946 let end_point = Point::new(
7947 end_row.previous_row().0,
7948 buffer.line_len(end_row.previous_row()),
7949 );
7950 let text = buffer
7951 .text_for_range(start_point..end_point)
7952 .collect::<String>();
7953
7954 let mut lines = text.split('\n').collect_vec();
7955
7956 let lines_before = lines.len();
7957 callback(&mut lines);
7958 let lines_after = lines.len();
7959
7960 edits.push((start_point..end_point, lines.join("\n")));
7961
7962 // Selections must change based on added and removed line count
7963 let start_row =
7964 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7965 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7966 new_selections.push(Selection {
7967 id: selection.id,
7968 start: start_row,
7969 end: end_row,
7970 goal: SelectionGoal::None,
7971 reversed: selection.reversed,
7972 });
7973
7974 if lines_after > lines_before {
7975 added_lines += lines_after - lines_before;
7976 } else if lines_before > lines_after {
7977 removed_lines += lines_before - lines_after;
7978 }
7979 }
7980
7981 self.transact(window, cx, |this, window, cx| {
7982 let buffer = this.buffer.update(cx, |buffer, cx| {
7983 buffer.edit(edits, None, cx);
7984 buffer.snapshot(cx)
7985 });
7986
7987 // Recalculate offsets on newly edited buffer
7988 let new_selections = new_selections
7989 .iter()
7990 .map(|s| {
7991 let start_point = Point::new(s.start.0, 0);
7992 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
7993 Selection {
7994 id: s.id,
7995 start: buffer.point_to_offset(start_point),
7996 end: buffer.point_to_offset(end_point),
7997 goal: s.goal,
7998 reversed: s.reversed,
7999 }
8000 })
8001 .collect();
8002
8003 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8004 s.select(new_selections);
8005 });
8006
8007 this.request_autoscroll(Autoscroll::fit(), cx);
8008 });
8009 }
8010
8011 pub fn convert_to_upper_case(
8012 &mut self,
8013 _: &ConvertToUpperCase,
8014 window: &mut Window,
8015 cx: &mut Context<Self>,
8016 ) {
8017 self.manipulate_text(window, cx, |text| text.to_uppercase())
8018 }
8019
8020 pub fn convert_to_lower_case(
8021 &mut self,
8022 _: &ConvertToLowerCase,
8023 window: &mut Window,
8024 cx: &mut Context<Self>,
8025 ) {
8026 self.manipulate_text(window, cx, |text| text.to_lowercase())
8027 }
8028
8029 pub fn convert_to_title_case(
8030 &mut self,
8031 _: &ConvertToTitleCase,
8032 window: &mut Window,
8033 cx: &mut Context<Self>,
8034 ) {
8035 self.manipulate_text(window, cx, |text| {
8036 text.split('\n')
8037 .map(|line| line.to_case(Case::Title))
8038 .join("\n")
8039 })
8040 }
8041
8042 pub fn convert_to_snake_case(
8043 &mut self,
8044 _: &ConvertToSnakeCase,
8045 window: &mut Window,
8046 cx: &mut Context<Self>,
8047 ) {
8048 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8049 }
8050
8051 pub fn convert_to_kebab_case(
8052 &mut self,
8053 _: &ConvertToKebabCase,
8054 window: &mut Window,
8055 cx: &mut Context<Self>,
8056 ) {
8057 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8058 }
8059
8060 pub fn convert_to_upper_camel_case(
8061 &mut self,
8062 _: &ConvertToUpperCamelCase,
8063 window: &mut Window,
8064 cx: &mut Context<Self>,
8065 ) {
8066 self.manipulate_text(window, cx, |text| {
8067 text.split('\n')
8068 .map(|line| line.to_case(Case::UpperCamel))
8069 .join("\n")
8070 })
8071 }
8072
8073 pub fn convert_to_lower_camel_case(
8074 &mut self,
8075 _: &ConvertToLowerCamelCase,
8076 window: &mut Window,
8077 cx: &mut Context<Self>,
8078 ) {
8079 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8080 }
8081
8082 pub fn convert_to_opposite_case(
8083 &mut self,
8084 _: &ConvertToOppositeCase,
8085 window: &mut Window,
8086 cx: &mut Context<Self>,
8087 ) {
8088 self.manipulate_text(window, cx, |text| {
8089 text.chars()
8090 .fold(String::with_capacity(text.len()), |mut t, c| {
8091 if c.is_uppercase() {
8092 t.extend(c.to_lowercase());
8093 } else {
8094 t.extend(c.to_uppercase());
8095 }
8096 t
8097 })
8098 })
8099 }
8100
8101 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8102 where
8103 Fn: FnMut(&str) -> String,
8104 {
8105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8106 let buffer = self.buffer.read(cx).snapshot(cx);
8107
8108 let mut new_selections = Vec::new();
8109 let mut edits = Vec::new();
8110 let mut selection_adjustment = 0i32;
8111
8112 for selection in self.selections.all::<usize>(cx) {
8113 let selection_is_empty = selection.is_empty();
8114
8115 let (start, end) = if selection_is_empty {
8116 let word_range = movement::surrounding_word(
8117 &display_map,
8118 selection.start.to_display_point(&display_map),
8119 );
8120 let start = word_range.start.to_offset(&display_map, Bias::Left);
8121 let end = word_range.end.to_offset(&display_map, Bias::Left);
8122 (start, end)
8123 } else {
8124 (selection.start, selection.end)
8125 };
8126
8127 let text = buffer.text_for_range(start..end).collect::<String>();
8128 let old_length = text.len() as i32;
8129 let text = callback(&text);
8130
8131 new_selections.push(Selection {
8132 start: (start as i32 - selection_adjustment) as usize,
8133 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8134 goal: SelectionGoal::None,
8135 ..selection
8136 });
8137
8138 selection_adjustment += old_length - text.len() as i32;
8139
8140 edits.push((start..end, text));
8141 }
8142
8143 self.transact(window, cx, |this, window, cx| {
8144 this.buffer.update(cx, |buffer, cx| {
8145 buffer.edit(edits, None, cx);
8146 });
8147
8148 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8149 s.select(new_selections);
8150 });
8151
8152 this.request_autoscroll(Autoscroll::fit(), cx);
8153 });
8154 }
8155
8156 pub fn duplicate(
8157 &mut self,
8158 upwards: bool,
8159 whole_lines: bool,
8160 window: &mut Window,
8161 cx: &mut Context<Self>,
8162 ) {
8163 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8164 let buffer = &display_map.buffer_snapshot;
8165 let selections = self.selections.all::<Point>(cx);
8166
8167 let mut edits = Vec::new();
8168 let mut selections_iter = selections.iter().peekable();
8169 while let Some(selection) = selections_iter.next() {
8170 let mut rows = selection.spanned_rows(false, &display_map);
8171 // duplicate line-wise
8172 if whole_lines || selection.start == selection.end {
8173 // Avoid duplicating the same lines twice.
8174 while let Some(next_selection) = selections_iter.peek() {
8175 let next_rows = next_selection.spanned_rows(false, &display_map);
8176 if next_rows.start < rows.end {
8177 rows.end = next_rows.end;
8178 selections_iter.next().unwrap();
8179 } else {
8180 break;
8181 }
8182 }
8183
8184 // Copy the text from the selected row region and splice it either at the start
8185 // or end of the region.
8186 let start = Point::new(rows.start.0, 0);
8187 let end = Point::new(
8188 rows.end.previous_row().0,
8189 buffer.line_len(rows.end.previous_row()),
8190 );
8191 let text = buffer
8192 .text_for_range(start..end)
8193 .chain(Some("\n"))
8194 .collect::<String>();
8195 let insert_location = if upwards {
8196 Point::new(rows.end.0, 0)
8197 } else {
8198 start
8199 };
8200 edits.push((insert_location..insert_location, text));
8201 } else {
8202 // duplicate character-wise
8203 let start = selection.start;
8204 let end = selection.end;
8205 let text = buffer.text_for_range(start..end).collect::<String>();
8206 edits.push((selection.end..selection.end, text));
8207 }
8208 }
8209
8210 self.transact(window, cx, |this, _, cx| {
8211 this.buffer.update(cx, |buffer, cx| {
8212 buffer.edit(edits, None, cx);
8213 });
8214
8215 this.request_autoscroll(Autoscroll::fit(), cx);
8216 });
8217 }
8218
8219 pub fn duplicate_line_up(
8220 &mut self,
8221 _: &DuplicateLineUp,
8222 window: &mut Window,
8223 cx: &mut Context<Self>,
8224 ) {
8225 self.duplicate(true, true, window, cx);
8226 }
8227
8228 pub fn duplicate_line_down(
8229 &mut self,
8230 _: &DuplicateLineDown,
8231 window: &mut Window,
8232 cx: &mut Context<Self>,
8233 ) {
8234 self.duplicate(false, true, window, cx);
8235 }
8236
8237 pub fn duplicate_selection(
8238 &mut self,
8239 _: &DuplicateSelection,
8240 window: &mut Window,
8241 cx: &mut Context<Self>,
8242 ) {
8243 self.duplicate(false, false, window, cx);
8244 }
8245
8246 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8248 let buffer = self.buffer.read(cx).snapshot(cx);
8249
8250 let mut edits = Vec::new();
8251 let mut unfold_ranges = Vec::new();
8252 let mut refold_creases = Vec::new();
8253
8254 let selections = self.selections.all::<Point>(cx);
8255 let mut selections = selections.iter().peekable();
8256 let mut contiguous_row_selections = Vec::new();
8257 let mut new_selections = Vec::new();
8258
8259 while let Some(selection) = selections.next() {
8260 // Find all the selections that span a contiguous row range
8261 let (start_row, end_row) = consume_contiguous_rows(
8262 &mut contiguous_row_selections,
8263 selection,
8264 &display_map,
8265 &mut selections,
8266 );
8267
8268 // Move the text spanned by the row range to be before the line preceding the row range
8269 if start_row.0 > 0 {
8270 let range_to_move = Point::new(
8271 start_row.previous_row().0,
8272 buffer.line_len(start_row.previous_row()),
8273 )
8274 ..Point::new(
8275 end_row.previous_row().0,
8276 buffer.line_len(end_row.previous_row()),
8277 );
8278 let insertion_point = display_map
8279 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8280 .0;
8281
8282 // Don't move lines across excerpts
8283 if buffer
8284 .excerpt_containing(insertion_point..range_to_move.end)
8285 .is_some()
8286 {
8287 let text = buffer
8288 .text_for_range(range_to_move.clone())
8289 .flat_map(|s| s.chars())
8290 .skip(1)
8291 .chain(['\n'])
8292 .collect::<String>();
8293
8294 edits.push((
8295 buffer.anchor_after(range_to_move.start)
8296 ..buffer.anchor_before(range_to_move.end),
8297 String::new(),
8298 ));
8299 let insertion_anchor = buffer.anchor_after(insertion_point);
8300 edits.push((insertion_anchor..insertion_anchor, text));
8301
8302 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8303
8304 // Move selections up
8305 new_selections.extend(contiguous_row_selections.drain(..).map(
8306 |mut selection| {
8307 selection.start.row -= row_delta;
8308 selection.end.row -= row_delta;
8309 selection
8310 },
8311 ));
8312
8313 // Move folds up
8314 unfold_ranges.push(range_to_move.clone());
8315 for fold in display_map.folds_in_range(
8316 buffer.anchor_before(range_to_move.start)
8317 ..buffer.anchor_after(range_to_move.end),
8318 ) {
8319 let mut start = fold.range.start.to_point(&buffer);
8320 let mut end = fold.range.end.to_point(&buffer);
8321 start.row -= row_delta;
8322 end.row -= row_delta;
8323 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8324 }
8325 }
8326 }
8327
8328 // If we didn't move line(s), preserve the existing selections
8329 new_selections.append(&mut contiguous_row_selections);
8330 }
8331
8332 self.transact(window, cx, |this, window, cx| {
8333 this.unfold_ranges(&unfold_ranges, true, true, cx);
8334 this.buffer.update(cx, |buffer, cx| {
8335 for (range, text) in edits {
8336 buffer.edit([(range, text)], None, cx);
8337 }
8338 });
8339 this.fold_creases(refold_creases, true, window, cx);
8340 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8341 s.select(new_selections);
8342 })
8343 });
8344 }
8345
8346 pub fn move_line_down(
8347 &mut self,
8348 _: &MoveLineDown,
8349 window: &mut Window,
8350 cx: &mut Context<Self>,
8351 ) {
8352 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8353 let buffer = self.buffer.read(cx).snapshot(cx);
8354
8355 let mut edits = Vec::new();
8356 let mut unfold_ranges = Vec::new();
8357 let mut refold_creases = Vec::new();
8358
8359 let selections = self.selections.all::<Point>(cx);
8360 let mut selections = selections.iter().peekable();
8361 let mut contiguous_row_selections = Vec::new();
8362 let mut new_selections = Vec::new();
8363
8364 while let Some(selection) = selections.next() {
8365 // Find all the selections that span a contiguous row range
8366 let (start_row, end_row) = consume_contiguous_rows(
8367 &mut contiguous_row_selections,
8368 selection,
8369 &display_map,
8370 &mut selections,
8371 );
8372
8373 // Move the text spanned by the row range to be after the last line of the row range
8374 if end_row.0 <= buffer.max_point().row {
8375 let range_to_move =
8376 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8377 let insertion_point = display_map
8378 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8379 .0;
8380
8381 // Don't move lines across excerpt boundaries
8382 if buffer
8383 .excerpt_containing(range_to_move.start..insertion_point)
8384 .is_some()
8385 {
8386 let mut text = String::from("\n");
8387 text.extend(buffer.text_for_range(range_to_move.clone()));
8388 text.pop(); // Drop trailing newline
8389 edits.push((
8390 buffer.anchor_after(range_to_move.start)
8391 ..buffer.anchor_before(range_to_move.end),
8392 String::new(),
8393 ));
8394 let insertion_anchor = buffer.anchor_after(insertion_point);
8395 edits.push((insertion_anchor..insertion_anchor, text));
8396
8397 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8398
8399 // Move selections down
8400 new_selections.extend(contiguous_row_selections.drain(..).map(
8401 |mut selection| {
8402 selection.start.row += row_delta;
8403 selection.end.row += row_delta;
8404 selection
8405 },
8406 ));
8407
8408 // Move folds down
8409 unfold_ranges.push(range_to_move.clone());
8410 for fold in display_map.folds_in_range(
8411 buffer.anchor_before(range_to_move.start)
8412 ..buffer.anchor_after(range_to_move.end),
8413 ) {
8414 let mut start = fold.range.start.to_point(&buffer);
8415 let mut end = fold.range.end.to_point(&buffer);
8416 start.row += row_delta;
8417 end.row += row_delta;
8418 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8419 }
8420 }
8421 }
8422
8423 // If we didn't move line(s), preserve the existing selections
8424 new_selections.append(&mut contiguous_row_selections);
8425 }
8426
8427 self.transact(window, cx, |this, window, cx| {
8428 this.unfold_ranges(&unfold_ranges, true, true, cx);
8429 this.buffer.update(cx, |buffer, cx| {
8430 for (range, text) in edits {
8431 buffer.edit([(range, text)], None, cx);
8432 }
8433 });
8434 this.fold_creases(refold_creases, true, window, cx);
8435 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8436 s.select(new_selections)
8437 });
8438 });
8439 }
8440
8441 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8442 let text_layout_details = &self.text_layout_details(window);
8443 self.transact(window, cx, |this, window, cx| {
8444 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8445 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8446 let line_mode = s.line_mode;
8447 s.move_with(|display_map, selection| {
8448 if !selection.is_empty() || line_mode {
8449 return;
8450 }
8451
8452 let mut head = selection.head();
8453 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8454 if head.column() == display_map.line_len(head.row()) {
8455 transpose_offset = display_map
8456 .buffer_snapshot
8457 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8458 }
8459
8460 if transpose_offset == 0 {
8461 return;
8462 }
8463
8464 *head.column_mut() += 1;
8465 head = display_map.clip_point(head, Bias::Right);
8466 let goal = SelectionGoal::HorizontalPosition(
8467 display_map
8468 .x_for_display_point(head, text_layout_details)
8469 .into(),
8470 );
8471 selection.collapse_to(head, goal);
8472
8473 let transpose_start = display_map
8474 .buffer_snapshot
8475 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8476 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8477 let transpose_end = display_map
8478 .buffer_snapshot
8479 .clip_offset(transpose_offset + 1, Bias::Right);
8480 if let Some(ch) =
8481 display_map.buffer_snapshot.chars_at(transpose_start).next()
8482 {
8483 edits.push((transpose_start..transpose_offset, String::new()));
8484 edits.push((transpose_end..transpose_end, ch.to_string()));
8485 }
8486 }
8487 });
8488 edits
8489 });
8490 this.buffer
8491 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8492 let selections = this.selections.all::<usize>(cx);
8493 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8494 s.select(selections);
8495 });
8496 });
8497 }
8498
8499 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8500 self.rewrap_impl(IsVimMode::No, cx)
8501 }
8502
8503 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8504 let buffer = self.buffer.read(cx).snapshot(cx);
8505 let selections = self.selections.all::<Point>(cx);
8506 let mut selections = selections.iter().peekable();
8507
8508 let mut edits = Vec::new();
8509 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8510
8511 while let Some(selection) = selections.next() {
8512 let mut start_row = selection.start.row;
8513 let mut end_row = selection.end.row;
8514
8515 // Skip selections that overlap with a range that has already been rewrapped.
8516 let selection_range = start_row..end_row;
8517 if rewrapped_row_ranges
8518 .iter()
8519 .any(|range| range.overlaps(&selection_range))
8520 {
8521 continue;
8522 }
8523
8524 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
8525
8526 // Since not all lines in the selection may be at the same indent
8527 // level, choose the indent size that is the most common between all
8528 // of the lines.
8529 //
8530 // If there is a tie, we use the deepest indent.
8531 let (indent_size, indent_end) = {
8532 let mut indent_size_occurrences = HashMap::default();
8533 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8534
8535 for row in start_row..=end_row {
8536 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8537 rows_by_indent_size.entry(indent).or_default().push(row);
8538 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8539 }
8540
8541 let indent_size = indent_size_occurrences
8542 .into_iter()
8543 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8544 .map(|(indent, _)| indent)
8545 .unwrap_or_default();
8546 let row = rows_by_indent_size[&indent_size][0];
8547 let indent_end = Point::new(row, indent_size.len);
8548
8549 (indent_size, indent_end)
8550 };
8551
8552 let mut line_prefix = indent_size.chars().collect::<String>();
8553
8554 let mut inside_comment = false;
8555 if let Some(comment_prefix) =
8556 buffer
8557 .language_scope_at(selection.head())
8558 .and_then(|language| {
8559 language
8560 .line_comment_prefixes()
8561 .iter()
8562 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8563 .cloned()
8564 })
8565 {
8566 line_prefix.push_str(&comment_prefix);
8567 inside_comment = true;
8568 }
8569
8570 let language_settings = buffer.language_settings_at(selection.head(), cx);
8571 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8572 RewrapBehavior::InComments => inside_comment,
8573 RewrapBehavior::InSelections => !selection.is_empty(),
8574 RewrapBehavior::Anywhere => true,
8575 };
8576
8577 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8578 if !should_rewrap {
8579 continue;
8580 }
8581
8582 if selection.is_empty() {
8583 'expand_upwards: while start_row > 0 {
8584 let prev_row = start_row - 1;
8585 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8586 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8587 {
8588 start_row = prev_row;
8589 } else {
8590 break 'expand_upwards;
8591 }
8592 }
8593
8594 'expand_downwards: while end_row < buffer.max_point().row {
8595 let next_row = end_row + 1;
8596 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8597 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8598 {
8599 end_row = next_row;
8600 } else {
8601 break 'expand_downwards;
8602 }
8603 }
8604 }
8605
8606 let start = Point::new(start_row, 0);
8607 let start_offset = start.to_offset(&buffer);
8608 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8609 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8610 let Some(lines_without_prefixes) = selection_text
8611 .lines()
8612 .map(|line| {
8613 line.strip_prefix(&line_prefix)
8614 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8615 .ok_or_else(|| {
8616 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8617 })
8618 })
8619 .collect::<Result<Vec<_>, _>>()
8620 .log_err()
8621 else {
8622 continue;
8623 };
8624
8625 let wrap_column = buffer
8626 .language_settings_at(Point::new(start_row, 0), cx)
8627 .preferred_line_length as usize;
8628 let wrapped_text = wrap_with_prefix(
8629 line_prefix,
8630 lines_without_prefixes.join(" "),
8631 wrap_column,
8632 tab_size,
8633 );
8634
8635 // TODO: should always use char-based diff while still supporting cursor behavior that
8636 // matches vim.
8637 let mut diff_options = DiffOptions::default();
8638 if is_vim_mode == IsVimMode::Yes {
8639 diff_options.max_word_diff_len = 0;
8640 diff_options.max_word_diff_line_count = 0;
8641 } else {
8642 diff_options.max_word_diff_len = usize::MAX;
8643 diff_options.max_word_diff_line_count = usize::MAX;
8644 }
8645
8646 for (old_range, new_text) in
8647 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8648 {
8649 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8650 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8651 edits.push((edit_start..edit_end, new_text));
8652 }
8653
8654 rewrapped_row_ranges.push(start_row..=end_row);
8655 }
8656
8657 self.buffer
8658 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8659 }
8660
8661 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8662 let mut text = String::new();
8663 let buffer = self.buffer.read(cx).snapshot(cx);
8664 let mut selections = self.selections.all::<Point>(cx);
8665 let mut clipboard_selections = Vec::with_capacity(selections.len());
8666 {
8667 let max_point = buffer.max_point();
8668 let mut is_first = true;
8669 for selection in &mut selections {
8670 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8671 if is_entire_line {
8672 selection.start = Point::new(selection.start.row, 0);
8673 if !selection.is_empty() && selection.end.column == 0 {
8674 selection.end = cmp::min(max_point, selection.end);
8675 } else {
8676 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8677 }
8678 selection.goal = SelectionGoal::None;
8679 }
8680 if is_first {
8681 is_first = false;
8682 } else {
8683 text += "\n";
8684 }
8685 let mut len = 0;
8686 for chunk in buffer.text_for_range(selection.start..selection.end) {
8687 text.push_str(chunk);
8688 len += chunk.len();
8689 }
8690 clipboard_selections.push(ClipboardSelection {
8691 len,
8692 is_entire_line,
8693 start_column: selection.start.column,
8694 });
8695 }
8696 }
8697
8698 self.transact(window, cx, |this, window, cx| {
8699 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8700 s.select(selections);
8701 });
8702 this.insert("", window, cx);
8703 });
8704 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8705 }
8706
8707 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8708 let item = self.cut_common(window, cx);
8709 cx.write_to_clipboard(item);
8710 }
8711
8712 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8713 self.change_selections(None, window, cx, |s| {
8714 s.move_with(|snapshot, sel| {
8715 if sel.is_empty() {
8716 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8717 }
8718 });
8719 });
8720 let item = self.cut_common(window, cx);
8721 cx.set_global(KillRing(item))
8722 }
8723
8724 pub fn kill_ring_yank(
8725 &mut self,
8726 _: &KillRingYank,
8727 window: &mut Window,
8728 cx: &mut Context<Self>,
8729 ) {
8730 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8731 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8732 (kill_ring.text().to_string(), kill_ring.metadata_json())
8733 } else {
8734 return;
8735 }
8736 } else {
8737 return;
8738 };
8739 self.do_paste(&text, metadata, false, window, cx);
8740 }
8741
8742 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8743 let selections = self.selections.all::<Point>(cx);
8744 let buffer = self.buffer.read(cx).read(cx);
8745 let mut text = String::new();
8746
8747 let mut clipboard_selections = Vec::with_capacity(selections.len());
8748 {
8749 let max_point = buffer.max_point();
8750 let mut is_first = true;
8751 for selection in selections.iter() {
8752 let mut start = selection.start;
8753 let mut end = selection.end;
8754 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8755 if is_entire_line {
8756 start = Point::new(start.row, 0);
8757 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8758 }
8759 if is_first {
8760 is_first = false;
8761 } else {
8762 text += "\n";
8763 }
8764 let mut len = 0;
8765 for chunk in buffer.text_for_range(start..end) {
8766 text.push_str(chunk);
8767 len += chunk.len();
8768 }
8769 clipboard_selections.push(ClipboardSelection {
8770 len,
8771 is_entire_line,
8772 start_column: start.column,
8773 });
8774 }
8775 }
8776
8777 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8778 text,
8779 clipboard_selections,
8780 ));
8781 }
8782
8783 pub fn do_paste(
8784 &mut self,
8785 text: &String,
8786 clipboard_selections: Option<Vec<ClipboardSelection>>,
8787 handle_entire_lines: bool,
8788 window: &mut Window,
8789 cx: &mut Context<Self>,
8790 ) {
8791 if self.read_only(cx) {
8792 return;
8793 }
8794
8795 let clipboard_text = Cow::Borrowed(text);
8796
8797 self.transact(window, cx, |this, window, cx| {
8798 if let Some(mut clipboard_selections) = clipboard_selections {
8799 let old_selections = this.selections.all::<usize>(cx);
8800 let all_selections_were_entire_line =
8801 clipboard_selections.iter().all(|s| s.is_entire_line);
8802 let first_selection_start_column =
8803 clipboard_selections.first().map(|s| s.start_column);
8804 if clipboard_selections.len() != old_selections.len() {
8805 clipboard_selections.drain(..);
8806 }
8807 let cursor_offset = this.selections.last::<usize>(cx).head();
8808 let mut auto_indent_on_paste = true;
8809
8810 this.buffer.update(cx, |buffer, cx| {
8811 let snapshot = buffer.read(cx);
8812 auto_indent_on_paste = snapshot
8813 .language_settings_at(cursor_offset, cx)
8814 .auto_indent_on_paste;
8815
8816 let mut start_offset = 0;
8817 let mut edits = Vec::new();
8818 let mut original_start_columns = Vec::new();
8819 for (ix, selection) in old_selections.iter().enumerate() {
8820 let to_insert;
8821 let entire_line;
8822 let original_start_column;
8823 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8824 let end_offset = start_offset + clipboard_selection.len;
8825 to_insert = &clipboard_text[start_offset..end_offset];
8826 entire_line = clipboard_selection.is_entire_line;
8827 start_offset = end_offset + 1;
8828 original_start_column = Some(clipboard_selection.start_column);
8829 } else {
8830 to_insert = clipboard_text.as_str();
8831 entire_line = all_selections_were_entire_line;
8832 original_start_column = first_selection_start_column
8833 }
8834
8835 // If the corresponding selection was empty when this slice of the
8836 // clipboard text was written, then the entire line containing the
8837 // selection was copied. If this selection is also currently empty,
8838 // then paste the line before the current line of the buffer.
8839 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8840 let column = selection.start.to_point(&snapshot).column as usize;
8841 let line_start = selection.start - column;
8842 line_start..line_start
8843 } else {
8844 selection.range()
8845 };
8846
8847 edits.push((range, to_insert));
8848 original_start_columns.extend(original_start_column);
8849 }
8850 drop(snapshot);
8851
8852 buffer.edit(
8853 edits,
8854 if auto_indent_on_paste {
8855 Some(AutoindentMode::Block {
8856 original_start_columns,
8857 })
8858 } else {
8859 None
8860 },
8861 cx,
8862 );
8863 });
8864
8865 let selections = this.selections.all::<usize>(cx);
8866 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8867 s.select(selections)
8868 });
8869 } else {
8870 this.insert(&clipboard_text, window, cx);
8871 }
8872 });
8873 }
8874
8875 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8876 if let Some(item) = cx.read_from_clipboard() {
8877 let entries = item.entries();
8878
8879 match entries.first() {
8880 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8881 // of all the pasted entries.
8882 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8883 .do_paste(
8884 clipboard_string.text(),
8885 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8886 true,
8887 window,
8888 cx,
8889 ),
8890 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8891 }
8892 }
8893 }
8894
8895 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8896 if self.read_only(cx) {
8897 return;
8898 }
8899
8900 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8901 if let Some((selections, _)) =
8902 self.selection_history.transaction(transaction_id).cloned()
8903 {
8904 self.change_selections(None, window, cx, |s| {
8905 s.select_anchors(selections.to_vec());
8906 });
8907 } else {
8908 log::error!(
8909 "No entry in selection_history found for undo. \
8910 This may correspond to a bug where undo does not update the selection. \
8911 If this is occurring, please add details to \
8912 https://github.com/zed-industries/zed/issues/22692"
8913 );
8914 }
8915 self.request_autoscroll(Autoscroll::fit(), cx);
8916 self.unmark_text(window, cx);
8917 self.refresh_inline_completion(true, false, window, cx);
8918 cx.emit(EditorEvent::Edited { transaction_id });
8919 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8920 }
8921 }
8922
8923 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8924 if self.read_only(cx) {
8925 return;
8926 }
8927
8928 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8929 if let Some((_, Some(selections))) =
8930 self.selection_history.transaction(transaction_id).cloned()
8931 {
8932 self.change_selections(None, window, cx, |s| {
8933 s.select_anchors(selections.to_vec());
8934 });
8935 } else {
8936 log::error!(
8937 "No entry in selection_history found for redo. \
8938 This may correspond to a bug where undo does not update the selection. \
8939 If this is occurring, please add details to \
8940 https://github.com/zed-industries/zed/issues/22692"
8941 );
8942 }
8943 self.request_autoscroll(Autoscroll::fit(), cx);
8944 self.unmark_text(window, cx);
8945 self.refresh_inline_completion(true, false, window, cx);
8946 cx.emit(EditorEvent::Edited { transaction_id });
8947 }
8948 }
8949
8950 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8951 self.buffer
8952 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8953 }
8954
8955 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8956 self.buffer
8957 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8958 }
8959
8960 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8961 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8962 let line_mode = s.line_mode;
8963 s.move_with(|map, selection| {
8964 let cursor = if selection.is_empty() && !line_mode {
8965 movement::left(map, selection.start)
8966 } else {
8967 selection.start
8968 };
8969 selection.collapse_to(cursor, SelectionGoal::None);
8970 });
8971 })
8972 }
8973
8974 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8976 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8977 })
8978 }
8979
8980 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8981 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8982 let line_mode = s.line_mode;
8983 s.move_with(|map, selection| {
8984 let cursor = if selection.is_empty() && !line_mode {
8985 movement::right(map, selection.end)
8986 } else {
8987 selection.end
8988 };
8989 selection.collapse_to(cursor, SelectionGoal::None)
8990 });
8991 })
8992 }
8993
8994 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
8995 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8996 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
8997 })
8998 }
8999
9000 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9001 if self.take_rename(true, window, cx).is_some() {
9002 return;
9003 }
9004
9005 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9006 cx.propagate();
9007 return;
9008 }
9009
9010 let text_layout_details = &self.text_layout_details(window);
9011 let selection_count = self.selections.count();
9012 let first_selection = self.selections.first_anchor();
9013
9014 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9015 let line_mode = s.line_mode;
9016 s.move_with(|map, selection| {
9017 if !selection.is_empty() && !line_mode {
9018 selection.goal = SelectionGoal::None;
9019 }
9020 let (cursor, goal) = movement::up(
9021 map,
9022 selection.start,
9023 selection.goal,
9024 false,
9025 text_layout_details,
9026 );
9027 selection.collapse_to(cursor, goal);
9028 });
9029 });
9030
9031 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9032 {
9033 cx.propagate();
9034 }
9035 }
9036
9037 pub fn move_up_by_lines(
9038 &mut self,
9039 action: &MoveUpByLines,
9040 window: &mut Window,
9041 cx: &mut Context<Self>,
9042 ) {
9043 if self.take_rename(true, window, cx).is_some() {
9044 return;
9045 }
9046
9047 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9048 cx.propagate();
9049 return;
9050 }
9051
9052 let text_layout_details = &self.text_layout_details(window);
9053
9054 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9055 let line_mode = s.line_mode;
9056 s.move_with(|map, selection| {
9057 if !selection.is_empty() && !line_mode {
9058 selection.goal = SelectionGoal::None;
9059 }
9060 let (cursor, goal) = movement::up_by_rows(
9061 map,
9062 selection.start,
9063 action.lines,
9064 selection.goal,
9065 false,
9066 text_layout_details,
9067 );
9068 selection.collapse_to(cursor, goal);
9069 });
9070 })
9071 }
9072
9073 pub fn move_down_by_lines(
9074 &mut self,
9075 action: &MoveDownByLines,
9076 window: &mut Window,
9077 cx: &mut Context<Self>,
9078 ) {
9079 if self.take_rename(true, window, cx).is_some() {
9080 return;
9081 }
9082
9083 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9084 cx.propagate();
9085 return;
9086 }
9087
9088 let text_layout_details = &self.text_layout_details(window);
9089
9090 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9091 let line_mode = s.line_mode;
9092 s.move_with(|map, selection| {
9093 if !selection.is_empty() && !line_mode {
9094 selection.goal = SelectionGoal::None;
9095 }
9096 let (cursor, goal) = movement::down_by_rows(
9097 map,
9098 selection.start,
9099 action.lines,
9100 selection.goal,
9101 false,
9102 text_layout_details,
9103 );
9104 selection.collapse_to(cursor, goal);
9105 });
9106 })
9107 }
9108
9109 pub fn select_down_by_lines(
9110 &mut self,
9111 action: &SelectDownByLines,
9112 window: &mut Window,
9113 cx: &mut Context<Self>,
9114 ) {
9115 let text_layout_details = &self.text_layout_details(window);
9116 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9117 s.move_heads_with(|map, head, goal| {
9118 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9119 })
9120 })
9121 }
9122
9123 pub fn select_up_by_lines(
9124 &mut self,
9125 action: &SelectUpByLines,
9126 window: &mut Window,
9127 cx: &mut Context<Self>,
9128 ) {
9129 let text_layout_details = &self.text_layout_details(window);
9130 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9131 s.move_heads_with(|map, head, goal| {
9132 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9133 })
9134 })
9135 }
9136
9137 pub fn select_page_up(
9138 &mut self,
9139 _: &SelectPageUp,
9140 window: &mut Window,
9141 cx: &mut Context<Self>,
9142 ) {
9143 let Some(row_count) = self.visible_row_count() else {
9144 return;
9145 };
9146
9147 let text_layout_details = &self.text_layout_details(window);
9148
9149 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9150 s.move_heads_with(|map, head, goal| {
9151 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9152 })
9153 })
9154 }
9155
9156 pub fn move_page_up(
9157 &mut self,
9158 action: &MovePageUp,
9159 window: &mut Window,
9160 cx: &mut Context<Self>,
9161 ) {
9162 if self.take_rename(true, window, cx).is_some() {
9163 return;
9164 }
9165
9166 if self
9167 .context_menu
9168 .borrow_mut()
9169 .as_mut()
9170 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9171 .unwrap_or(false)
9172 {
9173 return;
9174 }
9175
9176 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9177 cx.propagate();
9178 return;
9179 }
9180
9181 let Some(row_count) = self.visible_row_count() else {
9182 return;
9183 };
9184
9185 let autoscroll = if action.center_cursor {
9186 Autoscroll::center()
9187 } else {
9188 Autoscroll::fit()
9189 };
9190
9191 let text_layout_details = &self.text_layout_details(window);
9192
9193 self.change_selections(Some(autoscroll), window, cx, |s| {
9194 let line_mode = s.line_mode;
9195 s.move_with(|map, selection| {
9196 if !selection.is_empty() && !line_mode {
9197 selection.goal = SelectionGoal::None;
9198 }
9199 let (cursor, goal) = movement::up_by_rows(
9200 map,
9201 selection.end,
9202 row_count,
9203 selection.goal,
9204 false,
9205 text_layout_details,
9206 );
9207 selection.collapse_to(cursor, goal);
9208 });
9209 });
9210 }
9211
9212 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9213 let text_layout_details = &self.text_layout_details(window);
9214 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9215 s.move_heads_with(|map, head, goal| {
9216 movement::up(map, head, goal, false, text_layout_details)
9217 })
9218 })
9219 }
9220
9221 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9222 self.take_rename(true, window, cx);
9223
9224 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9225 cx.propagate();
9226 return;
9227 }
9228
9229 let text_layout_details = &self.text_layout_details(window);
9230 let selection_count = self.selections.count();
9231 let first_selection = self.selections.first_anchor();
9232
9233 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9234 let line_mode = s.line_mode;
9235 s.move_with(|map, selection| {
9236 if !selection.is_empty() && !line_mode {
9237 selection.goal = SelectionGoal::None;
9238 }
9239 let (cursor, goal) = movement::down(
9240 map,
9241 selection.end,
9242 selection.goal,
9243 false,
9244 text_layout_details,
9245 );
9246 selection.collapse_to(cursor, goal);
9247 });
9248 });
9249
9250 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9251 {
9252 cx.propagate();
9253 }
9254 }
9255
9256 pub fn select_page_down(
9257 &mut self,
9258 _: &SelectPageDown,
9259 window: &mut Window,
9260 cx: &mut Context<Self>,
9261 ) {
9262 let Some(row_count) = self.visible_row_count() else {
9263 return;
9264 };
9265
9266 let text_layout_details = &self.text_layout_details(window);
9267
9268 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9269 s.move_heads_with(|map, head, goal| {
9270 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9271 })
9272 })
9273 }
9274
9275 pub fn move_page_down(
9276 &mut self,
9277 action: &MovePageDown,
9278 window: &mut Window,
9279 cx: &mut Context<Self>,
9280 ) {
9281 if self.take_rename(true, window, cx).is_some() {
9282 return;
9283 }
9284
9285 if self
9286 .context_menu
9287 .borrow_mut()
9288 .as_mut()
9289 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9290 .unwrap_or(false)
9291 {
9292 return;
9293 }
9294
9295 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9296 cx.propagate();
9297 return;
9298 }
9299
9300 let Some(row_count) = self.visible_row_count() else {
9301 return;
9302 };
9303
9304 let autoscroll = if action.center_cursor {
9305 Autoscroll::center()
9306 } else {
9307 Autoscroll::fit()
9308 };
9309
9310 let text_layout_details = &self.text_layout_details(window);
9311 self.change_selections(Some(autoscroll), window, cx, |s| {
9312 let line_mode = s.line_mode;
9313 s.move_with(|map, selection| {
9314 if !selection.is_empty() && !line_mode {
9315 selection.goal = SelectionGoal::None;
9316 }
9317 let (cursor, goal) = movement::down_by_rows(
9318 map,
9319 selection.end,
9320 row_count,
9321 selection.goal,
9322 false,
9323 text_layout_details,
9324 );
9325 selection.collapse_to(cursor, goal);
9326 });
9327 });
9328 }
9329
9330 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9331 let text_layout_details = &self.text_layout_details(window);
9332 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9333 s.move_heads_with(|map, head, goal| {
9334 movement::down(map, head, goal, false, text_layout_details)
9335 })
9336 });
9337 }
9338
9339 pub fn context_menu_first(
9340 &mut self,
9341 _: &ContextMenuFirst,
9342 _window: &mut Window,
9343 cx: &mut Context<Self>,
9344 ) {
9345 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9346 context_menu.select_first(self.completion_provider.as_deref(), cx);
9347 }
9348 }
9349
9350 pub fn context_menu_prev(
9351 &mut self,
9352 _: &ContextMenuPrevious,
9353 _window: &mut Window,
9354 cx: &mut Context<Self>,
9355 ) {
9356 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9357 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9358 }
9359 }
9360
9361 pub fn context_menu_next(
9362 &mut self,
9363 _: &ContextMenuNext,
9364 _window: &mut Window,
9365 cx: &mut Context<Self>,
9366 ) {
9367 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9368 context_menu.select_next(self.completion_provider.as_deref(), cx);
9369 }
9370 }
9371
9372 pub fn context_menu_last(
9373 &mut self,
9374 _: &ContextMenuLast,
9375 _window: &mut Window,
9376 cx: &mut Context<Self>,
9377 ) {
9378 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9379 context_menu.select_last(self.completion_provider.as_deref(), cx);
9380 }
9381 }
9382
9383 pub fn move_to_previous_word_start(
9384 &mut self,
9385 _: &MoveToPreviousWordStart,
9386 window: &mut Window,
9387 cx: &mut Context<Self>,
9388 ) {
9389 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9390 s.move_cursors_with(|map, head, _| {
9391 (
9392 movement::previous_word_start(map, head),
9393 SelectionGoal::None,
9394 )
9395 });
9396 })
9397 }
9398
9399 pub fn move_to_previous_subword_start(
9400 &mut self,
9401 _: &MoveToPreviousSubwordStart,
9402 window: &mut Window,
9403 cx: &mut Context<Self>,
9404 ) {
9405 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9406 s.move_cursors_with(|map, head, _| {
9407 (
9408 movement::previous_subword_start(map, head),
9409 SelectionGoal::None,
9410 )
9411 });
9412 })
9413 }
9414
9415 pub fn select_to_previous_word_start(
9416 &mut self,
9417 _: &SelectToPreviousWordStart,
9418 window: &mut Window,
9419 cx: &mut Context<Self>,
9420 ) {
9421 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9422 s.move_heads_with(|map, head, _| {
9423 (
9424 movement::previous_word_start(map, head),
9425 SelectionGoal::None,
9426 )
9427 });
9428 })
9429 }
9430
9431 pub fn select_to_previous_subword_start(
9432 &mut self,
9433 _: &SelectToPreviousSubwordStart,
9434 window: &mut Window,
9435 cx: &mut Context<Self>,
9436 ) {
9437 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9438 s.move_heads_with(|map, head, _| {
9439 (
9440 movement::previous_subword_start(map, head),
9441 SelectionGoal::None,
9442 )
9443 });
9444 })
9445 }
9446
9447 pub fn delete_to_previous_word_start(
9448 &mut self,
9449 action: &DeleteToPreviousWordStart,
9450 window: &mut Window,
9451 cx: &mut Context<Self>,
9452 ) {
9453 self.transact(window, cx, |this, window, cx| {
9454 this.select_autoclose_pair(window, cx);
9455 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9456 let line_mode = s.line_mode;
9457 s.move_with(|map, selection| {
9458 if selection.is_empty() && !line_mode {
9459 let cursor = if action.ignore_newlines {
9460 movement::previous_word_start(map, selection.head())
9461 } else {
9462 movement::previous_word_start_or_newline(map, selection.head())
9463 };
9464 selection.set_head(cursor, SelectionGoal::None);
9465 }
9466 });
9467 });
9468 this.insert("", window, cx);
9469 });
9470 }
9471
9472 pub fn delete_to_previous_subword_start(
9473 &mut self,
9474 _: &DeleteToPreviousSubwordStart,
9475 window: &mut Window,
9476 cx: &mut Context<Self>,
9477 ) {
9478 self.transact(window, cx, |this, window, cx| {
9479 this.select_autoclose_pair(window, cx);
9480 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9481 let line_mode = s.line_mode;
9482 s.move_with(|map, selection| {
9483 if selection.is_empty() && !line_mode {
9484 let cursor = movement::previous_subword_start(map, selection.head());
9485 selection.set_head(cursor, SelectionGoal::None);
9486 }
9487 });
9488 });
9489 this.insert("", window, cx);
9490 });
9491 }
9492
9493 pub fn move_to_next_word_end(
9494 &mut self,
9495 _: &MoveToNextWordEnd,
9496 window: &mut Window,
9497 cx: &mut Context<Self>,
9498 ) {
9499 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9500 s.move_cursors_with(|map, head, _| {
9501 (movement::next_word_end(map, head), SelectionGoal::None)
9502 });
9503 })
9504 }
9505
9506 pub fn move_to_next_subword_end(
9507 &mut self,
9508 _: &MoveToNextSubwordEnd,
9509 window: &mut Window,
9510 cx: &mut Context<Self>,
9511 ) {
9512 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9513 s.move_cursors_with(|map, head, _| {
9514 (movement::next_subword_end(map, head), SelectionGoal::None)
9515 });
9516 })
9517 }
9518
9519 pub fn select_to_next_word_end(
9520 &mut self,
9521 _: &SelectToNextWordEnd,
9522 window: &mut Window,
9523 cx: &mut Context<Self>,
9524 ) {
9525 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9526 s.move_heads_with(|map, head, _| {
9527 (movement::next_word_end(map, head), SelectionGoal::None)
9528 });
9529 })
9530 }
9531
9532 pub fn select_to_next_subword_end(
9533 &mut self,
9534 _: &SelectToNextSubwordEnd,
9535 window: &mut Window,
9536 cx: &mut Context<Self>,
9537 ) {
9538 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9539 s.move_heads_with(|map, head, _| {
9540 (movement::next_subword_end(map, head), SelectionGoal::None)
9541 });
9542 })
9543 }
9544
9545 pub fn delete_to_next_word_end(
9546 &mut self,
9547 action: &DeleteToNextWordEnd,
9548 window: &mut Window,
9549 cx: &mut Context<Self>,
9550 ) {
9551 self.transact(window, cx, |this, window, cx| {
9552 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9553 let line_mode = s.line_mode;
9554 s.move_with(|map, selection| {
9555 if selection.is_empty() && !line_mode {
9556 let cursor = if action.ignore_newlines {
9557 movement::next_word_end(map, selection.head())
9558 } else {
9559 movement::next_word_end_or_newline(map, selection.head())
9560 };
9561 selection.set_head(cursor, SelectionGoal::None);
9562 }
9563 });
9564 });
9565 this.insert("", window, cx);
9566 });
9567 }
9568
9569 pub fn delete_to_next_subword_end(
9570 &mut self,
9571 _: &DeleteToNextSubwordEnd,
9572 window: &mut Window,
9573 cx: &mut Context<Self>,
9574 ) {
9575 self.transact(window, cx, |this, window, cx| {
9576 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9577 s.move_with(|map, selection| {
9578 if selection.is_empty() {
9579 let cursor = movement::next_subword_end(map, selection.head());
9580 selection.set_head(cursor, SelectionGoal::None);
9581 }
9582 });
9583 });
9584 this.insert("", window, cx);
9585 });
9586 }
9587
9588 pub fn move_to_beginning_of_line(
9589 &mut self,
9590 action: &MoveToBeginningOfLine,
9591 window: &mut Window,
9592 cx: &mut Context<Self>,
9593 ) {
9594 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9595 s.move_cursors_with(|map, head, _| {
9596 (
9597 movement::indented_line_beginning(
9598 map,
9599 head,
9600 action.stop_at_soft_wraps,
9601 action.stop_at_indent,
9602 ),
9603 SelectionGoal::None,
9604 )
9605 });
9606 })
9607 }
9608
9609 pub fn select_to_beginning_of_line(
9610 &mut self,
9611 action: &SelectToBeginningOfLine,
9612 window: &mut Window,
9613 cx: &mut Context<Self>,
9614 ) {
9615 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9616 s.move_heads_with(|map, head, _| {
9617 (
9618 movement::indented_line_beginning(
9619 map,
9620 head,
9621 action.stop_at_soft_wraps,
9622 action.stop_at_indent,
9623 ),
9624 SelectionGoal::None,
9625 )
9626 });
9627 });
9628 }
9629
9630 pub fn delete_to_beginning_of_line(
9631 &mut self,
9632 action: &DeleteToBeginningOfLine,
9633 window: &mut Window,
9634 cx: &mut Context<Self>,
9635 ) {
9636 self.transact(window, cx, |this, window, cx| {
9637 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9638 s.move_with(|_, selection| {
9639 selection.reversed = true;
9640 });
9641 });
9642
9643 this.select_to_beginning_of_line(
9644 &SelectToBeginningOfLine {
9645 stop_at_soft_wraps: false,
9646 stop_at_indent: action.stop_at_indent,
9647 },
9648 window,
9649 cx,
9650 );
9651 this.backspace(&Backspace, window, cx);
9652 });
9653 }
9654
9655 pub fn move_to_end_of_line(
9656 &mut self,
9657 action: &MoveToEndOfLine,
9658 window: &mut Window,
9659 cx: &mut Context<Self>,
9660 ) {
9661 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9662 s.move_cursors_with(|map, head, _| {
9663 (
9664 movement::line_end(map, head, action.stop_at_soft_wraps),
9665 SelectionGoal::None,
9666 )
9667 });
9668 })
9669 }
9670
9671 pub fn select_to_end_of_line(
9672 &mut self,
9673 action: &SelectToEndOfLine,
9674 window: &mut Window,
9675 cx: &mut Context<Self>,
9676 ) {
9677 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9678 s.move_heads_with(|map, head, _| {
9679 (
9680 movement::line_end(map, head, action.stop_at_soft_wraps),
9681 SelectionGoal::None,
9682 )
9683 });
9684 })
9685 }
9686
9687 pub fn delete_to_end_of_line(
9688 &mut self,
9689 _: &DeleteToEndOfLine,
9690 window: &mut Window,
9691 cx: &mut Context<Self>,
9692 ) {
9693 self.transact(window, cx, |this, window, cx| {
9694 this.select_to_end_of_line(
9695 &SelectToEndOfLine {
9696 stop_at_soft_wraps: false,
9697 },
9698 window,
9699 cx,
9700 );
9701 this.delete(&Delete, window, cx);
9702 });
9703 }
9704
9705 pub fn cut_to_end_of_line(
9706 &mut self,
9707 _: &CutToEndOfLine,
9708 window: &mut Window,
9709 cx: &mut Context<Self>,
9710 ) {
9711 self.transact(window, cx, |this, window, cx| {
9712 this.select_to_end_of_line(
9713 &SelectToEndOfLine {
9714 stop_at_soft_wraps: false,
9715 },
9716 window,
9717 cx,
9718 );
9719 this.cut(&Cut, window, cx);
9720 });
9721 }
9722
9723 pub fn move_to_start_of_paragraph(
9724 &mut self,
9725 _: &MoveToStartOfParagraph,
9726 window: &mut Window,
9727 cx: &mut Context<Self>,
9728 ) {
9729 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9730 cx.propagate();
9731 return;
9732 }
9733
9734 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9735 s.move_with(|map, selection| {
9736 selection.collapse_to(
9737 movement::start_of_paragraph(map, selection.head(), 1),
9738 SelectionGoal::None,
9739 )
9740 });
9741 })
9742 }
9743
9744 pub fn move_to_end_of_paragraph(
9745 &mut self,
9746 _: &MoveToEndOfParagraph,
9747 window: &mut Window,
9748 cx: &mut Context<Self>,
9749 ) {
9750 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9751 cx.propagate();
9752 return;
9753 }
9754
9755 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9756 s.move_with(|map, selection| {
9757 selection.collapse_to(
9758 movement::end_of_paragraph(map, selection.head(), 1),
9759 SelectionGoal::None,
9760 )
9761 });
9762 })
9763 }
9764
9765 pub fn select_to_start_of_paragraph(
9766 &mut self,
9767 _: &SelectToStartOfParagraph,
9768 window: &mut Window,
9769 cx: &mut Context<Self>,
9770 ) {
9771 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9772 cx.propagate();
9773 return;
9774 }
9775
9776 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9777 s.move_heads_with(|map, head, _| {
9778 (
9779 movement::start_of_paragraph(map, head, 1),
9780 SelectionGoal::None,
9781 )
9782 });
9783 })
9784 }
9785
9786 pub fn select_to_end_of_paragraph(
9787 &mut self,
9788 _: &SelectToEndOfParagraph,
9789 window: &mut Window,
9790 cx: &mut Context<Self>,
9791 ) {
9792 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9793 cx.propagate();
9794 return;
9795 }
9796
9797 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9798 s.move_heads_with(|map, head, _| {
9799 (
9800 movement::end_of_paragraph(map, head, 1),
9801 SelectionGoal::None,
9802 )
9803 });
9804 })
9805 }
9806
9807 pub fn move_to_start_of_excerpt(
9808 &mut self,
9809 _: &MoveToStartOfExcerpt,
9810 window: &mut Window,
9811 cx: &mut Context<Self>,
9812 ) {
9813 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9814 cx.propagate();
9815 return;
9816 }
9817
9818 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9819 s.move_with(|map, selection| {
9820 selection.collapse_to(
9821 movement::start_of_excerpt(
9822 map,
9823 selection.head(),
9824 workspace::searchable::Direction::Prev,
9825 ),
9826 SelectionGoal::None,
9827 )
9828 });
9829 })
9830 }
9831
9832 pub fn move_to_end_of_excerpt(
9833 &mut self,
9834 _: &MoveToEndOfExcerpt,
9835 window: &mut Window,
9836 cx: &mut Context<Self>,
9837 ) {
9838 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9839 cx.propagate();
9840 return;
9841 }
9842
9843 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9844 s.move_with(|map, selection| {
9845 selection.collapse_to(
9846 movement::end_of_excerpt(
9847 map,
9848 selection.head(),
9849 workspace::searchable::Direction::Next,
9850 ),
9851 SelectionGoal::None,
9852 )
9853 });
9854 })
9855 }
9856
9857 pub fn select_to_start_of_excerpt(
9858 &mut self,
9859 _: &SelectToStartOfExcerpt,
9860 window: &mut Window,
9861 cx: &mut Context<Self>,
9862 ) {
9863 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9864 cx.propagate();
9865 return;
9866 }
9867
9868 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9869 s.move_heads_with(|map, head, _| {
9870 (
9871 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9872 SelectionGoal::None,
9873 )
9874 });
9875 })
9876 }
9877
9878 pub fn select_to_end_of_excerpt(
9879 &mut self,
9880 _: &SelectToEndOfExcerpt,
9881 window: &mut Window,
9882 cx: &mut Context<Self>,
9883 ) {
9884 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9885 cx.propagate();
9886 return;
9887 }
9888
9889 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9890 s.move_heads_with(|map, head, _| {
9891 (
9892 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9893 SelectionGoal::None,
9894 )
9895 });
9896 })
9897 }
9898
9899 pub fn move_to_beginning(
9900 &mut self,
9901 _: &MoveToBeginning,
9902 window: &mut Window,
9903 cx: &mut Context<Self>,
9904 ) {
9905 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9906 cx.propagate();
9907 return;
9908 }
9909
9910 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9911 s.select_ranges(vec![0..0]);
9912 });
9913 }
9914
9915 pub fn select_to_beginning(
9916 &mut self,
9917 _: &SelectToBeginning,
9918 window: &mut Window,
9919 cx: &mut Context<Self>,
9920 ) {
9921 let mut selection = self.selections.last::<Point>(cx);
9922 selection.set_head(Point::zero(), SelectionGoal::None);
9923
9924 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9925 s.select(vec![selection]);
9926 });
9927 }
9928
9929 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9930 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9931 cx.propagate();
9932 return;
9933 }
9934
9935 let cursor = self.buffer.read(cx).read(cx).len();
9936 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9937 s.select_ranges(vec![cursor..cursor])
9938 });
9939 }
9940
9941 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9942 self.nav_history = nav_history;
9943 }
9944
9945 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9946 self.nav_history.as_ref()
9947 }
9948
9949 fn push_to_nav_history(
9950 &mut self,
9951 cursor_anchor: Anchor,
9952 new_position: Option<Point>,
9953 cx: &mut Context<Self>,
9954 ) {
9955 if let Some(nav_history) = self.nav_history.as_mut() {
9956 let buffer = self.buffer.read(cx).read(cx);
9957 let cursor_position = cursor_anchor.to_point(&buffer);
9958 let scroll_state = self.scroll_manager.anchor();
9959 let scroll_top_row = scroll_state.top_row(&buffer);
9960 drop(buffer);
9961
9962 if let Some(new_position) = new_position {
9963 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9964 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9965 return;
9966 }
9967 }
9968
9969 nav_history.push(
9970 Some(NavigationData {
9971 cursor_anchor,
9972 cursor_position,
9973 scroll_anchor: scroll_state,
9974 scroll_top_row,
9975 }),
9976 cx,
9977 );
9978 }
9979 }
9980
9981 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9982 let buffer = self.buffer.read(cx).snapshot(cx);
9983 let mut selection = self.selections.first::<usize>(cx);
9984 selection.set_head(buffer.len(), SelectionGoal::None);
9985 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9986 s.select(vec![selection]);
9987 });
9988 }
9989
9990 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
9991 let end = self.buffer.read(cx).read(cx).len();
9992 self.change_selections(None, window, cx, |s| {
9993 s.select_ranges(vec![0..end]);
9994 });
9995 }
9996
9997 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
9998 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9999 let mut selections = self.selections.all::<Point>(cx);
10000 let max_point = display_map.buffer_snapshot.max_point();
10001 for selection in &mut selections {
10002 let rows = selection.spanned_rows(true, &display_map);
10003 selection.start = Point::new(rows.start.0, 0);
10004 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10005 selection.reversed = false;
10006 }
10007 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10008 s.select(selections);
10009 });
10010 }
10011
10012 pub fn split_selection_into_lines(
10013 &mut self,
10014 _: &SplitSelectionIntoLines,
10015 window: &mut Window,
10016 cx: &mut Context<Self>,
10017 ) {
10018 let selections = self
10019 .selections
10020 .all::<Point>(cx)
10021 .into_iter()
10022 .map(|selection| selection.start..selection.end)
10023 .collect::<Vec<_>>();
10024 self.unfold_ranges(&selections, true, true, cx);
10025
10026 let mut new_selection_ranges = Vec::new();
10027 {
10028 let buffer = self.buffer.read(cx).read(cx);
10029 for selection in selections {
10030 for row in selection.start.row..selection.end.row {
10031 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10032 new_selection_ranges.push(cursor..cursor);
10033 }
10034
10035 let is_multiline_selection = selection.start.row != selection.end.row;
10036 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10037 // so this action feels more ergonomic when paired with other selection operations
10038 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10039 if !should_skip_last {
10040 new_selection_ranges.push(selection.end..selection.end);
10041 }
10042 }
10043 }
10044 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10045 s.select_ranges(new_selection_ranges);
10046 });
10047 }
10048
10049 pub fn add_selection_above(
10050 &mut self,
10051 _: &AddSelectionAbove,
10052 window: &mut Window,
10053 cx: &mut Context<Self>,
10054 ) {
10055 self.add_selection(true, window, cx);
10056 }
10057
10058 pub fn add_selection_below(
10059 &mut self,
10060 _: &AddSelectionBelow,
10061 window: &mut Window,
10062 cx: &mut Context<Self>,
10063 ) {
10064 self.add_selection(false, window, cx);
10065 }
10066
10067 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10068 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10069 let mut selections = self.selections.all::<Point>(cx);
10070 let text_layout_details = self.text_layout_details(window);
10071 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10072 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10073 let range = oldest_selection.display_range(&display_map).sorted();
10074
10075 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10076 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10077 let positions = start_x.min(end_x)..start_x.max(end_x);
10078
10079 selections.clear();
10080 let mut stack = Vec::new();
10081 for row in range.start.row().0..=range.end.row().0 {
10082 if let Some(selection) = self.selections.build_columnar_selection(
10083 &display_map,
10084 DisplayRow(row),
10085 &positions,
10086 oldest_selection.reversed,
10087 &text_layout_details,
10088 ) {
10089 stack.push(selection.id);
10090 selections.push(selection);
10091 }
10092 }
10093
10094 if above {
10095 stack.reverse();
10096 }
10097
10098 AddSelectionsState { above, stack }
10099 });
10100
10101 let last_added_selection = *state.stack.last().unwrap();
10102 let mut new_selections = Vec::new();
10103 if above == state.above {
10104 let end_row = if above {
10105 DisplayRow(0)
10106 } else {
10107 display_map.max_point().row()
10108 };
10109
10110 'outer: for selection in selections {
10111 if selection.id == last_added_selection {
10112 let range = selection.display_range(&display_map).sorted();
10113 debug_assert_eq!(range.start.row(), range.end.row());
10114 let mut row = range.start.row();
10115 let positions =
10116 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10117 px(start)..px(end)
10118 } else {
10119 let start_x =
10120 display_map.x_for_display_point(range.start, &text_layout_details);
10121 let end_x =
10122 display_map.x_for_display_point(range.end, &text_layout_details);
10123 start_x.min(end_x)..start_x.max(end_x)
10124 };
10125
10126 while row != end_row {
10127 if above {
10128 row.0 -= 1;
10129 } else {
10130 row.0 += 1;
10131 }
10132
10133 if let Some(new_selection) = self.selections.build_columnar_selection(
10134 &display_map,
10135 row,
10136 &positions,
10137 selection.reversed,
10138 &text_layout_details,
10139 ) {
10140 state.stack.push(new_selection.id);
10141 if above {
10142 new_selections.push(new_selection);
10143 new_selections.push(selection);
10144 } else {
10145 new_selections.push(selection);
10146 new_selections.push(new_selection);
10147 }
10148
10149 continue 'outer;
10150 }
10151 }
10152 }
10153
10154 new_selections.push(selection);
10155 }
10156 } else {
10157 new_selections = selections;
10158 new_selections.retain(|s| s.id != last_added_selection);
10159 state.stack.pop();
10160 }
10161
10162 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10163 s.select(new_selections);
10164 });
10165 if state.stack.len() > 1 {
10166 self.add_selections_state = Some(state);
10167 }
10168 }
10169
10170 pub fn select_next_match_internal(
10171 &mut self,
10172 display_map: &DisplaySnapshot,
10173 replace_newest: bool,
10174 autoscroll: Option<Autoscroll>,
10175 window: &mut Window,
10176 cx: &mut Context<Self>,
10177 ) -> Result<()> {
10178 fn select_next_match_ranges(
10179 this: &mut Editor,
10180 range: Range<usize>,
10181 replace_newest: bool,
10182 auto_scroll: Option<Autoscroll>,
10183 window: &mut Window,
10184 cx: &mut Context<Editor>,
10185 ) {
10186 this.unfold_ranges(&[range.clone()], false, true, cx);
10187 this.change_selections(auto_scroll, window, cx, |s| {
10188 if replace_newest {
10189 s.delete(s.newest_anchor().id);
10190 }
10191 s.insert_range(range.clone());
10192 });
10193 }
10194
10195 let buffer = &display_map.buffer_snapshot;
10196 let mut selections = self.selections.all::<usize>(cx);
10197 if let Some(mut select_next_state) = self.select_next_state.take() {
10198 let query = &select_next_state.query;
10199 if !select_next_state.done {
10200 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10201 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10202 let mut next_selected_range = None;
10203
10204 let bytes_after_last_selection =
10205 buffer.bytes_in_range(last_selection.end..buffer.len());
10206 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10207 let query_matches = query
10208 .stream_find_iter(bytes_after_last_selection)
10209 .map(|result| (last_selection.end, result))
10210 .chain(
10211 query
10212 .stream_find_iter(bytes_before_first_selection)
10213 .map(|result| (0, result)),
10214 );
10215
10216 for (start_offset, query_match) in query_matches {
10217 let query_match = query_match.unwrap(); // can only fail due to I/O
10218 let offset_range =
10219 start_offset + query_match.start()..start_offset + query_match.end();
10220 let display_range = offset_range.start.to_display_point(display_map)
10221 ..offset_range.end.to_display_point(display_map);
10222
10223 if !select_next_state.wordwise
10224 || (!movement::is_inside_word(display_map, display_range.start)
10225 && !movement::is_inside_word(display_map, display_range.end))
10226 {
10227 // TODO: This is n^2, because we might check all the selections
10228 if !selections
10229 .iter()
10230 .any(|selection| selection.range().overlaps(&offset_range))
10231 {
10232 next_selected_range = Some(offset_range);
10233 break;
10234 }
10235 }
10236 }
10237
10238 if let Some(next_selected_range) = next_selected_range {
10239 select_next_match_ranges(
10240 self,
10241 next_selected_range,
10242 replace_newest,
10243 autoscroll,
10244 window,
10245 cx,
10246 );
10247 } else {
10248 select_next_state.done = true;
10249 }
10250 }
10251
10252 self.select_next_state = Some(select_next_state);
10253 } else {
10254 let mut only_carets = true;
10255 let mut same_text_selected = true;
10256 let mut selected_text = None;
10257
10258 let mut selections_iter = selections.iter().peekable();
10259 while let Some(selection) = selections_iter.next() {
10260 if selection.start != selection.end {
10261 only_carets = false;
10262 }
10263
10264 if same_text_selected {
10265 if selected_text.is_none() {
10266 selected_text =
10267 Some(buffer.text_for_range(selection.range()).collect::<String>());
10268 }
10269
10270 if let Some(next_selection) = selections_iter.peek() {
10271 if next_selection.range().len() == selection.range().len() {
10272 let next_selected_text = buffer
10273 .text_for_range(next_selection.range())
10274 .collect::<String>();
10275 if Some(next_selected_text) != selected_text {
10276 same_text_selected = false;
10277 selected_text = None;
10278 }
10279 } else {
10280 same_text_selected = false;
10281 selected_text = None;
10282 }
10283 }
10284 }
10285 }
10286
10287 if only_carets {
10288 for selection in &mut selections {
10289 let word_range = movement::surrounding_word(
10290 display_map,
10291 selection.start.to_display_point(display_map),
10292 );
10293 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10294 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10295 selection.goal = SelectionGoal::None;
10296 selection.reversed = false;
10297 select_next_match_ranges(
10298 self,
10299 selection.start..selection.end,
10300 replace_newest,
10301 autoscroll,
10302 window,
10303 cx,
10304 );
10305 }
10306
10307 if selections.len() == 1 {
10308 let selection = selections
10309 .last()
10310 .expect("ensured that there's only one selection");
10311 let query = buffer
10312 .text_for_range(selection.start..selection.end)
10313 .collect::<String>();
10314 let is_empty = query.is_empty();
10315 let select_state = SelectNextState {
10316 query: AhoCorasick::new(&[query])?,
10317 wordwise: true,
10318 done: is_empty,
10319 };
10320 self.select_next_state = Some(select_state);
10321 } else {
10322 self.select_next_state = None;
10323 }
10324 } else if let Some(selected_text) = selected_text {
10325 self.select_next_state = Some(SelectNextState {
10326 query: AhoCorasick::new(&[selected_text])?,
10327 wordwise: false,
10328 done: false,
10329 });
10330 self.select_next_match_internal(
10331 display_map,
10332 replace_newest,
10333 autoscroll,
10334 window,
10335 cx,
10336 )?;
10337 }
10338 }
10339 Ok(())
10340 }
10341
10342 pub fn select_all_matches(
10343 &mut self,
10344 _action: &SelectAllMatches,
10345 window: &mut Window,
10346 cx: &mut Context<Self>,
10347 ) -> Result<()> {
10348 self.push_to_selection_history();
10349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10350
10351 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10352 let Some(select_next_state) = self.select_next_state.as_mut() else {
10353 return Ok(());
10354 };
10355 if select_next_state.done {
10356 return Ok(());
10357 }
10358
10359 let mut new_selections = self.selections.all::<usize>(cx);
10360
10361 let buffer = &display_map.buffer_snapshot;
10362 let query_matches = select_next_state
10363 .query
10364 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10365
10366 for query_match in query_matches {
10367 let query_match = query_match.unwrap(); // can only fail due to I/O
10368 let offset_range = query_match.start()..query_match.end();
10369 let display_range = offset_range.start.to_display_point(&display_map)
10370 ..offset_range.end.to_display_point(&display_map);
10371
10372 if !select_next_state.wordwise
10373 || (!movement::is_inside_word(&display_map, display_range.start)
10374 && !movement::is_inside_word(&display_map, display_range.end))
10375 {
10376 self.selections.change_with(cx, |selections| {
10377 new_selections.push(Selection {
10378 id: selections.new_selection_id(),
10379 start: offset_range.start,
10380 end: offset_range.end,
10381 reversed: false,
10382 goal: SelectionGoal::None,
10383 });
10384 });
10385 }
10386 }
10387
10388 new_selections.sort_by_key(|selection| selection.start);
10389 let mut ix = 0;
10390 while ix + 1 < new_selections.len() {
10391 let current_selection = &new_selections[ix];
10392 let next_selection = &new_selections[ix + 1];
10393 if current_selection.range().overlaps(&next_selection.range()) {
10394 if current_selection.id < next_selection.id {
10395 new_selections.remove(ix + 1);
10396 } else {
10397 new_selections.remove(ix);
10398 }
10399 } else {
10400 ix += 1;
10401 }
10402 }
10403
10404 let reversed = self.selections.oldest::<usize>(cx).reversed;
10405
10406 for selection in new_selections.iter_mut() {
10407 selection.reversed = reversed;
10408 }
10409
10410 select_next_state.done = true;
10411 self.unfold_ranges(
10412 &new_selections
10413 .iter()
10414 .map(|selection| selection.range())
10415 .collect::<Vec<_>>(),
10416 false,
10417 false,
10418 cx,
10419 );
10420 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10421 selections.select(new_selections)
10422 });
10423
10424 Ok(())
10425 }
10426
10427 pub fn select_next(
10428 &mut self,
10429 action: &SelectNext,
10430 window: &mut Window,
10431 cx: &mut Context<Self>,
10432 ) -> Result<()> {
10433 self.push_to_selection_history();
10434 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10435 self.select_next_match_internal(
10436 &display_map,
10437 action.replace_newest,
10438 Some(Autoscroll::newest()),
10439 window,
10440 cx,
10441 )?;
10442 Ok(())
10443 }
10444
10445 pub fn select_previous(
10446 &mut self,
10447 action: &SelectPrevious,
10448 window: &mut Window,
10449 cx: &mut Context<Self>,
10450 ) -> Result<()> {
10451 self.push_to_selection_history();
10452 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10453 let buffer = &display_map.buffer_snapshot;
10454 let mut selections = self.selections.all::<usize>(cx);
10455 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10456 let query = &select_prev_state.query;
10457 if !select_prev_state.done {
10458 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10459 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10460 let mut next_selected_range = None;
10461 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10462 let bytes_before_last_selection =
10463 buffer.reversed_bytes_in_range(0..last_selection.start);
10464 let bytes_after_first_selection =
10465 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10466 let query_matches = query
10467 .stream_find_iter(bytes_before_last_selection)
10468 .map(|result| (last_selection.start, result))
10469 .chain(
10470 query
10471 .stream_find_iter(bytes_after_first_selection)
10472 .map(|result| (buffer.len(), result)),
10473 );
10474 for (end_offset, query_match) in query_matches {
10475 let query_match = query_match.unwrap(); // can only fail due to I/O
10476 let offset_range =
10477 end_offset - query_match.end()..end_offset - query_match.start();
10478 let display_range = offset_range.start.to_display_point(&display_map)
10479 ..offset_range.end.to_display_point(&display_map);
10480
10481 if !select_prev_state.wordwise
10482 || (!movement::is_inside_word(&display_map, display_range.start)
10483 && !movement::is_inside_word(&display_map, display_range.end))
10484 {
10485 next_selected_range = Some(offset_range);
10486 break;
10487 }
10488 }
10489
10490 if let Some(next_selected_range) = next_selected_range {
10491 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10492 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10493 if action.replace_newest {
10494 s.delete(s.newest_anchor().id);
10495 }
10496 s.insert_range(next_selected_range);
10497 });
10498 } else {
10499 select_prev_state.done = true;
10500 }
10501 }
10502
10503 self.select_prev_state = Some(select_prev_state);
10504 } else {
10505 let mut only_carets = true;
10506 let mut same_text_selected = true;
10507 let mut selected_text = None;
10508
10509 let mut selections_iter = selections.iter().peekable();
10510 while let Some(selection) = selections_iter.next() {
10511 if selection.start != selection.end {
10512 only_carets = false;
10513 }
10514
10515 if same_text_selected {
10516 if selected_text.is_none() {
10517 selected_text =
10518 Some(buffer.text_for_range(selection.range()).collect::<String>());
10519 }
10520
10521 if let Some(next_selection) = selections_iter.peek() {
10522 if next_selection.range().len() == selection.range().len() {
10523 let next_selected_text = buffer
10524 .text_for_range(next_selection.range())
10525 .collect::<String>();
10526 if Some(next_selected_text) != selected_text {
10527 same_text_selected = false;
10528 selected_text = None;
10529 }
10530 } else {
10531 same_text_selected = false;
10532 selected_text = None;
10533 }
10534 }
10535 }
10536 }
10537
10538 if only_carets {
10539 for selection in &mut selections {
10540 let word_range = movement::surrounding_word(
10541 &display_map,
10542 selection.start.to_display_point(&display_map),
10543 );
10544 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10545 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10546 selection.goal = SelectionGoal::None;
10547 selection.reversed = false;
10548 }
10549 if selections.len() == 1 {
10550 let selection = selections
10551 .last()
10552 .expect("ensured that there's only one selection");
10553 let query = buffer
10554 .text_for_range(selection.start..selection.end)
10555 .collect::<String>();
10556 let is_empty = query.is_empty();
10557 let select_state = SelectNextState {
10558 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10559 wordwise: true,
10560 done: is_empty,
10561 };
10562 self.select_prev_state = Some(select_state);
10563 } else {
10564 self.select_prev_state = None;
10565 }
10566
10567 self.unfold_ranges(
10568 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10569 false,
10570 true,
10571 cx,
10572 );
10573 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10574 s.select(selections);
10575 });
10576 } else if let Some(selected_text) = selected_text {
10577 self.select_prev_state = Some(SelectNextState {
10578 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10579 wordwise: false,
10580 done: false,
10581 });
10582 self.select_previous(action, window, cx)?;
10583 }
10584 }
10585 Ok(())
10586 }
10587
10588 pub fn toggle_comments(
10589 &mut self,
10590 action: &ToggleComments,
10591 window: &mut Window,
10592 cx: &mut Context<Self>,
10593 ) {
10594 if self.read_only(cx) {
10595 return;
10596 }
10597 let text_layout_details = &self.text_layout_details(window);
10598 self.transact(window, cx, |this, window, cx| {
10599 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10600 let mut edits = Vec::new();
10601 let mut selection_edit_ranges = Vec::new();
10602 let mut last_toggled_row = None;
10603 let snapshot = this.buffer.read(cx).read(cx);
10604 let empty_str: Arc<str> = Arc::default();
10605 let mut suffixes_inserted = Vec::new();
10606 let ignore_indent = action.ignore_indent;
10607
10608 fn comment_prefix_range(
10609 snapshot: &MultiBufferSnapshot,
10610 row: MultiBufferRow,
10611 comment_prefix: &str,
10612 comment_prefix_whitespace: &str,
10613 ignore_indent: bool,
10614 ) -> Range<Point> {
10615 let indent_size = if ignore_indent {
10616 0
10617 } else {
10618 snapshot.indent_size_for_line(row).len
10619 };
10620
10621 let start = Point::new(row.0, indent_size);
10622
10623 let mut line_bytes = snapshot
10624 .bytes_in_range(start..snapshot.max_point())
10625 .flatten()
10626 .copied();
10627
10628 // If this line currently begins with the line comment prefix, then record
10629 // the range containing the prefix.
10630 if line_bytes
10631 .by_ref()
10632 .take(comment_prefix.len())
10633 .eq(comment_prefix.bytes())
10634 {
10635 // Include any whitespace that matches the comment prefix.
10636 let matching_whitespace_len = line_bytes
10637 .zip(comment_prefix_whitespace.bytes())
10638 .take_while(|(a, b)| a == b)
10639 .count() as u32;
10640 let end = Point::new(
10641 start.row,
10642 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10643 );
10644 start..end
10645 } else {
10646 start..start
10647 }
10648 }
10649
10650 fn comment_suffix_range(
10651 snapshot: &MultiBufferSnapshot,
10652 row: MultiBufferRow,
10653 comment_suffix: &str,
10654 comment_suffix_has_leading_space: bool,
10655 ) -> Range<Point> {
10656 let end = Point::new(row.0, snapshot.line_len(row));
10657 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10658
10659 let mut line_end_bytes = snapshot
10660 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10661 .flatten()
10662 .copied();
10663
10664 let leading_space_len = if suffix_start_column > 0
10665 && line_end_bytes.next() == Some(b' ')
10666 && comment_suffix_has_leading_space
10667 {
10668 1
10669 } else {
10670 0
10671 };
10672
10673 // If this line currently begins with the line comment prefix, then record
10674 // the range containing the prefix.
10675 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10676 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10677 start..end
10678 } else {
10679 end..end
10680 }
10681 }
10682
10683 // TODO: Handle selections that cross excerpts
10684 for selection in &mut selections {
10685 let start_column = snapshot
10686 .indent_size_for_line(MultiBufferRow(selection.start.row))
10687 .len;
10688 let language = if let Some(language) =
10689 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10690 {
10691 language
10692 } else {
10693 continue;
10694 };
10695
10696 selection_edit_ranges.clear();
10697
10698 // If multiple selections contain a given row, avoid processing that
10699 // row more than once.
10700 let mut start_row = MultiBufferRow(selection.start.row);
10701 if last_toggled_row == Some(start_row) {
10702 start_row = start_row.next_row();
10703 }
10704 let end_row =
10705 if selection.end.row > selection.start.row && selection.end.column == 0 {
10706 MultiBufferRow(selection.end.row - 1)
10707 } else {
10708 MultiBufferRow(selection.end.row)
10709 };
10710 last_toggled_row = Some(end_row);
10711
10712 if start_row > end_row {
10713 continue;
10714 }
10715
10716 // If the language has line comments, toggle those.
10717 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10718
10719 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10720 if ignore_indent {
10721 full_comment_prefixes = full_comment_prefixes
10722 .into_iter()
10723 .map(|s| Arc::from(s.trim_end()))
10724 .collect();
10725 }
10726
10727 if !full_comment_prefixes.is_empty() {
10728 let first_prefix = full_comment_prefixes
10729 .first()
10730 .expect("prefixes is non-empty");
10731 let prefix_trimmed_lengths = full_comment_prefixes
10732 .iter()
10733 .map(|p| p.trim_end_matches(' ').len())
10734 .collect::<SmallVec<[usize; 4]>>();
10735
10736 let mut all_selection_lines_are_comments = true;
10737
10738 for row in start_row.0..=end_row.0 {
10739 let row = MultiBufferRow(row);
10740 if start_row < end_row && snapshot.is_line_blank(row) {
10741 continue;
10742 }
10743
10744 let prefix_range = full_comment_prefixes
10745 .iter()
10746 .zip(prefix_trimmed_lengths.iter().copied())
10747 .map(|(prefix, trimmed_prefix_len)| {
10748 comment_prefix_range(
10749 snapshot.deref(),
10750 row,
10751 &prefix[..trimmed_prefix_len],
10752 &prefix[trimmed_prefix_len..],
10753 ignore_indent,
10754 )
10755 })
10756 .max_by_key(|range| range.end.column - range.start.column)
10757 .expect("prefixes is non-empty");
10758
10759 if prefix_range.is_empty() {
10760 all_selection_lines_are_comments = false;
10761 }
10762
10763 selection_edit_ranges.push(prefix_range);
10764 }
10765
10766 if all_selection_lines_are_comments {
10767 edits.extend(
10768 selection_edit_ranges
10769 .iter()
10770 .cloned()
10771 .map(|range| (range, empty_str.clone())),
10772 );
10773 } else {
10774 let min_column = selection_edit_ranges
10775 .iter()
10776 .map(|range| range.start.column)
10777 .min()
10778 .unwrap_or(0);
10779 edits.extend(selection_edit_ranges.iter().map(|range| {
10780 let position = Point::new(range.start.row, min_column);
10781 (position..position, first_prefix.clone())
10782 }));
10783 }
10784 } else if let Some((full_comment_prefix, comment_suffix)) =
10785 language.block_comment_delimiters()
10786 {
10787 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10788 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10789 let prefix_range = comment_prefix_range(
10790 snapshot.deref(),
10791 start_row,
10792 comment_prefix,
10793 comment_prefix_whitespace,
10794 ignore_indent,
10795 );
10796 let suffix_range = comment_suffix_range(
10797 snapshot.deref(),
10798 end_row,
10799 comment_suffix.trim_start_matches(' '),
10800 comment_suffix.starts_with(' '),
10801 );
10802
10803 if prefix_range.is_empty() || suffix_range.is_empty() {
10804 edits.push((
10805 prefix_range.start..prefix_range.start,
10806 full_comment_prefix.clone(),
10807 ));
10808 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10809 suffixes_inserted.push((end_row, comment_suffix.len()));
10810 } else {
10811 edits.push((prefix_range, empty_str.clone()));
10812 edits.push((suffix_range, empty_str.clone()));
10813 }
10814 } else {
10815 continue;
10816 }
10817 }
10818
10819 drop(snapshot);
10820 this.buffer.update(cx, |buffer, cx| {
10821 buffer.edit(edits, None, cx);
10822 });
10823
10824 // Adjust selections so that they end before any comment suffixes that
10825 // were inserted.
10826 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10827 let mut selections = this.selections.all::<Point>(cx);
10828 let snapshot = this.buffer.read(cx).read(cx);
10829 for selection in &mut selections {
10830 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10831 match row.cmp(&MultiBufferRow(selection.end.row)) {
10832 Ordering::Less => {
10833 suffixes_inserted.next();
10834 continue;
10835 }
10836 Ordering::Greater => break,
10837 Ordering::Equal => {
10838 if selection.end.column == snapshot.line_len(row) {
10839 if selection.is_empty() {
10840 selection.start.column -= suffix_len as u32;
10841 }
10842 selection.end.column -= suffix_len as u32;
10843 }
10844 break;
10845 }
10846 }
10847 }
10848 }
10849
10850 drop(snapshot);
10851 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10852 s.select(selections)
10853 });
10854
10855 let selections = this.selections.all::<Point>(cx);
10856 let selections_on_single_row = selections.windows(2).all(|selections| {
10857 selections[0].start.row == selections[1].start.row
10858 && selections[0].end.row == selections[1].end.row
10859 && selections[0].start.row == selections[0].end.row
10860 });
10861 let selections_selecting = selections
10862 .iter()
10863 .any(|selection| selection.start != selection.end);
10864 let advance_downwards = action.advance_downwards
10865 && selections_on_single_row
10866 && !selections_selecting
10867 && !matches!(this.mode, EditorMode::SingleLine { .. });
10868
10869 if advance_downwards {
10870 let snapshot = this.buffer.read(cx).snapshot(cx);
10871
10872 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10873 s.move_cursors_with(|display_snapshot, display_point, _| {
10874 let mut point = display_point.to_point(display_snapshot);
10875 point.row += 1;
10876 point = snapshot.clip_point(point, Bias::Left);
10877 let display_point = point.to_display_point(display_snapshot);
10878 let goal = SelectionGoal::HorizontalPosition(
10879 display_snapshot
10880 .x_for_display_point(display_point, text_layout_details)
10881 .into(),
10882 );
10883 (display_point, goal)
10884 })
10885 });
10886 }
10887 });
10888 }
10889
10890 pub fn select_enclosing_symbol(
10891 &mut self,
10892 _: &SelectEnclosingSymbol,
10893 window: &mut Window,
10894 cx: &mut Context<Self>,
10895 ) {
10896 let buffer = self.buffer.read(cx).snapshot(cx);
10897 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10898
10899 fn update_selection(
10900 selection: &Selection<usize>,
10901 buffer_snap: &MultiBufferSnapshot,
10902 ) -> Option<Selection<usize>> {
10903 let cursor = selection.head();
10904 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10905 for symbol in symbols.iter().rev() {
10906 let start = symbol.range.start.to_offset(buffer_snap);
10907 let end = symbol.range.end.to_offset(buffer_snap);
10908 let new_range = start..end;
10909 if start < selection.start || end > selection.end {
10910 return Some(Selection {
10911 id: selection.id,
10912 start: new_range.start,
10913 end: new_range.end,
10914 goal: SelectionGoal::None,
10915 reversed: selection.reversed,
10916 });
10917 }
10918 }
10919 None
10920 }
10921
10922 let mut selected_larger_symbol = false;
10923 let new_selections = old_selections
10924 .iter()
10925 .map(|selection| match update_selection(selection, &buffer) {
10926 Some(new_selection) => {
10927 if new_selection.range() != selection.range() {
10928 selected_larger_symbol = true;
10929 }
10930 new_selection
10931 }
10932 None => selection.clone(),
10933 })
10934 .collect::<Vec<_>>();
10935
10936 if selected_larger_symbol {
10937 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10938 s.select(new_selections);
10939 });
10940 }
10941 }
10942
10943 pub fn select_larger_syntax_node(
10944 &mut self,
10945 _: &SelectLargerSyntaxNode,
10946 window: &mut Window,
10947 cx: &mut Context<Self>,
10948 ) {
10949 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10950 let buffer = self.buffer.read(cx).snapshot(cx);
10951 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10952
10953 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10954 let mut selected_larger_node = false;
10955 let new_selections = old_selections
10956 .iter()
10957 .map(|selection| {
10958 let old_range = selection.start..selection.end;
10959 let mut new_range = old_range.clone();
10960 let mut new_node = None;
10961 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10962 {
10963 new_node = Some(node);
10964 new_range = match containing_range {
10965 MultiOrSingleBufferOffsetRange::Single(_) => break,
10966 MultiOrSingleBufferOffsetRange::Multi(range) => range,
10967 };
10968 if !display_map.intersects_fold(new_range.start)
10969 && !display_map.intersects_fold(new_range.end)
10970 {
10971 break;
10972 }
10973 }
10974
10975 if let Some(node) = new_node {
10976 // Log the ancestor, to support using this action as a way to explore TreeSitter
10977 // nodes. Parent and grandparent are also logged because this operation will not
10978 // visit nodes that have the same range as their parent.
10979 log::info!("Node: {node:?}");
10980 let parent = node.parent();
10981 log::info!("Parent: {parent:?}");
10982 let grandparent = parent.and_then(|x| x.parent());
10983 log::info!("Grandparent: {grandparent:?}");
10984 }
10985
10986 selected_larger_node |= new_range != old_range;
10987 Selection {
10988 id: selection.id,
10989 start: new_range.start,
10990 end: new_range.end,
10991 goal: SelectionGoal::None,
10992 reversed: selection.reversed,
10993 }
10994 })
10995 .collect::<Vec<_>>();
10996
10997 if selected_larger_node {
10998 stack.push(old_selections);
10999 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11000 s.select(new_selections);
11001 });
11002 }
11003 self.select_larger_syntax_node_stack = stack;
11004 }
11005
11006 pub fn select_smaller_syntax_node(
11007 &mut self,
11008 _: &SelectSmallerSyntaxNode,
11009 window: &mut Window,
11010 cx: &mut Context<Self>,
11011 ) {
11012 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11013 if let Some(selections) = stack.pop() {
11014 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11015 s.select(selections.to_vec());
11016 });
11017 }
11018 self.select_larger_syntax_node_stack = stack;
11019 }
11020
11021 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11022 if !EditorSettings::get_global(cx).gutter.runnables {
11023 self.clear_tasks();
11024 return Task::ready(());
11025 }
11026 let project = self.project.as_ref().map(Entity::downgrade);
11027 cx.spawn_in(window, |this, mut cx| async move {
11028 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11029 let Some(project) = project.and_then(|p| p.upgrade()) else {
11030 return;
11031 };
11032 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11033 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11034 }) else {
11035 return;
11036 };
11037
11038 let hide_runnables = project
11039 .update(&mut cx, |project, cx| {
11040 // Do not display any test indicators in non-dev server remote projects.
11041 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11042 })
11043 .unwrap_or(true);
11044 if hide_runnables {
11045 return;
11046 }
11047 let new_rows =
11048 cx.background_spawn({
11049 let snapshot = display_snapshot.clone();
11050 async move {
11051 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11052 }
11053 })
11054 .await;
11055
11056 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11057 this.update(&mut cx, |this, _| {
11058 this.clear_tasks();
11059 for (key, value) in rows {
11060 this.insert_tasks(key, value);
11061 }
11062 })
11063 .ok();
11064 })
11065 }
11066 fn fetch_runnable_ranges(
11067 snapshot: &DisplaySnapshot,
11068 range: Range<Anchor>,
11069 ) -> Vec<language::RunnableRange> {
11070 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11071 }
11072
11073 fn runnable_rows(
11074 project: Entity<Project>,
11075 snapshot: DisplaySnapshot,
11076 runnable_ranges: Vec<RunnableRange>,
11077 mut cx: AsyncWindowContext,
11078 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11079 runnable_ranges
11080 .into_iter()
11081 .filter_map(|mut runnable| {
11082 let tasks = cx
11083 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11084 .ok()?;
11085 if tasks.is_empty() {
11086 return None;
11087 }
11088
11089 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11090
11091 let row = snapshot
11092 .buffer_snapshot
11093 .buffer_line_for_row(MultiBufferRow(point.row))?
11094 .1
11095 .start
11096 .row;
11097
11098 let context_range =
11099 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11100 Some((
11101 (runnable.buffer_id, row),
11102 RunnableTasks {
11103 templates: tasks,
11104 offset: snapshot
11105 .buffer_snapshot
11106 .anchor_before(runnable.run_range.start),
11107 context_range,
11108 column: point.column,
11109 extra_variables: runnable.extra_captures,
11110 },
11111 ))
11112 })
11113 .collect()
11114 }
11115
11116 fn templates_with_tags(
11117 project: &Entity<Project>,
11118 runnable: &mut Runnable,
11119 cx: &mut App,
11120 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11121 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11122 let (worktree_id, file) = project
11123 .buffer_for_id(runnable.buffer, cx)
11124 .and_then(|buffer| buffer.read(cx).file())
11125 .map(|file| (file.worktree_id(cx), file.clone()))
11126 .unzip();
11127
11128 (
11129 project.task_store().read(cx).task_inventory().cloned(),
11130 worktree_id,
11131 file,
11132 )
11133 });
11134
11135 let tags = mem::take(&mut runnable.tags);
11136 let mut tags: Vec<_> = tags
11137 .into_iter()
11138 .flat_map(|tag| {
11139 let tag = tag.0.clone();
11140 inventory
11141 .as_ref()
11142 .into_iter()
11143 .flat_map(|inventory| {
11144 inventory.read(cx).list_tasks(
11145 file.clone(),
11146 Some(runnable.language.clone()),
11147 worktree_id,
11148 cx,
11149 )
11150 })
11151 .filter(move |(_, template)| {
11152 template.tags.iter().any(|source_tag| source_tag == &tag)
11153 })
11154 })
11155 .sorted_by_key(|(kind, _)| kind.to_owned())
11156 .collect();
11157 if let Some((leading_tag_source, _)) = tags.first() {
11158 // Strongest source wins; if we have worktree tag binding, prefer that to
11159 // global and language bindings;
11160 // if we have a global binding, prefer that to language binding.
11161 let first_mismatch = tags
11162 .iter()
11163 .position(|(tag_source, _)| tag_source != leading_tag_source);
11164 if let Some(index) = first_mismatch {
11165 tags.truncate(index);
11166 }
11167 }
11168
11169 tags
11170 }
11171
11172 pub fn move_to_enclosing_bracket(
11173 &mut self,
11174 _: &MoveToEnclosingBracket,
11175 window: &mut Window,
11176 cx: &mut Context<Self>,
11177 ) {
11178 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11179 s.move_offsets_with(|snapshot, selection| {
11180 let Some(enclosing_bracket_ranges) =
11181 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11182 else {
11183 return;
11184 };
11185
11186 let mut best_length = usize::MAX;
11187 let mut best_inside = false;
11188 let mut best_in_bracket_range = false;
11189 let mut best_destination = None;
11190 for (open, close) in enclosing_bracket_ranges {
11191 let close = close.to_inclusive();
11192 let length = close.end() - open.start;
11193 let inside = selection.start >= open.end && selection.end <= *close.start();
11194 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11195 || close.contains(&selection.head());
11196
11197 // If best is next to a bracket and current isn't, skip
11198 if !in_bracket_range && best_in_bracket_range {
11199 continue;
11200 }
11201
11202 // Prefer smaller lengths unless best is inside and current isn't
11203 if length > best_length && (best_inside || !inside) {
11204 continue;
11205 }
11206
11207 best_length = length;
11208 best_inside = inside;
11209 best_in_bracket_range = in_bracket_range;
11210 best_destination = Some(
11211 if close.contains(&selection.start) && close.contains(&selection.end) {
11212 if inside {
11213 open.end
11214 } else {
11215 open.start
11216 }
11217 } else if inside {
11218 *close.start()
11219 } else {
11220 *close.end()
11221 },
11222 );
11223 }
11224
11225 if let Some(destination) = best_destination {
11226 selection.collapse_to(destination, SelectionGoal::None);
11227 }
11228 })
11229 });
11230 }
11231
11232 pub fn undo_selection(
11233 &mut self,
11234 _: &UndoSelection,
11235 window: &mut Window,
11236 cx: &mut Context<Self>,
11237 ) {
11238 self.end_selection(window, cx);
11239 self.selection_history.mode = SelectionHistoryMode::Undoing;
11240 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11241 self.change_selections(None, window, cx, |s| {
11242 s.select_anchors(entry.selections.to_vec())
11243 });
11244 self.select_next_state = entry.select_next_state;
11245 self.select_prev_state = entry.select_prev_state;
11246 self.add_selections_state = entry.add_selections_state;
11247 self.request_autoscroll(Autoscroll::newest(), cx);
11248 }
11249 self.selection_history.mode = SelectionHistoryMode::Normal;
11250 }
11251
11252 pub fn redo_selection(
11253 &mut self,
11254 _: &RedoSelection,
11255 window: &mut Window,
11256 cx: &mut Context<Self>,
11257 ) {
11258 self.end_selection(window, cx);
11259 self.selection_history.mode = SelectionHistoryMode::Redoing;
11260 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11261 self.change_selections(None, window, cx, |s| {
11262 s.select_anchors(entry.selections.to_vec())
11263 });
11264 self.select_next_state = entry.select_next_state;
11265 self.select_prev_state = entry.select_prev_state;
11266 self.add_selections_state = entry.add_selections_state;
11267 self.request_autoscroll(Autoscroll::newest(), cx);
11268 }
11269 self.selection_history.mode = SelectionHistoryMode::Normal;
11270 }
11271
11272 pub fn expand_excerpts(
11273 &mut self,
11274 action: &ExpandExcerpts,
11275 _: &mut Window,
11276 cx: &mut Context<Self>,
11277 ) {
11278 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11279 }
11280
11281 pub fn expand_excerpts_down(
11282 &mut self,
11283 action: &ExpandExcerptsDown,
11284 _: &mut Window,
11285 cx: &mut Context<Self>,
11286 ) {
11287 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11288 }
11289
11290 pub fn expand_excerpts_up(
11291 &mut self,
11292 action: &ExpandExcerptsUp,
11293 _: &mut Window,
11294 cx: &mut Context<Self>,
11295 ) {
11296 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11297 }
11298
11299 pub fn expand_excerpts_for_direction(
11300 &mut self,
11301 lines: u32,
11302 direction: ExpandExcerptDirection,
11303
11304 cx: &mut Context<Self>,
11305 ) {
11306 let selections = self.selections.disjoint_anchors();
11307
11308 let lines = if lines == 0 {
11309 EditorSettings::get_global(cx).expand_excerpt_lines
11310 } else {
11311 lines
11312 };
11313
11314 self.buffer.update(cx, |buffer, cx| {
11315 let snapshot = buffer.snapshot(cx);
11316 let mut excerpt_ids = selections
11317 .iter()
11318 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11319 .collect::<Vec<_>>();
11320 excerpt_ids.sort();
11321 excerpt_ids.dedup();
11322 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11323 })
11324 }
11325
11326 pub fn expand_excerpt(
11327 &mut self,
11328 excerpt: ExcerptId,
11329 direction: ExpandExcerptDirection,
11330 cx: &mut Context<Self>,
11331 ) {
11332 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11333 self.buffer.update(cx, |buffer, cx| {
11334 buffer.expand_excerpts([excerpt], lines, direction, cx)
11335 })
11336 }
11337
11338 pub fn go_to_singleton_buffer_point(
11339 &mut self,
11340 point: Point,
11341 window: &mut Window,
11342 cx: &mut Context<Self>,
11343 ) {
11344 self.go_to_singleton_buffer_range(point..point, window, cx);
11345 }
11346
11347 pub fn go_to_singleton_buffer_range(
11348 &mut self,
11349 range: Range<Point>,
11350 window: &mut Window,
11351 cx: &mut Context<Self>,
11352 ) {
11353 let multibuffer = self.buffer().read(cx);
11354 let Some(buffer) = multibuffer.as_singleton() else {
11355 return;
11356 };
11357 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11358 return;
11359 };
11360 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11361 return;
11362 };
11363 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11364 s.select_anchor_ranges([start..end])
11365 });
11366 }
11367
11368 fn go_to_diagnostic(
11369 &mut self,
11370 _: &GoToDiagnostic,
11371 window: &mut Window,
11372 cx: &mut Context<Self>,
11373 ) {
11374 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11375 }
11376
11377 fn go_to_prev_diagnostic(
11378 &mut self,
11379 _: &GoToPreviousDiagnostic,
11380 window: &mut Window,
11381 cx: &mut Context<Self>,
11382 ) {
11383 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11384 }
11385
11386 pub fn go_to_diagnostic_impl(
11387 &mut self,
11388 direction: Direction,
11389 window: &mut Window,
11390 cx: &mut Context<Self>,
11391 ) {
11392 let buffer = self.buffer.read(cx).snapshot(cx);
11393 let selection = self.selections.newest::<usize>(cx);
11394
11395 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11396 if direction == Direction::Next {
11397 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11398 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11399 return;
11400 };
11401 self.activate_diagnostics(
11402 buffer_id,
11403 popover.local_diagnostic.diagnostic.group_id,
11404 window,
11405 cx,
11406 );
11407 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11408 let primary_range_start = active_diagnostics.primary_range.start;
11409 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11410 let mut new_selection = s.newest_anchor().clone();
11411 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11412 s.select_anchors(vec![new_selection.clone()]);
11413 });
11414 self.refresh_inline_completion(false, true, window, cx);
11415 }
11416 return;
11417 }
11418 }
11419
11420 let active_group_id = self
11421 .active_diagnostics
11422 .as_ref()
11423 .map(|active_group| active_group.group_id);
11424 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11425 active_diagnostics
11426 .primary_range
11427 .to_offset(&buffer)
11428 .to_inclusive()
11429 });
11430 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11431 if active_primary_range.contains(&selection.head()) {
11432 *active_primary_range.start()
11433 } else {
11434 selection.head()
11435 }
11436 } else {
11437 selection.head()
11438 };
11439
11440 let snapshot = self.snapshot(window, cx);
11441 let primary_diagnostics_before = buffer
11442 .diagnostics_in_range::<usize>(0..search_start)
11443 .filter(|entry| entry.diagnostic.is_primary)
11444 .filter(|entry| entry.range.start != entry.range.end)
11445 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11446 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11447 .collect::<Vec<_>>();
11448 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11449 primary_diagnostics_before
11450 .iter()
11451 .position(|entry| entry.diagnostic.group_id == active_group_id)
11452 });
11453
11454 let primary_diagnostics_after = buffer
11455 .diagnostics_in_range::<usize>(search_start..buffer.len())
11456 .filter(|entry| entry.diagnostic.is_primary)
11457 .filter(|entry| entry.range.start != entry.range.end)
11458 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11459 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11460 .collect::<Vec<_>>();
11461 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11462 primary_diagnostics_after
11463 .iter()
11464 .enumerate()
11465 .rev()
11466 .find_map(|(i, entry)| {
11467 if entry.diagnostic.group_id == active_group_id {
11468 Some(i)
11469 } else {
11470 None
11471 }
11472 })
11473 });
11474
11475 let next_primary_diagnostic = match direction {
11476 Direction::Prev => primary_diagnostics_before
11477 .iter()
11478 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11479 .rev()
11480 .next(),
11481 Direction::Next => primary_diagnostics_after
11482 .iter()
11483 .skip(
11484 last_same_group_diagnostic_after
11485 .map(|index| index + 1)
11486 .unwrap_or(0),
11487 )
11488 .next(),
11489 };
11490
11491 // Cycle around to the start of the buffer, potentially moving back to the start of
11492 // the currently active diagnostic.
11493 let cycle_around = || match direction {
11494 Direction::Prev => primary_diagnostics_after
11495 .iter()
11496 .rev()
11497 .chain(primary_diagnostics_before.iter().rev())
11498 .next(),
11499 Direction::Next => primary_diagnostics_before
11500 .iter()
11501 .chain(primary_diagnostics_after.iter())
11502 .next(),
11503 };
11504
11505 if let Some((primary_range, group_id)) = next_primary_diagnostic
11506 .or_else(cycle_around)
11507 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11508 {
11509 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11510 return;
11511 };
11512 self.activate_diagnostics(buffer_id, group_id, window, cx);
11513 if self.active_diagnostics.is_some() {
11514 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11515 s.select(vec![Selection {
11516 id: selection.id,
11517 start: primary_range.start,
11518 end: primary_range.start,
11519 reversed: false,
11520 goal: SelectionGoal::None,
11521 }]);
11522 });
11523 self.refresh_inline_completion(false, true, window, cx);
11524 }
11525 }
11526 }
11527
11528 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11529 let snapshot = self.snapshot(window, cx);
11530 let selection = self.selections.newest::<Point>(cx);
11531 self.go_to_hunk_after_or_before_position(
11532 &snapshot,
11533 selection.head(),
11534 Direction::Next,
11535 window,
11536 cx,
11537 );
11538 }
11539
11540 fn go_to_hunk_after_or_before_position(
11541 &mut self,
11542 snapshot: &EditorSnapshot,
11543 position: Point,
11544 direction: Direction,
11545 window: &mut Window,
11546 cx: &mut Context<Editor>,
11547 ) {
11548 let row = if direction == Direction::Next {
11549 self.hunk_after_position(snapshot, position)
11550 .map(|hunk| hunk.row_range.start)
11551 } else {
11552 self.hunk_before_position(snapshot, position)
11553 };
11554
11555 if let Some(row) = row {
11556 let destination = Point::new(row.0, 0);
11557 let autoscroll = Autoscroll::center();
11558
11559 self.unfold_ranges(&[destination..destination], false, false, cx);
11560 self.change_selections(Some(autoscroll), window, cx, |s| {
11561 s.select_ranges([destination..destination]);
11562 });
11563 }
11564 }
11565
11566 fn hunk_after_position(
11567 &mut self,
11568 snapshot: &EditorSnapshot,
11569 position: Point,
11570 ) -> Option<MultiBufferDiffHunk> {
11571 snapshot
11572 .buffer_snapshot
11573 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11574 .find(|hunk| hunk.row_range.start.0 > position.row)
11575 .or_else(|| {
11576 snapshot
11577 .buffer_snapshot
11578 .diff_hunks_in_range(Point::zero()..position)
11579 .find(|hunk| hunk.row_range.end.0 < position.row)
11580 })
11581 }
11582
11583 fn go_to_prev_hunk(
11584 &mut self,
11585 _: &GoToPreviousHunk,
11586 window: &mut Window,
11587 cx: &mut Context<Self>,
11588 ) {
11589 let snapshot = self.snapshot(window, cx);
11590 let selection = self.selections.newest::<Point>(cx);
11591 self.go_to_hunk_after_or_before_position(
11592 &snapshot,
11593 selection.head(),
11594 Direction::Prev,
11595 window,
11596 cx,
11597 );
11598 }
11599
11600 fn hunk_before_position(
11601 &mut self,
11602 snapshot: &EditorSnapshot,
11603 position: Point,
11604 ) -> Option<MultiBufferRow> {
11605 snapshot
11606 .buffer_snapshot
11607 .diff_hunk_before(position)
11608 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11609 }
11610
11611 pub fn go_to_definition(
11612 &mut self,
11613 _: &GoToDefinition,
11614 window: &mut Window,
11615 cx: &mut Context<Self>,
11616 ) -> Task<Result<Navigated>> {
11617 let definition =
11618 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11619 cx.spawn_in(window, |editor, mut cx| async move {
11620 if definition.await? == Navigated::Yes {
11621 return Ok(Navigated::Yes);
11622 }
11623 match editor.update_in(&mut cx, |editor, window, cx| {
11624 editor.find_all_references(&FindAllReferences, window, cx)
11625 })? {
11626 Some(references) => references.await,
11627 None => Ok(Navigated::No),
11628 }
11629 })
11630 }
11631
11632 pub fn go_to_declaration(
11633 &mut self,
11634 _: &GoToDeclaration,
11635 window: &mut Window,
11636 cx: &mut Context<Self>,
11637 ) -> Task<Result<Navigated>> {
11638 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11639 }
11640
11641 pub fn go_to_declaration_split(
11642 &mut self,
11643 _: &GoToDeclaration,
11644 window: &mut Window,
11645 cx: &mut Context<Self>,
11646 ) -> Task<Result<Navigated>> {
11647 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11648 }
11649
11650 pub fn go_to_implementation(
11651 &mut self,
11652 _: &GoToImplementation,
11653 window: &mut Window,
11654 cx: &mut Context<Self>,
11655 ) -> Task<Result<Navigated>> {
11656 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11657 }
11658
11659 pub fn go_to_implementation_split(
11660 &mut self,
11661 _: &GoToImplementationSplit,
11662 window: &mut Window,
11663 cx: &mut Context<Self>,
11664 ) -> Task<Result<Navigated>> {
11665 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11666 }
11667
11668 pub fn go_to_type_definition(
11669 &mut self,
11670 _: &GoToTypeDefinition,
11671 window: &mut Window,
11672 cx: &mut Context<Self>,
11673 ) -> Task<Result<Navigated>> {
11674 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11675 }
11676
11677 pub fn go_to_definition_split(
11678 &mut self,
11679 _: &GoToDefinitionSplit,
11680 window: &mut Window,
11681 cx: &mut Context<Self>,
11682 ) -> Task<Result<Navigated>> {
11683 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11684 }
11685
11686 pub fn go_to_type_definition_split(
11687 &mut self,
11688 _: &GoToTypeDefinitionSplit,
11689 window: &mut Window,
11690 cx: &mut Context<Self>,
11691 ) -> Task<Result<Navigated>> {
11692 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11693 }
11694
11695 fn go_to_definition_of_kind(
11696 &mut self,
11697 kind: GotoDefinitionKind,
11698 split: bool,
11699 window: &mut Window,
11700 cx: &mut Context<Self>,
11701 ) -> Task<Result<Navigated>> {
11702 let Some(provider) = self.semantics_provider.clone() else {
11703 return Task::ready(Ok(Navigated::No));
11704 };
11705 let head = self.selections.newest::<usize>(cx).head();
11706 let buffer = self.buffer.read(cx);
11707 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11708 text_anchor
11709 } else {
11710 return Task::ready(Ok(Navigated::No));
11711 };
11712
11713 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11714 return Task::ready(Ok(Navigated::No));
11715 };
11716
11717 cx.spawn_in(window, |editor, mut cx| async move {
11718 let definitions = definitions.await?;
11719 let navigated = editor
11720 .update_in(&mut cx, |editor, window, cx| {
11721 editor.navigate_to_hover_links(
11722 Some(kind),
11723 definitions
11724 .into_iter()
11725 .filter(|location| {
11726 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11727 })
11728 .map(HoverLink::Text)
11729 .collect::<Vec<_>>(),
11730 split,
11731 window,
11732 cx,
11733 )
11734 })?
11735 .await?;
11736 anyhow::Ok(navigated)
11737 })
11738 }
11739
11740 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11741 let selection = self.selections.newest_anchor();
11742 let head = selection.head();
11743 let tail = selection.tail();
11744
11745 let Some((buffer, start_position)) =
11746 self.buffer.read(cx).text_anchor_for_position(head, cx)
11747 else {
11748 return;
11749 };
11750
11751 let end_position = if head != tail {
11752 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11753 return;
11754 };
11755 Some(pos)
11756 } else {
11757 None
11758 };
11759
11760 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11761 let url = if let Some(end_pos) = end_position {
11762 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11763 } else {
11764 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11765 };
11766
11767 if let Some(url) = url {
11768 editor.update(&mut cx, |_, cx| {
11769 cx.open_url(&url);
11770 })
11771 } else {
11772 Ok(())
11773 }
11774 });
11775
11776 url_finder.detach();
11777 }
11778
11779 pub fn open_selected_filename(
11780 &mut self,
11781 _: &OpenSelectedFilename,
11782 window: &mut Window,
11783 cx: &mut Context<Self>,
11784 ) {
11785 let Some(workspace) = self.workspace() else {
11786 return;
11787 };
11788
11789 let position = self.selections.newest_anchor().head();
11790
11791 let Some((buffer, buffer_position)) =
11792 self.buffer.read(cx).text_anchor_for_position(position, cx)
11793 else {
11794 return;
11795 };
11796
11797 let project = self.project.clone();
11798
11799 cx.spawn_in(window, |_, mut cx| async move {
11800 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11801
11802 if let Some((_, path)) = result {
11803 workspace
11804 .update_in(&mut cx, |workspace, window, cx| {
11805 workspace.open_resolved_path(path, window, cx)
11806 })?
11807 .await?;
11808 }
11809 anyhow::Ok(())
11810 })
11811 .detach();
11812 }
11813
11814 pub(crate) fn navigate_to_hover_links(
11815 &mut self,
11816 kind: Option<GotoDefinitionKind>,
11817 mut definitions: Vec<HoverLink>,
11818 split: bool,
11819 window: &mut Window,
11820 cx: &mut Context<Editor>,
11821 ) -> Task<Result<Navigated>> {
11822 // If there is one definition, just open it directly
11823 if definitions.len() == 1 {
11824 let definition = definitions.pop().unwrap();
11825
11826 enum TargetTaskResult {
11827 Location(Option<Location>),
11828 AlreadyNavigated,
11829 }
11830
11831 let target_task = match definition {
11832 HoverLink::Text(link) => {
11833 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11834 }
11835 HoverLink::InlayHint(lsp_location, server_id) => {
11836 let computation =
11837 self.compute_target_location(lsp_location, server_id, window, cx);
11838 cx.background_spawn(async move {
11839 let location = computation.await?;
11840 Ok(TargetTaskResult::Location(location))
11841 })
11842 }
11843 HoverLink::Url(url) => {
11844 cx.open_url(&url);
11845 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11846 }
11847 HoverLink::File(path) => {
11848 if let Some(workspace) = self.workspace() {
11849 cx.spawn_in(window, |_, mut cx| async move {
11850 workspace
11851 .update_in(&mut cx, |workspace, window, cx| {
11852 workspace.open_resolved_path(path, window, cx)
11853 })?
11854 .await
11855 .map(|_| TargetTaskResult::AlreadyNavigated)
11856 })
11857 } else {
11858 Task::ready(Ok(TargetTaskResult::Location(None)))
11859 }
11860 }
11861 };
11862 cx.spawn_in(window, |editor, mut cx| async move {
11863 let target = match target_task.await.context("target resolution task")? {
11864 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11865 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11866 TargetTaskResult::Location(Some(target)) => target,
11867 };
11868
11869 editor.update_in(&mut cx, |editor, window, cx| {
11870 let Some(workspace) = editor.workspace() else {
11871 return Navigated::No;
11872 };
11873 let pane = workspace.read(cx).active_pane().clone();
11874
11875 let range = target.range.to_point(target.buffer.read(cx));
11876 let range = editor.range_for_match(&range);
11877 let range = collapse_multiline_range(range);
11878
11879 if !split
11880 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11881 {
11882 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11883 } else {
11884 window.defer(cx, move |window, cx| {
11885 let target_editor: Entity<Self> =
11886 workspace.update(cx, |workspace, cx| {
11887 let pane = if split {
11888 workspace.adjacent_pane(window, cx)
11889 } else {
11890 workspace.active_pane().clone()
11891 };
11892
11893 workspace.open_project_item(
11894 pane,
11895 target.buffer.clone(),
11896 true,
11897 true,
11898 window,
11899 cx,
11900 )
11901 });
11902 target_editor.update(cx, |target_editor, cx| {
11903 // When selecting a definition in a different buffer, disable the nav history
11904 // to avoid creating a history entry at the previous cursor location.
11905 pane.update(cx, |pane, _| pane.disable_history());
11906 target_editor.go_to_singleton_buffer_range(range, window, cx);
11907 pane.update(cx, |pane, _| pane.enable_history());
11908 });
11909 });
11910 }
11911 Navigated::Yes
11912 })
11913 })
11914 } else if !definitions.is_empty() {
11915 cx.spawn_in(window, |editor, mut cx| async move {
11916 let (title, location_tasks, workspace) = editor
11917 .update_in(&mut cx, |editor, window, cx| {
11918 let tab_kind = match kind {
11919 Some(GotoDefinitionKind::Implementation) => "Implementations",
11920 _ => "Definitions",
11921 };
11922 let title = definitions
11923 .iter()
11924 .find_map(|definition| match definition {
11925 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11926 let buffer = origin.buffer.read(cx);
11927 format!(
11928 "{} for {}",
11929 tab_kind,
11930 buffer
11931 .text_for_range(origin.range.clone())
11932 .collect::<String>()
11933 )
11934 }),
11935 HoverLink::InlayHint(_, _) => None,
11936 HoverLink::Url(_) => None,
11937 HoverLink::File(_) => None,
11938 })
11939 .unwrap_or(tab_kind.to_string());
11940 let location_tasks = definitions
11941 .into_iter()
11942 .map(|definition| match definition {
11943 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11944 HoverLink::InlayHint(lsp_location, server_id) => editor
11945 .compute_target_location(lsp_location, server_id, window, cx),
11946 HoverLink::Url(_) => Task::ready(Ok(None)),
11947 HoverLink::File(_) => Task::ready(Ok(None)),
11948 })
11949 .collect::<Vec<_>>();
11950 (title, location_tasks, editor.workspace().clone())
11951 })
11952 .context("location tasks preparation")?;
11953
11954 let locations = future::join_all(location_tasks)
11955 .await
11956 .into_iter()
11957 .filter_map(|location| location.transpose())
11958 .collect::<Result<_>>()
11959 .context("location tasks")?;
11960
11961 let Some(workspace) = workspace else {
11962 return Ok(Navigated::No);
11963 };
11964 let opened = workspace
11965 .update_in(&mut cx, |workspace, window, cx| {
11966 Self::open_locations_in_multibuffer(
11967 workspace,
11968 locations,
11969 title,
11970 split,
11971 MultibufferSelectionMode::First,
11972 window,
11973 cx,
11974 )
11975 })
11976 .ok();
11977
11978 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11979 })
11980 } else {
11981 Task::ready(Ok(Navigated::No))
11982 }
11983 }
11984
11985 fn compute_target_location(
11986 &self,
11987 lsp_location: lsp::Location,
11988 server_id: LanguageServerId,
11989 window: &mut Window,
11990 cx: &mut Context<Self>,
11991 ) -> Task<anyhow::Result<Option<Location>>> {
11992 let Some(project) = self.project.clone() else {
11993 return Task::ready(Ok(None));
11994 };
11995
11996 cx.spawn_in(window, move |editor, mut cx| async move {
11997 let location_task = editor.update(&mut cx, |_, cx| {
11998 project.update(cx, |project, cx| {
11999 let language_server_name = project
12000 .language_server_statuses(cx)
12001 .find(|(id, _)| server_id == *id)
12002 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12003 language_server_name.map(|language_server_name| {
12004 project.open_local_buffer_via_lsp(
12005 lsp_location.uri.clone(),
12006 server_id,
12007 language_server_name,
12008 cx,
12009 )
12010 })
12011 })
12012 })?;
12013 let location = match location_task {
12014 Some(task) => Some({
12015 let target_buffer_handle = task.await.context("open local buffer")?;
12016 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12017 let target_start = target_buffer
12018 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12019 let target_end = target_buffer
12020 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12021 target_buffer.anchor_after(target_start)
12022 ..target_buffer.anchor_before(target_end)
12023 })?;
12024 Location {
12025 buffer: target_buffer_handle,
12026 range,
12027 }
12028 }),
12029 None => None,
12030 };
12031 Ok(location)
12032 })
12033 }
12034
12035 pub fn find_all_references(
12036 &mut self,
12037 _: &FindAllReferences,
12038 window: &mut Window,
12039 cx: &mut Context<Self>,
12040 ) -> Option<Task<Result<Navigated>>> {
12041 let selection = self.selections.newest::<usize>(cx);
12042 let multi_buffer = self.buffer.read(cx);
12043 let head = selection.head();
12044
12045 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12046 let head_anchor = multi_buffer_snapshot.anchor_at(
12047 head,
12048 if head < selection.tail() {
12049 Bias::Right
12050 } else {
12051 Bias::Left
12052 },
12053 );
12054
12055 match self
12056 .find_all_references_task_sources
12057 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12058 {
12059 Ok(_) => {
12060 log::info!(
12061 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12062 );
12063 return None;
12064 }
12065 Err(i) => {
12066 self.find_all_references_task_sources.insert(i, head_anchor);
12067 }
12068 }
12069
12070 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12071 let workspace = self.workspace()?;
12072 let project = workspace.read(cx).project().clone();
12073 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12074 Some(cx.spawn_in(window, |editor, mut cx| async move {
12075 let _cleanup = defer({
12076 let mut cx = cx.clone();
12077 move || {
12078 let _ = editor.update(&mut cx, |editor, _| {
12079 if let Ok(i) =
12080 editor
12081 .find_all_references_task_sources
12082 .binary_search_by(|anchor| {
12083 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12084 })
12085 {
12086 editor.find_all_references_task_sources.remove(i);
12087 }
12088 });
12089 }
12090 });
12091
12092 let locations = references.await?;
12093 if locations.is_empty() {
12094 return anyhow::Ok(Navigated::No);
12095 }
12096
12097 workspace.update_in(&mut cx, |workspace, window, cx| {
12098 let title = locations
12099 .first()
12100 .as_ref()
12101 .map(|location| {
12102 let buffer = location.buffer.read(cx);
12103 format!(
12104 "References to `{}`",
12105 buffer
12106 .text_for_range(location.range.clone())
12107 .collect::<String>()
12108 )
12109 })
12110 .unwrap();
12111 Self::open_locations_in_multibuffer(
12112 workspace,
12113 locations,
12114 title,
12115 false,
12116 MultibufferSelectionMode::First,
12117 window,
12118 cx,
12119 );
12120 Navigated::Yes
12121 })
12122 }))
12123 }
12124
12125 /// Opens a multibuffer with the given project locations in it
12126 pub fn open_locations_in_multibuffer(
12127 workspace: &mut Workspace,
12128 mut locations: Vec<Location>,
12129 title: String,
12130 split: bool,
12131 multibuffer_selection_mode: MultibufferSelectionMode,
12132 window: &mut Window,
12133 cx: &mut Context<Workspace>,
12134 ) {
12135 // If there are multiple definitions, open them in a multibuffer
12136 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12137 let mut locations = locations.into_iter().peekable();
12138 let mut ranges = Vec::new();
12139 let capability = workspace.project().read(cx).capability();
12140
12141 let excerpt_buffer = cx.new(|cx| {
12142 let mut multibuffer = MultiBuffer::new(capability);
12143 while let Some(location) = locations.next() {
12144 let buffer = location.buffer.read(cx);
12145 let mut ranges_for_buffer = Vec::new();
12146 let range = location.range.to_offset(buffer);
12147 ranges_for_buffer.push(range.clone());
12148
12149 while let Some(next_location) = locations.peek() {
12150 if next_location.buffer == location.buffer {
12151 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12152 locations.next();
12153 } else {
12154 break;
12155 }
12156 }
12157
12158 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12159 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12160 location.buffer.clone(),
12161 ranges_for_buffer,
12162 DEFAULT_MULTIBUFFER_CONTEXT,
12163 cx,
12164 ))
12165 }
12166
12167 multibuffer.with_title(title)
12168 });
12169
12170 let editor = cx.new(|cx| {
12171 Editor::for_multibuffer(
12172 excerpt_buffer,
12173 Some(workspace.project().clone()),
12174 true,
12175 window,
12176 cx,
12177 )
12178 });
12179 editor.update(cx, |editor, cx| {
12180 match multibuffer_selection_mode {
12181 MultibufferSelectionMode::First => {
12182 if let Some(first_range) = ranges.first() {
12183 editor.change_selections(None, window, cx, |selections| {
12184 selections.clear_disjoint();
12185 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12186 });
12187 }
12188 editor.highlight_background::<Self>(
12189 &ranges,
12190 |theme| theme.editor_highlighted_line_background,
12191 cx,
12192 );
12193 }
12194 MultibufferSelectionMode::All => {
12195 editor.change_selections(None, window, cx, |selections| {
12196 selections.clear_disjoint();
12197 selections.select_anchor_ranges(ranges);
12198 });
12199 }
12200 }
12201 editor.register_buffers_with_language_servers(cx);
12202 });
12203
12204 let item = Box::new(editor);
12205 let item_id = item.item_id();
12206
12207 if split {
12208 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12209 } else {
12210 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12211 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12212 pane.close_current_preview_item(window, cx)
12213 } else {
12214 None
12215 }
12216 });
12217 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12218 }
12219 workspace.active_pane().update(cx, |pane, cx| {
12220 pane.set_preview_item_id(Some(item_id), cx);
12221 });
12222 }
12223
12224 pub fn rename(
12225 &mut self,
12226 _: &Rename,
12227 window: &mut Window,
12228 cx: &mut Context<Self>,
12229 ) -> Option<Task<Result<()>>> {
12230 use language::ToOffset as _;
12231
12232 let provider = self.semantics_provider.clone()?;
12233 let selection = self.selections.newest_anchor().clone();
12234 let (cursor_buffer, cursor_buffer_position) = self
12235 .buffer
12236 .read(cx)
12237 .text_anchor_for_position(selection.head(), cx)?;
12238 let (tail_buffer, cursor_buffer_position_end) = self
12239 .buffer
12240 .read(cx)
12241 .text_anchor_for_position(selection.tail(), cx)?;
12242 if tail_buffer != cursor_buffer {
12243 return None;
12244 }
12245
12246 let snapshot = cursor_buffer.read(cx).snapshot();
12247 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12248 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12249 let prepare_rename = provider
12250 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12251 .unwrap_or_else(|| Task::ready(Ok(None)));
12252 drop(snapshot);
12253
12254 Some(cx.spawn_in(window, |this, mut cx| async move {
12255 let rename_range = if let Some(range) = prepare_rename.await? {
12256 Some(range)
12257 } else {
12258 this.update(&mut cx, |this, cx| {
12259 let buffer = this.buffer.read(cx).snapshot(cx);
12260 let mut buffer_highlights = this
12261 .document_highlights_for_position(selection.head(), &buffer)
12262 .filter(|highlight| {
12263 highlight.start.excerpt_id == selection.head().excerpt_id
12264 && highlight.end.excerpt_id == selection.head().excerpt_id
12265 });
12266 buffer_highlights
12267 .next()
12268 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12269 })?
12270 };
12271 if let Some(rename_range) = rename_range {
12272 this.update_in(&mut cx, |this, window, cx| {
12273 let snapshot = cursor_buffer.read(cx).snapshot();
12274 let rename_buffer_range = rename_range.to_offset(&snapshot);
12275 let cursor_offset_in_rename_range =
12276 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12277 let cursor_offset_in_rename_range_end =
12278 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12279
12280 this.take_rename(false, window, cx);
12281 let buffer = this.buffer.read(cx).read(cx);
12282 let cursor_offset = selection.head().to_offset(&buffer);
12283 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12284 let rename_end = rename_start + rename_buffer_range.len();
12285 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12286 let mut old_highlight_id = None;
12287 let old_name: Arc<str> = buffer
12288 .chunks(rename_start..rename_end, true)
12289 .map(|chunk| {
12290 if old_highlight_id.is_none() {
12291 old_highlight_id = chunk.syntax_highlight_id;
12292 }
12293 chunk.text
12294 })
12295 .collect::<String>()
12296 .into();
12297
12298 drop(buffer);
12299
12300 // Position the selection in the rename editor so that it matches the current selection.
12301 this.show_local_selections = false;
12302 let rename_editor = cx.new(|cx| {
12303 let mut editor = Editor::single_line(window, cx);
12304 editor.buffer.update(cx, |buffer, cx| {
12305 buffer.edit([(0..0, old_name.clone())], None, cx)
12306 });
12307 let rename_selection_range = match cursor_offset_in_rename_range
12308 .cmp(&cursor_offset_in_rename_range_end)
12309 {
12310 Ordering::Equal => {
12311 editor.select_all(&SelectAll, window, cx);
12312 return editor;
12313 }
12314 Ordering::Less => {
12315 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12316 }
12317 Ordering::Greater => {
12318 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12319 }
12320 };
12321 if rename_selection_range.end > old_name.len() {
12322 editor.select_all(&SelectAll, window, cx);
12323 } else {
12324 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12325 s.select_ranges([rename_selection_range]);
12326 });
12327 }
12328 editor
12329 });
12330 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12331 if e == &EditorEvent::Focused {
12332 cx.emit(EditorEvent::FocusedIn)
12333 }
12334 })
12335 .detach();
12336
12337 let write_highlights =
12338 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12339 let read_highlights =
12340 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12341 let ranges = write_highlights
12342 .iter()
12343 .flat_map(|(_, ranges)| ranges.iter())
12344 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12345 .cloned()
12346 .collect();
12347
12348 this.highlight_text::<Rename>(
12349 ranges,
12350 HighlightStyle {
12351 fade_out: Some(0.6),
12352 ..Default::default()
12353 },
12354 cx,
12355 );
12356 let rename_focus_handle = rename_editor.focus_handle(cx);
12357 window.focus(&rename_focus_handle);
12358 let block_id = this.insert_blocks(
12359 [BlockProperties {
12360 style: BlockStyle::Flex,
12361 placement: BlockPlacement::Below(range.start),
12362 height: 1,
12363 render: Arc::new({
12364 let rename_editor = rename_editor.clone();
12365 move |cx: &mut BlockContext| {
12366 let mut text_style = cx.editor_style.text.clone();
12367 if let Some(highlight_style) = old_highlight_id
12368 .and_then(|h| h.style(&cx.editor_style.syntax))
12369 {
12370 text_style = text_style.highlight(highlight_style);
12371 }
12372 div()
12373 .block_mouse_down()
12374 .pl(cx.anchor_x)
12375 .child(EditorElement::new(
12376 &rename_editor,
12377 EditorStyle {
12378 background: cx.theme().system().transparent,
12379 local_player: cx.editor_style.local_player,
12380 text: text_style,
12381 scrollbar_width: cx.editor_style.scrollbar_width,
12382 syntax: cx.editor_style.syntax.clone(),
12383 status: cx.editor_style.status.clone(),
12384 inlay_hints_style: HighlightStyle {
12385 font_weight: Some(FontWeight::BOLD),
12386 ..make_inlay_hints_style(cx.app)
12387 },
12388 inline_completion_styles: make_suggestion_styles(
12389 cx.app,
12390 ),
12391 ..EditorStyle::default()
12392 },
12393 ))
12394 .into_any_element()
12395 }
12396 }),
12397 priority: 0,
12398 }],
12399 Some(Autoscroll::fit()),
12400 cx,
12401 )[0];
12402 this.pending_rename = Some(RenameState {
12403 range,
12404 old_name,
12405 editor: rename_editor,
12406 block_id,
12407 });
12408 })?;
12409 }
12410
12411 Ok(())
12412 }))
12413 }
12414
12415 pub fn confirm_rename(
12416 &mut self,
12417 _: &ConfirmRename,
12418 window: &mut Window,
12419 cx: &mut Context<Self>,
12420 ) -> Option<Task<Result<()>>> {
12421 let rename = self.take_rename(false, window, cx)?;
12422 let workspace = self.workspace()?.downgrade();
12423 let (buffer, start) = self
12424 .buffer
12425 .read(cx)
12426 .text_anchor_for_position(rename.range.start, cx)?;
12427 let (end_buffer, _) = self
12428 .buffer
12429 .read(cx)
12430 .text_anchor_for_position(rename.range.end, cx)?;
12431 if buffer != end_buffer {
12432 return None;
12433 }
12434
12435 let old_name = rename.old_name;
12436 let new_name = rename.editor.read(cx).text(cx);
12437
12438 let rename = self.semantics_provider.as_ref()?.perform_rename(
12439 &buffer,
12440 start,
12441 new_name.clone(),
12442 cx,
12443 )?;
12444
12445 Some(cx.spawn_in(window, |editor, mut cx| async move {
12446 let project_transaction = rename.await?;
12447 Self::open_project_transaction(
12448 &editor,
12449 workspace,
12450 project_transaction,
12451 format!("Rename: {} → {}", old_name, new_name),
12452 cx.clone(),
12453 )
12454 .await?;
12455
12456 editor.update(&mut cx, |editor, cx| {
12457 editor.refresh_document_highlights(cx);
12458 })?;
12459 Ok(())
12460 }))
12461 }
12462
12463 fn take_rename(
12464 &mut self,
12465 moving_cursor: bool,
12466 window: &mut Window,
12467 cx: &mut Context<Self>,
12468 ) -> Option<RenameState> {
12469 let rename = self.pending_rename.take()?;
12470 if rename.editor.focus_handle(cx).is_focused(window) {
12471 window.focus(&self.focus_handle);
12472 }
12473
12474 self.remove_blocks(
12475 [rename.block_id].into_iter().collect(),
12476 Some(Autoscroll::fit()),
12477 cx,
12478 );
12479 self.clear_highlights::<Rename>(cx);
12480 self.show_local_selections = true;
12481
12482 if moving_cursor {
12483 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12484 editor.selections.newest::<usize>(cx).head()
12485 });
12486
12487 // Update the selection to match the position of the selection inside
12488 // the rename editor.
12489 let snapshot = self.buffer.read(cx).read(cx);
12490 let rename_range = rename.range.to_offset(&snapshot);
12491 let cursor_in_editor = snapshot
12492 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12493 .min(rename_range.end);
12494 drop(snapshot);
12495
12496 self.change_selections(None, window, cx, |s| {
12497 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12498 });
12499 } else {
12500 self.refresh_document_highlights(cx);
12501 }
12502
12503 Some(rename)
12504 }
12505
12506 pub fn pending_rename(&self) -> Option<&RenameState> {
12507 self.pending_rename.as_ref()
12508 }
12509
12510 fn format(
12511 &mut self,
12512 _: &Format,
12513 window: &mut Window,
12514 cx: &mut Context<Self>,
12515 ) -> Option<Task<Result<()>>> {
12516 let project = match &self.project {
12517 Some(project) => project.clone(),
12518 None => return None,
12519 };
12520
12521 Some(self.perform_format(
12522 project,
12523 FormatTrigger::Manual,
12524 FormatTarget::Buffers,
12525 window,
12526 cx,
12527 ))
12528 }
12529
12530 fn format_selections(
12531 &mut self,
12532 _: &FormatSelections,
12533 window: &mut Window,
12534 cx: &mut Context<Self>,
12535 ) -> Option<Task<Result<()>>> {
12536 let project = match &self.project {
12537 Some(project) => project.clone(),
12538 None => return None,
12539 };
12540
12541 let ranges = self
12542 .selections
12543 .all_adjusted(cx)
12544 .into_iter()
12545 .map(|selection| selection.range())
12546 .collect_vec();
12547
12548 Some(self.perform_format(
12549 project,
12550 FormatTrigger::Manual,
12551 FormatTarget::Ranges(ranges),
12552 window,
12553 cx,
12554 ))
12555 }
12556
12557 fn perform_format(
12558 &mut self,
12559 project: Entity<Project>,
12560 trigger: FormatTrigger,
12561 target: FormatTarget,
12562 window: &mut Window,
12563 cx: &mut Context<Self>,
12564 ) -> Task<Result<()>> {
12565 let buffer = self.buffer.clone();
12566 let (buffers, target) = match target {
12567 FormatTarget::Buffers => {
12568 let mut buffers = buffer.read(cx).all_buffers();
12569 if trigger == FormatTrigger::Save {
12570 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12571 }
12572 (buffers, LspFormatTarget::Buffers)
12573 }
12574 FormatTarget::Ranges(selection_ranges) => {
12575 let multi_buffer = buffer.read(cx);
12576 let snapshot = multi_buffer.read(cx);
12577 let mut buffers = HashSet::default();
12578 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12579 BTreeMap::new();
12580 for selection_range in selection_ranges {
12581 for (buffer, buffer_range, _) in
12582 snapshot.range_to_buffer_ranges(selection_range)
12583 {
12584 let buffer_id = buffer.remote_id();
12585 let start = buffer.anchor_before(buffer_range.start);
12586 let end = buffer.anchor_after(buffer_range.end);
12587 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12588 buffer_id_to_ranges
12589 .entry(buffer_id)
12590 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12591 .or_insert_with(|| vec![start..end]);
12592 }
12593 }
12594 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12595 }
12596 };
12597
12598 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12599 let format = project.update(cx, |project, cx| {
12600 project.format(buffers, target, true, trigger, cx)
12601 });
12602
12603 cx.spawn_in(window, |_, mut cx| async move {
12604 let transaction = futures::select_biased! {
12605 () = timeout => {
12606 log::warn!("timed out waiting for formatting");
12607 None
12608 }
12609 transaction = format.log_err().fuse() => transaction,
12610 };
12611
12612 buffer
12613 .update(&mut cx, |buffer, cx| {
12614 if let Some(transaction) = transaction {
12615 if !buffer.is_singleton() {
12616 buffer.push_transaction(&transaction.0, cx);
12617 }
12618 }
12619 cx.notify();
12620 })
12621 .ok();
12622
12623 Ok(())
12624 })
12625 }
12626
12627 fn organize_imports(
12628 &mut self,
12629 _: &OrganizeImports,
12630 window: &mut Window,
12631 cx: &mut Context<Self>,
12632 ) -> Option<Task<Result<()>>> {
12633 let project = match &self.project {
12634 Some(project) => project.clone(),
12635 None => return None,
12636 };
12637 Some(self.perform_code_action_kind(
12638 project,
12639 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12640 window,
12641 cx,
12642 ))
12643 }
12644
12645 fn perform_code_action_kind(
12646 &mut self,
12647 project: Entity<Project>,
12648 kind: CodeActionKind,
12649 window: &mut Window,
12650 cx: &mut Context<Self>,
12651 ) -> Task<Result<()>> {
12652 let buffer = self.buffer.clone();
12653 let buffers = buffer.read(cx).all_buffers();
12654 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12655 let apply_action = project.update(cx, |project, cx| {
12656 project.apply_code_action_kind(buffers, kind, true, cx)
12657 });
12658 cx.spawn_in(window, |_, mut cx| async move {
12659 let transaction = futures::select_biased! {
12660 () = timeout => {
12661 log::warn!("timed out waiting for executing code action");
12662 None
12663 }
12664 transaction = apply_action.log_err().fuse() => transaction,
12665 };
12666 buffer
12667 .update(&mut cx, |buffer, cx| {
12668 // check if we need this
12669 if let Some(transaction) = transaction {
12670 if !buffer.is_singleton() {
12671 buffer.push_transaction(&transaction.0, cx);
12672 }
12673 }
12674 cx.notify();
12675 })
12676 .ok();
12677 Ok(())
12678 })
12679 }
12680
12681 fn restart_language_server(
12682 &mut self,
12683 _: &RestartLanguageServer,
12684 _: &mut Window,
12685 cx: &mut Context<Self>,
12686 ) {
12687 if let Some(project) = self.project.clone() {
12688 self.buffer.update(cx, |multi_buffer, cx| {
12689 project.update(cx, |project, cx| {
12690 project.restart_language_servers_for_buffers(
12691 multi_buffer.all_buffers().into_iter().collect(),
12692 cx,
12693 );
12694 });
12695 })
12696 }
12697 }
12698
12699 fn cancel_language_server_work(
12700 workspace: &mut Workspace,
12701 _: &actions::CancelLanguageServerWork,
12702 _: &mut Window,
12703 cx: &mut Context<Workspace>,
12704 ) {
12705 let project = workspace.project();
12706 let buffers = workspace
12707 .active_item(cx)
12708 .and_then(|item| item.act_as::<Editor>(cx))
12709 .map_or(HashSet::default(), |editor| {
12710 editor.read(cx).buffer.read(cx).all_buffers()
12711 });
12712 project.update(cx, |project, cx| {
12713 project.cancel_language_server_work_for_buffers(buffers, cx);
12714 });
12715 }
12716
12717 fn show_character_palette(
12718 &mut self,
12719 _: &ShowCharacterPalette,
12720 window: &mut Window,
12721 _: &mut Context<Self>,
12722 ) {
12723 window.show_character_palette();
12724 }
12725
12726 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12727 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12728 let buffer = self.buffer.read(cx).snapshot(cx);
12729 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12730 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12731 let is_valid = buffer
12732 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12733 .any(|entry| {
12734 entry.diagnostic.is_primary
12735 && !entry.range.is_empty()
12736 && entry.range.start == primary_range_start
12737 && entry.diagnostic.message == active_diagnostics.primary_message
12738 });
12739
12740 if is_valid != active_diagnostics.is_valid {
12741 active_diagnostics.is_valid = is_valid;
12742 if is_valid {
12743 let mut new_styles = HashMap::default();
12744 for (block_id, diagnostic) in &active_diagnostics.blocks {
12745 new_styles.insert(
12746 *block_id,
12747 diagnostic_block_renderer(diagnostic.clone(), None, true),
12748 );
12749 }
12750 self.display_map.update(cx, |display_map, _cx| {
12751 display_map.replace_blocks(new_styles);
12752 });
12753 } else {
12754 self.dismiss_diagnostics(cx);
12755 }
12756 }
12757 }
12758 }
12759
12760 fn activate_diagnostics(
12761 &mut self,
12762 buffer_id: BufferId,
12763 group_id: usize,
12764 window: &mut Window,
12765 cx: &mut Context<Self>,
12766 ) {
12767 self.dismiss_diagnostics(cx);
12768 let snapshot = self.snapshot(window, cx);
12769 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12770 let buffer = self.buffer.read(cx).snapshot(cx);
12771
12772 let mut primary_range = None;
12773 let mut primary_message = None;
12774 let diagnostic_group = buffer
12775 .diagnostic_group(buffer_id, group_id)
12776 .filter_map(|entry| {
12777 let start = entry.range.start;
12778 let end = entry.range.end;
12779 if snapshot.is_line_folded(MultiBufferRow(start.row))
12780 && (start.row == end.row
12781 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12782 {
12783 return None;
12784 }
12785 if entry.diagnostic.is_primary {
12786 primary_range = Some(entry.range.clone());
12787 primary_message = Some(entry.diagnostic.message.clone());
12788 }
12789 Some(entry)
12790 })
12791 .collect::<Vec<_>>();
12792 let primary_range = primary_range?;
12793 let primary_message = primary_message?;
12794
12795 let blocks = display_map
12796 .insert_blocks(
12797 diagnostic_group.iter().map(|entry| {
12798 let diagnostic = entry.diagnostic.clone();
12799 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12800 BlockProperties {
12801 style: BlockStyle::Fixed,
12802 placement: BlockPlacement::Below(
12803 buffer.anchor_after(entry.range.start),
12804 ),
12805 height: message_height,
12806 render: diagnostic_block_renderer(diagnostic, None, true),
12807 priority: 0,
12808 }
12809 }),
12810 cx,
12811 )
12812 .into_iter()
12813 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12814 .collect();
12815
12816 Some(ActiveDiagnosticGroup {
12817 primary_range: buffer.anchor_before(primary_range.start)
12818 ..buffer.anchor_after(primary_range.end),
12819 primary_message,
12820 group_id,
12821 blocks,
12822 is_valid: true,
12823 })
12824 });
12825 }
12826
12827 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12828 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12829 self.display_map.update(cx, |display_map, cx| {
12830 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12831 });
12832 cx.notify();
12833 }
12834 }
12835
12836 /// Disable inline diagnostics rendering for this editor.
12837 pub fn disable_inline_diagnostics(&mut self) {
12838 self.inline_diagnostics_enabled = false;
12839 self.inline_diagnostics_update = Task::ready(());
12840 self.inline_diagnostics.clear();
12841 }
12842
12843 pub fn inline_diagnostics_enabled(&self) -> bool {
12844 self.inline_diagnostics_enabled
12845 }
12846
12847 pub fn show_inline_diagnostics(&self) -> bool {
12848 self.show_inline_diagnostics
12849 }
12850
12851 pub fn toggle_inline_diagnostics(
12852 &mut self,
12853 _: &ToggleInlineDiagnostics,
12854 window: &mut Window,
12855 cx: &mut Context<'_, Editor>,
12856 ) {
12857 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12858 self.refresh_inline_diagnostics(false, window, cx);
12859 }
12860
12861 fn refresh_inline_diagnostics(
12862 &mut self,
12863 debounce: bool,
12864 window: &mut Window,
12865 cx: &mut Context<Self>,
12866 ) {
12867 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12868 self.inline_diagnostics_update = Task::ready(());
12869 self.inline_diagnostics.clear();
12870 return;
12871 }
12872
12873 let debounce_ms = ProjectSettings::get_global(cx)
12874 .diagnostics
12875 .inline
12876 .update_debounce_ms;
12877 let debounce = if debounce && debounce_ms > 0 {
12878 Some(Duration::from_millis(debounce_ms))
12879 } else {
12880 None
12881 };
12882 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12883 if let Some(debounce) = debounce {
12884 cx.background_executor().timer(debounce).await;
12885 }
12886 let Some(snapshot) = editor
12887 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12888 .ok()
12889 else {
12890 return;
12891 };
12892
12893 let new_inline_diagnostics = cx
12894 .background_spawn(async move {
12895 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12896 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12897 let message = diagnostic_entry
12898 .diagnostic
12899 .message
12900 .split_once('\n')
12901 .map(|(line, _)| line)
12902 .map(SharedString::new)
12903 .unwrap_or_else(|| {
12904 SharedString::from(diagnostic_entry.diagnostic.message)
12905 });
12906 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12907 let (Ok(i) | Err(i)) = inline_diagnostics
12908 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12909 inline_diagnostics.insert(
12910 i,
12911 (
12912 start_anchor,
12913 InlineDiagnostic {
12914 message,
12915 group_id: diagnostic_entry.diagnostic.group_id,
12916 start: diagnostic_entry.range.start.to_point(&snapshot),
12917 is_primary: diagnostic_entry.diagnostic.is_primary,
12918 severity: diagnostic_entry.diagnostic.severity,
12919 },
12920 ),
12921 );
12922 }
12923 inline_diagnostics
12924 })
12925 .await;
12926
12927 editor
12928 .update(&mut cx, |editor, cx| {
12929 editor.inline_diagnostics = new_inline_diagnostics;
12930 cx.notify();
12931 })
12932 .ok();
12933 });
12934 }
12935
12936 pub fn set_selections_from_remote(
12937 &mut self,
12938 selections: Vec<Selection<Anchor>>,
12939 pending_selection: Option<Selection<Anchor>>,
12940 window: &mut Window,
12941 cx: &mut Context<Self>,
12942 ) {
12943 let old_cursor_position = self.selections.newest_anchor().head();
12944 self.selections.change_with(cx, |s| {
12945 s.select_anchors(selections);
12946 if let Some(pending_selection) = pending_selection {
12947 s.set_pending(pending_selection, SelectMode::Character);
12948 } else {
12949 s.clear_pending();
12950 }
12951 });
12952 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12953 }
12954
12955 fn push_to_selection_history(&mut self) {
12956 self.selection_history.push(SelectionHistoryEntry {
12957 selections: self.selections.disjoint_anchors(),
12958 select_next_state: self.select_next_state.clone(),
12959 select_prev_state: self.select_prev_state.clone(),
12960 add_selections_state: self.add_selections_state.clone(),
12961 });
12962 }
12963
12964 pub fn transact(
12965 &mut self,
12966 window: &mut Window,
12967 cx: &mut Context<Self>,
12968 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12969 ) -> Option<TransactionId> {
12970 self.start_transaction_at(Instant::now(), window, cx);
12971 update(self, window, cx);
12972 self.end_transaction_at(Instant::now(), cx)
12973 }
12974
12975 pub fn start_transaction_at(
12976 &mut self,
12977 now: Instant,
12978 window: &mut Window,
12979 cx: &mut Context<Self>,
12980 ) {
12981 self.end_selection(window, cx);
12982 if let Some(tx_id) = self
12983 .buffer
12984 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
12985 {
12986 self.selection_history
12987 .insert_transaction(tx_id, self.selections.disjoint_anchors());
12988 cx.emit(EditorEvent::TransactionBegun {
12989 transaction_id: tx_id,
12990 })
12991 }
12992 }
12993
12994 pub fn end_transaction_at(
12995 &mut self,
12996 now: Instant,
12997 cx: &mut Context<Self>,
12998 ) -> Option<TransactionId> {
12999 if let Some(transaction_id) = self
13000 .buffer
13001 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13002 {
13003 if let Some((_, end_selections)) =
13004 self.selection_history.transaction_mut(transaction_id)
13005 {
13006 *end_selections = Some(self.selections.disjoint_anchors());
13007 } else {
13008 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13009 }
13010
13011 cx.emit(EditorEvent::Edited { transaction_id });
13012 Some(transaction_id)
13013 } else {
13014 None
13015 }
13016 }
13017
13018 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13019 if self.selection_mark_mode {
13020 self.change_selections(None, window, cx, |s| {
13021 s.move_with(|_, sel| {
13022 sel.collapse_to(sel.head(), SelectionGoal::None);
13023 });
13024 })
13025 }
13026 self.selection_mark_mode = true;
13027 cx.notify();
13028 }
13029
13030 pub fn swap_selection_ends(
13031 &mut self,
13032 _: &actions::SwapSelectionEnds,
13033 window: &mut Window,
13034 cx: &mut Context<Self>,
13035 ) {
13036 self.change_selections(None, window, cx, |s| {
13037 s.move_with(|_, sel| {
13038 if sel.start != sel.end {
13039 sel.reversed = !sel.reversed
13040 }
13041 });
13042 });
13043 self.request_autoscroll(Autoscroll::newest(), cx);
13044 cx.notify();
13045 }
13046
13047 pub fn toggle_fold(
13048 &mut self,
13049 _: &actions::ToggleFold,
13050 window: &mut Window,
13051 cx: &mut Context<Self>,
13052 ) {
13053 if self.is_singleton(cx) {
13054 let selection = self.selections.newest::<Point>(cx);
13055
13056 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13057 let range = if selection.is_empty() {
13058 let point = selection.head().to_display_point(&display_map);
13059 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13060 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13061 .to_point(&display_map);
13062 start..end
13063 } else {
13064 selection.range()
13065 };
13066 if display_map.folds_in_range(range).next().is_some() {
13067 self.unfold_lines(&Default::default(), window, cx)
13068 } else {
13069 self.fold(&Default::default(), window, cx)
13070 }
13071 } else {
13072 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13073 let buffer_ids: HashSet<_> = self
13074 .selections
13075 .disjoint_anchor_ranges()
13076 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13077 .collect();
13078
13079 let should_unfold = buffer_ids
13080 .iter()
13081 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13082
13083 for buffer_id in buffer_ids {
13084 if should_unfold {
13085 self.unfold_buffer(buffer_id, cx);
13086 } else {
13087 self.fold_buffer(buffer_id, cx);
13088 }
13089 }
13090 }
13091 }
13092
13093 pub fn toggle_fold_recursive(
13094 &mut self,
13095 _: &actions::ToggleFoldRecursive,
13096 window: &mut Window,
13097 cx: &mut Context<Self>,
13098 ) {
13099 let selection = self.selections.newest::<Point>(cx);
13100
13101 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13102 let range = if selection.is_empty() {
13103 let point = selection.head().to_display_point(&display_map);
13104 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13105 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13106 .to_point(&display_map);
13107 start..end
13108 } else {
13109 selection.range()
13110 };
13111 if display_map.folds_in_range(range).next().is_some() {
13112 self.unfold_recursive(&Default::default(), window, cx)
13113 } else {
13114 self.fold_recursive(&Default::default(), window, cx)
13115 }
13116 }
13117
13118 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13119 if self.is_singleton(cx) {
13120 let mut to_fold = Vec::new();
13121 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13122 let selections = self.selections.all_adjusted(cx);
13123
13124 for selection in selections {
13125 let range = selection.range().sorted();
13126 let buffer_start_row = range.start.row;
13127
13128 if range.start.row != range.end.row {
13129 let mut found = false;
13130 let mut row = range.start.row;
13131 while row <= range.end.row {
13132 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13133 {
13134 found = true;
13135 row = crease.range().end.row + 1;
13136 to_fold.push(crease);
13137 } else {
13138 row += 1
13139 }
13140 }
13141 if found {
13142 continue;
13143 }
13144 }
13145
13146 for row in (0..=range.start.row).rev() {
13147 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13148 if crease.range().end.row >= buffer_start_row {
13149 to_fold.push(crease);
13150 if row <= range.start.row {
13151 break;
13152 }
13153 }
13154 }
13155 }
13156 }
13157
13158 self.fold_creases(to_fold, true, window, cx);
13159 } else {
13160 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13161 let buffer_ids = self
13162 .selections
13163 .disjoint_anchor_ranges()
13164 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13165 .collect::<HashSet<_>>();
13166 for buffer_id in buffer_ids {
13167 self.fold_buffer(buffer_id, cx);
13168 }
13169 }
13170 }
13171
13172 fn fold_at_level(
13173 &mut self,
13174 fold_at: &FoldAtLevel,
13175 window: &mut Window,
13176 cx: &mut Context<Self>,
13177 ) {
13178 if !self.buffer.read(cx).is_singleton() {
13179 return;
13180 }
13181
13182 let fold_at_level = fold_at.0;
13183 let snapshot = self.buffer.read(cx).snapshot(cx);
13184 let mut to_fold = Vec::new();
13185 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13186
13187 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13188 while start_row < end_row {
13189 match self
13190 .snapshot(window, cx)
13191 .crease_for_buffer_row(MultiBufferRow(start_row))
13192 {
13193 Some(crease) => {
13194 let nested_start_row = crease.range().start.row + 1;
13195 let nested_end_row = crease.range().end.row;
13196
13197 if current_level < fold_at_level {
13198 stack.push((nested_start_row, nested_end_row, current_level + 1));
13199 } else if current_level == fold_at_level {
13200 to_fold.push(crease);
13201 }
13202
13203 start_row = nested_end_row + 1;
13204 }
13205 None => start_row += 1,
13206 }
13207 }
13208 }
13209
13210 self.fold_creases(to_fold, true, window, cx);
13211 }
13212
13213 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13214 if self.buffer.read(cx).is_singleton() {
13215 let mut fold_ranges = Vec::new();
13216 let snapshot = self.buffer.read(cx).snapshot(cx);
13217
13218 for row in 0..snapshot.max_row().0 {
13219 if let Some(foldable_range) = self
13220 .snapshot(window, cx)
13221 .crease_for_buffer_row(MultiBufferRow(row))
13222 {
13223 fold_ranges.push(foldable_range);
13224 }
13225 }
13226
13227 self.fold_creases(fold_ranges, true, window, cx);
13228 } else {
13229 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13230 editor
13231 .update_in(&mut cx, |editor, _, cx| {
13232 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13233 editor.fold_buffer(buffer_id, cx);
13234 }
13235 })
13236 .ok();
13237 });
13238 }
13239 }
13240
13241 pub fn fold_function_bodies(
13242 &mut self,
13243 _: &actions::FoldFunctionBodies,
13244 window: &mut Window,
13245 cx: &mut Context<Self>,
13246 ) {
13247 let snapshot = self.buffer.read(cx).snapshot(cx);
13248
13249 let ranges = snapshot
13250 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13251 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13252 .collect::<Vec<_>>();
13253
13254 let creases = ranges
13255 .into_iter()
13256 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13257 .collect();
13258
13259 self.fold_creases(creases, true, window, cx);
13260 }
13261
13262 pub fn fold_recursive(
13263 &mut self,
13264 _: &actions::FoldRecursive,
13265 window: &mut Window,
13266 cx: &mut Context<Self>,
13267 ) {
13268 let mut to_fold = Vec::new();
13269 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13270 let selections = self.selections.all_adjusted(cx);
13271
13272 for selection in selections {
13273 let range = selection.range().sorted();
13274 let buffer_start_row = range.start.row;
13275
13276 if range.start.row != range.end.row {
13277 let mut found = false;
13278 for row in range.start.row..=range.end.row {
13279 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13280 found = true;
13281 to_fold.push(crease);
13282 }
13283 }
13284 if found {
13285 continue;
13286 }
13287 }
13288
13289 for row in (0..=range.start.row).rev() {
13290 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13291 if crease.range().end.row >= buffer_start_row {
13292 to_fold.push(crease);
13293 } else {
13294 break;
13295 }
13296 }
13297 }
13298 }
13299
13300 self.fold_creases(to_fold, true, window, cx);
13301 }
13302
13303 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13304 let buffer_row = fold_at.buffer_row;
13305 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13306
13307 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13308 let autoscroll = self
13309 .selections
13310 .all::<Point>(cx)
13311 .iter()
13312 .any(|selection| crease.range().overlaps(&selection.range()));
13313
13314 self.fold_creases(vec![crease], autoscroll, window, cx);
13315 }
13316 }
13317
13318 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13319 if self.is_singleton(cx) {
13320 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13321 let buffer = &display_map.buffer_snapshot;
13322 let selections = self.selections.all::<Point>(cx);
13323 let ranges = selections
13324 .iter()
13325 .map(|s| {
13326 let range = s.display_range(&display_map).sorted();
13327 let mut start = range.start.to_point(&display_map);
13328 let mut end = range.end.to_point(&display_map);
13329 start.column = 0;
13330 end.column = buffer.line_len(MultiBufferRow(end.row));
13331 start..end
13332 })
13333 .collect::<Vec<_>>();
13334
13335 self.unfold_ranges(&ranges, true, true, cx);
13336 } else {
13337 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13338 let buffer_ids = self
13339 .selections
13340 .disjoint_anchor_ranges()
13341 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13342 .collect::<HashSet<_>>();
13343 for buffer_id in buffer_ids {
13344 self.unfold_buffer(buffer_id, cx);
13345 }
13346 }
13347 }
13348
13349 pub fn unfold_recursive(
13350 &mut self,
13351 _: &UnfoldRecursive,
13352 _window: &mut Window,
13353 cx: &mut Context<Self>,
13354 ) {
13355 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13356 let selections = self.selections.all::<Point>(cx);
13357 let ranges = selections
13358 .iter()
13359 .map(|s| {
13360 let mut range = s.display_range(&display_map).sorted();
13361 *range.start.column_mut() = 0;
13362 *range.end.column_mut() = display_map.line_len(range.end.row());
13363 let start = range.start.to_point(&display_map);
13364 let end = range.end.to_point(&display_map);
13365 start..end
13366 })
13367 .collect::<Vec<_>>();
13368
13369 self.unfold_ranges(&ranges, true, true, cx);
13370 }
13371
13372 pub fn unfold_at(
13373 &mut self,
13374 unfold_at: &UnfoldAt,
13375 _window: &mut Window,
13376 cx: &mut Context<Self>,
13377 ) {
13378 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13379
13380 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13381 ..Point::new(
13382 unfold_at.buffer_row.0,
13383 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13384 );
13385
13386 let autoscroll = self
13387 .selections
13388 .all::<Point>(cx)
13389 .iter()
13390 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13391
13392 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13393 }
13394
13395 pub fn unfold_all(
13396 &mut self,
13397 _: &actions::UnfoldAll,
13398 _window: &mut Window,
13399 cx: &mut Context<Self>,
13400 ) {
13401 if self.buffer.read(cx).is_singleton() {
13402 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13403 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13404 } else {
13405 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13406 editor
13407 .update(&mut cx, |editor, cx| {
13408 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13409 editor.unfold_buffer(buffer_id, cx);
13410 }
13411 })
13412 .ok();
13413 });
13414 }
13415 }
13416
13417 pub fn fold_selected_ranges(
13418 &mut self,
13419 _: &FoldSelectedRanges,
13420 window: &mut Window,
13421 cx: &mut Context<Self>,
13422 ) {
13423 let selections = self.selections.all::<Point>(cx);
13424 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13425 let line_mode = self.selections.line_mode;
13426 let ranges = selections
13427 .into_iter()
13428 .map(|s| {
13429 if line_mode {
13430 let start = Point::new(s.start.row, 0);
13431 let end = Point::new(
13432 s.end.row,
13433 display_map
13434 .buffer_snapshot
13435 .line_len(MultiBufferRow(s.end.row)),
13436 );
13437 Crease::simple(start..end, display_map.fold_placeholder.clone())
13438 } else {
13439 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13440 }
13441 })
13442 .collect::<Vec<_>>();
13443 self.fold_creases(ranges, true, window, cx);
13444 }
13445
13446 pub fn fold_ranges<T: ToOffset + Clone>(
13447 &mut self,
13448 ranges: Vec<Range<T>>,
13449 auto_scroll: bool,
13450 window: &mut Window,
13451 cx: &mut Context<Self>,
13452 ) {
13453 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13454 let ranges = ranges
13455 .into_iter()
13456 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13457 .collect::<Vec<_>>();
13458 self.fold_creases(ranges, auto_scroll, window, cx);
13459 }
13460
13461 pub fn fold_creases<T: ToOffset + Clone>(
13462 &mut self,
13463 creases: Vec<Crease<T>>,
13464 auto_scroll: bool,
13465 window: &mut Window,
13466 cx: &mut Context<Self>,
13467 ) {
13468 if creases.is_empty() {
13469 return;
13470 }
13471
13472 let mut buffers_affected = HashSet::default();
13473 let multi_buffer = self.buffer().read(cx);
13474 for crease in &creases {
13475 if let Some((_, buffer, _)) =
13476 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13477 {
13478 buffers_affected.insert(buffer.read(cx).remote_id());
13479 };
13480 }
13481
13482 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13483
13484 if auto_scroll {
13485 self.request_autoscroll(Autoscroll::fit(), cx);
13486 }
13487
13488 cx.notify();
13489
13490 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13491 // Clear diagnostics block when folding a range that contains it.
13492 let snapshot = self.snapshot(window, cx);
13493 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13494 drop(snapshot);
13495 self.active_diagnostics = Some(active_diagnostics);
13496 self.dismiss_diagnostics(cx);
13497 } else {
13498 self.active_diagnostics = Some(active_diagnostics);
13499 }
13500 }
13501
13502 self.scrollbar_marker_state.dirty = true;
13503 }
13504
13505 /// Removes any folds whose ranges intersect any of the given ranges.
13506 pub fn unfold_ranges<T: ToOffset + Clone>(
13507 &mut self,
13508 ranges: &[Range<T>],
13509 inclusive: bool,
13510 auto_scroll: bool,
13511 cx: &mut Context<Self>,
13512 ) {
13513 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13514 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13515 });
13516 }
13517
13518 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13519 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13520 return;
13521 }
13522 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13523 self.display_map.update(cx, |display_map, cx| {
13524 display_map.fold_buffers([buffer_id], cx)
13525 });
13526 cx.emit(EditorEvent::BufferFoldToggled {
13527 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13528 folded: true,
13529 });
13530 cx.notify();
13531 }
13532
13533 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13534 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13535 return;
13536 }
13537 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13538 self.display_map.update(cx, |display_map, cx| {
13539 display_map.unfold_buffers([buffer_id], cx);
13540 });
13541 cx.emit(EditorEvent::BufferFoldToggled {
13542 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13543 folded: false,
13544 });
13545 cx.notify();
13546 }
13547
13548 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13549 self.display_map.read(cx).is_buffer_folded(buffer)
13550 }
13551
13552 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13553 self.display_map.read(cx).folded_buffers()
13554 }
13555
13556 /// Removes any folds with the given ranges.
13557 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13558 &mut self,
13559 ranges: &[Range<T>],
13560 type_id: TypeId,
13561 auto_scroll: bool,
13562 cx: &mut Context<Self>,
13563 ) {
13564 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13565 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13566 });
13567 }
13568
13569 fn remove_folds_with<T: ToOffset + Clone>(
13570 &mut self,
13571 ranges: &[Range<T>],
13572 auto_scroll: bool,
13573 cx: &mut Context<Self>,
13574 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13575 ) {
13576 if ranges.is_empty() {
13577 return;
13578 }
13579
13580 let mut buffers_affected = HashSet::default();
13581 let multi_buffer = self.buffer().read(cx);
13582 for range in ranges {
13583 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13584 buffers_affected.insert(buffer.read(cx).remote_id());
13585 };
13586 }
13587
13588 self.display_map.update(cx, update);
13589
13590 if auto_scroll {
13591 self.request_autoscroll(Autoscroll::fit(), cx);
13592 }
13593
13594 cx.notify();
13595 self.scrollbar_marker_state.dirty = true;
13596 self.active_indent_guides_state.dirty = true;
13597 }
13598
13599 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13600 self.display_map.read(cx).fold_placeholder.clone()
13601 }
13602
13603 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13604 self.buffer.update(cx, |buffer, cx| {
13605 buffer.set_all_diff_hunks_expanded(cx);
13606 });
13607 }
13608
13609 pub fn expand_all_diff_hunks(
13610 &mut self,
13611 _: &ExpandAllDiffHunks,
13612 _window: &mut Window,
13613 cx: &mut Context<Self>,
13614 ) {
13615 self.buffer.update(cx, |buffer, cx| {
13616 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13617 });
13618 }
13619
13620 pub fn toggle_selected_diff_hunks(
13621 &mut self,
13622 _: &ToggleSelectedDiffHunks,
13623 _window: &mut Window,
13624 cx: &mut Context<Self>,
13625 ) {
13626 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13627 self.toggle_diff_hunks_in_ranges(ranges, cx);
13628 }
13629
13630 pub fn diff_hunks_in_ranges<'a>(
13631 &'a self,
13632 ranges: &'a [Range<Anchor>],
13633 buffer: &'a MultiBufferSnapshot,
13634 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13635 ranges.iter().flat_map(move |range| {
13636 let end_excerpt_id = range.end.excerpt_id;
13637 let range = range.to_point(buffer);
13638 let mut peek_end = range.end;
13639 if range.end.row < buffer.max_row().0 {
13640 peek_end = Point::new(range.end.row + 1, 0);
13641 }
13642 buffer
13643 .diff_hunks_in_range(range.start..peek_end)
13644 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13645 })
13646 }
13647
13648 pub fn has_stageable_diff_hunks_in_ranges(
13649 &self,
13650 ranges: &[Range<Anchor>],
13651 snapshot: &MultiBufferSnapshot,
13652 ) -> bool {
13653 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13654 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13655 }
13656
13657 pub fn toggle_staged_selected_diff_hunks(
13658 &mut self,
13659 _: &::git::ToggleStaged,
13660 _: &mut Window,
13661 cx: &mut Context<Self>,
13662 ) {
13663 let snapshot = self.buffer.read(cx).snapshot(cx);
13664 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13665 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13666 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13667 }
13668
13669 pub fn stage_and_next(
13670 &mut self,
13671 _: &::git::StageAndNext,
13672 window: &mut Window,
13673 cx: &mut Context<Self>,
13674 ) {
13675 self.do_stage_or_unstage_and_next(true, window, cx);
13676 }
13677
13678 pub fn unstage_and_next(
13679 &mut self,
13680 _: &::git::UnstageAndNext,
13681 window: &mut Window,
13682 cx: &mut Context<Self>,
13683 ) {
13684 self.do_stage_or_unstage_and_next(false, window, cx);
13685 }
13686
13687 pub fn stage_or_unstage_diff_hunks(
13688 &mut self,
13689 stage: bool,
13690 ranges: Vec<Range<Anchor>>,
13691 cx: &mut Context<Self>,
13692 ) {
13693 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13694 cx.spawn(|this, mut cx| async move {
13695 task.await?;
13696 this.update(&mut cx, |this, cx| {
13697 let snapshot = this.buffer.read(cx).snapshot(cx);
13698 let chunk_by = this
13699 .diff_hunks_in_ranges(&ranges, &snapshot)
13700 .chunk_by(|hunk| hunk.buffer_id);
13701 for (buffer_id, hunks) in &chunk_by {
13702 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13703 }
13704 })
13705 })
13706 .detach_and_log_err(cx);
13707 }
13708
13709 fn save_buffers_for_ranges_if_needed(
13710 &mut self,
13711 ranges: &[Range<Anchor>],
13712 cx: &mut Context<'_, Editor>,
13713 ) -> Task<Result<()>> {
13714 let multibuffer = self.buffer.read(cx);
13715 let snapshot = multibuffer.read(cx);
13716 let buffer_ids: HashSet<_> = ranges
13717 .iter()
13718 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13719 .collect();
13720 drop(snapshot);
13721
13722 let mut buffers = HashSet::default();
13723 for buffer_id in buffer_ids {
13724 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13725 let buffer = buffer_entity.read(cx);
13726 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13727 {
13728 buffers.insert(buffer_entity);
13729 }
13730 }
13731 }
13732
13733 if let Some(project) = &self.project {
13734 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13735 } else {
13736 Task::ready(Ok(()))
13737 }
13738 }
13739
13740 fn do_stage_or_unstage_and_next(
13741 &mut self,
13742 stage: bool,
13743 window: &mut Window,
13744 cx: &mut Context<Self>,
13745 ) {
13746 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13747
13748 if ranges.iter().any(|range| range.start != range.end) {
13749 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13750 return;
13751 }
13752
13753 let snapshot = self.snapshot(window, cx);
13754 let newest_range = self.selections.newest::<Point>(cx).range();
13755
13756 let run_twice = snapshot
13757 .hunks_for_ranges([newest_range])
13758 .first()
13759 .is_some_and(|hunk| {
13760 let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13761 self.hunk_after_position(&snapshot, next_line)
13762 .is_some_and(|other| other.row_range == hunk.row_range)
13763 });
13764
13765 if run_twice {
13766 self.go_to_next_hunk(&GoToHunk, window, cx);
13767 }
13768 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13769 self.go_to_next_hunk(&GoToHunk, window, cx);
13770 }
13771
13772 fn do_stage_or_unstage(
13773 &self,
13774 stage: bool,
13775 buffer_id: BufferId,
13776 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13777 cx: &mut App,
13778 ) -> Option<()> {
13779 let project = self.project.as_ref()?;
13780 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13781 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13782 let buffer_snapshot = buffer.read(cx).snapshot();
13783 let file_exists = buffer_snapshot
13784 .file()
13785 .is_some_and(|file| file.disk_state().exists());
13786 diff.update(cx, |diff, cx| {
13787 diff.stage_or_unstage_hunks(
13788 stage,
13789 &hunks
13790 .map(|hunk| buffer_diff::DiffHunk {
13791 buffer_range: hunk.buffer_range,
13792 diff_base_byte_range: hunk.diff_base_byte_range,
13793 secondary_status: hunk.secondary_status,
13794 range: Point::zero()..Point::zero(), // unused
13795 })
13796 .collect::<Vec<_>>(),
13797 &buffer_snapshot,
13798 file_exists,
13799 cx,
13800 )
13801 });
13802 None
13803 }
13804
13805 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13806 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13807 self.buffer
13808 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13809 }
13810
13811 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13812 self.buffer.update(cx, |buffer, cx| {
13813 let ranges = vec![Anchor::min()..Anchor::max()];
13814 if !buffer.all_diff_hunks_expanded()
13815 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13816 {
13817 buffer.collapse_diff_hunks(ranges, cx);
13818 true
13819 } else {
13820 false
13821 }
13822 })
13823 }
13824
13825 fn toggle_diff_hunks_in_ranges(
13826 &mut self,
13827 ranges: Vec<Range<Anchor>>,
13828 cx: &mut Context<'_, Editor>,
13829 ) {
13830 self.buffer.update(cx, |buffer, cx| {
13831 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13832 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13833 })
13834 }
13835
13836 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13837 self.buffer.update(cx, |buffer, cx| {
13838 let snapshot = buffer.snapshot(cx);
13839 let excerpt_id = range.end.excerpt_id;
13840 let point_range = range.to_point(&snapshot);
13841 let expand = !buffer.single_hunk_is_expanded(range, cx);
13842 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13843 })
13844 }
13845
13846 pub(crate) fn apply_all_diff_hunks(
13847 &mut self,
13848 _: &ApplyAllDiffHunks,
13849 window: &mut Window,
13850 cx: &mut Context<Self>,
13851 ) {
13852 let buffers = self.buffer.read(cx).all_buffers();
13853 for branch_buffer in buffers {
13854 branch_buffer.update(cx, |branch_buffer, cx| {
13855 branch_buffer.merge_into_base(Vec::new(), cx);
13856 });
13857 }
13858
13859 if let Some(project) = self.project.clone() {
13860 self.save(true, project, window, cx).detach_and_log_err(cx);
13861 }
13862 }
13863
13864 pub(crate) fn apply_selected_diff_hunks(
13865 &mut self,
13866 _: &ApplyDiffHunk,
13867 window: &mut Window,
13868 cx: &mut Context<Self>,
13869 ) {
13870 let snapshot = self.snapshot(window, cx);
13871 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13872 let mut ranges_by_buffer = HashMap::default();
13873 self.transact(window, cx, |editor, _window, cx| {
13874 for hunk in hunks {
13875 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13876 ranges_by_buffer
13877 .entry(buffer.clone())
13878 .or_insert_with(Vec::new)
13879 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13880 }
13881 }
13882
13883 for (buffer, ranges) in ranges_by_buffer {
13884 buffer.update(cx, |buffer, cx| {
13885 buffer.merge_into_base(ranges, cx);
13886 });
13887 }
13888 });
13889
13890 if let Some(project) = self.project.clone() {
13891 self.save(true, project, window, cx).detach_and_log_err(cx);
13892 }
13893 }
13894
13895 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13896 if hovered != self.gutter_hovered {
13897 self.gutter_hovered = hovered;
13898 cx.notify();
13899 }
13900 }
13901
13902 pub fn insert_blocks(
13903 &mut self,
13904 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13905 autoscroll: Option<Autoscroll>,
13906 cx: &mut Context<Self>,
13907 ) -> Vec<CustomBlockId> {
13908 let blocks = self
13909 .display_map
13910 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13911 if let Some(autoscroll) = autoscroll {
13912 self.request_autoscroll(autoscroll, cx);
13913 }
13914 cx.notify();
13915 blocks
13916 }
13917
13918 pub fn resize_blocks(
13919 &mut self,
13920 heights: HashMap<CustomBlockId, u32>,
13921 autoscroll: Option<Autoscroll>,
13922 cx: &mut Context<Self>,
13923 ) {
13924 self.display_map
13925 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13926 if let Some(autoscroll) = autoscroll {
13927 self.request_autoscroll(autoscroll, cx);
13928 }
13929 cx.notify();
13930 }
13931
13932 pub fn replace_blocks(
13933 &mut self,
13934 renderers: HashMap<CustomBlockId, RenderBlock>,
13935 autoscroll: Option<Autoscroll>,
13936 cx: &mut Context<Self>,
13937 ) {
13938 self.display_map
13939 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13940 if let Some(autoscroll) = autoscroll {
13941 self.request_autoscroll(autoscroll, cx);
13942 }
13943 cx.notify();
13944 }
13945
13946 pub fn remove_blocks(
13947 &mut self,
13948 block_ids: HashSet<CustomBlockId>,
13949 autoscroll: Option<Autoscroll>,
13950 cx: &mut Context<Self>,
13951 ) {
13952 self.display_map.update(cx, |display_map, cx| {
13953 display_map.remove_blocks(block_ids, cx)
13954 });
13955 if let Some(autoscroll) = autoscroll {
13956 self.request_autoscroll(autoscroll, cx);
13957 }
13958 cx.notify();
13959 }
13960
13961 pub fn row_for_block(
13962 &self,
13963 block_id: CustomBlockId,
13964 cx: &mut Context<Self>,
13965 ) -> Option<DisplayRow> {
13966 self.display_map
13967 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13968 }
13969
13970 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13971 self.focused_block = Some(focused_block);
13972 }
13973
13974 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13975 self.focused_block.take()
13976 }
13977
13978 pub fn insert_creases(
13979 &mut self,
13980 creases: impl IntoIterator<Item = Crease<Anchor>>,
13981 cx: &mut Context<Self>,
13982 ) -> Vec<CreaseId> {
13983 self.display_map
13984 .update(cx, |map, cx| map.insert_creases(creases, cx))
13985 }
13986
13987 pub fn remove_creases(
13988 &mut self,
13989 ids: impl IntoIterator<Item = CreaseId>,
13990 cx: &mut Context<Self>,
13991 ) {
13992 self.display_map
13993 .update(cx, |map, cx| map.remove_creases(ids, cx));
13994 }
13995
13996 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
13997 self.display_map
13998 .update(cx, |map, cx| map.snapshot(cx))
13999 .longest_row()
14000 }
14001
14002 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14003 self.display_map
14004 .update(cx, |map, cx| map.snapshot(cx))
14005 .max_point()
14006 }
14007
14008 pub fn text(&self, cx: &App) -> String {
14009 self.buffer.read(cx).read(cx).text()
14010 }
14011
14012 pub fn is_empty(&self, cx: &App) -> bool {
14013 self.buffer.read(cx).read(cx).is_empty()
14014 }
14015
14016 pub fn text_option(&self, cx: &App) -> Option<String> {
14017 let text = self.text(cx);
14018 let text = text.trim();
14019
14020 if text.is_empty() {
14021 return None;
14022 }
14023
14024 Some(text.to_string())
14025 }
14026
14027 pub fn set_text(
14028 &mut self,
14029 text: impl Into<Arc<str>>,
14030 window: &mut Window,
14031 cx: &mut Context<Self>,
14032 ) {
14033 self.transact(window, cx, |this, _, cx| {
14034 this.buffer
14035 .read(cx)
14036 .as_singleton()
14037 .expect("you can only call set_text on editors for singleton buffers")
14038 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14039 });
14040 }
14041
14042 pub fn display_text(&self, cx: &mut App) -> String {
14043 self.display_map
14044 .update(cx, |map, cx| map.snapshot(cx))
14045 .text()
14046 }
14047
14048 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14049 let mut wrap_guides = smallvec::smallvec![];
14050
14051 if self.show_wrap_guides == Some(false) {
14052 return wrap_guides;
14053 }
14054
14055 let settings = self.buffer.read(cx).language_settings(cx);
14056 if settings.show_wrap_guides {
14057 match self.soft_wrap_mode(cx) {
14058 SoftWrap::Column(soft_wrap) => {
14059 wrap_guides.push((soft_wrap as usize, true));
14060 }
14061 SoftWrap::Bounded(soft_wrap) => {
14062 wrap_guides.push((soft_wrap as usize, true));
14063 }
14064 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14065 }
14066 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14067 }
14068
14069 wrap_guides
14070 }
14071
14072 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14073 let settings = self.buffer.read(cx).language_settings(cx);
14074 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14075 match mode {
14076 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14077 SoftWrap::None
14078 }
14079 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14080 language_settings::SoftWrap::PreferredLineLength => {
14081 SoftWrap::Column(settings.preferred_line_length)
14082 }
14083 language_settings::SoftWrap::Bounded => {
14084 SoftWrap::Bounded(settings.preferred_line_length)
14085 }
14086 }
14087 }
14088
14089 pub fn set_soft_wrap_mode(
14090 &mut self,
14091 mode: language_settings::SoftWrap,
14092
14093 cx: &mut Context<Self>,
14094 ) {
14095 self.soft_wrap_mode_override = Some(mode);
14096 cx.notify();
14097 }
14098
14099 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14100 self.text_style_refinement = Some(style);
14101 }
14102
14103 /// called by the Element so we know what style we were most recently rendered with.
14104 pub(crate) fn set_style(
14105 &mut self,
14106 style: EditorStyle,
14107 window: &mut Window,
14108 cx: &mut Context<Self>,
14109 ) {
14110 let rem_size = window.rem_size();
14111 self.display_map.update(cx, |map, cx| {
14112 map.set_font(
14113 style.text.font(),
14114 style.text.font_size.to_pixels(rem_size),
14115 cx,
14116 )
14117 });
14118 self.style = Some(style);
14119 }
14120
14121 pub fn style(&self) -> Option<&EditorStyle> {
14122 self.style.as_ref()
14123 }
14124
14125 // Called by the element. This method is not designed to be called outside of the editor
14126 // element's layout code because it does not notify when rewrapping is computed synchronously.
14127 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14128 self.display_map
14129 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14130 }
14131
14132 pub fn set_soft_wrap(&mut self) {
14133 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14134 }
14135
14136 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14137 if self.soft_wrap_mode_override.is_some() {
14138 self.soft_wrap_mode_override.take();
14139 } else {
14140 let soft_wrap = match self.soft_wrap_mode(cx) {
14141 SoftWrap::GitDiff => return,
14142 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14143 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14144 language_settings::SoftWrap::None
14145 }
14146 };
14147 self.soft_wrap_mode_override = Some(soft_wrap);
14148 }
14149 cx.notify();
14150 }
14151
14152 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14153 let Some(workspace) = self.workspace() else {
14154 return;
14155 };
14156 let fs = workspace.read(cx).app_state().fs.clone();
14157 let current_show = TabBarSettings::get_global(cx).show;
14158 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14159 setting.show = Some(!current_show);
14160 });
14161 }
14162
14163 pub fn toggle_indent_guides(
14164 &mut self,
14165 _: &ToggleIndentGuides,
14166 _: &mut Window,
14167 cx: &mut Context<Self>,
14168 ) {
14169 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14170 self.buffer
14171 .read(cx)
14172 .language_settings(cx)
14173 .indent_guides
14174 .enabled
14175 });
14176 self.show_indent_guides = Some(!currently_enabled);
14177 cx.notify();
14178 }
14179
14180 fn should_show_indent_guides(&self) -> Option<bool> {
14181 self.show_indent_guides
14182 }
14183
14184 pub fn toggle_line_numbers(
14185 &mut self,
14186 _: &ToggleLineNumbers,
14187 _: &mut Window,
14188 cx: &mut Context<Self>,
14189 ) {
14190 let mut editor_settings = EditorSettings::get_global(cx).clone();
14191 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14192 EditorSettings::override_global(editor_settings, cx);
14193 }
14194
14195 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14196 self.use_relative_line_numbers
14197 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14198 }
14199
14200 pub fn toggle_relative_line_numbers(
14201 &mut self,
14202 _: &ToggleRelativeLineNumbers,
14203 _: &mut Window,
14204 cx: &mut Context<Self>,
14205 ) {
14206 let is_relative = self.should_use_relative_line_numbers(cx);
14207 self.set_relative_line_number(Some(!is_relative), cx)
14208 }
14209
14210 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14211 self.use_relative_line_numbers = is_relative;
14212 cx.notify();
14213 }
14214
14215 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14216 self.show_gutter = show_gutter;
14217 cx.notify();
14218 }
14219
14220 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14221 self.show_scrollbars = show_scrollbars;
14222 cx.notify();
14223 }
14224
14225 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14226 self.show_line_numbers = Some(show_line_numbers);
14227 cx.notify();
14228 }
14229
14230 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14231 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14232 cx.notify();
14233 }
14234
14235 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14236 self.show_code_actions = Some(show_code_actions);
14237 cx.notify();
14238 }
14239
14240 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14241 self.show_runnables = Some(show_runnables);
14242 cx.notify();
14243 }
14244
14245 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14246 if self.display_map.read(cx).masked != masked {
14247 self.display_map.update(cx, |map, _| map.masked = masked);
14248 }
14249 cx.notify()
14250 }
14251
14252 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14253 self.show_wrap_guides = Some(show_wrap_guides);
14254 cx.notify();
14255 }
14256
14257 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14258 self.show_indent_guides = Some(show_indent_guides);
14259 cx.notify();
14260 }
14261
14262 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14263 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14264 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14265 if let Some(dir) = file.abs_path(cx).parent() {
14266 return Some(dir.to_owned());
14267 }
14268 }
14269
14270 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14271 return Some(project_path.path.to_path_buf());
14272 }
14273 }
14274
14275 None
14276 }
14277
14278 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14279 self.active_excerpt(cx)?
14280 .1
14281 .read(cx)
14282 .file()
14283 .and_then(|f| f.as_local())
14284 }
14285
14286 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14287 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14288 let buffer = buffer.read(cx);
14289 if let Some(project_path) = buffer.project_path(cx) {
14290 let project = self.project.as_ref()?.read(cx);
14291 project.absolute_path(&project_path, cx)
14292 } else {
14293 buffer
14294 .file()
14295 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14296 }
14297 })
14298 }
14299
14300 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14301 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14302 let project_path = buffer.read(cx).project_path(cx)?;
14303 let project = self.project.as_ref()?.read(cx);
14304 let entry = project.entry_for_path(&project_path, cx)?;
14305 let path = entry.path.to_path_buf();
14306 Some(path)
14307 })
14308 }
14309
14310 pub fn reveal_in_finder(
14311 &mut self,
14312 _: &RevealInFileManager,
14313 _window: &mut Window,
14314 cx: &mut Context<Self>,
14315 ) {
14316 if let Some(target) = self.target_file(cx) {
14317 cx.reveal_path(&target.abs_path(cx));
14318 }
14319 }
14320
14321 pub fn copy_path(
14322 &mut self,
14323 _: &zed_actions::workspace::CopyPath,
14324 _window: &mut Window,
14325 cx: &mut Context<Self>,
14326 ) {
14327 if let Some(path) = self.target_file_abs_path(cx) {
14328 if let Some(path) = path.to_str() {
14329 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14330 }
14331 }
14332 }
14333
14334 pub fn copy_relative_path(
14335 &mut self,
14336 _: &zed_actions::workspace::CopyRelativePath,
14337 _window: &mut Window,
14338 cx: &mut Context<Self>,
14339 ) {
14340 if let Some(path) = self.target_file_path(cx) {
14341 if let Some(path) = path.to_str() {
14342 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14343 }
14344 }
14345 }
14346
14347 pub fn copy_file_name_without_extension(
14348 &mut self,
14349 _: &CopyFileNameWithoutExtension,
14350 _: &mut Window,
14351 cx: &mut Context<Self>,
14352 ) {
14353 if let Some(file) = self.target_file(cx) {
14354 if let Some(file_stem) = file.path().file_stem() {
14355 if let Some(name) = file_stem.to_str() {
14356 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14357 }
14358 }
14359 }
14360 }
14361
14362 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14363 if let Some(file) = self.target_file(cx) {
14364 if let Some(file_name) = file.path().file_name() {
14365 if let Some(name) = file_name.to_str() {
14366 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14367 }
14368 }
14369 }
14370 }
14371
14372 pub fn toggle_git_blame(
14373 &mut self,
14374 _: &ToggleGitBlame,
14375 window: &mut Window,
14376 cx: &mut Context<Self>,
14377 ) {
14378 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14379
14380 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14381 self.start_git_blame(true, window, cx);
14382 }
14383
14384 cx.notify();
14385 }
14386
14387 pub fn toggle_git_blame_inline(
14388 &mut self,
14389 _: &ToggleGitBlameInline,
14390 window: &mut Window,
14391 cx: &mut Context<Self>,
14392 ) {
14393 self.toggle_git_blame_inline_internal(true, window, cx);
14394 cx.notify();
14395 }
14396
14397 pub fn git_blame_inline_enabled(&self) -> bool {
14398 self.git_blame_inline_enabled
14399 }
14400
14401 pub fn toggle_selection_menu(
14402 &mut self,
14403 _: &ToggleSelectionMenu,
14404 _: &mut Window,
14405 cx: &mut Context<Self>,
14406 ) {
14407 self.show_selection_menu = self
14408 .show_selection_menu
14409 .map(|show_selections_menu| !show_selections_menu)
14410 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14411
14412 cx.notify();
14413 }
14414
14415 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14416 self.show_selection_menu
14417 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14418 }
14419
14420 fn start_git_blame(
14421 &mut self,
14422 user_triggered: bool,
14423 window: &mut Window,
14424 cx: &mut Context<Self>,
14425 ) {
14426 if let Some(project) = self.project.as_ref() {
14427 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14428 return;
14429 };
14430
14431 if buffer.read(cx).file().is_none() {
14432 return;
14433 }
14434
14435 let focused = self.focus_handle(cx).contains_focused(window, cx);
14436
14437 let project = project.clone();
14438 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14439 self.blame_subscription =
14440 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14441 self.blame = Some(blame);
14442 }
14443 }
14444
14445 fn toggle_git_blame_inline_internal(
14446 &mut self,
14447 user_triggered: bool,
14448 window: &mut Window,
14449 cx: &mut Context<Self>,
14450 ) {
14451 if self.git_blame_inline_enabled {
14452 self.git_blame_inline_enabled = false;
14453 self.show_git_blame_inline = false;
14454 self.show_git_blame_inline_delay_task.take();
14455 } else {
14456 self.git_blame_inline_enabled = true;
14457 self.start_git_blame_inline(user_triggered, window, cx);
14458 }
14459
14460 cx.notify();
14461 }
14462
14463 fn start_git_blame_inline(
14464 &mut self,
14465 user_triggered: bool,
14466 window: &mut Window,
14467 cx: &mut Context<Self>,
14468 ) {
14469 self.start_git_blame(user_triggered, window, cx);
14470
14471 if ProjectSettings::get_global(cx)
14472 .git
14473 .inline_blame_delay()
14474 .is_some()
14475 {
14476 self.start_inline_blame_timer(window, cx);
14477 } else {
14478 self.show_git_blame_inline = true
14479 }
14480 }
14481
14482 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14483 self.blame.as_ref()
14484 }
14485
14486 pub fn show_git_blame_gutter(&self) -> bool {
14487 self.show_git_blame_gutter
14488 }
14489
14490 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14491 self.show_git_blame_gutter && self.has_blame_entries(cx)
14492 }
14493
14494 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14495 self.show_git_blame_inline
14496 && (self.focus_handle.is_focused(window)
14497 || self
14498 .git_blame_inline_tooltip
14499 .as_ref()
14500 .and_then(|t| t.upgrade())
14501 .is_some())
14502 && !self.newest_selection_head_on_empty_line(cx)
14503 && self.has_blame_entries(cx)
14504 }
14505
14506 fn has_blame_entries(&self, cx: &App) -> bool {
14507 self.blame()
14508 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14509 }
14510
14511 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14512 let cursor_anchor = self.selections.newest_anchor().head();
14513
14514 let snapshot = self.buffer.read(cx).snapshot(cx);
14515 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14516
14517 snapshot.line_len(buffer_row) == 0
14518 }
14519
14520 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14521 let buffer_and_selection = maybe!({
14522 let selection = self.selections.newest::<Point>(cx);
14523 let selection_range = selection.range();
14524
14525 let multi_buffer = self.buffer().read(cx);
14526 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14527 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14528
14529 let (buffer, range, _) = if selection.reversed {
14530 buffer_ranges.first()
14531 } else {
14532 buffer_ranges.last()
14533 }?;
14534
14535 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14536 ..text::ToPoint::to_point(&range.end, &buffer).row;
14537 Some((
14538 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14539 selection,
14540 ))
14541 });
14542
14543 let Some((buffer, selection)) = buffer_and_selection else {
14544 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14545 };
14546
14547 let Some(project) = self.project.as_ref() else {
14548 return Task::ready(Err(anyhow!("editor does not have project")));
14549 };
14550
14551 project.update(cx, |project, cx| {
14552 project.get_permalink_to_line(&buffer, selection, cx)
14553 })
14554 }
14555
14556 pub fn copy_permalink_to_line(
14557 &mut self,
14558 _: &CopyPermalinkToLine,
14559 window: &mut Window,
14560 cx: &mut Context<Self>,
14561 ) {
14562 let permalink_task = self.get_permalink_to_line(cx);
14563 let workspace = self.workspace();
14564
14565 cx.spawn_in(window, |_, mut cx| async move {
14566 match permalink_task.await {
14567 Ok(permalink) => {
14568 cx.update(|_, cx| {
14569 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14570 })
14571 .ok();
14572 }
14573 Err(err) => {
14574 let message = format!("Failed to copy permalink: {err}");
14575
14576 Err::<(), anyhow::Error>(err).log_err();
14577
14578 if let Some(workspace) = workspace {
14579 workspace
14580 .update_in(&mut cx, |workspace, _, cx| {
14581 struct CopyPermalinkToLine;
14582
14583 workspace.show_toast(
14584 Toast::new(
14585 NotificationId::unique::<CopyPermalinkToLine>(),
14586 message,
14587 ),
14588 cx,
14589 )
14590 })
14591 .ok();
14592 }
14593 }
14594 }
14595 })
14596 .detach();
14597 }
14598
14599 pub fn copy_file_location(
14600 &mut self,
14601 _: &CopyFileLocation,
14602 _: &mut Window,
14603 cx: &mut Context<Self>,
14604 ) {
14605 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14606 if let Some(file) = self.target_file(cx) {
14607 if let Some(path) = file.path().to_str() {
14608 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14609 }
14610 }
14611 }
14612
14613 pub fn open_permalink_to_line(
14614 &mut self,
14615 _: &OpenPermalinkToLine,
14616 window: &mut Window,
14617 cx: &mut Context<Self>,
14618 ) {
14619 let permalink_task = self.get_permalink_to_line(cx);
14620 let workspace = self.workspace();
14621
14622 cx.spawn_in(window, |_, mut cx| async move {
14623 match permalink_task.await {
14624 Ok(permalink) => {
14625 cx.update(|_, cx| {
14626 cx.open_url(permalink.as_ref());
14627 })
14628 .ok();
14629 }
14630 Err(err) => {
14631 let message = format!("Failed to open permalink: {err}");
14632
14633 Err::<(), anyhow::Error>(err).log_err();
14634
14635 if let Some(workspace) = workspace {
14636 workspace
14637 .update(&mut cx, |workspace, cx| {
14638 struct OpenPermalinkToLine;
14639
14640 workspace.show_toast(
14641 Toast::new(
14642 NotificationId::unique::<OpenPermalinkToLine>(),
14643 message,
14644 ),
14645 cx,
14646 )
14647 })
14648 .ok();
14649 }
14650 }
14651 }
14652 })
14653 .detach();
14654 }
14655
14656 pub fn insert_uuid_v4(
14657 &mut self,
14658 _: &InsertUuidV4,
14659 window: &mut Window,
14660 cx: &mut Context<Self>,
14661 ) {
14662 self.insert_uuid(UuidVersion::V4, window, cx);
14663 }
14664
14665 pub fn insert_uuid_v7(
14666 &mut self,
14667 _: &InsertUuidV7,
14668 window: &mut Window,
14669 cx: &mut Context<Self>,
14670 ) {
14671 self.insert_uuid(UuidVersion::V7, window, cx);
14672 }
14673
14674 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14675 self.transact(window, cx, |this, window, cx| {
14676 let edits = this
14677 .selections
14678 .all::<Point>(cx)
14679 .into_iter()
14680 .map(|selection| {
14681 let uuid = match version {
14682 UuidVersion::V4 => uuid::Uuid::new_v4(),
14683 UuidVersion::V7 => uuid::Uuid::now_v7(),
14684 };
14685
14686 (selection.range(), uuid.to_string())
14687 });
14688 this.edit(edits, cx);
14689 this.refresh_inline_completion(true, false, window, cx);
14690 });
14691 }
14692
14693 pub fn open_selections_in_multibuffer(
14694 &mut self,
14695 _: &OpenSelectionsInMultibuffer,
14696 window: &mut Window,
14697 cx: &mut Context<Self>,
14698 ) {
14699 let multibuffer = self.buffer.read(cx);
14700
14701 let Some(buffer) = multibuffer.as_singleton() else {
14702 return;
14703 };
14704
14705 let Some(workspace) = self.workspace() else {
14706 return;
14707 };
14708
14709 let locations = self
14710 .selections
14711 .disjoint_anchors()
14712 .iter()
14713 .map(|range| Location {
14714 buffer: buffer.clone(),
14715 range: range.start.text_anchor..range.end.text_anchor,
14716 })
14717 .collect::<Vec<_>>();
14718
14719 let title = multibuffer.title(cx).to_string();
14720
14721 cx.spawn_in(window, |_, mut cx| async move {
14722 workspace.update_in(&mut cx, |workspace, window, cx| {
14723 Self::open_locations_in_multibuffer(
14724 workspace,
14725 locations,
14726 format!("Selections for '{title}'"),
14727 false,
14728 MultibufferSelectionMode::All,
14729 window,
14730 cx,
14731 );
14732 })
14733 })
14734 .detach();
14735 }
14736
14737 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14738 /// last highlight added will be used.
14739 ///
14740 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14741 pub fn highlight_rows<T: 'static>(
14742 &mut self,
14743 range: Range<Anchor>,
14744 color: Hsla,
14745 should_autoscroll: bool,
14746 cx: &mut Context<Self>,
14747 ) {
14748 let snapshot = self.buffer().read(cx).snapshot(cx);
14749 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14750 let ix = row_highlights.binary_search_by(|highlight| {
14751 Ordering::Equal
14752 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14753 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14754 });
14755
14756 if let Err(mut ix) = ix {
14757 let index = post_inc(&mut self.highlight_order);
14758
14759 // If this range intersects with the preceding highlight, then merge it with
14760 // the preceding highlight. Otherwise insert a new highlight.
14761 let mut merged = false;
14762 if ix > 0 {
14763 let prev_highlight = &mut row_highlights[ix - 1];
14764 if prev_highlight
14765 .range
14766 .end
14767 .cmp(&range.start, &snapshot)
14768 .is_ge()
14769 {
14770 ix -= 1;
14771 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14772 prev_highlight.range.end = range.end;
14773 }
14774 merged = true;
14775 prev_highlight.index = index;
14776 prev_highlight.color = color;
14777 prev_highlight.should_autoscroll = should_autoscroll;
14778 }
14779 }
14780
14781 if !merged {
14782 row_highlights.insert(
14783 ix,
14784 RowHighlight {
14785 range: range.clone(),
14786 index,
14787 color,
14788 should_autoscroll,
14789 },
14790 );
14791 }
14792
14793 // If any of the following highlights intersect with this one, merge them.
14794 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14795 let highlight = &row_highlights[ix];
14796 if next_highlight
14797 .range
14798 .start
14799 .cmp(&highlight.range.end, &snapshot)
14800 .is_le()
14801 {
14802 if next_highlight
14803 .range
14804 .end
14805 .cmp(&highlight.range.end, &snapshot)
14806 .is_gt()
14807 {
14808 row_highlights[ix].range.end = next_highlight.range.end;
14809 }
14810 row_highlights.remove(ix + 1);
14811 } else {
14812 break;
14813 }
14814 }
14815 }
14816 }
14817
14818 /// Remove any highlighted row ranges of the given type that intersect the
14819 /// given ranges.
14820 pub fn remove_highlighted_rows<T: 'static>(
14821 &mut self,
14822 ranges_to_remove: Vec<Range<Anchor>>,
14823 cx: &mut Context<Self>,
14824 ) {
14825 let snapshot = self.buffer().read(cx).snapshot(cx);
14826 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14827 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14828 row_highlights.retain(|highlight| {
14829 while let Some(range_to_remove) = ranges_to_remove.peek() {
14830 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14831 Ordering::Less | Ordering::Equal => {
14832 ranges_to_remove.next();
14833 }
14834 Ordering::Greater => {
14835 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14836 Ordering::Less | Ordering::Equal => {
14837 return false;
14838 }
14839 Ordering::Greater => break,
14840 }
14841 }
14842 }
14843 }
14844
14845 true
14846 })
14847 }
14848
14849 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14850 pub fn clear_row_highlights<T: 'static>(&mut self) {
14851 self.highlighted_rows.remove(&TypeId::of::<T>());
14852 }
14853
14854 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14855 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14856 self.highlighted_rows
14857 .get(&TypeId::of::<T>())
14858 .map_or(&[] as &[_], |vec| vec.as_slice())
14859 .iter()
14860 .map(|highlight| (highlight.range.clone(), highlight.color))
14861 }
14862
14863 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14864 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14865 /// Allows to ignore certain kinds of highlights.
14866 pub fn highlighted_display_rows(
14867 &self,
14868 window: &mut Window,
14869 cx: &mut App,
14870 ) -> BTreeMap<DisplayRow, Background> {
14871 let snapshot = self.snapshot(window, cx);
14872 let mut used_highlight_orders = HashMap::default();
14873 self.highlighted_rows
14874 .iter()
14875 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14876 .fold(
14877 BTreeMap::<DisplayRow, Background>::new(),
14878 |mut unique_rows, highlight| {
14879 let start = highlight.range.start.to_display_point(&snapshot);
14880 let end = highlight.range.end.to_display_point(&snapshot);
14881 let start_row = start.row().0;
14882 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14883 && end.column() == 0
14884 {
14885 end.row().0.saturating_sub(1)
14886 } else {
14887 end.row().0
14888 };
14889 for row in start_row..=end_row {
14890 let used_index =
14891 used_highlight_orders.entry(row).or_insert(highlight.index);
14892 if highlight.index >= *used_index {
14893 *used_index = highlight.index;
14894 unique_rows.insert(DisplayRow(row), highlight.color.into());
14895 }
14896 }
14897 unique_rows
14898 },
14899 )
14900 }
14901
14902 pub fn highlighted_display_row_for_autoscroll(
14903 &self,
14904 snapshot: &DisplaySnapshot,
14905 ) -> Option<DisplayRow> {
14906 self.highlighted_rows
14907 .values()
14908 .flat_map(|highlighted_rows| highlighted_rows.iter())
14909 .filter_map(|highlight| {
14910 if highlight.should_autoscroll {
14911 Some(highlight.range.start.to_display_point(snapshot).row())
14912 } else {
14913 None
14914 }
14915 })
14916 .min()
14917 }
14918
14919 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14920 self.highlight_background::<SearchWithinRange>(
14921 ranges,
14922 |colors| colors.editor_document_highlight_read_background,
14923 cx,
14924 )
14925 }
14926
14927 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14928 self.breadcrumb_header = Some(new_header);
14929 }
14930
14931 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14932 self.clear_background_highlights::<SearchWithinRange>(cx);
14933 }
14934
14935 pub fn highlight_background<T: 'static>(
14936 &mut self,
14937 ranges: &[Range<Anchor>],
14938 color_fetcher: fn(&ThemeColors) -> Hsla,
14939 cx: &mut Context<Self>,
14940 ) {
14941 self.background_highlights
14942 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14943 self.scrollbar_marker_state.dirty = true;
14944 cx.notify();
14945 }
14946
14947 pub fn clear_background_highlights<T: 'static>(
14948 &mut self,
14949 cx: &mut Context<Self>,
14950 ) -> Option<BackgroundHighlight> {
14951 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14952 if !text_highlights.1.is_empty() {
14953 self.scrollbar_marker_state.dirty = true;
14954 cx.notify();
14955 }
14956 Some(text_highlights)
14957 }
14958
14959 pub fn highlight_gutter<T: 'static>(
14960 &mut self,
14961 ranges: &[Range<Anchor>],
14962 color_fetcher: fn(&App) -> Hsla,
14963 cx: &mut Context<Self>,
14964 ) {
14965 self.gutter_highlights
14966 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14967 cx.notify();
14968 }
14969
14970 pub fn clear_gutter_highlights<T: 'static>(
14971 &mut self,
14972 cx: &mut Context<Self>,
14973 ) -> Option<GutterHighlight> {
14974 cx.notify();
14975 self.gutter_highlights.remove(&TypeId::of::<T>())
14976 }
14977
14978 #[cfg(feature = "test-support")]
14979 pub fn all_text_background_highlights(
14980 &self,
14981 window: &mut Window,
14982 cx: &mut Context<Self>,
14983 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14984 let snapshot = self.snapshot(window, cx);
14985 let buffer = &snapshot.buffer_snapshot;
14986 let start = buffer.anchor_before(0);
14987 let end = buffer.anchor_after(buffer.len());
14988 let theme = cx.theme().colors();
14989 self.background_highlights_in_range(start..end, &snapshot, theme)
14990 }
14991
14992 #[cfg(feature = "test-support")]
14993 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
14994 let snapshot = self.buffer().read(cx).snapshot(cx);
14995
14996 let highlights = self
14997 .background_highlights
14998 .get(&TypeId::of::<items::BufferSearchHighlights>());
14999
15000 if let Some((_color, ranges)) = highlights {
15001 ranges
15002 .iter()
15003 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15004 .collect_vec()
15005 } else {
15006 vec![]
15007 }
15008 }
15009
15010 fn document_highlights_for_position<'a>(
15011 &'a self,
15012 position: Anchor,
15013 buffer: &'a MultiBufferSnapshot,
15014 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15015 let read_highlights = self
15016 .background_highlights
15017 .get(&TypeId::of::<DocumentHighlightRead>())
15018 .map(|h| &h.1);
15019 let write_highlights = self
15020 .background_highlights
15021 .get(&TypeId::of::<DocumentHighlightWrite>())
15022 .map(|h| &h.1);
15023 let left_position = position.bias_left(buffer);
15024 let right_position = position.bias_right(buffer);
15025 read_highlights
15026 .into_iter()
15027 .chain(write_highlights)
15028 .flat_map(move |ranges| {
15029 let start_ix = match ranges.binary_search_by(|probe| {
15030 let cmp = probe.end.cmp(&left_position, buffer);
15031 if cmp.is_ge() {
15032 Ordering::Greater
15033 } else {
15034 Ordering::Less
15035 }
15036 }) {
15037 Ok(i) | Err(i) => i,
15038 };
15039
15040 ranges[start_ix..]
15041 .iter()
15042 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15043 })
15044 }
15045
15046 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15047 self.background_highlights
15048 .get(&TypeId::of::<T>())
15049 .map_or(false, |(_, highlights)| !highlights.is_empty())
15050 }
15051
15052 pub fn background_highlights_in_range(
15053 &self,
15054 search_range: Range<Anchor>,
15055 display_snapshot: &DisplaySnapshot,
15056 theme: &ThemeColors,
15057 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15058 let mut results = Vec::new();
15059 for (color_fetcher, ranges) in self.background_highlights.values() {
15060 let color = color_fetcher(theme);
15061 let start_ix = match ranges.binary_search_by(|probe| {
15062 let cmp = probe
15063 .end
15064 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15065 if cmp.is_gt() {
15066 Ordering::Greater
15067 } else {
15068 Ordering::Less
15069 }
15070 }) {
15071 Ok(i) | Err(i) => i,
15072 };
15073 for range in &ranges[start_ix..] {
15074 if range
15075 .start
15076 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15077 .is_ge()
15078 {
15079 break;
15080 }
15081
15082 let start = range.start.to_display_point(display_snapshot);
15083 let end = range.end.to_display_point(display_snapshot);
15084 results.push((start..end, color))
15085 }
15086 }
15087 results
15088 }
15089
15090 pub fn background_highlight_row_ranges<T: 'static>(
15091 &self,
15092 search_range: Range<Anchor>,
15093 display_snapshot: &DisplaySnapshot,
15094 count: usize,
15095 ) -> Vec<RangeInclusive<DisplayPoint>> {
15096 let mut results = Vec::new();
15097 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15098 return vec![];
15099 };
15100
15101 let start_ix = match ranges.binary_search_by(|probe| {
15102 let cmp = probe
15103 .end
15104 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15105 if cmp.is_gt() {
15106 Ordering::Greater
15107 } else {
15108 Ordering::Less
15109 }
15110 }) {
15111 Ok(i) | Err(i) => i,
15112 };
15113 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15114 if let (Some(start_display), Some(end_display)) = (start, end) {
15115 results.push(
15116 start_display.to_display_point(display_snapshot)
15117 ..=end_display.to_display_point(display_snapshot),
15118 );
15119 }
15120 };
15121 let mut start_row: Option<Point> = None;
15122 let mut end_row: Option<Point> = None;
15123 if ranges.len() > count {
15124 return Vec::new();
15125 }
15126 for range in &ranges[start_ix..] {
15127 if range
15128 .start
15129 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15130 .is_ge()
15131 {
15132 break;
15133 }
15134 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15135 if let Some(current_row) = &end_row {
15136 if end.row == current_row.row {
15137 continue;
15138 }
15139 }
15140 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15141 if start_row.is_none() {
15142 assert_eq!(end_row, None);
15143 start_row = Some(start);
15144 end_row = Some(end);
15145 continue;
15146 }
15147 if let Some(current_end) = end_row.as_mut() {
15148 if start.row > current_end.row + 1 {
15149 push_region(start_row, end_row);
15150 start_row = Some(start);
15151 end_row = Some(end);
15152 } else {
15153 // Merge two hunks.
15154 *current_end = end;
15155 }
15156 } else {
15157 unreachable!();
15158 }
15159 }
15160 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15161 push_region(start_row, end_row);
15162 results
15163 }
15164
15165 pub fn gutter_highlights_in_range(
15166 &self,
15167 search_range: Range<Anchor>,
15168 display_snapshot: &DisplaySnapshot,
15169 cx: &App,
15170 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15171 let mut results = Vec::new();
15172 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15173 let color = color_fetcher(cx);
15174 let start_ix = match ranges.binary_search_by(|probe| {
15175 let cmp = probe
15176 .end
15177 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15178 if cmp.is_gt() {
15179 Ordering::Greater
15180 } else {
15181 Ordering::Less
15182 }
15183 }) {
15184 Ok(i) | Err(i) => i,
15185 };
15186 for range in &ranges[start_ix..] {
15187 if range
15188 .start
15189 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15190 .is_ge()
15191 {
15192 break;
15193 }
15194
15195 let start = range.start.to_display_point(display_snapshot);
15196 let end = range.end.to_display_point(display_snapshot);
15197 results.push((start..end, color))
15198 }
15199 }
15200 results
15201 }
15202
15203 /// Get the text ranges corresponding to the redaction query
15204 pub fn redacted_ranges(
15205 &self,
15206 search_range: Range<Anchor>,
15207 display_snapshot: &DisplaySnapshot,
15208 cx: &App,
15209 ) -> Vec<Range<DisplayPoint>> {
15210 display_snapshot
15211 .buffer_snapshot
15212 .redacted_ranges(search_range, |file| {
15213 if let Some(file) = file {
15214 file.is_private()
15215 && EditorSettings::get(
15216 Some(SettingsLocation {
15217 worktree_id: file.worktree_id(cx),
15218 path: file.path().as_ref(),
15219 }),
15220 cx,
15221 )
15222 .redact_private_values
15223 } else {
15224 false
15225 }
15226 })
15227 .map(|range| {
15228 range.start.to_display_point(display_snapshot)
15229 ..range.end.to_display_point(display_snapshot)
15230 })
15231 .collect()
15232 }
15233
15234 pub fn highlight_text<T: 'static>(
15235 &mut self,
15236 ranges: Vec<Range<Anchor>>,
15237 style: HighlightStyle,
15238 cx: &mut Context<Self>,
15239 ) {
15240 self.display_map.update(cx, |map, _| {
15241 map.highlight_text(TypeId::of::<T>(), ranges, style)
15242 });
15243 cx.notify();
15244 }
15245
15246 pub(crate) fn highlight_inlays<T: 'static>(
15247 &mut self,
15248 highlights: Vec<InlayHighlight>,
15249 style: HighlightStyle,
15250 cx: &mut Context<Self>,
15251 ) {
15252 self.display_map.update(cx, |map, _| {
15253 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15254 });
15255 cx.notify();
15256 }
15257
15258 pub fn text_highlights<'a, T: 'static>(
15259 &'a self,
15260 cx: &'a App,
15261 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15262 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15263 }
15264
15265 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15266 let cleared = self
15267 .display_map
15268 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15269 if cleared {
15270 cx.notify();
15271 }
15272 }
15273
15274 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15275 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15276 && self.focus_handle.is_focused(window)
15277 }
15278
15279 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15280 self.show_cursor_when_unfocused = is_enabled;
15281 cx.notify();
15282 }
15283
15284 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15285 cx.notify();
15286 }
15287
15288 fn on_buffer_event(
15289 &mut self,
15290 multibuffer: &Entity<MultiBuffer>,
15291 event: &multi_buffer::Event,
15292 window: &mut Window,
15293 cx: &mut Context<Self>,
15294 ) {
15295 match event {
15296 multi_buffer::Event::Edited {
15297 singleton_buffer_edited,
15298 edited_buffer: buffer_edited,
15299 } => {
15300 self.scrollbar_marker_state.dirty = true;
15301 self.active_indent_guides_state.dirty = true;
15302 self.refresh_active_diagnostics(cx);
15303 self.refresh_code_actions(window, cx);
15304 if self.has_active_inline_completion() {
15305 self.update_visible_inline_completion(window, cx);
15306 }
15307 if let Some(buffer) = buffer_edited {
15308 let buffer_id = buffer.read(cx).remote_id();
15309 if !self.registered_buffers.contains_key(&buffer_id) {
15310 if let Some(project) = self.project.as_ref() {
15311 project.update(cx, |project, cx| {
15312 self.registered_buffers.insert(
15313 buffer_id,
15314 project.register_buffer_with_language_servers(&buffer, cx),
15315 );
15316 })
15317 }
15318 }
15319 }
15320 cx.emit(EditorEvent::BufferEdited);
15321 cx.emit(SearchEvent::MatchesInvalidated);
15322 if *singleton_buffer_edited {
15323 if let Some(project) = &self.project {
15324 #[allow(clippy::mutable_key_type)]
15325 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15326 multibuffer
15327 .all_buffers()
15328 .into_iter()
15329 .filter_map(|buffer| {
15330 buffer.update(cx, |buffer, cx| {
15331 let language = buffer.language()?;
15332 let should_discard = project.update(cx, |project, cx| {
15333 project.is_local()
15334 && !project.has_language_servers_for(buffer, cx)
15335 });
15336 should_discard.not().then_some(language.clone())
15337 })
15338 })
15339 .collect::<HashSet<_>>()
15340 });
15341 if !languages_affected.is_empty() {
15342 self.refresh_inlay_hints(
15343 InlayHintRefreshReason::BufferEdited(languages_affected),
15344 cx,
15345 );
15346 }
15347 }
15348 }
15349
15350 let Some(project) = &self.project else { return };
15351 let (telemetry, is_via_ssh) = {
15352 let project = project.read(cx);
15353 let telemetry = project.client().telemetry().clone();
15354 let is_via_ssh = project.is_via_ssh();
15355 (telemetry, is_via_ssh)
15356 };
15357 refresh_linked_ranges(self, window, cx);
15358 telemetry.log_edit_event("editor", is_via_ssh);
15359 }
15360 multi_buffer::Event::ExcerptsAdded {
15361 buffer,
15362 predecessor,
15363 excerpts,
15364 } => {
15365 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15366 let buffer_id = buffer.read(cx).remote_id();
15367 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15368 if let Some(project) = &self.project {
15369 get_uncommitted_diff_for_buffer(
15370 project,
15371 [buffer.clone()],
15372 self.buffer.clone(),
15373 cx,
15374 )
15375 .detach();
15376 }
15377 }
15378 cx.emit(EditorEvent::ExcerptsAdded {
15379 buffer: buffer.clone(),
15380 predecessor: *predecessor,
15381 excerpts: excerpts.clone(),
15382 });
15383 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15384 }
15385 multi_buffer::Event::ExcerptsRemoved { ids } => {
15386 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15387 let buffer = self.buffer.read(cx);
15388 self.registered_buffers
15389 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15390 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15391 }
15392 multi_buffer::Event::ExcerptsEdited {
15393 excerpt_ids,
15394 buffer_ids,
15395 } => {
15396 self.display_map.update(cx, |map, cx| {
15397 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15398 });
15399 cx.emit(EditorEvent::ExcerptsEdited {
15400 ids: excerpt_ids.clone(),
15401 })
15402 }
15403 multi_buffer::Event::ExcerptsExpanded { ids } => {
15404 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15405 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15406 }
15407 multi_buffer::Event::Reparsed(buffer_id) => {
15408 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15409
15410 cx.emit(EditorEvent::Reparsed(*buffer_id));
15411 }
15412 multi_buffer::Event::DiffHunksToggled => {
15413 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15414 }
15415 multi_buffer::Event::LanguageChanged(buffer_id) => {
15416 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15417 cx.emit(EditorEvent::Reparsed(*buffer_id));
15418 cx.notify();
15419 }
15420 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15421 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15422 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
15423 cx.emit(EditorEvent::TitleChanged)
15424 }
15425 // multi_buffer::Event::DiffBaseChanged => {
15426 // self.scrollbar_marker_state.dirty = true;
15427 // cx.emit(EditorEvent::DiffBaseChanged);
15428 // cx.notify();
15429 // }
15430 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15431 multi_buffer::Event::DiagnosticsUpdated => {
15432 self.refresh_active_diagnostics(cx);
15433 self.refresh_inline_diagnostics(true, window, cx);
15434 self.scrollbar_marker_state.dirty = true;
15435 cx.notify();
15436 }
15437 _ => {}
15438 };
15439 }
15440
15441 fn on_display_map_changed(
15442 &mut self,
15443 _: Entity<DisplayMap>,
15444 _: &mut Window,
15445 cx: &mut Context<Self>,
15446 ) {
15447 cx.notify();
15448 }
15449
15450 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15451 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15452 self.update_edit_prediction_settings(cx);
15453 self.refresh_inline_completion(true, false, window, cx);
15454 self.refresh_inlay_hints(
15455 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15456 self.selections.newest_anchor().head(),
15457 &self.buffer.read(cx).snapshot(cx),
15458 cx,
15459 )),
15460 cx,
15461 );
15462
15463 let old_cursor_shape = self.cursor_shape;
15464
15465 {
15466 let editor_settings = EditorSettings::get_global(cx);
15467 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15468 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15469 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15470 }
15471
15472 if old_cursor_shape != self.cursor_shape {
15473 cx.emit(EditorEvent::CursorShapeChanged);
15474 }
15475
15476 let project_settings = ProjectSettings::get_global(cx);
15477 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15478
15479 if self.mode == EditorMode::Full {
15480 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15481 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15482 if self.show_inline_diagnostics != show_inline_diagnostics {
15483 self.show_inline_diagnostics = show_inline_diagnostics;
15484 self.refresh_inline_diagnostics(false, window, cx);
15485 }
15486
15487 if self.git_blame_inline_enabled != inline_blame_enabled {
15488 self.toggle_git_blame_inline_internal(false, window, cx);
15489 }
15490 }
15491
15492 cx.notify();
15493 }
15494
15495 pub fn set_searchable(&mut self, searchable: bool) {
15496 self.searchable = searchable;
15497 }
15498
15499 pub fn searchable(&self) -> bool {
15500 self.searchable
15501 }
15502
15503 fn open_proposed_changes_editor(
15504 &mut self,
15505 _: &OpenProposedChangesEditor,
15506 window: &mut Window,
15507 cx: &mut Context<Self>,
15508 ) {
15509 let Some(workspace) = self.workspace() else {
15510 cx.propagate();
15511 return;
15512 };
15513
15514 let selections = self.selections.all::<usize>(cx);
15515 let multi_buffer = self.buffer.read(cx);
15516 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15517 let mut new_selections_by_buffer = HashMap::default();
15518 for selection in selections {
15519 for (buffer, range, _) in
15520 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15521 {
15522 let mut range = range.to_point(buffer);
15523 range.start.column = 0;
15524 range.end.column = buffer.line_len(range.end.row);
15525 new_selections_by_buffer
15526 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15527 .or_insert(Vec::new())
15528 .push(range)
15529 }
15530 }
15531
15532 let proposed_changes_buffers = new_selections_by_buffer
15533 .into_iter()
15534 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15535 .collect::<Vec<_>>();
15536 let proposed_changes_editor = cx.new(|cx| {
15537 ProposedChangesEditor::new(
15538 "Proposed changes",
15539 proposed_changes_buffers,
15540 self.project.clone(),
15541 window,
15542 cx,
15543 )
15544 });
15545
15546 window.defer(cx, move |window, cx| {
15547 workspace.update(cx, |workspace, cx| {
15548 workspace.active_pane().update(cx, |pane, cx| {
15549 pane.add_item(
15550 Box::new(proposed_changes_editor),
15551 true,
15552 true,
15553 None,
15554 window,
15555 cx,
15556 );
15557 });
15558 });
15559 });
15560 }
15561
15562 pub fn open_excerpts_in_split(
15563 &mut self,
15564 _: &OpenExcerptsSplit,
15565 window: &mut Window,
15566 cx: &mut Context<Self>,
15567 ) {
15568 self.open_excerpts_common(None, true, window, cx)
15569 }
15570
15571 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15572 self.open_excerpts_common(None, false, window, cx)
15573 }
15574
15575 fn open_excerpts_common(
15576 &mut self,
15577 jump_data: Option<JumpData>,
15578 split: bool,
15579 window: &mut Window,
15580 cx: &mut Context<Self>,
15581 ) {
15582 let Some(workspace) = self.workspace() else {
15583 cx.propagate();
15584 return;
15585 };
15586
15587 if self.buffer.read(cx).is_singleton() {
15588 cx.propagate();
15589 return;
15590 }
15591
15592 let mut new_selections_by_buffer = HashMap::default();
15593 match &jump_data {
15594 Some(JumpData::MultiBufferPoint {
15595 excerpt_id,
15596 position,
15597 anchor,
15598 line_offset_from_top,
15599 }) => {
15600 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15601 if let Some(buffer) = multi_buffer_snapshot
15602 .buffer_id_for_excerpt(*excerpt_id)
15603 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15604 {
15605 let buffer_snapshot = buffer.read(cx).snapshot();
15606 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15607 language::ToPoint::to_point(anchor, &buffer_snapshot)
15608 } else {
15609 buffer_snapshot.clip_point(*position, Bias::Left)
15610 };
15611 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15612 new_selections_by_buffer.insert(
15613 buffer,
15614 (
15615 vec![jump_to_offset..jump_to_offset],
15616 Some(*line_offset_from_top),
15617 ),
15618 );
15619 }
15620 }
15621 Some(JumpData::MultiBufferRow {
15622 row,
15623 line_offset_from_top,
15624 }) => {
15625 let point = MultiBufferPoint::new(row.0, 0);
15626 if let Some((buffer, buffer_point, _)) =
15627 self.buffer.read(cx).point_to_buffer_point(point, cx)
15628 {
15629 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15630 new_selections_by_buffer
15631 .entry(buffer)
15632 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15633 .0
15634 .push(buffer_offset..buffer_offset)
15635 }
15636 }
15637 None => {
15638 let selections = self.selections.all::<usize>(cx);
15639 let multi_buffer = self.buffer.read(cx);
15640 for selection in selections {
15641 for (snapshot, range, _, anchor) in multi_buffer
15642 .snapshot(cx)
15643 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15644 {
15645 if let Some(anchor) = anchor {
15646 // selection is in a deleted hunk
15647 let Some(buffer_id) = anchor.buffer_id else {
15648 continue;
15649 };
15650 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15651 continue;
15652 };
15653 let offset = text::ToOffset::to_offset(
15654 &anchor.text_anchor,
15655 &buffer_handle.read(cx).snapshot(),
15656 );
15657 let range = offset..offset;
15658 new_selections_by_buffer
15659 .entry(buffer_handle)
15660 .or_insert((Vec::new(), None))
15661 .0
15662 .push(range)
15663 } else {
15664 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15665 else {
15666 continue;
15667 };
15668 new_selections_by_buffer
15669 .entry(buffer_handle)
15670 .or_insert((Vec::new(), None))
15671 .0
15672 .push(range)
15673 }
15674 }
15675 }
15676 }
15677 }
15678
15679 if new_selections_by_buffer.is_empty() {
15680 return;
15681 }
15682
15683 // We defer the pane interaction because we ourselves are a workspace item
15684 // and activating a new item causes the pane to call a method on us reentrantly,
15685 // which panics if we're on the stack.
15686 window.defer(cx, move |window, cx| {
15687 workspace.update(cx, |workspace, cx| {
15688 let pane = if split {
15689 workspace.adjacent_pane(window, cx)
15690 } else {
15691 workspace.active_pane().clone()
15692 };
15693
15694 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15695 let editor = buffer
15696 .read(cx)
15697 .file()
15698 .is_none()
15699 .then(|| {
15700 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15701 // so `workspace.open_project_item` will never find them, always opening a new editor.
15702 // Instead, we try to activate the existing editor in the pane first.
15703 let (editor, pane_item_index) =
15704 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15705 let editor = item.downcast::<Editor>()?;
15706 let singleton_buffer =
15707 editor.read(cx).buffer().read(cx).as_singleton()?;
15708 if singleton_buffer == buffer {
15709 Some((editor, i))
15710 } else {
15711 None
15712 }
15713 })?;
15714 pane.update(cx, |pane, cx| {
15715 pane.activate_item(pane_item_index, true, true, window, cx)
15716 });
15717 Some(editor)
15718 })
15719 .flatten()
15720 .unwrap_or_else(|| {
15721 workspace.open_project_item::<Self>(
15722 pane.clone(),
15723 buffer,
15724 true,
15725 true,
15726 window,
15727 cx,
15728 )
15729 });
15730
15731 editor.update(cx, |editor, cx| {
15732 let autoscroll = match scroll_offset {
15733 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15734 None => Autoscroll::newest(),
15735 };
15736 let nav_history = editor.nav_history.take();
15737 editor.change_selections(Some(autoscroll), window, cx, |s| {
15738 s.select_ranges(ranges);
15739 });
15740 editor.nav_history = nav_history;
15741 });
15742 }
15743 })
15744 });
15745 }
15746
15747 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15748 let snapshot = self.buffer.read(cx).read(cx);
15749 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15750 Some(
15751 ranges
15752 .iter()
15753 .map(move |range| {
15754 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15755 })
15756 .collect(),
15757 )
15758 }
15759
15760 fn selection_replacement_ranges(
15761 &self,
15762 range: Range<OffsetUtf16>,
15763 cx: &mut App,
15764 ) -> Vec<Range<OffsetUtf16>> {
15765 let selections = self.selections.all::<OffsetUtf16>(cx);
15766 let newest_selection = selections
15767 .iter()
15768 .max_by_key(|selection| selection.id)
15769 .unwrap();
15770 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15771 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15772 let snapshot = self.buffer.read(cx).read(cx);
15773 selections
15774 .into_iter()
15775 .map(|mut selection| {
15776 selection.start.0 =
15777 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15778 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15779 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15780 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15781 })
15782 .collect()
15783 }
15784
15785 fn report_editor_event(
15786 &self,
15787 event_type: &'static str,
15788 file_extension: Option<String>,
15789 cx: &App,
15790 ) {
15791 if cfg!(any(test, feature = "test-support")) {
15792 return;
15793 }
15794
15795 let Some(project) = &self.project else { return };
15796
15797 // If None, we are in a file without an extension
15798 let file = self
15799 .buffer
15800 .read(cx)
15801 .as_singleton()
15802 .and_then(|b| b.read(cx).file());
15803 let file_extension = file_extension.or(file
15804 .as_ref()
15805 .and_then(|file| Path::new(file.file_name(cx)).extension())
15806 .and_then(|e| e.to_str())
15807 .map(|a| a.to_string()));
15808
15809 let vim_mode = cx
15810 .global::<SettingsStore>()
15811 .raw_user_settings()
15812 .get("vim_mode")
15813 == Some(&serde_json::Value::Bool(true));
15814
15815 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15816 let copilot_enabled = edit_predictions_provider
15817 == language::language_settings::EditPredictionProvider::Copilot;
15818 let copilot_enabled_for_language = self
15819 .buffer
15820 .read(cx)
15821 .language_settings(cx)
15822 .show_edit_predictions;
15823
15824 let project = project.read(cx);
15825 telemetry::event!(
15826 event_type,
15827 file_extension,
15828 vim_mode,
15829 copilot_enabled,
15830 copilot_enabled_for_language,
15831 edit_predictions_provider,
15832 is_via_ssh = project.is_via_ssh(),
15833 );
15834 }
15835
15836 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15837 /// with each line being an array of {text, highlight} objects.
15838 fn copy_highlight_json(
15839 &mut self,
15840 _: &CopyHighlightJson,
15841 window: &mut Window,
15842 cx: &mut Context<Self>,
15843 ) {
15844 #[derive(Serialize)]
15845 struct Chunk<'a> {
15846 text: String,
15847 highlight: Option<&'a str>,
15848 }
15849
15850 let snapshot = self.buffer.read(cx).snapshot(cx);
15851 let range = self
15852 .selected_text_range(false, window, cx)
15853 .and_then(|selection| {
15854 if selection.range.is_empty() {
15855 None
15856 } else {
15857 Some(selection.range)
15858 }
15859 })
15860 .unwrap_or_else(|| 0..snapshot.len());
15861
15862 let chunks = snapshot.chunks(range, true);
15863 let mut lines = Vec::new();
15864 let mut line: VecDeque<Chunk> = VecDeque::new();
15865
15866 let Some(style) = self.style.as_ref() else {
15867 return;
15868 };
15869
15870 for chunk in chunks {
15871 let highlight = chunk
15872 .syntax_highlight_id
15873 .and_then(|id| id.name(&style.syntax));
15874 let mut chunk_lines = chunk.text.split('\n').peekable();
15875 while let Some(text) = chunk_lines.next() {
15876 let mut merged_with_last_token = false;
15877 if let Some(last_token) = line.back_mut() {
15878 if last_token.highlight == highlight {
15879 last_token.text.push_str(text);
15880 merged_with_last_token = true;
15881 }
15882 }
15883
15884 if !merged_with_last_token {
15885 line.push_back(Chunk {
15886 text: text.into(),
15887 highlight,
15888 });
15889 }
15890
15891 if chunk_lines.peek().is_some() {
15892 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15893 line.pop_front();
15894 }
15895 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15896 line.pop_back();
15897 }
15898
15899 lines.push(mem::take(&mut line));
15900 }
15901 }
15902 }
15903
15904 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15905 return;
15906 };
15907 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15908 }
15909
15910 pub fn open_context_menu(
15911 &mut self,
15912 _: &OpenContextMenu,
15913 window: &mut Window,
15914 cx: &mut Context<Self>,
15915 ) {
15916 self.request_autoscroll(Autoscroll::newest(), cx);
15917 let position = self.selections.newest_display(cx).start;
15918 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15919 }
15920
15921 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15922 &self.inlay_hint_cache
15923 }
15924
15925 pub fn replay_insert_event(
15926 &mut self,
15927 text: &str,
15928 relative_utf16_range: Option<Range<isize>>,
15929 window: &mut Window,
15930 cx: &mut Context<Self>,
15931 ) {
15932 if !self.input_enabled {
15933 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15934 return;
15935 }
15936 if let Some(relative_utf16_range) = relative_utf16_range {
15937 let selections = self.selections.all::<OffsetUtf16>(cx);
15938 self.change_selections(None, window, cx, |s| {
15939 let new_ranges = selections.into_iter().map(|range| {
15940 let start = OffsetUtf16(
15941 range
15942 .head()
15943 .0
15944 .saturating_add_signed(relative_utf16_range.start),
15945 );
15946 let end = OffsetUtf16(
15947 range
15948 .head()
15949 .0
15950 .saturating_add_signed(relative_utf16_range.end),
15951 );
15952 start..end
15953 });
15954 s.select_ranges(new_ranges);
15955 });
15956 }
15957
15958 self.handle_input(text, window, cx);
15959 }
15960
15961 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15962 let Some(provider) = self.semantics_provider.as_ref() else {
15963 return false;
15964 };
15965
15966 let mut supports = false;
15967 self.buffer().update(cx, |this, cx| {
15968 this.for_each_buffer(|buffer| {
15969 supports |= provider.supports_inlay_hints(buffer, cx);
15970 });
15971 });
15972
15973 supports
15974 }
15975
15976 pub fn is_focused(&self, window: &Window) -> bool {
15977 self.focus_handle.is_focused(window)
15978 }
15979
15980 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15981 cx.emit(EditorEvent::Focused);
15982
15983 if let Some(descendant) = self
15984 .last_focused_descendant
15985 .take()
15986 .and_then(|descendant| descendant.upgrade())
15987 {
15988 window.focus(&descendant);
15989 } else {
15990 if let Some(blame) = self.blame.as_ref() {
15991 blame.update(cx, GitBlame::focus)
15992 }
15993
15994 self.blink_manager.update(cx, BlinkManager::enable);
15995 self.show_cursor_names(window, cx);
15996 self.buffer.update(cx, |buffer, cx| {
15997 buffer.finalize_last_transaction(cx);
15998 if self.leader_peer_id.is_none() {
15999 buffer.set_active_selections(
16000 &self.selections.disjoint_anchors(),
16001 self.selections.line_mode,
16002 self.cursor_shape,
16003 cx,
16004 );
16005 }
16006 });
16007 }
16008 }
16009
16010 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16011 cx.emit(EditorEvent::FocusedIn)
16012 }
16013
16014 fn handle_focus_out(
16015 &mut self,
16016 event: FocusOutEvent,
16017 _window: &mut Window,
16018 cx: &mut Context<Self>,
16019 ) {
16020 if event.blurred != self.focus_handle {
16021 self.last_focused_descendant = Some(event.blurred);
16022 }
16023 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16024 }
16025
16026 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16027 self.blink_manager.update(cx, BlinkManager::disable);
16028 self.buffer
16029 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16030
16031 if let Some(blame) = self.blame.as_ref() {
16032 blame.update(cx, GitBlame::blur)
16033 }
16034 if !self.hover_state.focused(window, cx) {
16035 hide_hover(self, cx);
16036 }
16037 if !self
16038 .context_menu
16039 .borrow()
16040 .as_ref()
16041 .is_some_and(|context_menu| context_menu.focused(window, cx))
16042 {
16043 self.hide_context_menu(window, cx);
16044 }
16045 self.discard_inline_completion(false, cx);
16046 cx.emit(EditorEvent::Blurred);
16047 cx.notify();
16048 }
16049
16050 pub fn register_action<A: Action>(
16051 &mut self,
16052 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16053 ) -> Subscription {
16054 let id = self.next_editor_action_id.post_inc();
16055 let listener = Arc::new(listener);
16056 self.editor_actions.borrow_mut().insert(
16057 id,
16058 Box::new(move |window, _| {
16059 let listener = listener.clone();
16060 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16061 let action = action.downcast_ref().unwrap();
16062 if phase == DispatchPhase::Bubble {
16063 listener(action, window, cx)
16064 }
16065 })
16066 }),
16067 );
16068
16069 let editor_actions = self.editor_actions.clone();
16070 Subscription::new(move || {
16071 editor_actions.borrow_mut().remove(&id);
16072 })
16073 }
16074
16075 pub fn file_header_size(&self) -> u32 {
16076 FILE_HEADER_HEIGHT
16077 }
16078
16079 pub fn restore(
16080 &mut self,
16081 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16082 window: &mut Window,
16083 cx: &mut Context<Self>,
16084 ) {
16085 let workspace = self.workspace();
16086 let project = self.project.as_ref();
16087 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16088 let mut tasks = Vec::new();
16089 for (buffer_id, changes) in revert_changes {
16090 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16091 buffer.update(cx, |buffer, cx| {
16092 buffer.edit(
16093 changes
16094 .into_iter()
16095 .map(|(range, text)| (range, text.to_string())),
16096 None,
16097 cx,
16098 );
16099 });
16100
16101 if let Some(project) =
16102 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16103 {
16104 project.update(cx, |project, cx| {
16105 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16106 })
16107 }
16108 }
16109 }
16110 tasks
16111 });
16112 cx.spawn_in(window, |_, mut cx| async move {
16113 for (buffer, task) in save_tasks {
16114 let result = task.await;
16115 if result.is_err() {
16116 let Some(path) = buffer
16117 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16118 .ok()
16119 else {
16120 continue;
16121 };
16122 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16123 let Some(task) = cx
16124 .update_window_entity(&workspace, |workspace, window, cx| {
16125 workspace
16126 .open_path_preview(path, None, false, false, false, window, cx)
16127 })
16128 .ok()
16129 else {
16130 continue;
16131 };
16132 task.await.log_err();
16133 }
16134 }
16135 }
16136 })
16137 .detach();
16138 self.change_selections(None, window, cx, |selections| selections.refresh());
16139 }
16140
16141 pub fn to_pixel_point(
16142 &self,
16143 source: multi_buffer::Anchor,
16144 editor_snapshot: &EditorSnapshot,
16145 window: &mut Window,
16146 ) -> Option<gpui::Point<Pixels>> {
16147 let source_point = source.to_display_point(editor_snapshot);
16148 self.display_to_pixel_point(source_point, editor_snapshot, window)
16149 }
16150
16151 pub fn display_to_pixel_point(
16152 &self,
16153 source: DisplayPoint,
16154 editor_snapshot: &EditorSnapshot,
16155 window: &mut Window,
16156 ) -> Option<gpui::Point<Pixels>> {
16157 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16158 let text_layout_details = self.text_layout_details(window);
16159 let scroll_top = text_layout_details
16160 .scroll_anchor
16161 .scroll_position(editor_snapshot)
16162 .y;
16163
16164 if source.row().as_f32() < scroll_top.floor() {
16165 return None;
16166 }
16167 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16168 let source_y = line_height * (source.row().as_f32() - scroll_top);
16169 Some(gpui::Point::new(source_x, source_y))
16170 }
16171
16172 pub fn has_visible_completions_menu(&self) -> bool {
16173 !self.edit_prediction_preview_is_active()
16174 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16175 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16176 })
16177 }
16178
16179 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16180 self.addons
16181 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16182 }
16183
16184 pub fn unregister_addon<T: Addon>(&mut self) {
16185 self.addons.remove(&std::any::TypeId::of::<T>());
16186 }
16187
16188 pub fn addon<T: Addon>(&self) -> Option<&T> {
16189 let type_id = std::any::TypeId::of::<T>();
16190 self.addons
16191 .get(&type_id)
16192 .and_then(|item| item.to_any().downcast_ref::<T>())
16193 }
16194
16195 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16196 let text_layout_details = self.text_layout_details(window);
16197 let style = &text_layout_details.editor_style;
16198 let font_id = window.text_system().resolve_font(&style.text.font());
16199 let font_size = style.text.font_size.to_pixels(window.rem_size());
16200 let line_height = style.text.line_height_in_pixels(window.rem_size());
16201 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16202
16203 gpui::Size::new(em_width, line_height)
16204 }
16205
16206 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16207 self.load_diff_task.clone()
16208 }
16209
16210 fn read_selections_from_db(
16211 &mut self,
16212 item_id: u64,
16213 workspace_id: WorkspaceId,
16214 window: &mut Window,
16215 cx: &mut Context<Editor>,
16216 ) {
16217 if !self.is_singleton(cx)
16218 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16219 {
16220 return;
16221 }
16222 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16223 return;
16224 };
16225 if selections.is_empty() {
16226 return;
16227 }
16228
16229 let snapshot = self.buffer.read(cx).snapshot(cx);
16230 self.change_selections(None, window, cx, |s| {
16231 s.select_ranges(selections.into_iter().map(|(start, end)| {
16232 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16233 }));
16234 });
16235 }
16236}
16237
16238fn insert_extra_newline_brackets(
16239 buffer: &MultiBufferSnapshot,
16240 range: Range<usize>,
16241 language: &language::LanguageScope,
16242) -> bool {
16243 let leading_whitespace_len = buffer
16244 .reversed_chars_at(range.start)
16245 .take_while(|c| c.is_whitespace() && *c != '\n')
16246 .map(|c| c.len_utf8())
16247 .sum::<usize>();
16248 let trailing_whitespace_len = buffer
16249 .chars_at(range.end)
16250 .take_while(|c| c.is_whitespace() && *c != '\n')
16251 .map(|c| c.len_utf8())
16252 .sum::<usize>();
16253 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16254
16255 language.brackets().any(|(pair, enabled)| {
16256 let pair_start = pair.start.trim_end();
16257 let pair_end = pair.end.trim_start();
16258
16259 enabled
16260 && pair.newline
16261 && buffer.contains_str_at(range.end, pair_end)
16262 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16263 })
16264}
16265
16266fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16267 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16268 [(buffer, range, _)] => (*buffer, range.clone()),
16269 _ => return false,
16270 };
16271 let pair = {
16272 let mut result: Option<BracketMatch> = None;
16273
16274 for pair in buffer
16275 .all_bracket_ranges(range.clone())
16276 .filter(move |pair| {
16277 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16278 })
16279 {
16280 let len = pair.close_range.end - pair.open_range.start;
16281
16282 if let Some(existing) = &result {
16283 let existing_len = existing.close_range.end - existing.open_range.start;
16284 if len > existing_len {
16285 continue;
16286 }
16287 }
16288
16289 result = Some(pair);
16290 }
16291
16292 result
16293 };
16294 let Some(pair) = pair else {
16295 return false;
16296 };
16297 pair.newline_only
16298 && buffer
16299 .chars_for_range(pair.open_range.end..range.start)
16300 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16301 .all(|c| c.is_whitespace() && c != '\n')
16302}
16303
16304fn get_uncommitted_diff_for_buffer(
16305 project: &Entity<Project>,
16306 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16307 buffer: Entity<MultiBuffer>,
16308 cx: &mut App,
16309) -> Task<()> {
16310 let mut tasks = Vec::new();
16311 project.update(cx, |project, cx| {
16312 for buffer in buffers {
16313 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16314 }
16315 });
16316 cx.spawn(|mut cx| async move {
16317 let diffs = future::join_all(tasks).await;
16318 buffer
16319 .update(&mut cx, |buffer, cx| {
16320 for diff in diffs.into_iter().flatten() {
16321 buffer.add_diff(diff, cx);
16322 }
16323 })
16324 .ok();
16325 })
16326}
16327
16328fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16329 let tab_size = tab_size.get() as usize;
16330 let mut width = offset;
16331
16332 for ch in text.chars() {
16333 width += if ch == '\t' {
16334 tab_size - (width % tab_size)
16335 } else {
16336 1
16337 };
16338 }
16339
16340 width - offset
16341}
16342
16343#[cfg(test)]
16344mod tests {
16345 use super::*;
16346
16347 #[test]
16348 fn test_string_size_with_expanded_tabs() {
16349 let nz = |val| NonZeroU32::new(val).unwrap();
16350 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16351 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16352 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16353 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16354 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16355 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16356 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16357 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16358 }
16359}
16360
16361/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16362struct WordBreakingTokenizer<'a> {
16363 input: &'a str,
16364}
16365
16366impl<'a> WordBreakingTokenizer<'a> {
16367 fn new(input: &'a str) -> Self {
16368 Self { input }
16369 }
16370}
16371
16372fn is_char_ideographic(ch: char) -> bool {
16373 use unicode_script::Script::*;
16374 use unicode_script::UnicodeScript;
16375 matches!(ch.script(), Han | Tangut | Yi)
16376}
16377
16378fn is_grapheme_ideographic(text: &str) -> bool {
16379 text.chars().any(is_char_ideographic)
16380}
16381
16382fn is_grapheme_whitespace(text: &str) -> bool {
16383 text.chars().any(|x| x.is_whitespace())
16384}
16385
16386fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16387 text.chars().next().map_or(false, |ch| {
16388 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16389 })
16390}
16391
16392#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16393struct WordBreakToken<'a> {
16394 token: &'a str,
16395 grapheme_len: usize,
16396 is_whitespace: bool,
16397}
16398
16399impl<'a> Iterator for WordBreakingTokenizer<'a> {
16400 /// Yields a span, the count of graphemes in the token, and whether it was
16401 /// whitespace. Note that it also breaks at word boundaries.
16402 type Item = WordBreakToken<'a>;
16403
16404 fn next(&mut self) -> Option<Self::Item> {
16405 use unicode_segmentation::UnicodeSegmentation;
16406 if self.input.is_empty() {
16407 return None;
16408 }
16409
16410 let mut iter = self.input.graphemes(true).peekable();
16411 let mut offset = 0;
16412 let mut graphemes = 0;
16413 if let Some(first_grapheme) = iter.next() {
16414 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16415 offset += first_grapheme.len();
16416 graphemes += 1;
16417 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16418 if let Some(grapheme) = iter.peek().copied() {
16419 if should_stay_with_preceding_ideograph(grapheme) {
16420 offset += grapheme.len();
16421 graphemes += 1;
16422 }
16423 }
16424 } else {
16425 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16426 let mut next_word_bound = words.peek().copied();
16427 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16428 next_word_bound = words.next();
16429 }
16430 while let Some(grapheme) = iter.peek().copied() {
16431 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16432 break;
16433 };
16434 if is_grapheme_whitespace(grapheme) != is_whitespace {
16435 break;
16436 };
16437 offset += grapheme.len();
16438 graphemes += 1;
16439 iter.next();
16440 }
16441 }
16442 let token = &self.input[..offset];
16443 self.input = &self.input[offset..];
16444 if is_whitespace {
16445 Some(WordBreakToken {
16446 token: " ",
16447 grapheme_len: 1,
16448 is_whitespace: true,
16449 })
16450 } else {
16451 Some(WordBreakToken {
16452 token,
16453 grapheme_len: graphemes,
16454 is_whitespace: false,
16455 })
16456 }
16457 } else {
16458 None
16459 }
16460 }
16461}
16462
16463#[test]
16464fn test_word_breaking_tokenizer() {
16465 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16466 ("", &[]),
16467 (" ", &[(" ", 1, true)]),
16468 ("Ʒ", &[("Ʒ", 1, false)]),
16469 ("Ǽ", &[("Ǽ", 1, false)]),
16470 ("⋑", &[("⋑", 1, false)]),
16471 ("⋑⋑", &[("⋑⋑", 2, false)]),
16472 (
16473 "原理,进而",
16474 &[
16475 ("原", 1, false),
16476 ("理,", 2, false),
16477 ("进", 1, false),
16478 ("而", 1, false),
16479 ],
16480 ),
16481 (
16482 "hello world",
16483 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16484 ),
16485 (
16486 "hello, world",
16487 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16488 ),
16489 (
16490 " hello world",
16491 &[
16492 (" ", 1, true),
16493 ("hello", 5, false),
16494 (" ", 1, true),
16495 ("world", 5, false),
16496 ],
16497 ),
16498 (
16499 "这是什么 \n 钢笔",
16500 &[
16501 ("这", 1, false),
16502 ("是", 1, false),
16503 ("什", 1, false),
16504 ("么", 1, false),
16505 (" ", 1, true),
16506 ("钢", 1, false),
16507 ("笔", 1, false),
16508 ],
16509 ),
16510 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16511 ];
16512
16513 for (input, result) in tests {
16514 assert_eq!(
16515 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16516 result
16517 .iter()
16518 .copied()
16519 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16520 token,
16521 grapheme_len,
16522 is_whitespace,
16523 })
16524 .collect::<Vec<_>>()
16525 );
16526 }
16527}
16528
16529fn wrap_with_prefix(
16530 line_prefix: String,
16531 unwrapped_text: String,
16532 wrap_column: usize,
16533 tab_size: NonZeroU32,
16534) -> String {
16535 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16536 let mut wrapped_text = String::new();
16537 let mut current_line = line_prefix.clone();
16538
16539 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16540 let mut current_line_len = line_prefix_len;
16541 for WordBreakToken {
16542 token,
16543 grapheme_len,
16544 is_whitespace,
16545 } in tokenizer
16546 {
16547 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16548 wrapped_text.push_str(current_line.trim_end());
16549 wrapped_text.push('\n');
16550 current_line.truncate(line_prefix.len());
16551 current_line_len = line_prefix_len;
16552 if !is_whitespace {
16553 current_line.push_str(token);
16554 current_line_len += grapheme_len;
16555 }
16556 } else if !is_whitespace {
16557 current_line.push_str(token);
16558 current_line_len += grapheme_len;
16559 } else if current_line_len != line_prefix_len {
16560 current_line.push(' ');
16561 current_line_len += 1;
16562 }
16563 }
16564
16565 if !current_line.is_empty() {
16566 wrapped_text.push_str(¤t_line);
16567 }
16568 wrapped_text
16569}
16570
16571#[test]
16572fn test_wrap_with_prefix() {
16573 assert_eq!(
16574 wrap_with_prefix(
16575 "# ".to_string(),
16576 "abcdefg".to_string(),
16577 4,
16578 NonZeroU32::new(4).unwrap()
16579 ),
16580 "# abcdefg"
16581 );
16582 assert_eq!(
16583 wrap_with_prefix(
16584 "".to_string(),
16585 "\thello world".to_string(),
16586 8,
16587 NonZeroU32::new(4).unwrap()
16588 ),
16589 "hello\nworld"
16590 );
16591 assert_eq!(
16592 wrap_with_prefix(
16593 "// ".to_string(),
16594 "xx \nyy zz aa bb cc".to_string(),
16595 12,
16596 NonZeroU32::new(4).unwrap()
16597 ),
16598 "// xx yy zz\n// aa bb cc"
16599 );
16600 assert_eq!(
16601 wrap_with_prefix(
16602 String::new(),
16603 "这是什么 \n 钢笔".to_string(),
16604 3,
16605 NonZeroU32::new(4).unwrap()
16606 ),
16607 "这是什\n么 钢\n笔"
16608 );
16609}
16610
16611pub trait CollaborationHub {
16612 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16613 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16614 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16615}
16616
16617impl CollaborationHub for Entity<Project> {
16618 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16619 self.read(cx).collaborators()
16620 }
16621
16622 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16623 self.read(cx).user_store().read(cx).participant_indices()
16624 }
16625
16626 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16627 let this = self.read(cx);
16628 let user_ids = this.collaborators().values().map(|c| c.user_id);
16629 this.user_store().read_with(cx, |user_store, cx| {
16630 user_store.participant_names(user_ids, cx)
16631 })
16632 }
16633}
16634
16635pub trait SemanticsProvider {
16636 fn hover(
16637 &self,
16638 buffer: &Entity<Buffer>,
16639 position: text::Anchor,
16640 cx: &mut App,
16641 ) -> Option<Task<Vec<project::Hover>>>;
16642
16643 fn inlay_hints(
16644 &self,
16645 buffer_handle: Entity<Buffer>,
16646 range: Range<text::Anchor>,
16647 cx: &mut App,
16648 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16649
16650 fn resolve_inlay_hint(
16651 &self,
16652 hint: InlayHint,
16653 buffer_handle: Entity<Buffer>,
16654 server_id: LanguageServerId,
16655 cx: &mut App,
16656 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16657
16658 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16659
16660 fn document_highlights(
16661 &self,
16662 buffer: &Entity<Buffer>,
16663 position: text::Anchor,
16664 cx: &mut App,
16665 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16666
16667 fn definitions(
16668 &self,
16669 buffer: &Entity<Buffer>,
16670 position: text::Anchor,
16671 kind: GotoDefinitionKind,
16672 cx: &mut App,
16673 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16674
16675 fn range_for_rename(
16676 &self,
16677 buffer: &Entity<Buffer>,
16678 position: text::Anchor,
16679 cx: &mut App,
16680 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16681
16682 fn perform_rename(
16683 &self,
16684 buffer: &Entity<Buffer>,
16685 position: text::Anchor,
16686 new_name: String,
16687 cx: &mut App,
16688 ) -> Option<Task<Result<ProjectTransaction>>>;
16689}
16690
16691pub trait CompletionProvider {
16692 fn completions(
16693 &self,
16694 buffer: &Entity<Buffer>,
16695 buffer_position: text::Anchor,
16696 trigger: CompletionContext,
16697 window: &mut Window,
16698 cx: &mut Context<Editor>,
16699 ) -> Task<Result<Vec<Completion>>>;
16700
16701 fn resolve_completions(
16702 &self,
16703 buffer: Entity<Buffer>,
16704 completion_indices: Vec<usize>,
16705 completions: Rc<RefCell<Box<[Completion]>>>,
16706 cx: &mut Context<Editor>,
16707 ) -> Task<Result<bool>>;
16708
16709 fn apply_additional_edits_for_completion(
16710 &self,
16711 _buffer: Entity<Buffer>,
16712 _completions: Rc<RefCell<Box<[Completion]>>>,
16713 _completion_index: usize,
16714 _push_to_history: bool,
16715 _cx: &mut Context<Editor>,
16716 ) -> Task<Result<Option<language::Transaction>>> {
16717 Task::ready(Ok(None))
16718 }
16719
16720 fn is_completion_trigger(
16721 &self,
16722 buffer: &Entity<Buffer>,
16723 position: language::Anchor,
16724 text: &str,
16725 trigger_in_words: bool,
16726 cx: &mut Context<Editor>,
16727 ) -> bool;
16728
16729 fn sort_completions(&self) -> bool {
16730 true
16731 }
16732}
16733
16734pub trait CodeActionProvider {
16735 fn id(&self) -> Arc<str>;
16736
16737 fn code_actions(
16738 &self,
16739 buffer: &Entity<Buffer>,
16740 range: Range<text::Anchor>,
16741 window: &mut Window,
16742 cx: &mut App,
16743 ) -> Task<Result<Vec<CodeAction>>>;
16744
16745 fn apply_code_action(
16746 &self,
16747 buffer_handle: Entity<Buffer>,
16748 action: CodeAction,
16749 excerpt_id: ExcerptId,
16750 push_to_history: bool,
16751 window: &mut Window,
16752 cx: &mut App,
16753 ) -> Task<Result<ProjectTransaction>>;
16754}
16755
16756impl CodeActionProvider for Entity<Project> {
16757 fn id(&self) -> Arc<str> {
16758 "project".into()
16759 }
16760
16761 fn code_actions(
16762 &self,
16763 buffer: &Entity<Buffer>,
16764 range: Range<text::Anchor>,
16765 _window: &mut Window,
16766 cx: &mut App,
16767 ) -> Task<Result<Vec<CodeAction>>> {
16768 self.update(cx, |project, cx| {
16769 project.code_actions(buffer, range, None, cx)
16770 })
16771 }
16772
16773 fn apply_code_action(
16774 &self,
16775 buffer_handle: Entity<Buffer>,
16776 action: CodeAction,
16777 _excerpt_id: ExcerptId,
16778 push_to_history: bool,
16779 _window: &mut Window,
16780 cx: &mut App,
16781 ) -> Task<Result<ProjectTransaction>> {
16782 self.update(cx, |project, cx| {
16783 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16784 })
16785 }
16786}
16787
16788fn snippet_completions(
16789 project: &Project,
16790 buffer: &Entity<Buffer>,
16791 buffer_position: text::Anchor,
16792 cx: &mut App,
16793) -> Task<Result<Vec<Completion>>> {
16794 let language = buffer.read(cx).language_at(buffer_position);
16795 let language_name = language.as_ref().map(|language| language.lsp_id());
16796 let snippet_store = project.snippets().read(cx);
16797 let snippets = snippet_store.snippets_for(language_name, cx);
16798
16799 if snippets.is_empty() {
16800 return Task::ready(Ok(vec![]));
16801 }
16802 let snapshot = buffer.read(cx).text_snapshot();
16803 let chars: String = snapshot
16804 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16805 .collect();
16806
16807 let scope = language.map(|language| language.default_scope());
16808 let executor = cx.background_executor().clone();
16809
16810 cx.background_spawn(async move {
16811 let classifier = CharClassifier::new(scope).for_completion(true);
16812 let mut last_word = chars
16813 .chars()
16814 .take_while(|c| classifier.is_word(*c))
16815 .collect::<String>();
16816 last_word = last_word.chars().rev().collect();
16817
16818 if last_word.is_empty() {
16819 return Ok(vec![]);
16820 }
16821
16822 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16823 let to_lsp = |point: &text::Anchor| {
16824 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16825 point_to_lsp(end)
16826 };
16827 let lsp_end = to_lsp(&buffer_position);
16828
16829 let candidates = snippets
16830 .iter()
16831 .enumerate()
16832 .flat_map(|(ix, snippet)| {
16833 snippet
16834 .prefix
16835 .iter()
16836 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16837 })
16838 .collect::<Vec<StringMatchCandidate>>();
16839
16840 let mut matches = fuzzy::match_strings(
16841 &candidates,
16842 &last_word,
16843 last_word.chars().any(|c| c.is_uppercase()),
16844 100,
16845 &Default::default(),
16846 executor,
16847 )
16848 .await;
16849
16850 // Remove all candidates where the query's start does not match the start of any word in the candidate
16851 if let Some(query_start) = last_word.chars().next() {
16852 matches.retain(|string_match| {
16853 split_words(&string_match.string).any(|word| {
16854 // Check that the first codepoint of the word as lowercase matches the first
16855 // codepoint of the query as lowercase
16856 word.chars()
16857 .flat_map(|codepoint| codepoint.to_lowercase())
16858 .zip(query_start.to_lowercase())
16859 .all(|(word_cp, query_cp)| word_cp == query_cp)
16860 })
16861 });
16862 }
16863
16864 let matched_strings = matches
16865 .into_iter()
16866 .map(|m| m.string)
16867 .collect::<HashSet<_>>();
16868
16869 let result: Vec<Completion> = snippets
16870 .into_iter()
16871 .filter_map(|snippet| {
16872 let matching_prefix = snippet
16873 .prefix
16874 .iter()
16875 .find(|prefix| matched_strings.contains(*prefix))?;
16876 let start = as_offset - last_word.len();
16877 let start = snapshot.anchor_before(start);
16878 let range = start..buffer_position;
16879 let lsp_start = to_lsp(&start);
16880 let lsp_range = lsp::Range {
16881 start: lsp_start,
16882 end: lsp_end,
16883 };
16884 Some(Completion {
16885 old_range: range,
16886 new_text: snippet.body.clone(),
16887 resolved: false,
16888 label: CodeLabel {
16889 text: matching_prefix.clone(),
16890 runs: vec![],
16891 filter_range: 0..matching_prefix.len(),
16892 },
16893 server_id: LanguageServerId(usize::MAX),
16894 documentation: snippet
16895 .description
16896 .clone()
16897 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16898 lsp_completion: lsp::CompletionItem {
16899 label: snippet.prefix.first().unwrap().clone(),
16900 kind: Some(CompletionItemKind::SNIPPET),
16901 label_details: snippet.description.as_ref().map(|description| {
16902 lsp::CompletionItemLabelDetails {
16903 detail: Some(description.clone()),
16904 description: None,
16905 }
16906 }),
16907 insert_text_format: Some(InsertTextFormat::SNIPPET),
16908 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16909 lsp::InsertReplaceEdit {
16910 new_text: snippet.body.clone(),
16911 insert: lsp_range,
16912 replace: lsp_range,
16913 },
16914 )),
16915 filter_text: Some(snippet.body.clone()),
16916 sort_text: Some(char::MAX.to_string()),
16917 ..Default::default()
16918 },
16919 confirm: None,
16920 })
16921 })
16922 .collect();
16923
16924 Ok(result)
16925 })
16926}
16927
16928impl CompletionProvider for Entity<Project> {
16929 fn completions(
16930 &self,
16931 buffer: &Entity<Buffer>,
16932 buffer_position: text::Anchor,
16933 options: CompletionContext,
16934 _window: &mut Window,
16935 cx: &mut Context<Editor>,
16936 ) -> Task<Result<Vec<Completion>>> {
16937 self.update(cx, |project, cx| {
16938 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16939 let project_completions = project.completions(buffer, buffer_position, options, cx);
16940 cx.background_spawn(async move {
16941 let mut completions = project_completions.await?;
16942 let snippets_completions = snippets.await?;
16943 completions.extend(snippets_completions);
16944 Ok(completions)
16945 })
16946 })
16947 }
16948
16949 fn resolve_completions(
16950 &self,
16951 buffer: Entity<Buffer>,
16952 completion_indices: Vec<usize>,
16953 completions: Rc<RefCell<Box<[Completion]>>>,
16954 cx: &mut Context<Editor>,
16955 ) -> Task<Result<bool>> {
16956 self.update(cx, |project, cx| {
16957 project.lsp_store().update(cx, |lsp_store, cx| {
16958 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16959 })
16960 })
16961 }
16962
16963 fn apply_additional_edits_for_completion(
16964 &self,
16965 buffer: Entity<Buffer>,
16966 completions: Rc<RefCell<Box<[Completion]>>>,
16967 completion_index: usize,
16968 push_to_history: bool,
16969 cx: &mut Context<Editor>,
16970 ) -> Task<Result<Option<language::Transaction>>> {
16971 self.update(cx, |project, cx| {
16972 project.lsp_store().update(cx, |lsp_store, cx| {
16973 lsp_store.apply_additional_edits_for_completion(
16974 buffer,
16975 completions,
16976 completion_index,
16977 push_to_history,
16978 cx,
16979 )
16980 })
16981 })
16982 }
16983
16984 fn is_completion_trigger(
16985 &self,
16986 buffer: &Entity<Buffer>,
16987 position: language::Anchor,
16988 text: &str,
16989 trigger_in_words: bool,
16990 cx: &mut Context<Editor>,
16991 ) -> bool {
16992 let mut chars = text.chars();
16993 let char = if let Some(char) = chars.next() {
16994 char
16995 } else {
16996 return false;
16997 };
16998 if chars.next().is_some() {
16999 return false;
17000 }
17001
17002 let buffer = buffer.read(cx);
17003 let snapshot = buffer.snapshot();
17004 if !snapshot.settings_at(position, cx).show_completions_on_input {
17005 return false;
17006 }
17007 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17008 if trigger_in_words && classifier.is_word(char) {
17009 return true;
17010 }
17011
17012 buffer.completion_triggers().contains(text)
17013 }
17014}
17015
17016impl SemanticsProvider for Entity<Project> {
17017 fn hover(
17018 &self,
17019 buffer: &Entity<Buffer>,
17020 position: text::Anchor,
17021 cx: &mut App,
17022 ) -> Option<Task<Vec<project::Hover>>> {
17023 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17024 }
17025
17026 fn document_highlights(
17027 &self,
17028 buffer: &Entity<Buffer>,
17029 position: text::Anchor,
17030 cx: &mut App,
17031 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17032 Some(self.update(cx, |project, cx| {
17033 project.document_highlights(buffer, position, cx)
17034 }))
17035 }
17036
17037 fn definitions(
17038 &self,
17039 buffer: &Entity<Buffer>,
17040 position: text::Anchor,
17041 kind: GotoDefinitionKind,
17042 cx: &mut App,
17043 ) -> Option<Task<Result<Vec<LocationLink>>>> {
17044 Some(self.update(cx, |project, cx| match kind {
17045 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17046 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17047 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17048 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17049 }))
17050 }
17051
17052 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17053 // TODO: make this work for remote projects
17054 self.update(cx, |this, cx| {
17055 buffer.update(cx, |buffer, cx| {
17056 this.any_language_server_supports_inlay_hints(buffer, cx)
17057 })
17058 })
17059 }
17060
17061 fn inlay_hints(
17062 &self,
17063 buffer_handle: Entity<Buffer>,
17064 range: Range<text::Anchor>,
17065 cx: &mut App,
17066 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17067 Some(self.update(cx, |project, cx| {
17068 project.inlay_hints(buffer_handle, range, cx)
17069 }))
17070 }
17071
17072 fn resolve_inlay_hint(
17073 &self,
17074 hint: InlayHint,
17075 buffer_handle: Entity<Buffer>,
17076 server_id: LanguageServerId,
17077 cx: &mut App,
17078 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17079 Some(self.update(cx, |project, cx| {
17080 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17081 }))
17082 }
17083
17084 fn range_for_rename(
17085 &self,
17086 buffer: &Entity<Buffer>,
17087 position: text::Anchor,
17088 cx: &mut App,
17089 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17090 Some(self.update(cx, |project, cx| {
17091 let buffer = buffer.clone();
17092 let task = project.prepare_rename(buffer.clone(), position, cx);
17093 cx.spawn(|_, mut cx| async move {
17094 Ok(match task.await? {
17095 PrepareRenameResponse::Success(range) => Some(range),
17096 PrepareRenameResponse::InvalidPosition => None,
17097 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17098 // Fallback on using TreeSitter info to determine identifier range
17099 buffer.update(&mut cx, |buffer, _| {
17100 let snapshot = buffer.snapshot();
17101 let (range, kind) = snapshot.surrounding_word(position);
17102 if kind != Some(CharKind::Word) {
17103 return None;
17104 }
17105 Some(
17106 snapshot.anchor_before(range.start)
17107 ..snapshot.anchor_after(range.end),
17108 )
17109 })?
17110 }
17111 })
17112 })
17113 }))
17114 }
17115
17116 fn perform_rename(
17117 &self,
17118 buffer: &Entity<Buffer>,
17119 position: text::Anchor,
17120 new_name: String,
17121 cx: &mut App,
17122 ) -> Option<Task<Result<ProjectTransaction>>> {
17123 Some(self.update(cx, |project, cx| {
17124 project.perform_rename(buffer.clone(), position, new_name, cx)
17125 }))
17126 }
17127}
17128
17129fn inlay_hint_settings(
17130 location: Anchor,
17131 snapshot: &MultiBufferSnapshot,
17132 cx: &mut Context<Editor>,
17133) -> InlayHintSettings {
17134 let file = snapshot.file_at(location);
17135 let language = snapshot.language_at(location).map(|l| l.name());
17136 language_settings(language, file, cx).inlay_hints
17137}
17138
17139fn consume_contiguous_rows(
17140 contiguous_row_selections: &mut Vec<Selection<Point>>,
17141 selection: &Selection<Point>,
17142 display_map: &DisplaySnapshot,
17143 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17144) -> (MultiBufferRow, MultiBufferRow) {
17145 contiguous_row_selections.push(selection.clone());
17146 let start_row = MultiBufferRow(selection.start.row);
17147 let mut end_row = ending_row(selection, display_map);
17148
17149 while let Some(next_selection) = selections.peek() {
17150 if next_selection.start.row <= end_row.0 {
17151 end_row = ending_row(next_selection, display_map);
17152 contiguous_row_selections.push(selections.next().unwrap().clone());
17153 } else {
17154 break;
17155 }
17156 }
17157 (start_row, end_row)
17158}
17159
17160fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17161 if next_selection.end.column > 0 || next_selection.is_empty() {
17162 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17163 } else {
17164 MultiBufferRow(next_selection.end.row)
17165 }
17166}
17167
17168impl EditorSnapshot {
17169 pub fn remote_selections_in_range<'a>(
17170 &'a self,
17171 range: &'a Range<Anchor>,
17172 collaboration_hub: &dyn CollaborationHub,
17173 cx: &'a App,
17174 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17175 let participant_names = collaboration_hub.user_names(cx);
17176 let participant_indices = collaboration_hub.user_participant_indices(cx);
17177 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17178 let collaborators_by_replica_id = collaborators_by_peer_id
17179 .iter()
17180 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17181 .collect::<HashMap<_, _>>();
17182 self.buffer_snapshot
17183 .selections_in_range(range, false)
17184 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17185 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17186 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17187 let user_name = participant_names.get(&collaborator.user_id).cloned();
17188 Some(RemoteSelection {
17189 replica_id,
17190 selection,
17191 cursor_shape,
17192 line_mode,
17193 participant_index,
17194 peer_id: collaborator.peer_id,
17195 user_name,
17196 })
17197 })
17198 }
17199
17200 pub fn hunks_for_ranges(
17201 &self,
17202 ranges: impl IntoIterator<Item = Range<Point>>,
17203 ) -> Vec<MultiBufferDiffHunk> {
17204 let mut hunks = Vec::new();
17205 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17206 HashMap::default();
17207 for query_range in ranges {
17208 let query_rows =
17209 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17210 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17211 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17212 ) {
17213 // Include deleted hunks that are adjacent to the query range, because
17214 // otherwise they would be missed.
17215 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17216 if hunk.status().is_deleted() {
17217 intersects_range |= hunk.row_range.start == query_rows.end;
17218 intersects_range |= hunk.row_range.end == query_rows.start;
17219 }
17220 if intersects_range {
17221 if !processed_buffer_rows
17222 .entry(hunk.buffer_id)
17223 .or_default()
17224 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17225 {
17226 continue;
17227 }
17228 hunks.push(hunk);
17229 }
17230 }
17231 }
17232
17233 hunks
17234 }
17235
17236 fn display_diff_hunks_for_rows<'a>(
17237 &'a self,
17238 display_rows: Range<DisplayRow>,
17239 folded_buffers: &'a HashSet<BufferId>,
17240 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17241 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17242 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17243
17244 self.buffer_snapshot
17245 .diff_hunks_in_range(buffer_start..buffer_end)
17246 .filter_map(|hunk| {
17247 if folded_buffers.contains(&hunk.buffer_id) {
17248 return None;
17249 }
17250
17251 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17252 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17253
17254 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17255 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17256
17257 let display_hunk = if hunk_display_start.column() != 0 {
17258 DisplayDiffHunk::Folded {
17259 display_row: hunk_display_start.row(),
17260 }
17261 } else {
17262 let mut end_row = hunk_display_end.row();
17263 if hunk_display_end.column() > 0 {
17264 end_row.0 += 1;
17265 }
17266 DisplayDiffHunk::Unfolded {
17267 status: hunk.status(),
17268 diff_base_byte_range: hunk.diff_base_byte_range,
17269 display_row_range: hunk_display_start.row()..end_row,
17270 multi_buffer_range: Anchor::range_in_buffer(
17271 hunk.excerpt_id,
17272 hunk.buffer_id,
17273 hunk.buffer_range,
17274 ),
17275 }
17276 };
17277
17278 Some(display_hunk)
17279 })
17280 }
17281
17282 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17283 self.display_snapshot.buffer_snapshot.language_at(position)
17284 }
17285
17286 pub fn is_focused(&self) -> bool {
17287 self.is_focused
17288 }
17289
17290 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17291 self.placeholder_text.as_ref()
17292 }
17293
17294 pub fn scroll_position(&self) -> gpui::Point<f32> {
17295 self.scroll_anchor.scroll_position(&self.display_snapshot)
17296 }
17297
17298 fn gutter_dimensions(
17299 &self,
17300 font_id: FontId,
17301 font_size: Pixels,
17302 max_line_number_width: Pixels,
17303 cx: &App,
17304 ) -> Option<GutterDimensions> {
17305 if !self.show_gutter {
17306 return None;
17307 }
17308
17309 let descent = cx.text_system().descent(font_id, font_size);
17310 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17311 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17312
17313 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17314 matches!(
17315 ProjectSettings::get_global(cx).git.git_gutter,
17316 Some(GitGutterSetting::TrackedFiles)
17317 )
17318 });
17319 let gutter_settings = EditorSettings::get_global(cx).gutter;
17320 let show_line_numbers = self
17321 .show_line_numbers
17322 .unwrap_or(gutter_settings.line_numbers);
17323 let line_gutter_width = if show_line_numbers {
17324 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17325 let min_width_for_number_on_gutter = em_advance * 4.0;
17326 max_line_number_width.max(min_width_for_number_on_gutter)
17327 } else {
17328 0.0.into()
17329 };
17330
17331 let show_code_actions = self
17332 .show_code_actions
17333 .unwrap_or(gutter_settings.code_actions);
17334
17335 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17336
17337 let git_blame_entries_width =
17338 self.git_blame_gutter_max_author_length
17339 .map(|max_author_length| {
17340 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17341
17342 /// The number of characters to dedicate to gaps and margins.
17343 const SPACING_WIDTH: usize = 4;
17344
17345 let max_char_count = max_author_length
17346 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17347 + ::git::SHORT_SHA_LENGTH
17348 + MAX_RELATIVE_TIMESTAMP.len()
17349 + SPACING_WIDTH;
17350
17351 em_advance * max_char_count
17352 });
17353
17354 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17355 left_padding += if show_code_actions || show_runnables {
17356 em_width * 3.0
17357 } else if show_git_gutter && show_line_numbers {
17358 em_width * 2.0
17359 } else if show_git_gutter || show_line_numbers {
17360 em_width
17361 } else {
17362 px(0.)
17363 };
17364
17365 let right_padding = if gutter_settings.folds && show_line_numbers {
17366 em_width * 4.0
17367 } else if gutter_settings.folds {
17368 em_width * 3.0
17369 } else if show_line_numbers {
17370 em_width
17371 } else {
17372 px(0.)
17373 };
17374
17375 Some(GutterDimensions {
17376 left_padding,
17377 right_padding,
17378 width: line_gutter_width + left_padding + right_padding,
17379 margin: -descent,
17380 git_blame_entries_width,
17381 })
17382 }
17383
17384 pub fn render_crease_toggle(
17385 &self,
17386 buffer_row: MultiBufferRow,
17387 row_contains_cursor: bool,
17388 editor: Entity<Editor>,
17389 window: &mut Window,
17390 cx: &mut App,
17391 ) -> Option<AnyElement> {
17392 let folded = self.is_line_folded(buffer_row);
17393 let mut is_foldable = false;
17394
17395 if let Some(crease) = self
17396 .crease_snapshot
17397 .query_row(buffer_row, &self.buffer_snapshot)
17398 {
17399 is_foldable = true;
17400 match crease {
17401 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17402 if let Some(render_toggle) = render_toggle {
17403 let toggle_callback =
17404 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17405 if folded {
17406 editor.update(cx, |editor, cx| {
17407 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17408 });
17409 } else {
17410 editor.update(cx, |editor, cx| {
17411 editor.unfold_at(
17412 &crate::UnfoldAt { buffer_row },
17413 window,
17414 cx,
17415 )
17416 });
17417 }
17418 });
17419 return Some((render_toggle)(
17420 buffer_row,
17421 folded,
17422 toggle_callback,
17423 window,
17424 cx,
17425 ));
17426 }
17427 }
17428 }
17429 }
17430
17431 is_foldable |= self.starts_indent(buffer_row);
17432
17433 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17434 Some(
17435 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17436 .toggle_state(folded)
17437 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17438 if folded {
17439 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17440 } else {
17441 this.fold_at(&FoldAt { buffer_row }, window, cx);
17442 }
17443 }))
17444 .into_any_element(),
17445 )
17446 } else {
17447 None
17448 }
17449 }
17450
17451 pub fn render_crease_trailer(
17452 &self,
17453 buffer_row: MultiBufferRow,
17454 window: &mut Window,
17455 cx: &mut App,
17456 ) -> Option<AnyElement> {
17457 let folded = self.is_line_folded(buffer_row);
17458 if let Crease::Inline { render_trailer, .. } = self
17459 .crease_snapshot
17460 .query_row(buffer_row, &self.buffer_snapshot)?
17461 {
17462 let render_trailer = render_trailer.as_ref()?;
17463 Some(render_trailer(buffer_row, folded, window, cx))
17464 } else {
17465 None
17466 }
17467 }
17468}
17469
17470impl Deref for EditorSnapshot {
17471 type Target = DisplaySnapshot;
17472
17473 fn deref(&self) -> &Self::Target {
17474 &self.display_snapshot
17475 }
17476}
17477
17478#[derive(Clone, Debug, PartialEq, Eq)]
17479pub enum EditorEvent {
17480 InputIgnored {
17481 text: Arc<str>,
17482 },
17483 InputHandled {
17484 utf16_range_to_replace: Option<Range<isize>>,
17485 text: Arc<str>,
17486 },
17487 ExcerptsAdded {
17488 buffer: Entity<Buffer>,
17489 predecessor: ExcerptId,
17490 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17491 },
17492 ExcerptsRemoved {
17493 ids: Vec<ExcerptId>,
17494 },
17495 BufferFoldToggled {
17496 ids: Vec<ExcerptId>,
17497 folded: bool,
17498 },
17499 ExcerptsEdited {
17500 ids: Vec<ExcerptId>,
17501 },
17502 ExcerptsExpanded {
17503 ids: Vec<ExcerptId>,
17504 },
17505 BufferEdited,
17506 Edited {
17507 transaction_id: clock::Lamport,
17508 },
17509 Reparsed(BufferId),
17510 Focused,
17511 FocusedIn,
17512 Blurred,
17513 DirtyChanged,
17514 Saved,
17515 TitleChanged,
17516 DiffBaseChanged,
17517 SelectionsChanged {
17518 local: bool,
17519 },
17520 ScrollPositionChanged {
17521 local: bool,
17522 autoscroll: bool,
17523 },
17524 Closed,
17525 TransactionUndone {
17526 transaction_id: clock::Lamport,
17527 },
17528 TransactionBegun {
17529 transaction_id: clock::Lamport,
17530 },
17531 Reloaded,
17532 CursorShapeChanged,
17533}
17534
17535impl EventEmitter<EditorEvent> for Editor {}
17536
17537impl Focusable for Editor {
17538 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17539 self.focus_handle.clone()
17540 }
17541}
17542
17543impl Render for Editor {
17544 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17545 let settings = ThemeSettings::get_global(cx);
17546
17547 let mut text_style = match self.mode {
17548 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17549 color: cx.theme().colors().editor_foreground,
17550 font_family: settings.ui_font.family.clone(),
17551 font_features: settings.ui_font.features.clone(),
17552 font_fallbacks: settings.ui_font.fallbacks.clone(),
17553 font_size: rems(0.875).into(),
17554 font_weight: settings.ui_font.weight,
17555 line_height: relative(settings.buffer_line_height.value()),
17556 ..Default::default()
17557 },
17558 EditorMode::Full => TextStyle {
17559 color: cx.theme().colors().editor_foreground,
17560 font_family: settings.buffer_font.family.clone(),
17561 font_features: settings.buffer_font.features.clone(),
17562 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17563 font_size: settings.buffer_font_size(cx).into(),
17564 font_weight: settings.buffer_font.weight,
17565 line_height: relative(settings.buffer_line_height.value()),
17566 ..Default::default()
17567 },
17568 };
17569 if let Some(text_style_refinement) = &self.text_style_refinement {
17570 text_style.refine(text_style_refinement)
17571 }
17572
17573 let background = match self.mode {
17574 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17575 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17576 EditorMode::Full => cx.theme().colors().editor_background,
17577 };
17578
17579 EditorElement::new(
17580 &cx.entity(),
17581 EditorStyle {
17582 background,
17583 local_player: cx.theme().players().local(),
17584 text: text_style,
17585 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17586 syntax: cx.theme().syntax().clone(),
17587 status: cx.theme().status().clone(),
17588 inlay_hints_style: make_inlay_hints_style(cx),
17589 inline_completion_styles: make_suggestion_styles(cx),
17590 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17591 },
17592 )
17593 }
17594}
17595
17596impl EntityInputHandler for Editor {
17597 fn text_for_range(
17598 &mut self,
17599 range_utf16: Range<usize>,
17600 adjusted_range: &mut Option<Range<usize>>,
17601 _: &mut Window,
17602 cx: &mut Context<Self>,
17603 ) -> Option<String> {
17604 let snapshot = self.buffer.read(cx).read(cx);
17605 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17606 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17607 if (start.0..end.0) != range_utf16 {
17608 adjusted_range.replace(start.0..end.0);
17609 }
17610 Some(snapshot.text_for_range(start..end).collect())
17611 }
17612
17613 fn selected_text_range(
17614 &mut self,
17615 ignore_disabled_input: bool,
17616 _: &mut Window,
17617 cx: &mut Context<Self>,
17618 ) -> Option<UTF16Selection> {
17619 // Prevent the IME menu from appearing when holding down an alphabetic key
17620 // while input is disabled.
17621 if !ignore_disabled_input && !self.input_enabled {
17622 return None;
17623 }
17624
17625 let selection = self.selections.newest::<OffsetUtf16>(cx);
17626 let range = selection.range();
17627
17628 Some(UTF16Selection {
17629 range: range.start.0..range.end.0,
17630 reversed: selection.reversed,
17631 })
17632 }
17633
17634 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17635 let snapshot = self.buffer.read(cx).read(cx);
17636 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17637 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17638 }
17639
17640 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17641 self.clear_highlights::<InputComposition>(cx);
17642 self.ime_transaction.take();
17643 }
17644
17645 fn replace_text_in_range(
17646 &mut self,
17647 range_utf16: Option<Range<usize>>,
17648 text: &str,
17649 window: &mut Window,
17650 cx: &mut Context<Self>,
17651 ) {
17652 if !self.input_enabled {
17653 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17654 return;
17655 }
17656
17657 self.transact(window, cx, |this, window, cx| {
17658 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17659 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17660 Some(this.selection_replacement_ranges(range_utf16, cx))
17661 } else {
17662 this.marked_text_ranges(cx)
17663 };
17664
17665 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17666 let newest_selection_id = this.selections.newest_anchor().id;
17667 this.selections
17668 .all::<OffsetUtf16>(cx)
17669 .iter()
17670 .zip(ranges_to_replace.iter())
17671 .find_map(|(selection, range)| {
17672 if selection.id == newest_selection_id {
17673 Some(
17674 (range.start.0 as isize - selection.head().0 as isize)
17675 ..(range.end.0 as isize - selection.head().0 as isize),
17676 )
17677 } else {
17678 None
17679 }
17680 })
17681 });
17682
17683 cx.emit(EditorEvent::InputHandled {
17684 utf16_range_to_replace: range_to_replace,
17685 text: text.into(),
17686 });
17687
17688 if let Some(new_selected_ranges) = new_selected_ranges {
17689 this.change_selections(None, window, cx, |selections| {
17690 selections.select_ranges(new_selected_ranges)
17691 });
17692 this.backspace(&Default::default(), window, cx);
17693 }
17694
17695 this.handle_input(text, window, cx);
17696 });
17697
17698 if let Some(transaction) = self.ime_transaction {
17699 self.buffer.update(cx, |buffer, cx| {
17700 buffer.group_until_transaction(transaction, cx);
17701 });
17702 }
17703
17704 self.unmark_text(window, cx);
17705 }
17706
17707 fn replace_and_mark_text_in_range(
17708 &mut self,
17709 range_utf16: Option<Range<usize>>,
17710 text: &str,
17711 new_selected_range_utf16: Option<Range<usize>>,
17712 window: &mut Window,
17713 cx: &mut Context<Self>,
17714 ) {
17715 if !self.input_enabled {
17716 return;
17717 }
17718
17719 let transaction = self.transact(window, cx, |this, window, cx| {
17720 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17721 let snapshot = this.buffer.read(cx).read(cx);
17722 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17723 for marked_range in &mut marked_ranges {
17724 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17725 marked_range.start.0 += relative_range_utf16.start;
17726 marked_range.start =
17727 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17728 marked_range.end =
17729 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17730 }
17731 }
17732 Some(marked_ranges)
17733 } else if let Some(range_utf16) = range_utf16 {
17734 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17735 Some(this.selection_replacement_ranges(range_utf16, cx))
17736 } else {
17737 None
17738 };
17739
17740 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17741 let newest_selection_id = this.selections.newest_anchor().id;
17742 this.selections
17743 .all::<OffsetUtf16>(cx)
17744 .iter()
17745 .zip(ranges_to_replace.iter())
17746 .find_map(|(selection, range)| {
17747 if selection.id == newest_selection_id {
17748 Some(
17749 (range.start.0 as isize - selection.head().0 as isize)
17750 ..(range.end.0 as isize - selection.head().0 as isize),
17751 )
17752 } else {
17753 None
17754 }
17755 })
17756 });
17757
17758 cx.emit(EditorEvent::InputHandled {
17759 utf16_range_to_replace: range_to_replace,
17760 text: text.into(),
17761 });
17762
17763 if let Some(ranges) = ranges_to_replace {
17764 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17765 }
17766
17767 let marked_ranges = {
17768 let snapshot = this.buffer.read(cx).read(cx);
17769 this.selections
17770 .disjoint_anchors()
17771 .iter()
17772 .map(|selection| {
17773 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17774 })
17775 .collect::<Vec<_>>()
17776 };
17777
17778 if text.is_empty() {
17779 this.unmark_text(window, cx);
17780 } else {
17781 this.highlight_text::<InputComposition>(
17782 marked_ranges.clone(),
17783 HighlightStyle {
17784 underline: Some(UnderlineStyle {
17785 thickness: px(1.),
17786 color: None,
17787 wavy: false,
17788 }),
17789 ..Default::default()
17790 },
17791 cx,
17792 );
17793 }
17794
17795 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17796 let use_autoclose = this.use_autoclose;
17797 let use_auto_surround = this.use_auto_surround;
17798 this.set_use_autoclose(false);
17799 this.set_use_auto_surround(false);
17800 this.handle_input(text, window, cx);
17801 this.set_use_autoclose(use_autoclose);
17802 this.set_use_auto_surround(use_auto_surround);
17803
17804 if let Some(new_selected_range) = new_selected_range_utf16 {
17805 let snapshot = this.buffer.read(cx).read(cx);
17806 let new_selected_ranges = marked_ranges
17807 .into_iter()
17808 .map(|marked_range| {
17809 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17810 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17811 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17812 snapshot.clip_offset_utf16(new_start, Bias::Left)
17813 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17814 })
17815 .collect::<Vec<_>>();
17816
17817 drop(snapshot);
17818 this.change_selections(None, window, cx, |selections| {
17819 selections.select_ranges(new_selected_ranges)
17820 });
17821 }
17822 });
17823
17824 self.ime_transaction = self.ime_transaction.or(transaction);
17825 if let Some(transaction) = self.ime_transaction {
17826 self.buffer.update(cx, |buffer, cx| {
17827 buffer.group_until_transaction(transaction, cx);
17828 });
17829 }
17830
17831 if self.text_highlights::<InputComposition>(cx).is_none() {
17832 self.ime_transaction.take();
17833 }
17834 }
17835
17836 fn bounds_for_range(
17837 &mut self,
17838 range_utf16: Range<usize>,
17839 element_bounds: gpui::Bounds<Pixels>,
17840 window: &mut Window,
17841 cx: &mut Context<Self>,
17842 ) -> Option<gpui::Bounds<Pixels>> {
17843 let text_layout_details = self.text_layout_details(window);
17844 let gpui::Size {
17845 width: em_width,
17846 height: line_height,
17847 } = self.character_size(window);
17848
17849 let snapshot = self.snapshot(window, cx);
17850 let scroll_position = snapshot.scroll_position();
17851 let scroll_left = scroll_position.x * em_width;
17852
17853 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17854 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17855 + self.gutter_dimensions.width
17856 + self.gutter_dimensions.margin;
17857 let y = line_height * (start.row().as_f32() - scroll_position.y);
17858
17859 Some(Bounds {
17860 origin: element_bounds.origin + point(x, y),
17861 size: size(em_width, line_height),
17862 })
17863 }
17864
17865 fn character_index_for_point(
17866 &mut self,
17867 point: gpui::Point<Pixels>,
17868 _window: &mut Window,
17869 _cx: &mut Context<Self>,
17870 ) -> Option<usize> {
17871 let position_map = self.last_position_map.as_ref()?;
17872 if !position_map.text_hitbox.contains(&point) {
17873 return None;
17874 }
17875 let display_point = position_map.point_for_position(point).previous_valid;
17876 let anchor = position_map
17877 .snapshot
17878 .display_point_to_anchor(display_point, Bias::Left);
17879 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17880 Some(utf16_offset.0)
17881 }
17882}
17883
17884trait SelectionExt {
17885 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17886 fn spanned_rows(
17887 &self,
17888 include_end_if_at_line_start: bool,
17889 map: &DisplaySnapshot,
17890 ) -> Range<MultiBufferRow>;
17891}
17892
17893impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17894 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17895 let start = self
17896 .start
17897 .to_point(&map.buffer_snapshot)
17898 .to_display_point(map);
17899 let end = self
17900 .end
17901 .to_point(&map.buffer_snapshot)
17902 .to_display_point(map);
17903 if self.reversed {
17904 end..start
17905 } else {
17906 start..end
17907 }
17908 }
17909
17910 fn spanned_rows(
17911 &self,
17912 include_end_if_at_line_start: bool,
17913 map: &DisplaySnapshot,
17914 ) -> Range<MultiBufferRow> {
17915 let start = self.start.to_point(&map.buffer_snapshot);
17916 let mut end = self.end.to_point(&map.buffer_snapshot);
17917 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17918 end.row -= 1;
17919 }
17920
17921 let buffer_start = map.prev_line_boundary(start).0;
17922 let buffer_end = map.next_line_boundary(end).0;
17923 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17924 }
17925}
17926
17927impl<T: InvalidationRegion> InvalidationStack<T> {
17928 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17929 where
17930 S: Clone + ToOffset,
17931 {
17932 while let Some(region) = self.last() {
17933 let all_selections_inside_invalidation_ranges =
17934 if selections.len() == region.ranges().len() {
17935 selections
17936 .iter()
17937 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17938 .all(|(selection, invalidation_range)| {
17939 let head = selection.head().to_offset(buffer);
17940 invalidation_range.start <= head && invalidation_range.end >= head
17941 })
17942 } else {
17943 false
17944 };
17945
17946 if all_selections_inside_invalidation_ranges {
17947 break;
17948 } else {
17949 self.pop();
17950 }
17951 }
17952 }
17953}
17954
17955impl<T> Default for InvalidationStack<T> {
17956 fn default() -> Self {
17957 Self(Default::default())
17958 }
17959}
17960
17961impl<T> Deref for InvalidationStack<T> {
17962 type Target = Vec<T>;
17963
17964 fn deref(&self) -> &Self::Target {
17965 &self.0
17966 }
17967}
17968
17969impl<T> DerefMut for InvalidationStack<T> {
17970 fn deref_mut(&mut self) -> &mut Self::Target {
17971 &mut self.0
17972 }
17973}
17974
17975impl InvalidationRegion for SnippetState {
17976 fn ranges(&self) -> &[Range<Anchor>] {
17977 &self.ranges[self.active_index]
17978 }
17979}
17980
17981pub fn diagnostic_block_renderer(
17982 diagnostic: Diagnostic,
17983 max_message_rows: Option<u8>,
17984 allow_closing: bool,
17985) -> RenderBlock {
17986 let (text_without_backticks, code_ranges) =
17987 highlight_diagnostic_message(&diagnostic, max_message_rows);
17988
17989 Arc::new(move |cx: &mut BlockContext| {
17990 let group_id: SharedString = cx.block_id.to_string().into();
17991
17992 let mut text_style = cx.window.text_style().clone();
17993 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
17994 let theme_settings = ThemeSettings::get_global(cx);
17995 text_style.font_family = theme_settings.buffer_font.family.clone();
17996 text_style.font_style = theme_settings.buffer_font.style;
17997 text_style.font_features = theme_settings.buffer_font.features.clone();
17998 text_style.font_weight = theme_settings.buffer_font.weight;
17999
18000 let multi_line_diagnostic = diagnostic.message.contains('\n');
18001
18002 let buttons = |diagnostic: &Diagnostic| {
18003 if multi_line_diagnostic {
18004 v_flex()
18005 } else {
18006 h_flex()
18007 }
18008 .when(allow_closing, |div| {
18009 div.children(diagnostic.is_primary.then(|| {
18010 IconButton::new("close-block", IconName::XCircle)
18011 .icon_color(Color::Muted)
18012 .size(ButtonSize::Compact)
18013 .style(ButtonStyle::Transparent)
18014 .visible_on_hover(group_id.clone())
18015 .on_click(move |_click, window, cx| {
18016 window.dispatch_action(Box::new(Cancel), cx)
18017 })
18018 .tooltip(|window, cx| {
18019 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18020 })
18021 }))
18022 })
18023 .child(
18024 IconButton::new("copy-block", IconName::Copy)
18025 .icon_color(Color::Muted)
18026 .size(ButtonSize::Compact)
18027 .style(ButtonStyle::Transparent)
18028 .visible_on_hover(group_id.clone())
18029 .on_click({
18030 let message = diagnostic.message.clone();
18031 move |_click, _, cx| {
18032 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18033 }
18034 })
18035 .tooltip(Tooltip::text("Copy diagnostic message")),
18036 )
18037 };
18038
18039 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18040 AvailableSpace::min_size(),
18041 cx.window,
18042 cx.app,
18043 );
18044
18045 h_flex()
18046 .id(cx.block_id)
18047 .group(group_id.clone())
18048 .relative()
18049 .size_full()
18050 .block_mouse_down()
18051 .pl(cx.gutter_dimensions.width)
18052 .w(cx.max_width - cx.gutter_dimensions.full_width())
18053 .child(
18054 div()
18055 .flex()
18056 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18057 .flex_shrink(),
18058 )
18059 .child(buttons(&diagnostic))
18060 .child(div().flex().flex_shrink_0().child(
18061 StyledText::new(text_without_backticks.clone()).with_default_highlights(
18062 &text_style,
18063 code_ranges.iter().map(|range| {
18064 (
18065 range.clone(),
18066 HighlightStyle {
18067 font_weight: Some(FontWeight::BOLD),
18068 ..Default::default()
18069 },
18070 )
18071 }),
18072 ),
18073 ))
18074 .into_any_element()
18075 })
18076}
18077
18078fn inline_completion_edit_text(
18079 current_snapshot: &BufferSnapshot,
18080 edits: &[(Range<Anchor>, String)],
18081 edit_preview: &EditPreview,
18082 include_deletions: bool,
18083 cx: &App,
18084) -> HighlightedText {
18085 let edits = edits
18086 .iter()
18087 .map(|(anchor, text)| {
18088 (
18089 anchor.start.text_anchor..anchor.end.text_anchor,
18090 text.clone(),
18091 )
18092 })
18093 .collect::<Vec<_>>();
18094
18095 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18096}
18097
18098pub fn highlight_diagnostic_message(
18099 diagnostic: &Diagnostic,
18100 mut max_message_rows: Option<u8>,
18101) -> (SharedString, Vec<Range<usize>>) {
18102 let mut text_without_backticks = String::new();
18103 let mut code_ranges = Vec::new();
18104
18105 if let Some(source) = &diagnostic.source {
18106 text_without_backticks.push_str(source);
18107 code_ranges.push(0..source.len());
18108 text_without_backticks.push_str(": ");
18109 }
18110
18111 let mut prev_offset = 0;
18112 let mut in_code_block = false;
18113 let has_row_limit = max_message_rows.is_some();
18114 let mut newline_indices = diagnostic
18115 .message
18116 .match_indices('\n')
18117 .filter(|_| has_row_limit)
18118 .map(|(ix, _)| ix)
18119 .fuse()
18120 .peekable();
18121
18122 for (quote_ix, _) in diagnostic
18123 .message
18124 .match_indices('`')
18125 .chain([(diagnostic.message.len(), "")])
18126 {
18127 let mut first_newline_ix = None;
18128 let mut last_newline_ix = None;
18129 while let Some(newline_ix) = newline_indices.peek() {
18130 if *newline_ix < quote_ix {
18131 if first_newline_ix.is_none() {
18132 first_newline_ix = Some(*newline_ix);
18133 }
18134 last_newline_ix = Some(*newline_ix);
18135
18136 if let Some(rows_left) = &mut max_message_rows {
18137 if *rows_left == 0 {
18138 break;
18139 } else {
18140 *rows_left -= 1;
18141 }
18142 }
18143 let _ = newline_indices.next();
18144 } else {
18145 break;
18146 }
18147 }
18148 let prev_len = text_without_backticks.len();
18149 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18150 text_without_backticks.push_str(new_text);
18151 if in_code_block {
18152 code_ranges.push(prev_len..text_without_backticks.len());
18153 }
18154 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18155 in_code_block = !in_code_block;
18156 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18157 text_without_backticks.push_str("...");
18158 break;
18159 }
18160 }
18161
18162 (text_without_backticks.into(), code_ranges)
18163}
18164
18165fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18166 match severity {
18167 DiagnosticSeverity::ERROR => colors.error,
18168 DiagnosticSeverity::WARNING => colors.warning,
18169 DiagnosticSeverity::INFORMATION => colors.info,
18170 DiagnosticSeverity::HINT => colors.info,
18171 _ => colors.ignored,
18172 }
18173}
18174
18175pub fn styled_runs_for_code_label<'a>(
18176 label: &'a CodeLabel,
18177 syntax_theme: &'a theme::SyntaxTheme,
18178) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18179 let fade_out = HighlightStyle {
18180 fade_out: Some(0.35),
18181 ..Default::default()
18182 };
18183
18184 let mut prev_end = label.filter_range.end;
18185 label
18186 .runs
18187 .iter()
18188 .enumerate()
18189 .flat_map(move |(ix, (range, highlight_id))| {
18190 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18191 style
18192 } else {
18193 return Default::default();
18194 };
18195 let mut muted_style = style;
18196 muted_style.highlight(fade_out);
18197
18198 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18199 if range.start >= label.filter_range.end {
18200 if range.start > prev_end {
18201 runs.push((prev_end..range.start, fade_out));
18202 }
18203 runs.push((range.clone(), muted_style));
18204 } else if range.end <= label.filter_range.end {
18205 runs.push((range.clone(), style));
18206 } else {
18207 runs.push((range.start..label.filter_range.end, style));
18208 runs.push((label.filter_range.end..range.end, muted_style));
18209 }
18210 prev_end = cmp::max(prev_end, range.end);
18211
18212 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18213 runs.push((prev_end..label.text.len(), fade_out));
18214 }
18215
18216 runs
18217 })
18218}
18219
18220pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18221 let mut prev_index = 0;
18222 let mut prev_codepoint: Option<char> = None;
18223 text.char_indices()
18224 .chain([(text.len(), '\0')])
18225 .filter_map(move |(index, codepoint)| {
18226 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18227 let is_boundary = index == text.len()
18228 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18229 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18230 if is_boundary {
18231 let chunk = &text[prev_index..index];
18232 prev_index = index;
18233 Some(chunk)
18234 } else {
18235 None
18236 }
18237 })
18238}
18239
18240pub trait RangeToAnchorExt: Sized {
18241 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18242
18243 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18244 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18245 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18246 }
18247}
18248
18249impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18250 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18251 let start_offset = self.start.to_offset(snapshot);
18252 let end_offset = self.end.to_offset(snapshot);
18253 if start_offset == end_offset {
18254 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18255 } else {
18256 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18257 }
18258 }
18259}
18260
18261pub trait RowExt {
18262 fn as_f32(&self) -> f32;
18263
18264 fn next_row(&self) -> Self;
18265
18266 fn previous_row(&self) -> Self;
18267
18268 fn minus(&self, other: Self) -> u32;
18269}
18270
18271impl RowExt for DisplayRow {
18272 fn as_f32(&self) -> f32 {
18273 self.0 as f32
18274 }
18275
18276 fn next_row(&self) -> Self {
18277 Self(self.0 + 1)
18278 }
18279
18280 fn previous_row(&self) -> Self {
18281 Self(self.0.saturating_sub(1))
18282 }
18283
18284 fn minus(&self, other: Self) -> u32 {
18285 self.0 - other.0
18286 }
18287}
18288
18289impl RowExt for MultiBufferRow {
18290 fn as_f32(&self) -> f32 {
18291 self.0 as f32
18292 }
18293
18294 fn next_row(&self) -> Self {
18295 Self(self.0 + 1)
18296 }
18297
18298 fn previous_row(&self) -> Self {
18299 Self(self.0.saturating_sub(1))
18300 }
18301
18302 fn minus(&self, other: Self) -> u32 {
18303 self.0 - other.0
18304 }
18305}
18306
18307trait RowRangeExt {
18308 type Row;
18309
18310 fn len(&self) -> usize;
18311
18312 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18313}
18314
18315impl RowRangeExt for Range<MultiBufferRow> {
18316 type Row = MultiBufferRow;
18317
18318 fn len(&self) -> usize {
18319 (self.end.0 - self.start.0) as usize
18320 }
18321
18322 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18323 (self.start.0..self.end.0).map(MultiBufferRow)
18324 }
18325}
18326
18327impl RowRangeExt for Range<DisplayRow> {
18328 type Row = DisplayRow;
18329
18330 fn len(&self) -> usize {
18331 (self.end.0 - self.start.0) as usize
18332 }
18333
18334 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18335 (self.start.0..self.end.0).map(DisplayRow)
18336 }
18337}
18338
18339/// If select range has more than one line, we
18340/// just point the cursor to range.start.
18341fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18342 if range.start.row == range.end.row {
18343 range
18344 } else {
18345 range.start..range.start
18346 }
18347}
18348pub struct KillRing(ClipboardItem);
18349impl Global for KillRing {}
18350
18351const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18352
18353fn all_edits_insertions_or_deletions(
18354 edits: &Vec<(Range<Anchor>, String)>,
18355 snapshot: &MultiBufferSnapshot,
18356) -> bool {
18357 let mut all_insertions = true;
18358 let mut all_deletions = true;
18359
18360 for (range, new_text) in edits.iter() {
18361 let range_is_empty = range.to_offset(&snapshot).is_empty();
18362 let text_is_empty = new_text.is_empty();
18363
18364 if range_is_empty != text_is_empty {
18365 if range_is_empty {
18366 all_deletions = false;
18367 } else {
18368 all_insertions = false;
18369 }
18370 } else {
18371 return false;
18372 }
18373
18374 if !all_insertions && !all_deletions {
18375 return false;
18376 }
18377 }
18378 all_insertions || all_deletions
18379}
18380
18381struct MissingEditPredictionKeybindingTooltip;
18382
18383impl Render for MissingEditPredictionKeybindingTooltip {
18384 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18385 ui::tooltip_container(window, cx, |container, _, cx| {
18386 container
18387 .flex_shrink_0()
18388 .max_w_80()
18389 .min_h(rems_from_px(124.))
18390 .justify_between()
18391 .child(
18392 v_flex()
18393 .flex_1()
18394 .text_ui_sm(cx)
18395 .child(Label::new("Conflict with Accept Keybinding"))
18396 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18397 )
18398 .child(
18399 h_flex()
18400 .pb_1()
18401 .gap_1()
18402 .items_end()
18403 .w_full()
18404 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18405 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18406 }))
18407 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18408 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18409 })),
18410 )
18411 })
18412 }
18413}