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 jsx_tag_auto_close;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51pub(crate) use actions::*;
52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use buffer_diff::DiffHunkStatus;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{
72 future::{self, Shared},
73 FutureExt,
74};
75use fuzzy::StringMatchCandidate;
76
77use ::git::Restore;
78use code_context_menus::{
79 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
80 CompletionsMenu, ContextMenuOrigin,
81};
82use git::blame::GitBlame;
83use gpui::{
84 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
85 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
86 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
87 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
88 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
89 ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
90 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
91 WeakEntity, WeakFocusHandle, Window,
92};
93use highlight_matching_bracket::refresh_matching_bracket_highlights;
94use hover_popover::{hide_hover, HoverState};
95use indent_guides::ActiveIndentGuidesState;
96use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
97pub use inline_completion::Direction;
98use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
99pub use items::MAX_TAB_TITLE_LEN;
100use itertools::Itertools;
101use language::{
102 language_settings::{
103 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
104 WordsCompletionMode,
105 },
106 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
107 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
108 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
109 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
110};
111use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
112use linked_editing_ranges::refresh_linked_ranges;
113use mouse_context_menu::MouseContextMenu;
114use persistence::DB;
115pub use proposed_changes_editor::{
116 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
117};
118use smallvec::smallvec;
119use std::iter::Peekable;
120use task::{ResolvedTask, TaskTemplate, TaskVariables};
121
122use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
123pub use lsp::CompletionContext;
124use lsp::{
125 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
126 InsertTextFormat, LanguageServerId, LanguageServerName,
127};
128
129use language::BufferSnapshot;
130use movement::TextLayoutDetails;
131pub use multi_buffer::{
132 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
133 ToOffset, ToPoint,
134};
135use multi_buffer::{
136 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
137 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
138};
139use project::{
140 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
141 project_settings::{GitGutterSetting, ProjectSettings},
142 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
143 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
144 TaskSourceKind,
145};
146use rand::prelude::*;
147use rpc::{proto::*, ErrorExt};
148use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
149use selections_collection::{
150 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
151};
152use serde::{Deserialize, Serialize};
153use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
154use smallvec::SmallVec;
155use snippet::Snippet;
156use std::{
157 any::TypeId,
158 borrow::Cow,
159 cell::RefCell,
160 cmp::{self, Ordering, Reverse},
161 mem,
162 num::NonZeroU32,
163 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
164 path::{Path, PathBuf},
165 rc::Rc,
166 sync::Arc,
167 time::{Duration, Instant},
168};
169pub use sum_tree::Bias;
170use sum_tree::TreeMap;
171use text::{BufferId, OffsetUtf16, Rope};
172use theme::{
173 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
174 ThemeColors, ThemeSettings,
175};
176use ui::{
177 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
178 Tooltip,
179};
180use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
181use workspace::{
182 item::{ItemHandle, PreviewTabsSettings},
183 ItemId, RestoreOnStartupBehavior,
184};
185use workspace::{
186 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
187 WorkspaceSettings,
188};
189use workspace::{
190 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
191};
192use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
193
194use crate::hover_links::{find_url, find_url_from_range};
195use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
196
197pub const FILE_HEADER_HEIGHT: u32 = 2;
198pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
199pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
200const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
201const MAX_LINE_LEN: usize = 1024;
202const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
203const MAX_SELECTION_HISTORY_LEN: usize = 1024;
204pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
205#[doc(hidden)]
206pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
207
208pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
209pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
210pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
211
212pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
213pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
214
215const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
216 alt: true,
217 shift: true,
218 control: false,
219 platform: false,
220 function: false,
221};
222
223#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
224pub enum InlayId {
225 InlineCompletion(usize),
226 Hint(usize),
227}
228
229impl InlayId {
230 fn id(&self) -> usize {
231 match self {
232 Self::InlineCompletion(id) => *id,
233 Self::Hint(id) => *id,
234 }
235 }
236}
237
238enum DocumentHighlightRead {}
239enum DocumentHighlightWrite {}
240enum InputComposition {}
241enum SelectedTextHighlight {}
242
243#[derive(Debug, Copy, Clone, PartialEq, Eq)]
244pub enum Navigated {
245 Yes,
246 No,
247}
248
249impl Navigated {
250 pub fn from_bool(yes: bool) -> Navigated {
251 if yes {
252 Navigated::Yes
253 } else {
254 Navigated::No
255 }
256 }
257}
258
259#[derive(Debug, Clone, PartialEq, Eq)]
260enum DisplayDiffHunk {
261 Folded {
262 display_row: DisplayRow,
263 },
264 Unfolded {
265 is_created_file: bool,
266 diff_base_byte_range: Range<usize>,
267 display_row_range: Range<DisplayRow>,
268 multi_buffer_range: Range<Anchor>,
269 status: DiffHunkStatus,
270 },
271}
272
273pub fn init_settings(cx: &mut App) {
274 EditorSettings::register(cx);
275}
276
277pub fn init(cx: &mut App) {
278 init_settings(cx);
279
280 workspace::register_project_item::<Editor>(cx);
281 workspace::FollowableViewRegistry::register::<Editor>(cx);
282 workspace::register_serializable_item::<Editor>(cx);
283
284 cx.observe_new(
285 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
286 workspace.register_action(Editor::new_file);
287 workspace.register_action(Editor::new_file_vertical);
288 workspace.register_action(Editor::new_file_horizontal);
289 workspace.register_action(Editor::cancel_language_server_work);
290 },
291 )
292 .detach();
293
294 cx.on_action(move |_: &workspace::NewFile, cx| {
295 let app_state = workspace::AppState::global(cx);
296 if let Some(app_state) = app_state.upgrade() {
297 workspace::open_new(
298 Default::default(),
299 app_state,
300 cx,
301 |workspace, window, cx| {
302 Editor::new_file(workspace, &Default::default(), window, cx)
303 },
304 )
305 .detach();
306 }
307 });
308 cx.on_action(move |_: &workspace::NewWindow, cx| {
309 let app_state = workspace::AppState::global(cx);
310 if let Some(app_state) = app_state.upgrade() {
311 workspace::open_new(
312 Default::default(),
313 app_state,
314 cx,
315 |workspace, window, cx| {
316 cx.activate(true);
317 Editor::new_file(workspace, &Default::default(), window, cx)
318 },
319 )
320 .detach();
321 }
322 });
323}
324
325pub struct SearchWithinRange;
326
327trait InvalidationRegion {
328 fn ranges(&self) -> &[Range<Anchor>];
329}
330
331#[derive(Clone, Debug, PartialEq)]
332pub enum SelectPhase {
333 Begin {
334 position: DisplayPoint,
335 add: bool,
336 click_count: usize,
337 },
338 BeginColumnar {
339 position: DisplayPoint,
340 reset: bool,
341 goal_column: u32,
342 },
343 Extend {
344 position: DisplayPoint,
345 click_count: usize,
346 },
347 Update {
348 position: DisplayPoint,
349 goal_column: u32,
350 scroll_delta: gpui::Point<f32>,
351 },
352 End,
353}
354
355#[derive(Clone, Debug)]
356pub enum SelectMode {
357 Character,
358 Word(Range<Anchor>),
359 Line(Range<Anchor>),
360 All,
361}
362
363#[derive(Copy, Clone, PartialEq, Eq, Debug)]
364pub enum EditorMode {
365 SingleLine { auto_width: bool },
366 AutoHeight { max_lines: usize },
367 Full,
368}
369
370#[derive(Copy, Clone, Debug)]
371pub enum SoftWrap {
372 /// Prefer not to wrap at all.
373 ///
374 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
375 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
376 GitDiff,
377 /// Prefer a single line generally, unless an overly long line is encountered.
378 None,
379 /// Soft wrap lines that exceed the editor width.
380 EditorWidth,
381 /// Soft wrap lines at the preferred line length.
382 Column(u32),
383 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
384 Bounded(u32),
385}
386
387#[derive(Clone)]
388pub struct EditorStyle {
389 pub background: Hsla,
390 pub local_player: PlayerColor,
391 pub text: TextStyle,
392 pub scrollbar_width: Pixels,
393 pub syntax: Arc<SyntaxTheme>,
394 pub status: StatusColors,
395 pub inlay_hints_style: HighlightStyle,
396 pub inline_completion_styles: InlineCompletionStyles,
397 pub unnecessary_code_fade: f32,
398}
399
400impl Default for EditorStyle {
401 fn default() -> Self {
402 Self {
403 background: Hsla::default(),
404 local_player: PlayerColor::default(),
405 text: TextStyle::default(),
406 scrollbar_width: Pixels::default(),
407 syntax: Default::default(),
408 // HACK: Status colors don't have a real default.
409 // We should look into removing the status colors from the editor
410 // style and retrieve them directly from the theme.
411 status: StatusColors::dark(),
412 inlay_hints_style: HighlightStyle::default(),
413 inline_completion_styles: InlineCompletionStyles {
414 insertion: HighlightStyle::default(),
415 whitespace: HighlightStyle::default(),
416 },
417 unnecessary_code_fade: Default::default(),
418 }
419 }
420}
421
422pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
423 let show_background = language_settings::language_settings(None, None, cx)
424 .inlay_hints
425 .show_background;
426
427 HighlightStyle {
428 color: Some(cx.theme().status().hint),
429 background_color: show_background.then(|| cx.theme().status().hint_background),
430 ..HighlightStyle::default()
431 }
432}
433
434pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
435 InlineCompletionStyles {
436 insertion: HighlightStyle {
437 color: Some(cx.theme().status().predictive),
438 ..HighlightStyle::default()
439 },
440 whitespace: HighlightStyle {
441 background_color: Some(cx.theme().status().created_background),
442 ..HighlightStyle::default()
443 },
444 }
445}
446
447type CompletionId = usize;
448
449pub(crate) enum EditDisplayMode {
450 TabAccept,
451 DiffPopover,
452 Inline,
453}
454
455enum InlineCompletion {
456 Edit {
457 edits: Vec<(Range<Anchor>, String)>,
458 edit_preview: Option<EditPreview>,
459 display_mode: EditDisplayMode,
460 snapshot: BufferSnapshot,
461 },
462 Move {
463 target: Anchor,
464 snapshot: BufferSnapshot,
465 },
466}
467
468struct InlineCompletionState {
469 inlay_ids: Vec<InlayId>,
470 completion: InlineCompletion,
471 completion_id: Option<SharedString>,
472 invalidation_range: Range<Anchor>,
473}
474
475enum EditPredictionSettings {
476 Disabled,
477 Enabled {
478 show_in_menu: bool,
479 preview_requires_modifier: bool,
480 },
481}
482
483enum InlineCompletionHighlight {}
484
485#[derive(Debug, Clone)]
486struct InlineDiagnostic {
487 message: SharedString,
488 group_id: usize,
489 is_primary: bool,
490 start: Point,
491 severity: DiagnosticSeverity,
492}
493
494pub enum MenuInlineCompletionsPolicy {
495 Never,
496 ByProvider,
497}
498
499pub enum EditPredictionPreview {
500 /// Modifier is not pressed
501 Inactive { released_too_fast: bool },
502 /// Modifier pressed
503 Active {
504 since: Instant,
505 previous_scroll_position: Option<ScrollAnchor>,
506 },
507}
508
509impl EditPredictionPreview {
510 pub fn released_too_fast(&self) -> bool {
511 match self {
512 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
513 EditPredictionPreview::Active { .. } => false,
514 }
515 }
516
517 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
518 if let EditPredictionPreview::Active {
519 previous_scroll_position,
520 ..
521 } = self
522 {
523 *previous_scroll_position = scroll_position;
524 }
525 }
526}
527
528#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
529struct EditorActionId(usize);
530
531impl EditorActionId {
532 pub fn post_inc(&mut self) -> Self {
533 let answer = self.0;
534
535 *self = Self(answer + 1);
536
537 Self(answer)
538 }
539}
540
541// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
542// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
543
544type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
545type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
546
547#[derive(Default)]
548struct ScrollbarMarkerState {
549 scrollbar_size: Size<Pixels>,
550 dirty: bool,
551 markers: Arc<[PaintQuad]>,
552 pending_refresh: Option<Task<Result<()>>>,
553}
554
555impl ScrollbarMarkerState {
556 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
557 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
558 }
559}
560
561#[derive(Clone, Debug)]
562struct RunnableTasks {
563 templates: Vec<(TaskSourceKind, TaskTemplate)>,
564 offset: multi_buffer::Anchor,
565 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
566 column: u32,
567 // Values of all named captures, including those starting with '_'
568 extra_variables: HashMap<String, String>,
569 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
570 context_range: Range<BufferOffset>,
571}
572
573impl RunnableTasks {
574 fn resolve<'a>(
575 &'a self,
576 cx: &'a task::TaskContext,
577 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
578 self.templates.iter().filter_map(|(kind, template)| {
579 template
580 .resolve_task(&kind.to_id_base(), cx)
581 .map(|task| (kind.clone(), task))
582 })
583 }
584}
585
586#[derive(Clone)]
587struct ResolvedTasks {
588 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
589 position: Anchor,
590}
591#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
592struct BufferOffset(usize);
593
594// Addons allow storing per-editor state in other crates (e.g. Vim)
595pub trait Addon: 'static {
596 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
597
598 fn render_buffer_header_controls(
599 &self,
600 _: &ExcerptInfo,
601 _: &Window,
602 _: &App,
603 ) -> Option<AnyElement> {
604 None
605 }
606
607 fn to_any(&self) -> &dyn std::any::Any;
608}
609
610/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
611///
612/// See the [module level documentation](self) for more information.
613pub struct Editor {
614 focus_handle: FocusHandle,
615 last_focused_descendant: Option<WeakFocusHandle>,
616 /// The text buffer being edited
617 buffer: Entity<MultiBuffer>,
618 /// Map of how text in the buffer should be displayed.
619 /// Handles soft wraps, folds, fake inlay text insertions, etc.
620 pub display_map: Entity<DisplayMap>,
621 pub selections: SelectionsCollection,
622 pub scroll_manager: ScrollManager,
623 /// When inline assist editors are linked, they all render cursors because
624 /// typing enters text into each of them, even the ones that aren't focused.
625 pub(crate) show_cursor_when_unfocused: bool,
626 columnar_selection_tail: Option<Anchor>,
627 add_selections_state: Option<AddSelectionsState>,
628 select_next_state: Option<SelectNextState>,
629 select_prev_state: Option<SelectNextState>,
630 selection_history: SelectionHistory,
631 autoclose_regions: Vec<AutocloseRegion>,
632 snippet_stack: InvalidationStack<SnippetState>,
633 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
634 ime_transaction: Option<TransactionId>,
635 active_diagnostics: Option<ActiveDiagnosticGroup>,
636 show_inline_diagnostics: bool,
637 inline_diagnostics_update: Task<()>,
638 inline_diagnostics_enabled: bool,
639 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
640 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
641 hard_wrap: Option<usize>,
642
643 // TODO: make this a access method
644 pub project: Option<Entity<Project>>,
645 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
646 completion_provider: Option<Box<dyn CompletionProvider>>,
647 collaboration_hub: Option<Box<dyn CollaborationHub>>,
648 blink_manager: Entity<BlinkManager>,
649 show_cursor_names: bool,
650 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
651 pub show_local_selections: bool,
652 mode: EditorMode,
653 show_breadcrumbs: bool,
654 show_gutter: bool,
655 show_scrollbars: bool,
656 show_line_numbers: Option<bool>,
657 use_relative_line_numbers: Option<bool>,
658 show_git_diff_gutter: Option<bool>,
659 show_code_actions: Option<bool>,
660 show_runnables: Option<bool>,
661 show_wrap_guides: Option<bool>,
662 show_indent_guides: Option<bool>,
663 placeholder_text: Option<Arc<str>>,
664 highlight_order: usize,
665 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
666 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
667 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
668 scrollbar_marker_state: ScrollbarMarkerState,
669 active_indent_guides_state: ActiveIndentGuidesState,
670 nav_history: Option<ItemNavHistory>,
671 context_menu: RefCell<Option<CodeContextMenu>>,
672 mouse_context_menu: Option<MouseContextMenu>,
673 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
674 signature_help_state: SignatureHelpState,
675 auto_signature_help: Option<bool>,
676 find_all_references_task_sources: Vec<Anchor>,
677 next_completion_id: CompletionId,
678 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
679 code_actions_task: Option<Task<Result<()>>>,
680 selection_highlight_task: Option<Task<()>>,
681 document_highlights_task: Option<Task<()>>,
682 linked_editing_range_task: Option<Task<Option<()>>>,
683 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
684 pending_rename: Option<RenameState>,
685 searchable: bool,
686 cursor_shape: CursorShape,
687 current_line_highlight: Option<CurrentLineHighlight>,
688 collapse_matches: bool,
689 autoindent_mode: Option<AutoindentMode>,
690 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
691 input_enabled: bool,
692 use_modal_editing: bool,
693 read_only: bool,
694 leader_peer_id: Option<PeerId>,
695 remote_id: Option<ViewId>,
696 hover_state: HoverState,
697 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
698 gutter_hovered: bool,
699 hovered_link_state: Option<HoveredLinkState>,
700 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
701 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
702 active_inline_completion: Option<InlineCompletionState>,
703 /// Used to prevent flickering as the user types while the menu is open
704 stale_inline_completion_in_menu: Option<InlineCompletionState>,
705 edit_prediction_settings: EditPredictionSettings,
706 inline_completions_hidden_for_vim_mode: bool,
707 show_inline_completions_override: Option<bool>,
708 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
709 edit_prediction_preview: EditPredictionPreview,
710 edit_prediction_indent_conflict: bool,
711 edit_prediction_requires_modifier_in_indent_conflict: bool,
712 inlay_hint_cache: InlayHintCache,
713 next_inlay_id: usize,
714 _subscriptions: Vec<Subscription>,
715 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
716 gutter_dimensions: GutterDimensions,
717 style: Option<EditorStyle>,
718 text_style_refinement: Option<TextStyleRefinement>,
719 next_editor_action_id: EditorActionId,
720 editor_actions:
721 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
722 use_autoclose: bool,
723 use_auto_surround: bool,
724 auto_replace_emoji_shortcode: bool,
725 jsx_tag_auto_close_enabled_in_any_buffer: bool,
726 show_git_blame_gutter: bool,
727 show_git_blame_inline: bool,
728 show_git_blame_inline_delay_task: Option<Task<()>>,
729 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
730 git_blame_inline_enabled: bool,
731 serialize_dirty_buffers: bool,
732 show_selection_menu: Option<bool>,
733 blame: Option<Entity<GitBlame>>,
734 blame_subscription: Option<Subscription>,
735 custom_context_menu: Option<
736 Box<
737 dyn 'static
738 + Fn(
739 &mut Self,
740 DisplayPoint,
741 &mut Window,
742 &mut Context<Self>,
743 ) -> Option<Entity<ui::ContextMenu>>,
744 >,
745 >,
746 last_bounds: Option<Bounds<Pixels>>,
747 last_position_map: Option<Rc<PositionMap>>,
748 expect_bounds_change: Option<Bounds<Pixels>>,
749 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
750 tasks_update_task: Option<Task<()>>,
751 in_project_search: bool,
752 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
753 breadcrumb_header: Option<String>,
754 focused_block: Option<FocusedBlock>,
755 next_scroll_position: NextScrollCursorCenterTopBottom,
756 addons: HashMap<TypeId, Box<dyn Addon>>,
757 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
758 load_diff_task: Option<Shared<Task<()>>>,
759 selection_mark_mode: bool,
760 toggle_fold_multiple_buffers: Task<()>,
761 _scroll_cursor_center_top_bottom_task: Task<()>,
762 serialize_selections: Task<()>,
763}
764
765#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
766enum NextScrollCursorCenterTopBottom {
767 #[default]
768 Center,
769 Top,
770 Bottom,
771}
772
773impl NextScrollCursorCenterTopBottom {
774 fn next(&self) -> Self {
775 match self {
776 Self::Center => Self::Top,
777 Self::Top => Self::Bottom,
778 Self::Bottom => Self::Center,
779 }
780 }
781}
782
783#[derive(Clone)]
784pub struct EditorSnapshot {
785 pub mode: EditorMode,
786 show_gutter: bool,
787 show_line_numbers: Option<bool>,
788 show_git_diff_gutter: Option<bool>,
789 show_code_actions: Option<bool>,
790 show_runnables: Option<bool>,
791 git_blame_gutter_max_author_length: Option<usize>,
792 pub display_snapshot: DisplaySnapshot,
793 pub placeholder_text: Option<Arc<str>>,
794 is_focused: bool,
795 scroll_anchor: ScrollAnchor,
796 ongoing_scroll: OngoingScroll,
797 current_line_highlight: CurrentLineHighlight,
798 gutter_hovered: bool,
799}
800
801const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
802
803#[derive(Default, Debug, Clone, Copy)]
804pub struct GutterDimensions {
805 pub left_padding: Pixels,
806 pub right_padding: Pixels,
807 pub width: Pixels,
808 pub margin: Pixels,
809 pub git_blame_entries_width: Option<Pixels>,
810}
811
812impl GutterDimensions {
813 /// The full width of the space taken up by the gutter.
814 pub fn full_width(&self) -> Pixels {
815 self.margin + self.width
816 }
817
818 /// The width of the space reserved for the fold indicators,
819 /// use alongside 'justify_end' and `gutter_width` to
820 /// right align content with the line numbers
821 pub fn fold_area_width(&self) -> Pixels {
822 self.margin + self.right_padding
823 }
824}
825
826#[derive(Debug)]
827pub struct RemoteSelection {
828 pub replica_id: ReplicaId,
829 pub selection: Selection<Anchor>,
830 pub cursor_shape: CursorShape,
831 pub peer_id: PeerId,
832 pub line_mode: bool,
833 pub participant_index: Option<ParticipantIndex>,
834 pub user_name: Option<SharedString>,
835}
836
837#[derive(Clone, Debug)]
838struct SelectionHistoryEntry {
839 selections: Arc<[Selection<Anchor>]>,
840 select_next_state: Option<SelectNextState>,
841 select_prev_state: Option<SelectNextState>,
842 add_selections_state: Option<AddSelectionsState>,
843}
844
845enum SelectionHistoryMode {
846 Normal,
847 Undoing,
848 Redoing,
849}
850
851#[derive(Clone, PartialEq, Eq, Hash)]
852struct HoveredCursor {
853 replica_id: u16,
854 selection_id: usize,
855}
856
857impl Default for SelectionHistoryMode {
858 fn default() -> Self {
859 Self::Normal
860 }
861}
862
863#[derive(Default)]
864struct SelectionHistory {
865 #[allow(clippy::type_complexity)]
866 selections_by_transaction:
867 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
868 mode: SelectionHistoryMode,
869 undo_stack: VecDeque<SelectionHistoryEntry>,
870 redo_stack: VecDeque<SelectionHistoryEntry>,
871}
872
873impl SelectionHistory {
874 fn insert_transaction(
875 &mut self,
876 transaction_id: TransactionId,
877 selections: Arc<[Selection<Anchor>]>,
878 ) {
879 self.selections_by_transaction
880 .insert(transaction_id, (selections, None));
881 }
882
883 #[allow(clippy::type_complexity)]
884 fn transaction(
885 &self,
886 transaction_id: TransactionId,
887 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
888 self.selections_by_transaction.get(&transaction_id)
889 }
890
891 #[allow(clippy::type_complexity)]
892 fn transaction_mut(
893 &mut self,
894 transaction_id: TransactionId,
895 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
896 self.selections_by_transaction.get_mut(&transaction_id)
897 }
898
899 fn push(&mut self, entry: SelectionHistoryEntry) {
900 if !entry.selections.is_empty() {
901 match self.mode {
902 SelectionHistoryMode::Normal => {
903 self.push_undo(entry);
904 self.redo_stack.clear();
905 }
906 SelectionHistoryMode::Undoing => self.push_redo(entry),
907 SelectionHistoryMode::Redoing => self.push_undo(entry),
908 }
909 }
910 }
911
912 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
913 if self
914 .undo_stack
915 .back()
916 .map_or(true, |e| e.selections != entry.selections)
917 {
918 self.undo_stack.push_back(entry);
919 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
920 self.undo_stack.pop_front();
921 }
922 }
923 }
924
925 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
926 if self
927 .redo_stack
928 .back()
929 .map_or(true, |e| e.selections != entry.selections)
930 {
931 self.redo_stack.push_back(entry);
932 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
933 self.redo_stack.pop_front();
934 }
935 }
936 }
937}
938
939struct RowHighlight {
940 index: usize,
941 range: Range<Anchor>,
942 color: Hsla,
943 should_autoscroll: bool,
944}
945
946#[derive(Clone, Debug)]
947struct AddSelectionsState {
948 above: bool,
949 stack: Vec<usize>,
950}
951
952#[derive(Clone)]
953struct SelectNextState {
954 query: AhoCorasick,
955 wordwise: bool,
956 done: bool,
957}
958
959impl std::fmt::Debug for SelectNextState {
960 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
961 f.debug_struct(std::any::type_name::<Self>())
962 .field("wordwise", &self.wordwise)
963 .field("done", &self.done)
964 .finish()
965 }
966}
967
968#[derive(Debug)]
969struct AutocloseRegion {
970 selection_id: usize,
971 range: Range<Anchor>,
972 pair: BracketPair,
973}
974
975#[derive(Debug)]
976struct SnippetState {
977 ranges: Vec<Vec<Range<Anchor>>>,
978 active_index: usize,
979 choices: Vec<Option<Vec<String>>>,
980}
981
982#[doc(hidden)]
983pub struct RenameState {
984 pub range: Range<Anchor>,
985 pub old_name: Arc<str>,
986 pub editor: Entity<Editor>,
987 block_id: CustomBlockId,
988}
989
990struct InvalidationStack<T>(Vec<T>);
991
992struct RegisteredInlineCompletionProvider {
993 provider: Arc<dyn InlineCompletionProviderHandle>,
994 _subscription: Subscription,
995}
996
997#[derive(Debug, PartialEq, Eq)]
998struct ActiveDiagnosticGroup {
999 primary_range: Range<Anchor>,
1000 primary_message: String,
1001 group_id: usize,
1002 blocks: HashMap<CustomBlockId, Diagnostic>,
1003 is_valid: bool,
1004}
1005
1006#[derive(Serialize, Deserialize, Clone, Debug)]
1007pub struct ClipboardSelection {
1008 /// The number of bytes in this selection.
1009 pub len: usize,
1010 /// Whether this was a full-line selection.
1011 pub is_entire_line: bool,
1012 /// The indentation of the first line when this content was originally copied.
1013 pub first_line_indent: u32,
1014}
1015
1016#[derive(Debug)]
1017pub(crate) struct NavigationData {
1018 cursor_anchor: Anchor,
1019 cursor_position: Point,
1020 scroll_anchor: ScrollAnchor,
1021 scroll_top_row: u32,
1022}
1023
1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1025pub enum GotoDefinitionKind {
1026 Symbol,
1027 Declaration,
1028 Type,
1029 Implementation,
1030}
1031
1032#[derive(Debug, Clone)]
1033enum InlayHintRefreshReason {
1034 ModifiersChanged(bool),
1035 Toggle(bool),
1036 SettingsChange(InlayHintSettings),
1037 NewLinesShown,
1038 BufferEdited(HashSet<Arc<Language>>),
1039 RefreshRequested,
1040 ExcerptsRemoved(Vec<ExcerptId>),
1041}
1042
1043impl InlayHintRefreshReason {
1044 fn description(&self) -> &'static str {
1045 match self {
1046 Self::ModifiersChanged(_) => "modifiers changed",
1047 Self::Toggle(_) => "toggle",
1048 Self::SettingsChange(_) => "settings change",
1049 Self::NewLinesShown => "new lines shown",
1050 Self::BufferEdited(_) => "buffer edited",
1051 Self::RefreshRequested => "refresh requested",
1052 Self::ExcerptsRemoved(_) => "excerpts removed",
1053 }
1054 }
1055}
1056
1057pub enum FormatTarget {
1058 Buffers,
1059 Ranges(Vec<Range<MultiBufferPoint>>),
1060}
1061
1062pub(crate) struct FocusedBlock {
1063 id: BlockId,
1064 focus_handle: WeakFocusHandle,
1065}
1066
1067#[derive(Clone)]
1068enum JumpData {
1069 MultiBufferRow {
1070 row: MultiBufferRow,
1071 line_offset_from_top: u32,
1072 },
1073 MultiBufferPoint {
1074 excerpt_id: ExcerptId,
1075 position: Point,
1076 anchor: text::Anchor,
1077 line_offset_from_top: u32,
1078 },
1079}
1080
1081pub enum MultibufferSelectionMode {
1082 First,
1083 All,
1084}
1085
1086impl Editor {
1087 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1088 let buffer = cx.new(|cx| Buffer::local("", cx));
1089 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1090 Self::new(
1091 EditorMode::SingleLine { auto_width: false },
1092 buffer,
1093 None,
1094 window,
1095 cx,
1096 )
1097 }
1098
1099 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1100 let buffer = cx.new(|cx| Buffer::local("", cx));
1101 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1102 Self::new(EditorMode::Full, buffer, None, window, cx)
1103 }
1104
1105 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1106 let buffer = cx.new(|cx| Buffer::local("", cx));
1107 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1108 Self::new(
1109 EditorMode::SingleLine { auto_width: true },
1110 buffer,
1111 None,
1112 window,
1113 cx,
1114 )
1115 }
1116
1117 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1118 let buffer = cx.new(|cx| Buffer::local("", cx));
1119 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1120 Self::new(
1121 EditorMode::AutoHeight { max_lines },
1122 buffer,
1123 None,
1124 window,
1125 cx,
1126 )
1127 }
1128
1129 pub fn for_buffer(
1130 buffer: Entity<Buffer>,
1131 project: Option<Entity<Project>>,
1132 window: &mut Window,
1133 cx: &mut Context<Self>,
1134 ) -> Self {
1135 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1136 Self::new(EditorMode::Full, buffer, project, window, cx)
1137 }
1138
1139 pub fn for_multibuffer(
1140 buffer: Entity<MultiBuffer>,
1141 project: Option<Entity<Project>>,
1142 window: &mut Window,
1143 cx: &mut Context<Self>,
1144 ) -> Self {
1145 Self::new(EditorMode::Full, buffer, project, window, cx)
1146 }
1147
1148 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1149 let mut clone = Self::new(
1150 self.mode,
1151 self.buffer.clone(),
1152 self.project.clone(),
1153 window,
1154 cx,
1155 );
1156 self.display_map.update(cx, |display_map, cx| {
1157 let snapshot = display_map.snapshot(cx);
1158 clone.display_map.update(cx, |display_map, cx| {
1159 display_map.set_state(&snapshot, cx);
1160 });
1161 });
1162 clone.selections.clone_state(&self.selections);
1163 clone.scroll_manager.clone_state(&self.scroll_manager);
1164 clone.searchable = self.searchable;
1165 clone
1166 }
1167
1168 pub fn new(
1169 mode: EditorMode,
1170 buffer: Entity<MultiBuffer>,
1171 project: Option<Entity<Project>>,
1172 window: &mut Window,
1173 cx: &mut Context<Self>,
1174 ) -> Self {
1175 let style = window.text_style();
1176 let font_size = style.font_size.to_pixels(window.rem_size());
1177 let editor = cx.entity().downgrade();
1178 let fold_placeholder = FoldPlaceholder {
1179 constrain_width: true,
1180 render: Arc::new(move |fold_id, fold_range, cx| {
1181 let editor = editor.clone();
1182 div()
1183 .id(fold_id)
1184 .bg(cx.theme().colors().ghost_element_background)
1185 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1186 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1187 .rounded_xs()
1188 .size_full()
1189 .cursor_pointer()
1190 .child("⋯")
1191 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1192 .on_click(move |_, _window, cx| {
1193 editor
1194 .update(cx, |editor, cx| {
1195 editor.unfold_ranges(
1196 &[fold_range.start..fold_range.end],
1197 true,
1198 false,
1199 cx,
1200 );
1201 cx.stop_propagation();
1202 })
1203 .ok();
1204 })
1205 .into_any()
1206 }),
1207 merge_adjacent: true,
1208 ..Default::default()
1209 };
1210 let display_map = cx.new(|cx| {
1211 DisplayMap::new(
1212 buffer.clone(),
1213 style.font(),
1214 font_size,
1215 None,
1216 FILE_HEADER_HEIGHT,
1217 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1218 fold_placeholder,
1219 cx,
1220 )
1221 });
1222
1223 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1224
1225 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1226
1227 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1228 .then(|| language_settings::SoftWrap::None);
1229
1230 let mut project_subscriptions = Vec::new();
1231 if mode == EditorMode::Full {
1232 if let Some(project) = project.as_ref() {
1233 project_subscriptions.push(cx.subscribe_in(
1234 project,
1235 window,
1236 |editor, _, event, window, cx| {
1237 if let project::Event::RefreshInlayHints = event {
1238 editor
1239 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1240 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1241 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1242 let focus_handle = editor.focus_handle(cx);
1243 if focus_handle.is_focused(window) {
1244 let snapshot = buffer.read(cx).snapshot();
1245 for (range, snippet) in snippet_edits {
1246 let editor_range =
1247 language::range_from_lsp(*range).to_offset(&snapshot);
1248 editor
1249 .insert_snippet(
1250 &[editor_range],
1251 snippet.clone(),
1252 window,
1253 cx,
1254 )
1255 .ok();
1256 }
1257 }
1258 }
1259 }
1260 },
1261 ));
1262 if let Some(task_inventory) = project
1263 .read(cx)
1264 .task_store()
1265 .read(cx)
1266 .task_inventory()
1267 .cloned()
1268 {
1269 project_subscriptions.push(cx.observe_in(
1270 &task_inventory,
1271 window,
1272 |editor, _, window, cx| {
1273 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1274 },
1275 ));
1276 }
1277 }
1278 }
1279
1280 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1281
1282 let inlay_hint_settings =
1283 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1284 let focus_handle = cx.focus_handle();
1285 cx.on_focus(&focus_handle, window, Self::handle_focus)
1286 .detach();
1287 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1288 .detach();
1289 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1290 .detach();
1291 cx.on_blur(&focus_handle, window, Self::handle_blur)
1292 .detach();
1293
1294 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1295 Some(false)
1296 } else {
1297 None
1298 };
1299
1300 let mut code_action_providers = Vec::new();
1301 let mut load_uncommitted_diff = None;
1302 if let Some(project) = project.clone() {
1303 load_uncommitted_diff = Some(
1304 get_uncommitted_diff_for_buffer(
1305 &project,
1306 buffer.read(cx).all_buffers(),
1307 buffer.clone(),
1308 cx,
1309 )
1310 .shared(),
1311 );
1312 code_action_providers.push(Rc::new(project) as Rc<_>);
1313 }
1314
1315 let mut this = Self {
1316 focus_handle,
1317 show_cursor_when_unfocused: false,
1318 last_focused_descendant: None,
1319 buffer: buffer.clone(),
1320 display_map: display_map.clone(),
1321 selections,
1322 scroll_manager: ScrollManager::new(cx),
1323 columnar_selection_tail: None,
1324 add_selections_state: None,
1325 select_next_state: None,
1326 select_prev_state: None,
1327 selection_history: Default::default(),
1328 autoclose_regions: Default::default(),
1329 snippet_stack: Default::default(),
1330 select_larger_syntax_node_stack: Vec::new(),
1331 ime_transaction: Default::default(),
1332 active_diagnostics: None,
1333 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1334 inline_diagnostics_update: Task::ready(()),
1335 inline_diagnostics: Vec::new(),
1336 soft_wrap_mode_override,
1337 hard_wrap: None,
1338 completion_provider: project.clone().map(|project| Box::new(project) as _),
1339 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1340 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1341 project,
1342 blink_manager: blink_manager.clone(),
1343 show_local_selections: true,
1344 show_scrollbars: true,
1345 mode,
1346 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1347 show_gutter: mode == EditorMode::Full,
1348 show_line_numbers: None,
1349 use_relative_line_numbers: None,
1350 show_git_diff_gutter: None,
1351 show_code_actions: None,
1352 show_runnables: None,
1353 show_wrap_guides: None,
1354 show_indent_guides,
1355 placeholder_text: None,
1356 highlight_order: 0,
1357 highlighted_rows: HashMap::default(),
1358 background_highlights: Default::default(),
1359 gutter_highlights: TreeMap::default(),
1360 scrollbar_marker_state: ScrollbarMarkerState::default(),
1361 active_indent_guides_state: ActiveIndentGuidesState::default(),
1362 nav_history: None,
1363 context_menu: RefCell::new(None),
1364 mouse_context_menu: None,
1365 completion_tasks: Default::default(),
1366 signature_help_state: SignatureHelpState::default(),
1367 auto_signature_help: None,
1368 find_all_references_task_sources: Vec::new(),
1369 next_completion_id: 0,
1370 next_inlay_id: 0,
1371 code_action_providers,
1372 available_code_actions: Default::default(),
1373 code_actions_task: Default::default(),
1374 selection_highlight_task: Default::default(),
1375 document_highlights_task: Default::default(),
1376 linked_editing_range_task: Default::default(),
1377 pending_rename: Default::default(),
1378 searchable: true,
1379 cursor_shape: EditorSettings::get_global(cx)
1380 .cursor_shape
1381 .unwrap_or_default(),
1382 current_line_highlight: None,
1383 autoindent_mode: Some(AutoindentMode::EachLine),
1384 collapse_matches: false,
1385 workspace: None,
1386 input_enabled: true,
1387 use_modal_editing: mode == EditorMode::Full,
1388 read_only: false,
1389 use_autoclose: true,
1390 use_auto_surround: true,
1391 auto_replace_emoji_shortcode: false,
1392 jsx_tag_auto_close_enabled_in_any_buffer: false,
1393 leader_peer_id: None,
1394 remote_id: None,
1395 hover_state: Default::default(),
1396 pending_mouse_down: None,
1397 hovered_link_state: Default::default(),
1398 edit_prediction_provider: None,
1399 active_inline_completion: None,
1400 stale_inline_completion_in_menu: None,
1401 edit_prediction_preview: EditPredictionPreview::Inactive {
1402 released_too_fast: false,
1403 },
1404 inline_diagnostics_enabled: mode == EditorMode::Full,
1405 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1406
1407 gutter_hovered: false,
1408 pixel_position_of_newest_cursor: None,
1409 last_bounds: None,
1410 last_position_map: None,
1411 expect_bounds_change: None,
1412 gutter_dimensions: GutterDimensions::default(),
1413 style: None,
1414 show_cursor_names: false,
1415 hovered_cursors: Default::default(),
1416 next_editor_action_id: EditorActionId::default(),
1417 editor_actions: Rc::default(),
1418 inline_completions_hidden_for_vim_mode: false,
1419 show_inline_completions_override: None,
1420 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1421 edit_prediction_settings: EditPredictionSettings::Disabled,
1422 edit_prediction_indent_conflict: false,
1423 edit_prediction_requires_modifier_in_indent_conflict: true,
1424 custom_context_menu: None,
1425 show_git_blame_gutter: false,
1426 show_git_blame_inline: false,
1427 show_selection_menu: None,
1428 show_git_blame_inline_delay_task: None,
1429 git_blame_inline_tooltip: None,
1430 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1431 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1432 .session
1433 .restore_unsaved_buffers,
1434 blame: None,
1435 blame_subscription: None,
1436 tasks: Default::default(),
1437 _subscriptions: vec![
1438 cx.observe(&buffer, Self::on_buffer_changed),
1439 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1440 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1441 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1442 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1443 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1444 cx.observe_window_activation(window, |editor, window, cx| {
1445 let active = window.is_window_active();
1446 editor.blink_manager.update(cx, |blink_manager, cx| {
1447 if active {
1448 blink_manager.enable(cx);
1449 } else {
1450 blink_manager.disable(cx);
1451 }
1452 });
1453 }),
1454 ],
1455 tasks_update_task: None,
1456 linked_edit_ranges: Default::default(),
1457 in_project_search: false,
1458 previous_search_ranges: None,
1459 breadcrumb_header: None,
1460 focused_block: None,
1461 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1462 addons: HashMap::default(),
1463 registered_buffers: HashMap::default(),
1464 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1465 selection_mark_mode: false,
1466 toggle_fold_multiple_buffers: Task::ready(()),
1467 serialize_selections: Task::ready(()),
1468 text_style_refinement: None,
1469 load_diff_task: load_uncommitted_diff,
1470 };
1471 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1472 this._subscriptions.extend(project_subscriptions);
1473
1474 this.end_selection(window, cx);
1475 this.scroll_manager.show_scrollbar(window, cx);
1476 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1477
1478 if mode == EditorMode::Full {
1479 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1480 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1481
1482 if this.git_blame_inline_enabled {
1483 this.git_blame_inline_enabled = true;
1484 this.start_git_blame_inline(false, window, cx);
1485 }
1486
1487 if let Some(buffer) = buffer.read(cx).as_singleton() {
1488 if let Some(project) = this.project.as_ref() {
1489 let handle = project.update(cx, |project, cx| {
1490 project.register_buffer_with_language_servers(&buffer, cx)
1491 });
1492 this.registered_buffers
1493 .insert(buffer.read(cx).remote_id(), handle);
1494 }
1495 }
1496 }
1497
1498 this.report_editor_event("Editor Opened", None, cx);
1499 this
1500 }
1501
1502 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1503 self.mouse_context_menu
1504 .as_ref()
1505 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1506 }
1507
1508 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1509 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1510 }
1511
1512 fn key_context_internal(
1513 &self,
1514 has_active_edit_prediction: bool,
1515 window: &Window,
1516 cx: &App,
1517 ) -> KeyContext {
1518 let mut key_context = KeyContext::new_with_defaults();
1519 key_context.add("Editor");
1520 let mode = match self.mode {
1521 EditorMode::SingleLine { .. } => "single_line",
1522 EditorMode::AutoHeight { .. } => "auto_height",
1523 EditorMode::Full => "full",
1524 };
1525
1526 if EditorSettings::jupyter_enabled(cx) {
1527 key_context.add("jupyter");
1528 }
1529
1530 key_context.set("mode", mode);
1531 if self.pending_rename.is_some() {
1532 key_context.add("renaming");
1533 }
1534
1535 match self.context_menu.borrow().as_ref() {
1536 Some(CodeContextMenu::Completions(_)) => {
1537 key_context.add("menu");
1538 key_context.add("showing_completions");
1539 }
1540 Some(CodeContextMenu::CodeActions(_)) => {
1541 key_context.add("menu");
1542 key_context.add("showing_code_actions")
1543 }
1544 None => {}
1545 }
1546
1547 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1548 if !self.focus_handle(cx).contains_focused(window, cx)
1549 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1550 {
1551 for addon in self.addons.values() {
1552 addon.extend_key_context(&mut key_context, cx)
1553 }
1554 }
1555
1556 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1557 if let Some(extension) = singleton_buffer
1558 .read(cx)
1559 .file()
1560 .and_then(|file| file.path().extension()?.to_str())
1561 {
1562 key_context.set("extension", extension.to_string());
1563 }
1564 } else {
1565 key_context.add("multibuffer");
1566 }
1567
1568 if has_active_edit_prediction {
1569 if self.edit_prediction_in_conflict() {
1570 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1571 } else {
1572 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1573 key_context.add("copilot_suggestion");
1574 }
1575 }
1576
1577 if self.selection_mark_mode {
1578 key_context.add("selection_mode");
1579 }
1580
1581 key_context
1582 }
1583
1584 pub fn edit_prediction_in_conflict(&self) -> bool {
1585 if !self.show_edit_predictions_in_menu() {
1586 return false;
1587 }
1588
1589 let showing_completions = self
1590 .context_menu
1591 .borrow()
1592 .as_ref()
1593 .map_or(false, |context| {
1594 matches!(context, CodeContextMenu::Completions(_))
1595 });
1596
1597 showing_completions
1598 || self.edit_prediction_requires_modifier()
1599 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1600 // bindings to insert tab characters.
1601 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1602 }
1603
1604 pub fn accept_edit_prediction_keybind(
1605 &self,
1606 window: &Window,
1607 cx: &App,
1608 ) -> AcceptEditPredictionBinding {
1609 let key_context = self.key_context_internal(true, window, cx);
1610 let in_conflict = self.edit_prediction_in_conflict();
1611
1612 AcceptEditPredictionBinding(
1613 window
1614 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1615 .into_iter()
1616 .filter(|binding| {
1617 !in_conflict
1618 || binding
1619 .keystrokes()
1620 .first()
1621 .map_or(false, |keystroke| keystroke.modifiers.modified())
1622 })
1623 .rev()
1624 .min_by_key(|binding| {
1625 binding
1626 .keystrokes()
1627 .first()
1628 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1629 }),
1630 )
1631 }
1632
1633 pub fn new_file(
1634 workspace: &mut Workspace,
1635 _: &workspace::NewFile,
1636 window: &mut Window,
1637 cx: &mut Context<Workspace>,
1638 ) {
1639 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1640 "Failed to create buffer",
1641 window,
1642 cx,
1643 |e, _, _| match e.error_code() {
1644 ErrorCode::RemoteUpgradeRequired => Some(format!(
1645 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1646 e.error_tag("required").unwrap_or("the latest version")
1647 )),
1648 _ => None,
1649 },
1650 );
1651 }
1652
1653 pub fn new_in_workspace(
1654 workspace: &mut Workspace,
1655 window: &mut Window,
1656 cx: &mut Context<Workspace>,
1657 ) -> Task<Result<Entity<Editor>>> {
1658 let project = workspace.project().clone();
1659 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1660
1661 cx.spawn_in(window, |workspace, mut cx| async move {
1662 let buffer = create.await?;
1663 workspace.update_in(&mut cx, |workspace, window, cx| {
1664 let editor =
1665 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1666 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1667 editor
1668 })
1669 })
1670 }
1671
1672 fn new_file_vertical(
1673 workspace: &mut Workspace,
1674 _: &workspace::NewFileSplitVertical,
1675 window: &mut Window,
1676 cx: &mut Context<Workspace>,
1677 ) {
1678 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1679 }
1680
1681 fn new_file_horizontal(
1682 workspace: &mut Workspace,
1683 _: &workspace::NewFileSplitHorizontal,
1684 window: &mut Window,
1685 cx: &mut Context<Workspace>,
1686 ) {
1687 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1688 }
1689
1690 fn new_file_in_direction(
1691 workspace: &mut Workspace,
1692 direction: SplitDirection,
1693 window: &mut Window,
1694 cx: &mut Context<Workspace>,
1695 ) {
1696 let project = workspace.project().clone();
1697 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1698
1699 cx.spawn_in(window, |workspace, mut cx| async move {
1700 let buffer = create.await?;
1701 workspace.update_in(&mut cx, move |workspace, window, cx| {
1702 workspace.split_item(
1703 direction,
1704 Box::new(
1705 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1706 ),
1707 window,
1708 cx,
1709 )
1710 })?;
1711 anyhow::Ok(())
1712 })
1713 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1714 match e.error_code() {
1715 ErrorCode::RemoteUpgradeRequired => Some(format!(
1716 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1717 e.error_tag("required").unwrap_or("the latest version")
1718 )),
1719 _ => None,
1720 }
1721 });
1722 }
1723
1724 pub fn leader_peer_id(&self) -> Option<PeerId> {
1725 self.leader_peer_id
1726 }
1727
1728 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1729 &self.buffer
1730 }
1731
1732 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1733 self.workspace.as_ref()?.0.upgrade()
1734 }
1735
1736 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1737 self.buffer().read(cx).title(cx)
1738 }
1739
1740 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1741 let git_blame_gutter_max_author_length = self
1742 .render_git_blame_gutter(cx)
1743 .then(|| {
1744 if let Some(blame) = self.blame.as_ref() {
1745 let max_author_length =
1746 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1747 Some(max_author_length)
1748 } else {
1749 None
1750 }
1751 })
1752 .flatten();
1753
1754 EditorSnapshot {
1755 mode: self.mode,
1756 show_gutter: self.show_gutter,
1757 show_line_numbers: self.show_line_numbers,
1758 show_git_diff_gutter: self.show_git_diff_gutter,
1759 show_code_actions: self.show_code_actions,
1760 show_runnables: self.show_runnables,
1761 git_blame_gutter_max_author_length,
1762 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1763 scroll_anchor: self.scroll_manager.anchor(),
1764 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1765 placeholder_text: self.placeholder_text.clone(),
1766 is_focused: self.focus_handle.is_focused(window),
1767 current_line_highlight: self
1768 .current_line_highlight
1769 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1770 gutter_hovered: self.gutter_hovered,
1771 }
1772 }
1773
1774 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1775 self.buffer.read(cx).language_at(point, cx)
1776 }
1777
1778 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1779 self.buffer.read(cx).read(cx).file_at(point).cloned()
1780 }
1781
1782 pub fn active_excerpt(
1783 &self,
1784 cx: &App,
1785 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1786 self.buffer
1787 .read(cx)
1788 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1789 }
1790
1791 pub fn mode(&self) -> EditorMode {
1792 self.mode
1793 }
1794
1795 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1796 self.collaboration_hub.as_deref()
1797 }
1798
1799 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1800 self.collaboration_hub = Some(hub);
1801 }
1802
1803 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1804 self.in_project_search = in_project_search;
1805 }
1806
1807 pub fn set_custom_context_menu(
1808 &mut self,
1809 f: impl 'static
1810 + Fn(
1811 &mut Self,
1812 DisplayPoint,
1813 &mut Window,
1814 &mut Context<Self>,
1815 ) -> Option<Entity<ui::ContextMenu>>,
1816 ) {
1817 self.custom_context_menu = Some(Box::new(f))
1818 }
1819
1820 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1821 self.completion_provider = provider;
1822 }
1823
1824 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1825 self.semantics_provider.clone()
1826 }
1827
1828 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1829 self.semantics_provider = provider;
1830 }
1831
1832 pub fn set_edit_prediction_provider<T>(
1833 &mut self,
1834 provider: Option<Entity<T>>,
1835 window: &mut Window,
1836 cx: &mut Context<Self>,
1837 ) where
1838 T: EditPredictionProvider,
1839 {
1840 self.edit_prediction_provider =
1841 provider.map(|provider| RegisteredInlineCompletionProvider {
1842 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1843 if this.focus_handle.is_focused(window) {
1844 this.update_visible_inline_completion(window, cx);
1845 }
1846 }),
1847 provider: Arc::new(provider),
1848 });
1849 self.update_edit_prediction_settings(cx);
1850 self.refresh_inline_completion(false, false, window, cx);
1851 }
1852
1853 pub fn placeholder_text(&self) -> Option<&str> {
1854 self.placeholder_text.as_deref()
1855 }
1856
1857 pub fn set_placeholder_text(
1858 &mut self,
1859 placeholder_text: impl Into<Arc<str>>,
1860 cx: &mut Context<Self>,
1861 ) {
1862 let placeholder_text = Some(placeholder_text.into());
1863 if self.placeholder_text != placeholder_text {
1864 self.placeholder_text = placeholder_text;
1865 cx.notify();
1866 }
1867 }
1868
1869 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1870 self.cursor_shape = cursor_shape;
1871
1872 // Disrupt blink for immediate user feedback that the cursor shape has changed
1873 self.blink_manager.update(cx, BlinkManager::show_cursor);
1874
1875 cx.notify();
1876 }
1877
1878 pub fn set_current_line_highlight(
1879 &mut self,
1880 current_line_highlight: Option<CurrentLineHighlight>,
1881 ) {
1882 self.current_line_highlight = current_line_highlight;
1883 }
1884
1885 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1886 self.collapse_matches = collapse_matches;
1887 }
1888
1889 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1890 let buffers = self.buffer.read(cx).all_buffers();
1891 let Some(project) = self.project.as_ref() else {
1892 return;
1893 };
1894 project.update(cx, |project, cx| {
1895 for buffer in buffers {
1896 self.registered_buffers
1897 .entry(buffer.read(cx).remote_id())
1898 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1899 }
1900 })
1901 }
1902
1903 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1904 if self.collapse_matches {
1905 return range.start..range.start;
1906 }
1907 range.clone()
1908 }
1909
1910 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1911 if self.display_map.read(cx).clip_at_line_ends != clip {
1912 self.display_map
1913 .update(cx, |map, _| map.clip_at_line_ends = clip);
1914 }
1915 }
1916
1917 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1918 self.input_enabled = input_enabled;
1919 }
1920
1921 pub fn set_inline_completions_hidden_for_vim_mode(
1922 &mut self,
1923 hidden: bool,
1924 window: &mut Window,
1925 cx: &mut Context<Self>,
1926 ) {
1927 if hidden != self.inline_completions_hidden_for_vim_mode {
1928 self.inline_completions_hidden_for_vim_mode = hidden;
1929 if hidden {
1930 self.update_visible_inline_completion(window, cx);
1931 } else {
1932 self.refresh_inline_completion(true, false, window, cx);
1933 }
1934 }
1935 }
1936
1937 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1938 self.menu_inline_completions_policy = value;
1939 }
1940
1941 pub fn set_autoindent(&mut self, autoindent: bool) {
1942 if autoindent {
1943 self.autoindent_mode = Some(AutoindentMode::EachLine);
1944 } else {
1945 self.autoindent_mode = None;
1946 }
1947 }
1948
1949 pub fn read_only(&self, cx: &App) -> bool {
1950 self.read_only || self.buffer.read(cx).read_only()
1951 }
1952
1953 pub fn set_read_only(&mut self, read_only: bool) {
1954 self.read_only = read_only;
1955 }
1956
1957 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1958 self.use_autoclose = autoclose;
1959 }
1960
1961 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1962 self.use_auto_surround = auto_surround;
1963 }
1964
1965 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1966 self.auto_replace_emoji_shortcode = auto_replace;
1967 }
1968
1969 pub fn toggle_edit_predictions(
1970 &mut self,
1971 _: &ToggleEditPrediction,
1972 window: &mut Window,
1973 cx: &mut Context<Self>,
1974 ) {
1975 if self.show_inline_completions_override.is_some() {
1976 self.set_show_edit_predictions(None, window, cx);
1977 } else {
1978 let show_edit_predictions = !self.edit_predictions_enabled();
1979 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1980 }
1981 }
1982
1983 pub fn set_show_edit_predictions(
1984 &mut self,
1985 show_edit_predictions: Option<bool>,
1986 window: &mut Window,
1987 cx: &mut Context<Self>,
1988 ) {
1989 self.show_inline_completions_override = show_edit_predictions;
1990 self.update_edit_prediction_settings(cx);
1991
1992 if let Some(false) = show_edit_predictions {
1993 self.discard_inline_completion(false, cx);
1994 } else {
1995 self.refresh_inline_completion(false, true, window, cx);
1996 }
1997 }
1998
1999 fn inline_completions_disabled_in_scope(
2000 &self,
2001 buffer: &Entity<Buffer>,
2002 buffer_position: language::Anchor,
2003 cx: &App,
2004 ) -> bool {
2005 let snapshot = buffer.read(cx).snapshot();
2006 let settings = snapshot.settings_at(buffer_position, cx);
2007
2008 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2009 return false;
2010 };
2011
2012 scope.override_name().map_or(false, |scope_name| {
2013 settings
2014 .edit_predictions_disabled_in
2015 .iter()
2016 .any(|s| s == scope_name)
2017 })
2018 }
2019
2020 pub fn set_use_modal_editing(&mut self, to: bool) {
2021 self.use_modal_editing = to;
2022 }
2023
2024 pub fn use_modal_editing(&self) -> bool {
2025 self.use_modal_editing
2026 }
2027
2028 fn selections_did_change(
2029 &mut self,
2030 local: bool,
2031 old_cursor_position: &Anchor,
2032 show_completions: bool,
2033 window: &mut Window,
2034 cx: &mut Context<Self>,
2035 ) {
2036 window.invalidate_character_coordinates();
2037
2038 // Copy selections to primary selection buffer
2039 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2040 if local {
2041 let selections = self.selections.all::<usize>(cx);
2042 let buffer_handle = self.buffer.read(cx).read(cx);
2043
2044 let mut text = String::new();
2045 for (index, selection) in selections.iter().enumerate() {
2046 let text_for_selection = buffer_handle
2047 .text_for_range(selection.start..selection.end)
2048 .collect::<String>();
2049
2050 text.push_str(&text_for_selection);
2051 if index != selections.len() - 1 {
2052 text.push('\n');
2053 }
2054 }
2055
2056 if !text.is_empty() {
2057 cx.write_to_primary(ClipboardItem::new_string(text));
2058 }
2059 }
2060
2061 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2062 self.buffer.update(cx, |buffer, cx| {
2063 buffer.set_active_selections(
2064 &self.selections.disjoint_anchors(),
2065 self.selections.line_mode,
2066 self.cursor_shape,
2067 cx,
2068 )
2069 });
2070 }
2071 let display_map = self
2072 .display_map
2073 .update(cx, |display_map, cx| display_map.snapshot(cx));
2074 let buffer = &display_map.buffer_snapshot;
2075 self.add_selections_state = None;
2076 self.select_next_state = None;
2077 self.select_prev_state = None;
2078 self.select_larger_syntax_node_stack.clear();
2079 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2080 self.snippet_stack
2081 .invalidate(&self.selections.disjoint_anchors(), buffer);
2082 self.take_rename(false, window, cx);
2083
2084 let new_cursor_position = self.selections.newest_anchor().head();
2085
2086 self.push_to_nav_history(
2087 *old_cursor_position,
2088 Some(new_cursor_position.to_point(buffer)),
2089 cx,
2090 );
2091
2092 if local {
2093 let new_cursor_position = self.selections.newest_anchor().head();
2094 let mut context_menu = self.context_menu.borrow_mut();
2095 let completion_menu = match context_menu.as_ref() {
2096 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2097 _ => {
2098 *context_menu = None;
2099 None
2100 }
2101 };
2102 if let Some(buffer_id) = new_cursor_position.buffer_id {
2103 if !self.registered_buffers.contains_key(&buffer_id) {
2104 if let Some(project) = self.project.as_ref() {
2105 project.update(cx, |project, cx| {
2106 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2107 return;
2108 };
2109 self.registered_buffers.insert(
2110 buffer_id,
2111 project.register_buffer_with_language_servers(&buffer, cx),
2112 );
2113 })
2114 }
2115 }
2116 }
2117
2118 if let Some(completion_menu) = completion_menu {
2119 let cursor_position = new_cursor_position.to_offset(buffer);
2120 let (word_range, kind) =
2121 buffer.surrounding_word(completion_menu.initial_position, true);
2122 if kind == Some(CharKind::Word)
2123 && word_range.to_inclusive().contains(&cursor_position)
2124 {
2125 let mut completion_menu = completion_menu.clone();
2126 drop(context_menu);
2127
2128 let query = Self::completion_query(buffer, cursor_position);
2129 cx.spawn(move |this, mut cx| async move {
2130 completion_menu
2131 .filter(query.as_deref(), cx.background_executor().clone())
2132 .await;
2133
2134 this.update(&mut cx, |this, cx| {
2135 let mut context_menu = this.context_menu.borrow_mut();
2136 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2137 else {
2138 return;
2139 };
2140
2141 if menu.id > completion_menu.id {
2142 return;
2143 }
2144
2145 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2146 drop(context_menu);
2147 cx.notify();
2148 })
2149 })
2150 .detach();
2151
2152 if show_completions {
2153 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2154 }
2155 } else {
2156 drop(context_menu);
2157 self.hide_context_menu(window, cx);
2158 }
2159 } else {
2160 drop(context_menu);
2161 }
2162
2163 hide_hover(self, cx);
2164
2165 if old_cursor_position.to_display_point(&display_map).row()
2166 != new_cursor_position.to_display_point(&display_map).row()
2167 {
2168 self.available_code_actions.take();
2169 }
2170 self.refresh_code_actions(window, cx);
2171 self.refresh_document_highlights(cx);
2172 self.refresh_selected_text_highlights(window, cx);
2173 refresh_matching_bracket_highlights(self, window, cx);
2174 self.update_visible_inline_completion(window, cx);
2175 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2176 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2177 if self.git_blame_inline_enabled {
2178 self.start_inline_blame_timer(window, cx);
2179 }
2180 }
2181
2182 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2183 cx.emit(EditorEvent::SelectionsChanged { local });
2184
2185 let selections = &self.selections.disjoint;
2186 if selections.len() == 1 {
2187 cx.emit(SearchEvent::ActiveMatchChanged)
2188 }
2189 if local
2190 && self.is_singleton(cx)
2191 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2192 {
2193 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2194 let background_executor = cx.background_executor().clone();
2195 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2196 let snapshot = self.buffer().read(cx).snapshot(cx);
2197 let selections = selections.clone();
2198 self.serialize_selections = cx.background_spawn(async move {
2199 background_executor.timer(Duration::from_millis(100)).await;
2200 let selections = selections
2201 .iter()
2202 .map(|selection| {
2203 (
2204 selection.start.to_offset(&snapshot),
2205 selection.end.to_offset(&snapshot),
2206 )
2207 })
2208 .collect();
2209 DB.save_editor_selections(editor_id, workspace_id, selections)
2210 .await
2211 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2212 .log_err();
2213 });
2214 }
2215 }
2216
2217 cx.notify();
2218 }
2219
2220 pub fn sync_selections(
2221 &mut self,
2222 other: Entity<Editor>,
2223 cx: &mut Context<Self>,
2224 ) -> gpui::Subscription {
2225 let other_selections = other.read(cx).selections.disjoint.to_vec();
2226 self.selections.change_with(cx, |selections| {
2227 selections.select_anchors(other_selections);
2228 });
2229
2230 let other_subscription =
2231 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2232 EditorEvent::SelectionsChanged { local: true } => {
2233 let other_selections = other.read(cx).selections.disjoint.to_vec();
2234 if other_selections.is_empty() {
2235 return;
2236 }
2237 this.selections.change_with(cx, |selections| {
2238 selections.select_anchors(other_selections);
2239 });
2240 }
2241 _ => {}
2242 });
2243
2244 let this_subscription =
2245 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2246 EditorEvent::SelectionsChanged { local: true } => {
2247 let these_selections = this.selections.disjoint.to_vec();
2248 if these_selections.is_empty() {
2249 return;
2250 }
2251 other.update(cx, |other_editor, cx| {
2252 other_editor.selections.change_with(cx, |selections| {
2253 selections.select_anchors(these_selections);
2254 })
2255 });
2256 }
2257 _ => {}
2258 });
2259
2260 Subscription::join(other_subscription, this_subscription)
2261 }
2262
2263 pub fn change_selections<R>(
2264 &mut self,
2265 autoscroll: Option<Autoscroll>,
2266 window: &mut Window,
2267 cx: &mut Context<Self>,
2268 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2269 ) -> R {
2270 self.change_selections_inner(autoscroll, true, window, cx, change)
2271 }
2272
2273 fn change_selections_inner<R>(
2274 &mut self,
2275 autoscroll: Option<Autoscroll>,
2276 request_completions: bool,
2277 window: &mut Window,
2278 cx: &mut Context<Self>,
2279 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2280 ) -> R {
2281 let old_cursor_position = self.selections.newest_anchor().head();
2282 self.push_to_selection_history();
2283
2284 let (changed, result) = self.selections.change_with(cx, change);
2285
2286 if changed {
2287 if let Some(autoscroll) = autoscroll {
2288 self.request_autoscroll(autoscroll, cx);
2289 }
2290 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2291
2292 if self.should_open_signature_help_automatically(
2293 &old_cursor_position,
2294 self.signature_help_state.backspace_pressed(),
2295 cx,
2296 ) {
2297 self.show_signature_help(&ShowSignatureHelp, window, cx);
2298 }
2299 self.signature_help_state.set_backspace_pressed(false);
2300 }
2301
2302 result
2303 }
2304
2305 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2306 where
2307 I: IntoIterator<Item = (Range<S>, T)>,
2308 S: ToOffset,
2309 T: Into<Arc<str>>,
2310 {
2311 if self.read_only(cx) {
2312 return;
2313 }
2314
2315 self.buffer
2316 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2317 }
2318
2319 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2320 where
2321 I: IntoIterator<Item = (Range<S>, T)>,
2322 S: ToOffset,
2323 T: Into<Arc<str>>,
2324 {
2325 if self.read_only(cx) {
2326 return;
2327 }
2328
2329 self.buffer.update(cx, |buffer, cx| {
2330 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2331 });
2332 }
2333
2334 pub fn edit_with_block_indent<I, S, T>(
2335 &mut self,
2336 edits: I,
2337 original_indent_columns: Vec<Option<u32>>,
2338 cx: &mut Context<Self>,
2339 ) where
2340 I: IntoIterator<Item = (Range<S>, T)>,
2341 S: ToOffset,
2342 T: Into<Arc<str>>,
2343 {
2344 if self.read_only(cx) {
2345 return;
2346 }
2347
2348 self.buffer.update(cx, |buffer, cx| {
2349 buffer.edit(
2350 edits,
2351 Some(AutoindentMode::Block {
2352 original_indent_columns,
2353 }),
2354 cx,
2355 )
2356 });
2357 }
2358
2359 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2360 self.hide_context_menu(window, cx);
2361
2362 match phase {
2363 SelectPhase::Begin {
2364 position,
2365 add,
2366 click_count,
2367 } => self.begin_selection(position, add, click_count, window, cx),
2368 SelectPhase::BeginColumnar {
2369 position,
2370 goal_column,
2371 reset,
2372 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2373 SelectPhase::Extend {
2374 position,
2375 click_count,
2376 } => self.extend_selection(position, click_count, window, cx),
2377 SelectPhase::Update {
2378 position,
2379 goal_column,
2380 scroll_delta,
2381 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2382 SelectPhase::End => self.end_selection(window, cx),
2383 }
2384 }
2385
2386 fn extend_selection(
2387 &mut self,
2388 position: DisplayPoint,
2389 click_count: usize,
2390 window: &mut Window,
2391 cx: &mut Context<Self>,
2392 ) {
2393 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2394 let tail = self.selections.newest::<usize>(cx).tail();
2395 self.begin_selection(position, false, click_count, window, cx);
2396
2397 let position = position.to_offset(&display_map, Bias::Left);
2398 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2399
2400 let mut pending_selection = self
2401 .selections
2402 .pending_anchor()
2403 .expect("extend_selection not called with pending selection");
2404 if position >= tail {
2405 pending_selection.start = tail_anchor;
2406 } else {
2407 pending_selection.end = tail_anchor;
2408 pending_selection.reversed = true;
2409 }
2410
2411 let mut pending_mode = self.selections.pending_mode().unwrap();
2412 match &mut pending_mode {
2413 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2414 _ => {}
2415 }
2416
2417 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2418 s.set_pending(pending_selection, pending_mode)
2419 });
2420 }
2421
2422 fn begin_selection(
2423 &mut self,
2424 position: DisplayPoint,
2425 add: bool,
2426 click_count: usize,
2427 window: &mut Window,
2428 cx: &mut Context<Self>,
2429 ) {
2430 if !self.focus_handle.is_focused(window) {
2431 self.last_focused_descendant = None;
2432 window.focus(&self.focus_handle);
2433 }
2434
2435 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2436 let buffer = &display_map.buffer_snapshot;
2437 let newest_selection = self.selections.newest_anchor().clone();
2438 let position = display_map.clip_point(position, Bias::Left);
2439
2440 let start;
2441 let end;
2442 let mode;
2443 let mut auto_scroll;
2444 match click_count {
2445 1 => {
2446 start = buffer.anchor_before(position.to_point(&display_map));
2447 end = start;
2448 mode = SelectMode::Character;
2449 auto_scroll = true;
2450 }
2451 2 => {
2452 let range = movement::surrounding_word(&display_map, position);
2453 start = buffer.anchor_before(range.start.to_point(&display_map));
2454 end = buffer.anchor_before(range.end.to_point(&display_map));
2455 mode = SelectMode::Word(start..end);
2456 auto_scroll = true;
2457 }
2458 3 => {
2459 let position = display_map
2460 .clip_point(position, Bias::Left)
2461 .to_point(&display_map);
2462 let line_start = display_map.prev_line_boundary(position).0;
2463 let next_line_start = buffer.clip_point(
2464 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2465 Bias::Left,
2466 );
2467 start = buffer.anchor_before(line_start);
2468 end = buffer.anchor_before(next_line_start);
2469 mode = SelectMode::Line(start..end);
2470 auto_scroll = true;
2471 }
2472 _ => {
2473 start = buffer.anchor_before(0);
2474 end = buffer.anchor_before(buffer.len());
2475 mode = SelectMode::All;
2476 auto_scroll = false;
2477 }
2478 }
2479 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2480
2481 let point_to_delete: Option<usize> = {
2482 let selected_points: Vec<Selection<Point>> =
2483 self.selections.disjoint_in_range(start..end, cx);
2484
2485 if !add || click_count > 1 {
2486 None
2487 } else if !selected_points.is_empty() {
2488 Some(selected_points[0].id)
2489 } else {
2490 let clicked_point_already_selected =
2491 self.selections.disjoint.iter().find(|selection| {
2492 selection.start.to_point(buffer) == start.to_point(buffer)
2493 || selection.end.to_point(buffer) == end.to_point(buffer)
2494 });
2495
2496 clicked_point_already_selected.map(|selection| selection.id)
2497 }
2498 };
2499
2500 let selections_count = self.selections.count();
2501
2502 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2503 if let Some(point_to_delete) = point_to_delete {
2504 s.delete(point_to_delete);
2505
2506 if selections_count == 1 {
2507 s.set_pending_anchor_range(start..end, mode);
2508 }
2509 } else {
2510 if !add {
2511 s.clear_disjoint();
2512 } else if click_count > 1 {
2513 s.delete(newest_selection.id)
2514 }
2515
2516 s.set_pending_anchor_range(start..end, mode);
2517 }
2518 });
2519 }
2520
2521 fn begin_columnar_selection(
2522 &mut self,
2523 position: DisplayPoint,
2524 goal_column: u32,
2525 reset: bool,
2526 window: &mut Window,
2527 cx: &mut Context<Self>,
2528 ) {
2529 if !self.focus_handle.is_focused(window) {
2530 self.last_focused_descendant = None;
2531 window.focus(&self.focus_handle);
2532 }
2533
2534 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2535
2536 if reset {
2537 let pointer_position = display_map
2538 .buffer_snapshot
2539 .anchor_before(position.to_point(&display_map));
2540
2541 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2542 s.clear_disjoint();
2543 s.set_pending_anchor_range(
2544 pointer_position..pointer_position,
2545 SelectMode::Character,
2546 );
2547 });
2548 }
2549
2550 let tail = self.selections.newest::<Point>(cx).tail();
2551 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2552
2553 if !reset {
2554 self.select_columns(
2555 tail.to_display_point(&display_map),
2556 position,
2557 goal_column,
2558 &display_map,
2559 window,
2560 cx,
2561 );
2562 }
2563 }
2564
2565 fn update_selection(
2566 &mut self,
2567 position: DisplayPoint,
2568 goal_column: u32,
2569 scroll_delta: gpui::Point<f32>,
2570 window: &mut Window,
2571 cx: &mut Context<Self>,
2572 ) {
2573 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2574
2575 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2576 let tail = tail.to_display_point(&display_map);
2577 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2578 } else if let Some(mut pending) = self.selections.pending_anchor() {
2579 let buffer = self.buffer.read(cx).snapshot(cx);
2580 let head;
2581 let tail;
2582 let mode = self.selections.pending_mode().unwrap();
2583 match &mode {
2584 SelectMode::Character => {
2585 head = position.to_point(&display_map);
2586 tail = pending.tail().to_point(&buffer);
2587 }
2588 SelectMode::Word(original_range) => {
2589 let original_display_range = original_range.start.to_display_point(&display_map)
2590 ..original_range.end.to_display_point(&display_map);
2591 let original_buffer_range = original_display_range.start.to_point(&display_map)
2592 ..original_display_range.end.to_point(&display_map);
2593 if movement::is_inside_word(&display_map, position)
2594 || original_display_range.contains(&position)
2595 {
2596 let word_range = movement::surrounding_word(&display_map, position);
2597 if word_range.start < original_display_range.start {
2598 head = word_range.start.to_point(&display_map);
2599 } else {
2600 head = word_range.end.to_point(&display_map);
2601 }
2602 } else {
2603 head = position.to_point(&display_map);
2604 }
2605
2606 if head <= original_buffer_range.start {
2607 tail = original_buffer_range.end;
2608 } else {
2609 tail = original_buffer_range.start;
2610 }
2611 }
2612 SelectMode::Line(original_range) => {
2613 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2614
2615 let position = display_map
2616 .clip_point(position, Bias::Left)
2617 .to_point(&display_map);
2618 let line_start = display_map.prev_line_boundary(position).0;
2619 let next_line_start = buffer.clip_point(
2620 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2621 Bias::Left,
2622 );
2623
2624 if line_start < original_range.start {
2625 head = line_start
2626 } else {
2627 head = next_line_start
2628 }
2629
2630 if head <= original_range.start {
2631 tail = original_range.end;
2632 } else {
2633 tail = original_range.start;
2634 }
2635 }
2636 SelectMode::All => {
2637 return;
2638 }
2639 };
2640
2641 if head < tail {
2642 pending.start = buffer.anchor_before(head);
2643 pending.end = buffer.anchor_before(tail);
2644 pending.reversed = true;
2645 } else {
2646 pending.start = buffer.anchor_before(tail);
2647 pending.end = buffer.anchor_before(head);
2648 pending.reversed = false;
2649 }
2650
2651 self.change_selections(None, window, cx, |s| {
2652 s.set_pending(pending, mode);
2653 });
2654 } else {
2655 log::error!("update_selection dispatched with no pending selection");
2656 return;
2657 }
2658
2659 self.apply_scroll_delta(scroll_delta, window, cx);
2660 cx.notify();
2661 }
2662
2663 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2664 self.columnar_selection_tail.take();
2665 if self.selections.pending_anchor().is_some() {
2666 let selections = self.selections.all::<usize>(cx);
2667 self.change_selections(None, window, cx, |s| {
2668 s.select(selections);
2669 s.clear_pending();
2670 });
2671 }
2672 }
2673
2674 fn select_columns(
2675 &mut self,
2676 tail: DisplayPoint,
2677 head: DisplayPoint,
2678 goal_column: u32,
2679 display_map: &DisplaySnapshot,
2680 window: &mut Window,
2681 cx: &mut Context<Self>,
2682 ) {
2683 let start_row = cmp::min(tail.row(), head.row());
2684 let end_row = cmp::max(tail.row(), head.row());
2685 let start_column = cmp::min(tail.column(), goal_column);
2686 let end_column = cmp::max(tail.column(), goal_column);
2687 let reversed = start_column < tail.column();
2688
2689 let selection_ranges = (start_row.0..=end_row.0)
2690 .map(DisplayRow)
2691 .filter_map(|row| {
2692 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2693 let start = display_map
2694 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2695 .to_point(display_map);
2696 let end = display_map
2697 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2698 .to_point(display_map);
2699 if reversed {
2700 Some(end..start)
2701 } else {
2702 Some(start..end)
2703 }
2704 } else {
2705 None
2706 }
2707 })
2708 .collect::<Vec<_>>();
2709
2710 self.change_selections(None, window, cx, |s| {
2711 s.select_ranges(selection_ranges);
2712 });
2713 cx.notify();
2714 }
2715
2716 pub fn has_pending_nonempty_selection(&self) -> bool {
2717 let pending_nonempty_selection = match self.selections.pending_anchor() {
2718 Some(Selection { start, end, .. }) => start != end,
2719 None => false,
2720 };
2721
2722 pending_nonempty_selection
2723 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2724 }
2725
2726 pub fn has_pending_selection(&self) -> bool {
2727 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2728 }
2729
2730 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2731 self.selection_mark_mode = false;
2732
2733 if self.clear_expanded_diff_hunks(cx) {
2734 cx.notify();
2735 return;
2736 }
2737 if self.dismiss_menus_and_popups(true, window, cx) {
2738 return;
2739 }
2740
2741 if self.mode == EditorMode::Full
2742 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2743 {
2744 return;
2745 }
2746
2747 cx.propagate();
2748 }
2749
2750 pub fn dismiss_menus_and_popups(
2751 &mut self,
2752 is_user_requested: bool,
2753 window: &mut Window,
2754 cx: &mut Context<Self>,
2755 ) -> bool {
2756 if self.take_rename(false, window, cx).is_some() {
2757 return true;
2758 }
2759
2760 if hide_hover(self, cx) {
2761 return true;
2762 }
2763
2764 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2765 return true;
2766 }
2767
2768 if self.hide_context_menu(window, cx).is_some() {
2769 return true;
2770 }
2771
2772 if self.mouse_context_menu.take().is_some() {
2773 return true;
2774 }
2775
2776 if is_user_requested && self.discard_inline_completion(true, cx) {
2777 return true;
2778 }
2779
2780 if self.snippet_stack.pop().is_some() {
2781 return true;
2782 }
2783
2784 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2785 self.dismiss_diagnostics(cx);
2786 return true;
2787 }
2788
2789 false
2790 }
2791
2792 fn linked_editing_ranges_for(
2793 &self,
2794 selection: Range<text::Anchor>,
2795 cx: &App,
2796 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2797 if self.linked_edit_ranges.is_empty() {
2798 return None;
2799 }
2800 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2801 selection.end.buffer_id.and_then(|end_buffer_id| {
2802 if selection.start.buffer_id != Some(end_buffer_id) {
2803 return None;
2804 }
2805 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2806 let snapshot = buffer.read(cx).snapshot();
2807 self.linked_edit_ranges
2808 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2809 .map(|ranges| (ranges, snapshot, buffer))
2810 })?;
2811 use text::ToOffset as TO;
2812 // find offset from the start of current range to current cursor position
2813 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2814
2815 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2816 let start_difference = start_offset - start_byte_offset;
2817 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2818 let end_difference = end_offset - start_byte_offset;
2819 // Current range has associated linked ranges.
2820 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2821 for range in linked_ranges.iter() {
2822 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2823 let end_offset = start_offset + end_difference;
2824 let start_offset = start_offset + start_difference;
2825 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2826 continue;
2827 }
2828 if self.selections.disjoint_anchor_ranges().any(|s| {
2829 if s.start.buffer_id != selection.start.buffer_id
2830 || s.end.buffer_id != selection.end.buffer_id
2831 {
2832 return false;
2833 }
2834 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2835 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2836 }) {
2837 continue;
2838 }
2839 let start = buffer_snapshot.anchor_after(start_offset);
2840 let end = buffer_snapshot.anchor_after(end_offset);
2841 linked_edits
2842 .entry(buffer.clone())
2843 .or_default()
2844 .push(start..end);
2845 }
2846 Some(linked_edits)
2847 }
2848
2849 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2850 let text: Arc<str> = text.into();
2851
2852 if self.read_only(cx) {
2853 return;
2854 }
2855
2856 let selections = self.selections.all_adjusted(cx);
2857 let mut bracket_inserted = false;
2858 let mut edits = Vec::new();
2859 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2860 let mut new_selections = Vec::with_capacity(selections.len());
2861 let mut new_autoclose_regions = Vec::new();
2862 let snapshot = self.buffer.read(cx).read(cx);
2863
2864 for (selection, autoclose_region) in
2865 self.selections_with_autoclose_regions(selections, &snapshot)
2866 {
2867 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2868 // Determine if the inserted text matches the opening or closing
2869 // bracket of any of this language's bracket pairs.
2870 let mut bracket_pair = None;
2871 let mut is_bracket_pair_start = false;
2872 let mut is_bracket_pair_end = false;
2873 if !text.is_empty() {
2874 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2875 // and they are removing the character that triggered IME popup.
2876 for (pair, enabled) in scope.brackets() {
2877 if !pair.close && !pair.surround {
2878 continue;
2879 }
2880
2881 if enabled && pair.start.ends_with(text.as_ref()) {
2882 let prefix_len = pair.start.len() - text.len();
2883 let preceding_text_matches_prefix = prefix_len == 0
2884 || (selection.start.column >= (prefix_len as u32)
2885 && snapshot.contains_str_at(
2886 Point::new(
2887 selection.start.row,
2888 selection.start.column - (prefix_len as u32),
2889 ),
2890 &pair.start[..prefix_len],
2891 ));
2892 if preceding_text_matches_prefix {
2893 bracket_pair = Some(pair.clone());
2894 is_bracket_pair_start = true;
2895 break;
2896 }
2897 }
2898 if pair.end.as_str() == text.as_ref() {
2899 bracket_pair = Some(pair.clone());
2900 is_bracket_pair_end = true;
2901 break;
2902 }
2903 }
2904 }
2905
2906 if let Some(bracket_pair) = bracket_pair {
2907 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
2908 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2909 let auto_surround =
2910 self.use_auto_surround && snapshot_settings.use_auto_surround;
2911 if selection.is_empty() {
2912 if is_bracket_pair_start {
2913 // If the inserted text is a suffix of an opening bracket and the
2914 // selection is preceded by the rest of the opening bracket, then
2915 // insert the closing bracket.
2916 let following_text_allows_autoclose = snapshot
2917 .chars_at(selection.start)
2918 .next()
2919 .map_or(true, |c| scope.should_autoclose_before(c));
2920
2921 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2922 && bracket_pair.start.len() == 1
2923 {
2924 let target = bracket_pair.start.chars().next().unwrap();
2925 let current_line_count = snapshot
2926 .reversed_chars_at(selection.start)
2927 .take_while(|&c| c != '\n')
2928 .filter(|&c| c == target)
2929 .count();
2930 current_line_count % 2 == 1
2931 } else {
2932 false
2933 };
2934
2935 if autoclose
2936 && bracket_pair.close
2937 && following_text_allows_autoclose
2938 && !is_closing_quote
2939 {
2940 let anchor = snapshot.anchor_before(selection.end);
2941 new_selections.push((selection.map(|_| anchor), text.len()));
2942 new_autoclose_regions.push((
2943 anchor,
2944 text.len(),
2945 selection.id,
2946 bracket_pair.clone(),
2947 ));
2948 edits.push((
2949 selection.range(),
2950 format!("{}{}", text, bracket_pair.end).into(),
2951 ));
2952 bracket_inserted = true;
2953 continue;
2954 }
2955 }
2956
2957 if let Some(region) = autoclose_region {
2958 // If the selection is followed by an auto-inserted closing bracket,
2959 // then don't insert that closing bracket again; just move the selection
2960 // past the closing bracket.
2961 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2962 && text.as_ref() == region.pair.end.as_str();
2963 if should_skip {
2964 let anchor = snapshot.anchor_after(selection.end);
2965 new_selections
2966 .push((selection.map(|_| anchor), region.pair.end.len()));
2967 continue;
2968 }
2969 }
2970
2971 let always_treat_brackets_as_autoclosed = snapshot
2972 .language_settings_at(selection.start, cx)
2973 .always_treat_brackets_as_autoclosed;
2974 if always_treat_brackets_as_autoclosed
2975 && is_bracket_pair_end
2976 && snapshot.contains_str_at(selection.end, text.as_ref())
2977 {
2978 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2979 // and the inserted text is a closing bracket and the selection is followed
2980 // by the closing bracket then move the selection past the closing bracket.
2981 let anchor = snapshot.anchor_after(selection.end);
2982 new_selections.push((selection.map(|_| anchor), text.len()));
2983 continue;
2984 }
2985 }
2986 // If an opening bracket is 1 character long and is typed while
2987 // text is selected, then surround that text with the bracket pair.
2988 else if auto_surround
2989 && bracket_pair.surround
2990 && is_bracket_pair_start
2991 && bracket_pair.start.chars().count() == 1
2992 {
2993 edits.push((selection.start..selection.start, text.clone()));
2994 edits.push((
2995 selection.end..selection.end,
2996 bracket_pair.end.as_str().into(),
2997 ));
2998 bracket_inserted = true;
2999 new_selections.push((
3000 Selection {
3001 id: selection.id,
3002 start: snapshot.anchor_after(selection.start),
3003 end: snapshot.anchor_before(selection.end),
3004 reversed: selection.reversed,
3005 goal: selection.goal,
3006 },
3007 0,
3008 ));
3009 continue;
3010 }
3011 }
3012 }
3013
3014 if self.auto_replace_emoji_shortcode
3015 && selection.is_empty()
3016 && text.as_ref().ends_with(':')
3017 {
3018 if let Some(possible_emoji_short_code) =
3019 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3020 {
3021 if !possible_emoji_short_code.is_empty() {
3022 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3023 let emoji_shortcode_start = Point::new(
3024 selection.start.row,
3025 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3026 );
3027
3028 // Remove shortcode from buffer
3029 edits.push((
3030 emoji_shortcode_start..selection.start,
3031 "".to_string().into(),
3032 ));
3033 new_selections.push((
3034 Selection {
3035 id: selection.id,
3036 start: snapshot.anchor_after(emoji_shortcode_start),
3037 end: snapshot.anchor_before(selection.start),
3038 reversed: selection.reversed,
3039 goal: selection.goal,
3040 },
3041 0,
3042 ));
3043
3044 // Insert emoji
3045 let selection_start_anchor = snapshot.anchor_after(selection.start);
3046 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3047 edits.push((selection.start..selection.end, emoji.to_string().into()));
3048
3049 continue;
3050 }
3051 }
3052 }
3053 }
3054
3055 // If not handling any auto-close operation, then just replace the selected
3056 // text with the given input and move the selection to the end of the
3057 // newly inserted text.
3058 let anchor = snapshot.anchor_after(selection.end);
3059 if !self.linked_edit_ranges.is_empty() {
3060 let start_anchor = snapshot.anchor_before(selection.start);
3061
3062 let is_word_char = text.chars().next().map_or(true, |char| {
3063 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3064 classifier.is_word(char)
3065 });
3066
3067 if is_word_char {
3068 if let Some(ranges) = self
3069 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3070 {
3071 for (buffer, edits) in ranges {
3072 linked_edits
3073 .entry(buffer.clone())
3074 .or_default()
3075 .extend(edits.into_iter().map(|range| (range, text.clone())));
3076 }
3077 }
3078 }
3079 }
3080
3081 new_selections.push((selection.map(|_| anchor), 0));
3082 edits.push((selection.start..selection.end, text.clone()));
3083 }
3084
3085 drop(snapshot);
3086
3087 self.transact(window, cx, |this, window, cx| {
3088 let initial_buffer_versions =
3089 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3090
3091 this.buffer.update(cx, |buffer, cx| {
3092 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3093 });
3094 for (buffer, edits) in linked_edits {
3095 buffer.update(cx, |buffer, cx| {
3096 let snapshot = buffer.snapshot();
3097 let edits = edits
3098 .into_iter()
3099 .map(|(range, text)| {
3100 use text::ToPoint as TP;
3101 let end_point = TP::to_point(&range.end, &snapshot);
3102 let start_point = TP::to_point(&range.start, &snapshot);
3103 (start_point..end_point, text)
3104 })
3105 .sorted_by_key(|(range, _)| range.start)
3106 .collect::<Vec<_>>();
3107 buffer.edit(edits, None, cx);
3108 })
3109 }
3110 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3111 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3112 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3113 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3114 .zip(new_selection_deltas)
3115 .map(|(selection, delta)| Selection {
3116 id: selection.id,
3117 start: selection.start + delta,
3118 end: selection.end + delta,
3119 reversed: selection.reversed,
3120 goal: SelectionGoal::None,
3121 })
3122 .collect::<Vec<_>>();
3123
3124 let mut i = 0;
3125 for (position, delta, selection_id, pair) in new_autoclose_regions {
3126 let position = position.to_offset(&map.buffer_snapshot) + delta;
3127 let start = map.buffer_snapshot.anchor_before(position);
3128 let end = map.buffer_snapshot.anchor_after(position);
3129 while let Some(existing_state) = this.autoclose_regions.get(i) {
3130 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3131 Ordering::Less => i += 1,
3132 Ordering::Greater => break,
3133 Ordering::Equal => {
3134 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3135 Ordering::Less => i += 1,
3136 Ordering::Equal => break,
3137 Ordering::Greater => break,
3138 }
3139 }
3140 }
3141 }
3142 this.autoclose_regions.insert(
3143 i,
3144 AutocloseRegion {
3145 selection_id,
3146 range: start..end,
3147 pair,
3148 },
3149 );
3150 }
3151
3152 let had_active_inline_completion = this.has_active_inline_completion();
3153 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3154 s.select(new_selections)
3155 });
3156
3157 if !bracket_inserted {
3158 if let Some(on_type_format_task) =
3159 this.trigger_on_type_formatting(text.to_string(), window, cx)
3160 {
3161 on_type_format_task.detach_and_log_err(cx);
3162 }
3163 }
3164
3165 let editor_settings = EditorSettings::get_global(cx);
3166 if bracket_inserted
3167 && (editor_settings.auto_signature_help
3168 || editor_settings.show_signature_help_after_edits)
3169 {
3170 this.show_signature_help(&ShowSignatureHelp, window, cx);
3171 }
3172
3173 let trigger_in_words =
3174 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3175 if this.hard_wrap.is_some() {
3176 let latest: Range<Point> = this.selections.newest(cx).range();
3177 if latest.is_empty()
3178 && this
3179 .buffer()
3180 .read(cx)
3181 .snapshot(cx)
3182 .line_len(MultiBufferRow(latest.start.row))
3183 == latest.start.column
3184 {
3185 this.rewrap_impl(true, cx)
3186 }
3187 }
3188 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3189 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3190 this.refresh_inline_completion(true, false, window, cx);
3191 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3192 });
3193 }
3194
3195 fn find_possible_emoji_shortcode_at_position(
3196 snapshot: &MultiBufferSnapshot,
3197 position: Point,
3198 ) -> Option<String> {
3199 let mut chars = Vec::new();
3200 let mut found_colon = false;
3201 for char in snapshot.reversed_chars_at(position).take(100) {
3202 // Found a possible emoji shortcode in the middle of the buffer
3203 if found_colon {
3204 if char.is_whitespace() {
3205 chars.reverse();
3206 return Some(chars.iter().collect());
3207 }
3208 // If the previous character is not a whitespace, we are in the middle of a word
3209 // and we only want to complete the shortcode if the word is made up of other emojis
3210 let mut containing_word = String::new();
3211 for ch in snapshot
3212 .reversed_chars_at(position)
3213 .skip(chars.len() + 1)
3214 .take(100)
3215 {
3216 if ch.is_whitespace() {
3217 break;
3218 }
3219 containing_word.push(ch);
3220 }
3221 let containing_word = containing_word.chars().rev().collect::<String>();
3222 if util::word_consists_of_emojis(containing_word.as_str()) {
3223 chars.reverse();
3224 return Some(chars.iter().collect());
3225 }
3226 }
3227
3228 if char.is_whitespace() || !char.is_ascii() {
3229 return None;
3230 }
3231 if char == ':' {
3232 found_colon = true;
3233 } else {
3234 chars.push(char);
3235 }
3236 }
3237 // Found a possible emoji shortcode at the beginning of the buffer
3238 chars.reverse();
3239 Some(chars.iter().collect())
3240 }
3241
3242 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3243 self.transact(window, cx, |this, window, cx| {
3244 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3245 let selections = this.selections.all::<usize>(cx);
3246 let multi_buffer = this.buffer.read(cx);
3247 let buffer = multi_buffer.snapshot(cx);
3248 selections
3249 .iter()
3250 .map(|selection| {
3251 let start_point = selection.start.to_point(&buffer);
3252 let mut indent =
3253 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3254 indent.len = cmp::min(indent.len, start_point.column);
3255 let start = selection.start;
3256 let end = selection.end;
3257 let selection_is_empty = start == end;
3258 let language_scope = buffer.language_scope_at(start);
3259 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3260 &language_scope
3261 {
3262 let insert_extra_newline =
3263 insert_extra_newline_brackets(&buffer, start..end, language)
3264 || insert_extra_newline_tree_sitter(&buffer, start..end);
3265
3266 // Comment extension on newline is allowed only for cursor selections
3267 let comment_delimiter = maybe!({
3268 if !selection_is_empty {
3269 return None;
3270 }
3271
3272 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3273 return None;
3274 }
3275
3276 let delimiters = language.line_comment_prefixes();
3277 let max_len_of_delimiter =
3278 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3279 let (snapshot, range) =
3280 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3281
3282 let mut index_of_first_non_whitespace = 0;
3283 let comment_candidate = snapshot
3284 .chars_for_range(range)
3285 .skip_while(|c| {
3286 let should_skip = c.is_whitespace();
3287 if should_skip {
3288 index_of_first_non_whitespace += 1;
3289 }
3290 should_skip
3291 })
3292 .take(max_len_of_delimiter)
3293 .collect::<String>();
3294 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3295 comment_candidate.starts_with(comment_prefix.as_ref())
3296 })?;
3297 let cursor_is_placed_after_comment_marker =
3298 index_of_first_non_whitespace + comment_prefix.len()
3299 <= start_point.column as usize;
3300 if cursor_is_placed_after_comment_marker {
3301 Some(comment_prefix.clone())
3302 } else {
3303 None
3304 }
3305 });
3306 (comment_delimiter, insert_extra_newline)
3307 } else {
3308 (None, false)
3309 };
3310
3311 let capacity_for_delimiter = comment_delimiter
3312 .as_deref()
3313 .map(str::len)
3314 .unwrap_or_default();
3315 let mut new_text =
3316 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3317 new_text.push('\n');
3318 new_text.extend(indent.chars());
3319 if let Some(delimiter) = &comment_delimiter {
3320 new_text.push_str(delimiter);
3321 }
3322 if insert_extra_newline {
3323 new_text = new_text.repeat(2);
3324 }
3325
3326 let anchor = buffer.anchor_after(end);
3327 let new_selection = selection.map(|_| anchor);
3328 (
3329 (start..end, new_text),
3330 (insert_extra_newline, new_selection),
3331 )
3332 })
3333 .unzip()
3334 };
3335
3336 this.edit_with_autoindent(edits, cx);
3337 let buffer = this.buffer.read(cx).snapshot(cx);
3338 let new_selections = selection_fixup_info
3339 .into_iter()
3340 .map(|(extra_newline_inserted, new_selection)| {
3341 let mut cursor = new_selection.end.to_point(&buffer);
3342 if extra_newline_inserted {
3343 cursor.row -= 1;
3344 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3345 }
3346 new_selection.map(|_| cursor)
3347 })
3348 .collect();
3349
3350 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3351 s.select(new_selections)
3352 });
3353 this.refresh_inline_completion(true, false, window, cx);
3354 });
3355 }
3356
3357 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3358 let buffer = self.buffer.read(cx);
3359 let snapshot = buffer.snapshot(cx);
3360
3361 let mut edits = Vec::new();
3362 let mut rows = Vec::new();
3363
3364 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3365 let cursor = selection.head();
3366 let row = cursor.row;
3367
3368 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3369
3370 let newline = "\n".to_string();
3371 edits.push((start_of_line..start_of_line, newline));
3372
3373 rows.push(row + rows_inserted as u32);
3374 }
3375
3376 self.transact(window, cx, |editor, window, cx| {
3377 editor.edit(edits, cx);
3378
3379 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3380 let mut index = 0;
3381 s.move_cursors_with(|map, _, _| {
3382 let row = rows[index];
3383 index += 1;
3384
3385 let point = Point::new(row, 0);
3386 let boundary = map.next_line_boundary(point).1;
3387 let clipped = map.clip_point(boundary, Bias::Left);
3388
3389 (clipped, SelectionGoal::None)
3390 });
3391 });
3392
3393 let mut indent_edits = Vec::new();
3394 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3395 for row in rows {
3396 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3397 for (row, indent) in indents {
3398 if indent.len == 0 {
3399 continue;
3400 }
3401
3402 let text = match indent.kind {
3403 IndentKind::Space => " ".repeat(indent.len as usize),
3404 IndentKind::Tab => "\t".repeat(indent.len as usize),
3405 };
3406 let point = Point::new(row.0, 0);
3407 indent_edits.push((point..point, text));
3408 }
3409 }
3410 editor.edit(indent_edits, cx);
3411 });
3412 }
3413
3414 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3415 let buffer = self.buffer.read(cx);
3416 let snapshot = buffer.snapshot(cx);
3417
3418 let mut edits = Vec::new();
3419 let mut rows = Vec::new();
3420 let mut rows_inserted = 0;
3421
3422 for selection in self.selections.all_adjusted(cx) {
3423 let cursor = selection.head();
3424 let row = cursor.row;
3425
3426 let point = Point::new(row + 1, 0);
3427 let start_of_line = snapshot.clip_point(point, Bias::Left);
3428
3429 let newline = "\n".to_string();
3430 edits.push((start_of_line..start_of_line, newline));
3431
3432 rows_inserted += 1;
3433 rows.push(row + rows_inserted);
3434 }
3435
3436 self.transact(window, cx, |editor, window, cx| {
3437 editor.edit(edits, cx);
3438
3439 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3440 let mut index = 0;
3441 s.move_cursors_with(|map, _, _| {
3442 let row = rows[index];
3443 index += 1;
3444
3445 let point = Point::new(row, 0);
3446 let boundary = map.next_line_boundary(point).1;
3447 let clipped = map.clip_point(boundary, Bias::Left);
3448
3449 (clipped, SelectionGoal::None)
3450 });
3451 });
3452
3453 let mut indent_edits = Vec::new();
3454 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3455 for row in rows {
3456 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3457 for (row, indent) in indents {
3458 if indent.len == 0 {
3459 continue;
3460 }
3461
3462 let text = match indent.kind {
3463 IndentKind::Space => " ".repeat(indent.len as usize),
3464 IndentKind::Tab => "\t".repeat(indent.len as usize),
3465 };
3466 let point = Point::new(row.0, 0);
3467 indent_edits.push((point..point, text));
3468 }
3469 }
3470 editor.edit(indent_edits, cx);
3471 });
3472 }
3473
3474 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3475 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3476 original_indent_columns: Vec::new(),
3477 });
3478 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3479 }
3480
3481 fn insert_with_autoindent_mode(
3482 &mut self,
3483 text: &str,
3484 autoindent_mode: Option<AutoindentMode>,
3485 window: &mut Window,
3486 cx: &mut Context<Self>,
3487 ) {
3488 if self.read_only(cx) {
3489 return;
3490 }
3491
3492 let text: Arc<str> = text.into();
3493 self.transact(window, cx, |this, window, cx| {
3494 let old_selections = this.selections.all_adjusted(cx);
3495 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3496 let anchors = {
3497 let snapshot = buffer.read(cx);
3498 old_selections
3499 .iter()
3500 .map(|s| {
3501 let anchor = snapshot.anchor_after(s.head());
3502 s.map(|_| anchor)
3503 })
3504 .collect::<Vec<_>>()
3505 };
3506 buffer.edit(
3507 old_selections
3508 .iter()
3509 .map(|s| (s.start..s.end, text.clone())),
3510 autoindent_mode,
3511 cx,
3512 );
3513 anchors
3514 });
3515
3516 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3517 s.select_anchors(selection_anchors);
3518 });
3519
3520 cx.notify();
3521 });
3522 }
3523
3524 fn trigger_completion_on_input(
3525 &mut self,
3526 text: &str,
3527 trigger_in_words: bool,
3528 window: &mut Window,
3529 cx: &mut Context<Self>,
3530 ) {
3531 if self.is_completion_trigger(text, trigger_in_words, cx) {
3532 self.show_completions(
3533 &ShowCompletions {
3534 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3535 },
3536 window,
3537 cx,
3538 );
3539 } else {
3540 self.hide_context_menu(window, cx);
3541 }
3542 }
3543
3544 fn is_completion_trigger(
3545 &self,
3546 text: &str,
3547 trigger_in_words: bool,
3548 cx: &mut Context<Self>,
3549 ) -> bool {
3550 let position = self.selections.newest_anchor().head();
3551 let multibuffer = self.buffer.read(cx);
3552 let Some(buffer) = position
3553 .buffer_id
3554 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3555 else {
3556 return false;
3557 };
3558
3559 if let Some(completion_provider) = &self.completion_provider {
3560 completion_provider.is_completion_trigger(
3561 &buffer,
3562 position.text_anchor,
3563 text,
3564 trigger_in_words,
3565 cx,
3566 )
3567 } else {
3568 false
3569 }
3570 }
3571
3572 /// If any empty selections is touching the start of its innermost containing autoclose
3573 /// region, expand it to select the brackets.
3574 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3575 let selections = self.selections.all::<usize>(cx);
3576 let buffer = self.buffer.read(cx).read(cx);
3577 let new_selections = self
3578 .selections_with_autoclose_regions(selections, &buffer)
3579 .map(|(mut selection, region)| {
3580 if !selection.is_empty() {
3581 return selection;
3582 }
3583
3584 if let Some(region) = region {
3585 let mut range = region.range.to_offset(&buffer);
3586 if selection.start == range.start && range.start >= region.pair.start.len() {
3587 range.start -= region.pair.start.len();
3588 if buffer.contains_str_at(range.start, ®ion.pair.start)
3589 && buffer.contains_str_at(range.end, ®ion.pair.end)
3590 {
3591 range.end += region.pair.end.len();
3592 selection.start = range.start;
3593 selection.end = range.end;
3594
3595 return selection;
3596 }
3597 }
3598 }
3599
3600 let always_treat_brackets_as_autoclosed = buffer
3601 .language_settings_at(selection.start, cx)
3602 .always_treat_brackets_as_autoclosed;
3603
3604 if !always_treat_brackets_as_autoclosed {
3605 return selection;
3606 }
3607
3608 if let Some(scope) = buffer.language_scope_at(selection.start) {
3609 for (pair, enabled) in scope.brackets() {
3610 if !enabled || !pair.close {
3611 continue;
3612 }
3613
3614 if buffer.contains_str_at(selection.start, &pair.end) {
3615 let pair_start_len = pair.start.len();
3616 if buffer.contains_str_at(
3617 selection.start.saturating_sub(pair_start_len),
3618 &pair.start,
3619 ) {
3620 selection.start -= pair_start_len;
3621 selection.end += pair.end.len();
3622
3623 return selection;
3624 }
3625 }
3626 }
3627 }
3628
3629 selection
3630 })
3631 .collect();
3632
3633 drop(buffer);
3634 self.change_selections(None, window, cx, |selections| {
3635 selections.select(new_selections)
3636 });
3637 }
3638
3639 /// Iterate the given selections, and for each one, find the smallest surrounding
3640 /// autoclose region. This uses the ordering of the selections and the autoclose
3641 /// regions to avoid repeated comparisons.
3642 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3643 &'a self,
3644 selections: impl IntoIterator<Item = Selection<D>>,
3645 buffer: &'a MultiBufferSnapshot,
3646 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3647 let mut i = 0;
3648 let mut regions = self.autoclose_regions.as_slice();
3649 selections.into_iter().map(move |selection| {
3650 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3651
3652 let mut enclosing = None;
3653 while let Some(pair_state) = regions.get(i) {
3654 if pair_state.range.end.to_offset(buffer) < range.start {
3655 regions = ®ions[i + 1..];
3656 i = 0;
3657 } else if pair_state.range.start.to_offset(buffer) > range.end {
3658 break;
3659 } else {
3660 if pair_state.selection_id == selection.id {
3661 enclosing = Some(pair_state);
3662 }
3663 i += 1;
3664 }
3665 }
3666
3667 (selection, enclosing)
3668 })
3669 }
3670
3671 /// Remove any autoclose regions that no longer contain their selection.
3672 fn invalidate_autoclose_regions(
3673 &mut self,
3674 mut selections: &[Selection<Anchor>],
3675 buffer: &MultiBufferSnapshot,
3676 ) {
3677 self.autoclose_regions.retain(|state| {
3678 let mut i = 0;
3679 while let Some(selection) = selections.get(i) {
3680 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3681 selections = &selections[1..];
3682 continue;
3683 }
3684 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3685 break;
3686 }
3687 if selection.id == state.selection_id {
3688 return true;
3689 } else {
3690 i += 1;
3691 }
3692 }
3693 false
3694 });
3695 }
3696
3697 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3698 let offset = position.to_offset(buffer);
3699 let (word_range, kind) = buffer.surrounding_word(offset, true);
3700 if offset > word_range.start && kind == Some(CharKind::Word) {
3701 Some(
3702 buffer
3703 .text_for_range(word_range.start..offset)
3704 .collect::<String>(),
3705 )
3706 } else {
3707 None
3708 }
3709 }
3710
3711 pub fn toggle_inlay_hints(
3712 &mut self,
3713 _: &ToggleInlayHints,
3714 _: &mut Window,
3715 cx: &mut Context<Self>,
3716 ) {
3717 self.refresh_inlay_hints(
3718 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3719 cx,
3720 );
3721 }
3722
3723 pub fn inlay_hints_enabled(&self) -> bool {
3724 self.inlay_hint_cache.enabled
3725 }
3726
3727 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3728 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3729 return;
3730 }
3731
3732 let reason_description = reason.description();
3733 let ignore_debounce = matches!(
3734 reason,
3735 InlayHintRefreshReason::SettingsChange(_)
3736 | InlayHintRefreshReason::Toggle(_)
3737 | InlayHintRefreshReason::ExcerptsRemoved(_)
3738 | InlayHintRefreshReason::ModifiersChanged(_)
3739 );
3740 let (invalidate_cache, required_languages) = match reason {
3741 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3742 match self.inlay_hint_cache.modifiers_override(enabled) {
3743 Some(enabled) => {
3744 if enabled {
3745 (InvalidationStrategy::RefreshRequested, None)
3746 } else {
3747 self.splice_inlays(
3748 &self
3749 .visible_inlay_hints(cx)
3750 .iter()
3751 .map(|inlay| inlay.id)
3752 .collect::<Vec<InlayId>>(),
3753 Vec::new(),
3754 cx,
3755 );
3756 return;
3757 }
3758 }
3759 None => return,
3760 }
3761 }
3762 InlayHintRefreshReason::Toggle(enabled) => {
3763 if self.inlay_hint_cache.toggle(enabled) {
3764 if enabled {
3765 (InvalidationStrategy::RefreshRequested, None)
3766 } else {
3767 self.splice_inlays(
3768 &self
3769 .visible_inlay_hints(cx)
3770 .iter()
3771 .map(|inlay| inlay.id)
3772 .collect::<Vec<InlayId>>(),
3773 Vec::new(),
3774 cx,
3775 );
3776 return;
3777 }
3778 } else {
3779 return;
3780 }
3781 }
3782 InlayHintRefreshReason::SettingsChange(new_settings) => {
3783 match self.inlay_hint_cache.update_settings(
3784 &self.buffer,
3785 new_settings,
3786 self.visible_inlay_hints(cx),
3787 cx,
3788 ) {
3789 ControlFlow::Break(Some(InlaySplice {
3790 to_remove,
3791 to_insert,
3792 })) => {
3793 self.splice_inlays(&to_remove, to_insert, cx);
3794 return;
3795 }
3796 ControlFlow::Break(None) => return,
3797 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3798 }
3799 }
3800 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3801 if let Some(InlaySplice {
3802 to_remove,
3803 to_insert,
3804 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3805 {
3806 self.splice_inlays(&to_remove, to_insert, cx);
3807 }
3808 return;
3809 }
3810 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3811 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3812 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3813 }
3814 InlayHintRefreshReason::RefreshRequested => {
3815 (InvalidationStrategy::RefreshRequested, None)
3816 }
3817 };
3818
3819 if let Some(InlaySplice {
3820 to_remove,
3821 to_insert,
3822 }) = self.inlay_hint_cache.spawn_hint_refresh(
3823 reason_description,
3824 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3825 invalidate_cache,
3826 ignore_debounce,
3827 cx,
3828 ) {
3829 self.splice_inlays(&to_remove, to_insert, cx);
3830 }
3831 }
3832
3833 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3834 self.display_map
3835 .read(cx)
3836 .current_inlays()
3837 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3838 .cloned()
3839 .collect()
3840 }
3841
3842 pub fn excerpts_for_inlay_hints_query(
3843 &self,
3844 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3845 cx: &mut Context<Editor>,
3846 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3847 let Some(project) = self.project.as_ref() else {
3848 return HashMap::default();
3849 };
3850 let project = project.read(cx);
3851 let multi_buffer = self.buffer().read(cx);
3852 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3853 let multi_buffer_visible_start = self
3854 .scroll_manager
3855 .anchor()
3856 .anchor
3857 .to_point(&multi_buffer_snapshot);
3858 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3859 multi_buffer_visible_start
3860 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3861 Bias::Left,
3862 );
3863 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3864 multi_buffer_snapshot
3865 .range_to_buffer_ranges(multi_buffer_visible_range)
3866 .into_iter()
3867 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3868 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3869 let buffer_file = project::File::from_dyn(buffer.file())?;
3870 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3871 let worktree_entry = buffer_worktree
3872 .read(cx)
3873 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3874 if worktree_entry.is_ignored {
3875 return None;
3876 }
3877
3878 let language = buffer.language()?;
3879 if let Some(restrict_to_languages) = restrict_to_languages {
3880 if !restrict_to_languages.contains(language) {
3881 return None;
3882 }
3883 }
3884 Some((
3885 excerpt_id,
3886 (
3887 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3888 buffer.version().clone(),
3889 excerpt_visible_range,
3890 ),
3891 ))
3892 })
3893 .collect()
3894 }
3895
3896 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3897 TextLayoutDetails {
3898 text_system: window.text_system().clone(),
3899 editor_style: self.style.clone().unwrap(),
3900 rem_size: window.rem_size(),
3901 scroll_anchor: self.scroll_manager.anchor(),
3902 visible_rows: self.visible_line_count(),
3903 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3904 }
3905 }
3906
3907 pub fn splice_inlays(
3908 &self,
3909 to_remove: &[InlayId],
3910 to_insert: Vec<Inlay>,
3911 cx: &mut Context<Self>,
3912 ) {
3913 self.display_map.update(cx, |display_map, cx| {
3914 display_map.splice_inlays(to_remove, to_insert, cx)
3915 });
3916 cx.notify();
3917 }
3918
3919 fn trigger_on_type_formatting(
3920 &self,
3921 input: String,
3922 window: &mut Window,
3923 cx: &mut Context<Self>,
3924 ) -> Option<Task<Result<()>>> {
3925 if input.len() != 1 {
3926 return None;
3927 }
3928
3929 let project = self.project.as_ref()?;
3930 let position = self.selections.newest_anchor().head();
3931 let (buffer, buffer_position) = self
3932 .buffer
3933 .read(cx)
3934 .text_anchor_for_position(position, cx)?;
3935
3936 let settings = language_settings::language_settings(
3937 buffer
3938 .read(cx)
3939 .language_at(buffer_position)
3940 .map(|l| l.name()),
3941 buffer.read(cx).file(),
3942 cx,
3943 );
3944 if !settings.use_on_type_format {
3945 return None;
3946 }
3947
3948 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3949 // hence we do LSP request & edit on host side only — add formats to host's history.
3950 let push_to_lsp_host_history = true;
3951 // If this is not the host, append its history with new edits.
3952 let push_to_client_history = project.read(cx).is_via_collab();
3953
3954 let on_type_formatting = project.update(cx, |project, cx| {
3955 project.on_type_format(
3956 buffer.clone(),
3957 buffer_position,
3958 input,
3959 push_to_lsp_host_history,
3960 cx,
3961 )
3962 });
3963 Some(cx.spawn_in(window, |editor, mut cx| async move {
3964 if let Some(transaction) = on_type_formatting.await? {
3965 if push_to_client_history {
3966 buffer
3967 .update(&mut cx, |buffer, _| {
3968 buffer.push_transaction(transaction, Instant::now());
3969 })
3970 .ok();
3971 }
3972 editor.update(&mut cx, |editor, cx| {
3973 editor.refresh_document_highlights(cx);
3974 })?;
3975 }
3976 Ok(())
3977 }))
3978 }
3979
3980 pub fn show_word_completions(
3981 &mut self,
3982 _: &ShowWordCompletions,
3983 window: &mut Window,
3984 cx: &mut Context<Self>,
3985 ) {
3986 self.open_completions_menu(true, None, window, cx);
3987 }
3988
3989 pub fn show_completions(
3990 &mut self,
3991 options: &ShowCompletions,
3992 window: &mut Window,
3993 cx: &mut Context<Self>,
3994 ) {
3995 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
3996 }
3997
3998 fn open_completions_menu(
3999 &mut self,
4000 ignore_completion_provider: bool,
4001 trigger: Option<&str>,
4002 window: &mut Window,
4003 cx: &mut Context<Self>,
4004 ) {
4005 if self.pending_rename.is_some() {
4006 return;
4007 }
4008 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4009 return;
4010 }
4011
4012 let position = self.selections.newest_anchor().head();
4013 if position.diff_base_anchor.is_some() {
4014 return;
4015 }
4016 let (buffer, buffer_position) =
4017 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4018 output
4019 } else {
4020 return;
4021 };
4022 let buffer_snapshot = buffer.read(cx).snapshot();
4023 let show_completion_documentation = buffer_snapshot
4024 .settings_at(buffer_position, cx)
4025 .show_completion_documentation;
4026
4027 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4028
4029 let trigger_kind = match trigger {
4030 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4031 CompletionTriggerKind::TRIGGER_CHARACTER
4032 }
4033 _ => CompletionTriggerKind::INVOKED,
4034 };
4035 let completion_context = CompletionContext {
4036 trigger_character: trigger.and_then(|trigger| {
4037 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4038 Some(String::from(trigger))
4039 } else {
4040 None
4041 }
4042 }),
4043 trigger_kind,
4044 };
4045
4046 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4047 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4048 let word_to_exclude = buffer_snapshot
4049 .text_for_range(old_range.clone())
4050 .collect::<String>();
4051 (
4052 buffer_snapshot.anchor_before(old_range.start)
4053 ..buffer_snapshot.anchor_after(old_range.end),
4054 Some(word_to_exclude),
4055 )
4056 } else {
4057 (buffer_position..buffer_position, None)
4058 };
4059
4060 let completion_settings = language_settings(
4061 buffer_snapshot
4062 .language_at(buffer_position)
4063 .map(|language| language.name()),
4064 buffer_snapshot.file(),
4065 cx,
4066 )
4067 .completions;
4068
4069 // The document can be large, so stay in reasonable bounds when searching for words,
4070 // otherwise completion pop-up might be slow to appear.
4071 const WORD_LOOKUP_ROWS: u32 = 5_000;
4072 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4073 let min_word_search = buffer_snapshot.clip_point(
4074 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4075 Bias::Left,
4076 );
4077 let max_word_search = buffer_snapshot.clip_point(
4078 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4079 Bias::Right,
4080 );
4081 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4082 ..buffer_snapshot.point_to_offset(max_word_search);
4083
4084 let provider = self
4085 .completion_provider
4086 .as_ref()
4087 .filter(|_| !ignore_completion_provider);
4088 let skip_digits = query
4089 .as_ref()
4090 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4091
4092 let (mut words, provided_completions) = match provider {
4093 Some(provider) => {
4094 let completions =
4095 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4096
4097 let words = match completion_settings.words {
4098 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4099 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4100 .background_spawn(async move {
4101 buffer_snapshot.words_in_range(WordsQuery {
4102 fuzzy_contents: None,
4103 range: word_search_range,
4104 skip_digits,
4105 })
4106 }),
4107 };
4108
4109 (words, completions)
4110 }
4111 None => (
4112 cx.background_spawn(async move {
4113 buffer_snapshot.words_in_range(WordsQuery {
4114 fuzzy_contents: None,
4115 range: word_search_range,
4116 skip_digits,
4117 })
4118 }),
4119 Task::ready(Ok(None)),
4120 ),
4121 };
4122
4123 let sort_completions = provider
4124 .as_ref()
4125 .map_or(true, |provider| provider.sort_completions());
4126
4127 let id = post_inc(&mut self.next_completion_id);
4128 let task = cx.spawn_in(window, |editor, mut cx| {
4129 async move {
4130 editor.update(&mut cx, |this, _| {
4131 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4132 })?;
4133
4134 let mut completions = Vec::new();
4135 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4136 completions.extend(provided_completions);
4137 if completion_settings.words == WordsCompletionMode::Fallback {
4138 words = Task::ready(HashMap::default());
4139 }
4140 }
4141
4142 let mut words = words.await;
4143 if let Some(word_to_exclude) = &word_to_exclude {
4144 words.remove(word_to_exclude);
4145 }
4146 for lsp_completion in &completions {
4147 words.remove(&lsp_completion.new_text);
4148 }
4149 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4150 old_range: old_range.clone(),
4151 new_text: word.clone(),
4152 label: CodeLabel::plain(word, None),
4153 documentation: None,
4154 source: CompletionSource::BufferWord {
4155 word_range,
4156 resolved: false,
4157 },
4158 confirm: None,
4159 }));
4160
4161 let menu = if completions.is_empty() {
4162 None
4163 } else {
4164 let mut menu = CompletionsMenu::new(
4165 id,
4166 sort_completions,
4167 show_completion_documentation,
4168 position,
4169 buffer.clone(),
4170 completions.into(),
4171 );
4172
4173 menu.filter(query.as_deref(), cx.background_executor().clone())
4174 .await;
4175
4176 menu.visible().then_some(menu)
4177 };
4178
4179 editor.update_in(&mut cx, |editor, window, cx| {
4180 match editor.context_menu.borrow().as_ref() {
4181 None => {}
4182 Some(CodeContextMenu::Completions(prev_menu)) => {
4183 if prev_menu.id > id {
4184 return;
4185 }
4186 }
4187 _ => return,
4188 }
4189
4190 if editor.focus_handle.is_focused(window) && menu.is_some() {
4191 let mut menu = menu.unwrap();
4192 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4193
4194 *editor.context_menu.borrow_mut() =
4195 Some(CodeContextMenu::Completions(menu));
4196
4197 if editor.show_edit_predictions_in_menu() {
4198 editor.update_visible_inline_completion(window, cx);
4199 } else {
4200 editor.discard_inline_completion(false, cx);
4201 }
4202
4203 cx.notify();
4204 } else if editor.completion_tasks.len() <= 1 {
4205 // If there are no more completion tasks and the last menu was
4206 // empty, we should hide it.
4207 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4208 // If it was already hidden and we don't show inline
4209 // completions in the menu, we should also show the
4210 // inline-completion when available.
4211 if was_hidden && editor.show_edit_predictions_in_menu() {
4212 editor.update_visible_inline_completion(window, cx);
4213 }
4214 }
4215 })?;
4216
4217 anyhow::Ok(())
4218 }
4219 .log_err()
4220 });
4221
4222 self.completion_tasks.push((id, task));
4223 }
4224
4225 pub fn confirm_completion(
4226 &mut self,
4227 action: &ConfirmCompletion,
4228 window: &mut Window,
4229 cx: &mut Context<Self>,
4230 ) -> Option<Task<Result<()>>> {
4231 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4232 }
4233
4234 pub fn compose_completion(
4235 &mut self,
4236 action: &ComposeCompletion,
4237 window: &mut Window,
4238 cx: &mut Context<Self>,
4239 ) -> Option<Task<Result<()>>> {
4240 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4241 }
4242
4243 fn do_completion(
4244 &mut self,
4245 item_ix: Option<usize>,
4246 intent: CompletionIntent,
4247 window: &mut Window,
4248 cx: &mut Context<Editor>,
4249 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4250 use language::ToOffset as _;
4251
4252 let completions_menu =
4253 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4254 menu
4255 } else {
4256 return None;
4257 };
4258
4259 let entries = completions_menu.entries.borrow();
4260 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4261 if self.show_edit_predictions_in_menu() {
4262 self.discard_inline_completion(true, cx);
4263 }
4264 let candidate_id = mat.candidate_id;
4265 drop(entries);
4266
4267 let buffer_handle = completions_menu.buffer;
4268 let completion = completions_menu
4269 .completions
4270 .borrow()
4271 .get(candidate_id)?
4272 .clone();
4273 cx.stop_propagation();
4274
4275 let snippet;
4276 let text;
4277
4278 if completion.is_snippet() {
4279 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4280 text = snippet.as_ref().unwrap().text.clone();
4281 } else {
4282 snippet = None;
4283 text = completion.new_text.clone();
4284 };
4285 let selections = self.selections.all::<usize>(cx);
4286 let buffer = buffer_handle.read(cx);
4287 let old_range = completion.old_range.to_offset(buffer);
4288 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4289
4290 let newest_selection = self.selections.newest_anchor();
4291 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4292 return None;
4293 }
4294
4295 let lookbehind = newest_selection
4296 .start
4297 .text_anchor
4298 .to_offset(buffer)
4299 .saturating_sub(old_range.start);
4300 let lookahead = old_range
4301 .end
4302 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4303 let mut common_prefix_len = old_text
4304 .bytes()
4305 .zip(text.bytes())
4306 .take_while(|(a, b)| a == b)
4307 .count();
4308
4309 let snapshot = self.buffer.read(cx).snapshot(cx);
4310 let mut range_to_replace: Option<Range<isize>> = None;
4311 let mut ranges = Vec::new();
4312 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4313 for selection in &selections {
4314 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4315 let start = selection.start.saturating_sub(lookbehind);
4316 let end = selection.end + lookahead;
4317 if selection.id == newest_selection.id {
4318 range_to_replace = Some(
4319 ((start + common_prefix_len) as isize - selection.start as isize)
4320 ..(end as isize - selection.start as isize),
4321 );
4322 }
4323 ranges.push(start + common_prefix_len..end);
4324 } else {
4325 common_prefix_len = 0;
4326 ranges.clear();
4327 ranges.extend(selections.iter().map(|s| {
4328 if s.id == newest_selection.id {
4329 range_to_replace = Some(
4330 old_range.start.to_offset_utf16(&snapshot).0 as isize
4331 - selection.start as isize
4332 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4333 - selection.start as isize,
4334 );
4335 old_range.clone()
4336 } else {
4337 s.start..s.end
4338 }
4339 }));
4340 break;
4341 }
4342 if !self.linked_edit_ranges.is_empty() {
4343 let start_anchor = snapshot.anchor_before(selection.head());
4344 let end_anchor = snapshot.anchor_after(selection.tail());
4345 if let Some(ranges) = self
4346 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4347 {
4348 for (buffer, edits) in ranges {
4349 linked_edits.entry(buffer.clone()).or_default().extend(
4350 edits
4351 .into_iter()
4352 .map(|range| (range, text[common_prefix_len..].to_owned())),
4353 );
4354 }
4355 }
4356 }
4357 }
4358 let text = &text[common_prefix_len..];
4359
4360 cx.emit(EditorEvent::InputHandled {
4361 utf16_range_to_replace: range_to_replace,
4362 text: text.into(),
4363 });
4364
4365 self.transact(window, cx, |this, window, cx| {
4366 if let Some(mut snippet) = snippet {
4367 snippet.text = text.to_string();
4368 for tabstop in snippet
4369 .tabstops
4370 .iter_mut()
4371 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4372 {
4373 tabstop.start -= common_prefix_len as isize;
4374 tabstop.end -= common_prefix_len as isize;
4375 }
4376
4377 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4378 } else {
4379 this.buffer.update(cx, |buffer, cx| {
4380 buffer.edit(
4381 ranges.iter().map(|range| (range.clone(), text)),
4382 this.autoindent_mode.clone(),
4383 cx,
4384 );
4385 });
4386 }
4387 for (buffer, edits) in linked_edits {
4388 buffer.update(cx, |buffer, cx| {
4389 let snapshot = buffer.snapshot();
4390 let edits = edits
4391 .into_iter()
4392 .map(|(range, text)| {
4393 use text::ToPoint as TP;
4394 let end_point = TP::to_point(&range.end, &snapshot);
4395 let start_point = TP::to_point(&range.start, &snapshot);
4396 (start_point..end_point, text)
4397 })
4398 .sorted_by_key(|(range, _)| range.start)
4399 .collect::<Vec<_>>();
4400 buffer.edit(edits, None, cx);
4401 })
4402 }
4403
4404 this.refresh_inline_completion(true, false, window, cx);
4405 });
4406
4407 let show_new_completions_on_confirm = completion
4408 .confirm
4409 .as_ref()
4410 .map_or(false, |confirm| confirm(intent, window, cx));
4411 if show_new_completions_on_confirm {
4412 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4413 }
4414
4415 let provider = self.completion_provider.as_ref()?;
4416 drop(completion);
4417 let apply_edits = provider.apply_additional_edits_for_completion(
4418 buffer_handle,
4419 completions_menu.completions.clone(),
4420 candidate_id,
4421 true,
4422 cx,
4423 );
4424
4425 let editor_settings = EditorSettings::get_global(cx);
4426 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4427 // After the code completion is finished, users often want to know what signatures are needed.
4428 // so we should automatically call signature_help
4429 self.show_signature_help(&ShowSignatureHelp, window, cx);
4430 }
4431
4432 Some(cx.foreground_executor().spawn(async move {
4433 apply_edits.await?;
4434 Ok(())
4435 }))
4436 }
4437
4438 pub fn toggle_code_actions(
4439 &mut self,
4440 action: &ToggleCodeActions,
4441 window: &mut Window,
4442 cx: &mut Context<Self>,
4443 ) {
4444 let mut context_menu = self.context_menu.borrow_mut();
4445 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4446 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4447 // Toggle if we're selecting the same one
4448 *context_menu = None;
4449 cx.notify();
4450 return;
4451 } else {
4452 // Otherwise, clear it and start a new one
4453 *context_menu = None;
4454 cx.notify();
4455 }
4456 }
4457 drop(context_menu);
4458 let snapshot = self.snapshot(window, cx);
4459 let deployed_from_indicator = action.deployed_from_indicator;
4460 let mut task = self.code_actions_task.take();
4461 let action = action.clone();
4462 cx.spawn_in(window, |editor, mut cx| async move {
4463 while let Some(prev_task) = task {
4464 prev_task.await.log_err();
4465 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4466 }
4467
4468 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4469 if editor.focus_handle.is_focused(window) {
4470 let multibuffer_point = action
4471 .deployed_from_indicator
4472 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4473 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4474 let (buffer, buffer_row) = snapshot
4475 .buffer_snapshot
4476 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4477 .and_then(|(buffer_snapshot, range)| {
4478 editor
4479 .buffer
4480 .read(cx)
4481 .buffer(buffer_snapshot.remote_id())
4482 .map(|buffer| (buffer, range.start.row))
4483 })?;
4484 let (_, code_actions) = editor
4485 .available_code_actions
4486 .clone()
4487 .and_then(|(location, code_actions)| {
4488 let snapshot = location.buffer.read(cx).snapshot();
4489 let point_range = location.range.to_point(&snapshot);
4490 let point_range = point_range.start.row..=point_range.end.row;
4491 if point_range.contains(&buffer_row) {
4492 Some((location, code_actions))
4493 } else {
4494 None
4495 }
4496 })
4497 .unzip();
4498 let buffer_id = buffer.read(cx).remote_id();
4499 let tasks = editor
4500 .tasks
4501 .get(&(buffer_id, buffer_row))
4502 .map(|t| Arc::new(t.to_owned()));
4503 if tasks.is_none() && code_actions.is_none() {
4504 return None;
4505 }
4506
4507 editor.completion_tasks.clear();
4508 editor.discard_inline_completion(false, cx);
4509 let task_context =
4510 tasks
4511 .as_ref()
4512 .zip(editor.project.clone())
4513 .map(|(tasks, project)| {
4514 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4515 });
4516
4517 Some(cx.spawn_in(window, |editor, mut cx| async move {
4518 let task_context = match task_context {
4519 Some(task_context) => task_context.await,
4520 None => None,
4521 };
4522 let resolved_tasks =
4523 tasks.zip(task_context).map(|(tasks, task_context)| {
4524 Rc::new(ResolvedTasks {
4525 templates: tasks.resolve(&task_context).collect(),
4526 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4527 multibuffer_point.row,
4528 tasks.column,
4529 )),
4530 })
4531 });
4532 let spawn_straight_away = resolved_tasks
4533 .as_ref()
4534 .map_or(false, |tasks| tasks.templates.len() == 1)
4535 && code_actions
4536 .as_ref()
4537 .map_or(true, |actions| actions.is_empty());
4538 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4539 *editor.context_menu.borrow_mut() =
4540 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4541 buffer,
4542 actions: CodeActionContents {
4543 tasks: resolved_tasks,
4544 actions: code_actions,
4545 },
4546 selected_item: Default::default(),
4547 scroll_handle: UniformListScrollHandle::default(),
4548 deployed_from_indicator,
4549 }));
4550 if spawn_straight_away {
4551 if let Some(task) = editor.confirm_code_action(
4552 &ConfirmCodeAction { item_ix: Some(0) },
4553 window,
4554 cx,
4555 ) {
4556 cx.notify();
4557 return task;
4558 }
4559 }
4560 cx.notify();
4561 Task::ready(Ok(()))
4562 }) {
4563 task.await
4564 } else {
4565 Ok(())
4566 }
4567 }))
4568 } else {
4569 Some(Task::ready(Ok(())))
4570 }
4571 })?;
4572 if let Some(task) = spawned_test_task {
4573 task.await?;
4574 }
4575
4576 Ok::<_, anyhow::Error>(())
4577 })
4578 .detach_and_log_err(cx);
4579 }
4580
4581 pub fn confirm_code_action(
4582 &mut self,
4583 action: &ConfirmCodeAction,
4584 window: &mut Window,
4585 cx: &mut Context<Self>,
4586 ) -> Option<Task<Result<()>>> {
4587 let actions_menu =
4588 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4589 menu
4590 } else {
4591 return None;
4592 };
4593 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4594 let action = actions_menu.actions.get(action_ix)?;
4595 let title = action.label();
4596 let buffer = actions_menu.buffer;
4597 let workspace = self.workspace()?;
4598
4599 match action {
4600 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4601 workspace.update(cx, |workspace, cx| {
4602 workspace::tasks::schedule_resolved_task(
4603 workspace,
4604 task_source_kind,
4605 resolved_task,
4606 false,
4607 cx,
4608 );
4609
4610 Some(Task::ready(Ok(())))
4611 })
4612 }
4613 CodeActionsItem::CodeAction {
4614 excerpt_id,
4615 action,
4616 provider,
4617 } => {
4618 let apply_code_action =
4619 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4620 let workspace = workspace.downgrade();
4621 Some(cx.spawn_in(window, |editor, cx| async move {
4622 let project_transaction = apply_code_action.await?;
4623 Self::open_project_transaction(
4624 &editor,
4625 workspace,
4626 project_transaction,
4627 title,
4628 cx,
4629 )
4630 .await
4631 }))
4632 }
4633 }
4634 }
4635
4636 pub async fn open_project_transaction(
4637 this: &WeakEntity<Editor>,
4638 workspace: WeakEntity<Workspace>,
4639 transaction: ProjectTransaction,
4640 title: String,
4641 mut cx: AsyncWindowContext,
4642 ) -> Result<()> {
4643 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4644 cx.update(|_, cx| {
4645 entries.sort_unstable_by_key(|(buffer, _)| {
4646 buffer.read(cx).file().map(|f| f.path().clone())
4647 });
4648 })?;
4649
4650 // If the project transaction's edits are all contained within this editor, then
4651 // avoid opening a new editor to display them.
4652
4653 if let Some((buffer, transaction)) = entries.first() {
4654 if entries.len() == 1 {
4655 let excerpt = this.update(&mut cx, |editor, cx| {
4656 editor
4657 .buffer()
4658 .read(cx)
4659 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4660 })?;
4661 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4662 if excerpted_buffer == *buffer {
4663 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4664 let excerpt_range = excerpt_range.to_offset(buffer);
4665 buffer
4666 .edited_ranges_for_transaction::<usize>(transaction)
4667 .all(|range| {
4668 excerpt_range.start <= range.start
4669 && excerpt_range.end >= range.end
4670 })
4671 })?;
4672
4673 if all_edits_within_excerpt {
4674 return Ok(());
4675 }
4676 }
4677 }
4678 }
4679 } else {
4680 return Ok(());
4681 }
4682
4683 let mut ranges_to_highlight = Vec::new();
4684 let excerpt_buffer = cx.new(|cx| {
4685 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4686 for (buffer_handle, transaction) in &entries {
4687 let buffer = buffer_handle.read(cx);
4688 ranges_to_highlight.extend(
4689 multibuffer.push_excerpts_with_context_lines(
4690 buffer_handle.clone(),
4691 buffer
4692 .edited_ranges_for_transaction::<usize>(transaction)
4693 .collect(),
4694 DEFAULT_MULTIBUFFER_CONTEXT,
4695 cx,
4696 ),
4697 );
4698 }
4699 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4700 multibuffer
4701 })?;
4702
4703 workspace.update_in(&mut cx, |workspace, window, cx| {
4704 let project = workspace.project().clone();
4705 let editor =
4706 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
4707 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4708 editor.update(cx, |editor, cx| {
4709 editor.highlight_background::<Self>(
4710 &ranges_to_highlight,
4711 |theme| theme.editor_highlighted_line_background,
4712 cx,
4713 );
4714 });
4715 })?;
4716
4717 Ok(())
4718 }
4719
4720 pub fn clear_code_action_providers(&mut self) {
4721 self.code_action_providers.clear();
4722 self.available_code_actions.take();
4723 }
4724
4725 pub fn add_code_action_provider(
4726 &mut self,
4727 provider: Rc<dyn CodeActionProvider>,
4728 window: &mut Window,
4729 cx: &mut Context<Self>,
4730 ) {
4731 if self
4732 .code_action_providers
4733 .iter()
4734 .any(|existing_provider| existing_provider.id() == provider.id())
4735 {
4736 return;
4737 }
4738
4739 self.code_action_providers.push(provider);
4740 self.refresh_code_actions(window, cx);
4741 }
4742
4743 pub fn remove_code_action_provider(
4744 &mut self,
4745 id: Arc<str>,
4746 window: &mut Window,
4747 cx: &mut Context<Self>,
4748 ) {
4749 self.code_action_providers
4750 .retain(|provider| provider.id() != id);
4751 self.refresh_code_actions(window, cx);
4752 }
4753
4754 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4755 let buffer = self.buffer.read(cx);
4756 let newest_selection = self.selections.newest_anchor().clone();
4757 if newest_selection.head().diff_base_anchor.is_some() {
4758 return None;
4759 }
4760 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4761 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4762 if start_buffer != end_buffer {
4763 return None;
4764 }
4765
4766 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4767 cx.background_executor()
4768 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4769 .await;
4770
4771 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4772 let providers = this.code_action_providers.clone();
4773 let tasks = this
4774 .code_action_providers
4775 .iter()
4776 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4777 .collect::<Vec<_>>();
4778 (providers, tasks)
4779 })?;
4780
4781 let mut actions = Vec::new();
4782 for (provider, provider_actions) in
4783 providers.into_iter().zip(future::join_all(tasks).await)
4784 {
4785 if let Some(provider_actions) = provider_actions.log_err() {
4786 actions.extend(provider_actions.into_iter().map(|action| {
4787 AvailableCodeAction {
4788 excerpt_id: newest_selection.start.excerpt_id,
4789 action,
4790 provider: provider.clone(),
4791 }
4792 }));
4793 }
4794 }
4795
4796 this.update(&mut cx, |this, cx| {
4797 this.available_code_actions = if actions.is_empty() {
4798 None
4799 } else {
4800 Some((
4801 Location {
4802 buffer: start_buffer,
4803 range: start..end,
4804 },
4805 actions.into(),
4806 ))
4807 };
4808 cx.notify();
4809 })
4810 }));
4811 None
4812 }
4813
4814 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4815 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4816 self.show_git_blame_inline = false;
4817
4818 self.show_git_blame_inline_delay_task =
4819 Some(cx.spawn_in(window, |this, mut cx| async move {
4820 cx.background_executor().timer(delay).await;
4821
4822 this.update(&mut cx, |this, cx| {
4823 this.show_git_blame_inline = true;
4824 cx.notify();
4825 })
4826 .log_err();
4827 }));
4828 }
4829 }
4830
4831 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4832 if self.pending_rename.is_some() {
4833 return None;
4834 }
4835
4836 let provider = self.semantics_provider.clone()?;
4837 let buffer = self.buffer.read(cx);
4838 let newest_selection = self.selections.newest_anchor().clone();
4839 let cursor_position = newest_selection.head();
4840 let (cursor_buffer, cursor_buffer_position) =
4841 buffer.text_anchor_for_position(cursor_position, cx)?;
4842 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4843 if cursor_buffer != tail_buffer {
4844 return None;
4845 }
4846 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4847 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4848 cx.background_executor()
4849 .timer(Duration::from_millis(debounce))
4850 .await;
4851
4852 let highlights = if let Some(highlights) = cx
4853 .update(|cx| {
4854 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4855 })
4856 .ok()
4857 .flatten()
4858 {
4859 highlights.await.log_err()
4860 } else {
4861 None
4862 };
4863
4864 if let Some(highlights) = highlights {
4865 this.update(&mut cx, |this, cx| {
4866 if this.pending_rename.is_some() {
4867 return;
4868 }
4869
4870 let buffer_id = cursor_position.buffer_id;
4871 let buffer = this.buffer.read(cx);
4872 if !buffer
4873 .text_anchor_for_position(cursor_position, cx)
4874 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4875 {
4876 return;
4877 }
4878
4879 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4880 let mut write_ranges = Vec::new();
4881 let mut read_ranges = Vec::new();
4882 for highlight in highlights {
4883 for (excerpt_id, excerpt_range) in
4884 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4885 {
4886 let start = highlight
4887 .range
4888 .start
4889 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4890 let end = highlight
4891 .range
4892 .end
4893 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4894 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4895 continue;
4896 }
4897
4898 let range = Anchor {
4899 buffer_id,
4900 excerpt_id,
4901 text_anchor: start,
4902 diff_base_anchor: None,
4903 }..Anchor {
4904 buffer_id,
4905 excerpt_id,
4906 text_anchor: end,
4907 diff_base_anchor: None,
4908 };
4909 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4910 write_ranges.push(range);
4911 } else {
4912 read_ranges.push(range);
4913 }
4914 }
4915 }
4916
4917 this.highlight_background::<DocumentHighlightRead>(
4918 &read_ranges,
4919 |theme| theme.editor_document_highlight_read_background,
4920 cx,
4921 );
4922 this.highlight_background::<DocumentHighlightWrite>(
4923 &write_ranges,
4924 |theme| theme.editor_document_highlight_write_background,
4925 cx,
4926 );
4927 cx.notify();
4928 })
4929 .log_err();
4930 }
4931 }));
4932 None
4933 }
4934
4935 pub fn refresh_selected_text_highlights(
4936 &mut self,
4937 window: &mut Window,
4938 cx: &mut Context<Editor>,
4939 ) {
4940 self.selection_highlight_task.take();
4941 if !EditorSettings::get_global(cx).selection_highlight {
4942 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4943 return;
4944 }
4945 if self.selections.count() != 1 || self.selections.line_mode {
4946 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4947 return;
4948 }
4949 let selection = self.selections.newest::<Point>(cx);
4950 if selection.is_empty() || selection.start.row != selection.end.row {
4951 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4952 return;
4953 }
4954 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4955 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4956 cx.background_executor()
4957 .timer(Duration::from_millis(debounce))
4958 .await;
4959 let Some(Some(matches_task)) = editor
4960 .update_in(&mut cx, |editor, _, cx| {
4961 if editor.selections.count() != 1 || editor.selections.line_mode {
4962 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4963 return None;
4964 }
4965 let selection = editor.selections.newest::<Point>(cx);
4966 if selection.is_empty() || selection.start.row != selection.end.row {
4967 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4968 return None;
4969 }
4970 let buffer = editor.buffer().read(cx).snapshot(cx);
4971 let query = buffer.text_for_range(selection.range()).collect::<String>();
4972 if query.trim().is_empty() {
4973 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4974 return None;
4975 }
4976 Some(cx.background_spawn(async move {
4977 let mut ranges = Vec::new();
4978 let selection_anchors = selection.range().to_anchors(&buffer);
4979 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4980 for (search_buffer, search_range, excerpt_id) in
4981 buffer.range_to_buffer_ranges(range)
4982 {
4983 ranges.extend(
4984 project::search::SearchQuery::text(
4985 query.clone(),
4986 false,
4987 false,
4988 false,
4989 Default::default(),
4990 Default::default(),
4991 None,
4992 )
4993 .unwrap()
4994 .search(search_buffer, Some(search_range.clone()))
4995 .await
4996 .into_iter()
4997 .filter_map(
4998 |match_range| {
4999 let start = search_buffer.anchor_after(
5000 search_range.start + match_range.start,
5001 );
5002 let end = search_buffer.anchor_before(
5003 search_range.start + match_range.end,
5004 );
5005 let range = Anchor::range_in_buffer(
5006 excerpt_id,
5007 search_buffer.remote_id(),
5008 start..end,
5009 );
5010 (range != selection_anchors).then_some(range)
5011 },
5012 ),
5013 );
5014 }
5015 }
5016 ranges
5017 }))
5018 })
5019 .log_err()
5020 else {
5021 return;
5022 };
5023 let matches = matches_task.await;
5024 editor
5025 .update_in(&mut cx, |editor, _, cx| {
5026 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5027 if !matches.is_empty() {
5028 editor.highlight_background::<SelectedTextHighlight>(
5029 &matches,
5030 |theme| theme.editor_document_highlight_bracket_background,
5031 cx,
5032 )
5033 }
5034 })
5035 .log_err();
5036 }));
5037 }
5038
5039 pub fn refresh_inline_completion(
5040 &mut self,
5041 debounce: bool,
5042 user_requested: bool,
5043 window: &mut Window,
5044 cx: &mut Context<Self>,
5045 ) -> Option<()> {
5046 let provider = self.edit_prediction_provider()?;
5047 let cursor = self.selections.newest_anchor().head();
5048 let (buffer, cursor_buffer_position) =
5049 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5050
5051 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5052 self.discard_inline_completion(false, cx);
5053 return None;
5054 }
5055
5056 if !user_requested
5057 && (!self.should_show_edit_predictions()
5058 || !self.is_focused(window)
5059 || buffer.read(cx).is_empty())
5060 {
5061 self.discard_inline_completion(false, cx);
5062 return None;
5063 }
5064
5065 self.update_visible_inline_completion(window, cx);
5066 provider.refresh(
5067 self.project.clone(),
5068 buffer,
5069 cursor_buffer_position,
5070 debounce,
5071 cx,
5072 );
5073 Some(())
5074 }
5075
5076 fn show_edit_predictions_in_menu(&self) -> bool {
5077 match self.edit_prediction_settings {
5078 EditPredictionSettings::Disabled => false,
5079 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5080 }
5081 }
5082
5083 pub fn edit_predictions_enabled(&self) -> bool {
5084 match self.edit_prediction_settings {
5085 EditPredictionSettings::Disabled => false,
5086 EditPredictionSettings::Enabled { .. } => true,
5087 }
5088 }
5089
5090 fn edit_prediction_requires_modifier(&self) -> bool {
5091 match self.edit_prediction_settings {
5092 EditPredictionSettings::Disabled => false,
5093 EditPredictionSettings::Enabled {
5094 preview_requires_modifier,
5095 ..
5096 } => preview_requires_modifier,
5097 }
5098 }
5099
5100 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5101 if self.edit_prediction_provider.is_none() {
5102 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5103 } else {
5104 let selection = self.selections.newest_anchor();
5105 let cursor = selection.head();
5106
5107 if let Some((buffer, cursor_buffer_position)) =
5108 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5109 {
5110 self.edit_prediction_settings =
5111 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5112 }
5113 }
5114 }
5115
5116 fn edit_prediction_settings_at_position(
5117 &self,
5118 buffer: &Entity<Buffer>,
5119 buffer_position: language::Anchor,
5120 cx: &App,
5121 ) -> EditPredictionSettings {
5122 if self.mode != EditorMode::Full
5123 || !self.show_inline_completions_override.unwrap_or(true)
5124 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5125 {
5126 return EditPredictionSettings::Disabled;
5127 }
5128
5129 let buffer = buffer.read(cx);
5130
5131 let file = buffer.file();
5132
5133 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5134 return EditPredictionSettings::Disabled;
5135 };
5136
5137 let by_provider = matches!(
5138 self.menu_inline_completions_policy,
5139 MenuInlineCompletionsPolicy::ByProvider
5140 );
5141
5142 let show_in_menu = by_provider
5143 && self
5144 .edit_prediction_provider
5145 .as_ref()
5146 .map_or(false, |provider| {
5147 provider.provider.show_completions_in_menu()
5148 });
5149
5150 let preview_requires_modifier =
5151 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5152
5153 EditPredictionSettings::Enabled {
5154 show_in_menu,
5155 preview_requires_modifier,
5156 }
5157 }
5158
5159 fn should_show_edit_predictions(&self) -> bool {
5160 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5161 }
5162
5163 pub fn edit_prediction_preview_is_active(&self) -> bool {
5164 matches!(
5165 self.edit_prediction_preview,
5166 EditPredictionPreview::Active { .. }
5167 )
5168 }
5169
5170 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5171 let cursor = self.selections.newest_anchor().head();
5172 if let Some((buffer, cursor_position)) =
5173 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5174 {
5175 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5176 } else {
5177 false
5178 }
5179 }
5180
5181 fn edit_predictions_enabled_in_buffer(
5182 &self,
5183 buffer: &Entity<Buffer>,
5184 buffer_position: language::Anchor,
5185 cx: &App,
5186 ) -> bool {
5187 maybe!({
5188 let provider = self.edit_prediction_provider()?;
5189 if !provider.is_enabled(&buffer, buffer_position, cx) {
5190 return Some(false);
5191 }
5192 let buffer = buffer.read(cx);
5193 let Some(file) = buffer.file() else {
5194 return Some(true);
5195 };
5196 let settings = all_language_settings(Some(file), cx);
5197 Some(settings.edit_predictions_enabled_for_file(file, cx))
5198 })
5199 .unwrap_or(false)
5200 }
5201
5202 fn cycle_inline_completion(
5203 &mut self,
5204 direction: Direction,
5205 window: &mut Window,
5206 cx: &mut Context<Self>,
5207 ) -> Option<()> {
5208 let provider = self.edit_prediction_provider()?;
5209 let cursor = self.selections.newest_anchor().head();
5210 let (buffer, cursor_buffer_position) =
5211 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5212 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5213 return None;
5214 }
5215
5216 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5217 self.update_visible_inline_completion(window, cx);
5218
5219 Some(())
5220 }
5221
5222 pub fn show_inline_completion(
5223 &mut self,
5224 _: &ShowEditPrediction,
5225 window: &mut Window,
5226 cx: &mut Context<Self>,
5227 ) {
5228 if !self.has_active_inline_completion() {
5229 self.refresh_inline_completion(false, true, window, cx);
5230 return;
5231 }
5232
5233 self.update_visible_inline_completion(window, cx);
5234 }
5235
5236 pub fn display_cursor_names(
5237 &mut self,
5238 _: &DisplayCursorNames,
5239 window: &mut Window,
5240 cx: &mut Context<Self>,
5241 ) {
5242 self.show_cursor_names(window, cx);
5243 }
5244
5245 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5246 self.show_cursor_names = true;
5247 cx.notify();
5248 cx.spawn_in(window, |this, mut cx| async move {
5249 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5250 this.update(&mut cx, |this, cx| {
5251 this.show_cursor_names = false;
5252 cx.notify()
5253 })
5254 .ok()
5255 })
5256 .detach();
5257 }
5258
5259 pub fn next_edit_prediction(
5260 &mut self,
5261 _: &NextEditPrediction,
5262 window: &mut Window,
5263 cx: &mut Context<Self>,
5264 ) {
5265 if self.has_active_inline_completion() {
5266 self.cycle_inline_completion(Direction::Next, window, cx);
5267 } else {
5268 let is_copilot_disabled = self
5269 .refresh_inline_completion(false, true, window, cx)
5270 .is_none();
5271 if is_copilot_disabled {
5272 cx.propagate();
5273 }
5274 }
5275 }
5276
5277 pub fn previous_edit_prediction(
5278 &mut self,
5279 _: &PreviousEditPrediction,
5280 window: &mut Window,
5281 cx: &mut Context<Self>,
5282 ) {
5283 if self.has_active_inline_completion() {
5284 self.cycle_inline_completion(Direction::Prev, window, cx);
5285 } else {
5286 let is_copilot_disabled = self
5287 .refresh_inline_completion(false, true, window, cx)
5288 .is_none();
5289 if is_copilot_disabled {
5290 cx.propagate();
5291 }
5292 }
5293 }
5294
5295 pub fn accept_edit_prediction(
5296 &mut self,
5297 _: &AcceptEditPrediction,
5298 window: &mut Window,
5299 cx: &mut Context<Self>,
5300 ) {
5301 if self.show_edit_predictions_in_menu() {
5302 self.hide_context_menu(window, cx);
5303 }
5304
5305 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5306 return;
5307 };
5308
5309 self.report_inline_completion_event(
5310 active_inline_completion.completion_id.clone(),
5311 true,
5312 cx,
5313 );
5314
5315 match &active_inline_completion.completion {
5316 InlineCompletion::Move { target, .. } => {
5317 let target = *target;
5318
5319 if let Some(position_map) = &self.last_position_map {
5320 if position_map
5321 .visible_row_range
5322 .contains(&target.to_display_point(&position_map.snapshot).row())
5323 || !self.edit_prediction_requires_modifier()
5324 {
5325 self.unfold_ranges(&[target..target], true, false, cx);
5326 // Note that this is also done in vim's handler of the Tab action.
5327 self.change_selections(
5328 Some(Autoscroll::newest()),
5329 window,
5330 cx,
5331 |selections| {
5332 selections.select_anchor_ranges([target..target]);
5333 },
5334 );
5335 self.clear_row_highlights::<EditPredictionPreview>();
5336
5337 self.edit_prediction_preview
5338 .set_previous_scroll_position(None);
5339 } else {
5340 self.edit_prediction_preview
5341 .set_previous_scroll_position(Some(
5342 position_map.snapshot.scroll_anchor,
5343 ));
5344
5345 self.highlight_rows::<EditPredictionPreview>(
5346 target..target,
5347 cx.theme().colors().editor_highlighted_line_background,
5348 true,
5349 cx,
5350 );
5351 self.request_autoscroll(Autoscroll::fit(), cx);
5352 }
5353 }
5354 }
5355 InlineCompletion::Edit { edits, .. } => {
5356 if let Some(provider) = self.edit_prediction_provider() {
5357 provider.accept(cx);
5358 }
5359
5360 let snapshot = self.buffer.read(cx).snapshot(cx);
5361 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5362
5363 self.buffer.update(cx, |buffer, cx| {
5364 buffer.edit(edits.iter().cloned(), None, cx)
5365 });
5366
5367 self.change_selections(None, window, cx, |s| {
5368 s.select_anchor_ranges([last_edit_end..last_edit_end])
5369 });
5370
5371 self.update_visible_inline_completion(window, cx);
5372 if self.active_inline_completion.is_none() {
5373 self.refresh_inline_completion(true, true, window, cx);
5374 }
5375
5376 cx.notify();
5377 }
5378 }
5379
5380 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5381 }
5382
5383 pub fn accept_partial_inline_completion(
5384 &mut self,
5385 _: &AcceptPartialEditPrediction,
5386 window: &mut Window,
5387 cx: &mut Context<Self>,
5388 ) {
5389 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5390 return;
5391 };
5392 if self.selections.count() != 1 {
5393 return;
5394 }
5395
5396 self.report_inline_completion_event(
5397 active_inline_completion.completion_id.clone(),
5398 true,
5399 cx,
5400 );
5401
5402 match &active_inline_completion.completion {
5403 InlineCompletion::Move { target, .. } => {
5404 let target = *target;
5405 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5406 selections.select_anchor_ranges([target..target]);
5407 });
5408 }
5409 InlineCompletion::Edit { edits, .. } => {
5410 // Find an insertion that starts at the cursor position.
5411 let snapshot = self.buffer.read(cx).snapshot(cx);
5412 let cursor_offset = self.selections.newest::<usize>(cx).head();
5413 let insertion = edits.iter().find_map(|(range, text)| {
5414 let range = range.to_offset(&snapshot);
5415 if range.is_empty() && range.start == cursor_offset {
5416 Some(text)
5417 } else {
5418 None
5419 }
5420 });
5421
5422 if let Some(text) = insertion {
5423 let mut partial_completion = text
5424 .chars()
5425 .by_ref()
5426 .take_while(|c| c.is_alphabetic())
5427 .collect::<String>();
5428 if partial_completion.is_empty() {
5429 partial_completion = text
5430 .chars()
5431 .by_ref()
5432 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5433 .collect::<String>();
5434 }
5435
5436 cx.emit(EditorEvent::InputHandled {
5437 utf16_range_to_replace: None,
5438 text: partial_completion.clone().into(),
5439 });
5440
5441 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5442
5443 self.refresh_inline_completion(true, true, window, cx);
5444 cx.notify();
5445 } else {
5446 self.accept_edit_prediction(&Default::default(), window, cx);
5447 }
5448 }
5449 }
5450 }
5451
5452 fn discard_inline_completion(
5453 &mut self,
5454 should_report_inline_completion_event: bool,
5455 cx: &mut Context<Self>,
5456 ) -> bool {
5457 if should_report_inline_completion_event {
5458 let completion_id = self
5459 .active_inline_completion
5460 .as_ref()
5461 .and_then(|active_completion| active_completion.completion_id.clone());
5462
5463 self.report_inline_completion_event(completion_id, false, cx);
5464 }
5465
5466 if let Some(provider) = self.edit_prediction_provider() {
5467 provider.discard(cx);
5468 }
5469
5470 self.take_active_inline_completion(cx)
5471 }
5472
5473 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5474 let Some(provider) = self.edit_prediction_provider() else {
5475 return;
5476 };
5477
5478 let Some((_, buffer, _)) = self
5479 .buffer
5480 .read(cx)
5481 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5482 else {
5483 return;
5484 };
5485
5486 let extension = buffer
5487 .read(cx)
5488 .file()
5489 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5490
5491 let event_type = match accepted {
5492 true => "Edit Prediction Accepted",
5493 false => "Edit Prediction Discarded",
5494 };
5495 telemetry::event!(
5496 event_type,
5497 provider = provider.name(),
5498 prediction_id = id,
5499 suggestion_accepted = accepted,
5500 file_extension = extension,
5501 );
5502 }
5503
5504 pub fn has_active_inline_completion(&self) -> bool {
5505 self.active_inline_completion.is_some()
5506 }
5507
5508 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5509 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5510 return false;
5511 };
5512
5513 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5514 self.clear_highlights::<InlineCompletionHighlight>(cx);
5515 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5516 true
5517 }
5518
5519 /// Returns true when we're displaying the edit prediction popover below the cursor
5520 /// like we are not previewing and the LSP autocomplete menu is visible
5521 /// or we are in `when_holding_modifier` mode.
5522 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5523 if self.edit_prediction_preview_is_active()
5524 || !self.show_edit_predictions_in_menu()
5525 || !self.edit_predictions_enabled()
5526 {
5527 return false;
5528 }
5529
5530 if self.has_visible_completions_menu() {
5531 return true;
5532 }
5533
5534 has_completion && self.edit_prediction_requires_modifier()
5535 }
5536
5537 fn handle_modifiers_changed(
5538 &mut self,
5539 modifiers: Modifiers,
5540 position_map: &PositionMap,
5541 window: &mut Window,
5542 cx: &mut Context<Self>,
5543 ) {
5544 if self.show_edit_predictions_in_menu() {
5545 self.update_edit_prediction_preview(&modifiers, window, cx);
5546 }
5547
5548 self.update_selection_mode(&modifiers, position_map, window, cx);
5549
5550 let mouse_position = window.mouse_position();
5551 if !position_map.text_hitbox.is_hovered(window) {
5552 return;
5553 }
5554
5555 self.update_hovered_link(
5556 position_map.point_for_position(mouse_position),
5557 &position_map.snapshot,
5558 modifiers,
5559 window,
5560 cx,
5561 )
5562 }
5563
5564 fn update_selection_mode(
5565 &mut self,
5566 modifiers: &Modifiers,
5567 position_map: &PositionMap,
5568 window: &mut Window,
5569 cx: &mut Context<Self>,
5570 ) {
5571 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5572 return;
5573 }
5574
5575 let mouse_position = window.mouse_position();
5576 let point_for_position = position_map.point_for_position(mouse_position);
5577 let position = point_for_position.previous_valid;
5578
5579 self.select(
5580 SelectPhase::BeginColumnar {
5581 position,
5582 reset: false,
5583 goal_column: point_for_position.exact_unclipped.column(),
5584 },
5585 window,
5586 cx,
5587 );
5588 }
5589
5590 fn update_edit_prediction_preview(
5591 &mut self,
5592 modifiers: &Modifiers,
5593 window: &mut Window,
5594 cx: &mut Context<Self>,
5595 ) {
5596 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5597 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5598 return;
5599 };
5600
5601 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5602 if matches!(
5603 self.edit_prediction_preview,
5604 EditPredictionPreview::Inactive { .. }
5605 ) {
5606 self.edit_prediction_preview = EditPredictionPreview::Active {
5607 previous_scroll_position: None,
5608 since: Instant::now(),
5609 };
5610
5611 self.update_visible_inline_completion(window, cx);
5612 cx.notify();
5613 }
5614 } else if let EditPredictionPreview::Active {
5615 previous_scroll_position,
5616 since,
5617 } = self.edit_prediction_preview
5618 {
5619 if let (Some(previous_scroll_position), Some(position_map)) =
5620 (previous_scroll_position, self.last_position_map.as_ref())
5621 {
5622 self.set_scroll_position(
5623 previous_scroll_position
5624 .scroll_position(&position_map.snapshot.display_snapshot),
5625 window,
5626 cx,
5627 );
5628 }
5629
5630 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5631 released_too_fast: since.elapsed() < Duration::from_millis(200),
5632 };
5633 self.clear_row_highlights::<EditPredictionPreview>();
5634 self.update_visible_inline_completion(window, cx);
5635 cx.notify();
5636 }
5637 }
5638
5639 fn update_visible_inline_completion(
5640 &mut self,
5641 _window: &mut Window,
5642 cx: &mut Context<Self>,
5643 ) -> Option<()> {
5644 let selection = self.selections.newest_anchor();
5645 let cursor = selection.head();
5646 let multibuffer = self.buffer.read(cx).snapshot(cx);
5647 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5648 let excerpt_id = cursor.excerpt_id;
5649
5650 let show_in_menu = self.show_edit_predictions_in_menu();
5651 let completions_menu_has_precedence = !show_in_menu
5652 && (self.context_menu.borrow().is_some()
5653 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5654
5655 if completions_menu_has_precedence
5656 || !offset_selection.is_empty()
5657 || self
5658 .active_inline_completion
5659 .as_ref()
5660 .map_or(false, |completion| {
5661 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5662 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5663 !invalidation_range.contains(&offset_selection.head())
5664 })
5665 {
5666 self.discard_inline_completion(false, cx);
5667 return None;
5668 }
5669
5670 self.take_active_inline_completion(cx);
5671 let Some(provider) = self.edit_prediction_provider() else {
5672 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5673 return None;
5674 };
5675
5676 let (buffer, cursor_buffer_position) =
5677 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5678
5679 self.edit_prediction_settings =
5680 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5681
5682 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5683
5684 if self.edit_prediction_indent_conflict {
5685 let cursor_point = cursor.to_point(&multibuffer);
5686
5687 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5688
5689 if let Some((_, indent)) = indents.iter().next() {
5690 if indent.len == cursor_point.column {
5691 self.edit_prediction_indent_conflict = false;
5692 }
5693 }
5694 }
5695
5696 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5697 let edits = inline_completion
5698 .edits
5699 .into_iter()
5700 .flat_map(|(range, new_text)| {
5701 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5702 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5703 Some((start..end, new_text))
5704 })
5705 .collect::<Vec<_>>();
5706 if edits.is_empty() {
5707 return None;
5708 }
5709
5710 let first_edit_start = edits.first().unwrap().0.start;
5711 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5712 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5713
5714 let last_edit_end = edits.last().unwrap().0.end;
5715 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5716 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5717
5718 let cursor_row = cursor.to_point(&multibuffer).row;
5719
5720 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5721
5722 let mut inlay_ids = Vec::new();
5723 let invalidation_row_range;
5724 let move_invalidation_row_range = if cursor_row < edit_start_row {
5725 Some(cursor_row..edit_end_row)
5726 } else if cursor_row > edit_end_row {
5727 Some(edit_start_row..cursor_row)
5728 } else {
5729 None
5730 };
5731 let is_move =
5732 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5733 let completion = if is_move {
5734 invalidation_row_range =
5735 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5736 let target = first_edit_start;
5737 InlineCompletion::Move { target, snapshot }
5738 } else {
5739 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5740 && !self.inline_completions_hidden_for_vim_mode;
5741
5742 if show_completions_in_buffer {
5743 if edits
5744 .iter()
5745 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5746 {
5747 let mut inlays = Vec::new();
5748 for (range, new_text) in &edits {
5749 let inlay = Inlay::inline_completion(
5750 post_inc(&mut self.next_inlay_id),
5751 range.start,
5752 new_text.as_str(),
5753 );
5754 inlay_ids.push(inlay.id);
5755 inlays.push(inlay);
5756 }
5757
5758 self.splice_inlays(&[], inlays, cx);
5759 } else {
5760 let background_color = cx.theme().status().deleted_background;
5761 self.highlight_text::<InlineCompletionHighlight>(
5762 edits.iter().map(|(range, _)| range.clone()).collect(),
5763 HighlightStyle {
5764 background_color: Some(background_color),
5765 ..Default::default()
5766 },
5767 cx,
5768 );
5769 }
5770 }
5771
5772 invalidation_row_range = edit_start_row..edit_end_row;
5773
5774 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5775 if provider.show_tab_accept_marker() {
5776 EditDisplayMode::TabAccept
5777 } else {
5778 EditDisplayMode::Inline
5779 }
5780 } else {
5781 EditDisplayMode::DiffPopover
5782 };
5783
5784 InlineCompletion::Edit {
5785 edits,
5786 edit_preview: inline_completion.edit_preview,
5787 display_mode,
5788 snapshot,
5789 }
5790 };
5791
5792 let invalidation_range = multibuffer
5793 .anchor_before(Point::new(invalidation_row_range.start, 0))
5794 ..multibuffer.anchor_after(Point::new(
5795 invalidation_row_range.end,
5796 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5797 ));
5798
5799 self.stale_inline_completion_in_menu = None;
5800 self.active_inline_completion = Some(InlineCompletionState {
5801 inlay_ids,
5802 completion,
5803 completion_id: inline_completion.id,
5804 invalidation_range,
5805 });
5806
5807 cx.notify();
5808
5809 Some(())
5810 }
5811
5812 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5813 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5814 }
5815
5816 fn render_code_actions_indicator(
5817 &self,
5818 _style: &EditorStyle,
5819 row: DisplayRow,
5820 is_active: bool,
5821 cx: &mut Context<Self>,
5822 ) -> Option<IconButton> {
5823 if self.available_code_actions.is_some() {
5824 Some(
5825 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5826 .shape(ui::IconButtonShape::Square)
5827 .icon_size(IconSize::XSmall)
5828 .icon_color(Color::Muted)
5829 .toggle_state(is_active)
5830 .tooltip({
5831 let focus_handle = self.focus_handle.clone();
5832 move |window, cx| {
5833 Tooltip::for_action_in(
5834 "Toggle Code Actions",
5835 &ToggleCodeActions {
5836 deployed_from_indicator: None,
5837 },
5838 &focus_handle,
5839 window,
5840 cx,
5841 )
5842 }
5843 })
5844 .on_click(cx.listener(move |editor, _e, window, cx| {
5845 window.focus(&editor.focus_handle(cx));
5846 editor.toggle_code_actions(
5847 &ToggleCodeActions {
5848 deployed_from_indicator: Some(row),
5849 },
5850 window,
5851 cx,
5852 );
5853 })),
5854 )
5855 } else {
5856 None
5857 }
5858 }
5859
5860 fn clear_tasks(&mut self) {
5861 self.tasks.clear()
5862 }
5863
5864 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5865 if self.tasks.insert(key, value).is_some() {
5866 // This case should hopefully be rare, but just in case...
5867 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5868 }
5869 }
5870
5871 fn build_tasks_context(
5872 project: &Entity<Project>,
5873 buffer: &Entity<Buffer>,
5874 buffer_row: u32,
5875 tasks: &Arc<RunnableTasks>,
5876 cx: &mut Context<Self>,
5877 ) -> Task<Option<task::TaskContext>> {
5878 let position = Point::new(buffer_row, tasks.column);
5879 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5880 let location = Location {
5881 buffer: buffer.clone(),
5882 range: range_start..range_start,
5883 };
5884 // Fill in the environmental variables from the tree-sitter captures
5885 let mut captured_task_variables = TaskVariables::default();
5886 for (capture_name, value) in tasks.extra_variables.clone() {
5887 captured_task_variables.insert(
5888 task::VariableName::Custom(capture_name.into()),
5889 value.clone(),
5890 );
5891 }
5892 project.update(cx, |project, cx| {
5893 project.task_store().update(cx, |task_store, cx| {
5894 task_store.task_context_for_location(captured_task_variables, location, cx)
5895 })
5896 })
5897 }
5898
5899 pub fn spawn_nearest_task(
5900 &mut self,
5901 action: &SpawnNearestTask,
5902 window: &mut Window,
5903 cx: &mut Context<Self>,
5904 ) {
5905 let Some((workspace, _)) = self.workspace.clone() else {
5906 return;
5907 };
5908 let Some(project) = self.project.clone() else {
5909 return;
5910 };
5911
5912 // Try to find a closest, enclosing node using tree-sitter that has a
5913 // task
5914 let Some((buffer, buffer_row, tasks)) = self
5915 .find_enclosing_node_task(cx)
5916 // Or find the task that's closest in row-distance.
5917 .or_else(|| self.find_closest_task(cx))
5918 else {
5919 return;
5920 };
5921
5922 let reveal_strategy = action.reveal;
5923 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5924 cx.spawn_in(window, |_, mut cx| async move {
5925 let context = task_context.await?;
5926 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5927
5928 let resolved = resolved_task.resolved.as_mut()?;
5929 resolved.reveal = reveal_strategy;
5930
5931 workspace
5932 .update(&mut cx, |workspace, cx| {
5933 workspace::tasks::schedule_resolved_task(
5934 workspace,
5935 task_source_kind,
5936 resolved_task,
5937 false,
5938 cx,
5939 );
5940 })
5941 .ok()
5942 })
5943 .detach();
5944 }
5945
5946 fn find_closest_task(
5947 &mut self,
5948 cx: &mut Context<Self>,
5949 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5950 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5951
5952 let ((buffer_id, row), tasks) = self
5953 .tasks
5954 .iter()
5955 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5956
5957 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5958 let tasks = Arc::new(tasks.to_owned());
5959 Some((buffer, *row, tasks))
5960 }
5961
5962 fn find_enclosing_node_task(
5963 &mut self,
5964 cx: &mut Context<Self>,
5965 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5966 let snapshot = self.buffer.read(cx).snapshot(cx);
5967 let offset = self.selections.newest::<usize>(cx).head();
5968 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5969 let buffer_id = excerpt.buffer().remote_id();
5970
5971 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5972 let mut cursor = layer.node().walk();
5973
5974 while cursor.goto_first_child_for_byte(offset).is_some() {
5975 if cursor.node().end_byte() == offset {
5976 cursor.goto_next_sibling();
5977 }
5978 }
5979
5980 // Ascend to the smallest ancestor that contains the range and has a task.
5981 loop {
5982 let node = cursor.node();
5983 let node_range = node.byte_range();
5984 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5985
5986 // Check if this node contains our offset
5987 if node_range.start <= offset && node_range.end >= offset {
5988 // If it contains offset, check for task
5989 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5990 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5991 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5992 }
5993 }
5994
5995 if !cursor.goto_parent() {
5996 break;
5997 }
5998 }
5999 None
6000 }
6001
6002 fn render_run_indicator(
6003 &self,
6004 _style: &EditorStyle,
6005 is_active: bool,
6006 row: DisplayRow,
6007 cx: &mut Context<Self>,
6008 ) -> IconButton {
6009 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6010 .shape(ui::IconButtonShape::Square)
6011 .icon_size(IconSize::XSmall)
6012 .icon_color(Color::Muted)
6013 .toggle_state(is_active)
6014 .on_click(cx.listener(move |editor, _e, window, cx| {
6015 window.focus(&editor.focus_handle(cx));
6016 editor.toggle_code_actions(
6017 &ToggleCodeActions {
6018 deployed_from_indicator: Some(row),
6019 },
6020 window,
6021 cx,
6022 );
6023 }))
6024 }
6025
6026 pub fn context_menu_visible(&self) -> bool {
6027 !self.edit_prediction_preview_is_active()
6028 && self
6029 .context_menu
6030 .borrow()
6031 .as_ref()
6032 .map_or(false, |menu| menu.visible())
6033 }
6034
6035 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6036 self.context_menu
6037 .borrow()
6038 .as_ref()
6039 .map(|menu| menu.origin())
6040 }
6041
6042 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6043 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6044
6045 fn render_edit_prediction_popover(
6046 &mut self,
6047 text_bounds: &Bounds<Pixels>,
6048 content_origin: gpui::Point<Pixels>,
6049 editor_snapshot: &EditorSnapshot,
6050 visible_row_range: Range<DisplayRow>,
6051 scroll_top: f32,
6052 scroll_bottom: f32,
6053 line_layouts: &[LineWithInvisibles],
6054 line_height: Pixels,
6055 scroll_pixel_position: gpui::Point<Pixels>,
6056 newest_selection_head: Option<DisplayPoint>,
6057 editor_width: Pixels,
6058 style: &EditorStyle,
6059 window: &mut Window,
6060 cx: &mut App,
6061 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6062 let active_inline_completion = self.active_inline_completion.as_ref()?;
6063
6064 if self.edit_prediction_visible_in_cursor_popover(true) {
6065 return None;
6066 }
6067
6068 match &active_inline_completion.completion {
6069 InlineCompletion::Move { target, .. } => {
6070 let target_display_point = target.to_display_point(editor_snapshot);
6071
6072 if self.edit_prediction_requires_modifier() {
6073 if !self.edit_prediction_preview_is_active() {
6074 return None;
6075 }
6076
6077 self.render_edit_prediction_modifier_jump_popover(
6078 text_bounds,
6079 content_origin,
6080 visible_row_range,
6081 line_layouts,
6082 line_height,
6083 scroll_pixel_position,
6084 newest_selection_head,
6085 target_display_point,
6086 window,
6087 cx,
6088 )
6089 } else {
6090 self.render_edit_prediction_eager_jump_popover(
6091 text_bounds,
6092 content_origin,
6093 editor_snapshot,
6094 visible_row_range,
6095 scroll_top,
6096 scroll_bottom,
6097 line_height,
6098 scroll_pixel_position,
6099 target_display_point,
6100 editor_width,
6101 window,
6102 cx,
6103 )
6104 }
6105 }
6106 InlineCompletion::Edit {
6107 display_mode: EditDisplayMode::Inline,
6108 ..
6109 } => None,
6110 InlineCompletion::Edit {
6111 display_mode: EditDisplayMode::TabAccept,
6112 edits,
6113 ..
6114 } => {
6115 let range = &edits.first()?.0;
6116 let target_display_point = range.end.to_display_point(editor_snapshot);
6117
6118 self.render_edit_prediction_end_of_line_popover(
6119 "Accept",
6120 editor_snapshot,
6121 visible_row_range,
6122 target_display_point,
6123 line_height,
6124 scroll_pixel_position,
6125 content_origin,
6126 editor_width,
6127 window,
6128 cx,
6129 )
6130 }
6131 InlineCompletion::Edit {
6132 edits,
6133 edit_preview,
6134 display_mode: EditDisplayMode::DiffPopover,
6135 snapshot,
6136 } => self.render_edit_prediction_diff_popover(
6137 text_bounds,
6138 content_origin,
6139 editor_snapshot,
6140 visible_row_range,
6141 line_layouts,
6142 line_height,
6143 scroll_pixel_position,
6144 newest_selection_head,
6145 editor_width,
6146 style,
6147 edits,
6148 edit_preview,
6149 snapshot,
6150 window,
6151 cx,
6152 ),
6153 }
6154 }
6155
6156 fn render_edit_prediction_modifier_jump_popover(
6157 &mut self,
6158 text_bounds: &Bounds<Pixels>,
6159 content_origin: gpui::Point<Pixels>,
6160 visible_row_range: Range<DisplayRow>,
6161 line_layouts: &[LineWithInvisibles],
6162 line_height: Pixels,
6163 scroll_pixel_position: gpui::Point<Pixels>,
6164 newest_selection_head: Option<DisplayPoint>,
6165 target_display_point: DisplayPoint,
6166 window: &mut Window,
6167 cx: &mut App,
6168 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6169 let scrolled_content_origin =
6170 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6171
6172 const SCROLL_PADDING_Y: Pixels = px(12.);
6173
6174 if target_display_point.row() < visible_row_range.start {
6175 return self.render_edit_prediction_scroll_popover(
6176 |_| SCROLL_PADDING_Y,
6177 IconName::ArrowUp,
6178 visible_row_range,
6179 line_layouts,
6180 newest_selection_head,
6181 scrolled_content_origin,
6182 window,
6183 cx,
6184 );
6185 } else if target_display_point.row() >= visible_row_range.end {
6186 return self.render_edit_prediction_scroll_popover(
6187 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6188 IconName::ArrowDown,
6189 visible_row_range,
6190 line_layouts,
6191 newest_selection_head,
6192 scrolled_content_origin,
6193 window,
6194 cx,
6195 );
6196 }
6197
6198 const POLE_WIDTH: Pixels = px(2.);
6199
6200 let line_layout =
6201 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6202 let target_column = target_display_point.column() as usize;
6203
6204 let target_x = line_layout.x_for_index(target_column);
6205 let target_y =
6206 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6207
6208 let flag_on_right = target_x < text_bounds.size.width / 2.;
6209
6210 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6211 border_color.l += 0.001;
6212
6213 let mut element = v_flex()
6214 .items_end()
6215 .when(flag_on_right, |el| el.items_start())
6216 .child(if flag_on_right {
6217 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6218 .rounded_bl(px(0.))
6219 .rounded_tl(px(0.))
6220 .border_l_2()
6221 .border_color(border_color)
6222 } else {
6223 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6224 .rounded_br(px(0.))
6225 .rounded_tr(px(0.))
6226 .border_r_2()
6227 .border_color(border_color)
6228 })
6229 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6230 .into_any();
6231
6232 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6233
6234 let mut origin = scrolled_content_origin + point(target_x, target_y)
6235 - point(
6236 if flag_on_right {
6237 POLE_WIDTH
6238 } else {
6239 size.width - POLE_WIDTH
6240 },
6241 size.height - line_height,
6242 );
6243
6244 origin.x = origin.x.max(content_origin.x);
6245
6246 element.prepaint_at(origin, window, cx);
6247
6248 Some((element, origin))
6249 }
6250
6251 fn render_edit_prediction_scroll_popover(
6252 &mut self,
6253 to_y: impl Fn(Size<Pixels>) -> Pixels,
6254 scroll_icon: IconName,
6255 visible_row_range: Range<DisplayRow>,
6256 line_layouts: &[LineWithInvisibles],
6257 newest_selection_head: Option<DisplayPoint>,
6258 scrolled_content_origin: gpui::Point<Pixels>,
6259 window: &mut Window,
6260 cx: &mut App,
6261 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6262 let mut element = self
6263 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6264 .into_any();
6265
6266 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6267
6268 let cursor = newest_selection_head?;
6269 let cursor_row_layout =
6270 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6271 let cursor_column = cursor.column() as usize;
6272
6273 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6274
6275 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6276
6277 element.prepaint_at(origin, window, cx);
6278 Some((element, origin))
6279 }
6280
6281 fn render_edit_prediction_eager_jump_popover(
6282 &mut self,
6283 text_bounds: &Bounds<Pixels>,
6284 content_origin: gpui::Point<Pixels>,
6285 editor_snapshot: &EditorSnapshot,
6286 visible_row_range: Range<DisplayRow>,
6287 scroll_top: f32,
6288 scroll_bottom: f32,
6289 line_height: Pixels,
6290 scroll_pixel_position: gpui::Point<Pixels>,
6291 target_display_point: DisplayPoint,
6292 editor_width: Pixels,
6293 window: &mut Window,
6294 cx: &mut App,
6295 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6296 if target_display_point.row().as_f32() < scroll_top {
6297 let mut element = self
6298 .render_edit_prediction_line_popover(
6299 "Jump to Edit",
6300 Some(IconName::ArrowUp),
6301 window,
6302 cx,
6303 )?
6304 .into_any();
6305
6306 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6307 let offset = point(
6308 (text_bounds.size.width - size.width) / 2.,
6309 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6310 );
6311
6312 let origin = text_bounds.origin + offset;
6313 element.prepaint_at(origin, window, cx);
6314 Some((element, origin))
6315 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6316 let mut element = self
6317 .render_edit_prediction_line_popover(
6318 "Jump to Edit",
6319 Some(IconName::ArrowDown),
6320 window,
6321 cx,
6322 )?
6323 .into_any();
6324
6325 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6326 let offset = point(
6327 (text_bounds.size.width - size.width) / 2.,
6328 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6329 );
6330
6331 let origin = text_bounds.origin + offset;
6332 element.prepaint_at(origin, window, cx);
6333 Some((element, origin))
6334 } else {
6335 self.render_edit_prediction_end_of_line_popover(
6336 "Jump to Edit",
6337 editor_snapshot,
6338 visible_row_range,
6339 target_display_point,
6340 line_height,
6341 scroll_pixel_position,
6342 content_origin,
6343 editor_width,
6344 window,
6345 cx,
6346 )
6347 }
6348 }
6349
6350 fn render_edit_prediction_end_of_line_popover(
6351 self: &mut Editor,
6352 label: &'static str,
6353 editor_snapshot: &EditorSnapshot,
6354 visible_row_range: Range<DisplayRow>,
6355 target_display_point: DisplayPoint,
6356 line_height: Pixels,
6357 scroll_pixel_position: gpui::Point<Pixels>,
6358 content_origin: gpui::Point<Pixels>,
6359 editor_width: Pixels,
6360 window: &mut Window,
6361 cx: &mut App,
6362 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6363 let target_line_end = DisplayPoint::new(
6364 target_display_point.row(),
6365 editor_snapshot.line_len(target_display_point.row()),
6366 );
6367
6368 let mut element = self
6369 .render_edit_prediction_line_popover(label, None, window, cx)?
6370 .into_any();
6371
6372 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6373
6374 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6375
6376 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6377 let mut origin = start_point
6378 + line_origin
6379 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6380 origin.x = origin.x.max(content_origin.x);
6381
6382 let max_x = content_origin.x + editor_width - size.width;
6383
6384 if origin.x > max_x {
6385 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6386
6387 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6388 origin.y += offset;
6389 IconName::ArrowUp
6390 } else {
6391 origin.y -= offset;
6392 IconName::ArrowDown
6393 };
6394
6395 element = self
6396 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6397 .into_any();
6398
6399 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6400
6401 origin.x = content_origin.x + editor_width - size.width - px(2.);
6402 }
6403
6404 element.prepaint_at(origin, window, cx);
6405 Some((element, origin))
6406 }
6407
6408 fn render_edit_prediction_diff_popover(
6409 self: &Editor,
6410 text_bounds: &Bounds<Pixels>,
6411 content_origin: gpui::Point<Pixels>,
6412 editor_snapshot: &EditorSnapshot,
6413 visible_row_range: Range<DisplayRow>,
6414 line_layouts: &[LineWithInvisibles],
6415 line_height: Pixels,
6416 scroll_pixel_position: gpui::Point<Pixels>,
6417 newest_selection_head: Option<DisplayPoint>,
6418 editor_width: Pixels,
6419 style: &EditorStyle,
6420 edits: &Vec<(Range<Anchor>, String)>,
6421 edit_preview: &Option<language::EditPreview>,
6422 snapshot: &language::BufferSnapshot,
6423 window: &mut Window,
6424 cx: &mut App,
6425 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6426 let edit_start = edits
6427 .first()
6428 .unwrap()
6429 .0
6430 .start
6431 .to_display_point(editor_snapshot);
6432 let edit_end = edits
6433 .last()
6434 .unwrap()
6435 .0
6436 .end
6437 .to_display_point(editor_snapshot);
6438
6439 let is_visible = visible_row_range.contains(&edit_start.row())
6440 || visible_row_range.contains(&edit_end.row());
6441 if !is_visible {
6442 return None;
6443 }
6444
6445 let highlighted_edits =
6446 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6447
6448 let styled_text = highlighted_edits.to_styled_text(&style.text);
6449 let line_count = highlighted_edits.text.lines().count();
6450
6451 const BORDER_WIDTH: Pixels = px(1.);
6452
6453 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6454 let has_keybind = keybind.is_some();
6455
6456 let mut element = h_flex()
6457 .items_start()
6458 .child(
6459 h_flex()
6460 .bg(cx.theme().colors().editor_background)
6461 .border(BORDER_WIDTH)
6462 .shadow_sm()
6463 .border_color(cx.theme().colors().border)
6464 .rounded_l_lg()
6465 .when(line_count > 1, |el| el.rounded_br_lg())
6466 .pr_1()
6467 .child(styled_text),
6468 )
6469 .child(
6470 h_flex()
6471 .h(line_height + BORDER_WIDTH * px(2.))
6472 .px_1p5()
6473 .gap_1()
6474 // Workaround: For some reason, there's a gap if we don't do this
6475 .ml(-BORDER_WIDTH)
6476 .shadow(smallvec![gpui::BoxShadow {
6477 color: gpui::black().opacity(0.05),
6478 offset: point(px(1.), px(1.)),
6479 blur_radius: px(2.),
6480 spread_radius: px(0.),
6481 }])
6482 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6483 .border(BORDER_WIDTH)
6484 .border_color(cx.theme().colors().border)
6485 .rounded_r_lg()
6486 .id("edit_prediction_diff_popover_keybind")
6487 .when(!has_keybind, |el| {
6488 let status_colors = cx.theme().status();
6489
6490 el.bg(status_colors.error_background)
6491 .border_color(status_colors.error.opacity(0.6))
6492 .child(Icon::new(IconName::Info).color(Color::Error))
6493 .cursor_default()
6494 .hoverable_tooltip(move |_window, cx| {
6495 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6496 })
6497 })
6498 .children(keybind),
6499 )
6500 .into_any();
6501
6502 let longest_row =
6503 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6504 let longest_line_width = if visible_row_range.contains(&longest_row) {
6505 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6506 } else {
6507 layout_line(
6508 longest_row,
6509 editor_snapshot,
6510 style,
6511 editor_width,
6512 |_| false,
6513 window,
6514 cx,
6515 )
6516 .width
6517 };
6518
6519 let viewport_bounds =
6520 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6521 right: -EditorElement::SCROLLBAR_WIDTH,
6522 ..Default::default()
6523 });
6524
6525 let x_after_longest =
6526 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6527 - scroll_pixel_position.x;
6528
6529 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6530
6531 // Fully visible if it can be displayed within the window (allow overlapping other
6532 // panes). However, this is only allowed if the popover starts within text_bounds.
6533 let can_position_to_the_right = x_after_longest < text_bounds.right()
6534 && x_after_longest + element_bounds.width < viewport_bounds.right();
6535
6536 let mut origin = if can_position_to_the_right {
6537 point(
6538 x_after_longest,
6539 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6540 - scroll_pixel_position.y,
6541 )
6542 } else {
6543 let cursor_row = newest_selection_head.map(|head| head.row());
6544 let above_edit = edit_start
6545 .row()
6546 .0
6547 .checked_sub(line_count as u32)
6548 .map(DisplayRow);
6549 let below_edit = Some(edit_end.row() + 1);
6550 let above_cursor =
6551 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6552 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6553
6554 // Place the edit popover adjacent to the edit if there is a location
6555 // available that is onscreen and does not obscure the cursor. Otherwise,
6556 // place it adjacent to the cursor.
6557 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6558 .into_iter()
6559 .flatten()
6560 .find(|&start_row| {
6561 let end_row = start_row + line_count as u32;
6562 visible_row_range.contains(&start_row)
6563 && visible_row_range.contains(&end_row)
6564 && cursor_row.map_or(true, |cursor_row| {
6565 !((start_row..end_row).contains(&cursor_row))
6566 })
6567 })?;
6568
6569 content_origin
6570 + point(
6571 -scroll_pixel_position.x,
6572 row_target.as_f32() * line_height - scroll_pixel_position.y,
6573 )
6574 };
6575
6576 origin.x -= BORDER_WIDTH;
6577
6578 window.defer_draw(element, origin, 1);
6579
6580 // Do not return an element, since it will already be drawn due to defer_draw.
6581 None
6582 }
6583
6584 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6585 px(30.)
6586 }
6587
6588 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6589 if self.read_only(cx) {
6590 cx.theme().players().read_only()
6591 } else {
6592 self.style.as_ref().unwrap().local_player
6593 }
6594 }
6595
6596 fn render_edit_prediction_accept_keybind(
6597 &self,
6598 window: &mut Window,
6599 cx: &App,
6600 ) -> Option<AnyElement> {
6601 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6602 let accept_keystroke = accept_binding.keystroke()?;
6603
6604 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6605
6606 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6607 Color::Accent
6608 } else {
6609 Color::Muted
6610 };
6611
6612 h_flex()
6613 .px_0p5()
6614 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6615 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6616 .text_size(TextSize::XSmall.rems(cx))
6617 .child(h_flex().children(ui::render_modifiers(
6618 &accept_keystroke.modifiers,
6619 PlatformStyle::platform(),
6620 Some(modifiers_color),
6621 Some(IconSize::XSmall.rems().into()),
6622 true,
6623 )))
6624 .when(is_platform_style_mac, |parent| {
6625 parent.child(accept_keystroke.key.clone())
6626 })
6627 .when(!is_platform_style_mac, |parent| {
6628 parent.child(
6629 Key::new(
6630 util::capitalize(&accept_keystroke.key),
6631 Some(Color::Default),
6632 )
6633 .size(Some(IconSize::XSmall.rems().into())),
6634 )
6635 })
6636 .into_any()
6637 .into()
6638 }
6639
6640 fn render_edit_prediction_line_popover(
6641 &self,
6642 label: impl Into<SharedString>,
6643 icon: Option<IconName>,
6644 window: &mut Window,
6645 cx: &App,
6646 ) -> Option<Stateful<Div>> {
6647 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6648
6649 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6650 let has_keybind = keybind.is_some();
6651
6652 let result = h_flex()
6653 .id("ep-line-popover")
6654 .py_0p5()
6655 .pl_1()
6656 .pr(padding_right)
6657 .gap_1()
6658 .rounded_md()
6659 .border_1()
6660 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6661 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6662 .shadow_sm()
6663 .when(!has_keybind, |el| {
6664 let status_colors = cx.theme().status();
6665
6666 el.bg(status_colors.error_background)
6667 .border_color(status_colors.error.opacity(0.6))
6668 .pl_2()
6669 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
6670 .cursor_default()
6671 .hoverable_tooltip(move |_window, cx| {
6672 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6673 })
6674 })
6675 .children(keybind)
6676 .child(
6677 Label::new(label)
6678 .size(LabelSize::Small)
6679 .when(!has_keybind, |el| {
6680 el.color(cx.theme().status().error.into()).strikethrough()
6681 }),
6682 )
6683 .when(!has_keybind, |el| {
6684 el.child(
6685 h_flex().ml_1().child(
6686 Icon::new(IconName::Info)
6687 .size(IconSize::Small)
6688 .color(cx.theme().status().error.into()),
6689 ),
6690 )
6691 })
6692 .when_some(icon, |element, icon| {
6693 element.child(
6694 div()
6695 .mt(px(1.5))
6696 .child(Icon::new(icon).size(IconSize::Small)),
6697 )
6698 });
6699
6700 Some(result)
6701 }
6702
6703 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6704 let accent_color = cx.theme().colors().text_accent;
6705 let editor_bg_color = cx.theme().colors().editor_background;
6706 editor_bg_color.blend(accent_color.opacity(0.1))
6707 }
6708
6709 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6710 let accent_color = cx.theme().colors().text_accent;
6711 let editor_bg_color = cx.theme().colors().editor_background;
6712 editor_bg_color.blend(accent_color.opacity(0.6))
6713 }
6714
6715 fn render_edit_prediction_cursor_popover(
6716 &self,
6717 min_width: Pixels,
6718 max_width: Pixels,
6719 cursor_point: Point,
6720 style: &EditorStyle,
6721 accept_keystroke: Option<&gpui::Keystroke>,
6722 _window: &Window,
6723 cx: &mut Context<Editor>,
6724 ) -> Option<AnyElement> {
6725 let provider = self.edit_prediction_provider.as_ref()?;
6726
6727 if provider.provider.needs_terms_acceptance(cx) {
6728 return Some(
6729 h_flex()
6730 .min_w(min_width)
6731 .flex_1()
6732 .px_2()
6733 .py_1()
6734 .gap_3()
6735 .elevation_2(cx)
6736 .hover(|style| style.bg(cx.theme().colors().element_hover))
6737 .id("accept-terms")
6738 .cursor_pointer()
6739 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6740 .on_click(cx.listener(|this, _event, window, cx| {
6741 cx.stop_propagation();
6742 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6743 window.dispatch_action(
6744 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6745 cx,
6746 );
6747 }))
6748 .child(
6749 h_flex()
6750 .flex_1()
6751 .gap_2()
6752 .child(Icon::new(IconName::ZedPredict))
6753 .child(Label::new("Accept Terms of Service"))
6754 .child(div().w_full())
6755 .child(
6756 Icon::new(IconName::ArrowUpRight)
6757 .color(Color::Muted)
6758 .size(IconSize::Small),
6759 )
6760 .into_any_element(),
6761 )
6762 .into_any(),
6763 );
6764 }
6765
6766 let is_refreshing = provider.provider.is_refreshing(cx);
6767
6768 fn pending_completion_container() -> Div {
6769 h_flex()
6770 .h_full()
6771 .flex_1()
6772 .gap_2()
6773 .child(Icon::new(IconName::ZedPredict))
6774 }
6775
6776 let completion = match &self.active_inline_completion {
6777 Some(prediction) => {
6778 if !self.has_visible_completions_menu() {
6779 const RADIUS: Pixels = px(6.);
6780 const BORDER_WIDTH: Pixels = px(1.);
6781
6782 return Some(
6783 h_flex()
6784 .elevation_2(cx)
6785 .border(BORDER_WIDTH)
6786 .border_color(cx.theme().colors().border)
6787 .when(accept_keystroke.is_none(), |el| {
6788 el.border_color(cx.theme().status().error)
6789 })
6790 .rounded(RADIUS)
6791 .rounded_tl(px(0.))
6792 .overflow_hidden()
6793 .child(div().px_1p5().child(match &prediction.completion {
6794 InlineCompletion::Move { target, snapshot } => {
6795 use text::ToPoint as _;
6796 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6797 {
6798 Icon::new(IconName::ZedPredictDown)
6799 } else {
6800 Icon::new(IconName::ZedPredictUp)
6801 }
6802 }
6803 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6804 }))
6805 .child(
6806 h_flex()
6807 .gap_1()
6808 .py_1()
6809 .px_2()
6810 .rounded_r(RADIUS - BORDER_WIDTH)
6811 .border_l_1()
6812 .border_color(cx.theme().colors().border)
6813 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6814 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6815 el.child(
6816 Label::new("Hold")
6817 .size(LabelSize::Small)
6818 .when(accept_keystroke.is_none(), |el| {
6819 el.strikethrough()
6820 })
6821 .line_height_style(LineHeightStyle::UiLabel),
6822 )
6823 })
6824 .id("edit_prediction_cursor_popover_keybind")
6825 .when(accept_keystroke.is_none(), |el| {
6826 let status_colors = cx.theme().status();
6827
6828 el.bg(status_colors.error_background)
6829 .border_color(status_colors.error.opacity(0.6))
6830 .child(Icon::new(IconName::Info).color(Color::Error))
6831 .cursor_default()
6832 .hoverable_tooltip(move |_window, cx| {
6833 cx.new(|_| MissingEditPredictionKeybindingTooltip)
6834 .into()
6835 })
6836 })
6837 .when_some(
6838 accept_keystroke.as_ref(),
6839 |el, accept_keystroke| {
6840 el.child(h_flex().children(ui::render_modifiers(
6841 &accept_keystroke.modifiers,
6842 PlatformStyle::platform(),
6843 Some(Color::Default),
6844 Some(IconSize::XSmall.rems().into()),
6845 false,
6846 )))
6847 },
6848 ),
6849 )
6850 .into_any(),
6851 );
6852 }
6853
6854 self.render_edit_prediction_cursor_popover_preview(
6855 prediction,
6856 cursor_point,
6857 style,
6858 cx,
6859 )?
6860 }
6861
6862 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6863 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6864 stale_completion,
6865 cursor_point,
6866 style,
6867 cx,
6868 )?,
6869
6870 None => {
6871 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6872 }
6873 },
6874
6875 None => pending_completion_container().child(Label::new("No Prediction")),
6876 };
6877
6878 let completion = if is_refreshing {
6879 completion
6880 .with_animation(
6881 "loading-completion",
6882 Animation::new(Duration::from_secs(2))
6883 .repeat()
6884 .with_easing(pulsating_between(0.4, 0.8)),
6885 |label, delta| label.opacity(delta),
6886 )
6887 .into_any_element()
6888 } else {
6889 completion.into_any_element()
6890 };
6891
6892 let has_completion = self.active_inline_completion.is_some();
6893
6894 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6895 Some(
6896 h_flex()
6897 .min_w(min_width)
6898 .max_w(max_width)
6899 .flex_1()
6900 .elevation_2(cx)
6901 .border_color(cx.theme().colors().border)
6902 .child(
6903 div()
6904 .flex_1()
6905 .py_1()
6906 .px_2()
6907 .overflow_hidden()
6908 .child(completion),
6909 )
6910 .when_some(accept_keystroke, |el, accept_keystroke| {
6911 if !accept_keystroke.modifiers.modified() {
6912 return el;
6913 }
6914
6915 el.child(
6916 h_flex()
6917 .h_full()
6918 .border_l_1()
6919 .rounded_r_lg()
6920 .border_color(cx.theme().colors().border)
6921 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6922 .gap_1()
6923 .py_1()
6924 .px_2()
6925 .child(
6926 h_flex()
6927 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6928 .when(is_platform_style_mac, |parent| parent.gap_1())
6929 .child(h_flex().children(ui::render_modifiers(
6930 &accept_keystroke.modifiers,
6931 PlatformStyle::platform(),
6932 Some(if !has_completion {
6933 Color::Muted
6934 } else {
6935 Color::Default
6936 }),
6937 None,
6938 false,
6939 ))),
6940 )
6941 .child(Label::new("Preview").into_any_element())
6942 .opacity(if has_completion { 1.0 } else { 0.4 }),
6943 )
6944 })
6945 .into_any(),
6946 )
6947 }
6948
6949 fn render_edit_prediction_cursor_popover_preview(
6950 &self,
6951 completion: &InlineCompletionState,
6952 cursor_point: Point,
6953 style: &EditorStyle,
6954 cx: &mut Context<Editor>,
6955 ) -> Option<Div> {
6956 use text::ToPoint as _;
6957
6958 fn render_relative_row_jump(
6959 prefix: impl Into<String>,
6960 current_row: u32,
6961 target_row: u32,
6962 ) -> Div {
6963 let (row_diff, arrow) = if target_row < current_row {
6964 (current_row - target_row, IconName::ArrowUp)
6965 } else {
6966 (target_row - current_row, IconName::ArrowDown)
6967 };
6968
6969 h_flex()
6970 .child(
6971 Label::new(format!("{}{}", prefix.into(), row_diff))
6972 .color(Color::Muted)
6973 .size(LabelSize::Small),
6974 )
6975 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6976 }
6977
6978 match &completion.completion {
6979 InlineCompletion::Move {
6980 target, snapshot, ..
6981 } => Some(
6982 h_flex()
6983 .px_2()
6984 .gap_2()
6985 .flex_1()
6986 .child(
6987 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6988 Icon::new(IconName::ZedPredictDown)
6989 } else {
6990 Icon::new(IconName::ZedPredictUp)
6991 },
6992 )
6993 .child(Label::new("Jump to Edit")),
6994 ),
6995
6996 InlineCompletion::Edit {
6997 edits,
6998 edit_preview,
6999 snapshot,
7000 display_mode: _,
7001 } => {
7002 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7003
7004 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7005 &snapshot,
7006 &edits,
7007 edit_preview.as_ref()?,
7008 true,
7009 cx,
7010 )
7011 .first_line_preview();
7012
7013 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7014 .with_default_highlights(&style.text, highlighted_edits.highlights);
7015
7016 let preview = h_flex()
7017 .gap_1()
7018 .min_w_16()
7019 .child(styled_text)
7020 .when(has_more_lines, |parent| parent.child("…"));
7021
7022 let left = if first_edit_row != cursor_point.row {
7023 render_relative_row_jump("", cursor_point.row, first_edit_row)
7024 .into_any_element()
7025 } else {
7026 Icon::new(IconName::ZedPredict).into_any_element()
7027 };
7028
7029 Some(
7030 h_flex()
7031 .h_full()
7032 .flex_1()
7033 .gap_2()
7034 .pr_1()
7035 .overflow_x_hidden()
7036 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7037 .child(left)
7038 .child(preview),
7039 )
7040 }
7041 }
7042 }
7043
7044 fn render_context_menu(
7045 &self,
7046 style: &EditorStyle,
7047 max_height_in_lines: u32,
7048 y_flipped: bool,
7049 window: &mut Window,
7050 cx: &mut Context<Editor>,
7051 ) -> Option<AnyElement> {
7052 let menu = self.context_menu.borrow();
7053 let menu = menu.as_ref()?;
7054 if !menu.visible() {
7055 return None;
7056 };
7057 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7058 }
7059
7060 fn render_context_menu_aside(
7061 &mut self,
7062 max_size: Size<Pixels>,
7063 window: &mut Window,
7064 cx: &mut Context<Editor>,
7065 ) -> Option<AnyElement> {
7066 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7067 if menu.visible() {
7068 menu.render_aside(self, max_size, window, cx)
7069 } else {
7070 None
7071 }
7072 })
7073 }
7074
7075 fn hide_context_menu(
7076 &mut self,
7077 window: &mut Window,
7078 cx: &mut Context<Self>,
7079 ) -> Option<CodeContextMenu> {
7080 cx.notify();
7081 self.completion_tasks.clear();
7082 let context_menu = self.context_menu.borrow_mut().take();
7083 self.stale_inline_completion_in_menu.take();
7084 self.update_visible_inline_completion(window, cx);
7085 context_menu
7086 }
7087
7088 fn show_snippet_choices(
7089 &mut self,
7090 choices: &Vec<String>,
7091 selection: Range<Anchor>,
7092 cx: &mut Context<Self>,
7093 ) {
7094 if selection.start.buffer_id.is_none() {
7095 return;
7096 }
7097 let buffer_id = selection.start.buffer_id.unwrap();
7098 let buffer = self.buffer().read(cx).buffer(buffer_id);
7099 let id = post_inc(&mut self.next_completion_id);
7100
7101 if let Some(buffer) = buffer {
7102 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7103 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7104 ));
7105 }
7106 }
7107
7108 pub fn insert_snippet(
7109 &mut self,
7110 insertion_ranges: &[Range<usize>],
7111 snippet: Snippet,
7112 window: &mut Window,
7113 cx: &mut Context<Self>,
7114 ) -> Result<()> {
7115 struct Tabstop<T> {
7116 is_end_tabstop: bool,
7117 ranges: Vec<Range<T>>,
7118 choices: Option<Vec<String>>,
7119 }
7120
7121 let tabstops = self.buffer.update(cx, |buffer, cx| {
7122 let snippet_text: Arc<str> = snippet.text.clone().into();
7123 buffer.edit(
7124 insertion_ranges
7125 .iter()
7126 .cloned()
7127 .map(|range| (range, snippet_text.clone())),
7128 Some(AutoindentMode::EachLine),
7129 cx,
7130 );
7131
7132 let snapshot = &*buffer.read(cx);
7133 let snippet = &snippet;
7134 snippet
7135 .tabstops
7136 .iter()
7137 .map(|tabstop| {
7138 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7139 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7140 });
7141 let mut tabstop_ranges = tabstop
7142 .ranges
7143 .iter()
7144 .flat_map(|tabstop_range| {
7145 let mut delta = 0_isize;
7146 insertion_ranges.iter().map(move |insertion_range| {
7147 let insertion_start = insertion_range.start as isize + delta;
7148 delta +=
7149 snippet.text.len() as isize - insertion_range.len() as isize;
7150
7151 let start = ((insertion_start + tabstop_range.start) as usize)
7152 .min(snapshot.len());
7153 let end = ((insertion_start + tabstop_range.end) as usize)
7154 .min(snapshot.len());
7155 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7156 })
7157 })
7158 .collect::<Vec<_>>();
7159 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7160
7161 Tabstop {
7162 is_end_tabstop,
7163 ranges: tabstop_ranges,
7164 choices: tabstop.choices.clone(),
7165 }
7166 })
7167 .collect::<Vec<_>>()
7168 });
7169 if let Some(tabstop) = tabstops.first() {
7170 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7171 s.select_ranges(tabstop.ranges.iter().cloned());
7172 });
7173
7174 if let Some(choices) = &tabstop.choices {
7175 if let Some(selection) = tabstop.ranges.first() {
7176 self.show_snippet_choices(choices, selection.clone(), cx)
7177 }
7178 }
7179
7180 // If we're already at the last tabstop and it's at the end of the snippet,
7181 // we're done, we don't need to keep the state around.
7182 if !tabstop.is_end_tabstop {
7183 let choices = tabstops
7184 .iter()
7185 .map(|tabstop| tabstop.choices.clone())
7186 .collect();
7187
7188 let ranges = tabstops
7189 .into_iter()
7190 .map(|tabstop| tabstop.ranges)
7191 .collect::<Vec<_>>();
7192
7193 self.snippet_stack.push(SnippetState {
7194 active_index: 0,
7195 ranges,
7196 choices,
7197 });
7198 }
7199
7200 // Check whether the just-entered snippet ends with an auto-closable bracket.
7201 if self.autoclose_regions.is_empty() {
7202 let snapshot = self.buffer.read(cx).snapshot(cx);
7203 for selection in &mut self.selections.all::<Point>(cx) {
7204 let selection_head = selection.head();
7205 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7206 continue;
7207 };
7208
7209 let mut bracket_pair = None;
7210 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7211 let prev_chars = snapshot
7212 .reversed_chars_at(selection_head)
7213 .collect::<String>();
7214 for (pair, enabled) in scope.brackets() {
7215 if enabled
7216 && pair.close
7217 && prev_chars.starts_with(pair.start.as_str())
7218 && next_chars.starts_with(pair.end.as_str())
7219 {
7220 bracket_pair = Some(pair.clone());
7221 break;
7222 }
7223 }
7224 if let Some(pair) = bracket_pair {
7225 let start = snapshot.anchor_after(selection_head);
7226 let end = snapshot.anchor_after(selection_head);
7227 self.autoclose_regions.push(AutocloseRegion {
7228 selection_id: selection.id,
7229 range: start..end,
7230 pair,
7231 });
7232 }
7233 }
7234 }
7235 }
7236 Ok(())
7237 }
7238
7239 pub fn move_to_next_snippet_tabstop(
7240 &mut self,
7241 window: &mut Window,
7242 cx: &mut Context<Self>,
7243 ) -> bool {
7244 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7245 }
7246
7247 pub fn move_to_prev_snippet_tabstop(
7248 &mut self,
7249 window: &mut Window,
7250 cx: &mut Context<Self>,
7251 ) -> bool {
7252 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7253 }
7254
7255 pub fn move_to_snippet_tabstop(
7256 &mut self,
7257 bias: Bias,
7258 window: &mut Window,
7259 cx: &mut Context<Self>,
7260 ) -> bool {
7261 if let Some(mut snippet) = self.snippet_stack.pop() {
7262 match bias {
7263 Bias::Left => {
7264 if snippet.active_index > 0 {
7265 snippet.active_index -= 1;
7266 } else {
7267 self.snippet_stack.push(snippet);
7268 return false;
7269 }
7270 }
7271 Bias::Right => {
7272 if snippet.active_index + 1 < snippet.ranges.len() {
7273 snippet.active_index += 1;
7274 } else {
7275 self.snippet_stack.push(snippet);
7276 return false;
7277 }
7278 }
7279 }
7280 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7281 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7282 s.select_anchor_ranges(current_ranges.iter().cloned())
7283 });
7284
7285 if let Some(choices) = &snippet.choices[snippet.active_index] {
7286 if let Some(selection) = current_ranges.first() {
7287 self.show_snippet_choices(&choices, selection.clone(), cx);
7288 }
7289 }
7290
7291 // If snippet state is not at the last tabstop, push it back on the stack
7292 if snippet.active_index + 1 < snippet.ranges.len() {
7293 self.snippet_stack.push(snippet);
7294 }
7295 return true;
7296 }
7297 }
7298
7299 false
7300 }
7301
7302 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7303 self.transact(window, cx, |this, window, cx| {
7304 this.select_all(&SelectAll, window, cx);
7305 this.insert("", window, cx);
7306 });
7307 }
7308
7309 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7310 self.transact(window, cx, |this, window, cx| {
7311 this.select_autoclose_pair(window, cx);
7312 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7313 if !this.linked_edit_ranges.is_empty() {
7314 let selections = this.selections.all::<MultiBufferPoint>(cx);
7315 let snapshot = this.buffer.read(cx).snapshot(cx);
7316
7317 for selection in selections.iter() {
7318 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7319 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7320 if selection_start.buffer_id != selection_end.buffer_id {
7321 continue;
7322 }
7323 if let Some(ranges) =
7324 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7325 {
7326 for (buffer, entries) in ranges {
7327 linked_ranges.entry(buffer).or_default().extend(entries);
7328 }
7329 }
7330 }
7331 }
7332
7333 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7334 if !this.selections.line_mode {
7335 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7336 for selection in &mut selections {
7337 if selection.is_empty() {
7338 let old_head = selection.head();
7339 let mut new_head =
7340 movement::left(&display_map, old_head.to_display_point(&display_map))
7341 .to_point(&display_map);
7342 if let Some((buffer, line_buffer_range)) = display_map
7343 .buffer_snapshot
7344 .buffer_line_for_row(MultiBufferRow(old_head.row))
7345 {
7346 let indent_size =
7347 buffer.indent_size_for_line(line_buffer_range.start.row);
7348 let indent_len = match indent_size.kind {
7349 IndentKind::Space => {
7350 buffer.settings_at(line_buffer_range.start, cx).tab_size
7351 }
7352 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7353 };
7354 if old_head.column <= indent_size.len && old_head.column > 0 {
7355 let indent_len = indent_len.get();
7356 new_head = cmp::min(
7357 new_head,
7358 MultiBufferPoint::new(
7359 old_head.row,
7360 ((old_head.column - 1) / indent_len) * indent_len,
7361 ),
7362 );
7363 }
7364 }
7365
7366 selection.set_head(new_head, SelectionGoal::None);
7367 }
7368 }
7369 }
7370
7371 this.signature_help_state.set_backspace_pressed(true);
7372 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7373 s.select(selections)
7374 });
7375 this.insert("", window, cx);
7376 let empty_str: Arc<str> = Arc::from("");
7377 for (buffer, edits) in linked_ranges {
7378 let snapshot = buffer.read(cx).snapshot();
7379 use text::ToPoint as TP;
7380
7381 let edits = edits
7382 .into_iter()
7383 .map(|range| {
7384 let end_point = TP::to_point(&range.end, &snapshot);
7385 let mut start_point = TP::to_point(&range.start, &snapshot);
7386
7387 if end_point == start_point {
7388 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7389 .saturating_sub(1);
7390 start_point =
7391 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7392 };
7393
7394 (start_point..end_point, empty_str.clone())
7395 })
7396 .sorted_by_key(|(range, _)| range.start)
7397 .collect::<Vec<_>>();
7398 buffer.update(cx, |this, cx| {
7399 this.edit(edits, None, cx);
7400 })
7401 }
7402 this.refresh_inline_completion(true, false, window, cx);
7403 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7404 });
7405 }
7406
7407 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7408 self.transact(window, cx, |this, window, cx| {
7409 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7410 let line_mode = s.line_mode;
7411 s.move_with(|map, selection| {
7412 if selection.is_empty() && !line_mode {
7413 let cursor = movement::right(map, selection.head());
7414 selection.end = cursor;
7415 selection.reversed = true;
7416 selection.goal = SelectionGoal::None;
7417 }
7418 })
7419 });
7420 this.insert("", window, cx);
7421 this.refresh_inline_completion(true, false, window, cx);
7422 });
7423 }
7424
7425 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7426 if self.move_to_prev_snippet_tabstop(window, cx) {
7427 return;
7428 }
7429
7430 self.outdent(&Outdent, window, cx);
7431 }
7432
7433 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7434 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7435 return;
7436 }
7437
7438 let mut selections = self.selections.all_adjusted(cx);
7439 let buffer = self.buffer.read(cx);
7440 let snapshot = buffer.snapshot(cx);
7441 let rows_iter = selections.iter().map(|s| s.head().row);
7442 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7443
7444 let mut edits = Vec::new();
7445 let mut prev_edited_row = 0;
7446 let mut row_delta = 0;
7447 for selection in &mut selections {
7448 if selection.start.row != prev_edited_row {
7449 row_delta = 0;
7450 }
7451 prev_edited_row = selection.end.row;
7452
7453 // If the selection is non-empty, then increase the indentation of the selected lines.
7454 if !selection.is_empty() {
7455 row_delta =
7456 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7457 continue;
7458 }
7459
7460 // If the selection is empty and the cursor is in the leading whitespace before the
7461 // suggested indentation, then auto-indent the line.
7462 let cursor = selection.head();
7463 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7464 if let Some(suggested_indent) =
7465 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7466 {
7467 if cursor.column < suggested_indent.len
7468 && cursor.column <= current_indent.len
7469 && current_indent.len <= suggested_indent.len
7470 {
7471 selection.start = Point::new(cursor.row, suggested_indent.len);
7472 selection.end = selection.start;
7473 if row_delta == 0 {
7474 edits.extend(Buffer::edit_for_indent_size_adjustment(
7475 cursor.row,
7476 current_indent,
7477 suggested_indent,
7478 ));
7479 row_delta = suggested_indent.len - current_indent.len;
7480 }
7481 continue;
7482 }
7483 }
7484
7485 // Otherwise, insert a hard or soft tab.
7486 let settings = buffer.language_settings_at(cursor, cx);
7487 let tab_size = if settings.hard_tabs {
7488 IndentSize::tab()
7489 } else {
7490 let tab_size = settings.tab_size.get();
7491 let char_column = snapshot
7492 .text_for_range(Point::new(cursor.row, 0)..cursor)
7493 .flat_map(str::chars)
7494 .count()
7495 + row_delta as usize;
7496 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7497 IndentSize::spaces(chars_to_next_tab_stop)
7498 };
7499 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7500 selection.end = selection.start;
7501 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7502 row_delta += tab_size.len;
7503 }
7504
7505 self.transact(window, cx, |this, window, cx| {
7506 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7507 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7508 s.select(selections)
7509 });
7510 this.refresh_inline_completion(true, false, window, cx);
7511 });
7512 }
7513
7514 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7515 if self.read_only(cx) {
7516 return;
7517 }
7518 let mut selections = self.selections.all::<Point>(cx);
7519 let mut prev_edited_row = 0;
7520 let mut row_delta = 0;
7521 let mut edits = Vec::new();
7522 let buffer = self.buffer.read(cx);
7523 let snapshot = buffer.snapshot(cx);
7524 for selection in &mut selections {
7525 if selection.start.row != prev_edited_row {
7526 row_delta = 0;
7527 }
7528 prev_edited_row = selection.end.row;
7529
7530 row_delta =
7531 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7532 }
7533
7534 self.transact(window, cx, |this, window, cx| {
7535 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7536 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7537 s.select(selections)
7538 });
7539 });
7540 }
7541
7542 fn indent_selection(
7543 buffer: &MultiBuffer,
7544 snapshot: &MultiBufferSnapshot,
7545 selection: &mut Selection<Point>,
7546 edits: &mut Vec<(Range<Point>, String)>,
7547 delta_for_start_row: u32,
7548 cx: &App,
7549 ) -> u32 {
7550 let settings = buffer.language_settings_at(selection.start, cx);
7551 let tab_size = settings.tab_size.get();
7552 let indent_kind = if settings.hard_tabs {
7553 IndentKind::Tab
7554 } else {
7555 IndentKind::Space
7556 };
7557 let mut start_row = selection.start.row;
7558 let mut end_row = selection.end.row + 1;
7559
7560 // If a selection ends at the beginning of a line, don't indent
7561 // that last line.
7562 if selection.end.column == 0 && selection.end.row > selection.start.row {
7563 end_row -= 1;
7564 }
7565
7566 // Avoid re-indenting a row that has already been indented by a
7567 // previous selection, but still update this selection's column
7568 // to reflect that indentation.
7569 if delta_for_start_row > 0 {
7570 start_row += 1;
7571 selection.start.column += delta_for_start_row;
7572 if selection.end.row == selection.start.row {
7573 selection.end.column += delta_for_start_row;
7574 }
7575 }
7576
7577 let mut delta_for_end_row = 0;
7578 let has_multiple_rows = start_row + 1 != end_row;
7579 for row in start_row..end_row {
7580 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7581 let indent_delta = match (current_indent.kind, indent_kind) {
7582 (IndentKind::Space, IndentKind::Space) => {
7583 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7584 IndentSize::spaces(columns_to_next_tab_stop)
7585 }
7586 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7587 (_, IndentKind::Tab) => IndentSize::tab(),
7588 };
7589
7590 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7591 0
7592 } else {
7593 selection.start.column
7594 };
7595 let row_start = Point::new(row, start);
7596 edits.push((
7597 row_start..row_start,
7598 indent_delta.chars().collect::<String>(),
7599 ));
7600
7601 // Update this selection's endpoints to reflect the indentation.
7602 if row == selection.start.row {
7603 selection.start.column += indent_delta.len;
7604 }
7605 if row == selection.end.row {
7606 selection.end.column += indent_delta.len;
7607 delta_for_end_row = indent_delta.len;
7608 }
7609 }
7610
7611 if selection.start.row == selection.end.row {
7612 delta_for_start_row + delta_for_end_row
7613 } else {
7614 delta_for_end_row
7615 }
7616 }
7617
7618 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7619 if self.read_only(cx) {
7620 return;
7621 }
7622 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7623 let selections = self.selections.all::<Point>(cx);
7624 let mut deletion_ranges = Vec::new();
7625 let mut last_outdent = None;
7626 {
7627 let buffer = self.buffer.read(cx);
7628 let snapshot = buffer.snapshot(cx);
7629 for selection in &selections {
7630 let settings = buffer.language_settings_at(selection.start, cx);
7631 let tab_size = settings.tab_size.get();
7632 let mut rows = selection.spanned_rows(false, &display_map);
7633
7634 // Avoid re-outdenting a row that has already been outdented by a
7635 // previous selection.
7636 if let Some(last_row) = last_outdent {
7637 if last_row == rows.start {
7638 rows.start = rows.start.next_row();
7639 }
7640 }
7641 let has_multiple_rows = rows.len() > 1;
7642 for row in rows.iter_rows() {
7643 let indent_size = snapshot.indent_size_for_line(row);
7644 if indent_size.len > 0 {
7645 let deletion_len = match indent_size.kind {
7646 IndentKind::Space => {
7647 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7648 if columns_to_prev_tab_stop == 0 {
7649 tab_size
7650 } else {
7651 columns_to_prev_tab_stop
7652 }
7653 }
7654 IndentKind::Tab => 1,
7655 };
7656 let start = if has_multiple_rows
7657 || deletion_len > selection.start.column
7658 || indent_size.len < selection.start.column
7659 {
7660 0
7661 } else {
7662 selection.start.column - deletion_len
7663 };
7664 deletion_ranges.push(
7665 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7666 );
7667 last_outdent = Some(row);
7668 }
7669 }
7670 }
7671 }
7672
7673 self.transact(window, cx, |this, window, cx| {
7674 this.buffer.update(cx, |buffer, cx| {
7675 let empty_str: Arc<str> = Arc::default();
7676 buffer.edit(
7677 deletion_ranges
7678 .into_iter()
7679 .map(|range| (range, empty_str.clone())),
7680 None,
7681 cx,
7682 );
7683 });
7684 let selections = this.selections.all::<usize>(cx);
7685 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7686 s.select(selections)
7687 });
7688 });
7689 }
7690
7691 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7692 if self.read_only(cx) {
7693 return;
7694 }
7695 let selections = self
7696 .selections
7697 .all::<usize>(cx)
7698 .into_iter()
7699 .map(|s| s.range());
7700
7701 self.transact(window, cx, |this, window, cx| {
7702 this.buffer.update(cx, |buffer, cx| {
7703 buffer.autoindent_ranges(selections, cx);
7704 });
7705 let selections = this.selections.all::<usize>(cx);
7706 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7707 s.select(selections)
7708 });
7709 });
7710 }
7711
7712 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7713 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7714 let selections = self.selections.all::<Point>(cx);
7715
7716 let mut new_cursors = Vec::new();
7717 let mut edit_ranges = Vec::new();
7718 let mut selections = selections.iter().peekable();
7719 while let Some(selection) = selections.next() {
7720 let mut rows = selection.spanned_rows(false, &display_map);
7721 let goal_display_column = selection.head().to_display_point(&display_map).column();
7722
7723 // Accumulate contiguous regions of rows that we want to delete.
7724 while let Some(next_selection) = selections.peek() {
7725 let next_rows = next_selection.spanned_rows(false, &display_map);
7726 if next_rows.start <= rows.end {
7727 rows.end = next_rows.end;
7728 selections.next().unwrap();
7729 } else {
7730 break;
7731 }
7732 }
7733
7734 let buffer = &display_map.buffer_snapshot;
7735 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7736 let edit_end;
7737 let cursor_buffer_row;
7738 if buffer.max_point().row >= rows.end.0 {
7739 // If there's a line after the range, delete the \n from the end of the row range
7740 // and position the cursor on the next line.
7741 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7742 cursor_buffer_row = rows.end;
7743 } else {
7744 // If there isn't a line after the range, delete the \n from the line before the
7745 // start of the row range and position the cursor there.
7746 edit_start = edit_start.saturating_sub(1);
7747 edit_end = buffer.len();
7748 cursor_buffer_row = rows.start.previous_row();
7749 }
7750
7751 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7752 *cursor.column_mut() =
7753 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7754
7755 new_cursors.push((
7756 selection.id,
7757 buffer.anchor_after(cursor.to_point(&display_map)),
7758 ));
7759 edit_ranges.push(edit_start..edit_end);
7760 }
7761
7762 self.transact(window, cx, |this, window, cx| {
7763 let buffer = this.buffer.update(cx, |buffer, cx| {
7764 let empty_str: Arc<str> = Arc::default();
7765 buffer.edit(
7766 edit_ranges
7767 .into_iter()
7768 .map(|range| (range, empty_str.clone())),
7769 None,
7770 cx,
7771 );
7772 buffer.snapshot(cx)
7773 });
7774 let new_selections = new_cursors
7775 .into_iter()
7776 .map(|(id, cursor)| {
7777 let cursor = cursor.to_point(&buffer);
7778 Selection {
7779 id,
7780 start: cursor,
7781 end: cursor,
7782 reversed: false,
7783 goal: SelectionGoal::None,
7784 }
7785 })
7786 .collect();
7787
7788 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7789 s.select(new_selections);
7790 });
7791 });
7792 }
7793
7794 pub fn join_lines_impl(
7795 &mut self,
7796 insert_whitespace: bool,
7797 window: &mut Window,
7798 cx: &mut Context<Self>,
7799 ) {
7800 if self.read_only(cx) {
7801 return;
7802 }
7803 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7804 for selection in self.selections.all::<Point>(cx) {
7805 let start = MultiBufferRow(selection.start.row);
7806 // Treat single line selections as if they include the next line. Otherwise this action
7807 // would do nothing for single line selections individual cursors.
7808 let end = if selection.start.row == selection.end.row {
7809 MultiBufferRow(selection.start.row + 1)
7810 } else {
7811 MultiBufferRow(selection.end.row)
7812 };
7813
7814 if let Some(last_row_range) = row_ranges.last_mut() {
7815 if start <= last_row_range.end {
7816 last_row_range.end = end;
7817 continue;
7818 }
7819 }
7820 row_ranges.push(start..end);
7821 }
7822
7823 let snapshot = self.buffer.read(cx).snapshot(cx);
7824 let mut cursor_positions = Vec::new();
7825 for row_range in &row_ranges {
7826 let anchor = snapshot.anchor_before(Point::new(
7827 row_range.end.previous_row().0,
7828 snapshot.line_len(row_range.end.previous_row()),
7829 ));
7830 cursor_positions.push(anchor..anchor);
7831 }
7832
7833 self.transact(window, cx, |this, window, cx| {
7834 for row_range in row_ranges.into_iter().rev() {
7835 for row in row_range.iter_rows().rev() {
7836 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7837 let next_line_row = row.next_row();
7838 let indent = snapshot.indent_size_for_line(next_line_row);
7839 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7840
7841 let replace =
7842 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7843 " "
7844 } else {
7845 ""
7846 };
7847
7848 this.buffer.update(cx, |buffer, cx| {
7849 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7850 });
7851 }
7852 }
7853
7854 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7855 s.select_anchor_ranges(cursor_positions)
7856 });
7857 });
7858 }
7859
7860 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7861 self.join_lines_impl(true, window, cx);
7862 }
7863
7864 pub fn sort_lines_case_sensitive(
7865 &mut self,
7866 _: &SortLinesCaseSensitive,
7867 window: &mut Window,
7868 cx: &mut Context<Self>,
7869 ) {
7870 self.manipulate_lines(window, cx, |lines| lines.sort())
7871 }
7872
7873 pub fn sort_lines_case_insensitive(
7874 &mut self,
7875 _: &SortLinesCaseInsensitive,
7876 window: &mut Window,
7877 cx: &mut Context<Self>,
7878 ) {
7879 self.manipulate_lines(window, cx, |lines| {
7880 lines.sort_by_key(|line| line.to_lowercase())
7881 })
7882 }
7883
7884 pub fn unique_lines_case_insensitive(
7885 &mut self,
7886 _: &UniqueLinesCaseInsensitive,
7887 window: &mut Window,
7888 cx: &mut Context<Self>,
7889 ) {
7890 self.manipulate_lines(window, cx, |lines| {
7891 let mut seen = HashSet::default();
7892 lines.retain(|line| seen.insert(line.to_lowercase()));
7893 })
7894 }
7895
7896 pub fn unique_lines_case_sensitive(
7897 &mut self,
7898 _: &UniqueLinesCaseSensitive,
7899 window: &mut Window,
7900 cx: &mut Context<Self>,
7901 ) {
7902 self.manipulate_lines(window, cx, |lines| {
7903 let mut seen = HashSet::default();
7904 lines.retain(|line| seen.insert(*line));
7905 })
7906 }
7907
7908 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7909 let Some(project) = self.project.clone() else {
7910 return;
7911 };
7912 self.reload(project, window, cx)
7913 .detach_and_notify_err(window, cx);
7914 }
7915
7916 pub fn restore_file(
7917 &mut self,
7918 _: &::git::RestoreFile,
7919 window: &mut Window,
7920 cx: &mut Context<Self>,
7921 ) {
7922 let mut buffer_ids = HashSet::default();
7923 let snapshot = self.buffer().read(cx).snapshot(cx);
7924 for selection in self.selections.all::<usize>(cx) {
7925 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7926 }
7927
7928 let buffer = self.buffer().read(cx);
7929 let ranges = buffer_ids
7930 .into_iter()
7931 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7932 .collect::<Vec<_>>();
7933
7934 self.restore_hunks_in_ranges(ranges, window, cx);
7935 }
7936
7937 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7938 let selections = self
7939 .selections
7940 .all(cx)
7941 .into_iter()
7942 .map(|s| s.range())
7943 .collect();
7944 self.restore_hunks_in_ranges(selections, window, cx);
7945 }
7946
7947 fn restore_hunks_in_ranges(
7948 &mut self,
7949 ranges: Vec<Range<Point>>,
7950 window: &mut Window,
7951 cx: &mut Context<Editor>,
7952 ) {
7953 let mut revert_changes = HashMap::default();
7954 let chunk_by = self
7955 .snapshot(window, cx)
7956 .hunks_for_ranges(ranges)
7957 .into_iter()
7958 .chunk_by(|hunk| hunk.buffer_id);
7959 for (buffer_id, hunks) in &chunk_by {
7960 let hunks = hunks.collect::<Vec<_>>();
7961 for hunk in &hunks {
7962 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7963 }
7964 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7965 }
7966 drop(chunk_by);
7967 if !revert_changes.is_empty() {
7968 self.transact(window, cx, |editor, window, cx| {
7969 editor.restore(revert_changes, window, cx);
7970 });
7971 }
7972 }
7973
7974 pub fn open_active_item_in_terminal(
7975 &mut self,
7976 _: &OpenInTerminal,
7977 window: &mut Window,
7978 cx: &mut Context<Self>,
7979 ) {
7980 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7981 let project_path = buffer.read(cx).project_path(cx)?;
7982 let project = self.project.as_ref()?.read(cx);
7983 let entry = project.entry_for_path(&project_path, cx)?;
7984 let parent = match &entry.canonical_path {
7985 Some(canonical_path) => canonical_path.to_path_buf(),
7986 None => project.absolute_path(&project_path, cx)?,
7987 }
7988 .parent()?
7989 .to_path_buf();
7990 Some(parent)
7991 }) {
7992 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7993 }
7994 }
7995
7996 pub fn prepare_restore_change(
7997 &self,
7998 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7999 hunk: &MultiBufferDiffHunk,
8000 cx: &mut App,
8001 ) -> Option<()> {
8002 if hunk.is_created_file() {
8003 return None;
8004 }
8005 let buffer = self.buffer.read(cx);
8006 let diff = buffer.diff_for(hunk.buffer_id)?;
8007 let buffer = buffer.buffer(hunk.buffer_id)?;
8008 let buffer = buffer.read(cx);
8009 let original_text = diff
8010 .read(cx)
8011 .base_text()
8012 .as_rope()
8013 .slice(hunk.diff_base_byte_range.clone());
8014 let buffer_snapshot = buffer.snapshot();
8015 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8016 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8017 probe
8018 .0
8019 .start
8020 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8021 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8022 }) {
8023 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8024 Some(())
8025 } else {
8026 None
8027 }
8028 }
8029
8030 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8031 self.manipulate_lines(window, cx, |lines| lines.reverse())
8032 }
8033
8034 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8035 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8036 }
8037
8038 fn manipulate_lines<Fn>(
8039 &mut self,
8040 window: &mut Window,
8041 cx: &mut Context<Self>,
8042 mut callback: Fn,
8043 ) where
8044 Fn: FnMut(&mut Vec<&str>),
8045 {
8046 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8047 let buffer = self.buffer.read(cx).snapshot(cx);
8048
8049 let mut edits = Vec::new();
8050
8051 let selections = self.selections.all::<Point>(cx);
8052 let mut selections = selections.iter().peekable();
8053 let mut contiguous_row_selections = Vec::new();
8054 let mut new_selections = Vec::new();
8055 let mut added_lines = 0;
8056 let mut removed_lines = 0;
8057
8058 while let Some(selection) = selections.next() {
8059 let (start_row, end_row) = consume_contiguous_rows(
8060 &mut contiguous_row_selections,
8061 selection,
8062 &display_map,
8063 &mut selections,
8064 );
8065
8066 let start_point = Point::new(start_row.0, 0);
8067 let end_point = Point::new(
8068 end_row.previous_row().0,
8069 buffer.line_len(end_row.previous_row()),
8070 );
8071 let text = buffer
8072 .text_for_range(start_point..end_point)
8073 .collect::<String>();
8074
8075 let mut lines = text.split('\n').collect_vec();
8076
8077 let lines_before = lines.len();
8078 callback(&mut lines);
8079 let lines_after = lines.len();
8080
8081 edits.push((start_point..end_point, lines.join("\n")));
8082
8083 // Selections must change based on added and removed line count
8084 let start_row =
8085 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8086 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8087 new_selections.push(Selection {
8088 id: selection.id,
8089 start: start_row,
8090 end: end_row,
8091 goal: SelectionGoal::None,
8092 reversed: selection.reversed,
8093 });
8094
8095 if lines_after > lines_before {
8096 added_lines += lines_after - lines_before;
8097 } else if lines_before > lines_after {
8098 removed_lines += lines_before - lines_after;
8099 }
8100 }
8101
8102 self.transact(window, cx, |this, window, cx| {
8103 let buffer = this.buffer.update(cx, |buffer, cx| {
8104 buffer.edit(edits, None, cx);
8105 buffer.snapshot(cx)
8106 });
8107
8108 // Recalculate offsets on newly edited buffer
8109 let new_selections = new_selections
8110 .iter()
8111 .map(|s| {
8112 let start_point = Point::new(s.start.0, 0);
8113 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8114 Selection {
8115 id: s.id,
8116 start: buffer.point_to_offset(start_point),
8117 end: buffer.point_to_offset(end_point),
8118 goal: s.goal,
8119 reversed: s.reversed,
8120 }
8121 })
8122 .collect();
8123
8124 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8125 s.select(new_selections);
8126 });
8127
8128 this.request_autoscroll(Autoscroll::fit(), cx);
8129 });
8130 }
8131
8132 pub fn convert_to_upper_case(
8133 &mut self,
8134 _: &ConvertToUpperCase,
8135 window: &mut Window,
8136 cx: &mut Context<Self>,
8137 ) {
8138 self.manipulate_text(window, cx, |text| text.to_uppercase())
8139 }
8140
8141 pub fn convert_to_lower_case(
8142 &mut self,
8143 _: &ConvertToLowerCase,
8144 window: &mut Window,
8145 cx: &mut Context<Self>,
8146 ) {
8147 self.manipulate_text(window, cx, |text| text.to_lowercase())
8148 }
8149
8150 pub fn convert_to_title_case(
8151 &mut self,
8152 _: &ConvertToTitleCase,
8153 window: &mut Window,
8154 cx: &mut Context<Self>,
8155 ) {
8156 self.manipulate_text(window, cx, |text| {
8157 text.split('\n')
8158 .map(|line| line.to_case(Case::Title))
8159 .join("\n")
8160 })
8161 }
8162
8163 pub fn convert_to_snake_case(
8164 &mut self,
8165 _: &ConvertToSnakeCase,
8166 window: &mut Window,
8167 cx: &mut Context<Self>,
8168 ) {
8169 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8170 }
8171
8172 pub fn convert_to_kebab_case(
8173 &mut self,
8174 _: &ConvertToKebabCase,
8175 window: &mut Window,
8176 cx: &mut Context<Self>,
8177 ) {
8178 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8179 }
8180
8181 pub fn convert_to_upper_camel_case(
8182 &mut self,
8183 _: &ConvertToUpperCamelCase,
8184 window: &mut Window,
8185 cx: &mut Context<Self>,
8186 ) {
8187 self.manipulate_text(window, cx, |text| {
8188 text.split('\n')
8189 .map(|line| line.to_case(Case::UpperCamel))
8190 .join("\n")
8191 })
8192 }
8193
8194 pub fn convert_to_lower_camel_case(
8195 &mut self,
8196 _: &ConvertToLowerCamelCase,
8197 window: &mut Window,
8198 cx: &mut Context<Self>,
8199 ) {
8200 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8201 }
8202
8203 pub fn convert_to_opposite_case(
8204 &mut self,
8205 _: &ConvertToOppositeCase,
8206 window: &mut Window,
8207 cx: &mut Context<Self>,
8208 ) {
8209 self.manipulate_text(window, cx, |text| {
8210 text.chars()
8211 .fold(String::with_capacity(text.len()), |mut t, c| {
8212 if c.is_uppercase() {
8213 t.extend(c.to_lowercase());
8214 } else {
8215 t.extend(c.to_uppercase());
8216 }
8217 t
8218 })
8219 })
8220 }
8221
8222 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8223 where
8224 Fn: FnMut(&str) -> String,
8225 {
8226 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8227 let buffer = self.buffer.read(cx).snapshot(cx);
8228
8229 let mut new_selections = Vec::new();
8230 let mut edits = Vec::new();
8231 let mut selection_adjustment = 0i32;
8232
8233 for selection in self.selections.all::<usize>(cx) {
8234 let selection_is_empty = selection.is_empty();
8235
8236 let (start, end) = if selection_is_empty {
8237 let word_range = movement::surrounding_word(
8238 &display_map,
8239 selection.start.to_display_point(&display_map),
8240 );
8241 let start = word_range.start.to_offset(&display_map, Bias::Left);
8242 let end = word_range.end.to_offset(&display_map, Bias::Left);
8243 (start, end)
8244 } else {
8245 (selection.start, selection.end)
8246 };
8247
8248 let text = buffer.text_for_range(start..end).collect::<String>();
8249 let old_length = text.len() as i32;
8250 let text = callback(&text);
8251
8252 new_selections.push(Selection {
8253 start: (start as i32 - selection_adjustment) as usize,
8254 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8255 goal: SelectionGoal::None,
8256 ..selection
8257 });
8258
8259 selection_adjustment += old_length - text.len() as i32;
8260
8261 edits.push((start..end, text));
8262 }
8263
8264 self.transact(window, cx, |this, window, cx| {
8265 this.buffer.update(cx, |buffer, cx| {
8266 buffer.edit(edits, None, cx);
8267 });
8268
8269 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8270 s.select(new_selections);
8271 });
8272
8273 this.request_autoscroll(Autoscroll::fit(), cx);
8274 });
8275 }
8276
8277 pub fn duplicate(
8278 &mut self,
8279 upwards: bool,
8280 whole_lines: bool,
8281 window: &mut Window,
8282 cx: &mut Context<Self>,
8283 ) {
8284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8285 let buffer = &display_map.buffer_snapshot;
8286 let selections = self.selections.all::<Point>(cx);
8287
8288 let mut edits = Vec::new();
8289 let mut selections_iter = selections.iter().peekable();
8290 while let Some(selection) = selections_iter.next() {
8291 let mut rows = selection.spanned_rows(false, &display_map);
8292 // duplicate line-wise
8293 if whole_lines || selection.start == selection.end {
8294 // Avoid duplicating the same lines twice.
8295 while let Some(next_selection) = selections_iter.peek() {
8296 let next_rows = next_selection.spanned_rows(false, &display_map);
8297 if next_rows.start < rows.end {
8298 rows.end = next_rows.end;
8299 selections_iter.next().unwrap();
8300 } else {
8301 break;
8302 }
8303 }
8304
8305 // Copy the text from the selected row region and splice it either at the start
8306 // or end of the region.
8307 let start = Point::new(rows.start.0, 0);
8308 let end = Point::new(
8309 rows.end.previous_row().0,
8310 buffer.line_len(rows.end.previous_row()),
8311 );
8312 let text = buffer
8313 .text_for_range(start..end)
8314 .chain(Some("\n"))
8315 .collect::<String>();
8316 let insert_location = if upwards {
8317 Point::new(rows.end.0, 0)
8318 } else {
8319 start
8320 };
8321 edits.push((insert_location..insert_location, text));
8322 } else {
8323 // duplicate character-wise
8324 let start = selection.start;
8325 let end = selection.end;
8326 let text = buffer.text_for_range(start..end).collect::<String>();
8327 edits.push((selection.end..selection.end, text));
8328 }
8329 }
8330
8331 self.transact(window, cx, |this, _, cx| {
8332 this.buffer.update(cx, |buffer, cx| {
8333 buffer.edit(edits, None, cx);
8334 });
8335
8336 this.request_autoscroll(Autoscroll::fit(), cx);
8337 });
8338 }
8339
8340 pub fn duplicate_line_up(
8341 &mut self,
8342 _: &DuplicateLineUp,
8343 window: &mut Window,
8344 cx: &mut Context<Self>,
8345 ) {
8346 self.duplicate(true, true, window, cx);
8347 }
8348
8349 pub fn duplicate_line_down(
8350 &mut self,
8351 _: &DuplicateLineDown,
8352 window: &mut Window,
8353 cx: &mut Context<Self>,
8354 ) {
8355 self.duplicate(false, true, window, cx);
8356 }
8357
8358 pub fn duplicate_selection(
8359 &mut self,
8360 _: &DuplicateSelection,
8361 window: &mut Window,
8362 cx: &mut Context<Self>,
8363 ) {
8364 self.duplicate(false, false, window, cx);
8365 }
8366
8367 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8368 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8369 let buffer = self.buffer.read(cx).snapshot(cx);
8370
8371 let mut edits = Vec::new();
8372 let mut unfold_ranges = Vec::new();
8373 let mut refold_creases = Vec::new();
8374
8375 let selections = self.selections.all::<Point>(cx);
8376 let mut selections = selections.iter().peekable();
8377 let mut contiguous_row_selections = Vec::new();
8378 let mut new_selections = Vec::new();
8379
8380 while let Some(selection) = selections.next() {
8381 // Find all the selections that span a contiguous row range
8382 let (start_row, end_row) = consume_contiguous_rows(
8383 &mut contiguous_row_selections,
8384 selection,
8385 &display_map,
8386 &mut selections,
8387 );
8388
8389 // Move the text spanned by the row range to be before the line preceding the row range
8390 if start_row.0 > 0 {
8391 let range_to_move = Point::new(
8392 start_row.previous_row().0,
8393 buffer.line_len(start_row.previous_row()),
8394 )
8395 ..Point::new(
8396 end_row.previous_row().0,
8397 buffer.line_len(end_row.previous_row()),
8398 );
8399 let insertion_point = display_map
8400 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8401 .0;
8402
8403 // Don't move lines across excerpts
8404 if buffer
8405 .excerpt_containing(insertion_point..range_to_move.end)
8406 .is_some()
8407 {
8408 let text = buffer
8409 .text_for_range(range_to_move.clone())
8410 .flat_map(|s| s.chars())
8411 .skip(1)
8412 .chain(['\n'])
8413 .collect::<String>();
8414
8415 edits.push((
8416 buffer.anchor_after(range_to_move.start)
8417 ..buffer.anchor_before(range_to_move.end),
8418 String::new(),
8419 ));
8420 let insertion_anchor = buffer.anchor_after(insertion_point);
8421 edits.push((insertion_anchor..insertion_anchor, text));
8422
8423 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8424
8425 // Move selections up
8426 new_selections.extend(contiguous_row_selections.drain(..).map(
8427 |mut selection| {
8428 selection.start.row -= row_delta;
8429 selection.end.row -= row_delta;
8430 selection
8431 },
8432 ));
8433
8434 // Move folds up
8435 unfold_ranges.push(range_to_move.clone());
8436 for fold in display_map.folds_in_range(
8437 buffer.anchor_before(range_to_move.start)
8438 ..buffer.anchor_after(range_to_move.end),
8439 ) {
8440 let mut start = fold.range.start.to_point(&buffer);
8441 let mut end = fold.range.end.to_point(&buffer);
8442 start.row -= row_delta;
8443 end.row -= row_delta;
8444 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8445 }
8446 }
8447 }
8448
8449 // If we didn't move line(s), preserve the existing selections
8450 new_selections.append(&mut contiguous_row_selections);
8451 }
8452
8453 self.transact(window, cx, |this, window, cx| {
8454 this.unfold_ranges(&unfold_ranges, true, true, cx);
8455 this.buffer.update(cx, |buffer, cx| {
8456 for (range, text) in edits {
8457 buffer.edit([(range, text)], None, cx);
8458 }
8459 });
8460 this.fold_creases(refold_creases, true, window, cx);
8461 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8462 s.select(new_selections);
8463 })
8464 });
8465 }
8466
8467 pub fn move_line_down(
8468 &mut self,
8469 _: &MoveLineDown,
8470 window: &mut Window,
8471 cx: &mut Context<Self>,
8472 ) {
8473 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8474 let buffer = self.buffer.read(cx).snapshot(cx);
8475
8476 let mut edits = Vec::new();
8477 let mut unfold_ranges = Vec::new();
8478 let mut refold_creases = Vec::new();
8479
8480 let selections = self.selections.all::<Point>(cx);
8481 let mut selections = selections.iter().peekable();
8482 let mut contiguous_row_selections = Vec::new();
8483 let mut new_selections = Vec::new();
8484
8485 while let Some(selection) = selections.next() {
8486 // Find all the selections that span a contiguous row range
8487 let (start_row, end_row) = consume_contiguous_rows(
8488 &mut contiguous_row_selections,
8489 selection,
8490 &display_map,
8491 &mut selections,
8492 );
8493
8494 // Move the text spanned by the row range to be after the last line of the row range
8495 if end_row.0 <= buffer.max_point().row {
8496 let range_to_move =
8497 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8498 let insertion_point = display_map
8499 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8500 .0;
8501
8502 // Don't move lines across excerpt boundaries
8503 if buffer
8504 .excerpt_containing(range_to_move.start..insertion_point)
8505 .is_some()
8506 {
8507 let mut text = String::from("\n");
8508 text.extend(buffer.text_for_range(range_to_move.clone()));
8509 text.pop(); // Drop trailing newline
8510 edits.push((
8511 buffer.anchor_after(range_to_move.start)
8512 ..buffer.anchor_before(range_to_move.end),
8513 String::new(),
8514 ));
8515 let insertion_anchor = buffer.anchor_after(insertion_point);
8516 edits.push((insertion_anchor..insertion_anchor, text));
8517
8518 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8519
8520 // Move selections down
8521 new_selections.extend(contiguous_row_selections.drain(..).map(
8522 |mut selection| {
8523 selection.start.row += row_delta;
8524 selection.end.row += row_delta;
8525 selection
8526 },
8527 ));
8528
8529 // Move folds down
8530 unfold_ranges.push(range_to_move.clone());
8531 for fold in display_map.folds_in_range(
8532 buffer.anchor_before(range_to_move.start)
8533 ..buffer.anchor_after(range_to_move.end),
8534 ) {
8535 let mut start = fold.range.start.to_point(&buffer);
8536 let mut end = fold.range.end.to_point(&buffer);
8537 start.row += row_delta;
8538 end.row += row_delta;
8539 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8540 }
8541 }
8542 }
8543
8544 // If we didn't move line(s), preserve the existing selections
8545 new_selections.append(&mut contiguous_row_selections);
8546 }
8547
8548 self.transact(window, cx, |this, window, cx| {
8549 this.unfold_ranges(&unfold_ranges, true, true, cx);
8550 this.buffer.update(cx, |buffer, cx| {
8551 for (range, text) in edits {
8552 buffer.edit([(range, text)], None, cx);
8553 }
8554 });
8555 this.fold_creases(refold_creases, true, window, cx);
8556 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8557 s.select(new_selections)
8558 });
8559 });
8560 }
8561
8562 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8563 let text_layout_details = &self.text_layout_details(window);
8564 self.transact(window, cx, |this, window, cx| {
8565 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8566 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8567 let line_mode = s.line_mode;
8568 s.move_with(|display_map, selection| {
8569 if !selection.is_empty() || line_mode {
8570 return;
8571 }
8572
8573 let mut head = selection.head();
8574 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8575 if head.column() == display_map.line_len(head.row()) {
8576 transpose_offset = display_map
8577 .buffer_snapshot
8578 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8579 }
8580
8581 if transpose_offset == 0 {
8582 return;
8583 }
8584
8585 *head.column_mut() += 1;
8586 head = display_map.clip_point(head, Bias::Right);
8587 let goal = SelectionGoal::HorizontalPosition(
8588 display_map
8589 .x_for_display_point(head, text_layout_details)
8590 .into(),
8591 );
8592 selection.collapse_to(head, goal);
8593
8594 let transpose_start = display_map
8595 .buffer_snapshot
8596 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8597 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8598 let transpose_end = display_map
8599 .buffer_snapshot
8600 .clip_offset(transpose_offset + 1, Bias::Right);
8601 if let Some(ch) =
8602 display_map.buffer_snapshot.chars_at(transpose_start).next()
8603 {
8604 edits.push((transpose_start..transpose_offset, String::new()));
8605 edits.push((transpose_end..transpose_end, ch.to_string()));
8606 }
8607 }
8608 });
8609 edits
8610 });
8611 this.buffer
8612 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8613 let selections = this.selections.all::<usize>(cx);
8614 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8615 s.select(selections);
8616 });
8617 });
8618 }
8619
8620 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8621 self.rewrap_impl(false, cx)
8622 }
8623
8624 pub fn rewrap_impl(&mut self, override_language_settings: bool, cx: &mut Context<Self>) {
8625 let buffer = self.buffer.read(cx).snapshot(cx);
8626 let selections = self.selections.all::<Point>(cx);
8627 let mut selections = selections.iter().peekable();
8628
8629 let mut edits = Vec::new();
8630 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8631
8632 while let Some(selection) = selections.next() {
8633 let mut start_row = selection.start.row;
8634 let mut end_row = selection.end.row;
8635
8636 // Skip selections that overlap with a range that has already been rewrapped.
8637 let selection_range = start_row..end_row;
8638 if rewrapped_row_ranges
8639 .iter()
8640 .any(|range| range.overlaps(&selection_range))
8641 {
8642 continue;
8643 }
8644
8645 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
8646
8647 // Since not all lines in the selection may be at the same indent
8648 // level, choose the indent size that is the most common between all
8649 // of the lines.
8650 //
8651 // If there is a tie, we use the deepest indent.
8652 let (indent_size, indent_end) = {
8653 let mut indent_size_occurrences = HashMap::default();
8654 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8655
8656 for row in start_row..=end_row {
8657 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8658 rows_by_indent_size.entry(indent).or_default().push(row);
8659 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8660 }
8661
8662 let indent_size = indent_size_occurrences
8663 .into_iter()
8664 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8665 .map(|(indent, _)| indent)
8666 .unwrap_or_default();
8667 let row = rows_by_indent_size[&indent_size][0];
8668 let indent_end = Point::new(row, indent_size.len);
8669
8670 (indent_size, indent_end)
8671 };
8672
8673 let mut line_prefix = indent_size.chars().collect::<String>();
8674
8675 let mut inside_comment = false;
8676 if let Some(comment_prefix) =
8677 buffer
8678 .language_scope_at(selection.head())
8679 .and_then(|language| {
8680 language
8681 .line_comment_prefixes()
8682 .iter()
8683 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8684 .cloned()
8685 })
8686 {
8687 line_prefix.push_str(&comment_prefix);
8688 inside_comment = true;
8689 }
8690
8691 let language_settings = buffer.language_settings_at(selection.head(), cx);
8692 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8693 RewrapBehavior::InComments => inside_comment,
8694 RewrapBehavior::InSelections => !selection.is_empty(),
8695 RewrapBehavior::Anywhere => true,
8696 };
8697
8698 let should_rewrap = override_language_settings
8699 || allow_rewrap_based_on_language
8700 || self.hard_wrap.is_some();
8701 if !should_rewrap {
8702 continue;
8703 }
8704
8705 if selection.is_empty() {
8706 'expand_upwards: while start_row > 0 {
8707 let prev_row = start_row - 1;
8708 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8709 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8710 {
8711 start_row = prev_row;
8712 } else {
8713 break 'expand_upwards;
8714 }
8715 }
8716
8717 'expand_downwards: while end_row < buffer.max_point().row {
8718 let next_row = end_row + 1;
8719 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8720 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8721 {
8722 end_row = next_row;
8723 } else {
8724 break 'expand_downwards;
8725 }
8726 }
8727 }
8728
8729 let start = Point::new(start_row, 0);
8730 let start_offset = start.to_offset(&buffer);
8731 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8732 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8733 let Some(lines_without_prefixes) = selection_text
8734 .lines()
8735 .map(|line| {
8736 line.strip_prefix(&line_prefix)
8737 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8738 .ok_or_else(|| {
8739 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8740 })
8741 })
8742 .collect::<Result<Vec<_>, _>>()
8743 .log_err()
8744 else {
8745 continue;
8746 };
8747
8748 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
8749 buffer
8750 .language_settings_at(Point::new(start_row, 0), cx)
8751 .preferred_line_length as usize
8752 });
8753 let wrapped_text = wrap_with_prefix(
8754 line_prefix,
8755 lines_without_prefixes.join(" "),
8756 wrap_column,
8757 tab_size,
8758 );
8759
8760 // TODO: should always use char-based diff while still supporting cursor behavior that
8761 // matches vim.
8762 let mut diff_options = DiffOptions::default();
8763 if override_language_settings {
8764 diff_options.max_word_diff_len = 0;
8765 diff_options.max_word_diff_line_count = 0;
8766 } else {
8767 diff_options.max_word_diff_len = usize::MAX;
8768 diff_options.max_word_diff_line_count = usize::MAX;
8769 }
8770
8771 for (old_range, new_text) in
8772 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8773 {
8774 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8775 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8776 edits.push((edit_start..edit_end, new_text));
8777 }
8778
8779 rewrapped_row_ranges.push(start_row..=end_row);
8780 }
8781
8782 self.buffer
8783 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8784 }
8785
8786 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8787 let mut text = String::new();
8788 let buffer = self.buffer.read(cx).snapshot(cx);
8789 let mut selections = self.selections.all::<Point>(cx);
8790 let mut clipboard_selections = Vec::with_capacity(selections.len());
8791 {
8792 let max_point = buffer.max_point();
8793 let mut is_first = true;
8794 for selection in &mut selections {
8795 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8796 if is_entire_line {
8797 selection.start = Point::new(selection.start.row, 0);
8798 if !selection.is_empty() && selection.end.column == 0 {
8799 selection.end = cmp::min(max_point, selection.end);
8800 } else {
8801 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8802 }
8803 selection.goal = SelectionGoal::None;
8804 }
8805 if is_first {
8806 is_first = false;
8807 } else {
8808 text += "\n";
8809 }
8810 let mut len = 0;
8811 for chunk in buffer.text_for_range(selection.start..selection.end) {
8812 text.push_str(chunk);
8813 len += chunk.len();
8814 }
8815 clipboard_selections.push(ClipboardSelection {
8816 len,
8817 is_entire_line,
8818 first_line_indent: buffer
8819 .indent_size_for_line(MultiBufferRow(selection.start.row))
8820 .len,
8821 });
8822 }
8823 }
8824
8825 self.transact(window, cx, |this, window, cx| {
8826 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8827 s.select(selections);
8828 });
8829 this.insert("", window, cx);
8830 });
8831 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8832 }
8833
8834 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8835 let item = self.cut_common(window, cx);
8836 cx.write_to_clipboard(item);
8837 }
8838
8839 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8840 self.change_selections(None, window, cx, |s| {
8841 s.move_with(|snapshot, sel| {
8842 if sel.is_empty() {
8843 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8844 }
8845 });
8846 });
8847 let item = self.cut_common(window, cx);
8848 cx.set_global(KillRing(item))
8849 }
8850
8851 pub fn kill_ring_yank(
8852 &mut self,
8853 _: &KillRingYank,
8854 window: &mut Window,
8855 cx: &mut Context<Self>,
8856 ) {
8857 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8858 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8859 (kill_ring.text().to_string(), kill_ring.metadata_json())
8860 } else {
8861 return;
8862 }
8863 } else {
8864 return;
8865 };
8866 self.do_paste(&text, metadata, false, window, cx);
8867 }
8868
8869 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8870 let selections = self.selections.all::<Point>(cx);
8871 let buffer = self.buffer.read(cx).read(cx);
8872 let mut text = String::new();
8873
8874 let mut clipboard_selections = Vec::with_capacity(selections.len());
8875 {
8876 let max_point = buffer.max_point();
8877 let mut is_first = true;
8878 for selection in selections.iter() {
8879 let mut start = selection.start;
8880 let mut end = selection.end;
8881 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8882 if is_entire_line {
8883 start = Point::new(start.row, 0);
8884 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8885 }
8886 if is_first {
8887 is_first = false;
8888 } else {
8889 text += "\n";
8890 }
8891 let mut len = 0;
8892 for chunk in buffer.text_for_range(start..end) {
8893 text.push_str(chunk);
8894 len += chunk.len();
8895 }
8896 clipboard_selections.push(ClipboardSelection {
8897 len,
8898 is_entire_line,
8899 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8900 });
8901 }
8902 }
8903
8904 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8905 text,
8906 clipboard_selections,
8907 ));
8908 }
8909
8910 pub fn do_paste(
8911 &mut self,
8912 text: &String,
8913 clipboard_selections: Option<Vec<ClipboardSelection>>,
8914 handle_entire_lines: bool,
8915 window: &mut Window,
8916 cx: &mut Context<Self>,
8917 ) {
8918 if self.read_only(cx) {
8919 return;
8920 }
8921
8922 let clipboard_text = Cow::Borrowed(text);
8923
8924 self.transact(window, cx, |this, window, cx| {
8925 if let Some(mut clipboard_selections) = clipboard_selections {
8926 let old_selections = this.selections.all::<usize>(cx);
8927 let all_selections_were_entire_line =
8928 clipboard_selections.iter().all(|s| s.is_entire_line);
8929 let first_selection_indent_column =
8930 clipboard_selections.first().map(|s| s.first_line_indent);
8931 if clipboard_selections.len() != old_selections.len() {
8932 clipboard_selections.drain(..);
8933 }
8934 let cursor_offset = this.selections.last::<usize>(cx).head();
8935 let mut auto_indent_on_paste = true;
8936
8937 this.buffer.update(cx, |buffer, cx| {
8938 let snapshot = buffer.read(cx);
8939 auto_indent_on_paste = snapshot
8940 .language_settings_at(cursor_offset, cx)
8941 .auto_indent_on_paste;
8942
8943 let mut start_offset = 0;
8944 let mut edits = Vec::new();
8945 let mut original_indent_columns = Vec::new();
8946 for (ix, selection) in old_selections.iter().enumerate() {
8947 let to_insert;
8948 let entire_line;
8949 let original_indent_column;
8950 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8951 let end_offset = start_offset + clipboard_selection.len;
8952 to_insert = &clipboard_text[start_offset..end_offset];
8953 entire_line = clipboard_selection.is_entire_line;
8954 start_offset = end_offset + 1;
8955 original_indent_column = Some(clipboard_selection.first_line_indent);
8956 } else {
8957 to_insert = clipboard_text.as_str();
8958 entire_line = all_selections_were_entire_line;
8959 original_indent_column = first_selection_indent_column
8960 }
8961
8962 // If the corresponding selection was empty when this slice of the
8963 // clipboard text was written, then the entire line containing the
8964 // selection was copied. If this selection is also currently empty,
8965 // then paste the line before the current line of the buffer.
8966 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8967 let column = selection.start.to_point(&snapshot).column as usize;
8968 let line_start = selection.start - column;
8969 line_start..line_start
8970 } else {
8971 selection.range()
8972 };
8973
8974 edits.push((range, to_insert));
8975 original_indent_columns.push(original_indent_column);
8976 }
8977 drop(snapshot);
8978
8979 buffer.edit(
8980 edits,
8981 if auto_indent_on_paste {
8982 Some(AutoindentMode::Block {
8983 original_indent_columns,
8984 })
8985 } else {
8986 None
8987 },
8988 cx,
8989 );
8990 });
8991
8992 let selections = this.selections.all::<usize>(cx);
8993 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8994 s.select(selections)
8995 });
8996 } else {
8997 this.insert(&clipboard_text, window, cx);
8998 }
8999 });
9000 }
9001
9002 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
9003 if let Some(item) = cx.read_from_clipboard() {
9004 let entries = item.entries();
9005
9006 match entries.first() {
9007 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
9008 // of all the pasted entries.
9009 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
9010 .do_paste(
9011 clipboard_string.text(),
9012 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9013 true,
9014 window,
9015 cx,
9016 ),
9017 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9018 }
9019 }
9020 }
9021
9022 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9023 if self.read_only(cx) {
9024 return;
9025 }
9026
9027 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9028 if let Some((selections, _)) =
9029 self.selection_history.transaction(transaction_id).cloned()
9030 {
9031 self.change_selections(None, window, cx, |s| {
9032 s.select_anchors(selections.to_vec());
9033 });
9034 } else {
9035 log::error!(
9036 "No entry in selection_history found for undo. \
9037 This may correspond to a bug where undo does not update the selection. \
9038 If this is occurring, please add details to \
9039 https://github.com/zed-industries/zed/issues/22692"
9040 );
9041 }
9042 self.request_autoscroll(Autoscroll::fit(), cx);
9043 self.unmark_text(window, cx);
9044 self.refresh_inline_completion(true, false, window, cx);
9045 cx.emit(EditorEvent::Edited { transaction_id });
9046 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9047 }
9048 }
9049
9050 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9051 if self.read_only(cx) {
9052 return;
9053 }
9054
9055 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9056 if let Some((_, Some(selections))) =
9057 self.selection_history.transaction(transaction_id).cloned()
9058 {
9059 self.change_selections(None, window, cx, |s| {
9060 s.select_anchors(selections.to_vec());
9061 });
9062 } else {
9063 log::error!(
9064 "No entry in selection_history found for redo. \
9065 This may correspond to a bug where undo does not update the selection. \
9066 If this is occurring, please add details to \
9067 https://github.com/zed-industries/zed/issues/22692"
9068 );
9069 }
9070 self.request_autoscroll(Autoscroll::fit(), cx);
9071 self.unmark_text(window, cx);
9072 self.refresh_inline_completion(true, false, window, cx);
9073 cx.emit(EditorEvent::Edited { transaction_id });
9074 }
9075 }
9076
9077 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9078 self.buffer
9079 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9080 }
9081
9082 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9083 self.buffer
9084 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9085 }
9086
9087 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9088 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9089 let line_mode = s.line_mode;
9090 s.move_with(|map, selection| {
9091 let cursor = if selection.is_empty() && !line_mode {
9092 movement::left(map, selection.start)
9093 } else {
9094 selection.start
9095 };
9096 selection.collapse_to(cursor, SelectionGoal::None);
9097 });
9098 })
9099 }
9100
9101 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9102 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9103 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9104 })
9105 }
9106
9107 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9108 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9109 let line_mode = s.line_mode;
9110 s.move_with(|map, selection| {
9111 let cursor = if selection.is_empty() && !line_mode {
9112 movement::right(map, selection.end)
9113 } else {
9114 selection.end
9115 };
9116 selection.collapse_to(cursor, SelectionGoal::None)
9117 });
9118 })
9119 }
9120
9121 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9122 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9123 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9124 })
9125 }
9126
9127 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9128 if self.take_rename(true, window, cx).is_some() {
9129 return;
9130 }
9131
9132 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9133 cx.propagate();
9134 return;
9135 }
9136
9137 let text_layout_details = &self.text_layout_details(window);
9138 let selection_count = self.selections.count();
9139 let first_selection = self.selections.first_anchor();
9140
9141 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9142 let line_mode = s.line_mode;
9143 s.move_with(|map, selection| {
9144 if !selection.is_empty() && !line_mode {
9145 selection.goal = SelectionGoal::None;
9146 }
9147 let (cursor, goal) = movement::up(
9148 map,
9149 selection.start,
9150 selection.goal,
9151 false,
9152 text_layout_details,
9153 );
9154 selection.collapse_to(cursor, goal);
9155 });
9156 });
9157
9158 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9159 {
9160 cx.propagate();
9161 }
9162 }
9163
9164 pub fn move_up_by_lines(
9165 &mut self,
9166 action: &MoveUpByLines,
9167 window: &mut Window,
9168 cx: &mut Context<Self>,
9169 ) {
9170 if self.take_rename(true, window, cx).is_some() {
9171 return;
9172 }
9173
9174 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9175 cx.propagate();
9176 return;
9177 }
9178
9179 let text_layout_details = &self.text_layout_details(window);
9180
9181 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9182 let line_mode = s.line_mode;
9183 s.move_with(|map, selection| {
9184 if !selection.is_empty() && !line_mode {
9185 selection.goal = SelectionGoal::None;
9186 }
9187 let (cursor, goal) = movement::up_by_rows(
9188 map,
9189 selection.start,
9190 action.lines,
9191 selection.goal,
9192 false,
9193 text_layout_details,
9194 );
9195 selection.collapse_to(cursor, goal);
9196 });
9197 })
9198 }
9199
9200 pub fn move_down_by_lines(
9201 &mut self,
9202 action: &MoveDownByLines,
9203 window: &mut Window,
9204 cx: &mut Context<Self>,
9205 ) {
9206 if self.take_rename(true, window, cx).is_some() {
9207 return;
9208 }
9209
9210 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9211 cx.propagate();
9212 return;
9213 }
9214
9215 let text_layout_details = &self.text_layout_details(window);
9216
9217 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9218 let line_mode = s.line_mode;
9219 s.move_with(|map, selection| {
9220 if !selection.is_empty() && !line_mode {
9221 selection.goal = SelectionGoal::None;
9222 }
9223 let (cursor, goal) = movement::down_by_rows(
9224 map,
9225 selection.start,
9226 action.lines,
9227 selection.goal,
9228 false,
9229 text_layout_details,
9230 );
9231 selection.collapse_to(cursor, goal);
9232 });
9233 })
9234 }
9235
9236 pub fn select_down_by_lines(
9237 &mut self,
9238 action: &SelectDownByLines,
9239 window: &mut Window,
9240 cx: &mut Context<Self>,
9241 ) {
9242 let text_layout_details = &self.text_layout_details(window);
9243 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9244 s.move_heads_with(|map, head, goal| {
9245 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9246 })
9247 })
9248 }
9249
9250 pub fn select_up_by_lines(
9251 &mut self,
9252 action: &SelectUpByLines,
9253 window: &mut Window,
9254 cx: &mut Context<Self>,
9255 ) {
9256 let text_layout_details = &self.text_layout_details(window);
9257 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9258 s.move_heads_with(|map, head, goal| {
9259 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9260 })
9261 })
9262 }
9263
9264 pub fn select_page_up(
9265 &mut self,
9266 _: &SelectPageUp,
9267 window: &mut Window,
9268 cx: &mut Context<Self>,
9269 ) {
9270 let Some(row_count) = self.visible_row_count() else {
9271 return;
9272 };
9273
9274 let text_layout_details = &self.text_layout_details(window);
9275
9276 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9277 s.move_heads_with(|map, head, goal| {
9278 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9279 })
9280 })
9281 }
9282
9283 pub fn move_page_up(
9284 &mut self,
9285 action: &MovePageUp,
9286 window: &mut Window,
9287 cx: &mut Context<Self>,
9288 ) {
9289 if self.take_rename(true, window, cx).is_some() {
9290 return;
9291 }
9292
9293 if self
9294 .context_menu
9295 .borrow_mut()
9296 .as_mut()
9297 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9298 .unwrap_or(false)
9299 {
9300 return;
9301 }
9302
9303 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9304 cx.propagate();
9305 return;
9306 }
9307
9308 let Some(row_count) = self.visible_row_count() else {
9309 return;
9310 };
9311
9312 let autoscroll = if action.center_cursor {
9313 Autoscroll::center()
9314 } else {
9315 Autoscroll::fit()
9316 };
9317
9318 let text_layout_details = &self.text_layout_details(window);
9319
9320 self.change_selections(Some(autoscroll), window, cx, |s| {
9321 let line_mode = s.line_mode;
9322 s.move_with(|map, selection| {
9323 if !selection.is_empty() && !line_mode {
9324 selection.goal = SelectionGoal::None;
9325 }
9326 let (cursor, goal) = movement::up_by_rows(
9327 map,
9328 selection.end,
9329 row_count,
9330 selection.goal,
9331 false,
9332 text_layout_details,
9333 );
9334 selection.collapse_to(cursor, goal);
9335 });
9336 });
9337 }
9338
9339 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9340 let text_layout_details = &self.text_layout_details(window);
9341 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9342 s.move_heads_with(|map, head, goal| {
9343 movement::up(map, head, goal, false, text_layout_details)
9344 })
9345 })
9346 }
9347
9348 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9349 self.take_rename(true, window, cx);
9350
9351 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9352 cx.propagate();
9353 return;
9354 }
9355
9356 let text_layout_details = &self.text_layout_details(window);
9357 let selection_count = self.selections.count();
9358 let first_selection = self.selections.first_anchor();
9359
9360 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9361 let line_mode = s.line_mode;
9362 s.move_with(|map, selection| {
9363 if !selection.is_empty() && !line_mode {
9364 selection.goal = SelectionGoal::None;
9365 }
9366 let (cursor, goal) = movement::down(
9367 map,
9368 selection.end,
9369 selection.goal,
9370 false,
9371 text_layout_details,
9372 );
9373 selection.collapse_to(cursor, goal);
9374 });
9375 });
9376
9377 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9378 {
9379 cx.propagate();
9380 }
9381 }
9382
9383 pub fn select_page_down(
9384 &mut self,
9385 _: &SelectPageDown,
9386 window: &mut Window,
9387 cx: &mut Context<Self>,
9388 ) {
9389 let Some(row_count) = self.visible_row_count() else {
9390 return;
9391 };
9392
9393 let text_layout_details = &self.text_layout_details(window);
9394
9395 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9396 s.move_heads_with(|map, head, goal| {
9397 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9398 })
9399 })
9400 }
9401
9402 pub fn move_page_down(
9403 &mut self,
9404 action: &MovePageDown,
9405 window: &mut Window,
9406 cx: &mut Context<Self>,
9407 ) {
9408 if self.take_rename(true, window, cx).is_some() {
9409 return;
9410 }
9411
9412 if self
9413 .context_menu
9414 .borrow_mut()
9415 .as_mut()
9416 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9417 .unwrap_or(false)
9418 {
9419 return;
9420 }
9421
9422 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9423 cx.propagate();
9424 return;
9425 }
9426
9427 let Some(row_count) = self.visible_row_count() else {
9428 return;
9429 };
9430
9431 let autoscroll = if action.center_cursor {
9432 Autoscroll::center()
9433 } else {
9434 Autoscroll::fit()
9435 };
9436
9437 let text_layout_details = &self.text_layout_details(window);
9438 self.change_selections(Some(autoscroll), window, cx, |s| {
9439 let line_mode = s.line_mode;
9440 s.move_with(|map, selection| {
9441 if !selection.is_empty() && !line_mode {
9442 selection.goal = SelectionGoal::None;
9443 }
9444 let (cursor, goal) = movement::down_by_rows(
9445 map,
9446 selection.end,
9447 row_count,
9448 selection.goal,
9449 false,
9450 text_layout_details,
9451 );
9452 selection.collapse_to(cursor, goal);
9453 });
9454 });
9455 }
9456
9457 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9458 let text_layout_details = &self.text_layout_details(window);
9459 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9460 s.move_heads_with(|map, head, goal| {
9461 movement::down(map, head, goal, false, text_layout_details)
9462 })
9463 });
9464 }
9465
9466 pub fn context_menu_first(
9467 &mut self,
9468 _: &ContextMenuFirst,
9469 _window: &mut Window,
9470 cx: &mut Context<Self>,
9471 ) {
9472 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9473 context_menu.select_first(self.completion_provider.as_deref(), cx);
9474 }
9475 }
9476
9477 pub fn context_menu_prev(
9478 &mut self,
9479 _: &ContextMenuPrevious,
9480 _window: &mut Window,
9481 cx: &mut Context<Self>,
9482 ) {
9483 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9484 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9485 }
9486 }
9487
9488 pub fn context_menu_next(
9489 &mut self,
9490 _: &ContextMenuNext,
9491 _window: &mut Window,
9492 cx: &mut Context<Self>,
9493 ) {
9494 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9495 context_menu.select_next(self.completion_provider.as_deref(), cx);
9496 }
9497 }
9498
9499 pub fn context_menu_last(
9500 &mut self,
9501 _: &ContextMenuLast,
9502 _window: &mut Window,
9503 cx: &mut Context<Self>,
9504 ) {
9505 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9506 context_menu.select_last(self.completion_provider.as_deref(), cx);
9507 }
9508 }
9509
9510 pub fn move_to_previous_word_start(
9511 &mut self,
9512 _: &MoveToPreviousWordStart,
9513 window: &mut Window,
9514 cx: &mut Context<Self>,
9515 ) {
9516 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9517 s.move_cursors_with(|map, head, _| {
9518 (
9519 movement::previous_word_start(map, head),
9520 SelectionGoal::None,
9521 )
9522 });
9523 })
9524 }
9525
9526 pub fn move_to_previous_subword_start(
9527 &mut self,
9528 _: &MoveToPreviousSubwordStart,
9529 window: &mut Window,
9530 cx: &mut Context<Self>,
9531 ) {
9532 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9533 s.move_cursors_with(|map, head, _| {
9534 (
9535 movement::previous_subword_start(map, head),
9536 SelectionGoal::None,
9537 )
9538 });
9539 })
9540 }
9541
9542 pub fn select_to_previous_word_start(
9543 &mut self,
9544 _: &SelectToPreviousWordStart,
9545 window: &mut Window,
9546 cx: &mut Context<Self>,
9547 ) {
9548 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9549 s.move_heads_with(|map, head, _| {
9550 (
9551 movement::previous_word_start(map, head),
9552 SelectionGoal::None,
9553 )
9554 });
9555 })
9556 }
9557
9558 pub fn select_to_previous_subword_start(
9559 &mut self,
9560 _: &SelectToPreviousSubwordStart,
9561 window: &mut Window,
9562 cx: &mut Context<Self>,
9563 ) {
9564 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9565 s.move_heads_with(|map, head, _| {
9566 (
9567 movement::previous_subword_start(map, head),
9568 SelectionGoal::None,
9569 )
9570 });
9571 })
9572 }
9573
9574 pub fn delete_to_previous_word_start(
9575 &mut self,
9576 action: &DeleteToPreviousWordStart,
9577 window: &mut Window,
9578 cx: &mut Context<Self>,
9579 ) {
9580 self.transact(window, cx, |this, window, cx| {
9581 this.select_autoclose_pair(window, cx);
9582 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9583 let line_mode = s.line_mode;
9584 s.move_with(|map, selection| {
9585 if selection.is_empty() && !line_mode {
9586 let cursor = if action.ignore_newlines {
9587 movement::previous_word_start(map, selection.head())
9588 } else {
9589 movement::previous_word_start_or_newline(map, selection.head())
9590 };
9591 selection.set_head(cursor, SelectionGoal::None);
9592 }
9593 });
9594 });
9595 this.insert("", window, cx);
9596 });
9597 }
9598
9599 pub fn delete_to_previous_subword_start(
9600 &mut self,
9601 _: &DeleteToPreviousSubwordStart,
9602 window: &mut Window,
9603 cx: &mut Context<Self>,
9604 ) {
9605 self.transact(window, cx, |this, window, cx| {
9606 this.select_autoclose_pair(window, cx);
9607 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9608 let line_mode = s.line_mode;
9609 s.move_with(|map, selection| {
9610 if selection.is_empty() && !line_mode {
9611 let cursor = movement::previous_subword_start(map, selection.head());
9612 selection.set_head(cursor, SelectionGoal::None);
9613 }
9614 });
9615 });
9616 this.insert("", window, cx);
9617 });
9618 }
9619
9620 pub fn move_to_next_word_end(
9621 &mut self,
9622 _: &MoveToNextWordEnd,
9623 window: &mut Window,
9624 cx: &mut Context<Self>,
9625 ) {
9626 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9627 s.move_cursors_with(|map, head, _| {
9628 (movement::next_word_end(map, head), SelectionGoal::None)
9629 });
9630 })
9631 }
9632
9633 pub fn move_to_next_subword_end(
9634 &mut self,
9635 _: &MoveToNextSubwordEnd,
9636 window: &mut Window,
9637 cx: &mut Context<Self>,
9638 ) {
9639 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9640 s.move_cursors_with(|map, head, _| {
9641 (movement::next_subword_end(map, head), SelectionGoal::None)
9642 });
9643 })
9644 }
9645
9646 pub fn select_to_next_word_end(
9647 &mut self,
9648 _: &SelectToNextWordEnd,
9649 window: &mut Window,
9650 cx: &mut Context<Self>,
9651 ) {
9652 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9653 s.move_heads_with(|map, head, _| {
9654 (movement::next_word_end(map, head), SelectionGoal::None)
9655 });
9656 })
9657 }
9658
9659 pub fn select_to_next_subword_end(
9660 &mut self,
9661 _: &SelectToNextSubwordEnd,
9662 window: &mut Window,
9663 cx: &mut Context<Self>,
9664 ) {
9665 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9666 s.move_heads_with(|map, head, _| {
9667 (movement::next_subword_end(map, head), SelectionGoal::None)
9668 });
9669 })
9670 }
9671
9672 pub fn delete_to_next_word_end(
9673 &mut self,
9674 action: &DeleteToNextWordEnd,
9675 window: &mut Window,
9676 cx: &mut Context<Self>,
9677 ) {
9678 self.transact(window, cx, |this, window, cx| {
9679 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9680 let line_mode = s.line_mode;
9681 s.move_with(|map, selection| {
9682 if selection.is_empty() && !line_mode {
9683 let cursor = if action.ignore_newlines {
9684 movement::next_word_end(map, selection.head())
9685 } else {
9686 movement::next_word_end_or_newline(map, selection.head())
9687 };
9688 selection.set_head(cursor, SelectionGoal::None);
9689 }
9690 });
9691 });
9692 this.insert("", window, cx);
9693 });
9694 }
9695
9696 pub fn delete_to_next_subword_end(
9697 &mut self,
9698 _: &DeleteToNextSubwordEnd,
9699 window: &mut Window,
9700 cx: &mut Context<Self>,
9701 ) {
9702 self.transact(window, cx, |this, window, cx| {
9703 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9704 s.move_with(|map, selection| {
9705 if selection.is_empty() {
9706 let cursor = movement::next_subword_end(map, selection.head());
9707 selection.set_head(cursor, SelectionGoal::None);
9708 }
9709 });
9710 });
9711 this.insert("", window, cx);
9712 });
9713 }
9714
9715 pub fn move_to_beginning_of_line(
9716 &mut self,
9717 action: &MoveToBeginningOfLine,
9718 window: &mut Window,
9719 cx: &mut Context<Self>,
9720 ) {
9721 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9722 s.move_cursors_with(|map, head, _| {
9723 (
9724 movement::indented_line_beginning(
9725 map,
9726 head,
9727 action.stop_at_soft_wraps,
9728 action.stop_at_indent,
9729 ),
9730 SelectionGoal::None,
9731 )
9732 });
9733 })
9734 }
9735
9736 pub fn select_to_beginning_of_line(
9737 &mut self,
9738 action: &SelectToBeginningOfLine,
9739 window: &mut Window,
9740 cx: &mut Context<Self>,
9741 ) {
9742 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9743 s.move_heads_with(|map, head, _| {
9744 (
9745 movement::indented_line_beginning(
9746 map,
9747 head,
9748 action.stop_at_soft_wraps,
9749 action.stop_at_indent,
9750 ),
9751 SelectionGoal::None,
9752 )
9753 });
9754 });
9755 }
9756
9757 pub fn delete_to_beginning_of_line(
9758 &mut self,
9759 action: &DeleteToBeginningOfLine,
9760 window: &mut Window,
9761 cx: &mut Context<Self>,
9762 ) {
9763 self.transact(window, cx, |this, window, cx| {
9764 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9765 s.move_with(|_, selection| {
9766 selection.reversed = true;
9767 });
9768 });
9769
9770 this.select_to_beginning_of_line(
9771 &SelectToBeginningOfLine {
9772 stop_at_soft_wraps: false,
9773 stop_at_indent: action.stop_at_indent,
9774 },
9775 window,
9776 cx,
9777 );
9778 this.backspace(&Backspace, window, cx);
9779 });
9780 }
9781
9782 pub fn move_to_end_of_line(
9783 &mut self,
9784 action: &MoveToEndOfLine,
9785 window: &mut Window,
9786 cx: &mut Context<Self>,
9787 ) {
9788 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9789 s.move_cursors_with(|map, head, _| {
9790 (
9791 movement::line_end(map, head, action.stop_at_soft_wraps),
9792 SelectionGoal::None,
9793 )
9794 });
9795 })
9796 }
9797
9798 pub fn select_to_end_of_line(
9799 &mut self,
9800 action: &SelectToEndOfLine,
9801 window: &mut Window,
9802 cx: &mut Context<Self>,
9803 ) {
9804 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9805 s.move_heads_with(|map, head, _| {
9806 (
9807 movement::line_end(map, head, action.stop_at_soft_wraps),
9808 SelectionGoal::None,
9809 )
9810 });
9811 })
9812 }
9813
9814 pub fn delete_to_end_of_line(
9815 &mut self,
9816 _: &DeleteToEndOfLine,
9817 window: &mut Window,
9818 cx: &mut Context<Self>,
9819 ) {
9820 self.transact(window, cx, |this, window, cx| {
9821 this.select_to_end_of_line(
9822 &SelectToEndOfLine {
9823 stop_at_soft_wraps: false,
9824 },
9825 window,
9826 cx,
9827 );
9828 this.delete(&Delete, window, cx);
9829 });
9830 }
9831
9832 pub fn cut_to_end_of_line(
9833 &mut self,
9834 _: &CutToEndOfLine,
9835 window: &mut Window,
9836 cx: &mut Context<Self>,
9837 ) {
9838 self.transact(window, cx, |this, window, cx| {
9839 this.select_to_end_of_line(
9840 &SelectToEndOfLine {
9841 stop_at_soft_wraps: false,
9842 },
9843 window,
9844 cx,
9845 );
9846 this.cut(&Cut, window, cx);
9847 });
9848 }
9849
9850 pub fn move_to_start_of_paragraph(
9851 &mut self,
9852 _: &MoveToStartOfParagraph,
9853 window: &mut Window,
9854 cx: &mut Context<Self>,
9855 ) {
9856 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9857 cx.propagate();
9858 return;
9859 }
9860
9861 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9862 s.move_with(|map, selection| {
9863 selection.collapse_to(
9864 movement::start_of_paragraph(map, selection.head(), 1),
9865 SelectionGoal::None,
9866 )
9867 });
9868 })
9869 }
9870
9871 pub fn move_to_end_of_paragraph(
9872 &mut self,
9873 _: &MoveToEndOfParagraph,
9874 window: &mut Window,
9875 cx: &mut Context<Self>,
9876 ) {
9877 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9878 cx.propagate();
9879 return;
9880 }
9881
9882 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9883 s.move_with(|map, selection| {
9884 selection.collapse_to(
9885 movement::end_of_paragraph(map, selection.head(), 1),
9886 SelectionGoal::None,
9887 )
9888 });
9889 })
9890 }
9891
9892 pub fn select_to_start_of_paragraph(
9893 &mut self,
9894 _: &SelectToStartOfParagraph,
9895 window: &mut Window,
9896 cx: &mut Context<Self>,
9897 ) {
9898 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9899 cx.propagate();
9900 return;
9901 }
9902
9903 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9904 s.move_heads_with(|map, head, _| {
9905 (
9906 movement::start_of_paragraph(map, head, 1),
9907 SelectionGoal::None,
9908 )
9909 });
9910 })
9911 }
9912
9913 pub fn select_to_end_of_paragraph(
9914 &mut self,
9915 _: &SelectToEndOfParagraph,
9916 window: &mut Window,
9917 cx: &mut Context<Self>,
9918 ) {
9919 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9920 cx.propagate();
9921 return;
9922 }
9923
9924 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9925 s.move_heads_with(|map, head, _| {
9926 (
9927 movement::end_of_paragraph(map, head, 1),
9928 SelectionGoal::None,
9929 )
9930 });
9931 })
9932 }
9933
9934 pub fn move_to_start_of_excerpt(
9935 &mut self,
9936 _: &MoveToStartOfExcerpt,
9937 window: &mut Window,
9938 cx: &mut Context<Self>,
9939 ) {
9940 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9941 cx.propagate();
9942 return;
9943 }
9944
9945 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9946 s.move_with(|map, selection| {
9947 selection.collapse_to(
9948 movement::start_of_excerpt(
9949 map,
9950 selection.head(),
9951 workspace::searchable::Direction::Prev,
9952 ),
9953 SelectionGoal::None,
9954 )
9955 });
9956 })
9957 }
9958
9959 pub fn move_to_start_of_next_excerpt(
9960 &mut self,
9961 _: &MoveToStartOfNextExcerpt,
9962 window: &mut Window,
9963 cx: &mut Context<Self>,
9964 ) {
9965 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9966 cx.propagate();
9967 return;
9968 }
9969
9970 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9971 s.move_with(|map, selection| {
9972 selection.collapse_to(
9973 movement::start_of_excerpt(
9974 map,
9975 selection.head(),
9976 workspace::searchable::Direction::Next,
9977 ),
9978 SelectionGoal::None,
9979 )
9980 });
9981 })
9982 }
9983
9984 pub fn move_to_end_of_excerpt(
9985 &mut self,
9986 _: &MoveToEndOfExcerpt,
9987 window: &mut Window,
9988 cx: &mut Context<Self>,
9989 ) {
9990 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9991 cx.propagate();
9992 return;
9993 }
9994
9995 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9996 s.move_with(|map, selection| {
9997 selection.collapse_to(
9998 movement::end_of_excerpt(
9999 map,
10000 selection.head(),
10001 workspace::searchable::Direction::Next,
10002 ),
10003 SelectionGoal::None,
10004 )
10005 });
10006 })
10007 }
10008
10009 pub fn move_to_end_of_previous_excerpt(
10010 &mut self,
10011 _: &MoveToEndOfPreviousExcerpt,
10012 window: &mut Window,
10013 cx: &mut Context<Self>,
10014 ) {
10015 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10016 cx.propagate();
10017 return;
10018 }
10019
10020 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10021 s.move_with(|map, selection| {
10022 selection.collapse_to(
10023 movement::end_of_excerpt(
10024 map,
10025 selection.head(),
10026 workspace::searchable::Direction::Prev,
10027 ),
10028 SelectionGoal::None,
10029 )
10030 });
10031 })
10032 }
10033
10034 pub fn select_to_start_of_excerpt(
10035 &mut self,
10036 _: &SelectToStartOfExcerpt,
10037 window: &mut Window,
10038 cx: &mut Context<Self>,
10039 ) {
10040 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10041 cx.propagate();
10042 return;
10043 }
10044
10045 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10046 s.move_heads_with(|map, head, _| {
10047 (
10048 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10049 SelectionGoal::None,
10050 )
10051 });
10052 })
10053 }
10054
10055 pub fn select_to_start_of_next_excerpt(
10056 &mut self,
10057 _: &SelectToStartOfNextExcerpt,
10058 window: &mut Window,
10059 cx: &mut Context<Self>,
10060 ) {
10061 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10062 cx.propagate();
10063 return;
10064 }
10065
10066 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10067 s.move_heads_with(|map, head, _| {
10068 (
10069 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10070 SelectionGoal::None,
10071 )
10072 });
10073 })
10074 }
10075
10076 pub fn select_to_end_of_excerpt(
10077 &mut self,
10078 _: &SelectToEndOfExcerpt,
10079 window: &mut Window,
10080 cx: &mut Context<Self>,
10081 ) {
10082 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10083 cx.propagate();
10084 return;
10085 }
10086
10087 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10088 s.move_heads_with(|map, head, _| {
10089 (
10090 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10091 SelectionGoal::None,
10092 )
10093 });
10094 })
10095 }
10096
10097 pub fn select_to_end_of_previous_excerpt(
10098 &mut self,
10099 _: &SelectToEndOfPreviousExcerpt,
10100 window: &mut Window,
10101 cx: &mut Context<Self>,
10102 ) {
10103 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10104 cx.propagate();
10105 return;
10106 }
10107
10108 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10109 s.move_heads_with(|map, head, _| {
10110 (
10111 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10112 SelectionGoal::None,
10113 )
10114 });
10115 })
10116 }
10117
10118 pub fn move_to_beginning(
10119 &mut self,
10120 _: &MoveToBeginning,
10121 window: &mut Window,
10122 cx: &mut Context<Self>,
10123 ) {
10124 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10125 cx.propagate();
10126 return;
10127 }
10128
10129 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10130 s.select_ranges(vec![0..0]);
10131 });
10132 }
10133
10134 pub fn select_to_beginning(
10135 &mut self,
10136 _: &SelectToBeginning,
10137 window: &mut Window,
10138 cx: &mut Context<Self>,
10139 ) {
10140 let mut selection = self.selections.last::<Point>(cx);
10141 selection.set_head(Point::zero(), SelectionGoal::None);
10142
10143 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10144 s.select(vec![selection]);
10145 });
10146 }
10147
10148 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10149 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10150 cx.propagate();
10151 return;
10152 }
10153
10154 let cursor = self.buffer.read(cx).read(cx).len();
10155 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10156 s.select_ranges(vec![cursor..cursor])
10157 });
10158 }
10159
10160 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10161 self.nav_history = nav_history;
10162 }
10163
10164 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10165 self.nav_history.as_ref()
10166 }
10167
10168 fn push_to_nav_history(
10169 &mut self,
10170 cursor_anchor: Anchor,
10171 new_position: Option<Point>,
10172 cx: &mut Context<Self>,
10173 ) {
10174 if let Some(nav_history) = self.nav_history.as_mut() {
10175 let buffer = self.buffer.read(cx).read(cx);
10176 let cursor_position = cursor_anchor.to_point(&buffer);
10177 let scroll_state = self.scroll_manager.anchor();
10178 let scroll_top_row = scroll_state.top_row(&buffer);
10179 drop(buffer);
10180
10181 if let Some(new_position) = new_position {
10182 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10183 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10184 return;
10185 }
10186 }
10187
10188 nav_history.push(
10189 Some(NavigationData {
10190 cursor_anchor,
10191 cursor_position,
10192 scroll_anchor: scroll_state,
10193 scroll_top_row,
10194 }),
10195 cx,
10196 );
10197 }
10198 }
10199
10200 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10201 let buffer = self.buffer.read(cx).snapshot(cx);
10202 let mut selection = self.selections.first::<usize>(cx);
10203 selection.set_head(buffer.len(), SelectionGoal::None);
10204 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10205 s.select(vec![selection]);
10206 });
10207 }
10208
10209 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10210 let end = self.buffer.read(cx).read(cx).len();
10211 self.change_selections(None, window, cx, |s| {
10212 s.select_ranges(vec![0..end]);
10213 });
10214 }
10215
10216 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10217 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10218 let mut selections = self.selections.all::<Point>(cx);
10219 let max_point = display_map.buffer_snapshot.max_point();
10220 for selection in &mut selections {
10221 let rows = selection.spanned_rows(true, &display_map);
10222 selection.start = Point::new(rows.start.0, 0);
10223 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10224 selection.reversed = false;
10225 }
10226 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10227 s.select(selections);
10228 });
10229 }
10230
10231 pub fn split_selection_into_lines(
10232 &mut self,
10233 _: &SplitSelectionIntoLines,
10234 window: &mut Window,
10235 cx: &mut Context<Self>,
10236 ) {
10237 let selections = self
10238 .selections
10239 .all::<Point>(cx)
10240 .into_iter()
10241 .map(|selection| selection.start..selection.end)
10242 .collect::<Vec<_>>();
10243 self.unfold_ranges(&selections, true, true, cx);
10244
10245 let mut new_selection_ranges = Vec::new();
10246 {
10247 let buffer = self.buffer.read(cx).read(cx);
10248 for selection in selections {
10249 for row in selection.start.row..selection.end.row {
10250 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10251 new_selection_ranges.push(cursor..cursor);
10252 }
10253
10254 let is_multiline_selection = selection.start.row != selection.end.row;
10255 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10256 // so this action feels more ergonomic when paired with other selection operations
10257 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10258 if !should_skip_last {
10259 new_selection_ranges.push(selection.end..selection.end);
10260 }
10261 }
10262 }
10263 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10264 s.select_ranges(new_selection_ranges);
10265 });
10266 }
10267
10268 pub fn add_selection_above(
10269 &mut self,
10270 _: &AddSelectionAbove,
10271 window: &mut Window,
10272 cx: &mut Context<Self>,
10273 ) {
10274 self.add_selection(true, window, cx);
10275 }
10276
10277 pub fn add_selection_below(
10278 &mut self,
10279 _: &AddSelectionBelow,
10280 window: &mut Window,
10281 cx: &mut Context<Self>,
10282 ) {
10283 self.add_selection(false, window, cx);
10284 }
10285
10286 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10287 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10288 let mut selections = self.selections.all::<Point>(cx);
10289 let text_layout_details = self.text_layout_details(window);
10290 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10291 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10292 let range = oldest_selection.display_range(&display_map).sorted();
10293
10294 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10295 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10296 let positions = start_x.min(end_x)..start_x.max(end_x);
10297
10298 selections.clear();
10299 let mut stack = Vec::new();
10300 for row in range.start.row().0..=range.end.row().0 {
10301 if let Some(selection) = self.selections.build_columnar_selection(
10302 &display_map,
10303 DisplayRow(row),
10304 &positions,
10305 oldest_selection.reversed,
10306 &text_layout_details,
10307 ) {
10308 stack.push(selection.id);
10309 selections.push(selection);
10310 }
10311 }
10312
10313 if above {
10314 stack.reverse();
10315 }
10316
10317 AddSelectionsState { above, stack }
10318 });
10319
10320 let last_added_selection = *state.stack.last().unwrap();
10321 let mut new_selections = Vec::new();
10322 if above == state.above {
10323 let end_row = if above {
10324 DisplayRow(0)
10325 } else {
10326 display_map.max_point().row()
10327 };
10328
10329 'outer: for selection in selections {
10330 if selection.id == last_added_selection {
10331 let range = selection.display_range(&display_map).sorted();
10332 debug_assert_eq!(range.start.row(), range.end.row());
10333 let mut row = range.start.row();
10334 let positions =
10335 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10336 px(start)..px(end)
10337 } else {
10338 let start_x =
10339 display_map.x_for_display_point(range.start, &text_layout_details);
10340 let end_x =
10341 display_map.x_for_display_point(range.end, &text_layout_details);
10342 start_x.min(end_x)..start_x.max(end_x)
10343 };
10344
10345 while row != end_row {
10346 if above {
10347 row.0 -= 1;
10348 } else {
10349 row.0 += 1;
10350 }
10351
10352 if let Some(new_selection) = self.selections.build_columnar_selection(
10353 &display_map,
10354 row,
10355 &positions,
10356 selection.reversed,
10357 &text_layout_details,
10358 ) {
10359 state.stack.push(new_selection.id);
10360 if above {
10361 new_selections.push(new_selection);
10362 new_selections.push(selection);
10363 } else {
10364 new_selections.push(selection);
10365 new_selections.push(new_selection);
10366 }
10367
10368 continue 'outer;
10369 }
10370 }
10371 }
10372
10373 new_selections.push(selection);
10374 }
10375 } else {
10376 new_selections = selections;
10377 new_selections.retain(|s| s.id != last_added_selection);
10378 state.stack.pop();
10379 }
10380
10381 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10382 s.select(new_selections);
10383 });
10384 if state.stack.len() > 1 {
10385 self.add_selections_state = Some(state);
10386 }
10387 }
10388
10389 pub fn select_next_match_internal(
10390 &mut self,
10391 display_map: &DisplaySnapshot,
10392 replace_newest: bool,
10393 autoscroll: Option<Autoscroll>,
10394 window: &mut Window,
10395 cx: &mut Context<Self>,
10396 ) -> Result<()> {
10397 fn select_next_match_ranges(
10398 this: &mut Editor,
10399 range: Range<usize>,
10400 replace_newest: bool,
10401 auto_scroll: Option<Autoscroll>,
10402 window: &mut Window,
10403 cx: &mut Context<Editor>,
10404 ) {
10405 this.unfold_ranges(&[range.clone()], false, true, cx);
10406 this.change_selections(auto_scroll, window, cx, |s| {
10407 if replace_newest {
10408 s.delete(s.newest_anchor().id);
10409 }
10410 s.insert_range(range.clone());
10411 });
10412 }
10413
10414 let buffer = &display_map.buffer_snapshot;
10415 let mut selections = self.selections.all::<usize>(cx);
10416 if let Some(mut select_next_state) = self.select_next_state.take() {
10417 let query = &select_next_state.query;
10418 if !select_next_state.done {
10419 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10420 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10421 let mut next_selected_range = None;
10422
10423 let bytes_after_last_selection =
10424 buffer.bytes_in_range(last_selection.end..buffer.len());
10425 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10426 let query_matches = query
10427 .stream_find_iter(bytes_after_last_selection)
10428 .map(|result| (last_selection.end, result))
10429 .chain(
10430 query
10431 .stream_find_iter(bytes_before_first_selection)
10432 .map(|result| (0, result)),
10433 );
10434
10435 for (start_offset, query_match) in query_matches {
10436 let query_match = query_match.unwrap(); // can only fail due to I/O
10437 let offset_range =
10438 start_offset + query_match.start()..start_offset + query_match.end();
10439 let display_range = offset_range.start.to_display_point(display_map)
10440 ..offset_range.end.to_display_point(display_map);
10441
10442 if !select_next_state.wordwise
10443 || (!movement::is_inside_word(display_map, display_range.start)
10444 && !movement::is_inside_word(display_map, display_range.end))
10445 {
10446 // TODO: This is n^2, because we might check all the selections
10447 if !selections
10448 .iter()
10449 .any(|selection| selection.range().overlaps(&offset_range))
10450 {
10451 next_selected_range = Some(offset_range);
10452 break;
10453 }
10454 }
10455 }
10456
10457 if let Some(next_selected_range) = next_selected_range {
10458 select_next_match_ranges(
10459 self,
10460 next_selected_range,
10461 replace_newest,
10462 autoscroll,
10463 window,
10464 cx,
10465 );
10466 } else {
10467 select_next_state.done = true;
10468 }
10469 }
10470
10471 self.select_next_state = Some(select_next_state);
10472 } else {
10473 let mut only_carets = true;
10474 let mut same_text_selected = true;
10475 let mut selected_text = None;
10476
10477 let mut selections_iter = selections.iter().peekable();
10478 while let Some(selection) = selections_iter.next() {
10479 if selection.start != selection.end {
10480 only_carets = false;
10481 }
10482
10483 if same_text_selected {
10484 if selected_text.is_none() {
10485 selected_text =
10486 Some(buffer.text_for_range(selection.range()).collect::<String>());
10487 }
10488
10489 if let Some(next_selection) = selections_iter.peek() {
10490 if next_selection.range().len() == selection.range().len() {
10491 let next_selected_text = buffer
10492 .text_for_range(next_selection.range())
10493 .collect::<String>();
10494 if Some(next_selected_text) != selected_text {
10495 same_text_selected = false;
10496 selected_text = None;
10497 }
10498 } else {
10499 same_text_selected = false;
10500 selected_text = None;
10501 }
10502 }
10503 }
10504 }
10505
10506 if only_carets {
10507 for selection in &mut selections {
10508 let word_range = movement::surrounding_word(
10509 display_map,
10510 selection.start.to_display_point(display_map),
10511 );
10512 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10513 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10514 selection.goal = SelectionGoal::None;
10515 selection.reversed = false;
10516 select_next_match_ranges(
10517 self,
10518 selection.start..selection.end,
10519 replace_newest,
10520 autoscroll,
10521 window,
10522 cx,
10523 );
10524 }
10525
10526 if selections.len() == 1 {
10527 let selection = selections
10528 .last()
10529 .expect("ensured that there's only one selection");
10530 let query = buffer
10531 .text_for_range(selection.start..selection.end)
10532 .collect::<String>();
10533 let is_empty = query.is_empty();
10534 let select_state = SelectNextState {
10535 query: AhoCorasick::new(&[query])?,
10536 wordwise: true,
10537 done: is_empty,
10538 };
10539 self.select_next_state = Some(select_state);
10540 } else {
10541 self.select_next_state = None;
10542 }
10543 } else if let Some(selected_text) = selected_text {
10544 self.select_next_state = Some(SelectNextState {
10545 query: AhoCorasick::new(&[selected_text])?,
10546 wordwise: false,
10547 done: false,
10548 });
10549 self.select_next_match_internal(
10550 display_map,
10551 replace_newest,
10552 autoscroll,
10553 window,
10554 cx,
10555 )?;
10556 }
10557 }
10558 Ok(())
10559 }
10560
10561 pub fn select_all_matches(
10562 &mut self,
10563 _action: &SelectAllMatches,
10564 window: &mut Window,
10565 cx: &mut Context<Self>,
10566 ) -> Result<()> {
10567 self.push_to_selection_history();
10568 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10569
10570 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10571 let Some(select_next_state) = self.select_next_state.as_mut() else {
10572 return Ok(());
10573 };
10574 if select_next_state.done {
10575 return Ok(());
10576 }
10577
10578 let mut new_selections = self.selections.all::<usize>(cx);
10579
10580 let buffer = &display_map.buffer_snapshot;
10581 let query_matches = select_next_state
10582 .query
10583 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10584
10585 for query_match in query_matches {
10586 let query_match = query_match.unwrap(); // can only fail due to I/O
10587 let offset_range = query_match.start()..query_match.end();
10588 let display_range = offset_range.start.to_display_point(&display_map)
10589 ..offset_range.end.to_display_point(&display_map);
10590
10591 if !select_next_state.wordwise
10592 || (!movement::is_inside_word(&display_map, display_range.start)
10593 && !movement::is_inside_word(&display_map, display_range.end))
10594 {
10595 self.selections.change_with(cx, |selections| {
10596 new_selections.push(Selection {
10597 id: selections.new_selection_id(),
10598 start: offset_range.start,
10599 end: offset_range.end,
10600 reversed: false,
10601 goal: SelectionGoal::None,
10602 });
10603 });
10604 }
10605 }
10606
10607 new_selections.sort_by_key(|selection| selection.start);
10608 let mut ix = 0;
10609 while ix + 1 < new_selections.len() {
10610 let current_selection = &new_selections[ix];
10611 let next_selection = &new_selections[ix + 1];
10612 if current_selection.range().overlaps(&next_selection.range()) {
10613 if current_selection.id < next_selection.id {
10614 new_selections.remove(ix + 1);
10615 } else {
10616 new_selections.remove(ix);
10617 }
10618 } else {
10619 ix += 1;
10620 }
10621 }
10622
10623 let reversed = self.selections.oldest::<usize>(cx).reversed;
10624
10625 for selection in new_selections.iter_mut() {
10626 selection.reversed = reversed;
10627 }
10628
10629 select_next_state.done = true;
10630 self.unfold_ranges(
10631 &new_selections
10632 .iter()
10633 .map(|selection| selection.range())
10634 .collect::<Vec<_>>(),
10635 false,
10636 false,
10637 cx,
10638 );
10639 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10640 selections.select(new_selections)
10641 });
10642
10643 Ok(())
10644 }
10645
10646 pub fn select_next(
10647 &mut self,
10648 action: &SelectNext,
10649 window: &mut Window,
10650 cx: &mut Context<Self>,
10651 ) -> Result<()> {
10652 self.push_to_selection_history();
10653 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10654 self.select_next_match_internal(
10655 &display_map,
10656 action.replace_newest,
10657 Some(Autoscroll::newest()),
10658 window,
10659 cx,
10660 )?;
10661 Ok(())
10662 }
10663
10664 pub fn select_previous(
10665 &mut self,
10666 action: &SelectPrevious,
10667 window: &mut Window,
10668 cx: &mut Context<Self>,
10669 ) -> Result<()> {
10670 self.push_to_selection_history();
10671 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10672 let buffer = &display_map.buffer_snapshot;
10673 let mut selections = self.selections.all::<usize>(cx);
10674 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10675 let query = &select_prev_state.query;
10676 if !select_prev_state.done {
10677 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10678 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10679 let mut next_selected_range = None;
10680 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10681 let bytes_before_last_selection =
10682 buffer.reversed_bytes_in_range(0..last_selection.start);
10683 let bytes_after_first_selection =
10684 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10685 let query_matches = query
10686 .stream_find_iter(bytes_before_last_selection)
10687 .map(|result| (last_selection.start, result))
10688 .chain(
10689 query
10690 .stream_find_iter(bytes_after_first_selection)
10691 .map(|result| (buffer.len(), result)),
10692 );
10693 for (end_offset, query_match) in query_matches {
10694 let query_match = query_match.unwrap(); // can only fail due to I/O
10695 let offset_range =
10696 end_offset - query_match.end()..end_offset - query_match.start();
10697 let display_range = offset_range.start.to_display_point(&display_map)
10698 ..offset_range.end.to_display_point(&display_map);
10699
10700 if !select_prev_state.wordwise
10701 || (!movement::is_inside_word(&display_map, display_range.start)
10702 && !movement::is_inside_word(&display_map, display_range.end))
10703 {
10704 next_selected_range = Some(offset_range);
10705 break;
10706 }
10707 }
10708
10709 if let Some(next_selected_range) = next_selected_range {
10710 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10711 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10712 if action.replace_newest {
10713 s.delete(s.newest_anchor().id);
10714 }
10715 s.insert_range(next_selected_range);
10716 });
10717 } else {
10718 select_prev_state.done = true;
10719 }
10720 }
10721
10722 self.select_prev_state = Some(select_prev_state);
10723 } else {
10724 let mut only_carets = true;
10725 let mut same_text_selected = true;
10726 let mut selected_text = None;
10727
10728 let mut selections_iter = selections.iter().peekable();
10729 while let Some(selection) = selections_iter.next() {
10730 if selection.start != selection.end {
10731 only_carets = false;
10732 }
10733
10734 if same_text_selected {
10735 if selected_text.is_none() {
10736 selected_text =
10737 Some(buffer.text_for_range(selection.range()).collect::<String>());
10738 }
10739
10740 if let Some(next_selection) = selections_iter.peek() {
10741 if next_selection.range().len() == selection.range().len() {
10742 let next_selected_text = buffer
10743 .text_for_range(next_selection.range())
10744 .collect::<String>();
10745 if Some(next_selected_text) != selected_text {
10746 same_text_selected = false;
10747 selected_text = None;
10748 }
10749 } else {
10750 same_text_selected = false;
10751 selected_text = None;
10752 }
10753 }
10754 }
10755 }
10756
10757 if only_carets {
10758 for selection in &mut selections {
10759 let word_range = movement::surrounding_word(
10760 &display_map,
10761 selection.start.to_display_point(&display_map),
10762 );
10763 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10764 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10765 selection.goal = SelectionGoal::None;
10766 selection.reversed = false;
10767 }
10768 if selections.len() == 1 {
10769 let selection = selections
10770 .last()
10771 .expect("ensured that there's only one selection");
10772 let query = buffer
10773 .text_for_range(selection.start..selection.end)
10774 .collect::<String>();
10775 let is_empty = query.is_empty();
10776 let select_state = SelectNextState {
10777 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10778 wordwise: true,
10779 done: is_empty,
10780 };
10781 self.select_prev_state = Some(select_state);
10782 } else {
10783 self.select_prev_state = None;
10784 }
10785
10786 self.unfold_ranges(
10787 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10788 false,
10789 true,
10790 cx,
10791 );
10792 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10793 s.select(selections);
10794 });
10795 } else if let Some(selected_text) = selected_text {
10796 self.select_prev_state = Some(SelectNextState {
10797 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10798 wordwise: false,
10799 done: false,
10800 });
10801 self.select_previous(action, window, cx)?;
10802 }
10803 }
10804 Ok(())
10805 }
10806
10807 pub fn toggle_comments(
10808 &mut self,
10809 action: &ToggleComments,
10810 window: &mut Window,
10811 cx: &mut Context<Self>,
10812 ) {
10813 if self.read_only(cx) {
10814 return;
10815 }
10816 let text_layout_details = &self.text_layout_details(window);
10817 self.transact(window, cx, |this, window, cx| {
10818 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10819 let mut edits = Vec::new();
10820 let mut selection_edit_ranges = Vec::new();
10821 let mut last_toggled_row = None;
10822 let snapshot = this.buffer.read(cx).read(cx);
10823 let empty_str: Arc<str> = Arc::default();
10824 let mut suffixes_inserted = Vec::new();
10825 let ignore_indent = action.ignore_indent;
10826
10827 fn comment_prefix_range(
10828 snapshot: &MultiBufferSnapshot,
10829 row: MultiBufferRow,
10830 comment_prefix: &str,
10831 comment_prefix_whitespace: &str,
10832 ignore_indent: bool,
10833 ) -> Range<Point> {
10834 let indent_size = if ignore_indent {
10835 0
10836 } else {
10837 snapshot.indent_size_for_line(row).len
10838 };
10839
10840 let start = Point::new(row.0, indent_size);
10841
10842 let mut line_bytes = snapshot
10843 .bytes_in_range(start..snapshot.max_point())
10844 .flatten()
10845 .copied();
10846
10847 // If this line currently begins with the line comment prefix, then record
10848 // the range containing the prefix.
10849 if line_bytes
10850 .by_ref()
10851 .take(comment_prefix.len())
10852 .eq(comment_prefix.bytes())
10853 {
10854 // Include any whitespace that matches the comment prefix.
10855 let matching_whitespace_len = line_bytes
10856 .zip(comment_prefix_whitespace.bytes())
10857 .take_while(|(a, b)| a == b)
10858 .count() as u32;
10859 let end = Point::new(
10860 start.row,
10861 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10862 );
10863 start..end
10864 } else {
10865 start..start
10866 }
10867 }
10868
10869 fn comment_suffix_range(
10870 snapshot: &MultiBufferSnapshot,
10871 row: MultiBufferRow,
10872 comment_suffix: &str,
10873 comment_suffix_has_leading_space: bool,
10874 ) -> Range<Point> {
10875 let end = Point::new(row.0, snapshot.line_len(row));
10876 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10877
10878 let mut line_end_bytes = snapshot
10879 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10880 .flatten()
10881 .copied();
10882
10883 let leading_space_len = if suffix_start_column > 0
10884 && line_end_bytes.next() == Some(b' ')
10885 && comment_suffix_has_leading_space
10886 {
10887 1
10888 } else {
10889 0
10890 };
10891
10892 // If this line currently begins with the line comment prefix, then record
10893 // the range containing the prefix.
10894 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10895 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10896 start..end
10897 } else {
10898 end..end
10899 }
10900 }
10901
10902 // TODO: Handle selections that cross excerpts
10903 for selection in &mut selections {
10904 let start_column = snapshot
10905 .indent_size_for_line(MultiBufferRow(selection.start.row))
10906 .len;
10907 let language = if let Some(language) =
10908 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10909 {
10910 language
10911 } else {
10912 continue;
10913 };
10914
10915 selection_edit_ranges.clear();
10916
10917 // If multiple selections contain a given row, avoid processing that
10918 // row more than once.
10919 let mut start_row = MultiBufferRow(selection.start.row);
10920 if last_toggled_row == Some(start_row) {
10921 start_row = start_row.next_row();
10922 }
10923 let end_row =
10924 if selection.end.row > selection.start.row && selection.end.column == 0 {
10925 MultiBufferRow(selection.end.row - 1)
10926 } else {
10927 MultiBufferRow(selection.end.row)
10928 };
10929 last_toggled_row = Some(end_row);
10930
10931 if start_row > end_row {
10932 continue;
10933 }
10934
10935 // If the language has line comments, toggle those.
10936 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10937
10938 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10939 if ignore_indent {
10940 full_comment_prefixes = full_comment_prefixes
10941 .into_iter()
10942 .map(|s| Arc::from(s.trim_end()))
10943 .collect();
10944 }
10945
10946 if !full_comment_prefixes.is_empty() {
10947 let first_prefix = full_comment_prefixes
10948 .first()
10949 .expect("prefixes is non-empty");
10950 let prefix_trimmed_lengths = full_comment_prefixes
10951 .iter()
10952 .map(|p| p.trim_end_matches(' ').len())
10953 .collect::<SmallVec<[usize; 4]>>();
10954
10955 let mut all_selection_lines_are_comments = true;
10956
10957 for row in start_row.0..=end_row.0 {
10958 let row = MultiBufferRow(row);
10959 if start_row < end_row && snapshot.is_line_blank(row) {
10960 continue;
10961 }
10962
10963 let prefix_range = full_comment_prefixes
10964 .iter()
10965 .zip(prefix_trimmed_lengths.iter().copied())
10966 .map(|(prefix, trimmed_prefix_len)| {
10967 comment_prefix_range(
10968 snapshot.deref(),
10969 row,
10970 &prefix[..trimmed_prefix_len],
10971 &prefix[trimmed_prefix_len..],
10972 ignore_indent,
10973 )
10974 })
10975 .max_by_key(|range| range.end.column - range.start.column)
10976 .expect("prefixes is non-empty");
10977
10978 if prefix_range.is_empty() {
10979 all_selection_lines_are_comments = false;
10980 }
10981
10982 selection_edit_ranges.push(prefix_range);
10983 }
10984
10985 if all_selection_lines_are_comments {
10986 edits.extend(
10987 selection_edit_ranges
10988 .iter()
10989 .cloned()
10990 .map(|range| (range, empty_str.clone())),
10991 );
10992 } else {
10993 let min_column = selection_edit_ranges
10994 .iter()
10995 .map(|range| range.start.column)
10996 .min()
10997 .unwrap_or(0);
10998 edits.extend(selection_edit_ranges.iter().map(|range| {
10999 let position = Point::new(range.start.row, min_column);
11000 (position..position, first_prefix.clone())
11001 }));
11002 }
11003 } else if let Some((full_comment_prefix, comment_suffix)) =
11004 language.block_comment_delimiters()
11005 {
11006 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11007 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11008 let prefix_range = comment_prefix_range(
11009 snapshot.deref(),
11010 start_row,
11011 comment_prefix,
11012 comment_prefix_whitespace,
11013 ignore_indent,
11014 );
11015 let suffix_range = comment_suffix_range(
11016 snapshot.deref(),
11017 end_row,
11018 comment_suffix.trim_start_matches(' '),
11019 comment_suffix.starts_with(' '),
11020 );
11021
11022 if prefix_range.is_empty() || suffix_range.is_empty() {
11023 edits.push((
11024 prefix_range.start..prefix_range.start,
11025 full_comment_prefix.clone(),
11026 ));
11027 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11028 suffixes_inserted.push((end_row, comment_suffix.len()));
11029 } else {
11030 edits.push((prefix_range, empty_str.clone()));
11031 edits.push((suffix_range, empty_str.clone()));
11032 }
11033 } else {
11034 continue;
11035 }
11036 }
11037
11038 drop(snapshot);
11039 this.buffer.update(cx, |buffer, cx| {
11040 buffer.edit(edits, None, cx);
11041 });
11042
11043 // Adjust selections so that they end before any comment suffixes that
11044 // were inserted.
11045 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11046 let mut selections = this.selections.all::<Point>(cx);
11047 let snapshot = this.buffer.read(cx).read(cx);
11048 for selection in &mut selections {
11049 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11050 match row.cmp(&MultiBufferRow(selection.end.row)) {
11051 Ordering::Less => {
11052 suffixes_inserted.next();
11053 continue;
11054 }
11055 Ordering::Greater => break,
11056 Ordering::Equal => {
11057 if selection.end.column == snapshot.line_len(row) {
11058 if selection.is_empty() {
11059 selection.start.column -= suffix_len as u32;
11060 }
11061 selection.end.column -= suffix_len as u32;
11062 }
11063 break;
11064 }
11065 }
11066 }
11067 }
11068
11069 drop(snapshot);
11070 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11071 s.select(selections)
11072 });
11073
11074 let selections = this.selections.all::<Point>(cx);
11075 let selections_on_single_row = selections.windows(2).all(|selections| {
11076 selections[0].start.row == selections[1].start.row
11077 && selections[0].end.row == selections[1].end.row
11078 && selections[0].start.row == selections[0].end.row
11079 });
11080 let selections_selecting = selections
11081 .iter()
11082 .any(|selection| selection.start != selection.end);
11083 let advance_downwards = action.advance_downwards
11084 && selections_on_single_row
11085 && !selections_selecting
11086 && !matches!(this.mode, EditorMode::SingleLine { .. });
11087
11088 if advance_downwards {
11089 let snapshot = this.buffer.read(cx).snapshot(cx);
11090
11091 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11092 s.move_cursors_with(|display_snapshot, display_point, _| {
11093 let mut point = display_point.to_point(display_snapshot);
11094 point.row += 1;
11095 point = snapshot.clip_point(point, Bias::Left);
11096 let display_point = point.to_display_point(display_snapshot);
11097 let goal = SelectionGoal::HorizontalPosition(
11098 display_snapshot
11099 .x_for_display_point(display_point, text_layout_details)
11100 .into(),
11101 );
11102 (display_point, goal)
11103 })
11104 });
11105 }
11106 });
11107 }
11108
11109 pub fn select_enclosing_symbol(
11110 &mut self,
11111 _: &SelectEnclosingSymbol,
11112 window: &mut Window,
11113 cx: &mut Context<Self>,
11114 ) {
11115 let buffer = self.buffer.read(cx).snapshot(cx);
11116 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11117
11118 fn update_selection(
11119 selection: &Selection<usize>,
11120 buffer_snap: &MultiBufferSnapshot,
11121 ) -> Option<Selection<usize>> {
11122 let cursor = selection.head();
11123 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11124 for symbol in symbols.iter().rev() {
11125 let start = symbol.range.start.to_offset(buffer_snap);
11126 let end = symbol.range.end.to_offset(buffer_snap);
11127 let new_range = start..end;
11128 if start < selection.start || end > selection.end {
11129 return Some(Selection {
11130 id: selection.id,
11131 start: new_range.start,
11132 end: new_range.end,
11133 goal: SelectionGoal::None,
11134 reversed: selection.reversed,
11135 });
11136 }
11137 }
11138 None
11139 }
11140
11141 let mut selected_larger_symbol = false;
11142 let new_selections = old_selections
11143 .iter()
11144 .map(|selection| match update_selection(selection, &buffer) {
11145 Some(new_selection) => {
11146 if new_selection.range() != selection.range() {
11147 selected_larger_symbol = true;
11148 }
11149 new_selection
11150 }
11151 None => selection.clone(),
11152 })
11153 .collect::<Vec<_>>();
11154
11155 if selected_larger_symbol {
11156 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11157 s.select(new_selections);
11158 });
11159 }
11160 }
11161
11162 pub fn select_larger_syntax_node(
11163 &mut self,
11164 _: &SelectLargerSyntaxNode,
11165 window: &mut Window,
11166 cx: &mut Context<Self>,
11167 ) {
11168 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11169 let buffer = self.buffer.read(cx).snapshot(cx);
11170 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11171
11172 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11173 let mut selected_larger_node = false;
11174 let new_selections = old_selections
11175 .iter()
11176 .map(|selection| {
11177 let old_range = selection.start..selection.end;
11178 let mut new_range = old_range.clone();
11179 let mut new_node = None;
11180 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11181 {
11182 new_node = Some(node);
11183 new_range = match containing_range {
11184 MultiOrSingleBufferOffsetRange::Single(_) => break,
11185 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11186 };
11187 if !display_map.intersects_fold(new_range.start)
11188 && !display_map.intersects_fold(new_range.end)
11189 {
11190 break;
11191 }
11192 }
11193
11194 if let Some(node) = new_node {
11195 // Log the ancestor, to support using this action as a way to explore TreeSitter
11196 // nodes. Parent and grandparent are also logged because this operation will not
11197 // visit nodes that have the same range as their parent.
11198 log::info!("Node: {node:?}");
11199 let parent = node.parent();
11200 log::info!("Parent: {parent:?}");
11201 let grandparent = parent.and_then(|x| x.parent());
11202 log::info!("Grandparent: {grandparent:?}");
11203 }
11204
11205 selected_larger_node |= new_range != old_range;
11206 Selection {
11207 id: selection.id,
11208 start: new_range.start,
11209 end: new_range.end,
11210 goal: SelectionGoal::None,
11211 reversed: selection.reversed,
11212 }
11213 })
11214 .collect::<Vec<_>>();
11215
11216 if selected_larger_node {
11217 stack.push(old_selections);
11218 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11219 s.select(new_selections);
11220 });
11221 }
11222 self.select_larger_syntax_node_stack = stack;
11223 }
11224
11225 pub fn select_smaller_syntax_node(
11226 &mut self,
11227 _: &SelectSmallerSyntaxNode,
11228 window: &mut Window,
11229 cx: &mut Context<Self>,
11230 ) {
11231 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11232 if let Some(selections) = stack.pop() {
11233 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11234 s.select(selections.to_vec());
11235 });
11236 }
11237 self.select_larger_syntax_node_stack = stack;
11238 }
11239
11240 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11241 if !EditorSettings::get_global(cx).gutter.runnables {
11242 self.clear_tasks();
11243 return Task::ready(());
11244 }
11245 let project = self.project.as_ref().map(Entity::downgrade);
11246 cx.spawn_in(window, |this, mut cx| async move {
11247 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11248 let Some(project) = project.and_then(|p| p.upgrade()) else {
11249 return;
11250 };
11251 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11252 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11253 }) else {
11254 return;
11255 };
11256
11257 let hide_runnables = project
11258 .update(&mut cx, |project, cx| {
11259 // Do not display any test indicators in non-dev server remote projects.
11260 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11261 })
11262 .unwrap_or(true);
11263 if hide_runnables {
11264 return;
11265 }
11266 let new_rows =
11267 cx.background_spawn({
11268 let snapshot = display_snapshot.clone();
11269 async move {
11270 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11271 }
11272 })
11273 .await;
11274
11275 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11276 this.update(&mut cx, |this, _| {
11277 this.clear_tasks();
11278 for (key, value) in rows {
11279 this.insert_tasks(key, value);
11280 }
11281 })
11282 .ok();
11283 })
11284 }
11285 fn fetch_runnable_ranges(
11286 snapshot: &DisplaySnapshot,
11287 range: Range<Anchor>,
11288 ) -> Vec<language::RunnableRange> {
11289 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11290 }
11291
11292 fn runnable_rows(
11293 project: Entity<Project>,
11294 snapshot: DisplaySnapshot,
11295 runnable_ranges: Vec<RunnableRange>,
11296 mut cx: AsyncWindowContext,
11297 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11298 runnable_ranges
11299 .into_iter()
11300 .filter_map(|mut runnable| {
11301 let tasks = cx
11302 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11303 .ok()?;
11304 if tasks.is_empty() {
11305 return None;
11306 }
11307
11308 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11309
11310 let row = snapshot
11311 .buffer_snapshot
11312 .buffer_line_for_row(MultiBufferRow(point.row))?
11313 .1
11314 .start
11315 .row;
11316
11317 let context_range =
11318 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11319 Some((
11320 (runnable.buffer_id, row),
11321 RunnableTasks {
11322 templates: tasks,
11323 offset: snapshot
11324 .buffer_snapshot
11325 .anchor_before(runnable.run_range.start),
11326 context_range,
11327 column: point.column,
11328 extra_variables: runnable.extra_captures,
11329 },
11330 ))
11331 })
11332 .collect()
11333 }
11334
11335 fn templates_with_tags(
11336 project: &Entity<Project>,
11337 runnable: &mut Runnable,
11338 cx: &mut App,
11339 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11340 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11341 let (worktree_id, file) = project
11342 .buffer_for_id(runnable.buffer, cx)
11343 .and_then(|buffer| buffer.read(cx).file())
11344 .map(|file| (file.worktree_id(cx), file.clone()))
11345 .unzip();
11346
11347 (
11348 project.task_store().read(cx).task_inventory().cloned(),
11349 worktree_id,
11350 file,
11351 )
11352 });
11353
11354 let tags = mem::take(&mut runnable.tags);
11355 let mut tags: Vec<_> = tags
11356 .into_iter()
11357 .flat_map(|tag| {
11358 let tag = tag.0.clone();
11359 inventory
11360 .as_ref()
11361 .into_iter()
11362 .flat_map(|inventory| {
11363 inventory.read(cx).list_tasks(
11364 file.clone(),
11365 Some(runnable.language.clone()),
11366 worktree_id,
11367 cx,
11368 )
11369 })
11370 .filter(move |(_, template)| {
11371 template.tags.iter().any(|source_tag| source_tag == &tag)
11372 })
11373 })
11374 .sorted_by_key(|(kind, _)| kind.to_owned())
11375 .collect();
11376 if let Some((leading_tag_source, _)) = tags.first() {
11377 // Strongest source wins; if we have worktree tag binding, prefer that to
11378 // global and language bindings;
11379 // if we have a global binding, prefer that to language binding.
11380 let first_mismatch = tags
11381 .iter()
11382 .position(|(tag_source, _)| tag_source != leading_tag_source);
11383 if let Some(index) = first_mismatch {
11384 tags.truncate(index);
11385 }
11386 }
11387
11388 tags
11389 }
11390
11391 pub fn move_to_enclosing_bracket(
11392 &mut self,
11393 _: &MoveToEnclosingBracket,
11394 window: &mut Window,
11395 cx: &mut Context<Self>,
11396 ) {
11397 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11398 s.move_offsets_with(|snapshot, selection| {
11399 let Some(enclosing_bracket_ranges) =
11400 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11401 else {
11402 return;
11403 };
11404
11405 let mut best_length = usize::MAX;
11406 let mut best_inside = false;
11407 let mut best_in_bracket_range = false;
11408 let mut best_destination = None;
11409 for (open, close) in enclosing_bracket_ranges {
11410 let close = close.to_inclusive();
11411 let length = close.end() - open.start;
11412 let inside = selection.start >= open.end && selection.end <= *close.start();
11413 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11414 || close.contains(&selection.head());
11415
11416 // If best is next to a bracket and current isn't, skip
11417 if !in_bracket_range && best_in_bracket_range {
11418 continue;
11419 }
11420
11421 // Prefer smaller lengths unless best is inside and current isn't
11422 if length > best_length && (best_inside || !inside) {
11423 continue;
11424 }
11425
11426 best_length = length;
11427 best_inside = inside;
11428 best_in_bracket_range = in_bracket_range;
11429 best_destination = Some(
11430 if close.contains(&selection.start) && close.contains(&selection.end) {
11431 if inside {
11432 open.end
11433 } else {
11434 open.start
11435 }
11436 } else if inside {
11437 *close.start()
11438 } else {
11439 *close.end()
11440 },
11441 );
11442 }
11443
11444 if let Some(destination) = best_destination {
11445 selection.collapse_to(destination, SelectionGoal::None);
11446 }
11447 })
11448 });
11449 }
11450
11451 pub fn undo_selection(
11452 &mut self,
11453 _: &UndoSelection,
11454 window: &mut Window,
11455 cx: &mut Context<Self>,
11456 ) {
11457 self.end_selection(window, cx);
11458 self.selection_history.mode = SelectionHistoryMode::Undoing;
11459 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11460 self.change_selections(None, window, cx, |s| {
11461 s.select_anchors(entry.selections.to_vec())
11462 });
11463 self.select_next_state = entry.select_next_state;
11464 self.select_prev_state = entry.select_prev_state;
11465 self.add_selections_state = entry.add_selections_state;
11466 self.request_autoscroll(Autoscroll::newest(), cx);
11467 }
11468 self.selection_history.mode = SelectionHistoryMode::Normal;
11469 }
11470
11471 pub fn redo_selection(
11472 &mut self,
11473 _: &RedoSelection,
11474 window: &mut Window,
11475 cx: &mut Context<Self>,
11476 ) {
11477 self.end_selection(window, cx);
11478 self.selection_history.mode = SelectionHistoryMode::Redoing;
11479 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11480 self.change_selections(None, window, cx, |s| {
11481 s.select_anchors(entry.selections.to_vec())
11482 });
11483 self.select_next_state = entry.select_next_state;
11484 self.select_prev_state = entry.select_prev_state;
11485 self.add_selections_state = entry.add_selections_state;
11486 self.request_autoscroll(Autoscroll::newest(), cx);
11487 }
11488 self.selection_history.mode = SelectionHistoryMode::Normal;
11489 }
11490
11491 pub fn expand_excerpts(
11492 &mut self,
11493 action: &ExpandExcerpts,
11494 _: &mut Window,
11495 cx: &mut Context<Self>,
11496 ) {
11497 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11498 }
11499
11500 pub fn expand_excerpts_down(
11501 &mut self,
11502 action: &ExpandExcerptsDown,
11503 _: &mut Window,
11504 cx: &mut Context<Self>,
11505 ) {
11506 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11507 }
11508
11509 pub fn expand_excerpts_up(
11510 &mut self,
11511 action: &ExpandExcerptsUp,
11512 _: &mut Window,
11513 cx: &mut Context<Self>,
11514 ) {
11515 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11516 }
11517
11518 pub fn expand_excerpts_for_direction(
11519 &mut self,
11520 lines: u32,
11521 direction: ExpandExcerptDirection,
11522
11523 cx: &mut Context<Self>,
11524 ) {
11525 let selections = self.selections.disjoint_anchors();
11526
11527 let lines = if lines == 0 {
11528 EditorSettings::get_global(cx).expand_excerpt_lines
11529 } else {
11530 lines
11531 };
11532
11533 self.buffer.update(cx, |buffer, cx| {
11534 let snapshot = buffer.snapshot(cx);
11535 let mut excerpt_ids = selections
11536 .iter()
11537 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11538 .collect::<Vec<_>>();
11539 excerpt_ids.sort();
11540 excerpt_ids.dedup();
11541 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11542 })
11543 }
11544
11545 pub fn expand_excerpt(
11546 &mut self,
11547 excerpt: ExcerptId,
11548 direction: ExpandExcerptDirection,
11549 cx: &mut Context<Self>,
11550 ) {
11551 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11552 self.buffer.update(cx, |buffer, cx| {
11553 buffer.expand_excerpts([excerpt], lines, direction, cx)
11554 })
11555 }
11556
11557 pub fn go_to_singleton_buffer_point(
11558 &mut self,
11559 point: Point,
11560 window: &mut Window,
11561 cx: &mut Context<Self>,
11562 ) {
11563 self.go_to_singleton_buffer_range(point..point, window, cx);
11564 }
11565
11566 pub fn go_to_singleton_buffer_range(
11567 &mut self,
11568 range: Range<Point>,
11569 window: &mut Window,
11570 cx: &mut Context<Self>,
11571 ) {
11572 let multibuffer = self.buffer().read(cx);
11573 let Some(buffer) = multibuffer.as_singleton() else {
11574 return;
11575 };
11576 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11577 return;
11578 };
11579 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11580 return;
11581 };
11582 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11583 s.select_anchor_ranges([start..end])
11584 });
11585 }
11586
11587 fn go_to_diagnostic(
11588 &mut self,
11589 _: &GoToDiagnostic,
11590 window: &mut Window,
11591 cx: &mut Context<Self>,
11592 ) {
11593 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11594 }
11595
11596 fn go_to_prev_diagnostic(
11597 &mut self,
11598 _: &GoToPreviousDiagnostic,
11599 window: &mut Window,
11600 cx: &mut Context<Self>,
11601 ) {
11602 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11603 }
11604
11605 pub fn go_to_diagnostic_impl(
11606 &mut self,
11607 direction: Direction,
11608 window: &mut Window,
11609 cx: &mut Context<Self>,
11610 ) {
11611 let buffer = self.buffer.read(cx).snapshot(cx);
11612 let selection = self.selections.newest::<usize>(cx);
11613
11614 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11615 if direction == Direction::Next {
11616 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11617 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11618 return;
11619 };
11620 self.activate_diagnostics(
11621 buffer_id,
11622 popover.local_diagnostic.diagnostic.group_id,
11623 window,
11624 cx,
11625 );
11626 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11627 let primary_range_start = active_diagnostics.primary_range.start;
11628 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11629 let mut new_selection = s.newest_anchor().clone();
11630 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11631 s.select_anchors(vec![new_selection.clone()]);
11632 });
11633 self.refresh_inline_completion(false, true, window, cx);
11634 }
11635 return;
11636 }
11637 }
11638
11639 let active_group_id = self
11640 .active_diagnostics
11641 .as_ref()
11642 .map(|active_group| active_group.group_id);
11643 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11644 active_diagnostics
11645 .primary_range
11646 .to_offset(&buffer)
11647 .to_inclusive()
11648 });
11649 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11650 if active_primary_range.contains(&selection.head()) {
11651 *active_primary_range.start()
11652 } else {
11653 selection.head()
11654 }
11655 } else {
11656 selection.head()
11657 };
11658
11659 let snapshot = self.snapshot(window, cx);
11660 let primary_diagnostics_before = buffer
11661 .diagnostics_in_range::<usize>(0..search_start)
11662 .filter(|entry| entry.diagnostic.is_primary)
11663 .filter(|entry| entry.range.start != entry.range.end)
11664 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11665 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11666 .collect::<Vec<_>>();
11667 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11668 primary_diagnostics_before
11669 .iter()
11670 .position(|entry| entry.diagnostic.group_id == active_group_id)
11671 });
11672
11673 let primary_diagnostics_after = buffer
11674 .diagnostics_in_range::<usize>(search_start..buffer.len())
11675 .filter(|entry| entry.diagnostic.is_primary)
11676 .filter(|entry| entry.range.start != entry.range.end)
11677 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11678 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11679 .collect::<Vec<_>>();
11680 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11681 primary_diagnostics_after
11682 .iter()
11683 .enumerate()
11684 .rev()
11685 .find_map(|(i, entry)| {
11686 if entry.diagnostic.group_id == active_group_id {
11687 Some(i)
11688 } else {
11689 None
11690 }
11691 })
11692 });
11693
11694 let next_primary_diagnostic = match direction {
11695 Direction::Prev => primary_diagnostics_before
11696 .iter()
11697 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11698 .rev()
11699 .next(),
11700 Direction::Next => primary_diagnostics_after
11701 .iter()
11702 .skip(
11703 last_same_group_diagnostic_after
11704 .map(|index| index + 1)
11705 .unwrap_or(0),
11706 )
11707 .next(),
11708 };
11709
11710 // Cycle around to the start of the buffer, potentially moving back to the start of
11711 // the currently active diagnostic.
11712 let cycle_around = || match direction {
11713 Direction::Prev => primary_diagnostics_after
11714 .iter()
11715 .rev()
11716 .chain(primary_diagnostics_before.iter().rev())
11717 .next(),
11718 Direction::Next => primary_diagnostics_before
11719 .iter()
11720 .chain(primary_diagnostics_after.iter())
11721 .next(),
11722 };
11723
11724 if let Some((primary_range, group_id)) = next_primary_diagnostic
11725 .or_else(cycle_around)
11726 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11727 {
11728 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11729 return;
11730 };
11731 self.activate_diagnostics(buffer_id, group_id, window, cx);
11732 if self.active_diagnostics.is_some() {
11733 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11734 s.select(vec![Selection {
11735 id: selection.id,
11736 start: primary_range.start,
11737 end: primary_range.start,
11738 reversed: false,
11739 goal: SelectionGoal::None,
11740 }]);
11741 });
11742 self.refresh_inline_completion(false, true, window, cx);
11743 }
11744 }
11745 }
11746
11747 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11748 let snapshot = self.snapshot(window, cx);
11749 let selection = self.selections.newest::<Point>(cx);
11750 self.go_to_hunk_before_or_after_position(
11751 &snapshot,
11752 selection.head(),
11753 Direction::Next,
11754 window,
11755 cx,
11756 );
11757 }
11758
11759 fn go_to_hunk_before_or_after_position(
11760 &mut self,
11761 snapshot: &EditorSnapshot,
11762 position: Point,
11763 direction: Direction,
11764 window: &mut Window,
11765 cx: &mut Context<Editor>,
11766 ) {
11767 let row = if direction == Direction::Next {
11768 self.hunk_after_position(snapshot, position)
11769 .map(|hunk| hunk.row_range.start)
11770 } else {
11771 self.hunk_before_position(snapshot, position)
11772 };
11773
11774 if let Some(row) = row {
11775 let destination = Point::new(row.0, 0);
11776 let autoscroll = Autoscroll::center();
11777
11778 self.unfold_ranges(&[destination..destination], false, false, cx);
11779 self.change_selections(Some(autoscroll), window, cx, |s| {
11780 s.select_ranges([destination..destination]);
11781 });
11782 }
11783 }
11784
11785 fn hunk_after_position(
11786 &mut self,
11787 snapshot: &EditorSnapshot,
11788 position: Point,
11789 ) -> Option<MultiBufferDiffHunk> {
11790 snapshot
11791 .buffer_snapshot
11792 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11793 .find(|hunk| hunk.row_range.start.0 > position.row)
11794 .or_else(|| {
11795 snapshot
11796 .buffer_snapshot
11797 .diff_hunks_in_range(Point::zero()..position)
11798 .find(|hunk| hunk.row_range.end.0 < position.row)
11799 })
11800 }
11801
11802 fn go_to_prev_hunk(
11803 &mut self,
11804 _: &GoToPreviousHunk,
11805 window: &mut Window,
11806 cx: &mut Context<Self>,
11807 ) {
11808 let snapshot = self.snapshot(window, cx);
11809 let selection = self.selections.newest::<Point>(cx);
11810 self.go_to_hunk_before_or_after_position(
11811 &snapshot,
11812 selection.head(),
11813 Direction::Prev,
11814 window,
11815 cx,
11816 );
11817 }
11818
11819 fn hunk_before_position(
11820 &mut self,
11821 snapshot: &EditorSnapshot,
11822 position: Point,
11823 ) -> Option<MultiBufferRow> {
11824 snapshot
11825 .buffer_snapshot
11826 .diff_hunk_before(position)
11827 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11828 }
11829
11830 pub fn go_to_definition(
11831 &mut self,
11832 _: &GoToDefinition,
11833 window: &mut Window,
11834 cx: &mut Context<Self>,
11835 ) -> Task<Result<Navigated>> {
11836 let definition =
11837 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11838 cx.spawn_in(window, |editor, mut cx| async move {
11839 if definition.await? == Navigated::Yes {
11840 return Ok(Navigated::Yes);
11841 }
11842 match editor.update_in(&mut cx, |editor, window, cx| {
11843 editor.find_all_references(&FindAllReferences, window, cx)
11844 })? {
11845 Some(references) => references.await,
11846 None => Ok(Navigated::No),
11847 }
11848 })
11849 }
11850
11851 pub fn go_to_declaration(
11852 &mut self,
11853 _: &GoToDeclaration,
11854 window: &mut Window,
11855 cx: &mut Context<Self>,
11856 ) -> Task<Result<Navigated>> {
11857 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11858 }
11859
11860 pub fn go_to_declaration_split(
11861 &mut self,
11862 _: &GoToDeclaration,
11863 window: &mut Window,
11864 cx: &mut Context<Self>,
11865 ) -> Task<Result<Navigated>> {
11866 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11867 }
11868
11869 pub fn go_to_implementation(
11870 &mut self,
11871 _: &GoToImplementation,
11872 window: &mut Window,
11873 cx: &mut Context<Self>,
11874 ) -> Task<Result<Navigated>> {
11875 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11876 }
11877
11878 pub fn go_to_implementation_split(
11879 &mut self,
11880 _: &GoToImplementationSplit,
11881 window: &mut Window,
11882 cx: &mut Context<Self>,
11883 ) -> Task<Result<Navigated>> {
11884 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11885 }
11886
11887 pub fn go_to_type_definition(
11888 &mut self,
11889 _: &GoToTypeDefinition,
11890 window: &mut Window,
11891 cx: &mut Context<Self>,
11892 ) -> Task<Result<Navigated>> {
11893 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11894 }
11895
11896 pub fn go_to_definition_split(
11897 &mut self,
11898 _: &GoToDefinitionSplit,
11899 window: &mut Window,
11900 cx: &mut Context<Self>,
11901 ) -> Task<Result<Navigated>> {
11902 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11903 }
11904
11905 pub fn go_to_type_definition_split(
11906 &mut self,
11907 _: &GoToTypeDefinitionSplit,
11908 window: &mut Window,
11909 cx: &mut Context<Self>,
11910 ) -> Task<Result<Navigated>> {
11911 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11912 }
11913
11914 fn go_to_definition_of_kind(
11915 &mut self,
11916 kind: GotoDefinitionKind,
11917 split: bool,
11918 window: &mut Window,
11919 cx: &mut Context<Self>,
11920 ) -> Task<Result<Navigated>> {
11921 let Some(provider) = self.semantics_provider.clone() else {
11922 return Task::ready(Ok(Navigated::No));
11923 };
11924 let head = self.selections.newest::<usize>(cx).head();
11925 let buffer = self.buffer.read(cx);
11926 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11927 text_anchor
11928 } else {
11929 return Task::ready(Ok(Navigated::No));
11930 };
11931
11932 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11933 return Task::ready(Ok(Navigated::No));
11934 };
11935
11936 cx.spawn_in(window, |editor, mut cx| async move {
11937 let definitions = definitions.await?;
11938 let navigated = editor
11939 .update_in(&mut cx, |editor, window, cx| {
11940 editor.navigate_to_hover_links(
11941 Some(kind),
11942 definitions
11943 .into_iter()
11944 .filter(|location| {
11945 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11946 })
11947 .map(HoverLink::Text)
11948 .collect::<Vec<_>>(),
11949 split,
11950 window,
11951 cx,
11952 )
11953 })?
11954 .await?;
11955 anyhow::Ok(navigated)
11956 })
11957 }
11958
11959 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11960 let selection = self.selections.newest_anchor();
11961 let head = selection.head();
11962 let tail = selection.tail();
11963
11964 let Some((buffer, start_position)) =
11965 self.buffer.read(cx).text_anchor_for_position(head, cx)
11966 else {
11967 return;
11968 };
11969
11970 let end_position = if head != tail {
11971 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11972 return;
11973 };
11974 Some(pos)
11975 } else {
11976 None
11977 };
11978
11979 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11980 let url = if let Some(end_pos) = end_position {
11981 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11982 } else {
11983 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11984 };
11985
11986 if let Some(url) = url {
11987 editor.update(&mut cx, |_, cx| {
11988 cx.open_url(&url);
11989 })
11990 } else {
11991 Ok(())
11992 }
11993 });
11994
11995 url_finder.detach();
11996 }
11997
11998 pub fn open_selected_filename(
11999 &mut self,
12000 _: &OpenSelectedFilename,
12001 window: &mut Window,
12002 cx: &mut Context<Self>,
12003 ) {
12004 let Some(workspace) = self.workspace() else {
12005 return;
12006 };
12007
12008 let position = self.selections.newest_anchor().head();
12009
12010 let Some((buffer, buffer_position)) =
12011 self.buffer.read(cx).text_anchor_for_position(position, cx)
12012 else {
12013 return;
12014 };
12015
12016 let project = self.project.clone();
12017
12018 cx.spawn_in(window, |_, mut cx| async move {
12019 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
12020
12021 if let Some((_, path)) = result {
12022 workspace
12023 .update_in(&mut cx, |workspace, window, cx| {
12024 workspace.open_resolved_path(path, window, cx)
12025 })?
12026 .await?;
12027 }
12028 anyhow::Ok(())
12029 })
12030 .detach();
12031 }
12032
12033 pub(crate) fn navigate_to_hover_links(
12034 &mut self,
12035 kind: Option<GotoDefinitionKind>,
12036 mut definitions: Vec<HoverLink>,
12037 split: bool,
12038 window: &mut Window,
12039 cx: &mut Context<Editor>,
12040 ) -> Task<Result<Navigated>> {
12041 // If there is one definition, just open it directly
12042 if definitions.len() == 1 {
12043 let definition = definitions.pop().unwrap();
12044
12045 enum TargetTaskResult {
12046 Location(Option<Location>),
12047 AlreadyNavigated,
12048 }
12049
12050 let target_task = match definition {
12051 HoverLink::Text(link) => {
12052 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12053 }
12054 HoverLink::InlayHint(lsp_location, server_id) => {
12055 let computation =
12056 self.compute_target_location(lsp_location, server_id, window, cx);
12057 cx.background_spawn(async move {
12058 let location = computation.await?;
12059 Ok(TargetTaskResult::Location(location))
12060 })
12061 }
12062 HoverLink::Url(url) => {
12063 cx.open_url(&url);
12064 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12065 }
12066 HoverLink::File(path) => {
12067 if let Some(workspace) = self.workspace() {
12068 cx.spawn_in(window, |_, mut cx| async move {
12069 workspace
12070 .update_in(&mut cx, |workspace, window, cx| {
12071 workspace.open_resolved_path(path, window, cx)
12072 })?
12073 .await
12074 .map(|_| TargetTaskResult::AlreadyNavigated)
12075 })
12076 } else {
12077 Task::ready(Ok(TargetTaskResult::Location(None)))
12078 }
12079 }
12080 };
12081 cx.spawn_in(window, |editor, mut cx| async move {
12082 let target = match target_task.await.context("target resolution task")? {
12083 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12084 TargetTaskResult::Location(None) => return Ok(Navigated::No),
12085 TargetTaskResult::Location(Some(target)) => target,
12086 };
12087
12088 editor.update_in(&mut cx, |editor, window, cx| {
12089 let Some(workspace) = editor.workspace() else {
12090 return Navigated::No;
12091 };
12092 let pane = workspace.read(cx).active_pane().clone();
12093
12094 let range = target.range.to_point(target.buffer.read(cx));
12095 let range = editor.range_for_match(&range);
12096 let range = collapse_multiline_range(range);
12097
12098 if !split
12099 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12100 {
12101 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12102 } else {
12103 window.defer(cx, move |window, cx| {
12104 let target_editor: Entity<Self> =
12105 workspace.update(cx, |workspace, cx| {
12106 let pane = if split {
12107 workspace.adjacent_pane(window, cx)
12108 } else {
12109 workspace.active_pane().clone()
12110 };
12111
12112 workspace.open_project_item(
12113 pane,
12114 target.buffer.clone(),
12115 true,
12116 true,
12117 window,
12118 cx,
12119 )
12120 });
12121 target_editor.update(cx, |target_editor, cx| {
12122 // When selecting a definition in a different buffer, disable the nav history
12123 // to avoid creating a history entry at the previous cursor location.
12124 pane.update(cx, |pane, _| pane.disable_history());
12125 target_editor.go_to_singleton_buffer_range(range, window, cx);
12126 pane.update(cx, |pane, _| pane.enable_history());
12127 });
12128 });
12129 }
12130 Navigated::Yes
12131 })
12132 })
12133 } else if !definitions.is_empty() {
12134 cx.spawn_in(window, |editor, mut cx| async move {
12135 let (title, location_tasks, workspace) = editor
12136 .update_in(&mut cx, |editor, window, cx| {
12137 let tab_kind = match kind {
12138 Some(GotoDefinitionKind::Implementation) => "Implementations",
12139 _ => "Definitions",
12140 };
12141 let title = definitions
12142 .iter()
12143 .find_map(|definition| match definition {
12144 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12145 let buffer = origin.buffer.read(cx);
12146 format!(
12147 "{} for {}",
12148 tab_kind,
12149 buffer
12150 .text_for_range(origin.range.clone())
12151 .collect::<String>()
12152 )
12153 }),
12154 HoverLink::InlayHint(_, _) => None,
12155 HoverLink::Url(_) => None,
12156 HoverLink::File(_) => None,
12157 })
12158 .unwrap_or(tab_kind.to_string());
12159 let location_tasks = definitions
12160 .into_iter()
12161 .map(|definition| match definition {
12162 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12163 HoverLink::InlayHint(lsp_location, server_id) => editor
12164 .compute_target_location(lsp_location, server_id, window, cx),
12165 HoverLink::Url(_) => Task::ready(Ok(None)),
12166 HoverLink::File(_) => Task::ready(Ok(None)),
12167 })
12168 .collect::<Vec<_>>();
12169 (title, location_tasks, editor.workspace().clone())
12170 })
12171 .context("location tasks preparation")?;
12172
12173 let locations = future::join_all(location_tasks)
12174 .await
12175 .into_iter()
12176 .filter_map(|location| location.transpose())
12177 .collect::<Result<_>>()
12178 .context("location tasks")?;
12179
12180 let Some(workspace) = workspace else {
12181 return Ok(Navigated::No);
12182 };
12183 let opened = workspace
12184 .update_in(&mut cx, |workspace, window, cx| {
12185 Self::open_locations_in_multibuffer(
12186 workspace,
12187 locations,
12188 title,
12189 split,
12190 MultibufferSelectionMode::First,
12191 window,
12192 cx,
12193 )
12194 })
12195 .ok();
12196
12197 anyhow::Ok(Navigated::from_bool(opened.is_some()))
12198 })
12199 } else {
12200 Task::ready(Ok(Navigated::No))
12201 }
12202 }
12203
12204 fn compute_target_location(
12205 &self,
12206 lsp_location: lsp::Location,
12207 server_id: LanguageServerId,
12208 window: &mut Window,
12209 cx: &mut Context<Self>,
12210 ) -> Task<anyhow::Result<Option<Location>>> {
12211 let Some(project) = self.project.clone() else {
12212 return Task::ready(Ok(None));
12213 };
12214
12215 cx.spawn_in(window, move |editor, mut cx| async move {
12216 let location_task = editor.update(&mut cx, |_, cx| {
12217 project.update(cx, |project, cx| {
12218 let language_server_name = project
12219 .language_server_statuses(cx)
12220 .find(|(id, _)| server_id == *id)
12221 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12222 language_server_name.map(|language_server_name| {
12223 project.open_local_buffer_via_lsp(
12224 lsp_location.uri.clone(),
12225 server_id,
12226 language_server_name,
12227 cx,
12228 )
12229 })
12230 })
12231 })?;
12232 let location = match location_task {
12233 Some(task) => Some({
12234 let target_buffer_handle = task.await.context("open local buffer")?;
12235 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12236 let target_start = target_buffer
12237 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12238 let target_end = target_buffer
12239 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12240 target_buffer.anchor_after(target_start)
12241 ..target_buffer.anchor_before(target_end)
12242 })?;
12243 Location {
12244 buffer: target_buffer_handle,
12245 range,
12246 }
12247 }),
12248 None => None,
12249 };
12250 Ok(location)
12251 })
12252 }
12253
12254 pub fn find_all_references(
12255 &mut self,
12256 _: &FindAllReferences,
12257 window: &mut Window,
12258 cx: &mut Context<Self>,
12259 ) -> Option<Task<Result<Navigated>>> {
12260 let selection = self.selections.newest::<usize>(cx);
12261 let multi_buffer = self.buffer.read(cx);
12262 let head = selection.head();
12263
12264 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12265 let head_anchor = multi_buffer_snapshot.anchor_at(
12266 head,
12267 if head < selection.tail() {
12268 Bias::Right
12269 } else {
12270 Bias::Left
12271 },
12272 );
12273
12274 match self
12275 .find_all_references_task_sources
12276 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12277 {
12278 Ok(_) => {
12279 log::info!(
12280 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12281 );
12282 return None;
12283 }
12284 Err(i) => {
12285 self.find_all_references_task_sources.insert(i, head_anchor);
12286 }
12287 }
12288
12289 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12290 let workspace = self.workspace()?;
12291 let project = workspace.read(cx).project().clone();
12292 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12293 Some(cx.spawn_in(window, |editor, mut cx| async move {
12294 let _cleanup = defer({
12295 let mut cx = cx.clone();
12296 move || {
12297 let _ = editor.update(&mut cx, |editor, _| {
12298 if let Ok(i) =
12299 editor
12300 .find_all_references_task_sources
12301 .binary_search_by(|anchor| {
12302 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12303 })
12304 {
12305 editor.find_all_references_task_sources.remove(i);
12306 }
12307 });
12308 }
12309 });
12310
12311 let locations = references.await?;
12312 if locations.is_empty() {
12313 return anyhow::Ok(Navigated::No);
12314 }
12315
12316 workspace.update_in(&mut cx, |workspace, window, cx| {
12317 let title = locations
12318 .first()
12319 .as_ref()
12320 .map(|location| {
12321 let buffer = location.buffer.read(cx);
12322 format!(
12323 "References to `{}`",
12324 buffer
12325 .text_for_range(location.range.clone())
12326 .collect::<String>()
12327 )
12328 })
12329 .unwrap();
12330 Self::open_locations_in_multibuffer(
12331 workspace,
12332 locations,
12333 title,
12334 false,
12335 MultibufferSelectionMode::First,
12336 window,
12337 cx,
12338 );
12339 Navigated::Yes
12340 })
12341 }))
12342 }
12343
12344 /// Opens a multibuffer with the given project locations in it
12345 pub fn open_locations_in_multibuffer(
12346 workspace: &mut Workspace,
12347 mut locations: Vec<Location>,
12348 title: String,
12349 split: bool,
12350 multibuffer_selection_mode: MultibufferSelectionMode,
12351 window: &mut Window,
12352 cx: &mut Context<Workspace>,
12353 ) {
12354 // If there are multiple definitions, open them in a multibuffer
12355 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12356 let mut locations = locations.into_iter().peekable();
12357 let mut ranges = Vec::new();
12358 let capability = workspace.project().read(cx).capability();
12359
12360 let excerpt_buffer = cx.new(|cx| {
12361 let mut multibuffer = MultiBuffer::new(capability);
12362 while let Some(location) = locations.next() {
12363 let buffer = location.buffer.read(cx);
12364 let mut ranges_for_buffer = Vec::new();
12365 let range = location.range.to_offset(buffer);
12366 ranges_for_buffer.push(range.clone());
12367
12368 while let Some(next_location) = locations.peek() {
12369 if next_location.buffer == location.buffer {
12370 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12371 locations.next();
12372 } else {
12373 break;
12374 }
12375 }
12376
12377 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12378 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12379 location.buffer.clone(),
12380 ranges_for_buffer,
12381 DEFAULT_MULTIBUFFER_CONTEXT,
12382 cx,
12383 ))
12384 }
12385
12386 multibuffer.with_title(title)
12387 });
12388
12389 let editor = cx.new(|cx| {
12390 Editor::for_multibuffer(
12391 excerpt_buffer,
12392 Some(workspace.project().clone()),
12393 window,
12394 cx,
12395 )
12396 });
12397 editor.update(cx, |editor, cx| {
12398 match multibuffer_selection_mode {
12399 MultibufferSelectionMode::First => {
12400 if let Some(first_range) = ranges.first() {
12401 editor.change_selections(None, window, cx, |selections| {
12402 selections.clear_disjoint();
12403 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12404 });
12405 }
12406 editor.highlight_background::<Self>(
12407 &ranges,
12408 |theme| theme.editor_highlighted_line_background,
12409 cx,
12410 );
12411 }
12412 MultibufferSelectionMode::All => {
12413 editor.change_selections(None, window, cx, |selections| {
12414 selections.clear_disjoint();
12415 selections.select_anchor_ranges(ranges);
12416 });
12417 }
12418 }
12419 editor.register_buffers_with_language_servers(cx);
12420 });
12421
12422 let item = Box::new(editor);
12423 let item_id = item.item_id();
12424
12425 if split {
12426 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12427 } else {
12428 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12429 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12430 pane.close_current_preview_item(window, cx)
12431 } else {
12432 None
12433 }
12434 });
12435 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12436 }
12437 workspace.active_pane().update(cx, |pane, cx| {
12438 pane.set_preview_item_id(Some(item_id), cx);
12439 });
12440 }
12441
12442 pub fn rename(
12443 &mut self,
12444 _: &Rename,
12445 window: &mut Window,
12446 cx: &mut Context<Self>,
12447 ) -> Option<Task<Result<()>>> {
12448 use language::ToOffset as _;
12449
12450 let provider = self.semantics_provider.clone()?;
12451 let selection = self.selections.newest_anchor().clone();
12452 let (cursor_buffer, cursor_buffer_position) = self
12453 .buffer
12454 .read(cx)
12455 .text_anchor_for_position(selection.head(), cx)?;
12456 let (tail_buffer, cursor_buffer_position_end) = self
12457 .buffer
12458 .read(cx)
12459 .text_anchor_for_position(selection.tail(), cx)?;
12460 if tail_buffer != cursor_buffer {
12461 return None;
12462 }
12463
12464 let snapshot = cursor_buffer.read(cx).snapshot();
12465 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12466 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12467 let prepare_rename = provider
12468 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12469 .unwrap_or_else(|| Task::ready(Ok(None)));
12470 drop(snapshot);
12471
12472 Some(cx.spawn_in(window, |this, mut cx| async move {
12473 let rename_range = if let Some(range) = prepare_rename.await? {
12474 Some(range)
12475 } else {
12476 this.update(&mut cx, |this, cx| {
12477 let buffer = this.buffer.read(cx).snapshot(cx);
12478 let mut buffer_highlights = this
12479 .document_highlights_for_position(selection.head(), &buffer)
12480 .filter(|highlight| {
12481 highlight.start.excerpt_id == selection.head().excerpt_id
12482 && highlight.end.excerpt_id == selection.head().excerpt_id
12483 });
12484 buffer_highlights
12485 .next()
12486 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12487 })?
12488 };
12489 if let Some(rename_range) = rename_range {
12490 this.update_in(&mut cx, |this, window, cx| {
12491 let snapshot = cursor_buffer.read(cx).snapshot();
12492 let rename_buffer_range = rename_range.to_offset(&snapshot);
12493 let cursor_offset_in_rename_range =
12494 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12495 let cursor_offset_in_rename_range_end =
12496 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12497
12498 this.take_rename(false, window, cx);
12499 let buffer = this.buffer.read(cx).read(cx);
12500 let cursor_offset = selection.head().to_offset(&buffer);
12501 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12502 let rename_end = rename_start + rename_buffer_range.len();
12503 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12504 let mut old_highlight_id = None;
12505 let old_name: Arc<str> = buffer
12506 .chunks(rename_start..rename_end, true)
12507 .map(|chunk| {
12508 if old_highlight_id.is_none() {
12509 old_highlight_id = chunk.syntax_highlight_id;
12510 }
12511 chunk.text
12512 })
12513 .collect::<String>()
12514 .into();
12515
12516 drop(buffer);
12517
12518 // Position the selection in the rename editor so that it matches the current selection.
12519 this.show_local_selections = false;
12520 let rename_editor = cx.new(|cx| {
12521 let mut editor = Editor::single_line(window, cx);
12522 editor.buffer.update(cx, |buffer, cx| {
12523 buffer.edit([(0..0, old_name.clone())], None, cx)
12524 });
12525 let rename_selection_range = match cursor_offset_in_rename_range
12526 .cmp(&cursor_offset_in_rename_range_end)
12527 {
12528 Ordering::Equal => {
12529 editor.select_all(&SelectAll, window, cx);
12530 return editor;
12531 }
12532 Ordering::Less => {
12533 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12534 }
12535 Ordering::Greater => {
12536 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12537 }
12538 };
12539 if rename_selection_range.end > old_name.len() {
12540 editor.select_all(&SelectAll, window, cx);
12541 } else {
12542 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12543 s.select_ranges([rename_selection_range]);
12544 });
12545 }
12546 editor
12547 });
12548 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12549 if e == &EditorEvent::Focused {
12550 cx.emit(EditorEvent::FocusedIn)
12551 }
12552 })
12553 .detach();
12554
12555 let write_highlights =
12556 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12557 let read_highlights =
12558 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12559 let ranges = write_highlights
12560 .iter()
12561 .flat_map(|(_, ranges)| ranges.iter())
12562 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12563 .cloned()
12564 .collect();
12565
12566 this.highlight_text::<Rename>(
12567 ranges,
12568 HighlightStyle {
12569 fade_out: Some(0.6),
12570 ..Default::default()
12571 },
12572 cx,
12573 );
12574 let rename_focus_handle = rename_editor.focus_handle(cx);
12575 window.focus(&rename_focus_handle);
12576 let block_id = this.insert_blocks(
12577 [BlockProperties {
12578 style: BlockStyle::Flex,
12579 placement: BlockPlacement::Below(range.start),
12580 height: 1,
12581 render: Arc::new({
12582 let rename_editor = rename_editor.clone();
12583 move |cx: &mut BlockContext| {
12584 let mut text_style = cx.editor_style.text.clone();
12585 if let Some(highlight_style) = old_highlight_id
12586 .and_then(|h| h.style(&cx.editor_style.syntax))
12587 {
12588 text_style = text_style.highlight(highlight_style);
12589 }
12590 div()
12591 .block_mouse_down()
12592 .pl(cx.anchor_x)
12593 .child(EditorElement::new(
12594 &rename_editor,
12595 EditorStyle {
12596 background: cx.theme().system().transparent,
12597 local_player: cx.editor_style.local_player,
12598 text: text_style,
12599 scrollbar_width: cx.editor_style.scrollbar_width,
12600 syntax: cx.editor_style.syntax.clone(),
12601 status: cx.editor_style.status.clone(),
12602 inlay_hints_style: HighlightStyle {
12603 font_weight: Some(FontWeight::BOLD),
12604 ..make_inlay_hints_style(cx.app)
12605 },
12606 inline_completion_styles: make_suggestion_styles(
12607 cx.app,
12608 ),
12609 ..EditorStyle::default()
12610 },
12611 ))
12612 .into_any_element()
12613 }
12614 }),
12615 priority: 0,
12616 }],
12617 Some(Autoscroll::fit()),
12618 cx,
12619 )[0];
12620 this.pending_rename = Some(RenameState {
12621 range,
12622 old_name,
12623 editor: rename_editor,
12624 block_id,
12625 });
12626 })?;
12627 }
12628
12629 Ok(())
12630 }))
12631 }
12632
12633 pub fn confirm_rename(
12634 &mut self,
12635 _: &ConfirmRename,
12636 window: &mut Window,
12637 cx: &mut Context<Self>,
12638 ) -> Option<Task<Result<()>>> {
12639 let rename = self.take_rename(false, window, cx)?;
12640 let workspace = self.workspace()?.downgrade();
12641 let (buffer, start) = self
12642 .buffer
12643 .read(cx)
12644 .text_anchor_for_position(rename.range.start, cx)?;
12645 let (end_buffer, _) = self
12646 .buffer
12647 .read(cx)
12648 .text_anchor_for_position(rename.range.end, cx)?;
12649 if buffer != end_buffer {
12650 return None;
12651 }
12652
12653 let old_name = rename.old_name;
12654 let new_name = rename.editor.read(cx).text(cx);
12655
12656 let rename = self.semantics_provider.as_ref()?.perform_rename(
12657 &buffer,
12658 start,
12659 new_name.clone(),
12660 cx,
12661 )?;
12662
12663 Some(cx.spawn_in(window, |editor, mut cx| async move {
12664 let project_transaction = rename.await?;
12665 Self::open_project_transaction(
12666 &editor,
12667 workspace,
12668 project_transaction,
12669 format!("Rename: {} → {}", old_name, new_name),
12670 cx.clone(),
12671 )
12672 .await?;
12673
12674 editor.update(&mut cx, |editor, cx| {
12675 editor.refresh_document_highlights(cx);
12676 })?;
12677 Ok(())
12678 }))
12679 }
12680
12681 fn take_rename(
12682 &mut self,
12683 moving_cursor: bool,
12684 window: &mut Window,
12685 cx: &mut Context<Self>,
12686 ) -> Option<RenameState> {
12687 let rename = self.pending_rename.take()?;
12688 if rename.editor.focus_handle(cx).is_focused(window) {
12689 window.focus(&self.focus_handle);
12690 }
12691
12692 self.remove_blocks(
12693 [rename.block_id].into_iter().collect(),
12694 Some(Autoscroll::fit()),
12695 cx,
12696 );
12697 self.clear_highlights::<Rename>(cx);
12698 self.show_local_selections = true;
12699
12700 if moving_cursor {
12701 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12702 editor.selections.newest::<usize>(cx).head()
12703 });
12704
12705 // Update the selection to match the position of the selection inside
12706 // the rename editor.
12707 let snapshot = self.buffer.read(cx).read(cx);
12708 let rename_range = rename.range.to_offset(&snapshot);
12709 let cursor_in_editor = snapshot
12710 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12711 .min(rename_range.end);
12712 drop(snapshot);
12713
12714 self.change_selections(None, window, cx, |s| {
12715 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12716 });
12717 } else {
12718 self.refresh_document_highlights(cx);
12719 }
12720
12721 Some(rename)
12722 }
12723
12724 pub fn pending_rename(&self) -> Option<&RenameState> {
12725 self.pending_rename.as_ref()
12726 }
12727
12728 fn format(
12729 &mut self,
12730 _: &Format,
12731 window: &mut Window,
12732 cx: &mut Context<Self>,
12733 ) -> Option<Task<Result<()>>> {
12734 let project = match &self.project {
12735 Some(project) => project.clone(),
12736 None => return None,
12737 };
12738
12739 Some(self.perform_format(
12740 project,
12741 FormatTrigger::Manual,
12742 FormatTarget::Buffers,
12743 window,
12744 cx,
12745 ))
12746 }
12747
12748 fn format_selections(
12749 &mut self,
12750 _: &FormatSelections,
12751 window: &mut Window,
12752 cx: &mut Context<Self>,
12753 ) -> Option<Task<Result<()>>> {
12754 let project = match &self.project {
12755 Some(project) => project.clone(),
12756 None => return None,
12757 };
12758
12759 let ranges = self
12760 .selections
12761 .all_adjusted(cx)
12762 .into_iter()
12763 .map(|selection| selection.range())
12764 .collect_vec();
12765
12766 Some(self.perform_format(
12767 project,
12768 FormatTrigger::Manual,
12769 FormatTarget::Ranges(ranges),
12770 window,
12771 cx,
12772 ))
12773 }
12774
12775 fn perform_format(
12776 &mut self,
12777 project: Entity<Project>,
12778 trigger: FormatTrigger,
12779 target: FormatTarget,
12780 window: &mut Window,
12781 cx: &mut Context<Self>,
12782 ) -> Task<Result<()>> {
12783 let buffer = self.buffer.clone();
12784 let (buffers, target) = match target {
12785 FormatTarget::Buffers => {
12786 let mut buffers = buffer.read(cx).all_buffers();
12787 if trigger == FormatTrigger::Save {
12788 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12789 }
12790 (buffers, LspFormatTarget::Buffers)
12791 }
12792 FormatTarget::Ranges(selection_ranges) => {
12793 let multi_buffer = buffer.read(cx);
12794 let snapshot = multi_buffer.read(cx);
12795 let mut buffers = HashSet::default();
12796 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12797 BTreeMap::new();
12798 for selection_range in selection_ranges {
12799 for (buffer, buffer_range, _) in
12800 snapshot.range_to_buffer_ranges(selection_range)
12801 {
12802 let buffer_id = buffer.remote_id();
12803 let start = buffer.anchor_before(buffer_range.start);
12804 let end = buffer.anchor_after(buffer_range.end);
12805 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12806 buffer_id_to_ranges
12807 .entry(buffer_id)
12808 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12809 .or_insert_with(|| vec![start..end]);
12810 }
12811 }
12812 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12813 }
12814 };
12815
12816 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12817 let format = project.update(cx, |project, cx| {
12818 project.format(buffers, target, true, trigger, cx)
12819 });
12820
12821 cx.spawn_in(window, |_, mut cx| async move {
12822 let transaction = futures::select_biased! {
12823 transaction = format.log_err().fuse() => transaction,
12824 () = timeout => {
12825 log::warn!("timed out waiting for formatting");
12826 None
12827 }
12828 };
12829
12830 buffer
12831 .update(&mut cx, |buffer, cx| {
12832 if let Some(transaction) = transaction {
12833 if !buffer.is_singleton() {
12834 buffer.push_transaction(&transaction.0, cx);
12835 }
12836 }
12837 cx.notify();
12838 })
12839 .ok();
12840
12841 Ok(())
12842 })
12843 }
12844
12845 fn organize_imports(
12846 &mut self,
12847 _: &OrganizeImports,
12848 window: &mut Window,
12849 cx: &mut Context<Self>,
12850 ) -> Option<Task<Result<()>>> {
12851 let project = match &self.project {
12852 Some(project) => project.clone(),
12853 None => return None,
12854 };
12855 Some(self.perform_code_action_kind(
12856 project,
12857 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12858 window,
12859 cx,
12860 ))
12861 }
12862
12863 fn perform_code_action_kind(
12864 &mut self,
12865 project: Entity<Project>,
12866 kind: CodeActionKind,
12867 window: &mut Window,
12868 cx: &mut Context<Self>,
12869 ) -> Task<Result<()>> {
12870 let buffer = self.buffer.clone();
12871 let buffers = buffer.read(cx).all_buffers();
12872 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12873 let apply_action = project.update(cx, |project, cx| {
12874 project.apply_code_action_kind(buffers, kind, true, cx)
12875 });
12876 cx.spawn_in(window, |_, mut cx| async move {
12877 let transaction = futures::select_biased! {
12878 () = timeout => {
12879 log::warn!("timed out waiting for executing code action");
12880 None
12881 }
12882 transaction = apply_action.log_err().fuse() => transaction,
12883 };
12884 buffer
12885 .update(&mut cx, |buffer, cx| {
12886 // check if we need this
12887 if let Some(transaction) = transaction {
12888 if !buffer.is_singleton() {
12889 buffer.push_transaction(&transaction.0, cx);
12890 }
12891 }
12892 cx.notify();
12893 })
12894 .ok();
12895 Ok(())
12896 })
12897 }
12898
12899 fn restart_language_server(
12900 &mut self,
12901 _: &RestartLanguageServer,
12902 _: &mut Window,
12903 cx: &mut Context<Self>,
12904 ) {
12905 if let Some(project) = self.project.clone() {
12906 self.buffer.update(cx, |multi_buffer, cx| {
12907 project.update(cx, |project, cx| {
12908 project.restart_language_servers_for_buffers(
12909 multi_buffer.all_buffers().into_iter().collect(),
12910 cx,
12911 );
12912 });
12913 })
12914 }
12915 }
12916
12917 fn cancel_language_server_work(
12918 workspace: &mut Workspace,
12919 _: &actions::CancelLanguageServerWork,
12920 _: &mut Window,
12921 cx: &mut Context<Workspace>,
12922 ) {
12923 let project = workspace.project();
12924 let buffers = workspace
12925 .active_item(cx)
12926 .and_then(|item| item.act_as::<Editor>(cx))
12927 .map_or(HashSet::default(), |editor| {
12928 editor.read(cx).buffer.read(cx).all_buffers()
12929 });
12930 project.update(cx, |project, cx| {
12931 project.cancel_language_server_work_for_buffers(buffers, cx);
12932 });
12933 }
12934
12935 fn show_character_palette(
12936 &mut self,
12937 _: &ShowCharacterPalette,
12938 window: &mut Window,
12939 _: &mut Context<Self>,
12940 ) {
12941 window.show_character_palette();
12942 }
12943
12944 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12945 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12946 let buffer = self.buffer.read(cx).snapshot(cx);
12947 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12948 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12949 let is_valid = buffer
12950 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12951 .any(|entry| {
12952 entry.diagnostic.is_primary
12953 && !entry.range.is_empty()
12954 && entry.range.start == primary_range_start
12955 && entry.diagnostic.message == active_diagnostics.primary_message
12956 });
12957
12958 if is_valid != active_diagnostics.is_valid {
12959 active_diagnostics.is_valid = is_valid;
12960 if is_valid {
12961 let mut new_styles = HashMap::default();
12962 for (block_id, diagnostic) in &active_diagnostics.blocks {
12963 new_styles.insert(
12964 *block_id,
12965 diagnostic_block_renderer(diagnostic.clone(), None, true),
12966 );
12967 }
12968 self.display_map.update(cx, |display_map, _cx| {
12969 display_map.replace_blocks(new_styles);
12970 });
12971 } else {
12972 self.dismiss_diagnostics(cx);
12973 }
12974 }
12975 }
12976 }
12977
12978 fn activate_diagnostics(
12979 &mut self,
12980 buffer_id: BufferId,
12981 group_id: usize,
12982 window: &mut Window,
12983 cx: &mut Context<Self>,
12984 ) {
12985 self.dismiss_diagnostics(cx);
12986 let snapshot = self.snapshot(window, cx);
12987 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12988 let buffer = self.buffer.read(cx).snapshot(cx);
12989
12990 let mut primary_range = None;
12991 let mut primary_message = None;
12992 let diagnostic_group = buffer
12993 .diagnostic_group(buffer_id, group_id)
12994 .filter_map(|entry| {
12995 let start = entry.range.start;
12996 let end = entry.range.end;
12997 if snapshot.is_line_folded(MultiBufferRow(start.row))
12998 && (start.row == end.row
12999 || snapshot.is_line_folded(MultiBufferRow(end.row)))
13000 {
13001 return None;
13002 }
13003 if entry.diagnostic.is_primary {
13004 primary_range = Some(entry.range.clone());
13005 primary_message = Some(entry.diagnostic.message.clone());
13006 }
13007 Some(entry)
13008 })
13009 .collect::<Vec<_>>();
13010 let primary_range = primary_range?;
13011 let primary_message = primary_message?;
13012
13013 let blocks = display_map
13014 .insert_blocks(
13015 diagnostic_group.iter().map(|entry| {
13016 let diagnostic = entry.diagnostic.clone();
13017 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13018 BlockProperties {
13019 style: BlockStyle::Fixed,
13020 placement: BlockPlacement::Below(
13021 buffer.anchor_after(entry.range.start),
13022 ),
13023 height: message_height,
13024 render: diagnostic_block_renderer(diagnostic, None, true),
13025 priority: 0,
13026 }
13027 }),
13028 cx,
13029 )
13030 .into_iter()
13031 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13032 .collect();
13033
13034 Some(ActiveDiagnosticGroup {
13035 primary_range: buffer.anchor_before(primary_range.start)
13036 ..buffer.anchor_after(primary_range.end),
13037 primary_message,
13038 group_id,
13039 blocks,
13040 is_valid: true,
13041 })
13042 });
13043 }
13044
13045 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13046 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13047 self.display_map.update(cx, |display_map, cx| {
13048 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13049 });
13050 cx.notify();
13051 }
13052 }
13053
13054 /// Disable inline diagnostics rendering for this editor.
13055 pub fn disable_inline_diagnostics(&mut self) {
13056 self.inline_diagnostics_enabled = false;
13057 self.inline_diagnostics_update = Task::ready(());
13058 self.inline_diagnostics.clear();
13059 }
13060
13061 pub fn inline_diagnostics_enabled(&self) -> bool {
13062 self.inline_diagnostics_enabled
13063 }
13064
13065 pub fn show_inline_diagnostics(&self) -> bool {
13066 self.show_inline_diagnostics
13067 }
13068
13069 pub fn toggle_inline_diagnostics(
13070 &mut self,
13071 _: &ToggleInlineDiagnostics,
13072 window: &mut Window,
13073 cx: &mut Context<'_, Editor>,
13074 ) {
13075 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13076 self.refresh_inline_diagnostics(false, window, cx);
13077 }
13078
13079 fn refresh_inline_diagnostics(
13080 &mut self,
13081 debounce: bool,
13082 window: &mut Window,
13083 cx: &mut Context<Self>,
13084 ) {
13085 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13086 self.inline_diagnostics_update = Task::ready(());
13087 self.inline_diagnostics.clear();
13088 return;
13089 }
13090
13091 let debounce_ms = ProjectSettings::get_global(cx)
13092 .diagnostics
13093 .inline
13094 .update_debounce_ms;
13095 let debounce = if debounce && debounce_ms > 0 {
13096 Some(Duration::from_millis(debounce_ms))
13097 } else {
13098 None
13099 };
13100 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
13101 if let Some(debounce) = debounce {
13102 cx.background_executor().timer(debounce).await;
13103 }
13104 let Some(snapshot) = editor
13105 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13106 .ok()
13107 else {
13108 return;
13109 };
13110
13111 let new_inline_diagnostics = cx
13112 .background_spawn(async move {
13113 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13114 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13115 let message = diagnostic_entry
13116 .diagnostic
13117 .message
13118 .split_once('\n')
13119 .map(|(line, _)| line)
13120 .map(SharedString::new)
13121 .unwrap_or_else(|| {
13122 SharedString::from(diagnostic_entry.diagnostic.message)
13123 });
13124 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13125 let (Ok(i) | Err(i)) = inline_diagnostics
13126 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13127 inline_diagnostics.insert(
13128 i,
13129 (
13130 start_anchor,
13131 InlineDiagnostic {
13132 message,
13133 group_id: diagnostic_entry.diagnostic.group_id,
13134 start: diagnostic_entry.range.start.to_point(&snapshot),
13135 is_primary: diagnostic_entry.diagnostic.is_primary,
13136 severity: diagnostic_entry.diagnostic.severity,
13137 },
13138 ),
13139 );
13140 }
13141 inline_diagnostics
13142 })
13143 .await;
13144
13145 editor
13146 .update(&mut cx, |editor, cx| {
13147 editor.inline_diagnostics = new_inline_diagnostics;
13148 cx.notify();
13149 })
13150 .ok();
13151 });
13152 }
13153
13154 pub fn set_selections_from_remote(
13155 &mut self,
13156 selections: Vec<Selection<Anchor>>,
13157 pending_selection: Option<Selection<Anchor>>,
13158 window: &mut Window,
13159 cx: &mut Context<Self>,
13160 ) {
13161 let old_cursor_position = self.selections.newest_anchor().head();
13162 self.selections.change_with(cx, |s| {
13163 s.select_anchors(selections);
13164 if let Some(pending_selection) = pending_selection {
13165 s.set_pending(pending_selection, SelectMode::Character);
13166 } else {
13167 s.clear_pending();
13168 }
13169 });
13170 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13171 }
13172
13173 fn push_to_selection_history(&mut self) {
13174 self.selection_history.push(SelectionHistoryEntry {
13175 selections: self.selections.disjoint_anchors(),
13176 select_next_state: self.select_next_state.clone(),
13177 select_prev_state: self.select_prev_state.clone(),
13178 add_selections_state: self.add_selections_state.clone(),
13179 });
13180 }
13181
13182 pub fn transact(
13183 &mut self,
13184 window: &mut Window,
13185 cx: &mut Context<Self>,
13186 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13187 ) -> Option<TransactionId> {
13188 self.start_transaction_at(Instant::now(), window, cx);
13189 update(self, window, cx);
13190 self.end_transaction_at(Instant::now(), cx)
13191 }
13192
13193 pub fn start_transaction_at(
13194 &mut self,
13195 now: Instant,
13196 window: &mut Window,
13197 cx: &mut Context<Self>,
13198 ) {
13199 self.end_selection(window, cx);
13200 if let Some(tx_id) = self
13201 .buffer
13202 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13203 {
13204 self.selection_history
13205 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13206 cx.emit(EditorEvent::TransactionBegun {
13207 transaction_id: tx_id,
13208 })
13209 }
13210 }
13211
13212 pub fn end_transaction_at(
13213 &mut self,
13214 now: Instant,
13215 cx: &mut Context<Self>,
13216 ) -> Option<TransactionId> {
13217 if let Some(transaction_id) = self
13218 .buffer
13219 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13220 {
13221 if let Some((_, end_selections)) =
13222 self.selection_history.transaction_mut(transaction_id)
13223 {
13224 *end_selections = Some(self.selections.disjoint_anchors());
13225 } else {
13226 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13227 }
13228
13229 cx.emit(EditorEvent::Edited { transaction_id });
13230 Some(transaction_id)
13231 } else {
13232 None
13233 }
13234 }
13235
13236 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13237 if self.selection_mark_mode {
13238 self.change_selections(None, window, cx, |s| {
13239 s.move_with(|_, sel| {
13240 sel.collapse_to(sel.head(), SelectionGoal::None);
13241 });
13242 })
13243 }
13244 self.selection_mark_mode = true;
13245 cx.notify();
13246 }
13247
13248 pub fn swap_selection_ends(
13249 &mut self,
13250 _: &actions::SwapSelectionEnds,
13251 window: &mut Window,
13252 cx: &mut Context<Self>,
13253 ) {
13254 self.change_selections(None, window, cx, |s| {
13255 s.move_with(|_, sel| {
13256 if sel.start != sel.end {
13257 sel.reversed = !sel.reversed
13258 }
13259 });
13260 });
13261 self.request_autoscroll(Autoscroll::newest(), cx);
13262 cx.notify();
13263 }
13264
13265 pub fn toggle_fold(
13266 &mut self,
13267 _: &actions::ToggleFold,
13268 window: &mut Window,
13269 cx: &mut Context<Self>,
13270 ) {
13271 if self.is_singleton(cx) {
13272 let selection = self.selections.newest::<Point>(cx);
13273
13274 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13275 let range = if selection.is_empty() {
13276 let point = selection.head().to_display_point(&display_map);
13277 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13278 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13279 .to_point(&display_map);
13280 start..end
13281 } else {
13282 selection.range()
13283 };
13284 if display_map.folds_in_range(range).next().is_some() {
13285 self.unfold_lines(&Default::default(), window, cx)
13286 } else {
13287 self.fold(&Default::default(), window, cx)
13288 }
13289 } else {
13290 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13291 let buffer_ids: HashSet<_> = self
13292 .selections
13293 .disjoint_anchor_ranges()
13294 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13295 .collect();
13296
13297 let should_unfold = buffer_ids
13298 .iter()
13299 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13300
13301 for buffer_id in buffer_ids {
13302 if should_unfold {
13303 self.unfold_buffer(buffer_id, cx);
13304 } else {
13305 self.fold_buffer(buffer_id, cx);
13306 }
13307 }
13308 }
13309 }
13310
13311 pub fn toggle_fold_recursive(
13312 &mut self,
13313 _: &actions::ToggleFoldRecursive,
13314 window: &mut Window,
13315 cx: &mut Context<Self>,
13316 ) {
13317 let selection = self.selections.newest::<Point>(cx);
13318
13319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13320 let range = if selection.is_empty() {
13321 let point = selection.head().to_display_point(&display_map);
13322 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13323 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13324 .to_point(&display_map);
13325 start..end
13326 } else {
13327 selection.range()
13328 };
13329 if display_map.folds_in_range(range).next().is_some() {
13330 self.unfold_recursive(&Default::default(), window, cx)
13331 } else {
13332 self.fold_recursive(&Default::default(), window, cx)
13333 }
13334 }
13335
13336 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13337 if self.is_singleton(cx) {
13338 let mut to_fold = Vec::new();
13339 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13340 let selections = self.selections.all_adjusted(cx);
13341
13342 for selection in selections {
13343 let range = selection.range().sorted();
13344 let buffer_start_row = range.start.row;
13345
13346 if range.start.row != range.end.row {
13347 let mut found = false;
13348 let mut row = range.start.row;
13349 while row <= range.end.row {
13350 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13351 {
13352 found = true;
13353 row = crease.range().end.row + 1;
13354 to_fold.push(crease);
13355 } else {
13356 row += 1
13357 }
13358 }
13359 if found {
13360 continue;
13361 }
13362 }
13363
13364 for row in (0..=range.start.row).rev() {
13365 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13366 if crease.range().end.row >= buffer_start_row {
13367 to_fold.push(crease);
13368 if row <= range.start.row {
13369 break;
13370 }
13371 }
13372 }
13373 }
13374 }
13375
13376 self.fold_creases(to_fold, true, window, cx);
13377 } else {
13378 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13379 let buffer_ids = self
13380 .selections
13381 .disjoint_anchor_ranges()
13382 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13383 .collect::<HashSet<_>>();
13384 for buffer_id in buffer_ids {
13385 self.fold_buffer(buffer_id, cx);
13386 }
13387 }
13388 }
13389
13390 fn fold_at_level(
13391 &mut self,
13392 fold_at: &FoldAtLevel,
13393 window: &mut Window,
13394 cx: &mut Context<Self>,
13395 ) {
13396 if !self.buffer.read(cx).is_singleton() {
13397 return;
13398 }
13399
13400 let fold_at_level = fold_at.0;
13401 let snapshot = self.buffer.read(cx).snapshot(cx);
13402 let mut to_fold = Vec::new();
13403 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13404
13405 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13406 while start_row < end_row {
13407 match self
13408 .snapshot(window, cx)
13409 .crease_for_buffer_row(MultiBufferRow(start_row))
13410 {
13411 Some(crease) => {
13412 let nested_start_row = crease.range().start.row + 1;
13413 let nested_end_row = crease.range().end.row;
13414
13415 if current_level < fold_at_level {
13416 stack.push((nested_start_row, nested_end_row, current_level + 1));
13417 } else if current_level == fold_at_level {
13418 to_fold.push(crease);
13419 }
13420
13421 start_row = nested_end_row + 1;
13422 }
13423 None => start_row += 1,
13424 }
13425 }
13426 }
13427
13428 self.fold_creases(to_fold, true, window, cx);
13429 }
13430
13431 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13432 if self.buffer.read(cx).is_singleton() {
13433 let mut fold_ranges = Vec::new();
13434 let snapshot = self.buffer.read(cx).snapshot(cx);
13435
13436 for row in 0..snapshot.max_row().0 {
13437 if let Some(foldable_range) = self
13438 .snapshot(window, cx)
13439 .crease_for_buffer_row(MultiBufferRow(row))
13440 {
13441 fold_ranges.push(foldable_range);
13442 }
13443 }
13444
13445 self.fold_creases(fold_ranges, true, window, cx);
13446 } else {
13447 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13448 editor
13449 .update_in(&mut cx, |editor, _, cx| {
13450 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13451 editor.fold_buffer(buffer_id, cx);
13452 }
13453 })
13454 .ok();
13455 });
13456 }
13457 }
13458
13459 pub fn fold_function_bodies(
13460 &mut self,
13461 _: &actions::FoldFunctionBodies,
13462 window: &mut Window,
13463 cx: &mut Context<Self>,
13464 ) {
13465 let snapshot = self.buffer.read(cx).snapshot(cx);
13466
13467 let ranges = snapshot
13468 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13469 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13470 .collect::<Vec<_>>();
13471
13472 let creases = ranges
13473 .into_iter()
13474 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13475 .collect();
13476
13477 self.fold_creases(creases, true, window, cx);
13478 }
13479
13480 pub fn fold_recursive(
13481 &mut self,
13482 _: &actions::FoldRecursive,
13483 window: &mut Window,
13484 cx: &mut Context<Self>,
13485 ) {
13486 let mut to_fold = Vec::new();
13487 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13488 let selections = self.selections.all_adjusted(cx);
13489
13490 for selection in selections {
13491 let range = selection.range().sorted();
13492 let buffer_start_row = range.start.row;
13493
13494 if range.start.row != range.end.row {
13495 let mut found = false;
13496 for row in range.start.row..=range.end.row {
13497 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13498 found = true;
13499 to_fold.push(crease);
13500 }
13501 }
13502 if found {
13503 continue;
13504 }
13505 }
13506
13507 for row in (0..=range.start.row).rev() {
13508 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13509 if crease.range().end.row >= buffer_start_row {
13510 to_fold.push(crease);
13511 } else {
13512 break;
13513 }
13514 }
13515 }
13516 }
13517
13518 self.fold_creases(to_fold, true, window, cx);
13519 }
13520
13521 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13522 let buffer_row = fold_at.buffer_row;
13523 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13524
13525 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13526 let autoscroll = self
13527 .selections
13528 .all::<Point>(cx)
13529 .iter()
13530 .any(|selection| crease.range().overlaps(&selection.range()));
13531
13532 self.fold_creases(vec![crease], autoscroll, window, cx);
13533 }
13534 }
13535
13536 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13537 if self.is_singleton(cx) {
13538 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13539 let buffer = &display_map.buffer_snapshot;
13540 let selections = self.selections.all::<Point>(cx);
13541 let ranges = selections
13542 .iter()
13543 .map(|s| {
13544 let range = s.display_range(&display_map).sorted();
13545 let mut start = range.start.to_point(&display_map);
13546 let mut end = range.end.to_point(&display_map);
13547 start.column = 0;
13548 end.column = buffer.line_len(MultiBufferRow(end.row));
13549 start..end
13550 })
13551 .collect::<Vec<_>>();
13552
13553 self.unfold_ranges(&ranges, true, true, cx);
13554 } else {
13555 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13556 let buffer_ids = self
13557 .selections
13558 .disjoint_anchor_ranges()
13559 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13560 .collect::<HashSet<_>>();
13561 for buffer_id in buffer_ids {
13562 self.unfold_buffer(buffer_id, cx);
13563 }
13564 }
13565 }
13566
13567 pub fn unfold_recursive(
13568 &mut self,
13569 _: &UnfoldRecursive,
13570 _window: &mut Window,
13571 cx: &mut Context<Self>,
13572 ) {
13573 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13574 let selections = self.selections.all::<Point>(cx);
13575 let ranges = selections
13576 .iter()
13577 .map(|s| {
13578 let mut range = s.display_range(&display_map).sorted();
13579 *range.start.column_mut() = 0;
13580 *range.end.column_mut() = display_map.line_len(range.end.row());
13581 let start = range.start.to_point(&display_map);
13582 let end = range.end.to_point(&display_map);
13583 start..end
13584 })
13585 .collect::<Vec<_>>();
13586
13587 self.unfold_ranges(&ranges, true, true, cx);
13588 }
13589
13590 pub fn unfold_at(
13591 &mut self,
13592 unfold_at: &UnfoldAt,
13593 _window: &mut Window,
13594 cx: &mut Context<Self>,
13595 ) {
13596 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13597
13598 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13599 ..Point::new(
13600 unfold_at.buffer_row.0,
13601 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13602 );
13603
13604 let autoscroll = self
13605 .selections
13606 .all::<Point>(cx)
13607 .iter()
13608 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13609
13610 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13611 }
13612
13613 pub fn unfold_all(
13614 &mut self,
13615 _: &actions::UnfoldAll,
13616 _window: &mut Window,
13617 cx: &mut Context<Self>,
13618 ) {
13619 if self.buffer.read(cx).is_singleton() {
13620 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13621 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13622 } else {
13623 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13624 editor
13625 .update(&mut cx, |editor, cx| {
13626 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13627 editor.unfold_buffer(buffer_id, cx);
13628 }
13629 })
13630 .ok();
13631 });
13632 }
13633 }
13634
13635 pub fn fold_selected_ranges(
13636 &mut self,
13637 _: &FoldSelectedRanges,
13638 window: &mut Window,
13639 cx: &mut Context<Self>,
13640 ) {
13641 let selections = self.selections.all::<Point>(cx);
13642 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13643 let line_mode = self.selections.line_mode;
13644 let ranges = selections
13645 .into_iter()
13646 .map(|s| {
13647 if line_mode {
13648 let start = Point::new(s.start.row, 0);
13649 let end = Point::new(
13650 s.end.row,
13651 display_map
13652 .buffer_snapshot
13653 .line_len(MultiBufferRow(s.end.row)),
13654 );
13655 Crease::simple(start..end, display_map.fold_placeholder.clone())
13656 } else {
13657 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13658 }
13659 })
13660 .collect::<Vec<_>>();
13661 self.fold_creases(ranges, true, window, cx);
13662 }
13663
13664 pub fn fold_ranges<T: ToOffset + Clone>(
13665 &mut self,
13666 ranges: Vec<Range<T>>,
13667 auto_scroll: bool,
13668 window: &mut Window,
13669 cx: &mut Context<Self>,
13670 ) {
13671 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13672 let ranges = ranges
13673 .into_iter()
13674 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13675 .collect::<Vec<_>>();
13676 self.fold_creases(ranges, auto_scroll, window, cx);
13677 }
13678
13679 pub fn fold_creases<T: ToOffset + Clone>(
13680 &mut self,
13681 creases: Vec<Crease<T>>,
13682 auto_scroll: bool,
13683 window: &mut Window,
13684 cx: &mut Context<Self>,
13685 ) {
13686 if creases.is_empty() {
13687 return;
13688 }
13689
13690 let mut buffers_affected = HashSet::default();
13691 let multi_buffer = self.buffer().read(cx);
13692 for crease in &creases {
13693 if let Some((_, buffer, _)) =
13694 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13695 {
13696 buffers_affected.insert(buffer.read(cx).remote_id());
13697 };
13698 }
13699
13700 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13701
13702 if auto_scroll {
13703 self.request_autoscroll(Autoscroll::fit(), cx);
13704 }
13705
13706 cx.notify();
13707
13708 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13709 // Clear diagnostics block when folding a range that contains it.
13710 let snapshot = self.snapshot(window, cx);
13711 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13712 drop(snapshot);
13713 self.active_diagnostics = Some(active_diagnostics);
13714 self.dismiss_diagnostics(cx);
13715 } else {
13716 self.active_diagnostics = Some(active_diagnostics);
13717 }
13718 }
13719
13720 self.scrollbar_marker_state.dirty = true;
13721 }
13722
13723 /// Removes any folds whose ranges intersect any of the given ranges.
13724 pub fn unfold_ranges<T: ToOffset + Clone>(
13725 &mut self,
13726 ranges: &[Range<T>],
13727 inclusive: bool,
13728 auto_scroll: bool,
13729 cx: &mut Context<Self>,
13730 ) {
13731 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13732 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13733 });
13734 }
13735
13736 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13737 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13738 return;
13739 }
13740 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13741 self.display_map.update(cx, |display_map, cx| {
13742 display_map.fold_buffers([buffer_id], cx)
13743 });
13744 cx.emit(EditorEvent::BufferFoldToggled {
13745 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13746 folded: true,
13747 });
13748 cx.notify();
13749 }
13750
13751 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13752 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13753 return;
13754 }
13755 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13756 self.display_map.update(cx, |display_map, cx| {
13757 display_map.unfold_buffers([buffer_id], cx);
13758 });
13759 cx.emit(EditorEvent::BufferFoldToggled {
13760 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13761 folded: false,
13762 });
13763 cx.notify();
13764 }
13765
13766 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13767 self.display_map.read(cx).is_buffer_folded(buffer)
13768 }
13769
13770 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13771 self.display_map.read(cx).folded_buffers()
13772 }
13773
13774 /// Removes any folds with the given ranges.
13775 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13776 &mut self,
13777 ranges: &[Range<T>],
13778 type_id: TypeId,
13779 auto_scroll: bool,
13780 cx: &mut Context<Self>,
13781 ) {
13782 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13783 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13784 });
13785 }
13786
13787 fn remove_folds_with<T: ToOffset + Clone>(
13788 &mut self,
13789 ranges: &[Range<T>],
13790 auto_scroll: bool,
13791 cx: &mut Context<Self>,
13792 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13793 ) {
13794 if ranges.is_empty() {
13795 return;
13796 }
13797
13798 let mut buffers_affected = HashSet::default();
13799 let multi_buffer = self.buffer().read(cx);
13800 for range in ranges {
13801 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13802 buffers_affected.insert(buffer.read(cx).remote_id());
13803 };
13804 }
13805
13806 self.display_map.update(cx, update);
13807
13808 if auto_scroll {
13809 self.request_autoscroll(Autoscroll::fit(), cx);
13810 }
13811
13812 cx.notify();
13813 self.scrollbar_marker_state.dirty = true;
13814 self.active_indent_guides_state.dirty = true;
13815 }
13816
13817 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13818 self.display_map.read(cx).fold_placeholder.clone()
13819 }
13820
13821 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13822 self.buffer.update(cx, |buffer, cx| {
13823 buffer.set_all_diff_hunks_expanded(cx);
13824 });
13825 }
13826
13827 pub fn expand_all_diff_hunks(
13828 &mut self,
13829 _: &ExpandAllDiffHunks,
13830 _window: &mut Window,
13831 cx: &mut Context<Self>,
13832 ) {
13833 self.buffer.update(cx, |buffer, cx| {
13834 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13835 });
13836 }
13837
13838 pub fn toggle_selected_diff_hunks(
13839 &mut self,
13840 _: &ToggleSelectedDiffHunks,
13841 _window: &mut Window,
13842 cx: &mut Context<Self>,
13843 ) {
13844 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13845 self.toggle_diff_hunks_in_ranges(ranges, cx);
13846 }
13847
13848 pub fn diff_hunks_in_ranges<'a>(
13849 &'a self,
13850 ranges: &'a [Range<Anchor>],
13851 buffer: &'a MultiBufferSnapshot,
13852 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13853 ranges.iter().flat_map(move |range| {
13854 let end_excerpt_id = range.end.excerpt_id;
13855 let range = range.to_point(buffer);
13856 let mut peek_end = range.end;
13857 if range.end.row < buffer.max_row().0 {
13858 peek_end = Point::new(range.end.row + 1, 0);
13859 }
13860 buffer
13861 .diff_hunks_in_range(range.start..peek_end)
13862 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13863 })
13864 }
13865
13866 pub fn has_stageable_diff_hunks_in_ranges(
13867 &self,
13868 ranges: &[Range<Anchor>],
13869 snapshot: &MultiBufferSnapshot,
13870 ) -> bool {
13871 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13872 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13873 }
13874
13875 pub fn toggle_staged_selected_diff_hunks(
13876 &mut self,
13877 _: &::git::ToggleStaged,
13878 _: &mut Window,
13879 cx: &mut Context<Self>,
13880 ) {
13881 let snapshot = self.buffer.read(cx).snapshot(cx);
13882 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13883 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13884 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13885 }
13886
13887 pub fn stage_and_next(
13888 &mut self,
13889 _: &::git::StageAndNext,
13890 window: &mut Window,
13891 cx: &mut Context<Self>,
13892 ) {
13893 self.do_stage_or_unstage_and_next(true, window, cx);
13894 }
13895
13896 pub fn unstage_and_next(
13897 &mut self,
13898 _: &::git::UnstageAndNext,
13899 window: &mut Window,
13900 cx: &mut Context<Self>,
13901 ) {
13902 self.do_stage_or_unstage_and_next(false, window, cx);
13903 }
13904
13905 pub fn stage_or_unstage_diff_hunks(
13906 &mut self,
13907 stage: bool,
13908 ranges: Vec<Range<Anchor>>,
13909 cx: &mut Context<Self>,
13910 ) {
13911 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13912 cx.spawn(|this, mut cx| async move {
13913 task.await?;
13914 this.update(&mut cx, |this, cx| {
13915 let snapshot = this.buffer.read(cx).snapshot(cx);
13916 let chunk_by = this
13917 .diff_hunks_in_ranges(&ranges, &snapshot)
13918 .chunk_by(|hunk| hunk.buffer_id);
13919 for (buffer_id, hunks) in &chunk_by {
13920 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13921 }
13922 })
13923 })
13924 .detach_and_log_err(cx);
13925 }
13926
13927 fn save_buffers_for_ranges_if_needed(
13928 &mut self,
13929 ranges: &[Range<Anchor>],
13930 cx: &mut Context<'_, Editor>,
13931 ) -> Task<Result<()>> {
13932 let multibuffer = self.buffer.read(cx);
13933 let snapshot = multibuffer.read(cx);
13934 let buffer_ids: HashSet<_> = ranges
13935 .iter()
13936 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13937 .collect();
13938 drop(snapshot);
13939
13940 let mut buffers = HashSet::default();
13941 for buffer_id in buffer_ids {
13942 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13943 let buffer = buffer_entity.read(cx);
13944 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13945 {
13946 buffers.insert(buffer_entity);
13947 }
13948 }
13949 }
13950
13951 if let Some(project) = &self.project {
13952 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13953 } else {
13954 Task::ready(Ok(()))
13955 }
13956 }
13957
13958 fn do_stage_or_unstage_and_next(
13959 &mut self,
13960 stage: bool,
13961 window: &mut Window,
13962 cx: &mut Context<Self>,
13963 ) {
13964 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13965
13966 if ranges.iter().any(|range| range.start != range.end) {
13967 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13968 return;
13969 }
13970
13971 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13972 let snapshot = self.snapshot(window, cx);
13973 let position = self.selections.newest::<Point>(cx).head();
13974 let mut row = snapshot
13975 .buffer_snapshot
13976 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13977 .find(|hunk| hunk.row_range.start.0 > position.row)
13978 .map(|hunk| hunk.row_range.start);
13979
13980 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
13981 // Outside of the project diff editor, wrap around to the beginning.
13982 if !all_diff_hunks_expanded {
13983 row = row.or_else(|| {
13984 snapshot
13985 .buffer_snapshot
13986 .diff_hunks_in_range(Point::zero()..position)
13987 .find(|hunk| hunk.row_range.end.0 < position.row)
13988 .map(|hunk| hunk.row_range.start)
13989 });
13990 }
13991
13992 if let Some(row) = row {
13993 let destination = Point::new(row.0, 0);
13994 let autoscroll = Autoscroll::center();
13995
13996 self.unfold_ranges(&[destination..destination], false, false, cx);
13997 self.change_selections(Some(autoscroll), window, cx, |s| {
13998 s.select_ranges([destination..destination]);
13999 });
14000 } else if all_diff_hunks_expanded {
14001 window.dispatch_action(::git::ExpandCommitEditor.boxed_clone(), cx);
14002 }
14003 }
14004
14005 fn do_stage_or_unstage(
14006 &self,
14007 stage: bool,
14008 buffer_id: BufferId,
14009 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14010 cx: &mut App,
14011 ) -> Option<()> {
14012 let project = self.project.as_ref()?;
14013 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14014 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14015 let buffer_snapshot = buffer.read(cx).snapshot();
14016 let file_exists = buffer_snapshot
14017 .file()
14018 .is_some_and(|file| file.disk_state().exists());
14019 diff.update(cx, |diff, cx| {
14020 diff.stage_or_unstage_hunks(
14021 stage,
14022 &hunks
14023 .map(|hunk| buffer_diff::DiffHunk {
14024 buffer_range: hunk.buffer_range,
14025 diff_base_byte_range: hunk.diff_base_byte_range,
14026 secondary_status: hunk.secondary_status,
14027 range: Point::zero()..Point::zero(), // unused
14028 })
14029 .collect::<Vec<_>>(),
14030 &buffer_snapshot,
14031 file_exists,
14032 cx,
14033 )
14034 });
14035 None
14036 }
14037
14038 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14039 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14040 self.buffer
14041 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14042 }
14043
14044 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14045 self.buffer.update(cx, |buffer, cx| {
14046 let ranges = vec![Anchor::min()..Anchor::max()];
14047 if !buffer.all_diff_hunks_expanded()
14048 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14049 {
14050 buffer.collapse_diff_hunks(ranges, cx);
14051 true
14052 } else {
14053 false
14054 }
14055 })
14056 }
14057
14058 fn toggle_diff_hunks_in_ranges(
14059 &mut self,
14060 ranges: Vec<Range<Anchor>>,
14061 cx: &mut Context<'_, Editor>,
14062 ) {
14063 self.buffer.update(cx, |buffer, cx| {
14064 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14065 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14066 })
14067 }
14068
14069 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14070 self.buffer.update(cx, |buffer, cx| {
14071 let snapshot = buffer.snapshot(cx);
14072 let excerpt_id = range.end.excerpt_id;
14073 let point_range = range.to_point(&snapshot);
14074 let expand = !buffer.single_hunk_is_expanded(range, cx);
14075 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14076 })
14077 }
14078
14079 pub(crate) fn apply_all_diff_hunks(
14080 &mut self,
14081 _: &ApplyAllDiffHunks,
14082 window: &mut Window,
14083 cx: &mut Context<Self>,
14084 ) {
14085 let buffers = self.buffer.read(cx).all_buffers();
14086 for branch_buffer in buffers {
14087 branch_buffer.update(cx, |branch_buffer, cx| {
14088 branch_buffer.merge_into_base(Vec::new(), cx);
14089 });
14090 }
14091
14092 if let Some(project) = self.project.clone() {
14093 self.save(true, project, window, cx).detach_and_log_err(cx);
14094 }
14095 }
14096
14097 pub(crate) fn apply_selected_diff_hunks(
14098 &mut self,
14099 _: &ApplyDiffHunk,
14100 window: &mut Window,
14101 cx: &mut Context<Self>,
14102 ) {
14103 let snapshot = self.snapshot(window, cx);
14104 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14105 let mut ranges_by_buffer = HashMap::default();
14106 self.transact(window, cx, |editor, _window, cx| {
14107 for hunk in hunks {
14108 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14109 ranges_by_buffer
14110 .entry(buffer.clone())
14111 .or_insert_with(Vec::new)
14112 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14113 }
14114 }
14115
14116 for (buffer, ranges) in ranges_by_buffer {
14117 buffer.update(cx, |buffer, cx| {
14118 buffer.merge_into_base(ranges, cx);
14119 });
14120 }
14121 });
14122
14123 if let Some(project) = self.project.clone() {
14124 self.save(true, project, window, cx).detach_and_log_err(cx);
14125 }
14126 }
14127
14128 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14129 if hovered != self.gutter_hovered {
14130 self.gutter_hovered = hovered;
14131 cx.notify();
14132 }
14133 }
14134
14135 pub fn insert_blocks(
14136 &mut self,
14137 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14138 autoscroll: Option<Autoscroll>,
14139 cx: &mut Context<Self>,
14140 ) -> Vec<CustomBlockId> {
14141 let blocks = self
14142 .display_map
14143 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14144 if let Some(autoscroll) = autoscroll {
14145 self.request_autoscroll(autoscroll, cx);
14146 }
14147 cx.notify();
14148 blocks
14149 }
14150
14151 pub fn resize_blocks(
14152 &mut self,
14153 heights: HashMap<CustomBlockId, u32>,
14154 autoscroll: Option<Autoscroll>,
14155 cx: &mut Context<Self>,
14156 ) {
14157 self.display_map
14158 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14159 if let Some(autoscroll) = autoscroll {
14160 self.request_autoscroll(autoscroll, cx);
14161 }
14162 cx.notify();
14163 }
14164
14165 pub fn replace_blocks(
14166 &mut self,
14167 renderers: HashMap<CustomBlockId, RenderBlock>,
14168 autoscroll: Option<Autoscroll>,
14169 cx: &mut Context<Self>,
14170 ) {
14171 self.display_map
14172 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14173 if let Some(autoscroll) = autoscroll {
14174 self.request_autoscroll(autoscroll, cx);
14175 }
14176 cx.notify();
14177 }
14178
14179 pub fn remove_blocks(
14180 &mut self,
14181 block_ids: HashSet<CustomBlockId>,
14182 autoscroll: Option<Autoscroll>,
14183 cx: &mut Context<Self>,
14184 ) {
14185 self.display_map.update(cx, |display_map, cx| {
14186 display_map.remove_blocks(block_ids, cx)
14187 });
14188 if let Some(autoscroll) = autoscroll {
14189 self.request_autoscroll(autoscroll, cx);
14190 }
14191 cx.notify();
14192 }
14193
14194 pub fn row_for_block(
14195 &self,
14196 block_id: CustomBlockId,
14197 cx: &mut Context<Self>,
14198 ) -> Option<DisplayRow> {
14199 self.display_map
14200 .update(cx, |map, cx| map.row_for_block(block_id, cx))
14201 }
14202
14203 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14204 self.focused_block = Some(focused_block);
14205 }
14206
14207 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14208 self.focused_block.take()
14209 }
14210
14211 pub fn insert_creases(
14212 &mut self,
14213 creases: impl IntoIterator<Item = Crease<Anchor>>,
14214 cx: &mut Context<Self>,
14215 ) -> Vec<CreaseId> {
14216 self.display_map
14217 .update(cx, |map, cx| map.insert_creases(creases, cx))
14218 }
14219
14220 pub fn remove_creases(
14221 &mut self,
14222 ids: impl IntoIterator<Item = CreaseId>,
14223 cx: &mut Context<Self>,
14224 ) {
14225 self.display_map
14226 .update(cx, |map, cx| map.remove_creases(ids, cx));
14227 }
14228
14229 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14230 self.display_map
14231 .update(cx, |map, cx| map.snapshot(cx))
14232 .longest_row()
14233 }
14234
14235 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14236 self.display_map
14237 .update(cx, |map, cx| map.snapshot(cx))
14238 .max_point()
14239 }
14240
14241 pub fn text(&self, cx: &App) -> String {
14242 self.buffer.read(cx).read(cx).text()
14243 }
14244
14245 pub fn is_empty(&self, cx: &App) -> bool {
14246 self.buffer.read(cx).read(cx).is_empty()
14247 }
14248
14249 pub fn text_option(&self, cx: &App) -> Option<String> {
14250 let text = self.text(cx);
14251 let text = text.trim();
14252
14253 if text.is_empty() {
14254 return None;
14255 }
14256
14257 Some(text.to_string())
14258 }
14259
14260 pub fn set_text(
14261 &mut self,
14262 text: impl Into<Arc<str>>,
14263 window: &mut Window,
14264 cx: &mut Context<Self>,
14265 ) {
14266 self.transact(window, cx, |this, _, cx| {
14267 this.buffer
14268 .read(cx)
14269 .as_singleton()
14270 .expect("you can only call set_text on editors for singleton buffers")
14271 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14272 });
14273 }
14274
14275 pub fn display_text(&self, cx: &mut App) -> String {
14276 self.display_map
14277 .update(cx, |map, cx| map.snapshot(cx))
14278 .text()
14279 }
14280
14281 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14282 let mut wrap_guides = smallvec::smallvec![];
14283
14284 if self.show_wrap_guides == Some(false) {
14285 return wrap_guides;
14286 }
14287
14288 let settings = self.buffer.read(cx).language_settings(cx);
14289 if settings.show_wrap_guides {
14290 match self.soft_wrap_mode(cx) {
14291 SoftWrap::Column(soft_wrap) => {
14292 wrap_guides.push((soft_wrap as usize, true));
14293 }
14294 SoftWrap::Bounded(soft_wrap) => {
14295 wrap_guides.push((soft_wrap as usize, true));
14296 }
14297 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14298 }
14299 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14300 }
14301
14302 wrap_guides
14303 }
14304
14305 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14306 let settings = self.buffer.read(cx).language_settings(cx);
14307 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14308 match mode {
14309 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14310 SoftWrap::None
14311 }
14312 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14313 language_settings::SoftWrap::PreferredLineLength => {
14314 SoftWrap::Column(settings.preferred_line_length)
14315 }
14316 language_settings::SoftWrap::Bounded => {
14317 SoftWrap::Bounded(settings.preferred_line_length)
14318 }
14319 }
14320 }
14321
14322 pub fn set_soft_wrap_mode(
14323 &mut self,
14324 mode: language_settings::SoftWrap,
14325
14326 cx: &mut Context<Self>,
14327 ) {
14328 self.soft_wrap_mode_override = Some(mode);
14329 cx.notify();
14330 }
14331
14332 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14333 self.hard_wrap = hard_wrap;
14334 cx.notify();
14335 }
14336
14337 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14338 self.text_style_refinement = Some(style);
14339 }
14340
14341 /// called by the Element so we know what style we were most recently rendered with.
14342 pub(crate) fn set_style(
14343 &mut self,
14344 style: EditorStyle,
14345 window: &mut Window,
14346 cx: &mut Context<Self>,
14347 ) {
14348 let rem_size = window.rem_size();
14349 self.display_map.update(cx, |map, cx| {
14350 map.set_font(
14351 style.text.font(),
14352 style.text.font_size.to_pixels(rem_size),
14353 cx,
14354 )
14355 });
14356 self.style = Some(style);
14357 }
14358
14359 pub fn style(&self) -> Option<&EditorStyle> {
14360 self.style.as_ref()
14361 }
14362
14363 // Called by the element. This method is not designed to be called outside of the editor
14364 // element's layout code because it does not notify when rewrapping is computed synchronously.
14365 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14366 self.display_map
14367 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14368 }
14369
14370 pub fn set_soft_wrap(&mut self) {
14371 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14372 }
14373
14374 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14375 if self.soft_wrap_mode_override.is_some() {
14376 self.soft_wrap_mode_override.take();
14377 } else {
14378 let soft_wrap = match self.soft_wrap_mode(cx) {
14379 SoftWrap::GitDiff => return,
14380 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14381 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14382 language_settings::SoftWrap::None
14383 }
14384 };
14385 self.soft_wrap_mode_override = Some(soft_wrap);
14386 }
14387 cx.notify();
14388 }
14389
14390 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14391 let Some(workspace) = self.workspace() else {
14392 return;
14393 };
14394 let fs = workspace.read(cx).app_state().fs.clone();
14395 let current_show = TabBarSettings::get_global(cx).show;
14396 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14397 setting.show = Some(!current_show);
14398 });
14399 }
14400
14401 pub fn toggle_indent_guides(
14402 &mut self,
14403 _: &ToggleIndentGuides,
14404 _: &mut Window,
14405 cx: &mut Context<Self>,
14406 ) {
14407 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14408 self.buffer
14409 .read(cx)
14410 .language_settings(cx)
14411 .indent_guides
14412 .enabled
14413 });
14414 self.show_indent_guides = Some(!currently_enabled);
14415 cx.notify();
14416 }
14417
14418 fn should_show_indent_guides(&self) -> Option<bool> {
14419 self.show_indent_guides
14420 }
14421
14422 pub fn toggle_line_numbers(
14423 &mut self,
14424 _: &ToggleLineNumbers,
14425 _: &mut Window,
14426 cx: &mut Context<Self>,
14427 ) {
14428 let mut editor_settings = EditorSettings::get_global(cx).clone();
14429 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14430 EditorSettings::override_global(editor_settings, cx);
14431 }
14432
14433 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
14434 if let Some(show_line_numbers) = self.show_line_numbers {
14435 return show_line_numbers;
14436 }
14437 EditorSettings::get_global(cx).gutter.line_numbers
14438 }
14439
14440 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14441 self.use_relative_line_numbers
14442 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14443 }
14444
14445 pub fn toggle_relative_line_numbers(
14446 &mut self,
14447 _: &ToggleRelativeLineNumbers,
14448 _: &mut Window,
14449 cx: &mut Context<Self>,
14450 ) {
14451 let is_relative = self.should_use_relative_line_numbers(cx);
14452 self.set_relative_line_number(Some(!is_relative), cx)
14453 }
14454
14455 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14456 self.use_relative_line_numbers = is_relative;
14457 cx.notify();
14458 }
14459
14460 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14461 self.show_gutter = show_gutter;
14462 cx.notify();
14463 }
14464
14465 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14466 self.show_scrollbars = show_scrollbars;
14467 cx.notify();
14468 }
14469
14470 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14471 self.show_line_numbers = Some(show_line_numbers);
14472 cx.notify();
14473 }
14474
14475 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14476 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14477 cx.notify();
14478 }
14479
14480 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14481 self.show_code_actions = Some(show_code_actions);
14482 cx.notify();
14483 }
14484
14485 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14486 self.show_runnables = Some(show_runnables);
14487 cx.notify();
14488 }
14489
14490 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14491 if self.display_map.read(cx).masked != masked {
14492 self.display_map.update(cx, |map, _| map.masked = masked);
14493 }
14494 cx.notify()
14495 }
14496
14497 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14498 self.show_wrap_guides = Some(show_wrap_guides);
14499 cx.notify();
14500 }
14501
14502 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14503 self.show_indent_guides = Some(show_indent_guides);
14504 cx.notify();
14505 }
14506
14507 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14508 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14509 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14510 if let Some(dir) = file.abs_path(cx).parent() {
14511 return Some(dir.to_owned());
14512 }
14513 }
14514
14515 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14516 return Some(project_path.path.to_path_buf());
14517 }
14518 }
14519
14520 None
14521 }
14522
14523 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14524 self.active_excerpt(cx)?
14525 .1
14526 .read(cx)
14527 .file()
14528 .and_then(|f| f.as_local())
14529 }
14530
14531 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14532 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14533 let buffer = buffer.read(cx);
14534 if let Some(project_path) = buffer.project_path(cx) {
14535 let project = self.project.as_ref()?.read(cx);
14536 project.absolute_path(&project_path, cx)
14537 } else {
14538 buffer
14539 .file()
14540 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14541 }
14542 })
14543 }
14544
14545 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14546 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14547 let project_path = buffer.read(cx).project_path(cx)?;
14548 let project = self.project.as_ref()?.read(cx);
14549 let entry = project.entry_for_path(&project_path, cx)?;
14550 let path = entry.path.to_path_buf();
14551 Some(path)
14552 })
14553 }
14554
14555 pub fn reveal_in_finder(
14556 &mut self,
14557 _: &RevealInFileManager,
14558 _window: &mut Window,
14559 cx: &mut Context<Self>,
14560 ) {
14561 if let Some(target) = self.target_file(cx) {
14562 cx.reveal_path(&target.abs_path(cx));
14563 }
14564 }
14565
14566 pub fn copy_path(
14567 &mut self,
14568 _: &zed_actions::workspace::CopyPath,
14569 _window: &mut Window,
14570 cx: &mut Context<Self>,
14571 ) {
14572 if let Some(path) = self.target_file_abs_path(cx) {
14573 if let Some(path) = path.to_str() {
14574 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14575 }
14576 }
14577 }
14578
14579 pub fn copy_relative_path(
14580 &mut self,
14581 _: &zed_actions::workspace::CopyRelativePath,
14582 _window: &mut Window,
14583 cx: &mut Context<Self>,
14584 ) {
14585 if let Some(path) = self.target_file_path(cx) {
14586 if let Some(path) = path.to_str() {
14587 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14588 }
14589 }
14590 }
14591
14592 pub fn copy_file_name_without_extension(
14593 &mut self,
14594 _: &CopyFileNameWithoutExtension,
14595 _: &mut Window,
14596 cx: &mut Context<Self>,
14597 ) {
14598 if let Some(file) = self.target_file(cx) {
14599 if let Some(file_stem) = file.path().file_stem() {
14600 if let Some(name) = file_stem.to_str() {
14601 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14602 }
14603 }
14604 }
14605 }
14606
14607 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14608 if let Some(file) = self.target_file(cx) {
14609 if let Some(file_name) = file.path().file_name() {
14610 if let Some(name) = file_name.to_str() {
14611 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14612 }
14613 }
14614 }
14615 }
14616
14617 pub fn toggle_git_blame(
14618 &mut self,
14619 _: &::git::Blame,
14620 window: &mut Window,
14621 cx: &mut Context<Self>,
14622 ) {
14623 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14624
14625 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14626 self.start_git_blame(true, window, cx);
14627 }
14628
14629 cx.notify();
14630 }
14631
14632 pub fn toggle_git_blame_inline(
14633 &mut self,
14634 _: &ToggleGitBlameInline,
14635 window: &mut Window,
14636 cx: &mut Context<Self>,
14637 ) {
14638 self.toggle_git_blame_inline_internal(true, window, cx);
14639 cx.notify();
14640 }
14641
14642 pub fn git_blame_inline_enabled(&self) -> bool {
14643 self.git_blame_inline_enabled
14644 }
14645
14646 pub fn toggle_selection_menu(
14647 &mut self,
14648 _: &ToggleSelectionMenu,
14649 _: &mut Window,
14650 cx: &mut Context<Self>,
14651 ) {
14652 self.show_selection_menu = self
14653 .show_selection_menu
14654 .map(|show_selections_menu| !show_selections_menu)
14655 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14656
14657 cx.notify();
14658 }
14659
14660 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14661 self.show_selection_menu
14662 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14663 }
14664
14665 fn start_git_blame(
14666 &mut self,
14667 user_triggered: bool,
14668 window: &mut Window,
14669 cx: &mut Context<Self>,
14670 ) {
14671 if let Some(project) = self.project.as_ref() {
14672 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14673 return;
14674 };
14675
14676 if buffer.read(cx).file().is_none() {
14677 return;
14678 }
14679
14680 let focused = self.focus_handle(cx).contains_focused(window, cx);
14681
14682 let project = project.clone();
14683 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14684 self.blame_subscription =
14685 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14686 self.blame = Some(blame);
14687 }
14688 }
14689
14690 fn toggle_git_blame_inline_internal(
14691 &mut self,
14692 user_triggered: bool,
14693 window: &mut Window,
14694 cx: &mut Context<Self>,
14695 ) {
14696 if self.git_blame_inline_enabled {
14697 self.git_blame_inline_enabled = false;
14698 self.show_git_blame_inline = false;
14699 self.show_git_blame_inline_delay_task.take();
14700 } else {
14701 self.git_blame_inline_enabled = true;
14702 self.start_git_blame_inline(user_triggered, window, cx);
14703 }
14704
14705 cx.notify();
14706 }
14707
14708 fn start_git_blame_inline(
14709 &mut self,
14710 user_triggered: bool,
14711 window: &mut Window,
14712 cx: &mut Context<Self>,
14713 ) {
14714 self.start_git_blame(user_triggered, window, cx);
14715
14716 if ProjectSettings::get_global(cx)
14717 .git
14718 .inline_blame_delay()
14719 .is_some()
14720 {
14721 self.start_inline_blame_timer(window, cx);
14722 } else {
14723 self.show_git_blame_inline = true
14724 }
14725 }
14726
14727 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14728 self.blame.as_ref()
14729 }
14730
14731 pub fn show_git_blame_gutter(&self) -> bool {
14732 self.show_git_blame_gutter
14733 }
14734
14735 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14736 self.show_git_blame_gutter && self.has_blame_entries(cx)
14737 }
14738
14739 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14740 self.show_git_blame_inline
14741 && (self.focus_handle.is_focused(window)
14742 || self
14743 .git_blame_inline_tooltip
14744 .as_ref()
14745 .and_then(|t| t.upgrade())
14746 .is_some())
14747 && !self.newest_selection_head_on_empty_line(cx)
14748 && self.has_blame_entries(cx)
14749 }
14750
14751 fn has_blame_entries(&self, cx: &App) -> bool {
14752 self.blame()
14753 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14754 }
14755
14756 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14757 let cursor_anchor = self.selections.newest_anchor().head();
14758
14759 let snapshot = self.buffer.read(cx).snapshot(cx);
14760 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14761
14762 snapshot.line_len(buffer_row) == 0
14763 }
14764
14765 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14766 let buffer_and_selection = maybe!({
14767 let selection = self.selections.newest::<Point>(cx);
14768 let selection_range = selection.range();
14769
14770 let multi_buffer = self.buffer().read(cx);
14771 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14772 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14773
14774 let (buffer, range, _) = if selection.reversed {
14775 buffer_ranges.first()
14776 } else {
14777 buffer_ranges.last()
14778 }?;
14779
14780 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14781 ..text::ToPoint::to_point(&range.end, &buffer).row;
14782 Some((
14783 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14784 selection,
14785 ))
14786 });
14787
14788 let Some((buffer, selection)) = buffer_and_selection else {
14789 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14790 };
14791
14792 let Some(project) = self.project.as_ref() else {
14793 return Task::ready(Err(anyhow!("editor does not have project")));
14794 };
14795
14796 project.update(cx, |project, cx| {
14797 project.get_permalink_to_line(&buffer, selection, cx)
14798 })
14799 }
14800
14801 pub fn copy_permalink_to_line(
14802 &mut self,
14803 _: &CopyPermalinkToLine,
14804 window: &mut Window,
14805 cx: &mut Context<Self>,
14806 ) {
14807 let permalink_task = self.get_permalink_to_line(cx);
14808 let workspace = self.workspace();
14809
14810 cx.spawn_in(window, |_, mut cx| async move {
14811 match permalink_task.await {
14812 Ok(permalink) => {
14813 cx.update(|_, cx| {
14814 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14815 })
14816 .ok();
14817 }
14818 Err(err) => {
14819 let message = format!("Failed to copy permalink: {err}");
14820
14821 Err::<(), anyhow::Error>(err).log_err();
14822
14823 if let Some(workspace) = workspace {
14824 workspace
14825 .update_in(&mut cx, |workspace, _, cx| {
14826 struct CopyPermalinkToLine;
14827
14828 workspace.show_toast(
14829 Toast::new(
14830 NotificationId::unique::<CopyPermalinkToLine>(),
14831 message,
14832 ),
14833 cx,
14834 )
14835 })
14836 .ok();
14837 }
14838 }
14839 }
14840 })
14841 .detach();
14842 }
14843
14844 pub fn copy_file_location(
14845 &mut self,
14846 _: &CopyFileLocation,
14847 _: &mut Window,
14848 cx: &mut Context<Self>,
14849 ) {
14850 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14851 if let Some(file) = self.target_file(cx) {
14852 if let Some(path) = file.path().to_str() {
14853 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14854 }
14855 }
14856 }
14857
14858 pub fn open_permalink_to_line(
14859 &mut self,
14860 _: &OpenPermalinkToLine,
14861 window: &mut Window,
14862 cx: &mut Context<Self>,
14863 ) {
14864 let permalink_task = self.get_permalink_to_line(cx);
14865 let workspace = self.workspace();
14866
14867 cx.spawn_in(window, |_, mut cx| async move {
14868 match permalink_task.await {
14869 Ok(permalink) => {
14870 cx.update(|_, cx| {
14871 cx.open_url(permalink.as_ref());
14872 })
14873 .ok();
14874 }
14875 Err(err) => {
14876 let message = format!("Failed to open permalink: {err}");
14877
14878 Err::<(), anyhow::Error>(err).log_err();
14879
14880 if let Some(workspace) = workspace {
14881 workspace
14882 .update(&mut cx, |workspace, cx| {
14883 struct OpenPermalinkToLine;
14884
14885 workspace.show_toast(
14886 Toast::new(
14887 NotificationId::unique::<OpenPermalinkToLine>(),
14888 message,
14889 ),
14890 cx,
14891 )
14892 })
14893 .ok();
14894 }
14895 }
14896 }
14897 })
14898 .detach();
14899 }
14900
14901 pub fn insert_uuid_v4(
14902 &mut self,
14903 _: &InsertUuidV4,
14904 window: &mut Window,
14905 cx: &mut Context<Self>,
14906 ) {
14907 self.insert_uuid(UuidVersion::V4, window, cx);
14908 }
14909
14910 pub fn insert_uuid_v7(
14911 &mut self,
14912 _: &InsertUuidV7,
14913 window: &mut Window,
14914 cx: &mut Context<Self>,
14915 ) {
14916 self.insert_uuid(UuidVersion::V7, window, cx);
14917 }
14918
14919 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14920 self.transact(window, cx, |this, window, cx| {
14921 let edits = this
14922 .selections
14923 .all::<Point>(cx)
14924 .into_iter()
14925 .map(|selection| {
14926 let uuid = match version {
14927 UuidVersion::V4 => uuid::Uuid::new_v4(),
14928 UuidVersion::V7 => uuid::Uuid::now_v7(),
14929 };
14930
14931 (selection.range(), uuid.to_string())
14932 });
14933 this.edit(edits, cx);
14934 this.refresh_inline_completion(true, false, window, cx);
14935 });
14936 }
14937
14938 pub fn open_selections_in_multibuffer(
14939 &mut self,
14940 _: &OpenSelectionsInMultibuffer,
14941 window: &mut Window,
14942 cx: &mut Context<Self>,
14943 ) {
14944 let multibuffer = self.buffer.read(cx);
14945
14946 let Some(buffer) = multibuffer.as_singleton() else {
14947 return;
14948 };
14949
14950 let Some(workspace) = self.workspace() else {
14951 return;
14952 };
14953
14954 let locations = self
14955 .selections
14956 .disjoint_anchors()
14957 .iter()
14958 .map(|range| Location {
14959 buffer: buffer.clone(),
14960 range: range.start.text_anchor..range.end.text_anchor,
14961 })
14962 .collect::<Vec<_>>();
14963
14964 let title = multibuffer.title(cx).to_string();
14965
14966 cx.spawn_in(window, |_, mut cx| async move {
14967 workspace.update_in(&mut cx, |workspace, window, cx| {
14968 Self::open_locations_in_multibuffer(
14969 workspace,
14970 locations,
14971 format!("Selections for '{title}'"),
14972 false,
14973 MultibufferSelectionMode::All,
14974 window,
14975 cx,
14976 );
14977 })
14978 })
14979 .detach();
14980 }
14981
14982 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14983 /// last highlight added will be used.
14984 ///
14985 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14986 pub fn highlight_rows<T: 'static>(
14987 &mut self,
14988 range: Range<Anchor>,
14989 color: Hsla,
14990 should_autoscroll: bool,
14991 cx: &mut Context<Self>,
14992 ) {
14993 let snapshot = self.buffer().read(cx).snapshot(cx);
14994 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14995 let ix = row_highlights.binary_search_by(|highlight| {
14996 Ordering::Equal
14997 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14998 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14999 });
15000
15001 if let Err(mut ix) = ix {
15002 let index = post_inc(&mut self.highlight_order);
15003
15004 // If this range intersects with the preceding highlight, then merge it with
15005 // the preceding highlight. Otherwise insert a new highlight.
15006 let mut merged = false;
15007 if ix > 0 {
15008 let prev_highlight = &mut row_highlights[ix - 1];
15009 if prev_highlight
15010 .range
15011 .end
15012 .cmp(&range.start, &snapshot)
15013 .is_ge()
15014 {
15015 ix -= 1;
15016 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15017 prev_highlight.range.end = range.end;
15018 }
15019 merged = true;
15020 prev_highlight.index = index;
15021 prev_highlight.color = color;
15022 prev_highlight.should_autoscroll = should_autoscroll;
15023 }
15024 }
15025
15026 if !merged {
15027 row_highlights.insert(
15028 ix,
15029 RowHighlight {
15030 range: range.clone(),
15031 index,
15032 color,
15033 should_autoscroll,
15034 },
15035 );
15036 }
15037
15038 // If any of the following highlights intersect with this one, merge them.
15039 while let Some(next_highlight) = row_highlights.get(ix + 1) {
15040 let highlight = &row_highlights[ix];
15041 if next_highlight
15042 .range
15043 .start
15044 .cmp(&highlight.range.end, &snapshot)
15045 .is_le()
15046 {
15047 if next_highlight
15048 .range
15049 .end
15050 .cmp(&highlight.range.end, &snapshot)
15051 .is_gt()
15052 {
15053 row_highlights[ix].range.end = next_highlight.range.end;
15054 }
15055 row_highlights.remove(ix + 1);
15056 } else {
15057 break;
15058 }
15059 }
15060 }
15061 }
15062
15063 /// Remove any highlighted row ranges of the given type that intersect the
15064 /// given ranges.
15065 pub fn remove_highlighted_rows<T: 'static>(
15066 &mut self,
15067 ranges_to_remove: Vec<Range<Anchor>>,
15068 cx: &mut Context<Self>,
15069 ) {
15070 let snapshot = self.buffer().read(cx).snapshot(cx);
15071 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15072 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15073 row_highlights.retain(|highlight| {
15074 while let Some(range_to_remove) = ranges_to_remove.peek() {
15075 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15076 Ordering::Less | Ordering::Equal => {
15077 ranges_to_remove.next();
15078 }
15079 Ordering::Greater => {
15080 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15081 Ordering::Less | Ordering::Equal => {
15082 return false;
15083 }
15084 Ordering::Greater => break,
15085 }
15086 }
15087 }
15088 }
15089
15090 true
15091 })
15092 }
15093
15094 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15095 pub fn clear_row_highlights<T: 'static>(&mut self) {
15096 self.highlighted_rows.remove(&TypeId::of::<T>());
15097 }
15098
15099 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15100 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15101 self.highlighted_rows
15102 .get(&TypeId::of::<T>())
15103 .map_or(&[] as &[_], |vec| vec.as_slice())
15104 .iter()
15105 .map(|highlight| (highlight.range.clone(), highlight.color))
15106 }
15107
15108 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15109 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15110 /// Allows to ignore certain kinds of highlights.
15111 pub fn highlighted_display_rows(
15112 &self,
15113 window: &mut Window,
15114 cx: &mut App,
15115 ) -> BTreeMap<DisplayRow, LineHighlight> {
15116 let snapshot = self.snapshot(window, cx);
15117 let mut used_highlight_orders = HashMap::default();
15118 self.highlighted_rows
15119 .iter()
15120 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15121 .fold(
15122 BTreeMap::<DisplayRow, LineHighlight>::new(),
15123 |mut unique_rows, highlight| {
15124 let start = highlight.range.start.to_display_point(&snapshot);
15125 let end = highlight.range.end.to_display_point(&snapshot);
15126 let start_row = start.row().0;
15127 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15128 && end.column() == 0
15129 {
15130 end.row().0.saturating_sub(1)
15131 } else {
15132 end.row().0
15133 };
15134 for row in start_row..=end_row {
15135 let used_index =
15136 used_highlight_orders.entry(row).or_insert(highlight.index);
15137 if highlight.index >= *used_index {
15138 *used_index = highlight.index;
15139 unique_rows.insert(DisplayRow(row), highlight.color.into());
15140 }
15141 }
15142 unique_rows
15143 },
15144 )
15145 }
15146
15147 pub fn highlighted_display_row_for_autoscroll(
15148 &self,
15149 snapshot: &DisplaySnapshot,
15150 ) -> Option<DisplayRow> {
15151 self.highlighted_rows
15152 .values()
15153 .flat_map(|highlighted_rows| highlighted_rows.iter())
15154 .filter_map(|highlight| {
15155 if highlight.should_autoscroll {
15156 Some(highlight.range.start.to_display_point(snapshot).row())
15157 } else {
15158 None
15159 }
15160 })
15161 .min()
15162 }
15163
15164 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15165 self.highlight_background::<SearchWithinRange>(
15166 ranges,
15167 |colors| colors.editor_document_highlight_read_background,
15168 cx,
15169 )
15170 }
15171
15172 pub fn set_breadcrumb_header(&mut self, new_header: String) {
15173 self.breadcrumb_header = Some(new_header);
15174 }
15175
15176 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15177 self.clear_background_highlights::<SearchWithinRange>(cx);
15178 }
15179
15180 pub fn highlight_background<T: 'static>(
15181 &mut self,
15182 ranges: &[Range<Anchor>],
15183 color_fetcher: fn(&ThemeColors) -> Hsla,
15184 cx: &mut Context<Self>,
15185 ) {
15186 self.background_highlights
15187 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15188 self.scrollbar_marker_state.dirty = true;
15189 cx.notify();
15190 }
15191
15192 pub fn clear_background_highlights<T: 'static>(
15193 &mut self,
15194 cx: &mut Context<Self>,
15195 ) -> Option<BackgroundHighlight> {
15196 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15197 if !text_highlights.1.is_empty() {
15198 self.scrollbar_marker_state.dirty = true;
15199 cx.notify();
15200 }
15201 Some(text_highlights)
15202 }
15203
15204 pub fn highlight_gutter<T: 'static>(
15205 &mut self,
15206 ranges: &[Range<Anchor>],
15207 color_fetcher: fn(&App) -> Hsla,
15208 cx: &mut Context<Self>,
15209 ) {
15210 self.gutter_highlights
15211 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15212 cx.notify();
15213 }
15214
15215 pub fn clear_gutter_highlights<T: 'static>(
15216 &mut self,
15217 cx: &mut Context<Self>,
15218 ) -> Option<GutterHighlight> {
15219 cx.notify();
15220 self.gutter_highlights.remove(&TypeId::of::<T>())
15221 }
15222
15223 #[cfg(feature = "test-support")]
15224 pub fn all_text_background_highlights(
15225 &self,
15226 window: &mut Window,
15227 cx: &mut Context<Self>,
15228 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15229 let snapshot = self.snapshot(window, cx);
15230 let buffer = &snapshot.buffer_snapshot;
15231 let start = buffer.anchor_before(0);
15232 let end = buffer.anchor_after(buffer.len());
15233 let theme = cx.theme().colors();
15234 self.background_highlights_in_range(start..end, &snapshot, theme)
15235 }
15236
15237 #[cfg(feature = "test-support")]
15238 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15239 let snapshot = self.buffer().read(cx).snapshot(cx);
15240
15241 let highlights = self
15242 .background_highlights
15243 .get(&TypeId::of::<items::BufferSearchHighlights>());
15244
15245 if let Some((_color, ranges)) = highlights {
15246 ranges
15247 .iter()
15248 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15249 .collect_vec()
15250 } else {
15251 vec![]
15252 }
15253 }
15254
15255 fn document_highlights_for_position<'a>(
15256 &'a self,
15257 position: Anchor,
15258 buffer: &'a MultiBufferSnapshot,
15259 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15260 let read_highlights = self
15261 .background_highlights
15262 .get(&TypeId::of::<DocumentHighlightRead>())
15263 .map(|h| &h.1);
15264 let write_highlights = self
15265 .background_highlights
15266 .get(&TypeId::of::<DocumentHighlightWrite>())
15267 .map(|h| &h.1);
15268 let left_position = position.bias_left(buffer);
15269 let right_position = position.bias_right(buffer);
15270 read_highlights
15271 .into_iter()
15272 .chain(write_highlights)
15273 .flat_map(move |ranges| {
15274 let start_ix = match ranges.binary_search_by(|probe| {
15275 let cmp = probe.end.cmp(&left_position, buffer);
15276 if cmp.is_ge() {
15277 Ordering::Greater
15278 } else {
15279 Ordering::Less
15280 }
15281 }) {
15282 Ok(i) | Err(i) => i,
15283 };
15284
15285 ranges[start_ix..]
15286 .iter()
15287 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15288 })
15289 }
15290
15291 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15292 self.background_highlights
15293 .get(&TypeId::of::<T>())
15294 .map_or(false, |(_, highlights)| !highlights.is_empty())
15295 }
15296
15297 pub fn background_highlights_in_range(
15298 &self,
15299 search_range: Range<Anchor>,
15300 display_snapshot: &DisplaySnapshot,
15301 theme: &ThemeColors,
15302 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15303 let mut results = Vec::new();
15304 for (color_fetcher, ranges) in self.background_highlights.values() {
15305 let color = color_fetcher(theme);
15306 let start_ix = match ranges.binary_search_by(|probe| {
15307 let cmp = probe
15308 .end
15309 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15310 if cmp.is_gt() {
15311 Ordering::Greater
15312 } else {
15313 Ordering::Less
15314 }
15315 }) {
15316 Ok(i) | Err(i) => i,
15317 };
15318 for range in &ranges[start_ix..] {
15319 if range
15320 .start
15321 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15322 .is_ge()
15323 {
15324 break;
15325 }
15326
15327 let start = range.start.to_display_point(display_snapshot);
15328 let end = range.end.to_display_point(display_snapshot);
15329 results.push((start..end, color))
15330 }
15331 }
15332 results
15333 }
15334
15335 pub fn background_highlight_row_ranges<T: 'static>(
15336 &self,
15337 search_range: Range<Anchor>,
15338 display_snapshot: &DisplaySnapshot,
15339 count: usize,
15340 ) -> Vec<RangeInclusive<DisplayPoint>> {
15341 let mut results = Vec::new();
15342 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15343 return vec![];
15344 };
15345
15346 let start_ix = match ranges.binary_search_by(|probe| {
15347 let cmp = probe
15348 .end
15349 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15350 if cmp.is_gt() {
15351 Ordering::Greater
15352 } else {
15353 Ordering::Less
15354 }
15355 }) {
15356 Ok(i) | Err(i) => i,
15357 };
15358 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15359 if let (Some(start_display), Some(end_display)) = (start, end) {
15360 results.push(
15361 start_display.to_display_point(display_snapshot)
15362 ..=end_display.to_display_point(display_snapshot),
15363 );
15364 }
15365 };
15366 let mut start_row: Option<Point> = None;
15367 let mut end_row: Option<Point> = None;
15368 if ranges.len() > count {
15369 return Vec::new();
15370 }
15371 for range in &ranges[start_ix..] {
15372 if range
15373 .start
15374 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15375 .is_ge()
15376 {
15377 break;
15378 }
15379 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15380 if let Some(current_row) = &end_row {
15381 if end.row == current_row.row {
15382 continue;
15383 }
15384 }
15385 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15386 if start_row.is_none() {
15387 assert_eq!(end_row, None);
15388 start_row = Some(start);
15389 end_row = Some(end);
15390 continue;
15391 }
15392 if let Some(current_end) = end_row.as_mut() {
15393 if start.row > current_end.row + 1 {
15394 push_region(start_row, end_row);
15395 start_row = Some(start);
15396 end_row = Some(end);
15397 } else {
15398 // Merge two hunks.
15399 *current_end = end;
15400 }
15401 } else {
15402 unreachable!();
15403 }
15404 }
15405 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15406 push_region(start_row, end_row);
15407 results
15408 }
15409
15410 pub fn gutter_highlights_in_range(
15411 &self,
15412 search_range: Range<Anchor>,
15413 display_snapshot: &DisplaySnapshot,
15414 cx: &App,
15415 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15416 let mut results = Vec::new();
15417 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15418 let color = color_fetcher(cx);
15419 let start_ix = match ranges.binary_search_by(|probe| {
15420 let cmp = probe
15421 .end
15422 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15423 if cmp.is_gt() {
15424 Ordering::Greater
15425 } else {
15426 Ordering::Less
15427 }
15428 }) {
15429 Ok(i) | Err(i) => i,
15430 };
15431 for range in &ranges[start_ix..] {
15432 if range
15433 .start
15434 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15435 .is_ge()
15436 {
15437 break;
15438 }
15439
15440 let start = range.start.to_display_point(display_snapshot);
15441 let end = range.end.to_display_point(display_snapshot);
15442 results.push((start..end, color))
15443 }
15444 }
15445 results
15446 }
15447
15448 /// Get the text ranges corresponding to the redaction query
15449 pub fn redacted_ranges(
15450 &self,
15451 search_range: Range<Anchor>,
15452 display_snapshot: &DisplaySnapshot,
15453 cx: &App,
15454 ) -> Vec<Range<DisplayPoint>> {
15455 display_snapshot
15456 .buffer_snapshot
15457 .redacted_ranges(search_range, |file| {
15458 if let Some(file) = file {
15459 file.is_private()
15460 && EditorSettings::get(
15461 Some(SettingsLocation {
15462 worktree_id: file.worktree_id(cx),
15463 path: file.path().as_ref(),
15464 }),
15465 cx,
15466 )
15467 .redact_private_values
15468 } else {
15469 false
15470 }
15471 })
15472 .map(|range| {
15473 range.start.to_display_point(display_snapshot)
15474 ..range.end.to_display_point(display_snapshot)
15475 })
15476 .collect()
15477 }
15478
15479 pub fn highlight_text<T: 'static>(
15480 &mut self,
15481 ranges: Vec<Range<Anchor>>,
15482 style: HighlightStyle,
15483 cx: &mut Context<Self>,
15484 ) {
15485 self.display_map.update(cx, |map, _| {
15486 map.highlight_text(TypeId::of::<T>(), ranges, style)
15487 });
15488 cx.notify();
15489 }
15490
15491 pub(crate) fn highlight_inlays<T: 'static>(
15492 &mut self,
15493 highlights: Vec<InlayHighlight>,
15494 style: HighlightStyle,
15495 cx: &mut Context<Self>,
15496 ) {
15497 self.display_map.update(cx, |map, _| {
15498 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15499 });
15500 cx.notify();
15501 }
15502
15503 pub fn text_highlights<'a, T: 'static>(
15504 &'a self,
15505 cx: &'a App,
15506 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15507 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15508 }
15509
15510 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15511 let cleared = self
15512 .display_map
15513 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15514 if cleared {
15515 cx.notify();
15516 }
15517 }
15518
15519 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15520 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15521 && self.focus_handle.is_focused(window)
15522 }
15523
15524 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15525 self.show_cursor_when_unfocused = is_enabled;
15526 cx.notify();
15527 }
15528
15529 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15530 cx.notify();
15531 }
15532
15533 fn on_buffer_event(
15534 &mut self,
15535 multibuffer: &Entity<MultiBuffer>,
15536 event: &multi_buffer::Event,
15537 window: &mut Window,
15538 cx: &mut Context<Self>,
15539 ) {
15540 match event {
15541 multi_buffer::Event::Edited {
15542 singleton_buffer_edited,
15543 edited_buffer: buffer_edited,
15544 } => {
15545 self.scrollbar_marker_state.dirty = true;
15546 self.active_indent_guides_state.dirty = true;
15547 self.refresh_active_diagnostics(cx);
15548 self.refresh_code_actions(window, cx);
15549 if self.has_active_inline_completion() {
15550 self.update_visible_inline_completion(window, cx);
15551 }
15552 if let Some(buffer) = buffer_edited {
15553 let buffer_id = buffer.read(cx).remote_id();
15554 if !self.registered_buffers.contains_key(&buffer_id) {
15555 if let Some(project) = self.project.as_ref() {
15556 project.update(cx, |project, cx| {
15557 self.registered_buffers.insert(
15558 buffer_id,
15559 project.register_buffer_with_language_servers(&buffer, cx),
15560 );
15561 })
15562 }
15563 }
15564 }
15565 cx.emit(EditorEvent::BufferEdited);
15566 cx.emit(SearchEvent::MatchesInvalidated);
15567 if *singleton_buffer_edited {
15568 if let Some(project) = &self.project {
15569 #[allow(clippy::mutable_key_type)]
15570 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15571 multibuffer
15572 .all_buffers()
15573 .into_iter()
15574 .filter_map(|buffer| {
15575 buffer.update(cx, |buffer, cx| {
15576 let language = buffer.language()?;
15577 let should_discard = project.update(cx, |project, cx| {
15578 project.is_local()
15579 && !project.has_language_servers_for(buffer, cx)
15580 });
15581 should_discard.not().then_some(language.clone())
15582 })
15583 })
15584 .collect::<HashSet<_>>()
15585 });
15586 if !languages_affected.is_empty() {
15587 self.refresh_inlay_hints(
15588 InlayHintRefreshReason::BufferEdited(languages_affected),
15589 cx,
15590 );
15591 }
15592 }
15593 }
15594
15595 let Some(project) = &self.project else { return };
15596 let (telemetry, is_via_ssh) = {
15597 let project = project.read(cx);
15598 let telemetry = project.client().telemetry().clone();
15599 let is_via_ssh = project.is_via_ssh();
15600 (telemetry, is_via_ssh)
15601 };
15602 refresh_linked_ranges(self, window, cx);
15603 telemetry.log_edit_event("editor", is_via_ssh);
15604 }
15605 multi_buffer::Event::ExcerptsAdded {
15606 buffer,
15607 predecessor,
15608 excerpts,
15609 } => {
15610 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15611 let buffer_id = buffer.read(cx).remote_id();
15612 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15613 if let Some(project) = &self.project {
15614 get_uncommitted_diff_for_buffer(
15615 project,
15616 [buffer.clone()],
15617 self.buffer.clone(),
15618 cx,
15619 )
15620 .detach();
15621 }
15622 }
15623 cx.emit(EditorEvent::ExcerptsAdded {
15624 buffer: buffer.clone(),
15625 predecessor: *predecessor,
15626 excerpts: excerpts.clone(),
15627 });
15628 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15629 }
15630 multi_buffer::Event::ExcerptsRemoved { ids } => {
15631 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15632 let buffer = self.buffer.read(cx);
15633 self.registered_buffers
15634 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15635 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15636 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15637 }
15638 multi_buffer::Event::ExcerptsEdited {
15639 excerpt_ids,
15640 buffer_ids,
15641 } => {
15642 self.display_map.update(cx, |map, cx| {
15643 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15644 });
15645 cx.emit(EditorEvent::ExcerptsEdited {
15646 ids: excerpt_ids.clone(),
15647 })
15648 }
15649 multi_buffer::Event::ExcerptsExpanded { ids } => {
15650 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15651 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15652 }
15653 multi_buffer::Event::Reparsed(buffer_id) => {
15654 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15655 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15656
15657 cx.emit(EditorEvent::Reparsed(*buffer_id));
15658 }
15659 multi_buffer::Event::DiffHunksToggled => {
15660 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15661 }
15662 multi_buffer::Event::LanguageChanged(buffer_id) => {
15663 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15664 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15665 cx.emit(EditorEvent::Reparsed(*buffer_id));
15666 cx.notify();
15667 }
15668 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15669 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15670 multi_buffer::Event::FileHandleChanged
15671 | multi_buffer::Event::Reloaded
15672 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15673 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15674 multi_buffer::Event::DiagnosticsUpdated => {
15675 self.refresh_active_diagnostics(cx);
15676 self.refresh_inline_diagnostics(true, window, cx);
15677 self.scrollbar_marker_state.dirty = true;
15678 cx.notify();
15679 }
15680 _ => {}
15681 };
15682 }
15683
15684 fn on_display_map_changed(
15685 &mut self,
15686 _: Entity<DisplayMap>,
15687 _: &mut Window,
15688 cx: &mut Context<Self>,
15689 ) {
15690 cx.notify();
15691 }
15692
15693 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15694 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15695 self.update_edit_prediction_settings(cx);
15696 self.refresh_inline_completion(true, false, window, cx);
15697 self.refresh_inlay_hints(
15698 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15699 self.selections.newest_anchor().head(),
15700 &self.buffer.read(cx).snapshot(cx),
15701 cx,
15702 )),
15703 cx,
15704 );
15705
15706 let old_cursor_shape = self.cursor_shape;
15707
15708 {
15709 let editor_settings = EditorSettings::get_global(cx);
15710 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15711 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15712 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15713 }
15714
15715 if old_cursor_shape != self.cursor_shape {
15716 cx.emit(EditorEvent::CursorShapeChanged);
15717 }
15718
15719 let project_settings = ProjectSettings::get_global(cx);
15720 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15721
15722 if self.mode == EditorMode::Full {
15723 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15724 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15725 if self.show_inline_diagnostics != show_inline_diagnostics {
15726 self.show_inline_diagnostics = show_inline_diagnostics;
15727 self.refresh_inline_diagnostics(false, window, cx);
15728 }
15729
15730 if self.git_blame_inline_enabled != inline_blame_enabled {
15731 self.toggle_git_blame_inline_internal(false, window, cx);
15732 }
15733 }
15734
15735 cx.notify();
15736 }
15737
15738 pub fn set_searchable(&mut self, searchable: bool) {
15739 self.searchable = searchable;
15740 }
15741
15742 pub fn searchable(&self) -> bool {
15743 self.searchable
15744 }
15745
15746 fn open_proposed_changes_editor(
15747 &mut self,
15748 _: &OpenProposedChangesEditor,
15749 window: &mut Window,
15750 cx: &mut Context<Self>,
15751 ) {
15752 let Some(workspace) = self.workspace() else {
15753 cx.propagate();
15754 return;
15755 };
15756
15757 let selections = self.selections.all::<usize>(cx);
15758 let multi_buffer = self.buffer.read(cx);
15759 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15760 let mut new_selections_by_buffer = HashMap::default();
15761 for selection in selections {
15762 for (buffer, range, _) in
15763 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15764 {
15765 let mut range = range.to_point(buffer);
15766 range.start.column = 0;
15767 range.end.column = buffer.line_len(range.end.row);
15768 new_selections_by_buffer
15769 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15770 .or_insert(Vec::new())
15771 .push(range)
15772 }
15773 }
15774
15775 let proposed_changes_buffers = new_selections_by_buffer
15776 .into_iter()
15777 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15778 .collect::<Vec<_>>();
15779 let proposed_changes_editor = cx.new(|cx| {
15780 ProposedChangesEditor::new(
15781 "Proposed changes",
15782 proposed_changes_buffers,
15783 self.project.clone(),
15784 window,
15785 cx,
15786 )
15787 });
15788
15789 window.defer(cx, move |window, cx| {
15790 workspace.update(cx, |workspace, cx| {
15791 workspace.active_pane().update(cx, |pane, cx| {
15792 pane.add_item(
15793 Box::new(proposed_changes_editor),
15794 true,
15795 true,
15796 None,
15797 window,
15798 cx,
15799 );
15800 });
15801 });
15802 });
15803 }
15804
15805 pub fn open_excerpts_in_split(
15806 &mut self,
15807 _: &OpenExcerptsSplit,
15808 window: &mut Window,
15809 cx: &mut Context<Self>,
15810 ) {
15811 self.open_excerpts_common(None, true, window, cx)
15812 }
15813
15814 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15815 self.open_excerpts_common(None, false, window, cx)
15816 }
15817
15818 fn open_excerpts_common(
15819 &mut self,
15820 jump_data: Option<JumpData>,
15821 split: bool,
15822 window: &mut Window,
15823 cx: &mut Context<Self>,
15824 ) {
15825 let Some(workspace) = self.workspace() else {
15826 cx.propagate();
15827 return;
15828 };
15829
15830 if self.buffer.read(cx).is_singleton() {
15831 cx.propagate();
15832 return;
15833 }
15834
15835 let mut new_selections_by_buffer = HashMap::default();
15836 match &jump_data {
15837 Some(JumpData::MultiBufferPoint {
15838 excerpt_id,
15839 position,
15840 anchor,
15841 line_offset_from_top,
15842 }) => {
15843 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15844 if let Some(buffer) = multi_buffer_snapshot
15845 .buffer_id_for_excerpt(*excerpt_id)
15846 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15847 {
15848 let buffer_snapshot = buffer.read(cx).snapshot();
15849 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15850 language::ToPoint::to_point(anchor, &buffer_snapshot)
15851 } else {
15852 buffer_snapshot.clip_point(*position, Bias::Left)
15853 };
15854 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15855 new_selections_by_buffer.insert(
15856 buffer,
15857 (
15858 vec![jump_to_offset..jump_to_offset],
15859 Some(*line_offset_from_top),
15860 ),
15861 );
15862 }
15863 }
15864 Some(JumpData::MultiBufferRow {
15865 row,
15866 line_offset_from_top,
15867 }) => {
15868 let point = MultiBufferPoint::new(row.0, 0);
15869 if let Some((buffer, buffer_point, _)) =
15870 self.buffer.read(cx).point_to_buffer_point(point, cx)
15871 {
15872 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15873 new_selections_by_buffer
15874 .entry(buffer)
15875 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15876 .0
15877 .push(buffer_offset..buffer_offset)
15878 }
15879 }
15880 None => {
15881 let selections = self.selections.all::<usize>(cx);
15882 let multi_buffer = self.buffer.read(cx);
15883 for selection in selections {
15884 for (snapshot, range, _, anchor) in multi_buffer
15885 .snapshot(cx)
15886 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15887 {
15888 if let Some(anchor) = anchor {
15889 // selection is in a deleted hunk
15890 let Some(buffer_id) = anchor.buffer_id else {
15891 continue;
15892 };
15893 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15894 continue;
15895 };
15896 let offset = text::ToOffset::to_offset(
15897 &anchor.text_anchor,
15898 &buffer_handle.read(cx).snapshot(),
15899 );
15900 let range = offset..offset;
15901 new_selections_by_buffer
15902 .entry(buffer_handle)
15903 .or_insert((Vec::new(), None))
15904 .0
15905 .push(range)
15906 } else {
15907 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15908 else {
15909 continue;
15910 };
15911 new_selections_by_buffer
15912 .entry(buffer_handle)
15913 .or_insert((Vec::new(), None))
15914 .0
15915 .push(range)
15916 }
15917 }
15918 }
15919 }
15920 }
15921
15922 if new_selections_by_buffer.is_empty() {
15923 return;
15924 }
15925
15926 // We defer the pane interaction because we ourselves are a workspace item
15927 // and activating a new item causes the pane to call a method on us reentrantly,
15928 // which panics if we're on the stack.
15929 window.defer(cx, move |window, cx| {
15930 workspace.update(cx, |workspace, cx| {
15931 let pane = if split {
15932 workspace.adjacent_pane(window, cx)
15933 } else {
15934 workspace.active_pane().clone()
15935 };
15936
15937 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15938 let editor = buffer
15939 .read(cx)
15940 .file()
15941 .is_none()
15942 .then(|| {
15943 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15944 // so `workspace.open_project_item` will never find them, always opening a new editor.
15945 // Instead, we try to activate the existing editor in the pane first.
15946 let (editor, pane_item_index) =
15947 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15948 let editor = item.downcast::<Editor>()?;
15949 let singleton_buffer =
15950 editor.read(cx).buffer().read(cx).as_singleton()?;
15951 if singleton_buffer == buffer {
15952 Some((editor, i))
15953 } else {
15954 None
15955 }
15956 })?;
15957 pane.update(cx, |pane, cx| {
15958 pane.activate_item(pane_item_index, true, true, window, cx)
15959 });
15960 Some(editor)
15961 })
15962 .flatten()
15963 .unwrap_or_else(|| {
15964 workspace.open_project_item::<Self>(
15965 pane.clone(),
15966 buffer,
15967 true,
15968 true,
15969 window,
15970 cx,
15971 )
15972 });
15973
15974 editor.update(cx, |editor, cx| {
15975 let autoscroll = match scroll_offset {
15976 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15977 None => Autoscroll::newest(),
15978 };
15979 let nav_history = editor.nav_history.take();
15980 editor.change_selections(Some(autoscroll), window, cx, |s| {
15981 s.select_ranges(ranges);
15982 });
15983 editor.nav_history = nav_history;
15984 });
15985 }
15986 })
15987 });
15988 }
15989
15990 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15991 let snapshot = self.buffer.read(cx).read(cx);
15992 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15993 Some(
15994 ranges
15995 .iter()
15996 .map(move |range| {
15997 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15998 })
15999 .collect(),
16000 )
16001 }
16002
16003 fn selection_replacement_ranges(
16004 &self,
16005 range: Range<OffsetUtf16>,
16006 cx: &mut App,
16007 ) -> Vec<Range<OffsetUtf16>> {
16008 let selections = self.selections.all::<OffsetUtf16>(cx);
16009 let newest_selection = selections
16010 .iter()
16011 .max_by_key(|selection| selection.id)
16012 .unwrap();
16013 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16014 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16015 let snapshot = self.buffer.read(cx).read(cx);
16016 selections
16017 .into_iter()
16018 .map(|mut selection| {
16019 selection.start.0 =
16020 (selection.start.0 as isize).saturating_add(start_delta) as usize;
16021 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16022 snapshot.clip_offset_utf16(selection.start, Bias::Left)
16023 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16024 })
16025 .collect()
16026 }
16027
16028 fn report_editor_event(
16029 &self,
16030 event_type: &'static str,
16031 file_extension: Option<String>,
16032 cx: &App,
16033 ) {
16034 if cfg!(any(test, feature = "test-support")) {
16035 return;
16036 }
16037
16038 let Some(project) = &self.project else { return };
16039
16040 // If None, we are in a file without an extension
16041 let file = self
16042 .buffer
16043 .read(cx)
16044 .as_singleton()
16045 .and_then(|b| b.read(cx).file());
16046 let file_extension = file_extension.or(file
16047 .as_ref()
16048 .and_then(|file| Path::new(file.file_name(cx)).extension())
16049 .and_then(|e| e.to_str())
16050 .map(|a| a.to_string()));
16051
16052 let vim_mode = cx
16053 .global::<SettingsStore>()
16054 .raw_user_settings()
16055 .get("vim_mode")
16056 == Some(&serde_json::Value::Bool(true));
16057
16058 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16059 let copilot_enabled = edit_predictions_provider
16060 == language::language_settings::EditPredictionProvider::Copilot;
16061 let copilot_enabled_for_language = self
16062 .buffer
16063 .read(cx)
16064 .language_settings(cx)
16065 .show_edit_predictions;
16066
16067 let project = project.read(cx);
16068 telemetry::event!(
16069 event_type,
16070 file_extension,
16071 vim_mode,
16072 copilot_enabled,
16073 copilot_enabled_for_language,
16074 edit_predictions_provider,
16075 is_via_ssh = project.is_via_ssh(),
16076 );
16077 }
16078
16079 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16080 /// with each line being an array of {text, highlight} objects.
16081 fn copy_highlight_json(
16082 &mut self,
16083 _: &CopyHighlightJson,
16084 window: &mut Window,
16085 cx: &mut Context<Self>,
16086 ) {
16087 #[derive(Serialize)]
16088 struct Chunk<'a> {
16089 text: String,
16090 highlight: Option<&'a str>,
16091 }
16092
16093 let snapshot = self.buffer.read(cx).snapshot(cx);
16094 let range = self
16095 .selected_text_range(false, window, cx)
16096 .and_then(|selection| {
16097 if selection.range.is_empty() {
16098 None
16099 } else {
16100 Some(selection.range)
16101 }
16102 })
16103 .unwrap_or_else(|| 0..snapshot.len());
16104
16105 let chunks = snapshot.chunks(range, true);
16106 let mut lines = Vec::new();
16107 let mut line: VecDeque<Chunk> = VecDeque::new();
16108
16109 let Some(style) = self.style.as_ref() else {
16110 return;
16111 };
16112
16113 for chunk in chunks {
16114 let highlight = chunk
16115 .syntax_highlight_id
16116 .and_then(|id| id.name(&style.syntax));
16117 let mut chunk_lines = chunk.text.split('\n').peekable();
16118 while let Some(text) = chunk_lines.next() {
16119 let mut merged_with_last_token = false;
16120 if let Some(last_token) = line.back_mut() {
16121 if last_token.highlight == highlight {
16122 last_token.text.push_str(text);
16123 merged_with_last_token = true;
16124 }
16125 }
16126
16127 if !merged_with_last_token {
16128 line.push_back(Chunk {
16129 text: text.into(),
16130 highlight,
16131 });
16132 }
16133
16134 if chunk_lines.peek().is_some() {
16135 if line.len() > 1 && line.front().unwrap().text.is_empty() {
16136 line.pop_front();
16137 }
16138 if line.len() > 1 && line.back().unwrap().text.is_empty() {
16139 line.pop_back();
16140 }
16141
16142 lines.push(mem::take(&mut line));
16143 }
16144 }
16145 }
16146
16147 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16148 return;
16149 };
16150 cx.write_to_clipboard(ClipboardItem::new_string(lines));
16151 }
16152
16153 pub fn open_context_menu(
16154 &mut self,
16155 _: &OpenContextMenu,
16156 window: &mut Window,
16157 cx: &mut Context<Self>,
16158 ) {
16159 self.request_autoscroll(Autoscroll::newest(), cx);
16160 let position = self.selections.newest_display(cx).start;
16161 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16162 }
16163
16164 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16165 &self.inlay_hint_cache
16166 }
16167
16168 pub fn replay_insert_event(
16169 &mut self,
16170 text: &str,
16171 relative_utf16_range: Option<Range<isize>>,
16172 window: &mut Window,
16173 cx: &mut Context<Self>,
16174 ) {
16175 if !self.input_enabled {
16176 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16177 return;
16178 }
16179 if let Some(relative_utf16_range) = relative_utf16_range {
16180 let selections = self.selections.all::<OffsetUtf16>(cx);
16181 self.change_selections(None, window, cx, |s| {
16182 let new_ranges = selections.into_iter().map(|range| {
16183 let start = OffsetUtf16(
16184 range
16185 .head()
16186 .0
16187 .saturating_add_signed(relative_utf16_range.start),
16188 );
16189 let end = OffsetUtf16(
16190 range
16191 .head()
16192 .0
16193 .saturating_add_signed(relative_utf16_range.end),
16194 );
16195 start..end
16196 });
16197 s.select_ranges(new_ranges);
16198 });
16199 }
16200
16201 self.handle_input(text, window, cx);
16202 }
16203
16204 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16205 let Some(provider) = self.semantics_provider.as_ref() else {
16206 return false;
16207 };
16208
16209 let mut supports = false;
16210 self.buffer().update(cx, |this, cx| {
16211 this.for_each_buffer(|buffer| {
16212 supports |= provider.supports_inlay_hints(buffer, cx);
16213 });
16214 });
16215
16216 supports
16217 }
16218
16219 pub fn is_focused(&self, window: &Window) -> bool {
16220 self.focus_handle.is_focused(window)
16221 }
16222
16223 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16224 cx.emit(EditorEvent::Focused);
16225
16226 if let Some(descendant) = self
16227 .last_focused_descendant
16228 .take()
16229 .and_then(|descendant| descendant.upgrade())
16230 {
16231 window.focus(&descendant);
16232 } else {
16233 if let Some(blame) = self.blame.as_ref() {
16234 blame.update(cx, GitBlame::focus)
16235 }
16236
16237 self.blink_manager.update(cx, BlinkManager::enable);
16238 self.show_cursor_names(window, cx);
16239 self.buffer.update(cx, |buffer, cx| {
16240 buffer.finalize_last_transaction(cx);
16241 if self.leader_peer_id.is_none() {
16242 buffer.set_active_selections(
16243 &self.selections.disjoint_anchors(),
16244 self.selections.line_mode,
16245 self.cursor_shape,
16246 cx,
16247 );
16248 }
16249 });
16250 }
16251 }
16252
16253 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16254 cx.emit(EditorEvent::FocusedIn)
16255 }
16256
16257 fn handle_focus_out(
16258 &mut self,
16259 event: FocusOutEvent,
16260 _window: &mut Window,
16261 cx: &mut Context<Self>,
16262 ) {
16263 if event.blurred != self.focus_handle {
16264 self.last_focused_descendant = Some(event.blurred);
16265 }
16266 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16267 }
16268
16269 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16270 self.blink_manager.update(cx, BlinkManager::disable);
16271 self.buffer
16272 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16273
16274 if let Some(blame) = self.blame.as_ref() {
16275 blame.update(cx, GitBlame::blur)
16276 }
16277 if !self.hover_state.focused(window, cx) {
16278 hide_hover(self, cx);
16279 }
16280 if !self
16281 .context_menu
16282 .borrow()
16283 .as_ref()
16284 .is_some_and(|context_menu| context_menu.focused(window, cx))
16285 {
16286 self.hide_context_menu(window, cx);
16287 }
16288 self.discard_inline_completion(false, cx);
16289 cx.emit(EditorEvent::Blurred);
16290 cx.notify();
16291 }
16292
16293 pub fn register_action<A: Action>(
16294 &mut self,
16295 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16296 ) -> Subscription {
16297 let id = self.next_editor_action_id.post_inc();
16298 let listener = Arc::new(listener);
16299 self.editor_actions.borrow_mut().insert(
16300 id,
16301 Box::new(move |window, _| {
16302 let listener = listener.clone();
16303 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16304 let action = action.downcast_ref().unwrap();
16305 if phase == DispatchPhase::Bubble {
16306 listener(action, window, cx)
16307 }
16308 })
16309 }),
16310 );
16311
16312 let editor_actions = self.editor_actions.clone();
16313 Subscription::new(move || {
16314 editor_actions.borrow_mut().remove(&id);
16315 })
16316 }
16317
16318 pub fn file_header_size(&self) -> u32 {
16319 FILE_HEADER_HEIGHT
16320 }
16321
16322 pub fn restore(
16323 &mut self,
16324 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16325 window: &mut Window,
16326 cx: &mut Context<Self>,
16327 ) {
16328 let workspace = self.workspace();
16329 let project = self.project.as_ref();
16330 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16331 let mut tasks = Vec::new();
16332 for (buffer_id, changes) in revert_changes {
16333 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16334 buffer.update(cx, |buffer, cx| {
16335 buffer.edit(
16336 changes
16337 .into_iter()
16338 .map(|(range, text)| (range, text.to_string())),
16339 None,
16340 cx,
16341 );
16342 });
16343
16344 if let Some(project) =
16345 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16346 {
16347 project.update(cx, |project, cx| {
16348 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16349 })
16350 }
16351 }
16352 }
16353 tasks
16354 });
16355 cx.spawn_in(window, |_, mut cx| async move {
16356 for (buffer, task) in save_tasks {
16357 let result = task.await;
16358 if result.is_err() {
16359 let Some(path) = buffer
16360 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16361 .ok()
16362 else {
16363 continue;
16364 };
16365 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16366 let Some(task) = cx
16367 .update_window_entity(&workspace, |workspace, window, cx| {
16368 workspace
16369 .open_path_preview(path, None, false, false, false, window, cx)
16370 })
16371 .ok()
16372 else {
16373 continue;
16374 };
16375 task.await.log_err();
16376 }
16377 }
16378 }
16379 })
16380 .detach();
16381 self.change_selections(None, window, cx, |selections| selections.refresh());
16382 }
16383
16384 pub fn to_pixel_point(
16385 &self,
16386 source: multi_buffer::Anchor,
16387 editor_snapshot: &EditorSnapshot,
16388 window: &mut Window,
16389 ) -> Option<gpui::Point<Pixels>> {
16390 let source_point = source.to_display_point(editor_snapshot);
16391 self.display_to_pixel_point(source_point, editor_snapshot, window)
16392 }
16393
16394 pub fn display_to_pixel_point(
16395 &self,
16396 source: DisplayPoint,
16397 editor_snapshot: &EditorSnapshot,
16398 window: &mut Window,
16399 ) -> Option<gpui::Point<Pixels>> {
16400 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16401 let text_layout_details = self.text_layout_details(window);
16402 let scroll_top = text_layout_details
16403 .scroll_anchor
16404 .scroll_position(editor_snapshot)
16405 .y;
16406
16407 if source.row().as_f32() < scroll_top.floor() {
16408 return None;
16409 }
16410 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16411 let source_y = line_height * (source.row().as_f32() - scroll_top);
16412 Some(gpui::Point::new(source_x, source_y))
16413 }
16414
16415 pub fn has_visible_completions_menu(&self) -> bool {
16416 !self.edit_prediction_preview_is_active()
16417 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16418 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16419 })
16420 }
16421
16422 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16423 self.addons
16424 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16425 }
16426
16427 pub fn unregister_addon<T: Addon>(&mut self) {
16428 self.addons.remove(&std::any::TypeId::of::<T>());
16429 }
16430
16431 pub fn addon<T: Addon>(&self) -> Option<&T> {
16432 let type_id = std::any::TypeId::of::<T>();
16433 self.addons
16434 .get(&type_id)
16435 .and_then(|item| item.to_any().downcast_ref::<T>())
16436 }
16437
16438 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16439 let text_layout_details = self.text_layout_details(window);
16440 let style = &text_layout_details.editor_style;
16441 let font_id = window.text_system().resolve_font(&style.text.font());
16442 let font_size = style.text.font_size.to_pixels(window.rem_size());
16443 let line_height = style.text.line_height_in_pixels(window.rem_size());
16444 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16445
16446 gpui::Size::new(em_width, line_height)
16447 }
16448
16449 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16450 self.load_diff_task.clone()
16451 }
16452
16453 fn read_selections_from_db(
16454 &mut self,
16455 item_id: u64,
16456 workspace_id: WorkspaceId,
16457 window: &mut Window,
16458 cx: &mut Context<Editor>,
16459 ) {
16460 if !self.is_singleton(cx)
16461 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16462 {
16463 return;
16464 }
16465 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16466 return;
16467 };
16468 if selections.is_empty() {
16469 return;
16470 }
16471
16472 let snapshot = self.buffer.read(cx).snapshot(cx);
16473 self.change_selections(None, window, cx, |s| {
16474 s.select_ranges(selections.into_iter().map(|(start, end)| {
16475 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16476 }));
16477 });
16478 }
16479}
16480
16481fn insert_extra_newline_brackets(
16482 buffer: &MultiBufferSnapshot,
16483 range: Range<usize>,
16484 language: &language::LanguageScope,
16485) -> bool {
16486 let leading_whitespace_len = buffer
16487 .reversed_chars_at(range.start)
16488 .take_while(|c| c.is_whitespace() && *c != '\n')
16489 .map(|c| c.len_utf8())
16490 .sum::<usize>();
16491 let trailing_whitespace_len = buffer
16492 .chars_at(range.end)
16493 .take_while(|c| c.is_whitespace() && *c != '\n')
16494 .map(|c| c.len_utf8())
16495 .sum::<usize>();
16496 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16497
16498 language.brackets().any(|(pair, enabled)| {
16499 let pair_start = pair.start.trim_end();
16500 let pair_end = pair.end.trim_start();
16501
16502 enabled
16503 && pair.newline
16504 && buffer.contains_str_at(range.end, pair_end)
16505 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16506 })
16507}
16508
16509fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16510 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16511 [(buffer, range, _)] => (*buffer, range.clone()),
16512 _ => return false,
16513 };
16514 let pair = {
16515 let mut result: Option<BracketMatch> = None;
16516
16517 for pair in buffer
16518 .all_bracket_ranges(range.clone())
16519 .filter(move |pair| {
16520 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16521 })
16522 {
16523 let len = pair.close_range.end - pair.open_range.start;
16524
16525 if let Some(existing) = &result {
16526 let existing_len = existing.close_range.end - existing.open_range.start;
16527 if len > existing_len {
16528 continue;
16529 }
16530 }
16531
16532 result = Some(pair);
16533 }
16534
16535 result
16536 };
16537 let Some(pair) = pair else {
16538 return false;
16539 };
16540 pair.newline_only
16541 && buffer
16542 .chars_for_range(pair.open_range.end..range.start)
16543 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16544 .all(|c| c.is_whitespace() && c != '\n')
16545}
16546
16547fn get_uncommitted_diff_for_buffer(
16548 project: &Entity<Project>,
16549 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16550 buffer: Entity<MultiBuffer>,
16551 cx: &mut App,
16552) -> Task<()> {
16553 let mut tasks = Vec::new();
16554 project.update(cx, |project, cx| {
16555 for buffer in buffers {
16556 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16557 }
16558 });
16559 cx.spawn(|mut cx| async move {
16560 let diffs = future::join_all(tasks).await;
16561 buffer
16562 .update(&mut cx, |buffer, cx| {
16563 for diff in diffs.into_iter().flatten() {
16564 buffer.add_diff(diff, cx);
16565 }
16566 })
16567 .ok();
16568 })
16569}
16570
16571fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16572 let tab_size = tab_size.get() as usize;
16573 let mut width = offset;
16574
16575 for ch in text.chars() {
16576 width += if ch == '\t' {
16577 tab_size - (width % tab_size)
16578 } else {
16579 1
16580 };
16581 }
16582
16583 width - offset
16584}
16585
16586#[cfg(test)]
16587mod tests {
16588 use super::*;
16589
16590 #[test]
16591 fn test_string_size_with_expanded_tabs() {
16592 let nz = |val| NonZeroU32::new(val).unwrap();
16593 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16594 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16595 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16596 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16597 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16598 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16599 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16600 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16601 }
16602}
16603
16604/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16605struct WordBreakingTokenizer<'a> {
16606 input: &'a str,
16607}
16608
16609impl<'a> WordBreakingTokenizer<'a> {
16610 fn new(input: &'a str) -> Self {
16611 Self { input }
16612 }
16613}
16614
16615fn is_char_ideographic(ch: char) -> bool {
16616 use unicode_script::Script::*;
16617 use unicode_script::UnicodeScript;
16618 matches!(ch.script(), Han | Tangut | Yi)
16619}
16620
16621fn is_grapheme_ideographic(text: &str) -> bool {
16622 text.chars().any(is_char_ideographic)
16623}
16624
16625fn is_grapheme_whitespace(text: &str) -> bool {
16626 text.chars().any(|x| x.is_whitespace())
16627}
16628
16629fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16630 text.chars().next().map_or(false, |ch| {
16631 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16632 })
16633}
16634
16635#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16636struct WordBreakToken<'a> {
16637 token: &'a str,
16638 grapheme_len: usize,
16639 is_whitespace: bool,
16640}
16641
16642impl<'a> Iterator for WordBreakingTokenizer<'a> {
16643 /// Yields a span, the count of graphemes in the token, and whether it was
16644 /// whitespace. Note that it also breaks at word boundaries.
16645 type Item = WordBreakToken<'a>;
16646
16647 fn next(&mut self) -> Option<Self::Item> {
16648 use unicode_segmentation::UnicodeSegmentation;
16649 if self.input.is_empty() {
16650 return None;
16651 }
16652
16653 let mut iter = self.input.graphemes(true).peekable();
16654 let mut offset = 0;
16655 let mut graphemes = 0;
16656 if let Some(first_grapheme) = iter.next() {
16657 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16658 offset += first_grapheme.len();
16659 graphemes += 1;
16660 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16661 if let Some(grapheme) = iter.peek().copied() {
16662 if should_stay_with_preceding_ideograph(grapheme) {
16663 offset += grapheme.len();
16664 graphemes += 1;
16665 }
16666 }
16667 } else {
16668 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16669 let mut next_word_bound = words.peek().copied();
16670 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16671 next_word_bound = words.next();
16672 }
16673 while let Some(grapheme) = iter.peek().copied() {
16674 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16675 break;
16676 };
16677 if is_grapheme_whitespace(grapheme) != is_whitespace {
16678 break;
16679 };
16680 offset += grapheme.len();
16681 graphemes += 1;
16682 iter.next();
16683 }
16684 }
16685 let token = &self.input[..offset];
16686 self.input = &self.input[offset..];
16687 if is_whitespace {
16688 Some(WordBreakToken {
16689 token: " ",
16690 grapheme_len: 1,
16691 is_whitespace: true,
16692 })
16693 } else {
16694 Some(WordBreakToken {
16695 token,
16696 grapheme_len: graphemes,
16697 is_whitespace: false,
16698 })
16699 }
16700 } else {
16701 None
16702 }
16703 }
16704}
16705
16706#[test]
16707fn test_word_breaking_tokenizer() {
16708 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16709 ("", &[]),
16710 (" ", &[(" ", 1, true)]),
16711 ("Ʒ", &[("Ʒ", 1, false)]),
16712 ("Ǽ", &[("Ǽ", 1, false)]),
16713 ("⋑", &[("⋑", 1, false)]),
16714 ("⋑⋑", &[("⋑⋑", 2, false)]),
16715 (
16716 "原理,进而",
16717 &[
16718 ("原", 1, false),
16719 ("理,", 2, false),
16720 ("进", 1, false),
16721 ("而", 1, false),
16722 ],
16723 ),
16724 (
16725 "hello world",
16726 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16727 ),
16728 (
16729 "hello, world",
16730 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16731 ),
16732 (
16733 " hello world",
16734 &[
16735 (" ", 1, true),
16736 ("hello", 5, false),
16737 (" ", 1, true),
16738 ("world", 5, false),
16739 ],
16740 ),
16741 (
16742 "这是什么 \n 钢笔",
16743 &[
16744 ("这", 1, false),
16745 ("是", 1, false),
16746 ("什", 1, false),
16747 ("么", 1, false),
16748 (" ", 1, true),
16749 ("钢", 1, false),
16750 ("笔", 1, false),
16751 ],
16752 ),
16753 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16754 ];
16755
16756 for (input, result) in tests {
16757 assert_eq!(
16758 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16759 result
16760 .iter()
16761 .copied()
16762 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16763 token,
16764 grapheme_len,
16765 is_whitespace,
16766 })
16767 .collect::<Vec<_>>()
16768 );
16769 }
16770}
16771
16772fn wrap_with_prefix(
16773 line_prefix: String,
16774 unwrapped_text: String,
16775 wrap_column: usize,
16776 tab_size: NonZeroU32,
16777) -> String {
16778 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16779 let mut wrapped_text = String::new();
16780 let mut current_line = line_prefix.clone();
16781
16782 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16783 let mut current_line_len = line_prefix_len;
16784 for WordBreakToken {
16785 token,
16786 grapheme_len,
16787 is_whitespace,
16788 } in tokenizer
16789 {
16790 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16791 wrapped_text.push_str(current_line.trim_end());
16792 wrapped_text.push('\n');
16793 current_line.truncate(line_prefix.len());
16794 current_line_len = line_prefix_len;
16795 if !is_whitespace {
16796 current_line.push_str(token);
16797 current_line_len += grapheme_len;
16798 }
16799 } else if !is_whitespace {
16800 current_line.push_str(token);
16801 current_line_len += grapheme_len;
16802 } else if current_line_len != line_prefix_len {
16803 current_line.push(' ');
16804 current_line_len += 1;
16805 }
16806 }
16807
16808 if !current_line.is_empty() {
16809 wrapped_text.push_str(¤t_line);
16810 }
16811 wrapped_text
16812}
16813
16814#[test]
16815fn test_wrap_with_prefix() {
16816 assert_eq!(
16817 wrap_with_prefix(
16818 "# ".to_string(),
16819 "abcdefg".to_string(),
16820 4,
16821 NonZeroU32::new(4).unwrap()
16822 ),
16823 "# abcdefg"
16824 );
16825 assert_eq!(
16826 wrap_with_prefix(
16827 "".to_string(),
16828 "\thello world".to_string(),
16829 8,
16830 NonZeroU32::new(4).unwrap()
16831 ),
16832 "hello\nworld"
16833 );
16834 assert_eq!(
16835 wrap_with_prefix(
16836 "// ".to_string(),
16837 "xx \nyy zz aa bb cc".to_string(),
16838 12,
16839 NonZeroU32::new(4).unwrap()
16840 ),
16841 "// xx yy zz\n// aa bb cc"
16842 );
16843 assert_eq!(
16844 wrap_with_prefix(
16845 String::new(),
16846 "这是什么 \n 钢笔".to_string(),
16847 3,
16848 NonZeroU32::new(4).unwrap()
16849 ),
16850 "这是什\n么 钢\n笔"
16851 );
16852}
16853
16854pub trait CollaborationHub {
16855 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16856 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16857 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16858}
16859
16860impl CollaborationHub for Entity<Project> {
16861 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16862 self.read(cx).collaborators()
16863 }
16864
16865 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16866 self.read(cx).user_store().read(cx).participant_indices()
16867 }
16868
16869 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16870 let this = self.read(cx);
16871 let user_ids = this.collaborators().values().map(|c| c.user_id);
16872 this.user_store().read_with(cx, |user_store, cx| {
16873 user_store.participant_names(user_ids, cx)
16874 })
16875 }
16876}
16877
16878pub trait SemanticsProvider {
16879 fn hover(
16880 &self,
16881 buffer: &Entity<Buffer>,
16882 position: text::Anchor,
16883 cx: &mut App,
16884 ) -> Option<Task<Vec<project::Hover>>>;
16885
16886 fn inlay_hints(
16887 &self,
16888 buffer_handle: Entity<Buffer>,
16889 range: Range<text::Anchor>,
16890 cx: &mut App,
16891 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16892
16893 fn resolve_inlay_hint(
16894 &self,
16895 hint: InlayHint,
16896 buffer_handle: Entity<Buffer>,
16897 server_id: LanguageServerId,
16898 cx: &mut App,
16899 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16900
16901 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16902
16903 fn document_highlights(
16904 &self,
16905 buffer: &Entity<Buffer>,
16906 position: text::Anchor,
16907 cx: &mut App,
16908 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16909
16910 fn definitions(
16911 &self,
16912 buffer: &Entity<Buffer>,
16913 position: text::Anchor,
16914 kind: GotoDefinitionKind,
16915 cx: &mut App,
16916 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16917
16918 fn range_for_rename(
16919 &self,
16920 buffer: &Entity<Buffer>,
16921 position: text::Anchor,
16922 cx: &mut App,
16923 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16924
16925 fn perform_rename(
16926 &self,
16927 buffer: &Entity<Buffer>,
16928 position: text::Anchor,
16929 new_name: String,
16930 cx: &mut App,
16931 ) -> Option<Task<Result<ProjectTransaction>>>;
16932}
16933
16934pub trait CompletionProvider {
16935 fn completions(
16936 &self,
16937 buffer: &Entity<Buffer>,
16938 buffer_position: text::Anchor,
16939 trigger: CompletionContext,
16940 window: &mut Window,
16941 cx: &mut Context<Editor>,
16942 ) -> Task<Result<Option<Vec<Completion>>>>;
16943
16944 fn resolve_completions(
16945 &self,
16946 buffer: Entity<Buffer>,
16947 completion_indices: Vec<usize>,
16948 completions: Rc<RefCell<Box<[Completion]>>>,
16949 cx: &mut Context<Editor>,
16950 ) -> Task<Result<bool>>;
16951
16952 fn apply_additional_edits_for_completion(
16953 &self,
16954 _buffer: Entity<Buffer>,
16955 _completions: Rc<RefCell<Box<[Completion]>>>,
16956 _completion_index: usize,
16957 _push_to_history: bool,
16958 _cx: &mut Context<Editor>,
16959 ) -> Task<Result<Option<language::Transaction>>> {
16960 Task::ready(Ok(None))
16961 }
16962
16963 fn is_completion_trigger(
16964 &self,
16965 buffer: &Entity<Buffer>,
16966 position: language::Anchor,
16967 text: &str,
16968 trigger_in_words: bool,
16969 cx: &mut Context<Editor>,
16970 ) -> bool;
16971
16972 fn sort_completions(&self) -> bool {
16973 true
16974 }
16975}
16976
16977pub trait CodeActionProvider {
16978 fn id(&self) -> Arc<str>;
16979
16980 fn code_actions(
16981 &self,
16982 buffer: &Entity<Buffer>,
16983 range: Range<text::Anchor>,
16984 window: &mut Window,
16985 cx: &mut App,
16986 ) -> Task<Result<Vec<CodeAction>>>;
16987
16988 fn apply_code_action(
16989 &self,
16990 buffer_handle: Entity<Buffer>,
16991 action: CodeAction,
16992 excerpt_id: ExcerptId,
16993 push_to_history: bool,
16994 window: &mut Window,
16995 cx: &mut App,
16996 ) -> Task<Result<ProjectTransaction>>;
16997}
16998
16999impl CodeActionProvider for Entity<Project> {
17000 fn id(&self) -> Arc<str> {
17001 "project".into()
17002 }
17003
17004 fn code_actions(
17005 &self,
17006 buffer: &Entity<Buffer>,
17007 range: Range<text::Anchor>,
17008 _window: &mut Window,
17009 cx: &mut App,
17010 ) -> Task<Result<Vec<CodeAction>>> {
17011 self.update(cx, |project, cx| {
17012 project.code_actions(buffer, range, None, cx)
17013 })
17014 }
17015
17016 fn apply_code_action(
17017 &self,
17018 buffer_handle: Entity<Buffer>,
17019 action: CodeAction,
17020 _excerpt_id: ExcerptId,
17021 push_to_history: bool,
17022 _window: &mut Window,
17023 cx: &mut App,
17024 ) -> Task<Result<ProjectTransaction>> {
17025 self.update(cx, |project, cx| {
17026 project.apply_code_action(buffer_handle, action, push_to_history, cx)
17027 })
17028 }
17029}
17030
17031fn snippet_completions(
17032 project: &Project,
17033 buffer: &Entity<Buffer>,
17034 buffer_position: text::Anchor,
17035 cx: &mut App,
17036) -> Task<Result<Vec<Completion>>> {
17037 let language = buffer.read(cx).language_at(buffer_position);
17038 let language_name = language.as_ref().map(|language| language.lsp_id());
17039 let snippet_store = project.snippets().read(cx);
17040 let snippets = snippet_store.snippets_for(language_name, cx);
17041
17042 if snippets.is_empty() {
17043 return Task::ready(Ok(vec![]));
17044 }
17045 let snapshot = buffer.read(cx).text_snapshot();
17046 let chars: String = snapshot
17047 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17048 .collect();
17049
17050 let scope = language.map(|language| language.default_scope());
17051 let executor = cx.background_executor().clone();
17052
17053 cx.background_spawn(async move {
17054 let classifier = CharClassifier::new(scope).for_completion(true);
17055 let mut last_word = chars
17056 .chars()
17057 .take_while(|c| classifier.is_word(*c))
17058 .collect::<String>();
17059 last_word = last_word.chars().rev().collect();
17060
17061 if last_word.is_empty() {
17062 return Ok(vec![]);
17063 }
17064
17065 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17066 let to_lsp = |point: &text::Anchor| {
17067 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
17068 point_to_lsp(end)
17069 };
17070 let lsp_end = to_lsp(&buffer_position);
17071
17072 let candidates = snippets
17073 .iter()
17074 .enumerate()
17075 .flat_map(|(ix, snippet)| {
17076 snippet
17077 .prefix
17078 .iter()
17079 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
17080 })
17081 .collect::<Vec<StringMatchCandidate>>();
17082
17083 let mut matches = fuzzy::match_strings(
17084 &candidates,
17085 &last_word,
17086 last_word.chars().any(|c| c.is_uppercase()),
17087 100,
17088 &Default::default(),
17089 executor,
17090 )
17091 .await;
17092
17093 // Remove all candidates where the query's start does not match the start of any word in the candidate
17094 if let Some(query_start) = last_word.chars().next() {
17095 matches.retain(|string_match| {
17096 split_words(&string_match.string).any(|word| {
17097 // Check that the first codepoint of the word as lowercase matches the first
17098 // codepoint of the query as lowercase
17099 word.chars()
17100 .flat_map(|codepoint| codepoint.to_lowercase())
17101 .zip(query_start.to_lowercase())
17102 .all(|(word_cp, query_cp)| word_cp == query_cp)
17103 })
17104 });
17105 }
17106
17107 let matched_strings = matches
17108 .into_iter()
17109 .map(|m| m.string)
17110 .collect::<HashSet<_>>();
17111
17112 let result: Vec<Completion> = snippets
17113 .into_iter()
17114 .filter_map(|snippet| {
17115 let matching_prefix = snippet
17116 .prefix
17117 .iter()
17118 .find(|prefix| matched_strings.contains(*prefix))?;
17119 let start = as_offset - last_word.len();
17120 let start = snapshot.anchor_before(start);
17121 let range = start..buffer_position;
17122 let lsp_start = to_lsp(&start);
17123 let lsp_range = lsp::Range {
17124 start: lsp_start,
17125 end: lsp_end,
17126 };
17127 Some(Completion {
17128 old_range: range,
17129 new_text: snippet.body.clone(),
17130 source: CompletionSource::Lsp {
17131 server_id: LanguageServerId(usize::MAX),
17132 resolved: true,
17133 lsp_completion: Box::new(lsp::CompletionItem {
17134 label: snippet.prefix.first().unwrap().clone(),
17135 kind: Some(CompletionItemKind::SNIPPET),
17136 label_details: snippet.description.as_ref().map(|description| {
17137 lsp::CompletionItemLabelDetails {
17138 detail: Some(description.clone()),
17139 description: None,
17140 }
17141 }),
17142 insert_text_format: Some(InsertTextFormat::SNIPPET),
17143 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17144 lsp::InsertReplaceEdit {
17145 new_text: snippet.body.clone(),
17146 insert: lsp_range,
17147 replace: lsp_range,
17148 },
17149 )),
17150 filter_text: Some(snippet.body.clone()),
17151 sort_text: Some(char::MAX.to_string()),
17152 ..lsp::CompletionItem::default()
17153 }),
17154 lsp_defaults: None,
17155 },
17156 label: CodeLabel {
17157 text: matching_prefix.clone(),
17158 runs: Vec::new(),
17159 filter_range: 0..matching_prefix.len(),
17160 },
17161 documentation: snippet
17162 .description
17163 .clone()
17164 .map(|description| CompletionDocumentation::SingleLine(description.into())),
17165 confirm: None,
17166 })
17167 })
17168 .collect();
17169
17170 Ok(result)
17171 })
17172}
17173
17174impl CompletionProvider for Entity<Project> {
17175 fn completions(
17176 &self,
17177 buffer: &Entity<Buffer>,
17178 buffer_position: text::Anchor,
17179 options: CompletionContext,
17180 _window: &mut Window,
17181 cx: &mut Context<Editor>,
17182 ) -> Task<Result<Option<Vec<Completion>>>> {
17183 self.update(cx, |project, cx| {
17184 let snippets = snippet_completions(project, buffer, buffer_position, cx);
17185 let project_completions = project.completions(buffer, buffer_position, options, cx);
17186 cx.background_spawn(async move {
17187 let snippets_completions = snippets.await?;
17188 match project_completions.await? {
17189 Some(mut completions) => {
17190 completions.extend(snippets_completions);
17191 Ok(Some(completions))
17192 }
17193 None => {
17194 if snippets_completions.is_empty() {
17195 Ok(None)
17196 } else {
17197 Ok(Some(snippets_completions))
17198 }
17199 }
17200 }
17201 })
17202 })
17203 }
17204
17205 fn resolve_completions(
17206 &self,
17207 buffer: Entity<Buffer>,
17208 completion_indices: Vec<usize>,
17209 completions: Rc<RefCell<Box<[Completion]>>>,
17210 cx: &mut Context<Editor>,
17211 ) -> Task<Result<bool>> {
17212 self.update(cx, |project, cx| {
17213 project.lsp_store().update(cx, |lsp_store, cx| {
17214 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17215 })
17216 })
17217 }
17218
17219 fn apply_additional_edits_for_completion(
17220 &self,
17221 buffer: Entity<Buffer>,
17222 completions: Rc<RefCell<Box<[Completion]>>>,
17223 completion_index: usize,
17224 push_to_history: bool,
17225 cx: &mut Context<Editor>,
17226 ) -> Task<Result<Option<language::Transaction>>> {
17227 self.update(cx, |project, cx| {
17228 project.lsp_store().update(cx, |lsp_store, cx| {
17229 lsp_store.apply_additional_edits_for_completion(
17230 buffer,
17231 completions,
17232 completion_index,
17233 push_to_history,
17234 cx,
17235 )
17236 })
17237 })
17238 }
17239
17240 fn is_completion_trigger(
17241 &self,
17242 buffer: &Entity<Buffer>,
17243 position: language::Anchor,
17244 text: &str,
17245 trigger_in_words: bool,
17246 cx: &mut Context<Editor>,
17247 ) -> bool {
17248 let mut chars = text.chars();
17249 let char = if let Some(char) = chars.next() {
17250 char
17251 } else {
17252 return false;
17253 };
17254 if chars.next().is_some() {
17255 return false;
17256 }
17257
17258 let buffer = buffer.read(cx);
17259 let snapshot = buffer.snapshot();
17260 if !snapshot.settings_at(position, cx).show_completions_on_input {
17261 return false;
17262 }
17263 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17264 if trigger_in_words && classifier.is_word(char) {
17265 return true;
17266 }
17267
17268 buffer.completion_triggers().contains(text)
17269 }
17270}
17271
17272impl SemanticsProvider for Entity<Project> {
17273 fn hover(
17274 &self,
17275 buffer: &Entity<Buffer>,
17276 position: text::Anchor,
17277 cx: &mut App,
17278 ) -> Option<Task<Vec<project::Hover>>> {
17279 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17280 }
17281
17282 fn document_highlights(
17283 &self,
17284 buffer: &Entity<Buffer>,
17285 position: text::Anchor,
17286 cx: &mut App,
17287 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17288 Some(self.update(cx, |project, cx| {
17289 project.document_highlights(buffer, position, cx)
17290 }))
17291 }
17292
17293 fn definitions(
17294 &self,
17295 buffer: &Entity<Buffer>,
17296 position: text::Anchor,
17297 kind: GotoDefinitionKind,
17298 cx: &mut App,
17299 ) -> Option<Task<Result<Vec<LocationLink>>>> {
17300 Some(self.update(cx, |project, cx| match kind {
17301 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17302 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17303 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17304 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17305 }))
17306 }
17307
17308 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17309 // TODO: make this work for remote projects
17310 self.update(cx, |this, cx| {
17311 buffer.update(cx, |buffer, cx| {
17312 this.any_language_server_supports_inlay_hints(buffer, cx)
17313 })
17314 })
17315 }
17316
17317 fn inlay_hints(
17318 &self,
17319 buffer_handle: Entity<Buffer>,
17320 range: Range<text::Anchor>,
17321 cx: &mut App,
17322 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17323 Some(self.update(cx, |project, cx| {
17324 project.inlay_hints(buffer_handle, range, cx)
17325 }))
17326 }
17327
17328 fn resolve_inlay_hint(
17329 &self,
17330 hint: InlayHint,
17331 buffer_handle: Entity<Buffer>,
17332 server_id: LanguageServerId,
17333 cx: &mut App,
17334 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17335 Some(self.update(cx, |project, cx| {
17336 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17337 }))
17338 }
17339
17340 fn range_for_rename(
17341 &self,
17342 buffer: &Entity<Buffer>,
17343 position: text::Anchor,
17344 cx: &mut App,
17345 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17346 Some(self.update(cx, |project, cx| {
17347 let buffer = buffer.clone();
17348 let task = project.prepare_rename(buffer.clone(), position, cx);
17349 cx.spawn(|_, mut cx| async move {
17350 Ok(match task.await? {
17351 PrepareRenameResponse::Success(range) => Some(range),
17352 PrepareRenameResponse::InvalidPosition => None,
17353 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17354 // Fallback on using TreeSitter info to determine identifier range
17355 buffer.update(&mut cx, |buffer, _| {
17356 let snapshot = buffer.snapshot();
17357 let (range, kind) = snapshot.surrounding_word(position);
17358 if kind != Some(CharKind::Word) {
17359 return None;
17360 }
17361 Some(
17362 snapshot.anchor_before(range.start)
17363 ..snapshot.anchor_after(range.end),
17364 )
17365 })?
17366 }
17367 })
17368 })
17369 }))
17370 }
17371
17372 fn perform_rename(
17373 &self,
17374 buffer: &Entity<Buffer>,
17375 position: text::Anchor,
17376 new_name: String,
17377 cx: &mut App,
17378 ) -> Option<Task<Result<ProjectTransaction>>> {
17379 Some(self.update(cx, |project, cx| {
17380 project.perform_rename(buffer.clone(), position, new_name, cx)
17381 }))
17382 }
17383}
17384
17385fn inlay_hint_settings(
17386 location: Anchor,
17387 snapshot: &MultiBufferSnapshot,
17388 cx: &mut Context<Editor>,
17389) -> InlayHintSettings {
17390 let file = snapshot.file_at(location);
17391 let language = snapshot.language_at(location).map(|l| l.name());
17392 language_settings(language, file, cx).inlay_hints
17393}
17394
17395fn consume_contiguous_rows(
17396 contiguous_row_selections: &mut Vec<Selection<Point>>,
17397 selection: &Selection<Point>,
17398 display_map: &DisplaySnapshot,
17399 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17400) -> (MultiBufferRow, MultiBufferRow) {
17401 contiguous_row_selections.push(selection.clone());
17402 let start_row = MultiBufferRow(selection.start.row);
17403 let mut end_row = ending_row(selection, display_map);
17404
17405 while let Some(next_selection) = selections.peek() {
17406 if next_selection.start.row <= end_row.0 {
17407 end_row = ending_row(next_selection, display_map);
17408 contiguous_row_selections.push(selections.next().unwrap().clone());
17409 } else {
17410 break;
17411 }
17412 }
17413 (start_row, end_row)
17414}
17415
17416fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17417 if next_selection.end.column > 0 || next_selection.is_empty() {
17418 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17419 } else {
17420 MultiBufferRow(next_selection.end.row)
17421 }
17422}
17423
17424impl EditorSnapshot {
17425 pub fn remote_selections_in_range<'a>(
17426 &'a self,
17427 range: &'a Range<Anchor>,
17428 collaboration_hub: &dyn CollaborationHub,
17429 cx: &'a App,
17430 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17431 let participant_names = collaboration_hub.user_names(cx);
17432 let participant_indices = collaboration_hub.user_participant_indices(cx);
17433 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17434 let collaborators_by_replica_id = collaborators_by_peer_id
17435 .iter()
17436 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17437 .collect::<HashMap<_, _>>();
17438 self.buffer_snapshot
17439 .selections_in_range(range, false)
17440 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17441 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17442 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17443 let user_name = participant_names.get(&collaborator.user_id).cloned();
17444 Some(RemoteSelection {
17445 replica_id,
17446 selection,
17447 cursor_shape,
17448 line_mode,
17449 participant_index,
17450 peer_id: collaborator.peer_id,
17451 user_name,
17452 })
17453 })
17454 }
17455
17456 pub fn hunks_for_ranges(
17457 &self,
17458 ranges: impl IntoIterator<Item = Range<Point>>,
17459 ) -> Vec<MultiBufferDiffHunk> {
17460 let mut hunks = Vec::new();
17461 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17462 HashMap::default();
17463 for query_range in ranges {
17464 let query_rows =
17465 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17466 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17467 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17468 ) {
17469 // Include deleted hunks that are adjacent to the query range, because
17470 // otherwise they would be missed.
17471 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17472 if hunk.status().is_deleted() {
17473 intersects_range |= hunk.row_range.start == query_rows.end;
17474 intersects_range |= hunk.row_range.end == query_rows.start;
17475 }
17476 if intersects_range {
17477 if !processed_buffer_rows
17478 .entry(hunk.buffer_id)
17479 .or_default()
17480 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17481 {
17482 continue;
17483 }
17484 hunks.push(hunk);
17485 }
17486 }
17487 }
17488
17489 hunks
17490 }
17491
17492 fn display_diff_hunks_for_rows<'a>(
17493 &'a self,
17494 display_rows: Range<DisplayRow>,
17495 folded_buffers: &'a HashSet<BufferId>,
17496 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17497 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17498 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17499
17500 self.buffer_snapshot
17501 .diff_hunks_in_range(buffer_start..buffer_end)
17502 .filter_map(|hunk| {
17503 if folded_buffers.contains(&hunk.buffer_id) {
17504 return None;
17505 }
17506
17507 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17508 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17509
17510 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17511 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17512
17513 let display_hunk = if hunk_display_start.column() != 0 {
17514 DisplayDiffHunk::Folded {
17515 display_row: hunk_display_start.row(),
17516 }
17517 } else {
17518 let mut end_row = hunk_display_end.row();
17519 if hunk_display_end.column() > 0 {
17520 end_row.0 += 1;
17521 }
17522 let is_created_file = hunk.is_created_file();
17523 DisplayDiffHunk::Unfolded {
17524 status: hunk.status(),
17525 diff_base_byte_range: hunk.diff_base_byte_range,
17526 display_row_range: hunk_display_start.row()..end_row,
17527 multi_buffer_range: Anchor::range_in_buffer(
17528 hunk.excerpt_id,
17529 hunk.buffer_id,
17530 hunk.buffer_range,
17531 ),
17532 is_created_file,
17533 }
17534 };
17535
17536 Some(display_hunk)
17537 })
17538 }
17539
17540 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17541 self.display_snapshot.buffer_snapshot.language_at(position)
17542 }
17543
17544 pub fn is_focused(&self) -> bool {
17545 self.is_focused
17546 }
17547
17548 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17549 self.placeholder_text.as_ref()
17550 }
17551
17552 pub fn scroll_position(&self) -> gpui::Point<f32> {
17553 self.scroll_anchor.scroll_position(&self.display_snapshot)
17554 }
17555
17556 fn gutter_dimensions(
17557 &self,
17558 font_id: FontId,
17559 font_size: Pixels,
17560 max_line_number_width: Pixels,
17561 cx: &App,
17562 ) -> Option<GutterDimensions> {
17563 if !self.show_gutter {
17564 return None;
17565 }
17566
17567 let descent = cx.text_system().descent(font_id, font_size);
17568 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17569 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17570
17571 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17572 matches!(
17573 ProjectSettings::get_global(cx).git.git_gutter,
17574 Some(GitGutterSetting::TrackedFiles)
17575 )
17576 });
17577 let gutter_settings = EditorSettings::get_global(cx).gutter;
17578 let show_line_numbers = self
17579 .show_line_numbers
17580 .unwrap_or(gutter_settings.line_numbers);
17581 let line_gutter_width = if show_line_numbers {
17582 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17583 let min_width_for_number_on_gutter = em_advance * 4.0;
17584 max_line_number_width.max(min_width_for_number_on_gutter)
17585 } else {
17586 0.0.into()
17587 };
17588
17589 let show_code_actions = self
17590 .show_code_actions
17591 .unwrap_or(gutter_settings.code_actions);
17592
17593 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17594
17595 let git_blame_entries_width =
17596 self.git_blame_gutter_max_author_length
17597 .map(|max_author_length| {
17598 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17599
17600 /// The number of characters to dedicate to gaps and margins.
17601 const SPACING_WIDTH: usize = 4;
17602
17603 let max_char_count = max_author_length
17604 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17605 + ::git::SHORT_SHA_LENGTH
17606 + MAX_RELATIVE_TIMESTAMP.len()
17607 + SPACING_WIDTH;
17608
17609 em_advance * max_char_count
17610 });
17611
17612 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17613 left_padding += if show_code_actions || show_runnables {
17614 em_width * 3.0
17615 } else if show_git_gutter && show_line_numbers {
17616 em_width * 2.0
17617 } else if show_git_gutter || show_line_numbers {
17618 em_width
17619 } else {
17620 px(0.)
17621 };
17622
17623 let right_padding = if gutter_settings.folds && show_line_numbers {
17624 em_width * 4.0
17625 } else if gutter_settings.folds {
17626 em_width * 3.0
17627 } else if show_line_numbers {
17628 em_width
17629 } else {
17630 px(0.)
17631 };
17632
17633 Some(GutterDimensions {
17634 left_padding,
17635 right_padding,
17636 width: line_gutter_width + left_padding + right_padding,
17637 margin: -descent,
17638 git_blame_entries_width,
17639 })
17640 }
17641
17642 pub fn render_crease_toggle(
17643 &self,
17644 buffer_row: MultiBufferRow,
17645 row_contains_cursor: bool,
17646 editor: Entity<Editor>,
17647 window: &mut Window,
17648 cx: &mut App,
17649 ) -> Option<AnyElement> {
17650 let folded = self.is_line_folded(buffer_row);
17651 let mut is_foldable = false;
17652
17653 if let Some(crease) = self
17654 .crease_snapshot
17655 .query_row(buffer_row, &self.buffer_snapshot)
17656 {
17657 is_foldable = true;
17658 match crease {
17659 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17660 if let Some(render_toggle) = render_toggle {
17661 let toggle_callback =
17662 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17663 if folded {
17664 editor.update(cx, |editor, cx| {
17665 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17666 });
17667 } else {
17668 editor.update(cx, |editor, cx| {
17669 editor.unfold_at(
17670 &crate::UnfoldAt { buffer_row },
17671 window,
17672 cx,
17673 )
17674 });
17675 }
17676 });
17677 return Some((render_toggle)(
17678 buffer_row,
17679 folded,
17680 toggle_callback,
17681 window,
17682 cx,
17683 ));
17684 }
17685 }
17686 }
17687 }
17688
17689 is_foldable |= self.starts_indent(buffer_row);
17690
17691 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17692 Some(
17693 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17694 .toggle_state(folded)
17695 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17696 if folded {
17697 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17698 } else {
17699 this.fold_at(&FoldAt { buffer_row }, window, cx);
17700 }
17701 }))
17702 .into_any_element(),
17703 )
17704 } else {
17705 None
17706 }
17707 }
17708
17709 pub fn render_crease_trailer(
17710 &self,
17711 buffer_row: MultiBufferRow,
17712 window: &mut Window,
17713 cx: &mut App,
17714 ) -> Option<AnyElement> {
17715 let folded = self.is_line_folded(buffer_row);
17716 if let Crease::Inline { render_trailer, .. } = self
17717 .crease_snapshot
17718 .query_row(buffer_row, &self.buffer_snapshot)?
17719 {
17720 let render_trailer = render_trailer.as_ref()?;
17721 Some(render_trailer(buffer_row, folded, window, cx))
17722 } else {
17723 None
17724 }
17725 }
17726}
17727
17728impl Deref for EditorSnapshot {
17729 type Target = DisplaySnapshot;
17730
17731 fn deref(&self) -> &Self::Target {
17732 &self.display_snapshot
17733 }
17734}
17735
17736#[derive(Clone, Debug, PartialEq, Eq)]
17737pub enum EditorEvent {
17738 InputIgnored {
17739 text: Arc<str>,
17740 },
17741 InputHandled {
17742 utf16_range_to_replace: Option<Range<isize>>,
17743 text: Arc<str>,
17744 },
17745 ExcerptsAdded {
17746 buffer: Entity<Buffer>,
17747 predecessor: ExcerptId,
17748 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17749 },
17750 ExcerptsRemoved {
17751 ids: Vec<ExcerptId>,
17752 },
17753 BufferFoldToggled {
17754 ids: Vec<ExcerptId>,
17755 folded: bool,
17756 },
17757 ExcerptsEdited {
17758 ids: Vec<ExcerptId>,
17759 },
17760 ExcerptsExpanded {
17761 ids: Vec<ExcerptId>,
17762 },
17763 BufferEdited,
17764 Edited {
17765 transaction_id: clock::Lamport,
17766 },
17767 Reparsed(BufferId),
17768 Focused,
17769 FocusedIn,
17770 Blurred,
17771 DirtyChanged,
17772 Saved,
17773 TitleChanged,
17774 DiffBaseChanged,
17775 SelectionsChanged {
17776 local: bool,
17777 },
17778 ScrollPositionChanged {
17779 local: bool,
17780 autoscroll: bool,
17781 },
17782 Closed,
17783 TransactionUndone {
17784 transaction_id: clock::Lamport,
17785 },
17786 TransactionBegun {
17787 transaction_id: clock::Lamport,
17788 },
17789 Reloaded,
17790 CursorShapeChanged,
17791}
17792
17793impl EventEmitter<EditorEvent> for Editor {}
17794
17795impl Focusable for Editor {
17796 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17797 self.focus_handle.clone()
17798 }
17799}
17800
17801impl Render for Editor {
17802 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17803 let settings = ThemeSettings::get_global(cx);
17804
17805 let mut text_style = match self.mode {
17806 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17807 color: cx.theme().colors().editor_foreground,
17808 font_family: settings.ui_font.family.clone(),
17809 font_features: settings.ui_font.features.clone(),
17810 font_fallbacks: settings.ui_font.fallbacks.clone(),
17811 font_size: rems(0.875).into(),
17812 font_weight: settings.ui_font.weight,
17813 line_height: relative(settings.buffer_line_height.value()),
17814 ..Default::default()
17815 },
17816 EditorMode::Full => TextStyle {
17817 color: cx.theme().colors().editor_foreground,
17818 font_family: settings.buffer_font.family.clone(),
17819 font_features: settings.buffer_font.features.clone(),
17820 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17821 font_size: settings.buffer_font_size(cx).into(),
17822 font_weight: settings.buffer_font.weight,
17823 line_height: relative(settings.buffer_line_height.value()),
17824 ..Default::default()
17825 },
17826 };
17827 if let Some(text_style_refinement) = &self.text_style_refinement {
17828 text_style.refine(text_style_refinement)
17829 }
17830
17831 let background = match self.mode {
17832 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17833 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17834 EditorMode::Full => cx.theme().colors().editor_background,
17835 };
17836
17837 EditorElement::new(
17838 &cx.entity(),
17839 EditorStyle {
17840 background,
17841 local_player: cx.theme().players().local(),
17842 text: text_style,
17843 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17844 syntax: cx.theme().syntax().clone(),
17845 status: cx.theme().status().clone(),
17846 inlay_hints_style: make_inlay_hints_style(cx),
17847 inline_completion_styles: make_suggestion_styles(cx),
17848 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17849 },
17850 )
17851 }
17852}
17853
17854impl EntityInputHandler for Editor {
17855 fn text_for_range(
17856 &mut self,
17857 range_utf16: Range<usize>,
17858 adjusted_range: &mut Option<Range<usize>>,
17859 _: &mut Window,
17860 cx: &mut Context<Self>,
17861 ) -> Option<String> {
17862 let snapshot = self.buffer.read(cx).read(cx);
17863 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17864 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17865 if (start.0..end.0) != range_utf16 {
17866 adjusted_range.replace(start.0..end.0);
17867 }
17868 Some(snapshot.text_for_range(start..end).collect())
17869 }
17870
17871 fn selected_text_range(
17872 &mut self,
17873 ignore_disabled_input: bool,
17874 _: &mut Window,
17875 cx: &mut Context<Self>,
17876 ) -> Option<UTF16Selection> {
17877 // Prevent the IME menu from appearing when holding down an alphabetic key
17878 // while input is disabled.
17879 if !ignore_disabled_input && !self.input_enabled {
17880 return None;
17881 }
17882
17883 let selection = self.selections.newest::<OffsetUtf16>(cx);
17884 let range = selection.range();
17885
17886 Some(UTF16Selection {
17887 range: range.start.0..range.end.0,
17888 reversed: selection.reversed,
17889 })
17890 }
17891
17892 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17893 let snapshot = self.buffer.read(cx).read(cx);
17894 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17895 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17896 }
17897
17898 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17899 self.clear_highlights::<InputComposition>(cx);
17900 self.ime_transaction.take();
17901 }
17902
17903 fn replace_text_in_range(
17904 &mut self,
17905 range_utf16: Option<Range<usize>>,
17906 text: &str,
17907 window: &mut Window,
17908 cx: &mut Context<Self>,
17909 ) {
17910 if !self.input_enabled {
17911 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17912 return;
17913 }
17914
17915 self.transact(window, cx, |this, window, cx| {
17916 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17917 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17918 Some(this.selection_replacement_ranges(range_utf16, cx))
17919 } else {
17920 this.marked_text_ranges(cx)
17921 };
17922
17923 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17924 let newest_selection_id = this.selections.newest_anchor().id;
17925 this.selections
17926 .all::<OffsetUtf16>(cx)
17927 .iter()
17928 .zip(ranges_to_replace.iter())
17929 .find_map(|(selection, range)| {
17930 if selection.id == newest_selection_id {
17931 Some(
17932 (range.start.0 as isize - selection.head().0 as isize)
17933 ..(range.end.0 as isize - selection.head().0 as isize),
17934 )
17935 } else {
17936 None
17937 }
17938 })
17939 });
17940
17941 cx.emit(EditorEvent::InputHandled {
17942 utf16_range_to_replace: range_to_replace,
17943 text: text.into(),
17944 });
17945
17946 if let Some(new_selected_ranges) = new_selected_ranges {
17947 this.change_selections(None, window, cx, |selections| {
17948 selections.select_ranges(new_selected_ranges)
17949 });
17950 this.backspace(&Default::default(), window, cx);
17951 }
17952
17953 this.handle_input(text, window, cx);
17954 });
17955
17956 if let Some(transaction) = self.ime_transaction {
17957 self.buffer.update(cx, |buffer, cx| {
17958 buffer.group_until_transaction(transaction, cx);
17959 });
17960 }
17961
17962 self.unmark_text(window, cx);
17963 }
17964
17965 fn replace_and_mark_text_in_range(
17966 &mut self,
17967 range_utf16: Option<Range<usize>>,
17968 text: &str,
17969 new_selected_range_utf16: Option<Range<usize>>,
17970 window: &mut Window,
17971 cx: &mut Context<Self>,
17972 ) {
17973 if !self.input_enabled {
17974 return;
17975 }
17976
17977 let transaction = self.transact(window, cx, |this, window, cx| {
17978 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17979 let snapshot = this.buffer.read(cx).read(cx);
17980 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17981 for marked_range in &mut marked_ranges {
17982 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17983 marked_range.start.0 += relative_range_utf16.start;
17984 marked_range.start =
17985 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17986 marked_range.end =
17987 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17988 }
17989 }
17990 Some(marked_ranges)
17991 } else if let Some(range_utf16) = range_utf16 {
17992 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17993 Some(this.selection_replacement_ranges(range_utf16, cx))
17994 } else {
17995 None
17996 };
17997
17998 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17999 let newest_selection_id = this.selections.newest_anchor().id;
18000 this.selections
18001 .all::<OffsetUtf16>(cx)
18002 .iter()
18003 .zip(ranges_to_replace.iter())
18004 .find_map(|(selection, range)| {
18005 if selection.id == newest_selection_id {
18006 Some(
18007 (range.start.0 as isize - selection.head().0 as isize)
18008 ..(range.end.0 as isize - selection.head().0 as isize),
18009 )
18010 } else {
18011 None
18012 }
18013 })
18014 });
18015
18016 cx.emit(EditorEvent::InputHandled {
18017 utf16_range_to_replace: range_to_replace,
18018 text: text.into(),
18019 });
18020
18021 if let Some(ranges) = ranges_to_replace {
18022 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18023 }
18024
18025 let marked_ranges = {
18026 let snapshot = this.buffer.read(cx).read(cx);
18027 this.selections
18028 .disjoint_anchors()
18029 .iter()
18030 .map(|selection| {
18031 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18032 })
18033 .collect::<Vec<_>>()
18034 };
18035
18036 if text.is_empty() {
18037 this.unmark_text(window, cx);
18038 } else {
18039 this.highlight_text::<InputComposition>(
18040 marked_ranges.clone(),
18041 HighlightStyle {
18042 underline: Some(UnderlineStyle {
18043 thickness: px(1.),
18044 color: None,
18045 wavy: false,
18046 }),
18047 ..Default::default()
18048 },
18049 cx,
18050 );
18051 }
18052
18053 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18054 let use_autoclose = this.use_autoclose;
18055 let use_auto_surround = this.use_auto_surround;
18056 this.set_use_autoclose(false);
18057 this.set_use_auto_surround(false);
18058 this.handle_input(text, window, cx);
18059 this.set_use_autoclose(use_autoclose);
18060 this.set_use_auto_surround(use_auto_surround);
18061
18062 if let Some(new_selected_range) = new_selected_range_utf16 {
18063 let snapshot = this.buffer.read(cx).read(cx);
18064 let new_selected_ranges = marked_ranges
18065 .into_iter()
18066 .map(|marked_range| {
18067 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
18068 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
18069 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
18070 snapshot.clip_offset_utf16(new_start, Bias::Left)
18071 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
18072 })
18073 .collect::<Vec<_>>();
18074
18075 drop(snapshot);
18076 this.change_selections(None, window, cx, |selections| {
18077 selections.select_ranges(new_selected_ranges)
18078 });
18079 }
18080 });
18081
18082 self.ime_transaction = self.ime_transaction.or(transaction);
18083 if let Some(transaction) = self.ime_transaction {
18084 self.buffer.update(cx, |buffer, cx| {
18085 buffer.group_until_transaction(transaction, cx);
18086 });
18087 }
18088
18089 if self.text_highlights::<InputComposition>(cx).is_none() {
18090 self.ime_transaction.take();
18091 }
18092 }
18093
18094 fn bounds_for_range(
18095 &mut self,
18096 range_utf16: Range<usize>,
18097 element_bounds: gpui::Bounds<Pixels>,
18098 window: &mut Window,
18099 cx: &mut Context<Self>,
18100 ) -> Option<gpui::Bounds<Pixels>> {
18101 let text_layout_details = self.text_layout_details(window);
18102 let gpui::Size {
18103 width: em_width,
18104 height: line_height,
18105 } = self.character_size(window);
18106
18107 let snapshot = self.snapshot(window, cx);
18108 let scroll_position = snapshot.scroll_position();
18109 let scroll_left = scroll_position.x * em_width;
18110
18111 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
18112 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
18113 + self.gutter_dimensions.width
18114 + self.gutter_dimensions.margin;
18115 let y = line_height * (start.row().as_f32() - scroll_position.y);
18116
18117 Some(Bounds {
18118 origin: element_bounds.origin + point(x, y),
18119 size: size(em_width, line_height),
18120 })
18121 }
18122
18123 fn character_index_for_point(
18124 &mut self,
18125 point: gpui::Point<Pixels>,
18126 _window: &mut Window,
18127 _cx: &mut Context<Self>,
18128 ) -> Option<usize> {
18129 let position_map = self.last_position_map.as_ref()?;
18130 if !position_map.text_hitbox.contains(&point) {
18131 return None;
18132 }
18133 let display_point = position_map.point_for_position(point).previous_valid;
18134 let anchor = position_map
18135 .snapshot
18136 .display_point_to_anchor(display_point, Bias::Left);
18137 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18138 Some(utf16_offset.0)
18139 }
18140}
18141
18142trait SelectionExt {
18143 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18144 fn spanned_rows(
18145 &self,
18146 include_end_if_at_line_start: bool,
18147 map: &DisplaySnapshot,
18148 ) -> Range<MultiBufferRow>;
18149}
18150
18151impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18152 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18153 let start = self
18154 .start
18155 .to_point(&map.buffer_snapshot)
18156 .to_display_point(map);
18157 let end = self
18158 .end
18159 .to_point(&map.buffer_snapshot)
18160 .to_display_point(map);
18161 if self.reversed {
18162 end..start
18163 } else {
18164 start..end
18165 }
18166 }
18167
18168 fn spanned_rows(
18169 &self,
18170 include_end_if_at_line_start: bool,
18171 map: &DisplaySnapshot,
18172 ) -> Range<MultiBufferRow> {
18173 let start = self.start.to_point(&map.buffer_snapshot);
18174 let mut end = self.end.to_point(&map.buffer_snapshot);
18175 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18176 end.row -= 1;
18177 }
18178
18179 let buffer_start = map.prev_line_boundary(start).0;
18180 let buffer_end = map.next_line_boundary(end).0;
18181 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18182 }
18183}
18184
18185impl<T: InvalidationRegion> InvalidationStack<T> {
18186 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18187 where
18188 S: Clone + ToOffset,
18189 {
18190 while let Some(region) = self.last() {
18191 let all_selections_inside_invalidation_ranges =
18192 if selections.len() == region.ranges().len() {
18193 selections
18194 .iter()
18195 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18196 .all(|(selection, invalidation_range)| {
18197 let head = selection.head().to_offset(buffer);
18198 invalidation_range.start <= head && invalidation_range.end >= head
18199 })
18200 } else {
18201 false
18202 };
18203
18204 if all_selections_inside_invalidation_ranges {
18205 break;
18206 } else {
18207 self.pop();
18208 }
18209 }
18210 }
18211}
18212
18213impl<T> Default for InvalidationStack<T> {
18214 fn default() -> Self {
18215 Self(Default::default())
18216 }
18217}
18218
18219impl<T> Deref for InvalidationStack<T> {
18220 type Target = Vec<T>;
18221
18222 fn deref(&self) -> &Self::Target {
18223 &self.0
18224 }
18225}
18226
18227impl<T> DerefMut for InvalidationStack<T> {
18228 fn deref_mut(&mut self) -> &mut Self::Target {
18229 &mut self.0
18230 }
18231}
18232
18233impl InvalidationRegion for SnippetState {
18234 fn ranges(&self) -> &[Range<Anchor>] {
18235 &self.ranges[self.active_index]
18236 }
18237}
18238
18239pub fn diagnostic_block_renderer(
18240 diagnostic: Diagnostic,
18241 max_message_rows: Option<u8>,
18242 allow_closing: bool,
18243) -> RenderBlock {
18244 let (text_without_backticks, code_ranges) =
18245 highlight_diagnostic_message(&diagnostic, max_message_rows);
18246
18247 Arc::new(move |cx: &mut BlockContext| {
18248 let group_id: SharedString = cx.block_id.to_string().into();
18249
18250 let mut text_style = cx.window.text_style().clone();
18251 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18252 let theme_settings = ThemeSettings::get_global(cx);
18253 text_style.font_family = theme_settings.buffer_font.family.clone();
18254 text_style.font_style = theme_settings.buffer_font.style;
18255 text_style.font_features = theme_settings.buffer_font.features.clone();
18256 text_style.font_weight = theme_settings.buffer_font.weight;
18257
18258 let multi_line_diagnostic = diagnostic.message.contains('\n');
18259
18260 let buttons = |diagnostic: &Diagnostic| {
18261 if multi_line_diagnostic {
18262 v_flex()
18263 } else {
18264 h_flex()
18265 }
18266 .when(allow_closing, |div| {
18267 div.children(diagnostic.is_primary.then(|| {
18268 IconButton::new("close-block", IconName::XCircle)
18269 .icon_color(Color::Muted)
18270 .size(ButtonSize::Compact)
18271 .style(ButtonStyle::Transparent)
18272 .visible_on_hover(group_id.clone())
18273 .on_click(move |_click, window, cx| {
18274 window.dispatch_action(Box::new(Cancel), cx)
18275 })
18276 .tooltip(|window, cx| {
18277 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18278 })
18279 }))
18280 })
18281 .child(
18282 IconButton::new("copy-block", IconName::Copy)
18283 .icon_color(Color::Muted)
18284 .size(ButtonSize::Compact)
18285 .style(ButtonStyle::Transparent)
18286 .visible_on_hover(group_id.clone())
18287 .on_click({
18288 let message = diagnostic.message.clone();
18289 move |_click, _, cx| {
18290 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18291 }
18292 })
18293 .tooltip(Tooltip::text("Copy diagnostic message")),
18294 )
18295 };
18296
18297 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18298 AvailableSpace::min_size(),
18299 cx.window,
18300 cx.app,
18301 );
18302
18303 h_flex()
18304 .id(cx.block_id)
18305 .group(group_id.clone())
18306 .relative()
18307 .size_full()
18308 .block_mouse_down()
18309 .pl(cx.gutter_dimensions.width)
18310 .w(cx.max_width - cx.gutter_dimensions.full_width())
18311 .child(
18312 div()
18313 .flex()
18314 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18315 .flex_shrink(),
18316 )
18317 .child(buttons(&diagnostic))
18318 .child(div().flex().flex_shrink_0().child(
18319 StyledText::new(text_without_backticks.clone()).with_default_highlights(
18320 &text_style,
18321 code_ranges.iter().map(|range| {
18322 (
18323 range.clone(),
18324 HighlightStyle {
18325 font_weight: Some(FontWeight::BOLD),
18326 ..Default::default()
18327 },
18328 )
18329 }),
18330 ),
18331 ))
18332 .into_any_element()
18333 })
18334}
18335
18336fn inline_completion_edit_text(
18337 current_snapshot: &BufferSnapshot,
18338 edits: &[(Range<Anchor>, String)],
18339 edit_preview: &EditPreview,
18340 include_deletions: bool,
18341 cx: &App,
18342) -> HighlightedText {
18343 let edits = edits
18344 .iter()
18345 .map(|(anchor, text)| {
18346 (
18347 anchor.start.text_anchor..anchor.end.text_anchor,
18348 text.clone(),
18349 )
18350 })
18351 .collect::<Vec<_>>();
18352
18353 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18354}
18355
18356pub fn highlight_diagnostic_message(
18357 diagnostic: &Diagnostic,
18358 mut max_message_rows: Option<u8>,
18359) -> (SharedString, Vec<Range<usize>>) {
18360 let mut text_without_backticks = String::new();
18361 let mut code_ranges = Vec::new();
18362
18363 if let Some(source) = &diagnostic.source {
18364 text_without_backticks.push_str(source);
18365 code_ranges.push(0..source.len());
18366 text_without_backticks.push_str(": ");
18367 }
18368
18369 let mut prev_offset = 0;
18370 let mut in_code_block = false;
18371 let has_row_limit = max_message_rows.is_some();
18372 let mut newline_indices = diagnostic
18373 .message
18374 .match_indices('\n')
18375 .filter(|_| has_row_limit)
18376 .map(|(ix, _)| ix)
18377 .fuse()
18378 .peekable();
18379
18380 for (quote_ix, _) in diagnostic
18381 .message
18382 .match_indices('`')
18383 .chain([(diagnostic.message.len(), "")])
18384 {
18385 let mut first_newline_ix = None;
18386 let mut last_newline_ix = None;
18387 while let Some(newline_ix) = newline_indices.peek() {
18388 if *newline_ix < quote_ix {
18389 if first_newline_ix.is_none() {
18390 first_newline_ix = Some(*newline_ix);
18391 }
18392 last_newline_ix = Some(*newline_ix);
18393
18394 if let Some(rows_left) = &mut max_message_rows {
18395 if *rows_left == 0 {
18396 break;
18397 } else {
18398 *rows_left -= 1;
18399 }
18400 }
18401 let _ = newline_indices.next();
18402 } else {
18403 break;
18404 }
18405 }
18406 let prev_len = text_without_backticks.len();
18407 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18408 text_without_backticks.push_str(new_text);
18409 if in_code_block {
18410 code_ranges.push(prev_len..text_without_backticks.len());
18411 }
18412 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18413 in_code_block = !in_code_block;
18414 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18415 text_without_backticks.push_str("...");
18416 break;
18417 }
18418 }
18419
18420 (text_without_backticks.into(), code_ranges)
18421}
18422
18423fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18424 match severity {
18425 DiagnosticSeverity::ERROR => colors.error,
18426 DiagnosticSeverity::WARNING => colors.warning,
18427 DiagnosticSeverity::INFORMATION => colors.info,
18428 DiagnosticSeverity::HINT => colors.info,
18429 _ => colors.ignored,
18430 }
18431}
18432
18433pub fn styled_runs_for_code_label<'a>(
18434 label: &'a CodeLabel,
18435 syntax_theme: &'a theme::SyntaxTheme,
18436) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18437 let fade_out = HighlightStyle {
18438 fade_out: Some(0.35),
18439 ..Default::default()
18440 };
18441
18442 let mut prev_end = label.filter_range.end;
18443 label
18444 .runs
18445 .iter()
18446 .enumerate()
18447 .flat_map(move |(ix, (range, highlight_id))| {
18448 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18449 style
18450 } else {
18451 return Default::default();
18452 };
18453 let mut muted_style = style;
18454 muted_style.highlight(fade_out);
18455
18456 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18457 if range.start >= label.filter_range.end {
18458 if range.start > prev_end {
18459 runs.push((prev_end..range.start, fade_out));
18460 }
18461 runs.push((range.clone(), muted_style));
18462 } else if range.end <= label.filter_range.end {
18463 runs.push((range.clone(), style));
18464 } else {
18465 runs.push((range.start..label.filter_range.end, style));
18466 runs.push((label.filter_range.end..range.end, muted_style));
18467 }
18468 prev_end = cmp::max(prev_end, range.end);
18469
18470 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18471 runs.push((prev_end..label.text.len(), fade_out));
18472 }
18473
18474 runs
18475 })
18476}
18477
18478pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18479 let mut prev_index = 0;
18480 let mut prev_codepoint: Option<char> = None;
18481 text.char_indices()
18482 .chain([(text.len(), '\0')])
18483 .filter_map(move |(index, codepoint)| {
18484 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18485 let is_boundary = index == text.len()
18486 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18487 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18488 if is_boundary {
18489 let chunk = &text[prev_index..index];
18490 prev_index = index;
18491 Some(chunk)
18492 } else {
18493 None
18494 }
18495 })
18496}
18497
18498pub trait RangeToAnchorExt: Sized {
18499 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18500
18501 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18502 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18503 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18504 }
18505}
18506
18507impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18508 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18509 let start_offset = self.start.to_offset(snapshot);
18510 let end_offset = self.end.to_offset(snapshot);
18511 if start_offset == end_offset {
18512 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18513 } else {
18514 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18515 }
18516 }
18517}
18518
18519pub trait RowExt {
18520 fn as_f32(&self) -> f32;
18521
18522 fn next_row(&self) -> Self;
18523
18524 fn previous_row(&self) -> Self;
18525
18526 fn minus(&self, other: Self) -> u32;
18527}
18528
18529impl RowExt for DisplayRow {
18530 fn as_f32(&self) -> f32 {
18531 self.0 as f32
18532 }
18533
18534 fn next_row(&self) -> Self {
18535 Self(self.0 + 1)
18536 }
18537
18538 fn previous_row(&self) -> Self {
18539 Self(self.0.saturating_sub(1))
18540 }
18541
18542 fn minus(&self, other: Self) -> u32 {
18543 self.0 - other.0
18544 }
18545}
18546
18547impl RowExt for MultiBufferRow {
18548 fn as_f32(&self) -> f32 {
18549 self.0 as f32
18550 }
18551
18552 fn next_row(&self) -> Self {
18553 Self(self.0 + 1)
18554 }
18555
18556 fn previous_row(&self) -> Self {
18557 Self(self.0.saturating_sub(1))
18558 }
18559
18560 fn minus(&self, other: Self) -> u32 {
18561 self.0 - other.0
18562 }
18563}
18564
18565trait RowRangeExt {
18566 type Row;
18567
18568 fn len(&self) -> usize;
18569
18570 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18571}
18572
18573impl RowRangeExt for Range<MultiBufferRow> {
18574 type Row = MultiBufferRow;
18575
18576 fn len(&self) -> usize {
18577 (self.end.0 - self.start.0) as usize
18578 }
18579
18580 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18581 (self.start.0..self.end.0).map(MultiBufferRow)
18582 }
18583}
18584
18585impl RowRangeExt for Range<DisplayRow> {
18586 type Row = DisplayRow;
18587
18588 fn len(&self) -> usize {
18589 (self.end.0 - self.start.0) as usize
18590 }
18591
18592 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18593 (self.start.0..self.end.0).map(DisplayRow)
18594 }
18595}
18596
18597/// If select range has more than one line, we
18598/// just point the cursor to range.start.
18599fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18600 if range.start.row == range.end.row {
18601 range
18602 } else {
18603 range.start..range.start
18604 }
18605}
18606pub struct KillRing(ClipboardItem);
18607impl Global for KillRing {}
18608
18609const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18610
18611fn all_edits_insertions_or_deletions(
18612 edits: &Vec<(Range<Anchor>, String)>,
18613 snapshot: &MultiBufferSnapshot,
18614) -> bool {
18615 let mut all_insertions = true;
18616 let mut all_deletions = true;
18617
18618 for (range, new_text) in edits.iter() {
18619 let range_is_empty = range.to_offset(&snapshot).is_empty();
18620 let text_is_empty = new_text.is_empty();
18621
18622 if range_is_empty != text_is_empty {
18623 if range_is_empty {
18624 all_deletions = false;
18625 } else {
18626 all_insertions = false;
18627 }
18628 } else {
18629 return false;
18630 }
18631
18632 if !all_insertions && !all_deletions {
18633 return false;
18634 }
18635 }
18636 all_insertions || all_deletions
18637}
18638
18639struct MissingEditPredictionKeybindingTooltip;
18640
18641impl Render for MissingEditPredictionKeybindingTooltip {
18642 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18643 ui::tooltip_container(window, cx, |container, _, cx| {
18644 container
18645 .flex_shrink_0()
18646 .max_w_80()
18647 .min_h(rems_from_px(124.))
18648 .justify_between()
18649 .child(
18650 v_flex()
18651 .flex_1()
18652 .text_ui_sm(cx)
18653 .child(Label::new("Conflict with Accept Keybinding"))
18654 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18655 )
18656 .child(
18657 h_flex()
18658 .pb_1()
18659 .gap_1()
18660 .items_end()
18661 .w_full()
18662 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18663 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18664 }))
18665 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18666 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18667 })),
18668 )
18669 })
18670 }
18671}
18672
18673#[derive(Debug, Clone, Copy, PartialEq)]
18674pub struct LineHighlight {
18675 pub background: Background,
18676 pub border: Option<gpui::Hsla>,
18677}
18678
18679impl From<Hsla> for LineHighlight {
18680 fn from(hsla: Hsla) -> Self {
18681 Self {
18682 background: hsla.into(),
18683 border: None,
18684 }
18685 }
18686}
18687
18688impl From<Background> for LineHighlight {
18689 fn from(background: Background) -> Self {
18690 Self {
18691 background,
18692 border: None,
18693 }
18694 }
18695}