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, join, 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, AppContext, AsyncWindowContext, AvailableSpace, Background,
86 Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity,
87 EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight,
88 Global, 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| match event {
1237 project::Event::RefreshCodeLens => {
1238 // we always query lens with actions, without storing them, always refreshing them
1239 }
1240 project::Event::RefreshInlayHints => {
1241 editor
1242 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1243 }
1244 project::Event::SnippetEdit(id, snippet_edits) => {
1245 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1246 let focus_handle = editor.focus_handle(cx);
1247 if focus_handle.is_focused(window) {
1248 let snapshot = buffer.read(cx).snapshot();
1249 for (range, snippet) in snippet_edits {
1250 let editor_range =
1251 language::range_from_lsp(*range).to_offset(&snapshot);
1252 editor
1253 .insert_snippet(
1254 &[editor_range],
1255 snippet.clone(),
1256 window,
1257 cx,
1258 )
1259 .ok();
1260 }
1261 }
1262 }
1263 }
1264 _ => {}
1265 },
1266 ));
1267 if let Some(task_inventory) = project
1268 .read(cx)
1269 .task_store()
1270 .read(cx)
1271 .task_inventory()
1272 .cloned()
1273 {
1274 project_subscriptions.push(cx.observe_in(
1275 &task_inventory,
1276 window,
1277 |editor, _, window, cx| {
1278 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1279 },
1280 ));
1281 }
1282 }
1283 }
1284
1285 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1286
1287 let inlay_hint_settings =
1288 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1289 let focus_handle = cx.focus_handle();
1290 cx.on_focus(&focus_handle, window, Self::handle_focus)
1291 .detach();
1292 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1293 .detach();
1294 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1295 .detach();
1296 cx.on_blur(&focus_handle, window, Self::handle_blur)
1297 .detach();
1298
1299 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1300 Some(false)
1301 } else {
1302 None
1303 };
1304
1305 let mut code_action_providers = Vec::new();
1306 let mut load_uncommitted_diff = None;
1307 if let Some(project) = project.clone() {
1308 load_uncommitted_diff = Some(
1309 get_uncommitted_diff_for_buffer(
1310 &project,
1311 buffer.read(cx).all_buffers(),
1312 buffer.clone(),
1313 cx,
1314 )
1315 .shared(),
1316 );
1317 code_action_providers.push(Rc::new(project) as Rc<_>);
1318 }
1319
1320 let mut this = Self {
1321 focus_handle,
1322 show_cursor_when_unfocused: false,
1323 last_focused_descendant: None,
1324 buffer: buffer.clone(),
1325 display_map: display_map.clone(),
1326 selections,
1327 scroll_manager: ScrollManager::new(cx),
1328 columnar_selection_tail: None,
1329 add_selections_state: None,
1330 select_next_state: None,
1331 select_prev_state: None,
1332 selection_history: Default::default(),
1333 autoclose_regions: Default::default(),
1334 snippet_stack: Default::default(),
1335 select_larger_syntax_node_stack: Vec::new(),
1336 ime_transaction: Default::default(),
1337 active_diagnostics: None,
1338 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1339 inline_diagnostics_update: Task::ready(()),
1340 inline_diagnostics: Vec::new(),
1341 soft_wrap_mode_override,
1342 hard_wrap: None,
1343 completion_provider: project.clone().map(|project| Box::new(project) as _),
1344 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1345 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1346 project,
1347 blink_manager: blink_manager.clone(),
1348 show_local_selections: true,
1349 show_scrollbars: true,
1350 mode,
1351 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1352 show_gutter: mode == EditorMode::Full,
1353 show_line_numbers: None,
1354 use_relative_line_numbers: None,
1355 show_git_diff_gutter: None,
1356 show_code_actions: None,
1357 show_runnables: None,
1358 show_wrap_guides: None,
1359 show_indent_guides,
1360 placeholder_text: None,
1361 highlight_order: 0,
1362 highlighted_rows: HashMap::default(),
1363 background_highlights: Default::default(),
1364 gutter_highlights: TreeMap::default(),
1365 scrollbar_marker_state: ScrollbarMarkerState::default(),
1366 active_indent_guides_state: ActiveIndentGuidesState::default(),
1367 nav_history: None,
1368 context_menu: RefCell::new(None),
1369 mouse_context_menu: None,
1370 completion_tasks: Default::default(),
1371 signature_help_state: SignatureHelpState::default(),
1372 auto_signature_help: None,
1373 find_all_references_task_sources: Vec::new(),
1374 next_completion_id: 0,
1375 next_inlay_id: 0,
1376 code_action_providers,
1377 available_code_actions: Default::default(),
1378 code_actions_task: Default::default(),
1379 selection_highlight_task: Default::default(),
1380 document_highlights_task: Default::default(),
1381 linked_editing_range_task: Default::default(),
1382 pending_rename: Default::default(),
1383 searchable: true,
1384 cursor_shape: EditorSettings::get_global(cx)
1385 .cursor_shape
1386 .unwrap_or_default(),
1387 current_line_highlight: None,
1388 autoindent_mode: Some(AutoindentMode::EachLine),
1389 collapse_matches: false,
1390 workspace: None,
1391 input_enabled: true,
1392 use_modal_editing: mode == EditorMode::Full,
1393 read_only: false,
1394 use_autoclose: true,
1395 use_auto_surround: true,
1396 auto_replace_emoji_shortcode: false,
1397 jsx_tag_auto_close_enabled_in_any_buffer: false,
1398 leader_peer_id: None,
1399 remote_id: None,
1400 hover_state: Default::default(),
1401 pending_mouse_down: None,
1402 hovered_link_state: Default::default(),
1403 edit_prediction_provider: None,
1404 active_inline_completion: None,
1405 stale_inline_completion_in_menu: None,
1406 edit_prediction_preview: EditPredictionPreview::Inactive {
1407 released_too_fast: false,
1408 },
1409 inline_diagnostics_enabled: mode == EditorMode::Full,
1410 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1411
1412 gutter_hovered: false,
1413 pixel_position_of_newest_cursor: None,
1414 last_bounds: None,
1415 last_position_map: None,
1416 expect_bounds_change: None,
1417 gutter_dimensions: GutterDimensions::default(),
1418 style: None,
1419 show_cursor_names: false,
1420 hovered_cursors: Default::default(),
1421 next_editor_action_id: EditorActionId::default(),
1422 editor_actions: Rc::default(),
1423 inline_completions_hidden_for_vim_mode: false,
1424 show_inline_completions_override: None,
1425 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1426 edit_prediction_settings: EditPredictionSettings::Disabled,
1427 edit_prediction_indent_conflict: false,
1428 edit_prediction_requires_modifier_in_indent_conflict: true,
1429 custom_context_menu: None,
1430 show_git_blame_gutter: false,
1431 show_git_blame_inline: false,
1432 show_selection_menu: None,
1433 show_git_blame_inline_delay_task: None,
1434 git_blame_inline_tooltip: None,
1435 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1436 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1437 .session
1438 .restore_unsaved_buffers,
1439 blame: None,
1440 blame_subscription: None,
1441 tasks: Default::default(),
1442 _subscriptions: vec![
1443 cx.observe(&buffer, Self::on_buffer_changed),
1444 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1445 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1446 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1447 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1448 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1449 cx.observe_window_activation(window, |editor, window, cx| {
1450 let active = window.is_window_active();
1451 editor.blink_manager.update(cx, |blink_manager, cx| {
1452 if active {
1453 blink_manager.enable(cx);
1454 } else {
1455 blink_manager.disable(cx);
1456 }
1457 });
1458 }),
1459 ],
1460 tasks_update_task: None,
1461 linked_edit_ranges: Default::default(),
1462 in_project_search: false,
1463 previous_search_ranges: None,
1464 breadcrumb_header: None,
1465 focused_block: None,
1466 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1467 addons: HashMap::default(),
1468 registered_buffers: HashMap::default(),
1469 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1470 selection_mark_mode: false,
1471 toggle_fold_multiple_buffers: Task::ready(()),
1472 serialize_selections: Task::ready(()),
1473 text_style_refinement: None,
1474 load_diff_task: load_uncommitted_diff,
1475 };
1476 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1477 this._subscriptions.extend(project_subscriptions);
1478
1479 this.end_selection(window, cx);
1480 this.scroll_manager.show_scrollbar(window, cx);
1481 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1482
1483 if mode == EditorMode::Full {
1484 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1485 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1486
1487 if this.git_blame_inline_enabled {
1488 this.git_blame_inline_enabled = true;
1489 this.start_git_blame_inline(false, window, cx);
1490 }
1491
1492 if let Some(buffer) = buffer.read(cx).as_singleton() {
1493 if let Some(project) = this.project.as_ref() {
1494 let handle = project.update(cx, |project, cx| {
1495 project.register_buffer_with_language_servers(&buffer, cx)
1496 });
1497 this.registered_buffers
1498 .insert(buffer.read(cx).remote_id(), handle);
1499 }
1500 }
1501 }
1502
1503 this.report_editor_event("Editor Opened", None, cx);
1504 this
1505 }
1506
1507 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1508 self.mouse_context_menu
1509 .as_ref()
1510 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1511 }
1512
1513 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1514 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1515 }
1516
1517 fn key_context_internal(
1518 &self,
1519 has_active_edit_prediction: bool,
1520 window: &Window,
1521 cx: &App,
1522 ) -> KeyContext {
1523 let mut key_context = KeyContext::new_with_defaults();
1524 key_context.add("Editor");
1525 let mode = match self.mode {
1526 EditorMode::SingleLine { .. } => "single_line",
1527 EditorMode::AutoHeight { .. } => "auto_height",
1528 EditorMode::Full => "full",
1529 };
1530
1531 if EditorSettings::jupyter_enabled(cx) {
1532 key_context.add("jupyter");
1533 }
1534
1535 key_context.set("mode", mode);
1536 if self.pending_rename.is_some() {
1537 key_context.add("renaming");
1538 }
1539
1540 match self.context_menu.borrow().as_ref() {
1541 Some(CodeContextMenu::Completions(_)) => {
1542 key_context.add("menu");
1543 key_context.add("showing_completions");
1544 }
1545 Some(CodeContextMenu::CodeActions(_)) => {
1546 key_context.add("menu");
1547 key_context.add("showing_code_actions")
1548 }
1549 None => {}
1550 }
1551
1552 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1553 if !self.focus_handle(cx).contains_focused(window, cx)
1554 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1555 {
1556 for addon in self.addons.values() {
1557 addon.extend_key_context(&mut key_context, cx)
1558 }
1559 }
1560
1561 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1562 if let Some(extension) = singleton_buffer
1563 .read(cx)
1564 .file()
1565 .and_then(|file| file.path().extension()?.to_str())
1566 {
1567 key_context.set("extension", extension.to_string());
1568 }
1569 } else {
1570 key_context.add("multibuffer");
1571 }
1572
1573 if has_active_edit_prediction {
1574 if self.edit_prediction_in_conflict() {
1575 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1576 } else {
1577 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1578 key_context.add("copilot_suggestion");
1579 }
1580 }
1581
1582 if self.selection_mark_mode {
1583 key_context.add("selection_mode");
1584 }
1585
1586 key_context
1587 }
1588
1589 pub fn edit_prediction_in_conflict(&self) -> bool {
1590 if !self.show_edit_predictions_in_menu() {
1591 return false;
1592 }
1593
1594 let showing_completions = self
1595 .context_menu
1596 .borrow()
1597 .as_ref()
1598 .map_or(false, |context| {
1599 matches!(context, CodeContextMenu::Completions(_))
1600 });
1601
1602 showing_completions
1603 || self.edit_prediction_requires_modifier()
1604 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1605 // bindings to insert tab characters.
1606 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1607 }
1608
1609 pub fn accept_edit_prediction_keybind(
1610 &self,
1611 window: &Window,
1612 cx: &App,
1613 ) -> AcceptEditPredictionBinding {
1614 let key_context = self.key_context_internal(true, window, cx);
1615 let in_conflict = self.edit_prediction_in_conflict();
1616
1617 AcceptEditPredictionBinding(
1618 window
1619 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1620 .into_iter()
1621 .filter(|binding| {
1622 !in_conflict
1623 || binding
1624 .keystrokes()
1625 .first()
1626 .map_or(false, |keystroke| keystroke.modifiers.modified())
1627 })
1628 .rev()
1629 .min_by_key(|binding| {
1630 binding
1631 .keystrokes()
1632 .first()
1633 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1634 }),
1635 )
1636 }
1637
1638 pub fn new_file(
1639 workspace: &mut Workspace,
1640 _: &workspace::NewFile,
1641 window: &mut Window,
1642 cx: &mut Context<Workspace>,
1643 ) {
1644 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1645 "Failed to create buffer",
1646 window,
1647 cx,
1648 |e, _, _| match e.error_code() {
1649 ErrorCode::RemoteUpgradeRequired => Some(format!(
1650 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1651 e.error_tag("required").unwrap_or("the latest version")
1652 )),
1653 _ => None,
1654 },
1655 );
1656 }
1657
1658 pub fn new_in_workspace(
1659 workspace: &mut Workspace,
1660 window: &mut Window,
1661 cx: &mut Context<Workspace>,
1662 ) -> Task<Result<Entity<Editor>>> {
1663 let project = workspace.project().clone();
1664 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1665
1666 cx.spawn_in(window, |workspace, mut cx| async move {
1667 let buffer = create.await?;
1668 workspace.update_in(&mut cx, |workspace, window, cx| {
1669 let editor =
1670 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1671 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1672 editor
1673 })
1674 })
1675 }
1676
1677 fn new_file_vertical(
1678 workspace: &mut Workspace,
1679 _: &workspace::NewFileSplitVertical,
1680 window: &mut Window,
1681 cx: &mut Context<Workspace>,
1682 ) {
1683 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1684 }
1685
1686 fn new_file_horizontal(
1687 workspace: &mut Workspace,
1688 _: &workspace::NewFileSplitHorizontal,
1689 window: &mut Window,
1690 cx: &mut Context<Workspace>,
1691 ) {
1692 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1693 }
1694
1695 fn new_file_in_direction(
1696 workspace: &mut Workspace,
1697 direction: SplitDirection,
1698 window: &mut Window,
1699 cx: &mut Context<Workspace>,
1700 ) {
1701 let project = workspace.project().clone();
1702 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1703
1704 cx.spawn_in(window, |workspace, mut cx| async move {
1705 let buffer = create.await?;
1706 workspace.update_in(&mut cx, move |workspace, window, cx| {
1707 workspace.split_item(
1708 direction,
1709 Box::new(
1710 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1711 ),
1712 window,
1713 cx,
1714 )
1715 })?;
1716 anyhow::Ok(())
1717 })
1718 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1719 match e.error_code() {
1720 ErrorCode::RemoteUpgradeRequired => Some(format!(
1721 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1722 e.error_tag("required").unwrap_or("the latest version")
1723 )),
1724 _ => None,
1725 }
1726 });
1727 }
1728
1729 pub fn leader_peer_id(&self) -> Option<PeerId> {
1730 self.leader_peer_id
1731 }
1732
1733 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1734 &self.buffer
1735 }
1736
1737 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1738 self.workspace.as_ref()?.0.upgrade()
1739 }
1740
1741 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1742 self.buffer().read(cx).title(cx)
1743 }
1744
1745 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1746 let git_blame_gutter_max_author_length = self
1747 .render_git_blame_gutter(cx)
1748 .then(|| {
1749 if let Some(blame) = self.blame.as_ref() {
1750 let max_author_length =
1751 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1752 Some(max_author_length)
1753 } else {
1754 None
1755 }
1756 })
1757 .flatten();
1758
1759 EditorSnapshot {
1760 mode: self.mode,
1761 show_gutter: self.show_gutter,
1762 show_line_numbers: self.show_line_numbers,
1763 show_git_diff_gutter: self.show_git_diff_gutter,
1764 show_code_actions: self.show_code_actions,
1765 show_runnables: self.show_runnables,
1766 git_blame_gutter_max_author_length,
1767 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1768 scroll_anchor: self.scroll_manager.anchor(),
1769 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1770 placeholder_text: self.placeholder_text.clone(),
1771 is_focused: self.focus_handle.is_focused(window),
1772 current_line_highlight: self
1773 .current_line_highlight
1774 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1775 gutter_hovered: self.gutter_hovered,
1776 }
1777 }
1778
1779 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1780 self.buffer.read(cx).language_at(point, cx)
1781 }
1782
1783 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1784 self.buffer.read(cx).read(cx).file_at(point).cloned()
1785 }
1786
1787 pub fn active_excerpt(
1788 &self,
1789 cx: &App,
1790 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1791 self.buffer
1792 .read(cx)
1793 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1794 }
1795
1796 pub fn mode(&self) -> EditorMode {
1797 self.mode
1798 }
1799
1800 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1801 self.collaboration_hub.as_deref()
1802 }
1803
1804 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1805 self.collaboration_hub = Some(hub);
1806 }
1807
1808 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1809 self.in_project_search = in_project_search;
1810 }
1811
1812 pub fn set_custom_context_menu(
1813 &mut self,
1814 f: impl 'static
1815 + Fn(
1816 &mut Self,
1817 DisplayPoint,
1818 &mut Window,
1819 &mut Context<Self>,
1820 ) -> Option<Entity<ui::ContextMenu>>,
1821 ) {
1822 self.custom_context_menu = Some(Box::new(f))
1823 }
1824
1825 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1826 self.completion_provider = provider;
1827 }
1828
1829 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1830 self.semantics_provider.clone()
1831 }
1832
1833 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1834 self.semantics_provider = provider;
1835 }
1836
1837 pub fn set_edit_prediction_provider<T>(
1838 &mut self,
1839 provider: Option<Entity<T>>,
1840 window: &mut Window,
1841 cx: &mut Context<Self>,
1842 ) where
1843 T: EditPredictionProvider,
1844 {
1845 self.edit_prediction_provider =
1846 provider.map(|provider| RegisteredInlineCompletionProvider {
1847 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1848 if this.focus_handle.is_focused(window) {
1849 this.update_visible_inline_completion(window, cx);
1850 }
1851 }),
1852 provider: Arc::new(provider),
1853 });
1854 self.update_edit_prediction_settings(cx);
1855 self.refresh_inline_completion(false, false, window, cx);
1856 }
1857
1858 pub fn placeholder_text(&self) -> Option<&str> {
1859 self.placeholder_text.as_deref()
1860 }
1861
1862 pub fn set_placeholder_text(
1863 &mut self,
1864 placeholder_text: impl Into<Arc<str>>,
1865 cx: &mut Context<Self>,
1866 ) {
1867 let placeholder_text = Some(placeholder_text.into());
1868 if self.placeholder_text != placeholder_text {
1869 self.placeholder_text = placeholder_text;
1870 cx.notify();
1871 }
1872 }
1873
1874 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1875 self.cursor_shape = cursor_shape;
1876
1877 // Disrupt blink for immediate user feedback that the cursor shape has changed
1878 self.blink_manager.update(cx, BlinkManager::show_cursor);
1879
1880 cx.notify();
1881 }
1882
1883 pub fn set_current_line_highlight(
1884 &mut self,
1885 current_line_highlight: Option<CurrentLineHighlight>,
1886 ) {
1887 self.current_line_highlight = current_line_highlight;
1888 }
1889
1890 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1891 self.collapse_matches = collapse_matches;
1892 }
1893
1894 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1895 let buffers = self.buffer.read(cx).all_buffers();
1896 let Some(project) = self.project.as_ref() else {
1897 return;
1898 };
1899 project.update(cx, |project, cx| {
1900 for buffer in buffers {
1901 self.registered_buffers
1902 .entry(buffer.read(cx).remote_id())
1903 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1904 }
1905 })
1906 }
1907
1908 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1909 if self.collapse_matches {
1910 return range.start..range.start;
1911 }
1912 range.clone()
1913 }
1914
1915 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1916 if self.display_map.read(cx).clip_at_line_ends != clip {
1917 self.display_map
1918 .update(cx, |map, _| map.clip_at_line_ends = clip);
1919 }
1920 }
1921
1922 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1923 self.input_enabled = input_enabled;
1924 }
1925
1926 pub fn set_inline_completions_hidden_for_vim_mode(
1927 &mut self,
1928 hidden: bool,
1929 window: &mut Window,
1930 cx: &mut Context<Self>,
1931 ) {
1932 if hidden != self.inline_completions_hidden_for_vim_mode {
1933 self.inline_completions_hidden_for_vim_mode = hidden;
1934 if hidden {
1935 self.update_visible_inline_completion(window, cx);
1936 } else {
1937 self.refresh_inline_completion(true, false, window, cx);
1938 }
1939 }
1940 }
1941
1942 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1943 self.menu_inline_completions_policy = value;
1944 }
1945
1946 pub fn set_autoindent(&mut self, autoindent: bool) {
1947 if autoindent {
1948 self.autoindent_mode = Some(AutoindentMode::EachLine);
1949 } else {
1950 self.autoindent_mode = None;
1951 }
1952 }
1953
1954 pub fn read_only(&self, cx: &App) -> bool {
1955 self.read_only || self.buffer.read(cx).read_only()
1956 }
1957
1958 pub fn set_read_only(&mut self, read_only: bool) {
1959 self.read_only = read_only;
1960 }
1961
1962 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1963 self.use_autoclose = autoclose;
1964 }
1965
1966 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1967 self.use_auto_surround = auto_surround;
1968 }
1969
1970 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1971 self.auto_replace_emoji_shortcode = auto_replace;
1972 }
1973
1974 pub fn toggle_edit_predictions(
1975 &mut self,
1976 _: &ToggleEditPrediction,
1977 window: &mut Window,
1978 cx: &mut Context<Self>,
1979 ) {
1980 if self.show_inline_completions_override.is_some() {
1981 self.set_show_edit_predictions(None, window, cx);
1982 } else {
1983 let show_edit_predictions = !self.edit_predictions_enabled();
1984 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1985 }
1986 }
1987
1988 pub fn set_show_edit_predictions(
1989 &mut self,
1990 show_edit_predictions: Option<bool>,
1991 window: &mut Window,
1992 cx: &mut Context<Self>,
1993 ) {
1994 self.show_inline_completions_override = show_edit_predictions;
1995 self.update_edit_prediction_settings(cx);
1996
1997 if let Some(false) = show_edit_predictions {
1998 self.discard_inline_completion(false, cx);
1999 } else {
2000 self.refresh_inline_completion(false, true, window, cx);
2001 }
2002 }
2003
2004 fn inline_completions_disabled_in_scope(
2005 &self,
2006 buffer: &Entity<Buffer>,
2007 buffer_position: language::Anchor,
2008 cx: &App,
2009 ) -> bool {
2010 let snapshot = buffer.read(cx).snapshot();
2011 let settings = snapshot.settings_at(buffer_position, cx);
2012
2013 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2014 return false;
2015 };
2016
2017 scope.override_name().map_or(false, |scope_name| {
2018 settings
2019 .edit_predictions_disabled_in
2020 .iter()
2021 .any(|s| s == scope_name)
2022 })
2023 }
2024
2025 pub fn set_use_modal_editing(&mut self, to: bool) {
2026 self.use_modal_editing = to;
2027 }
2028
2029 pub fn use_modal_editing(&self) -> bool {
2030 self.use_modal_editing
2031 }
2032
2033 fn selections_did_change(
2034 &mut self,
2035 local: bool,
2036 old_cursor_position: &Anchor,
2037 show_completions: bool,
2038 window: &mut Window,
2039 cx: &mut Context<Self>,
2040 ) {
2041 window.invalidate_character_coordinates();
2042
2043 // Copy selections to primary selection buffer
2044 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2045 if local {
2046 let selections = self.selections.all::<usize>(cx);
2047 let buffer_handle = self.buffer.read(cx).read(cx);
2048
2049 let mut text = String::new();
2050 for (index, selection) in selections.iter().enumerate() {
2051 let text_for_selection = buffer_handle
2052 .text_for_range(selection.start..selection.end)
2053 .collect::<String>();
2054
2055 text.push_str(&text_for_selection);
2056 if index != selections.len() - 1 {
2057 text.push('\n');
2058 }
2059 }
2060
2061 if !text.is_empty() {
2062 cx.write_to_primary(ClipboardItem::new_string(text));
2063 }
2064 }
2065
2066 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2067 self.buffer.update(cx, |buffer, cx| {
2068 buffer.set_active_selections(
2069 &self.selections.disjoint_anchors(),
2070 self.selections.line_mode,
2071 self.cursor_shape,
2072 cx,
2073 )
2074 });
2075 }
2076 let display_map = self
2077 .display_map
2078 .update(cx, |display_map, cx| display_map.snapshot(cx));
2079 let buffer = &display_map.buffer_snapshot;
2080 self.add_selections_state = None;
2081 self.select_next_state = None;
2082 self.select_prev_state = None;
2083 self.select_larger_syntax_node_stack.clear();
2084 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2085 self.snippet_stack
2086 .invalidate(&self.selections.disjoint_anchors(), buffer);
2087 self.take_rename(false, window, cx);
2088
2089 let new_cursor_position = self.selections.newest_anchor().head();
2090
2091 self.push_to_nav_history(
2092 *old_cursor_position,
2093 Some(new_cursor_position.to_point(buffer)),
2094 cx,
2095 );
2096
2097 if local {
2098 let new_cursor_position = self.selections.newest_anchor().head();
2099 let mut context_menu = self.context_menu.borrow_mut();
2100 let completion_menu = match context_menu.as_ref() {
2101 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2102 _ => {
2103 *context_menu = None;
2104 None
2105 }
2106 };
2107 if let Some(buffer_id) = new_cursor_position.buffer_id {
2108 if !self.registered_buffers.contains_key(&buffer_id) {
2109 if let Some(project) = self.project.as_ref() {
2110 project.update(cx, |project, cx| {
2111 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2112 return;
2113 };
2114 self.registered_buffers.insert(
2115 buffer_id,
2116 project.register_buffer_with_language_servers(&buffer, cx),
2117 );
2118 })
2119 }
2120 }
2121 }
2122
2123 if let Some(completion_menu) = completion_menu {
2124 let cursor_position = new_cursor_position.to_offset(buffer);
2125 let (word_range, kind) =
2126 buffer.surrounding_word(completion_menu.initial_position, true);
2127 if kind == Some(CharKind::Word)
2128 && word_range.to_inclusive().contains(&cursor_position)
2129 {
2130 let mut completion_menu = completion_menu.clone();
2131 drop(context_menu);
2132
2133 let query = Self::completion_query(buffer, cursor_position);
2134 cx.spawn(move |this, mut cx| async move {
2135 completion_menu
2136 .filter(query.as_deref(), cx.background_executor().clone())
2137 .await;
2138
2139 this.update(&mut cx, |this, cx| {
2140 let mut context_menu = this.context_menu.borrow_mut();
2141 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2142 else {
2143 return;
2144 };
2145
2146 if menu.id > completion_menu.id {
2147 return;
2148 }
2149
2150 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2151 drop(context_menu);
2152 cx.notify();
2153 })
2154 })
2155 .detach();
2156
2157 if show_completions {
2158 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2159 }
2160 } else {
2161 drop(context_menu);
2162 self.hide_context_menu(window, cx);
2163 }
2164 } else {
2165 drop(context_menu);
2166 }
2167
2168 hide_hover(self, cx);
2169
2170 if old_cursor_position.to_display_point(&display_map).row()
2171 != new_cursor_position.to_display_point(&display_map).row()
2172 {
2173 self.available_code_actions.take();
2174 }
2175 self.refresh_code_actions(window, cx);
2176 self.refresh_document_highlights(cx);
2177 self.refresh_selected_text_highlights(window, cx);
2178 refresh_matching_bracket_highlights(self, window, cx);
2179 self.update_visible_inline_completion(window, cx);
2180 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2181 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2182 if self.git_blame_inline_enabled {
2183 self.start_inline_blame_timer(window, cx);
2184 }
2185 }
2186
2187 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2188 cx.emit(EditorEvent::SelectionsChanged { local });
2189
2190 let selections = &self.selections.disjoint;
2191 if selections.len() == 1 {
2192 cx.emit(SearchEvent::ActiveMatchChanged)
2193 }
2194 if local
2195 && self.is_singleton(cx)
2196 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2197 {
2198 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2199 let background_executor = cx.background_executor().clone();
2200 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2201 let snapshot = self.buffer().read(cx).snapshot(cx);
2202 let selections = selections.clone();
2203 self.serialize_selections = cx.background_spawn(async move {
2204 background_executor.timer(Duration::from_millis(100)).await;
2205 let selections = selections
2206 .iter()
2207 .map(|selection| {
2208 (
2209 selection.start.to_offset(&snapshot),
2210 selection.end.to_offset(&snapshot),
2211 )
2212 })
2213 .collect();
2214 DB.save_editor_selections(editor_id, workspace_id, selections)
2215 .await
2216 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2217 .log_err();
2218 });
2219 }
2220 }
2221
2222 cx.notify();
2223 }
2224
2225 pub fn sync_selections(
2226 &mut self,
2227 other: Entity<Editor>,
2228 cx: &mut Context<Self>,
2229 ) -> gpui::Subscription {
2230 let other_selections = other.read(cx).selections.disjoint.to_vec();
2231 self.selections.change_with(cx, |selections| {
2232 selections.select_anchors(other_selections);
2233 });
2234
2235 let other_subscription =
2236 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2237 EditorEvent::SelectionsChanged { local: true } => {
2238 let other_selections = other.read(cx).selections.disjoint.to_vec();
2239 if other_selections.is_empty() {
2240 return;
2241 }
2242 this.selections.change_with(cx, |selections| {
2243 selections.select_anchors(other_selections);
2244 });
2245 }
2246 _ => {}
2247 });
2248
2249 let this_subscription =
2250 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2251 EditorEvent::SelectionsChanged { local: true } => {
2252 let these_selections = this.selections.disjoint.to_vec();
2253 if these_selections.is_empty() {
2254 return;
2255 }
2256 other.update(cx, |other_editor, cx| {
2257 other_editor.selections.change_with(cx, |selections| {
2258 selections.select_anchors(these_selections);
2259 })
2260 });
2261 }
2262 _ => {}
2263 });
2264
2265 Subscription::join(other_subscription, this_subscription)
2266 }
2267
2268 pub fn change_selections<R>(
2269 &mut self,
2270 autoscroll: Option<Autoscroll>,
2271 window: &mut Window,
2272 cx: &mut Context<Self>,
2273 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2274 ) -> R {
2275 self.change_selections_inner(autoscroll, true, window, cx, change)
2276 }
2277
2278 fn change_selections_inner<R>(
2279 &mut self,
2280 autoscroll: Option<Autoscroll>,
2281 request_completions: bool,
2282 window: &mut Window,
2283 cx: &mut Context<Self>,
2284 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2285 ) -> R {
2286 let old_cursor_position = self.selections.newest_anchor().head();
2287 self.push_to_selection_history();
2288
2289 let (changed, result) = self.selections.change_with(cx, change);
2290
2291 if changed {
2292 if let Some(autoscroll) = autoscroll {
2293 self.request_autoscroll(autoscroll, cx);
2294 }
2295 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2296
2297 if self.should_open_signature_help_automatically(
2298 &old_cursor_position,
2299 self.signature_help_state.backspace_pressed(),
2300 cx,
2301 ) {
2302 self.show_signature_help(&ShowSignatureHelp, window, cx);
2303 }
2304 self.signature_help_state.set_backspace_pressed(false);
2305 }
2306
2307 result
2308 }
2309
2310 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2311 where
2312 I: IntoIterator<Item = (Range<S>, T)>,
2313 S: ToOffset,
2314 T: Into<Arc<str>>,
2315 {
2316 if self.read_only(cx) {
2317 return;
2318 }
2319
2320 self.buffer
2321 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2322 }
2323
2324 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2325 where
2326 I: IntoIterator<Item = (Range<S>, T)>,
2327 S: ToOffset,
2328 T: Into<Arc<str>>,
2329 {
2330 if self.read_only(cx) {
2331 return;
2332 }
2333
2334 self.buffer.update(cx, |buffer, cx| {
2335 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2336 });
2337 }
2338
2339 pub fn edit_with_block_indent<I, S, T>(
2340 &mut self,
2341 edits: I,
2342 original_indent_columns: Vec<Option<u32>>,
2343 cx: &mut Context<Self>,
2344 ) where
2345 I: IntoIterator<Item = (Range<S>, T)>,
2346 S: ToOffset,
2347 T: Into<Arc<str>>,
2348 {
2349 if self.read_only(cx) {
2350 return;
2351 }
2352
2353 self.buffer.update(cx, |buffer, cx| {
2354 buffer.edit(
2355 edits,
2356 Some(AutoindentMode::Block {
2357 original_indent_columns,
2358 }),
2359 cx,
2360 )
2361 });
2362 }
2363
2364 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2365 self.hide_context_menu(window, cx);
2366
2367 match phase {
2368 SelectPhase::Begin {
2369 position,
2370 add,
2371 click_count,
2372 } => self.begin_selection(position, add, click_count, window, cx),
2373 SelectPhase::BeginColumnar {
2374 position,
2375 goal_column,
2376 reset,
2377 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2378 SelectPhase::Extend {
2379 position,
2380 click_count,
2381 } => self.extend_selection(position, click_count, window, cx),
2382 SelectPhase::Update {
2383 position,
2384 goal_column,
2385 scroll_delta,
2386 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2387 SelectPhase::End => self.end_selection(window, cx),
2388 }
2389 }
2390
2391 fn extend_selection(
2392 &mut self,
2393 position: DisplayPoint,
2394 click_count: usize,
2395 window: &mut Window,
2396 cx: &mut Context<Self>,
2397 ) {
2398 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2399 let tail = self.selections.newest::<usize>(cx).tail();
2400 self.begin_selection(position, false, click_count, window, cx);
2401
2402 let position = position.to_offset(&display_map, Bias::Left);
2403 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2404
2405 let mut pending_selection = self
2406 .selections
2407 .pending_anchor()
2408 .expect("extend_selection not called with pending selection");
2409 if position >= tail {
2410 pending_selection.start = tail_anchor;
2411 } else {
2412 pending_selection.end = tail_anchor;
2413 pending_selection.reversed = true;
2414 }
2415
2416 let mut pending_mode = self.selections.pending_mode().unwrap();
2417 match &mut pending_mode {
2418 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2419 _ => {}
2420 }
2421
2422 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2423 s.set_pending(pending_selection, pending_mode)
2424 });
2425 }
2426
2427 fn begin_selection(
2428 &mut self,
2429 position: DisplayPoint,
2430 add: bool,
2431 click_count: usize,
2432 window: &mut Window,
2433 cx: &mut Context<Self>,
2434 ) {
2435 if !self.focus_handle.is_focused(window) {
2436 self.last_focused_descendant = None;
2437 window.focus(&self.focus_handle);
2438 }
2439
2440 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2441 let buffer = &display_map.buffer_snapshot;
2442 let newest_selection = self.selections.newest_anchor().clone();
2443 let position = display_map.clip_point(position, Bias::Left);
2444
2445 let start;
2446 let end;
2447 let mode;
2448 let mut auto_scroll;
2449 match click_count {
2450 1 => {
2451 start = buffer.anchor_before(position.to_point(&display_map));
2452 end = start;
2453 mode = SelectMode::Character;
2454 auto_scroll = true;
2455 }
2456 2 => {
2457 let range = movement::surrounding_word(&display_map, position);
2458 start = buffer.anchor_before(range.start.to_point(&display_map));
2459 end = buffer.anchor_before(range.end.to_point(&display_map));
2460 mode = SelectMode::Word(start..end);
2461 auto_scroll = true;
2462 }
2463 3 => {
2464 let position = display_map
2465 .clip_point(position, Bias::Left)
2466 .to_point(&display_map);
2467 let line_start = display_map.prev_line_boundary(position).0;
2468 let next_line_start = buffer.clip_point(
2469 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2470 Bias::Left,
2471 );
2472 start = buffer.anchor_before(line_start);
2473 end = buffer.anchor_before(next_line_start);
2474 mode = SelectMode::Line(start..end);
2475 auto_scroll = true;
2476 }
2477 _ => {
2478 start = buffer.anchor_before(0);
2479 end = buffer.anchor_before(buffer.len());
2480 mode = SelectMode::All;
2481 auto_scroll = false;
2482 }
2483 }
2484 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2485
2486 let point_to_delete: Option<usize> = {
2487 let selected_points: Vec<Selection<Point>> =
2488 self.selections.disjoint_in_range(start..end, cx);
2489
2490 if !add || click_count > 1 {
2491 None
2492 } else if !selected_points.is_empty() {
2493 Some(selected_points[0].id)
2494 } else {
2495 let clicked_point_already_selected =
2496 self.selections.disjoint.iter().find(|selection| {
2497 selection.start.to_point(buffer) == start.to_point(buffer)
2498 || selection.end.to_point(buffer) == end.to_point(buffer)
2499 });
2500
2501 clicked_point_already_selected.map(|selection| selection.id)
2502 }
2503 };
2504
2505 let selections_count = self.selections.count();
2506
2507 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2508 if let Some(point_to_delete) = point_to_delete {
2509 s.delete(point_to_delete);
2510
2511 if selections_count == 1 {
2512 s.set_pending_anchor_range(start..end, mode);
2513 }
2514 } else {
2515 if !add {
2516 s.clear_disjoint();
2517 } else if click_count > 1 {
2518 s.delete(newest_selection.id)
2519 }
2520
2521 s.set_pending_anchor_range(start..end, mode);
2522 }
2523 });
2524 }
2525
2526 fn begin_columnar_selection(
2527 &mut self,
2528 position: DisplayPoint,
2529 goal_column: u32,
2530 reset: bool,
2531 window: &mut Window,
2532 cx: &mut Context<Self>,
2533 ) {
2534 if !self.focus_handle.is_focused(window) {
2535 self.last_focused_descendant = None;
2536 window.focus(&self.focus_handle);
2537 }
2538
2539 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2540
2541 if reset {
2542 let pointer_position = display_map
2543 .buffer_snapshot
2544 .anchor_before(position.to_point(&display_map));
2545
2546 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2547 s.clear_disjoint();
2548 s.set_pending_anchor_range(
2549 pointer_position..pointer_position,
2550 SelectMode::Character,
2551 );
2552 });
2553 }
2554
2555 let tail = self.selections.newest::<Point>(cx).tail();
2556 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2557
2558 if !reset {
2559 self.select_columns(
2560 tail.to_display_point(&display_map),
2561 position,
2562 goal_column,
2563 &display_map,
2564 window,
2565 cx,
2566 );
2567 }
2568 }
2569
2570 fn update_selection(
2571 &mut self,
2572 position: DisplayPoint,
2573 goal_column: u32,
2574 scroll_delta: gpui::Point<f32>,
2575 window: &mut Window,
2576 cx: &mut Context<Self>,
2577 ) {
2578 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2579
2580 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2581 let tail = tail.to_display_point(&display_map);
2582 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2583 } else if let Some(mut pending) = self.selections.pending_anchor() {
2584 let buffer = self.buffer.read(cx).snapshot(cx);
2585 let head;
2586 let tail;
2587 let mode = self.selections.pending_mode().unwrap();
2588 match &mode {
2589 SelectMode::Character => {
2590 head = position.to_point(&display_map);
2591 tail = pending.tail().to_point(&buffer);
2592 }
2593 SelectMode::Word(original_range) => {
2594 let original_display_range = original_range.start.to_display_point(&display_map)
2595 ..original_range.end.to_display_point(&display_map);
2596 let original_buffer_range = original_display_range.start.to_point(&display_map)
2597 ..original_display_range.end.to_point(&display_map);
2598 if movement::is_inside_word(&display_map, position)
2599 || original_display_range.contains(&position)
2600 {
2601 let word_range = movement::surrounding_word(&display_map, position);
2602 if word_range.start < original_display_range.start {
2603 head = word_range.start.to_point(&display_map);
2604 } else {
2605 head = word_range.end.to_point(&display_map);
2606 }
2607 } else {
2608 head = position.to_point(&display_map);
2609 }
2610
2611 if head <= original_buffer_range.start {
2612 tail = original_buffer_range.end;
2613 } else {
2614 tail = original_buffer_range.start;
2615 }
2616 }
2617 SelectMode::Line(original_range) => {
2618 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2619
2620 let position = display_map
2621 .clip_point(position, Bias::Left)
2622 .to_point(&display_map);
2623 let line_start = display_map.prev_line_boundary(position).0;
2624 let next_line_start = buffer.clip_point(
2625 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2626 Bias::Left,
2627 );
2628
2629 if line_start < original_range.start {
2630 head = line_start
2631 } else {
2632 head = next_line_start
2633 }
2634
2635 if head <= original_range.start {
2636 tail = original_range.end;
2637 } else {
2638 tail = original_range.start;
2639 }
2640 }
2641 SelectMode::All => {
2642 return;
2643 }
2644 };
2645
2646 if head < tail {
2647 pending.start = buffer.anchor_before(head);
2648 pending.end = buffer.anchor_before(tail);
2649 pending.reversed = true;
2650 } else {
2651 pending.start = buffer.anchor_before(tail);
2652 pending.end = buffer.anchor_before(head);
2653 pending.reversed = false;
2654 }
2655
2656 self.change_selections(None, window, cx, |s| {
2657 s.set_pending(pending, mode);
2658 });
2659 } else {
2660 log::error!("update_selection dispatched with no pending selection");
2661 return;
2662 }
2663
2664 self.apply_scroll_delta(scroll_delta, window, cx);
2665 cx.notify();
2666 }
2667
2668 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2669 self.columnar_selection_tail.take();
2670 if self.selections.pending_anchor().is_some() {
2671 let selections = self.selections.all::<usize>(cx);
2672 self.change_selections(None, window, cx, |s| {
2673 s.select(selections);
2674 s.clear_pending();
2675 });
2676 }
2677 }
2678
2679 fn select_columns(
2680 &mut self,
2681 tail: DisplayPoint,
2682 head: DisplayPoint,
2683 goal_column: u32,
2684 display_map: &DisplaySnapshot,
2685 window: &mut Window,
2686 cx: &mut Context<Self>,
2687 ) {
2688 let start_row = cmp::min(tail.row(), head.row());
2689 let end_row = cmp::max(tail.row(), head.row());
2690 let start_column = cmp::min(tail.column(), goal_column);
2691 let end_column = cmp::max(tail.column(), goal_column);
2692 let reversed = start_column < tail.column();
2693
2694 let selection_ranges = (start_row.0..=end_row.0)
2695 .map(DisplayRow)
2696 .filter_map(|row| {
2697 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2698 let start = display_map
2699 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2700 .to_point(display_map);
2701 let end = display_map
2702 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2703 .to_point(display_map);
2704 if reversed {
2705 Some(end..start)
2706 } else {
2707 Some(start..end)
2708 }
2709 } else {
2710 None
2711 }
2712 })
2713 .collect::<Vec<_>>();
2714
2715 self.change_selections(None, window, cx, |s| {
2716 s.select_ranges(selection_ranges);
2717 });
2718 cx.notify();
2719 }
2720
2721 pub fn has_pending_nonempty_selection(&self) -> bool {
2722 let pending_nonempty_selection = match self.selections.pending_anchor() {
2723 Some(Selection { start, end, .. }) => start != end,
2724 None => false,
2725 };
2726
2727 pending_nonempty_selection
2728 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2729 }
2730
2731 pub fn has_pending_selection(&self) -> bool {
2732 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2733 }
2734
2735 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2736 self.selection_mark_mode = false;
2737
2738 if self.clear_expanded_diff_hunks(cx) {
2739 cx.notify();
2740 return;
2741 }
2742 if self.dismiss_menus_and_popups(true, window, cx) {
2743 return;
2744 }
2745
2746 if self.mode == EditorMode::Full
2747 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2748 {
2749 return;
2750 }
2751
2752 cx.propagate();
2753 }
2754
2755 pub fn dismiss_menus_and_popups(
2756 &mut self,
2757 is_user_requested: bool,
2758 window: &mut Window,
2759 cx: &mut Context<Self>,
2760 ) -> bool {
2761 if self.take_rename(false, window, cx).is_some() {
2762 return true;
2763 }
2764
2765 if hide_hover(self, cx) {
2766 return true;
2767 }
2768
2769 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2770 return true;
2771 }
2772
2773 if self.hide_context_menu(window, cx).is_some() {
2774 return true;
2775 }
2776
2777 if self.mouse_context_menu.take().is_some() {
2778 return true;
2779 }
2780
2781 if is_user_requested && self.discard_inline_completion(true, cx) {
2782 return true;
2783 }
2784
2785 if self.snippet_stack.pop().is_some() {
2786 return true;
2787 }
2788
2789 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2790 self.dismiss_diagnostics(cx);
2791 return true;
2792 }
2793
2794 false
2795 }
2796
2797 fn linked_editing_ranges_for(
2798 &self,
2799 selection: Range<text::Anchor>,
2800 cx: &App,
2801 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2802 if self.linked_edit_ranges.is_empty() {
2803 return None;
2804 }
2805 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2806 selection.end.buffer_id.and_then(|end_buffer_id| {
2807 if selection.start.buffer_id != Some(end_buffer_id) {
2808 return None;
2809 }
2810 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2811 let snapshot = buffer.read(cx).snapshot();
2812 self.linked_edit_ranges
2813 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2814 .map(|ranges| (ranges, snapshot, buffer))
2815 })?;
2816 use text::ToOffset as TO;
2817 // find offset from the start of current range to current cursor position
2818 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2819
2820 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2821 let start_difference = start_offset - start_byte_offset;
2822 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2823 let end_difference = end_offset - start_byte_offset;
2824 // Current range has associated linked ranges.
2825 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2826 for range in linked_ranges.iter() {
2827 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2828 let end_offset = start_offset + end_difference;
2829 let start_offset = start_offset + start_difference;
2830 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2831 continue;
2832 }
2833 if self.selections.disjoint_anchor_ranges().any(|s| {
2834 if s.start.buffer_id != selection.start.buffer_id
2835 || s.end.buffer_id != selection.end.buffer_id
2836 {
2837 return false;
2838 }
2839 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2840 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2841 }) {
2842 continue;
2843 }
2844 let start = buffer_snapshot.anchor_after(start_offset);
2845 let end = buffer_snapshot.anchor_after(end_offset);
2846 linked_edits
2847 .entry(buffer.clone())
2848 .or_default()
2849 .push(start..end);
2850 }
2851 Some(linked_edits)
2852 }
2853
2854 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2855 let text: Arc<str> = text.into();
2856
2857 if self.read_only(cx) {
2858 return;
2859 }
2860
2861 let selections = self.selections.all_adjusted(cx);
2862 let mut bracket_inserted = false;
2863 let mut edits = Vec::new();
2864 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2865 let mut new_selections = Vec::with_capacity(selections.len());
2866 let mut new_autoclose_regions = Vec::new();
2867 let snapshot = self.buffer.read(cx).read(cx);
2868
2869 for (selection, autoclose_region) in
2870 self.selections_with_autoclose_regions(selections, &snapshot)
2871 {
2872 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2873 // Determine if the inserted text matches the opening or closing
2874 // bracket of any of this language's bracket pairs.
2875 let mut bracket_pair = None;
2876 let mut is_bracket_pair_start = false;
2877 let mut is_bracket_pair_end = false;
2878 if !text.is_empty() {
2879 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2880 // and they are removing the character that triggered IME popup.
2881 for (pair, enabled) in scope.brackets() {
2882 if !pair.close && !pair.surround {
2883 continue;
2884 }
2885
2886 if enabled && pair.start.ends_with(text.as_ref()) {
2887 let prefix_len = pair.start.len() - text.len();
2888 let preceding_text_matches_prefix = prefix_len == 0
2889 || (selection.start.column >= (prefix_len as u32)
2890 && snapshot.contains_str_at(
2891 Point::new(
2892 selection.start.row,
2893 selection.start.column - (prefix_len as u32),
2894 ),
2895 &pair.start[..prefix_len],
2896 ));
2897 if preceding_text_matches_prefix {
2898 bracket_pair = Some(pair.clone());
2899 is_bracket_pair_start = true;
2900 break;
2901 }
2902 }
2903 if pair.end.as_str() == text.as_ref() {
2904 bracket_pair = Some(pair.clone());
2905 is_bracket_pair_end = true;
2906 break;
2907 }
2908 }
2909 }
2910
2911 if let Some(bracket_pair) = bracket_pair {
2912 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
2913 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2914 let auto_surround =
2915 self.use_auto_surround && snapshot_settings.use_auto_surround;
2916 if selection.is_empty() {
2917 if is_bracket_pair_start {
2918 // If the inserted text is a suffix of an opening bracket and the
2919 // selection is preceded by the rest of the opening bracket, then
2920 // insert the closing bracket.
2921 let following_text_allows_autoclose = snapshot
2922 .chars_at(selection.start)
2923 .next()
2924 .map_or(true, |c| scope.should_autoclose_before(c));
2925
2926 let preceding_text_allows_autoclose = selection.start.column == 0
2927 || snapshot.reversed_chars_at(selection.start).next().map_or(
2928 true,
2929 |c| {
2930 bracket_pair.start != bracket_pair.end
2931 || !snapshot
2932 .char_classifier_at(selection.start)
2933 .is_word(c)
2934 },
2935 );
2936
2937 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2938 && bracket_pair.start.len() == 1
2939 {
2940 let target = bracket_pair.start.chars().next().unwrap();
2941 let current_line_count = snapshot
2942 .reversed_chars_at(selection.start)
2943 .take_while(|&c| c != '\n')
2944 .filter(|&c| c == target)
2945 .count();
2946 current_line_count % 2 == 1
2947 } else {
2948 false
2949 };
2950
2951 if autoclose
2952 && bracket_pair.close
2953 && following_text_allows_autoclose
2954 && preceding_text_allows_autoclose
2955 && !is_closing_quote
2956 {
2957 let anchor = snapshot.anchor_before(selection.end);
2958 new_selections.push((selection.map(|_| anchor), text.len()));
2959 new_autoclose_regions.push((
2960 anchor,
2961 text.len(),
2962 selection.id,
2963 bracket_pair.clone(),
2964 ));
2965 edits.push((
2966 selection.range(),
2967 format!("{}{}", text, bracket_pair.end).into(),
2968 ));
2969 bracket_inserted = true;
2970 continue;
2971 }
2972 }
2973
2974 if let Some(region) = autoclose_region {
2975 // If the selection is followed by an auto-inserted closing bracket,
2976 // then don't insert that closing bracket again; just move the selection
2977 // past the closing bracket.
2978 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2979 && text.as_ref() == region.pair.end.as_str();
2980 if should_skip {
2981 let anchor = snapshot.anchor_after(selection.end);
2982 new_selections
2983 .push((selection.map(|_| anchor), region.pair.end.len()));
2984 continue;
2985 }
2986 }
2987
2988 let always_treat_brackets_as_autoclosed = snapshot
2989 .language_settings_at(selection.start, cx)
2990 .always_treat_brackets_as_autoclosed;
2991 if always_treat_brackets_as_autoclosed
2992 && is_bracket_pair_end
2993 && snapshot.contains_str_at(selection.end, text.as_ref())
2994 {
2995 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2996 // and the inserted text is a closing bracket and the selection is followed
2997 // by the closing bracket then move the selection past the closing bracket.
2998 let anchor = snapshot.anchor_after(selection.end);
2999 new_selections.push((selection.map(|_| anchor), text.len()));
3000 continue;
3001 }
3002 }
3003 // If an opening bracket is 1 character long and is typed while
3004 // text is selected, then surround that text with the bracket pair.
3005 else if auto_surround
3006 && bracket_pair.surround
3007 && is_bracket_pair_start
3008 && bracket_pair.start.chars().count() == 1
3009 {
3010 edits.push((selection.start..selection.start, text.clone()));
3011 edits.push((
3012 selection.end..selection.end,
3013 bracket_pair.end.as_str().into(),
3014 ));
3015 bracket_inserted = true;
3016 new_selections.push((
3017 Selection {
3018 id: selection.id,
3019 start: snapshot.anchor_after(selection.start),
3020 end: snapshot.anchor_before(selection.end),
3021 reversed: selection.reversed,
3022 goal: selection.goal,
3023 },
3024 0,
3025 ));
3026 continue;
3027 }
3028 }
3029 }
3030
3031 if self.auto_replace_emoji_shortcode
3032 && selection.is_empty()
3033 && text.as_ref().ends_with(':')
3034 {
3035 if let Some(possible_emoji_short_code) =
3036 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3037 {
3038 if !possible_emoji_short_code.is_empty() {
3039 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3040 let emoji_shortcode_start = Point::new(
3041 selection.start.row,
3042 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3043 );
3044
3045 // Remove shortcode from buffer
3046 edits.push((
3047 emoji_shortcode_start..selection.start,
3048 "".to_string().into(),
3049 ));
3050 new_selections.push((
3051 Selection {
3052 id: selection.id,
3053 start: snapshot.anchor_after(emoji_shortcode_start),
3054 end: snapshot.anchor_before(selection.start),
3055 reversed: selection.reversed,
3056 goal: selection.goal,
3057 },
3058 0,
3059 ));
3060
3061 // Insert emoji
3062 let selection_start_anchor = snapshot.anchor_after(selection.start);
3063 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3064 edits.push((selection.start..selection.end, emoji.to_string().into()));
3065
3066 continue;
3067 }
3068 }
3069 }
3070 }
3071
3072 // If not handling any auto-close operation, then just replace the selected
3073 // text with the given input and move the selection to the end of the
3074 // newly inserted text.
3075 let anchor = snapshot.anchor_after(selection.end);
3076 if !self.linked_edit_ranges.is_empty() {
3077 let start_anchor = snapshot.anchor_before(selection.start);
3078
3079 let is_word_char = text.chars().next().map_or(true, |char| {
3080 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3081 classifier.is_word(char)
3082 });
3083
3084 if is_word_char {
3085 if let Some(ranges) = self
3086 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3087 {
3088 for (buffer, edits) in ranges {
3089 linked_edits
3090 .entry(buffer.clone())
3091 .or_default()
3092 .extend(edits.into_iter().map(|range| (range, text.clone())));
3093 }
3094 }
3095 }
3096 }
3097
3098 new_selections.push((selection.map(|_| anchor), 0));
3099 edits.push((selection.start..selection.end, text.clone()));
3100 }
3101
3102 drop(snapshot);
3103
3104 self.transact(window, cx, |this, window, cx| {
3105 let initial_buffer_versions =
3106 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3107
3108 this.buffer.update(cx, |buffer, cx| {
3109 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3110 });
3111 for (buffer, edits) in linked_edits {
3112 buffer.update(cx, |buffer, cx| {
3113 let snapshot = buffer.snapshot();
3114 let edits = edits
3115 .into_iter()
3116 .map(|(range, text)| {
3117 use text::ToPoint as TP;
3118 let end_point = TP::to_point(&range.end, &snapshot);
3119 let start_point = TP::to_point(&range.start, &snapshot);
3120 (start_point..end_point, text)
3121 })
3122 .sorted_by_key(|(range, _)| range.start)
3123 .collect::<Vec<_>>();
3124 buffer.edit(edits, None, cx);
3125 })
3126 }
3127 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3128 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3129 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3130 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3131 .zip(new_selection_deltas)
3132 .map(|(selection, delta)| Selection {
3133 id: selection.id,
3134 start: selection.start + delta,
3135 end: selection.end + delta,
3136 reversed: selection.reversed,
3137 goal: SelectionGoal::None,
3138 })
3139 .collect::<Vec<_>>();
3140
3141 let mut i = 0;
3142 for (position, delta, selection_id, pair) in new_autoclose_regions {
3143 let position = position.to_offset(&map.buffer_snapshot) + delta;
3144 let start = map.buffer_snapshot.anchor_before(position);
3145 let end = map.buffer_snapshot.anchor_after(position);
3146 while let Some(existing_state) = this.autoclose_regions.get(i) {
3147 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3148 Ordering::Less => i += 1,
3149 Ordering::Greater => break,
3150 Ordering::Equal => {
3151 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3152 Ordering::Less => i += 1,
3153 Ordering::Equal => break,
3154 Ordering::Greater => break,
3155 }
3156 }
3157 }
3158 }
3159 this.autoclose_regions.insert(
3160 i,
3161 AutocloseRegion {
3162 selection_id,
3163 range: start..end,
3164 pair,
3165 },
3166 );
3167 }
3168
3169 let had_active_inline_completion = this.has_active_inline_completion();
3170 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3171 s.select(new_selections)
3172 });
3173
3174 if !bracket_inserted {
3175 if let Some(on_type_format_task) =
3176 this.trigger_on_type_formatting(text.to_string(), window, cx)
3177 {
3178 on_type_format_task.detach_and_log_err(cx);
3179 }
3180 }
3181
3182 let editor_settings = EditorSettings::get_global(cx);
3183 if bracket_inserted
3184 && (editor_settings.auto_signature_help
3185 || editor_settings.show_signature_help_after_edits)
3186 {
3187 this.show_signature_help(&ShowSignatureHelp, window, cx);
3188 }
3189
3190 let trigger_in_words =
3191 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3192 if this.hard_wrap.is_some() {
3193 let latest: Range<Point> = this.selections.newest(cx).range();
3194 if latest.is_empty()
3195 && this
3196 .buffer()
3197 .read(cx)
3198 .snapshot(cx)
3199 .line_len(MultiBufferRow(latest.start.row))
3200 == latest.start.column
3201 {
3202 this.rewrap_impl(true, cx)
3203 }
3204 }
3205 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3206 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3207 this.refresh_inline_completion(true, false, window, cx);
3208 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3209 });
3210 }
3211
3212 fn find_possible_emoji_shortcode_at_position(
3213 snapshot: &MultiBufferSnapshot,
3214 position: Point,
3215 ) -> Option<String> {
3216 let mut chars = Vec::new();
3217 let mut found_colon = false;
3218 for char in snapshot.reversed_chars_at(position).take(100) {
3219 // Found a possible emoji shortcode in the middle of the buffer
3220 if found_colon {
3221 if char.is_whitespace() {
3222 chars.reverse();
3223 return Some(chars.iter().collect());
3224 }
3225 // If the previous character is not a whitespace, we are in the middle of a word
3226 // and we only want to complete the shortcode if the word is made up of other emojis
3227 let mut containing_word = String::new();
3228 for ch in snapshot
3229 .reversed_chars_at(position)
3230 .skip(chars.len() + 1)
3231 .take(100)
3232 {
3233 if ch.is_whitespace() {
3234 break;
3235 }
3236 containing_word.push(ch);
3237 }
3238 let containing_word = containing_word.chars().rev().collect::<String>();
3239 if util::word_consists_of_emojis(containing_word.as_str()) {
3240 chars.reverse();
3241 return Some(chars.iter().collect());
3242 }
3243 }
3244
3245 if char.is_whitespace() || !char.is_ascii() {
3246 return None;
3247 }
3248 if char == ':' {
3249 found_colon = true;
3250 } else {
3251 chars.push(char);
3252 }
3253 }
3254 // Found a possible emoji shortcode at the beginning of the buffer
3255 chars.reverse();
3256 Some(chars.iter().collect())
3257 }
3258
3259 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3260 self.transact(window, cx, |this, window, cx| {
3261 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3262 let selections = this.selections.all::<usize>(cx);
3263 let multi_buffer = this.buffer.read(cx);
3264 let buffer = multi_buffer.snapshot(cx);
3265 selections
3266 .iter()
3267 .map(|selection| {
3268 let start_point = selection.start.to_point(&buffer);
3269 let mut indent =
3270 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3271 indent.len = cmp::min(indent.len, start_point.column);
3272 let start = selection.start;
3273 let end = selection.end;
3274 let selection_is_empty = start == end;
3275 let language_scope = buffer.language_scope_at(start);
3276 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3277 &language_scope
3278 {
3279 let insert_extra_newline =
3280 insert_extra_newline_brackets(&buffer, start..end, language)
3281 || insert_extra_newline_tree_sitter(&buffer, start..end);
3282
3283 // Comment extension on newline is allowed only for cursor selections
3284 let comment_delimiter = maybe!({
3285 if !selection_is_empty {
3286 return None;
3287 }
3288
3289 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3290 return None;
3291 }
3292
3293 let delimiters = language.line_comment_prefixes();
3294 let max_len_of_delimiter =
3295 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3296 let (snapshot, range) =
3297 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3298
3299 let mut index_of_first_non_whitespace = 0;
3300 let comment_candidate = snapshot
3301 .chars_for_range(range)
3302 .skip_while(|c| {
3303 let should_skip = c.is_whitespace();
3304 if should_skip {
3305 index_of_first_non_whitespace += 1;
3306 }
3307 should_skip
3308 })
3309 .take(max_len_of_delimiter)
3310 .collect::<String>();
3311 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3312 comment_candidate.starts_with(comment_prefix.as_ref())
3313 })?;
3314 let cursor_is_placed_after_comment_marker =
3315 index_of_first_non_whitespace + comment_prefix.len()
3316 <= start_point.column as usize;
3317 if cursor_is_placed_after_comment_marker {
3318 Some(comment_prefix.clone())
3319 } else {
3320 None
3321 }
3322 });
3323 (comment_delimiter, insert_extra_newline)
3324 } else {
3325 (None, false)
3326 };
3327
3328 let capacity_for_delimiter = comment_delimiter
3329 .as_deref()
3330 .map(str::len)
3331 .unwrap_or_default();
3332 let mut new_text =
3333 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3334 new_text.push('\n');
3335 new_text.extend(indent.chars());
3336 if let Some(delimiter) = &comment_delimiter {
3337 new_text.push_str(delimiter);
3338 }
3339 if insert_extra_newline {
3340 new_text = new_text.repeat(2);
3341 }
3342
3343 let anchor = buffer.anchor_after(end);
3344 let new_selection = selection.map(|_| anchor);
3345 (
3346 (start..end, new_text),
3347 (insert_extra_newline, new_selection),
3348 )
3349 })
3350 .unzip()
3351 };
3352
3353 this.edit_with_autoindent(edits, cx);
3354 let buffer = this.buffer.read(cx).snapshot(cx);
3355 let new_selections = selection_fixup_info
3356 .into_iter()
3357 .map(|(extra_newline_inserted, new_selection)| {
3358 let mut cursor = new_selection.end.to_point(&buffer);
3359 if extra_newline_inserted {
3360 cursor.row -= 1;
3361 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3362 }
3363 new_selection.map(|_| cursor)
3364 })
3365 .collect();
3366
3367 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3368 s.select(new_selections)
3369 });
3370 this.refresh_inline_completion(true, false, window, cx);
3371 });
3372 }
3373
3374 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3375 let buffer = self.buffer.read(cx);
3376 let snapshot = buffer.snapshot(cx);
3377
3378 let mut edits = Vec::new();
3379 let mut rows = Vec::new();
3380
3381 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3382 let cursor = selection.head();
3383 let row = cursor.row;
3384
3385 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3386
3387 let newline = "\n".to_string();
3388 edits.push((start_of_line..start_of_line, newline));
3389
3390 rows.push(row + rows_inserted as u32);
3391 }
3392
3393 self.transact(window, cx, |editor, window, cx| {
3394 editor.edit(edits, cx);
3395
3396 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3397 let mut index = 0;
3398 s.move_cursors_with(|map, _, _| {
3399 let row = rows[index];
3400 index += 1;
3401
3402 let point = Point::new(row, 0);
3403 let boundary = map.next_line_boundary(point).1;
3404 let clipped = map.clip_point(boundary, Bias::Left);
3405
3406 (clipped, SelectionGoal::None)
3407 });
3408 });
3409
3410 let mut indent_edits = Vec::new();
3411 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3412 for row in rows {
3413 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3414 for (row, indent) in indents {
3415 if indent.len == 0 {
3416 continue;
3417 }
3418
3419 let text = match indent.kind {
3420 IndentKind::Space => " ".repeat(indent.len as usize),
3421 IndentKind::Tab => "\t".repeat(indent.len as usize),
3422 };
3423 let point = Point::new(row.0, 0);
3424 indent_edits.push((point..point, text));
3425 }
3426 }
3427 editor.edit(indent_edits, cx);
3428 });
3429 }
3430
3431 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3432 let buffer = self.buffer.read(cx);
3433 let snapshot = buffer.snapshot(cx);
3434
3435 let mut edits = Vec::new();
3436 let mut rows = Vec::new();
3437 let mut rows_inserted = 0;
3438
3439 for selection in self.selections.all_adjusted(cx) {
3440 let cursor = selection.head();
3441 let row = cursor.row;
3442
3443 let point = Point::new(row + 1, 0);
3444 let start_of_line = snapshot.clip_point(point, Bias::Left);
3445
3446 let newline = "\n".to_string();
3447 edits.push((start_of_line..start_of_line, newline));
3448
3449 rows_inserted += 1;
3450 rows.push(row + rows_inserted);
3451 }
3452
3453 self.transact(window, cx, |editor, window, cx| {
3454 editor.edit(edits, cx);
3455
3456 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3457 let mut index = 0;
3458 s.move_cursors_with(|map, _, _| {
3459 let row = rows[index];
3460 index += 1;
3461
3462 let point = Point::new(row, 0);
3463 let boundary = map.next_line_boundary(point).1;
3464 let clipped = map.clip_point(boundary, Bias::Left);
3465
3466 (clipped, SelectionGoal::None)
3467 });
3468 });
3469
3470 let mut indent_edits = Vec::new();
3471 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3472 for row in rows {
3473 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3474 for (row, indent) in indents {
3475 if indent.len == 0 {
3476 continue;
3477 }
3478
3479 let text = match indent.kind {
3480 IndentKind::Space => " ".repeat(indent.len as usize),
3481 IndentKind::Tab => "\t".repeat(indent.len as usize),
3482 };
3483 let point = Point::new(row.0, 0);
3484 indent_edits.push((point..point, text));
3485 }
3486 }
3487 editor.edit(indent_edits, cx);
3488 });
3489 }
3490
3491 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3492 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3493 original_indent_columns: Vec::new(),
3494 });
3495 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3496 }
3497
3498 fn insert_with_autoindent_mode(
3499 &mut self,
3500 text: &str,
3501 autoindent_mode: Option<AutoindentMode>,
3502 window: &mut Window,
3503 cx: &mut Context<Self>,
3504 ) {
3505 if self.read_only(cx) {
3506 return;
3507 }
3508
3509 let text: Arc<str> = text.into();
3510 self.transact(window, cx, |this, window, cx| {
3511 let old_selections = this.selections.all_adjusted(cx);
3512 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3513 let anchors = {
3514 let snapshot = buffer.read(cx);
3515 old_selections
3516 .iter()
3517 .map(|s| {
3518 let anchor = snapshot.anchor_after(s.head());
3519 s.map(|_| anchor)
3520 })
3521 .collect::<Vec<_>>()
3522 };
3523 buffer.edit(
3524 old_selections
3525 .iter()
3526 .map(|s| (s.start..s.end, text.clone())),
3527 autoindent_mode,
3528 cx,
3529 );
3530 anchors
3531 });
3532
3533 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3534 s.select_anchors(selection_anchors);
3535 });
3536
3537 cx.notify();
3538 });
3539 }
3540
3541 fn trigger_completion_on_input(
3542 &mut self,
3543 text: &str,
3544 trigger_in_words: bool,
3545 window: &mut Window,
3546 cx: &mut Context<Self>,
3547 ) {
3548 if self.is_completion_trigger(text, trigger_in_words, cx) {
3549 self.show_completions(
3550 &ShowCompletions {
3551 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3552 },
3553 window,
3554 cx,
3555 );
3556 } else {
3557 self.hide_context_menu(window, cx);
3558 }
3559 }
3560
3561 fn is_completion_trigger(
3562 &self,
3563 text: &str,
3564 trigger_in_words: bool,
3565 cx: &mut Context<Self>,
3566 ) -> bool {
3567 let position = self.selections.newest_anchor().head();
3568 let multibuffer = self.buffer.read(cx);
3569 let Some(buffer) = position
3570 .buffer_id
3571 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3572 else {
3573 return false;
3574 };
3575
3576 if let Some(completion_provider) = &self.completion_provider {
3577 completion_provider.is_completion_trigger(
3578 &buffer,
3579 position.text_anchor,
3580 text,
3581 trigger_in_words,
3582 cx,
3583 )
3584 } else {
3585 false
3586 }
3587 }
3588
3589 /// If any empty selections is touching the start of its innermost containing autoclose
3590 /// region, expand it to select the brackets.
3591 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3592 let selections = self.selections.all::<usize>(cx);
3593 let buffer = self.buffer.read(cx).read(cx);
3594 let new_selections = self
3595 .selections_with_autoclose_regions(selections, &buffer)
3596 .map(|(mut selection, region)| {
3597 if !selection.is_empty() {
3598 return selection;
3599 }
3600
3601 if let Some(region) = region {
3602 let mut range = region.range.to_offset(&buffer);
3603 if selection.start == range.start && range.start >= region.pair.start.len() {
3604 range.start -= region.pair.start.len();
3605 if buffer.contains_str_at(range.start, ®ion.pair.start)
3606 && buffer.contains_str_at(range.end, ®ion.pair.end)
3607 {
3608 range.end += region.pair.end.len();
3609 selection.start = range.start;
3610 selection.end = range.end;
3611
3612 return selection;
3613 }
3614 }
3615 }
3616
3617 let always_treat_brackets_as_autoclosed = buffer
3618 .language_settings_at(selection.start, cx)
3619 .always_treat_brackets_as_autoclosed;
3620
3621 if !always_treat_brackets_as_autoclosed {
3622 return selection;
3623 }
3624
3625 if let Some(scope) = buffer.language_scope_at(selection.start) {
3626 for (pair, enabled) in scope.brackets() {
3627 if !enabled || !pair.close {
3628 continue;
3629 }
3630
3631 if buffer.contains_str_at(selection.start, &pair.end) {
3632 let pair_start_len = pair.start.len();
3633 if buffer.contains_str_at(
3634 selection.start.saturating_sub(pair_start_len),
3635 &pair.start,
3636 ) {
3637 selection.start -= pair_start_len;
3638 selection.end += pair.end.len();
3639
3640 return selection;
3641 }
3642 }
3643 }
3644 }
3645
3646 selection
3647 })
3648 .collect();
3649
3650 drop(buffer);
3651 self.change_selections(None, window, cx, |selections| {
3652 selections.select(new_selections)
3653 });
3654 }
3655
3656 /// Iterate the given selections, and for each one, find the smallest surrounding
3657 /// autoclose region. This uses the ordering of the selections and the autoclose
3658 /// regions to avoid repeated comparisons.
3659 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3660 &'a self,
3661 selections: impl IntoIterator<Item = Selection<D>>,
3662 buffer: &'a MultiBufferSnapshot,
3663 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3664 let mut i = 0;
3665 let mut regions = self.autoclose_regions.as_slice();
3666 selections.into_iter().map(move |selection| {
3667 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3668
3669 let mut enclosing = None;
3670 while let Some(pair_state) = regions.get(i) {
3671 if pair_state.range.end.to_offset(buffer) < range.start {
3672 regions = ®ions[i + 1..];
3673 i = 0;
3674 } else if pair_state.range.start.to_offset(buffer) > range.end {
3675 break;
3676 } else {
3677 if pair_state.selection_id == selection.id {
3678 enclosing = Some(pair_state);
3679 }
3680 i += 1;
3681 }
3682 }
3683
3684 (selection, enclosing)
3685 })
3686 }
3687
3688 /// Remove any autoclose regions that no longer contain their selection.
3689 fn invalidate_autoclose_regions(
3690 &mut self,
3691 mut selections: &[Selection<Anchor>],
3692 buffer: &MultiBufferSnapshot,
3693 ) {
3694 self.autoclose_regions.retain(|state| {
3695 let mut i = 0;
3696 while let Some(selection) = selections.get(i) {
3697 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3698 selections = &selections[1..];
3699 continue;
3700 }
3701 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3702 break;
3703 }
3704 if selection.id == state.selection_id {
3705 return true;
3706 } else {
3707 i += 1;
3708 }
3709 }
3710 false
3711 });
3712 }
3713
3714 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3715 let offset = position.to_offset(buffer);
3716 let (word_range, kind) = buffer.surrounding_word(offset, true);
3717 if offset > word_range.start && kind == Some(CharKind::Word) {
3718 Some(
3719 buffer
3720 .text_for_range(word_range.start..offset)
3721 .collect::<String>(),
3722 )
3723 } else {
3724 None
3725 }
3726 }
3727
3728 pub fn toggle_inlay_hints(
3729 &mut self,
3730 _: &ToggleInlayHints,
3731 _: &mut Window,
3732 cx: &mut Context<Self>,
3733 ) {
3734 self.refresh_inlay_hints(
3735 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3736 cx,
3737 );
3738 }
3739
3740 pub fn inlay_hints_enabled(&self) -> bool {
3741 self.inlay_hint_cache.enabled
3742 }
3743
3744 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3745 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3746 return;
3747 }
3748
3749 let reason_description = reason.description();
3750 let ignore_debounce = matches!(
3751 reason,
3752 InlayHintRefreshReason::SettingsChange(_)
3753 | InlayHintRefreshReason::Toggle(_)
3754 | InlayHintRefreshReason::ExcerptsRemoved(_)
3755 | InlayHintRefreshReason::ModifiersChanged(_)
3756 );
3757 let (invalidate_cache, required_languages) = match reason {
3758 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3759 match self.inlay_hint_cache.modifiers_override(enabled) {
3760 Some(enabled) => {
3761 if enabled {
3762 (InvalidationStrategy::RefreshRequested, None)
3763 } else {
3764 self.splice_inlays(
3765 &self
3766 .visible_inlay_hints(cx)
3767 .iter()
3768 .map(|inlay| inlay.id)
3769 .collect::<Vec<InlayId>>(),
3770 Vec::new(),
3771 cx,
3772 );
3773 return;
3774 }
3775 }
3776 None => return,
3777 }
3778 }
3779 InlayHintRefreshReason::Toggle(enabled) => {
3780 if self.inlay_hint_cache.toggle(enabled) {
3781 if enabled {
3782 (InvalidationStrategy::RefreshRequested, None)
3783 } else {
3784 self.splice_inlays(
3785 &self
3786 .visible_inlay_hints(cx)
3787 .iter()
3788 .map(|inlay| inlay.id)
3789 .collect::<Vec<InlayId>>(),
3790 Vec::new(),
3791 cx,
3792 );
3793 return;
3794 }
3795 } else {
3796 return;
3797 }
3798 }
3799 InlayHintRefreshReason::SettingsChange(new_settings) => {
3800 match self.inlay_hint_cache.update_settings(
3801 &self.buffer,
3802 new_settings,
3803 self.visible_inlay_hints(cx),
3804 cx,
3805 ) {
3806 ControlFlow::Break(Some(InlaySplice {
3807 to_remove,
3808 to_insert,
3809 })) => {
3810 self.splice_inlays(&to_remove, to_insert, cx);
3811 return;
3812 }
3813 ControlFlow::Break(None) => return,
3814 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3815 }
3816 }
3817 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3818 if let Some(InlaySplice {
3819 to_remove,
3820 to_insert,
3821 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3822 {
3823 self.splice_inlays(&to_remove, to_insert, cx);
3824 }
3825 return;
3826 }
3827 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3828 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3829 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3830 }
3831 InlayHintRefreshReason::RefreshRequested => {
3832 (InvalidationStrategy::RefreshRequested, None)
3833 }
3834 };
3835
3836 if let Some(InlaySplice {
3837 to_remove,
3838 to_insert,
3839 }) = self.inlay_hint_cache.spawn_hint_refresh(
3840 reason_description,
3841 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3842 invalidate_cache,
3843 ignore_debounce,
3844 cx,
3845 ) {
3846 self.splice_inlays(&to_remove, to_insert, cx);
3847 }
3848 }
3849
3850 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3851 self.display_map
3852 .read(cx)
3853 .current_inlays()
3854 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3855 .cloned()
3856 .collect()
3857 }
3858
3859 pub fn excerpts_for_inlay_hints_query(
3860 &self,
3861 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3862 cx: &mut Context<Editor>,
3863 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3864 let Some(project) = self.project.as_ref() else {
3865 return HashMap::default();
3866 };
3867 let project = project.read(cx);
3868 let multi_buffer = self.buffer().read(cx);
3869 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3870 let multi_buffer_visible_start = self
3871 .scroll_manager
3872 .anchor()
3873 .anchor
3874 .to_point(&multi_buffer_snapshot);
3875 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3876 multi_buffer_visible_start
3877 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3878 Bias::Left,
3879 );
3880 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3881 multi_buffer_snapshot
3882 .range_to_buffer_ranges(multi_buffer_visible_range)
3883 .into_iter()
3884 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3885 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3886 let buffer_file = project::File::from_dyn(buffer.file())?;
3887 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3888 let worktree_entry = buffer_worktree
3889 .read(cx)
3890 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3891 if worktree_entry.is_ignored {
3892 return None;
3893 }
3894
3895 let language = buffer.language()?;
3896 if let Some(restrict_to_languages) = restrict_to_languages {
3897 if !restrict_to_languages.contains(language) {
3898 return None;
3899 }
3900 }
3901 Some((
3902 excerpt_id,
3903 (
3904 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3905 buffer.version().clone(),
3906 excerpt_visible_range,
3907 ),
3908 ))
3909 })
3910 .collect()
3911 }
3912
3913 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3914 TextLayoutDetails {
3915 text_system: window.text_system().clone(),
3916 editor_style: self.style.clone().unwrap(),
3917 rem_size: window.rem_size(),
3918 scroll_anchor: self.scroll_manager.anchor(),
3919 visible_rows: self.visible_line_count(),
3920 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3921 }
3922 }
3923
3924 pub fn splice_inlays(
3925 &self,
3926 to_remove: &[InlayId],
3927 to_insert: Vec<Inlay>,
3928 cx: &mut Context<Self>,
3929 ) {
3930 self.display_map.update(cx, |display_map, cx| {
3931 display_map.splice_inlays(to_remove, to_insert, cx)
3932 });
3933 cx.notify();
3934 }
3935
3936 fn trigger_on_type_formatting(
3937 &self,
3938 input: String,
3939 window: &mut Window,
3940 cx: &mut Context<Self>,
3941 ) -> Option<Task<Result<()>>> {
3942 if input.len() != 1 {
3943 return None;
3944 }
3945
3946 let project = self.project.as_ref()?;
3947 let position = self.selections.newest_anchor().head();
3948 let (buffer, buffer_position) = self
3949 .buffer
3950 .read(cx)
3951 .text_anchor_for_position(position, cx)?;
3952
3953 let settings = language_settings::language_settings(
3954 buffer
3955 .read(cx)
3956 .language_at(buffer_position)
3957 .map(|l| l.name()),
3958 buffer.read(cx).file(),
3959 cx,
3960 );
3961 if !settings.use_on_type_format {
3962 return None;
3963 }
3964
3965 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3966 // hence we do LSP request & edit on host side only — add formats to host's history.
3967 let push_to_lsp_host_history = true;
3968 // If this is not the host, append its history with new edits.
3969 let push_to_client_history = project.read(cx).is_via_collab();
3970
3971 let on_type_formatting = project.update(cx, |project, cx| {
3972 project.on_type_format(
3973 buffer.clone(),
3974 buffer_position,
3975 input,
3976 push_to_lsp_host_history,
3977 cx,
3978 )
3979 });
3980 Some(cx.spawn_in(window, |editor, mut cx| async move {
3981 if let Some(transaction) = on_type_formatting.await? {
3982 if push_to_client_history {
3983 buffer
3984 .update(&mut cx, |buffer, _| {
3985 buffer.push_transaction(transaction, Instant::now());
3986 })
3987 .ok();
3988 }
3989 editor.update(&mut cx, |editor, cx| {
3990 editor.refresh_document_highlights(cx);
3991 })?;
3992 }
3993 Ok(())
3994 }))
3995 }
3996
3997 pub fn show_word_completions(
3998 &mut self,
3999 _: &ShowWordCompletions,
4000 window: &mut Window,
4001 cx: &mut Context<Self>,
4002 ) {
4003 self.open_completions_menu(true, None, window, cx);
4004 }
4005
4006 pub fn show_completions(
4007 &mut self,
4008 options: &ShowCompletions,
4009 window: &mut Window,
4010 cx: &mut Context<Self>,
4011 ) {
4012 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4013 }
4014
4015 fn open_completions_menu(
4016 &mut self,
4017 ignore_completion_provider: bool,
4018 trigger: Option<&str>,
4019 window: &mut Window,
4020 cx: &mut Context<Self>,
4021 ) {
4022 if self.pending_rename.is_some() {
4023 return;
4024 }
4025 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4026 return;
4027 }
4028
4029 let position = self.selections.newest_anchor().head();
4030 if position.diff_base_anchor.is_some() {
4031 return;
4032 }
4033 let (buffer, buffer_position) =
4034 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4035 output
4036 } else {
4037 return;
4038 };
4039 let buffer_snapshot = buffer.read(cx).snapshot();
4040 let show_completion_documentation = buffer_snapshot
4041 .settings_at(buffer_position, cx)
4042 .show_completion_documentation;
4043
4044 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4045
4046 let trigger_kind = match trigger {
4047 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4048 CompletionTriggerKind::TRIGGER_CHARACTER
4049 }
4050 _ => CompletionTriggerKind::INVOKED,
4051 };
4052 let completion_context = CompletionContext {
4053 trigger_character: trigger.and_then(|trigger| {
4054 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4055 Some(String::from(trigger))
4056 } else {
4057 None
4058 }
4059 }),
4060 trigger_kind,
4061 };
4062
4063 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4064 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4065 let word_to_exclude = buffer_snapshot
4066 .text_for_range(old_range.clone())
4067 .collect::<String>();
4068 (
4069 buffer_snapshot.anchor_before(old_range.start)
4070 ..buffer_snapshot.anchor_after(old_range.end),
4071 Some(word_to_exclude),
4072 )
4073 } else {
4074 (buffer_position..buffer_position, None)
4075 };
4076
4077 let completion_settings = language_settings(
4078 buffer_snapshot
4079 .language_at(buffer_position)
4080 .map(|language| language.name()),
4081 buffer_snapshot.file(),
4082 cx,
4083 )
4084 .completions;
4085
4086 // The document can be large, so stay in reasonable bounds when searching for words,
4087 // otherwise completion pop-up might be slow to appear.
4088 const WORD_LOOKUP_ROWS: u32 = 5_000;
4089 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4090 let min_word_search = buffer_snapshot.clip_point(
4091 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4092 Bias::Left,
4093 );
4094 let max_word_search = buffer_snapshot.clip_point(
4095 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4096 Bias::Right,
4097 );
4098 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4099 ..buffer_snapshot.point_to_offset(max_word_search);
4100
4101 let provider = self
4102 .completion_provider
4103 .as_ref()
4104 .filter(|_| !ignore_completion_provider);
4105 let skip_digits = query
4106 .as_ref()
4107 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4108
4109 let (mut words, provided_completions) = match provider {
4110 Some(provider) => {
4111 let completions =
4112 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4113
4114 let words = match completion_settings.words {
4115 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4116 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4117 .background_spawn(async move {
4118 buffer_snapshot.words_in_range(WordsQuery {
4119 fuzzy_contents: None,
4120 range: word_search_range,
4121 skip_digits,
4122 })
4123 }),
4124 };
4125
4126 (words, completions)
4127 }
4128 None => (
4129 cx.background_spawn(async move {
4130 buffer_snapshot.words_in_range(WordsQuery {
4131 fuzzy_contents: None,
4132 range: word_search_range,
4133 skip_digits,
4134 })
4135 }),
4136 Task::ready(Ok(None)),
4137 ),
4138 };
4139
4140 let sort_completions = provider
4141 .as_ref()
4142 .map_or(true, |provider| provider.sort_completions());
4143
4144 let id = post_inc(&mut self.next_completion_id);
4145 let task = cx.spawn_in(window, |editor, mut cx| {
4146 async move {
4147 editor.update(&mut cx, |this, _| {
4148 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4149 })?;
4150
4151 let mut completions = Vec::new();
4152 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4153 completions.extend(provided_completions);
4154 if completion_settings.words == WordsCompletionMode::Fallback {
4155 words = Task::ready(HashMap::default());
4156 }
4157 }
4158
4159 let mut words = words.await;
4160 if let Some(word_to_exclude) = &word_to_exclude {
4161 words.remove(word_to_exclude);
4162 }
4163 for lsp_completion in &completions {
4164 words.remove(&lsp_completion.new_text);
4165 }
4166 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4167 old_range: old_range.clone(),
4168 new_text: word.clone(),
4169 label: CodeLabel::plain(word, None),
4170 documentation: None,
4171 source: CompletionSource::BufferWord {
4172 word_range,
4173 resolved: false,
4174 },
4175 confirm: None,
4176 }));
4177
4178 let menu = if completions.is_empty() {
4179 None
4180 } else {
4181 let mut menu = CompletionsMenu::new(
4182 id,
4183 sort_completions,
4184 show_completion_documentation,
4185 position,
4186 buffer.clone(),
4187 completions.into(),
4188 );
4189
4190 menu.filter(query.as_deref(), cx.background_executor().clone())
4191 .await;
4192
4193 menu.visible().then_some(menu)
4194 };
4195
4196 editor.update_in(&mut cx, |editor, window, cx| {
4197 match editor.context_menu.borrow().as_ref() {
4198 None => {}
4199 Some(CodeContextMenu::Completions(prev_menu)) => {
4200 if prev_menu.id > id {
4201 return;
4202 }
4203 }
4204 _ => return,
4205 }
4206
4207 if editor.focus_handle.is_focused(window) && menu.is_some() {
4208 let mut menu = menu.unwrap();
4209 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4210
4211 *editor.context_menu.borrow_mut() =
4212 Some(CodeContextMenu::Completions(menu));
4213
4214 if editor.show_edit_predictions_in_menu() {
4215 editor.update_visible_inline_completion(window, cx);
4216 } else {
4217 editor.discard_inline_completion(false, cx);
4218 }
4219
4220 cx.notify();
4221 } else if editor.completion_tasks.len() <= 1 {
4222 // If there are no more completion tasks and the last menu was
4223 // empty, we should hide it.
4224 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4225 // If it was already hidden and we don't show inline
4226 // completions in the menu, we should also show the
4227 // inline-completion when available.
4228 if was_hidden && editor.show_edit_predictions_in_menu() {
4229 editor.update_visible_inline_completion(window, cx);
4230 }
4231 }
4232 })?;
4233
4234 anyhow::Ok(())
4235 }
4236 .log_err()
4237 });
4238
4239 self.completion_tasks.push((id, task));
4240 }
4241
4242 pub fn confirm_completion(
4243 &mut self,
4244 action: &ConfirmCompletion,
4245 window: &mut Window,
4246 cx: &mut Context<Self>,
4247 ) -> Option<Task<Result<()>>> {
4248 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4249 }
4250
4251 pub fn compose_completion(
4252 &mut self,
4253 action: &ComposeCompletion,
4254 window: &mut Window,
4255 cx: &mut Context<Self>,
4256 ) -> Option<Task<Result<()>>> {
4257 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4258 }
4259
4260 fn do_completion(
4261 &mut self,
4262 item_ix: Option<usize>,
4263 intent: CompletionIntent,
4264 window: &mut Window,
4265 cx: &mut Context<Editor>,
4266 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4267 use language::ToOffset as _;
4268
4269 let completions_menu =
4270 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4271 menu
4272 } else {
4273 return None;
4274 };
4275
4276 let entries = completions_menu.entries.borrow();
4277 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4278 if self.show_edit_predictions_in_menu() {
4279 self.discard_inline_completion(true, cx);
4280 }
4281 let candidate_id = mat.candidate_id;
4282 drop(entries);
4283
4284 let buffer_handle = completions_menu.buffer;
4285 let completion = completions_menu
4286 .completions
4287 .borrow()
4288 .get(candidate_id)?
4289 .clone();
4290 cx.stop_propagation();
4291
4292 let snippet;
4293 let text;
4294
4295 if completion.is_snippet() {
4296 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4297 text = snippet.as_ref().unwrap().text.clone();
4298 } else {
4299 snippet = None;
4300 text = completion.new_text.clone();
4301 };
4302 let selections = self.selections.all::<usize>(cx);
4303 let buffer = buffer_handle.read(cx);
4304 let old_range = completion.old_range.to_offset(buffer);
4305 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4306
4307 let newest_selection = self.selections.newest_anchor();
4308 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4309 return None;
4310 }
4311
4312 let lookbehind = newest_selection
4313 .start
4314 .text_anchor
4315 .to_offset(buffer)
4316 .saturating_sub(old_range.start);
4317 let lookahead = old_range
4318 .end
4319 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4320 let mut common_prefix_len = old_text
4321 .bytes()
4322 .zip(text.bytes())
4323 .take_while(|(a, b)| a == b)
4324 .count();
4325
4326 let snapshot = self.buffer.read(cx).snapshot(cx);
4327 let mut range_to_replace: Option<Range<isize>> = None;
4328 let mut ranges = Vec::new();
4329 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4330 for selection in &selections {
4331 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4332 let start = selection.start.saturating_sub(lookbehind);
4333 let end = selection.end + lookahead;
4334 if selection.id == newest_selection.id {
4335 range_to_replace = Some(
4336 ((start + common_prefix_len) as isize - selection.start as isize)
4337 ..(end as isize - selection.start as isize),
4338 );
4339 }
4340 ranges.push(start + common_prefix_len..end);
4341 } else {
4342 common_prefix_len = 0;
4343 ranges.clear();
4344 ranges.extend(selections.iter().map(|s| {
4345 if s.id == newest_selection.id {
4346 range_to_replace = Some(
4347 old_range.start.to_offset_utf16(&snapshot).0 as isize
4348 - selection.start as isize
4349 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4350 - selection.start as isize,
4351 );
4352 old_range.clone()
4353 } else {
4354 s.start..s.end
4355 }
4356 }));
4357 break;
4358 }
4359 if !self.linked_edit_ranges.is_empty() {
4360 let start_anchor = snapshot.anchor_before(selection.head());
4361 let end_anchor = snapshot.anchor_after(selection.tail());
4362 if let Some(ranges) = self
4363 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4364 {
4365 for (buffer, edits) in ranges {
4366 linked_edits.entry(buffer.clone()).or_default().extend(
4367 edits
4368 .into_iter()
4369 .map(|range| (range, text[common_prefix_len..].to_owned())),
4370 );
4371 }
4372 }
4373 }
4374 }
4375 let text = &text[common_prefix_len..];
4376
4377 cx.emit(EditorEvent::InputHandled {
4378 utf16_range_to_replace: range_to_replace,
4379 text: text.into(),
4380 });
4381
4382 self.transact(window, cx, |this, window, cx| {
4383 if let Some(mut snippet) = snippet {
4384 snippet.text = text.to_string();
4385 for tabstop in snippet
4386 .tabstops
4387 .iter_mut()
4388 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4389 {
4390 tabstop.start -= common_prefix_len as isize;
4391 tabstop.end -= common_prefix_len as isize;
4392 }
4393
4394 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4395 } else {
4396 this.buffer.update(cx, |buffer, cx| {
4397 buffer.edit(
4398 ranges.iter().map(|range| (range.clone(), text)),
4399 this.autoindent_mode.clone(),
4400 cx,
4401 );
4402 });
4403 }
4404 for (buffer, edits) in linked_edits {
4405 buffer.update(cx, |buffer, cx| {
4406 let snapshot = buffer.snapshot();
4407 let edits = edits
4408 .into_iter()
4409 .map(|(range, text)| {
4410 use text::ToPoint as TP;
4411 let end_point = TP::to_point(&range.end, &snapshot);
4412 let start_point = TP::to_point(&range.start, &snapshot);
4413 (start_point..end_point, text)
4414 })
4415 .sorted_by_key(|(range, _)| range.start)
4416 .collect::<Vec<_>>();
4417 buffer.edit(edits, None, cx);
4418 })
4419 }
4420
4421 this.refresh_inline_completion(true, false, window, cx);
4422 });
4423
4424 let show_new_completions_on_confirm = completion
4425 .confirm
4426 .as_ref()
4427 .map_or(false, |confirm| confirm(intent, window, cx));
4428 if show_new_completions_on_confirm {
4429 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4430 }
4431
4432 let provider = self.completion_provider.as_ref()?;
4433 drop(completion);
4434 let apply_edits = provider.apply_additional_edits_for_completion(
4435 buffer_handle,
4436 completions_menu.completions.clone(),
4437 candidate_id,
4438 true,
4439 cx,
4440 );
4441
4442 let editor_settings = EditorSettings::get_global(cx);
4443 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4444 // After the code completion is finished, users often want to know what signatures are needed.
4445 // so we should automatically call signature_help
4446 self.show_signature_help(&ShowSignatureHelp, window, cx);
4447 }
4448
4449 Some(cx.foreground_executor().spawn(async move {
4450 apply_edits.await?;
4451 Ok(())
4452 }))
4453 }
4454
4455 pub fn toggle_code_actions(
4456 &mut self,
4457 action: &ToggleCodeActions,
4458 window: &mut Window,
4459 cx: &mut Context<Self>,
4460 ) {
4461 let mut context_menu = self.context_menu.borrow_mut();
4462 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4463 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4464 // Toggle if we're selecting the same one
4465 *context_menu = None;
4466 cx.notify();
4467 return;
4468 } else {
4469 // Otherwise, clear it and start a new one
4470 *context_menu = None;
4471 cx.notify();
4472 }
4473 }
4474 drop(context_menu);
4475 let snapshot = self.snapshot(window, cx);
4476 let deployed_from_indicator = action.deployed_from_indicator;
4477 let mut task = self.code_actions_task.take();
4478 let action = action.clone();
4479 cx.spawn_in(window, |editor, mut cx| async move {
4480 while let Some(prev_task) = task {
4481 prev_task.await.log_err();
4482 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4483 }
4484
4485 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4486 if editor.focus_handle.is_focused(window) {
4487 let multibuffer_point = action
4488 .deployed_from_indicator
4489 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4490 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4491 let (buffer, buffer_row) = snapshot
4492 .buffer_snapshot
4493 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4494 .and_then(|(buffer_snapshot, range)| {
4495 editor
4496 .buffer
4497 .read(cx)
4498 .buffer(buffer_snapshot.remote_id())
4499 .map(|buffer| (buffer, range.start.row))
4500 })?;
4501 let (_, code_actions) = editor
4502 .available_code_actions
4503 .clone()
4504 .and_then(|(location, code_actions)| {
4505 let snapshot = location.buffer.read(cx).snapshot();
4506 let point_range = location.range.to_point(&snapshot);
4507 let point_range = point_range.start.row..=point_range.end.row;
4508 if point_range.contains(&buffer_row) {
4509 Some((location, code_actions))
4510 } else {
4511 None
4512 }
4513 })
4514 .unzip();
4515 let buffer_id = buffer.read(cx).remote_id();
4516 let tasks = editor
4517 .tasks
4518 .get(&(buffer_id, buffer_row))
4519 .map(|t| Arc::new(t.to_owned()));
4520 if tasks.is_none() && code_actions.is_none() {
4521 return None;
4522 }
4523
4524 editor.completion_tasks.clear();
4525 editor.discard_inline_completion(false, cx);
4526 let task_context =
4527 tasks
4528 .as_ref()
4529 .zip(editor.project.clone())
4530 .map(|(tasks, project)| {
4531 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4532 });
4533
4534 Some(cx.spawn_in(window, |editor, mut cx| async move {
4535 let task_context = match task_context {
4536 Some(task_context) => task_context.await,
4537 None => None,
4538 };
4539 let resolved_tasks =
4540 tasks.zip(task_context).map(|(tasks, task_context)| {
4541 Rc::new(ResolvedTasks {
4542 templates: tasks.resolve(&task_context).collect(),
4543 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4544 multibuffer_point.row,
4545 tasks.column,
4546 )),
4547 })
4548 });
4549 let spawn_straight_away = resolved_tasks
4550 .as_ref()
4551 .map_or(false, |tasks| tasks.templates.len() == 1)
4552 && code_actions
4553 .as_ref()
4554 .map_or(true, |actions| actions.is_empty());
4555 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4556 *editor.context_menu.borrow_mut() =
4557 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4558 buffer,
4559 actions: CodeActionContents {
4560 tasks: resolved_tasks,
4561 actions: code_actions,
4562 },
4563 selected_item: Default::default(),
4564 scroll_handle: UniformListScrollHandle::default(),
4565 deployed_from_indicator,
4566 }));
4567 if spawn_straight_away {
4568 if let Some(task) = editor.confirm_code_action(
4569 &ConfirmCodeAction { item_ix: Some(0) },
4570 window,
4571 cx,
4572 ) {
4573 cx.notify();
4574 return task;
4575 }
4576 }
4577 cx.notify();
4578 Task::ready(Ok(()))
4579 }) {
4580 task.await
4581 } else {
4582 Ok(())
4583 }
4584 }))
4585 } else {
4586 Some(Task::ready(Ok(())))
4587 }
4588 })?;
4589 if let Some(task) = spawned_test_task {
4590 task.await?;
4591 }
4592
4593 Ok::<_, anyhow::Error>(())
4594 })
4595 .detach_and_log_err(cx);
4596 }
4597
4598 pub fn confirm_code_action(
4599 &mut self,
4600 action: &ConfirmCodeAction,
4601 window: &mut Window,
4602 cx: &mut Context<Self>,
4603 ) -> Option<Task<Result<()>>> {
4604 let actions_menu =
4605 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4606 menu
4607 } else {
4608 return None;
4609 };
4610 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4611 let action = actions_menu.actions.get(action_ix)?;
4612 let title = action.label();
4613 let buffer = actions_menu.buffer;
4614 let workspace = self.workspace()?;
4615
4616 match action {
4617 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4618 workspace.update(cx, |workspace, cx| {
4619 workspace::tasks::schedule_resolved_task(
4620 workspace,
4621 task_source_kind,
4622 resolved_task,
4623 false,
4624 cx,
4625 );
4626
4627 Some(Task::ready(Ok(())))
4628 })
4629 }
4630 CodeActionsItem::CodeAction {
4631 excerpt_id,
4632 action,
4633 provider,
4634 } => {
4635 let apply_code_action =
4636 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4637 let workspace = workspace.downgrade();
4638 Some(cx.spawn_in(window, |editor, cx| async move {
4639 let project_transaction = apply_code_action.await?;
4640 Self::open_project_transaction(
4641 &editor,
4642 workspace,
4643 project_transaction,
4644 title,
4645 cx,
4646 )
4647 .await
4648 }))
4649 }
4650 }
4651 }
4652
4653 pub async fn open_project_transaction(
4654 this: &WeakEntity<Editor>,
4655 workspace: WeakEntity<Workspace>,
4656 transaction: ProjectTransaction,
4657 title: String,
4658 mut cx: AsyncWindowContext,
4659 ) -> Result<()> {
4660 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4661 cx.update(|_, cx| {
4662 entries.sort_unstable_by_key(|(buffer, _)| {
4663 buffer.read(cx).file().map(|f| f.path().clone())
4664 });
4665 })?;
4666
4667 // If the project transaction's edits are all contained within this editor, then
4668 // avoid opening a new editor to display them.
4669
4670 if let Some((buffer, transaction)) = entries.first() {
4671 if entries.len() == 1 {
4672 let excerpt = this.update(&mut cx, |editor, cx| {
4673 editor
4674 .buffer()
4675 .read(cx)
4676 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4677 })?;
4678 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4679 if excerpted_buffer == *buffer {
4680 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4681 let excerpt_range = excerpt_range.to_offset(buffer);
4682 buffer
4683 .edited_ranges_for_transaction::<usize>(transaction)
4684 .all(|range| {
4685 excerpt_range.start <= range.start
4686 && excerpt_range.end >= range.end
4687 })
4688 })?;
4689
4690 if all_edits_within_excerpt {
4691 return Ok(());
4692 }
4693 }
4694 }
4695 }
4696 } else {
4697 return Ok(());
4698 }
4699
4700 let mut ranges_to_highlight = Vec::new();
4701 let excerpt_buffer = cx.new(|cx| {
4702 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4703 for (buffer_handle, transaction) in &entries {
4704 let buffer = buffer_handle.read(cx);
4705 ranges_to_highlight.extend(
4706 multibuffer.push_excerpts_with_context_lines(
4707 buffer_handle.clone(),
4708 buffer
4709 .edited_ranges_for_transaction::<usize>(transaction)
4710 .collect(),
4711 DEFAULT_MULTIBUFFER_CONTEXT,
4712 cx,
4713 ),
4714 );
4715 }
4716 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4717 multibuffer
4718 })?;
4719
4720 workspace.update_in(&mut cx, |workspace, window, cx| {
4721 let project = workspace.project().clone();
4722 let editor =
4723 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
4724 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4725 editor.update(cx, |editor, cx| {
4726 editor.highlight_background::<Self>(
4727 &ranges_to_highlight,
4728 |theme| theme.editor_highlighted_line_background,
4729 cx,
4730 );
4731 });
4732 })?;
4733
4734 Ok(())
4735 }
4736
4737 pub fn clear_code_action_providers(&mut self) {
4738 self.code_action_providers.clear();
4739 self.available_code_actions.take();
4740 }
4741
4742 pub fn add_code_action_provider(
4743 &mut self,
4744 provider: Rc<dyn CodeActionProvider>,
4745 window: &mut Window,
4746 cx: &mut Context<Self>,
4747 ) {
4748 if self
4749 .code_action_providers
4750 .iter()
4751 .any(|existing_provider| existing_provider.id() == provider.id())
4752 {
4753 return;
4754 }
4755
4756 self.code_action_providers.push(provider);
4757 self.refresh_code_actions(window, cx);
4758 }
4759
4760 pub fn remove_code_action_provider(
4761 &mut self,
4762 id: Arc<str>,
4763 window: &mut Window,
4764 cx: &mut Context<Self>,
4765 ) {
4766 self.code_action_providers
4767 .retain(|provider| provider.id() != id);
4768 self.refresh_code_actions(window, cx);
4769 }
4770
4771 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4772 let buffer = self.buffer.read(cx);
4773 let newest_selection = self.selections.newest_anchor().clone();
4774 if newest_selection.head().diff_base_anchor.is_some() {
4775 return None;
4776 }
4777 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4778 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4779 if start_buffer != end_buffer {
4780 return None;
4781 }
4782
4783 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4784 cx.background_executor()
4785 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4786 .await;
4787
4788 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4789 let providers = this.code_action_providers.clone();
4790 let tasks = this
4791 .code_action_providers
4792 .iter()
4793 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4794 .collect::<Vec<_>>();
4795 (providers, tasks)
4796 })?;
4797
4798 let mut actions = Vec::new();
4799 for (provider, provider_actions) in
4800 providers.into_iter().zip(future::join_all(tasks).await)
4801 {
4802 if let Some(provider_actions) = provider_actions.log_err() {
4803 actions.extend(provider_actions.into_iter().map(|action| {
4804 AvailableCodeAction {
4805 excerpt_id: newest_selection.start.excerpt_id,
4806 action,
4807 provider: provider.clone(),
4808 }
4809 }));
4810 }
4811 }
4812
4813 this.update(&mut cx, |this, cx| {
4814 this.available_code_actions = if actions.is_empty() {
4815 None
4816 } else {
4817 Some((
4818 Location {
4819 buffer: start_buffer,
4820 range: start..end,
4821 },
4822 actions.into(),
4823 ))
4824 };
4825 cx.notify();
4826 })
4827 }));
4828 None
4829 }
4830
4831 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4832 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4833 self.show_git_blame_inline = false;
4834
4835 self.show_git_blame_inline_delay_task =
4836 Some(cx.spawn_in(window, |this, mut cx| async move {
4837 cx.background_executor().timer(delay).await;
4838
4839 this.update(&mut cx, |this, cx| {
4840 this.show_git_blame_inline = true;
4841 cx.notify();
4842 })
4843 .log_err();
4844 }));
4845 }
4846 }
4847
4848 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4849 if self.pending_rename.is_some() {
4850 return None;
4851 }
4852
4853 let provider = self.semantics_provider.clone()?;
4854 let buffer = self.buffer.read(cx);
4855 let newest_selection = self.selections.newest_anchor().clone();
4856 let cursor_position = newest_selection.head();
4857 let (cursor_buffer, cursor_buffer_position) =
4858 buffer.text_anchor_for_position(cursor_position, cx)?;
4859 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4860 if cursor_buffer != tail_buffer {
4861 return None;
4862 }
4863 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4864 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4865 cx.background_executor()
4866 .timer(Duration::from_millis(debounce))
4867 .await;
4868
4869 let highlights = if let Some(highlights) = cx
4870 .update(|cx| {
4871 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4872 })
4873 .ok()
4874 .flatten()
4875 {
4876 highlights.await.log_err()
4877 } else {
4878 None
4879 };
4880
4881 if let Some(highlights) = highlights {
4882 this.update(&mut cx, |this, cx| {
4883 if this.pending_rename.is_some() {
4884 return;
4885 }
4886
4887 let buffer_id = cursor_position.buffer_id;
4888 let buffer = this.buffer.read(cx);
4889 if !buffer
4890 .text_anchor_for_position(cursor_position, cx)
4891 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4892 {
4893 return;
4894 }
4895
4896 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4897 let mut write_ranges = Vec::new();
4898 let mut read_ranges = Vec::new();
4899 for highlight in highlights {
4900 for (excerpt_id, excerpt_range) in
4901 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4902 {
4903 let start = highlight
4904 .range
4905 .start
4906 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4907 let end = highlight
4908 .range
4909 .end
4910 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4911 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4912 continue;
4913 }
4914
4915 let range = Anchor {
4916 buffer_id,
4917 excerpt_id,
4918 text_anchor: start,
4919 diff_base_anchor: None,
4920 }..Anchor {
4921 buffer_id,
4922 excerpt_id,
4923 text_anchor: end,
4924 diff_base_anchor: None,
4925 };
4926 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4927 write_ranges.push(range);
4928 } else {
4929 read_ranges.push(range);
4930 }
4931 }
4932 }
4933
4934 this.highlight_background::<DocumentHighlightRead>(
4935 &read_ranges,
4936 |theme| theme.editor_document_highlight_read_background,
4937 cx,
4938 );
4939 this.highlight_background::<DocumentHighlightWrite>(
4940 &write_ranges,
4941 |theme| theme.editor_document_highlight_write_background,
4942 cx,
4943 );
4944 cx.notify();
4945 })
4946 .log_err();
4947 }
4948 }));
4949 None
4950 }
4951
4952 pub fn refresh_selected_text_highlights(
4953 &mut self,
4954 window: &mut Window,
4955 cx: &mut Context<Editor>,
4956 ) {
4957 if matches!(self.mode, EditorMode::SingleLine { .. }) {
4958 return;
4959 }
4960 self.selection_highlight_task.take();
4961 if !EditorSettings::get_global(cx).selection_highlight {
4962 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4963 return;
4964 }
4965 if self.selections.count() != 1 || self.selections.line_mode {
4966 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4967 return;
4968 }
4969 let selection = self.selections.newest::<Point>(cx);
4970 if selection.is_empty() || selection.start.row != selection.end.row {
4971 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4972 return;
4973 }
4974 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4975 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4976 cx.background_executor()
4977 .timer(Duration::from_millis(debounce))
4978 .await;
4979 let Some(Some(matches_task)) = editor
4980 .update_in(&mut cx, |editor, _, cx| {
4981 if editor.selections.count() != 1 || editor.selections.line_mode {
4982 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4983 return None;
4984 }
4985 let selection = editor.selections.newest::<Point>(cx);
4986 if selection.is_empty() || selection.start.row != selection.end.row {
4987 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4988 return None;
4989 }
4990 let buffer = editor.buffer().read(cx).snapshot(cx);
4991 let query = buffer.text_for_range(selection.range()).collect::<String>();
4992 if query.trim().is_empty() {
4993 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4994 return None;
4995 }
4996 Some(cx.background_spawn(async move {
4997 let mut ranges = Vec::new();
4998 let selection_anchors = selection.range().to_anchors(&buffer);
4999 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5000 for (search_buffer, search_range, excerpt_id) in
5001 buffer.range_to_buffer_ranges(range)
5002 {
5003 ranges.extend(
5004 project::search::SearchQuery::text(
5005 query.clone(),
5006 false,
5007 false,
5008 false,
5009 Default::default(),
5010 Default::default(),
5011 None,
5012 )
5013 .unwrap()
5014 .search(search_buffer, Some(search_range.clone()))
5015 .await
5016 .into_iter()
5017 .filter_map(
5018 |match_range| {
5019 let start = search_buffer.anchor_after(
5020 search_range.start + match_range.start,
5021 );
5022 let end = search_buffer.anchor_before(
5023 search_range.start + match_range.end,
5024 );
5025 let range = Anchor::range_in_buffer(
5026 excerpt_id,
5027 search_buffer.remote_id(),
5028 start..end,
5029 );
5030 (range != selection_anchors).then_some(range)
5031 },
5032 ),
5033 );
5034 }
5035 }
5036 ranges
5037 }))
5038 })
5039 .log_err()
5040 else {
5041 return;
5042 };
5043 let matches = matches_task.await;
5044 editor
5045 .update_in(&mut cx, |editor, _, cx| {
5046 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5047 if !matches.is_empty() {
5048 editor.highlight_background::<SelectedTextHighlight>(
5049 &matches,
5050 |theme| theme.editor_document_highlight_bracket_background,
5051 cx,
5052 )
5053 }
5054 })
5055 .log_err();
5056 }));
5057 }
5058
5059 pub fn refresh_inline_completion(
5060 &mut self,
5061 debounce: bool,
5062 user_requested: bool,
5063 window: &mut Window,
5064 cx: &mut Context<Self>,
5065 ) -> Option<()> {
5066 let provider = self.edit_prediction_provider()?;
5067 let cursor = self.selections.newest_anchor().head();
5068 let (buffer, cursor_buffer_position) =
5069 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5070
5071 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5072 self.discard_inline_completion(false, cx);
5073 return None;
5074 }
5075
5076 if !user_requested
5077 && (!self.should_show_edit_predictions()
5078 || !self.is_focused(window)
5079 || buffer.read(cx).is_empty())
5080 {
5081 self.discard_inline_completion(false, cx);
5082 return None;
5083 }
5084
5085 self.update_visible_inline_completion(window, cx);
5086 provider.refresh(
5087 self.project.clone(),
5088 buffer,
5089 cursor_buffer_position,
5090 debounce,
5091 cx,
5092 );
5093 Some(())
5094 }
5095
5096 fn show_edit_predictions_in_menu(&self) -> bool {
5097 match self.edit_prediction_settings {
5098 EditPredictionSettings::Disabled => false,
5099 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5100 }
5101 }
5102
5103 pub fn edit_predictions_enabled(&self) -> bool {
5104 match self.edit_prediction_settings {
5105 EditPredictionSettings::Disabled => false,
5106 EditPredictionSettings::Enabled { .. } => true,
5107 }
5108 }
5109
5110 fn edit_prediction_requires_modifier(&self) -> bool {
5111 match self.edit_prediction_settings {
5112 EditPredictionSettings::Disabled => false,
5113 EditPredictionSettings::Enabled {
5114 preview_requires_modifier,
5115 ..
5116 } => preview_requires_modifier,
5117 }
5118 }
5119
5120 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5121 if self.edit_prediction_provider.is_none() {
5122 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5123 } else {
5124 let selection = self.selections.newest_anchor();
5125 let cursor = selection.head();
5126
5127 if let Some((buffer, cursor_buffer_position)) =
5128 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5129 {
5130 self.edit_prediction_settings =
5131 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5132 }
5133 }
5134 }
5135
5136 fn edit_prediction_settings_at_position(
5137 &self,
5138 buffer: &Entity<Buffer>,
5139 buffer_position: language::Anchor,
5140 cx: &App,
5141 ) -> EditPredictionSettings {
5142 if self.mode != EditorMode::Full
5143 || !self.show_inline_completions_override.unwrap_or(true)
5144 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5145 {
5146 return EditPredictionSettings::Disabled;
5147 }
5148
5149 let buffer = buffer.read(cx);
5150
5151 let file = buffer.file();
5152
5153 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5154 return EditPredictionSettings::Disabled;
5155 };
5156
5157 let by_provider = matches!(
5158 self.menu_inline_completions_policy,
5159 MenuInlineCompletionsPolicy::ByProvider
5160 );
5161
5162 let show_in_menu = by_provider
5163 && self
5164 .edit_prediction_provider
5165 .as_ref()
5166 .map_or(false, |provider| {
5167 provider.provider.show_completions_in_menu()
5168 });
5169
5170 let preview_requires_modifier =
5171 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5172
5173 EditPredictionSettings::Enabled {
5174 show_in_menu,
5175 preview_requires_modifier,
5176 }
5177 }
5178
5179 fn should_show_edit_predictions(&self) -> bool {
5180 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5181 }
5182
5183 pub fn edit_prediction_preview_is_active(&self) -> bool {
5184 matches!(
5185 self.edit_prediction_preview,
5186 EditPredictionPreview::Active { .. }
5187 )
5188 }
5189
5190 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5191 let cursor = self.selections.newest_anchor().head();
5192 if let Some((buffer, cursor_position)) =
5193 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5194 {
5195 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5196 } else {
5197 false
5198 }
5199 }
5200
5201 fn edit_predictions_enabled_in_buffer(
5202 &self,
5203 buffer: &Entity<Buffer>,
5204 buffer_position: language::Anchor,
5205 cx: &App,
5206 ) -> bool {
5207 maybe!({
5208 if self.read_only(cx) {
5209 return Some(false);
5210 }
5211 let provider = self.edit_prediction_provider()?;
5212 if !provider.is_enabled(&buffer, buffer_position, cx) {
5213 return Some(false);
5214 }
5215 let buffer = buffer.read(cx);
5216 let Some(file) = buffer.file() else {
5217 return Some(true);
5218 };
5219 let settings = all_language_settings(Some(file), cx);
5220 Some(settings.edit_predictions_enabled_for_file(file, cx))
5221 })
5222 .unwrap_or(false)
5223 }
5224
5225 fn cycle_inline_completion(
5226 &mut self,
5227 direction: Direction,
5228 window: &mut Window,
5229 cx: &mut Context<Self>,
5230 ) -> Option<()> {
5231 let provider = self.edit_prediction_provider()?;
5232 let cursor = self.selections.newest_anchor().head();
5233 let (buffer, cursor_buffer_position) =
5234 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5235 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5236 return None;
5237 }
5238
5239 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5240 self.update_visible_inline_completion(window, cx);
5241
5242 Some(())
5243 }
5244
5245 pub fn show_inline_completion(
5246 &mut self,
5247 _: &ShowEditPrediction,
5248 window: &mut Window,
5249 cx: &mut Context<Self>,
5250 ) {
5251 if !self.has_active_inline_completion() {
5252 self.refresh_inline_completion(false, true, window, cx);
5253 return;
5254 }
5255
5256 self.update_visible_inline_completion(window, cx);
5257 }
5258
5259 pub fn display_cursor_names(
5260 &mut self,
5261 _: &DisplayCursorNames,
5262 window: &mut Window,
5263 cx: &mut Context<Self>,
5264 ) {
5265 self.show_cursor_names(window, cx);
5266 }
5267
5268 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5269 self.show_cursor_names = true;
5270 cx.notify();
5271 cx.spawn_in(window, |this, mut cx| async move {
5272 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5273 this.update(&mut cx, |this, cx| {
5274 this.show_cursor_names = false;
5275 cx.notify()
5276 })
5277 .ok()
5278 })
5279 .detach();
5280 }
5281
5282 pub fn next_edit_prediction(
5283 &mut self,
5284 _: &NextEditPrediction,
5285 window: &mut Window,
5286 cx: &mut Context<Self>,
5287 ) {
5288 if self.has_active_inline_completion() {
5289 self.cycle_inline_completion(Direction::Next, window, cx);
5290 } else {
5291 let is_copilot_disabled = self
5292 .refresh_inline_completion(false, true, window, cx)
5293 .is_none();
5294 if is_copilot_disabled {
5295 cx.propagate();
5296 }
5297 }
5298 }
5299
5300 pub fn previous_edit_prediction(
5301 &mut self,
5302 _: &PreviousEditPrediction,
5303 window: &mut Window,
5304 cx: &mut Context<Self>,
5305 ) {
5306 if self.has_active_inline_completion() {
5307 self.cycle_inline_completion(Direction::Prev, window, cx);
5308 } else {
5309 let is_copilot_disabled = self
5310 .refresh_inline_completion(false, true, window, cx)
5311 .is_none();
5312 if is_copilot_disabled {
5313 cx.propagate();
5314 }
5315 }
5316 }
5317
5318 pub fn accept_edit_prediction(
5319 &mut self,
5320 _: &AcceptEditPrediction,
5321 window: &mut Window,
5322 cx: &mut Context<Self>,
5323 ) {
5324 if self.show_edit_predictions_in_menu() {
5325 self.hide_context_menu(window, cx);
5326 }
5327
5328 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5329 return;
5330 };
5331
5332 self.report_inline_completion_event(
5333 active_inline_completion.completion_id.clone(),
5334 true,
5335 cx,
5336 );
5337
5338 match &active_inline_completion.completion {
5339 InlineCompletion::Move { target, .. } => {
5340 let target = *target;
5341
5342 if let Some(position_map) = &self.last_position_map {
5343 if position_map
5344 .visible_row_range
5345 .contains(&target.to_display_point(&position_map.snapshot).row())
5346 || !self.edit_prediction_requires_modifier()
5347 {
5348 self.unfold_ranges(&[target..target], true, false, cx);
5349 // Note that this is also done in vim's handler of the Tab action.
5350 self.change_selections(
5351 Some(Autoscroll::newest()),
5352 window,
5353 cx,
5354 |selections| {
5355 selections.select_anchor_ranges([target..target]);
5356 },
5357 );
5358 self.clear_row_highlights::<EditPredictionPreview>();
5359
5360 self.edit_prediction_preview
5361 .set_previous_scroll_position(None);
5362 } else {
5363 self.edit_prediction_preview
5364 .set_previous_scroll_position(Some(
5365 position_map.snapshot.scroll_anchor,
5366 ));
5367
5368 self.highlight_rows::<EditPredictionPreview>(
5369 target..target,
5370 cx.theme().colors().editor_highlighted_line_background,
5371 true,
5372 cx,
5373 );
5374 self.request_autoscroll(Autoscroll::fit(), cx);
5375 }
5376 }
5377 }
5378 InlineCompletion::Edit { edits, .. } => {
5379 if let Some(provider) = self.edit_prediction_provider() {
5380 provider.accept(cx);
5381 }
5382
5383 let snapshot = self.buffer.read(cx).snapshot(cx);
5384 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5385
5386 self.buffer.update(cx, |buffer, cx| {
5387 buffer.edit(edits.iter().cloned(), None, cx)
5388 });
5389
5390 self.change_selections(None, window, cx, |s| {
5391 s.select_anchor_ranges([last_edit_end..last_edit_end])
5392 });
5393
5394 self.update_visible_inline_completion(window, cx);
5395 if self.active_inline_completion.is_none() {
5396 self.refresh_inline_completion(true, true, window, cx);
5397 }
5398
5399 cx.notify();
5400 }
5401 }
5402
5403 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5404 }
5405
5406 pub fn accept_partial_inline_completion(
5407 &mut self,
5408 _: &AcceptPartialEditPrediction,
5409 window: &mut Window,
5410 cx: &mut Context<Self>,
5411 ) {
5412 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5413 return;
5414 };
5415 if self.selections.count() != 1 {
5416 return;
5417 }
5418
5419 self.report_inline_completion_event(
5420 active_inline_completion.completion_id.clone(),
5421 true,
5422 cx,
5423 );
5424
5425 match &active_inline_completion.completion {
5426 InlineCompletion::Move { target, .. } => {
5427 let target = *target;
5428 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5429 selections.select_anchor_ranges([target..target]);
5430 });
5431 }
5432 InlineCompletion::Edit { edits, .. } => {
5433 // Find an insertion that starts at the cursor position.
5434 let snapshot = self.buffer.read(cx).snapshot(cx);
5435 let cursor_offset = self.selections.newest::<usize>(cx).head();
5436 let insertion = edits.iter().find_map(|(range, text)| {
5437 let range = range.to_offset(&snapshot);
5438 if range.is_empty() && range.start == cursor_offset {
5439 Some(text)
5440 } else {
5441 None
5442 }
5443 });
5444
5445 if let Some(text) = insertion {
5446 let mut partial_completion = text
5447 .chars()
5448 .by_ref()
5449 .take_while(|c| c.is_alphabetic())
5450 .collect::<String>();
5451 if partial_completion.is_empty() {
5452 partial_completion = text
5453 .chars()
5454 .by_ref()
5455 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5456 .collect::<String>();
5457 }
5458
5459 cx.emit(EditorEvent::InputHandled {
5460 utf16_range_to_replace: None,
5461 text: partial_completion.clone().into(),
5462 });
5463
5464 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5465
5466 self.refresh_inline_completion(true, true, window, cx);
5467 cx.notify();
5468 } else {
5469 self.accept_edit_prediction(&Default::default(), window, cx);
5470 }
5471 }
5472 }
5473 }
5474
5475 fn discard_inline_completion(
5476 &mut self,
5477 should_report_inline_completion_event: bool,
5478 cx: &mut Context<Self>,
5479 ) -> bool {
5480 if should_report_inline_completion_event {
5481 let completion_id = self
5482 .active_inline_completion
5483 .as_ref()
5484 .and_then(|active_completion| active_completion.completion_id.clone());
5485
5486 self.report_inline_completion_event(completion_id, false, cx);
5487 }
5488
5489 if let Some(provider) = self.edit_prediction_provider() {
5490 provider.discard(cx);
5491 }
5492
5493 self.take_active_inline_completion(cx)
5494 }
5495
5496 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5497 let Some(provider) = self.edit_prediction_provider() else {
5498 return;
5499 };
5500
5501 let Some((_, buffer, _)) = self
5502 .buffer
5503 .read(cx)
5504 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5505 else {
5506 return;
5507 };
5508
5509 let extension = buffer
5510 .read(cx)
5511 .file()
5512 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5513
5514 let event_type = match accepted {
5515 true => "Edit Prediction Accepted",
5516 false => "Edit Prediction Discarded",
5517 };
5518 telemetry::event!(
5519 event_type,
5520 provider = provider.name(),
5521 prediction_id = id,
5522 suggestion_accepted = accepted,
5523 file_extension = extension,
5524 );
5525 }
5526
5527 pub fn has_active_inline_completion(&self) -> bool {
5528 self.active_inline_completion.is_some()
5529 }
5530
5531 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5532 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5533 return false;
5534 };
5535
5536 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5537 self.clear_highlights::<InlineCompletionHighlight>(cx);
5538 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5539 true
5540 }
5541
5542 /// Returns true when we're displaying the edit prediction popover below the cursor
5543 /// like we are not previewing and the LSP autocomplete menu is visible
5544 /// or we are in `when_holding_modifier` mode.
5545 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5546 if self.edit_prediction_preview_is_active()
5547 || !self.show_edit_predictions_in_menu()
5548 || !self.edit_predictions_enabled()
5549 {
5550 return false;
5551 }
5552
5553 if self.has_visible_completions_menu() {
5554 return true;
5555 }
5556
5557 has_completion && self.edit_prediction_requires_modifier()
5558 }
5559
5560 fn handle_modifiers_changed(
5561 &mut self,
5562 modifiers: Modifiers,
5563 position_map: &PositionMap,
5564 window: &mut Window,
5565 cx: &mut Context<Self>,
5566 ) {
5567 if self.show_edit_predictions_in_menu() {
5568 self.update_edit_prediction_preview(&modifiers, window, cx);
5569 }
5570
5571 self.update_selection_mode(&modifiers, position_map, window, cx);
5572
5573 let mouse_position = window.mouse_position();
5574 if !position_map.text_hitbox.is_hovered(window) {
5575 return;
5576 }
5577
5578 self.update_hovered_link(
5579 position_map.point_for_position(mouse_position),
5580 &position_map.snapshot,
5581 modifiers,
5582 window,
5583 cx,
5584 )
5585 }
5586
5587 fn update_selection_mode(
5588 &mut self,
5589 modifiers: &Modifiers,
5590 position_map: &PositionMap,
5591 window: &mut Window,
5592 cx: &mut Context<Self>,
5593 ) {
5594 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5595 return;
5596 }
5597
5598 let mouse_position = window.mouse_position();
5599 let point_for_position = position_map.point_for_position(mouse_position);
5600 let position = point_for_position.previous_valid;
5601
5602 self.select(
5603 SelectPhase::BeginColumnar {
5604 position,
5605 reset: false,
5606 goal_column: point_for_position.exact_unclipped.column(),
5607 },
5608 window,
5609 cx,
5610 );
5611 }
5612
5613 fn update_edit_prediction_preview(
5614 &mut self,
5615 modifiers: &Modifiers,
5616 window: &mut Window,
5617 cx: &mut Context<Self>,
5618 ) {
5619 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5620 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5621 return;
5622 };
5623
5624 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5625 if matches!(
5626 self.edit_prediction_preview,
5627 EditPredictionPreview::Inactive { .. }
5628 ) {
5629 self.edit_prediction_preview = EditPredictionPreview::Active {
5630 previous_scroll_position: None,
5631 since: Instant::now(),
5632 };
5633
5634 self.update_visible_inline_completion(window, cx);
5635 cx.notify();
5636 }
5637 } else if let EditPredictionPreview::Active {
5638 previous_scroll_position,
5639 since,
5640 } = self.edit_prediction_preview
5641 {
5642 if let (Some(previous_scroll_position), Some(position_map)) =
5643 (previous_scroll_position, self.last_position_map.as_ref())
5644 {
5645 self.set_scroll_position(
5646 previous_scroll_position
5647 .scroll_position(&position_map.snapshot.display_snapshot),
5648 window,
5649 cx,
5650 );
5651 }
5652
5653 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5654 released_too_fast: since.elapsed() < Duration::from_millis(200),
5655 };
5656 self.clear_row_highlights::<EditPredictionPreview>();
5657 self.update_visible_inline_completion(window, cx);
5658 cx.notify();
5659 }
5660 }
5661
5662 fn update_visible_inline_completion(
5663 &mut self,
5664 _window: &mut Window,
5665 cx: &mut Context<Self>,
5666 ) -> Option<()> {
5667 let selection = self.selections.newest_anchor();
5668 let cursor = selection.head();
5669 let multibuffer = self.buffer.read(cx).snapshot(cx);
5670 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5671 let excerpt_id = cursor.excerpt_id;
5672
5673 let show_in_menu = self.show_edit_predictions_in_menu();
5674 let completions_menu_has_precedence = !show_in_menu
5675 && (self.context_menu.borrow().is_some()
5676 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5677
5678 if completions_menu_has_precedence
5679 || !offset_selection.is_empty()
5680 || self
5681 .active_inline_completion
5682 .as_ref()
5683 .map_or(false, |completion| {
5684 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5685 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5686 !invalidation_range.contains(&offset_selection.head())
5687 })
5688 {
5689 self.discard_inline_completion(false, cx);
5690 return None;
5691 }
5692
5693 self.take_active_inline_completion(cx);
5694 let Some(provider) = self.edit_prediction_provider() else {
5695 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5696 return None;
5697 };
5698
5699 let (buffer, cursor_buffer_position) =
5700 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5701
5702 self.edit_prediction_settings =
5703 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5704
5705 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5706
5707 if self.edit_prediction_indent_conflict {
5708 let cursor_point = cursor.to_point(&multibuffer);
5709
5710 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5711
5712 if let Some((_, indent)) = indents.iter().next() {
5713 if indent.len == cursor_point.column {
5714 self.edit_prediction_indent_conflict = false;
5715 }
5716 }
5717 }
5718
5719 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5720 let edits = inline_completion
5721 .edits
5722 .into_iter()
5723 .flat_map(|(range, new_text)| {
5724 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5725 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5726 Some((start..end, new_text))
5727 })
5728 .collect::<Vec<_>>();
5729 if edits.is_empty() {
5730 return None;
5731 }
5732
5733 let first_edit_start = edits.first().unwrap().0.start;
5734 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5735 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5736
5737 let last_edit_end = edits.last().unwrap().0.end;
5738 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5739 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5740
5741 let cursor_row = cursor.to_point(&multibuffer).row;
5742
5743 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5744
5745 let mut inlay_ids = Vec::new();
5746 let invalidation_row_range;
5747 let move_invalidation_row_range = if cursor_row < edit_start_row {
5748 Some(cursor_row..edit_end_row)
5749 } else if cursor_row > edit_end_row {
5750 Some(edit_start_row..cursor_row)
5751 } else {
5752 None
5753 };
5754 let is_move =
5755 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5756 let completion = if is_move {
5757 invalidation_row_range =
5758 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5759 let target = first_edit_start;
5760 InlineCompletion::Move { target, snapshot }
5761 } else {
5762 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5763 && !self.inline_completions_hidden_for_vim_mode;
5764
5765 if show_completions_in_buffer {
5766 if edits
5767 .iter()
5768 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5769 {
5770 let mut inlays = Vec::new();
5771 for (range, new_text) in &edits {
5772 let inlay = Inlay::inline_completion(
5773 post_inc(&mut self.next_inlay_id),
5774 range.start,
5775 new_text.as_str(),
5776 );
5777 inlay_ids.push(inlay.id);
5778 inlays.push(inlay);
5779 }
5780
5781 self.splice_inlays(&[], inlays, cx);
5782 } else {
5783 let background_color = cx.theme().status().deleted_background;
5784 self.highlight_text::<InlineCompletionHighlight>(
5785 edits.iter().map(|(range, _)| range.clone()).collect(),
5786 HighlightStyle {
5787 background_color: Some(background_color),
5788 ..Default::default()
5789 },
5790 cx,
5791 );
5792 }
5793 }
5794
5795 invalidation_row_range = edit_start_row..edit_end_row;
5796
5797 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5798 if provider.show_tab_accept_marker() {
5799 EditDisplayMode::TabAccept
5800 } else {
5801 EditDisplayMode::Inline
5802 }
5803 } else {
5804 EditDisplayMode::DiffPopover
5805 };
5806
5807 InlineCompletion::Edit {
5808 edits,
5809 edit_preview: inline_completion.edit_preview,
5810 display_mode,
5811 snapshot,
5812 }
5813 };
5814
5815 let invalidation_range = multibuffer
5816 .anchor_before(Point::new(invalidation_row_range.start, 0))
5817 ..multibuffer.anchor_after(Point::new(
5818 invalidation_row_range.end,
5819 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5820 ));
5821
5822 self.stale_inline_completion_in_menu = None;
5823 self.active_inline_completion = Some(InlineCompletionState {
5824 inlay_ids,
5825 completion,
5826 completion_id: inline_completion.id,
5827 invalidation_range,
5828 });
5829
5830 cx.notify();
5831
5832 Some(())
5833 }
5834
5835 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5836 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5837 }
5838
5839 fn render_code_actions_indicator(
5840 &self,
5841 _style: &EditorStyle,
5842 row: DisplayRow,
5843 is_active: bool,
5844 cx: &mut Context<Self>,
5845 ) -> Option<IconButton> {
5846 if self.available_code_actions.is_some() {
5847 Some(
5848 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5849 .shape(ui::IconButtonShape::Square)
5850 .icon_size(IconSize::XSmall)
5851 .icon_color(Color::Muted)
5852 .toggle_state(is_active)
5853 .tooltip({
5854 let focus_handle = self.focus_handle.clone();
5855 move |window, cx| {
5856 Tooltip::for_action_in(
5857 "Toggle Code Actions",
5858 &ToggleCodeActions {
5859 deployed_from_indicator: None,
5860 },
5861 &focus_handle,
5862 window,
5863 cx,
5864 )
5865 }
5866 })
5867 .on_click(cx.listener(move |editor, _e, window, cx| {
5868 window.focus(&editor.focus_handle(cx));
5869 editor.toggle_code_actions(
5870 &ToggleCodeActions {
5871 deployed_from_indicator: Some(row),
5872 },
5873 window,
5874 cx,
5875 );
5876 })),
5877 )
5878 } else {
5879 None
5880 }
5881 }
5882
5883 fn clear_tasks(&mut self) {
5884 self.tasks.clear()
5885 }
5886
5887 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5888 if self.tasks.insert(key, value).is_some() {
5889 // This case should hopefully be rare, but just in case...
5890 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5891 }
5892 }
5893
5894 fn build_tasks_context(
5895 project: &Entity<Project>,
5896 buffer: &Entity<Buffer>,
5897 buffer_row: u32,
5898 tasks: &Arc<RunnableTasks>,
5899 cx: &mut Context<Self>,
5900 ) -> Task<Option<task::TaskContext>> {
5901 let position = Point::new(buffer_row, tasks.column);
5902 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5903 let location = Location {
5904 buffer: buffer.clone(),
5905 range: range_start..range_start,
5906 };
5907 // Fill in the environmental variables from the tree-sitter captures
5908 let mut captured_task_variables = TaskVariables::default();
5909 for (capture_name, value) in tasks.extra_variables.clone() {
5910 captured_task_variables.insert(
5911 task::VariableName::Custom(capture_name.into()),
5912 value.clone(),
5913 );
5914 }
5915 project.update(cx, |project, cx| {
5916 project.task_store().update(cx, |task_store, cx| {
5917 task_store.task_context_for_location(captured_task_variables, location, cx)
5918 })
5919 })
5920 }
5921
5922 pub fn spawn_nearest_task(
5923 &mut self,
5924 action: &SpawnNearestTask,
5925 window: &mut Window,
5926 cx: &mut Context<Self>,
5927 ) {
5928 let Some((workspace, _)) = self.workspace.clone() else {
5929 return;
5930 };
5931 let Some(project) = self.project.clone() else {
5932 return;
5933 };
5934
5935 // Try to find a closest, enclosing node using tree-sitter that has a
5936 // task
5937 let Some((buffer, buffer_row, tasks)) = self
5938 .find_enclosing_node_task(cx)
5939 // Or find the task that's closest in row-distance.
5940 .or_else(|| self.find_closest_task(cx))
5941 else {
5942 return;
5943 };
5944
5945 let reveal_strategy = action.reveal;
5946 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5947 cx.spawn_in(window, |_, mut cx| async move {
5948 let context = task_context.await?;
5949 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5950
5951 let resolved = resolved_task.resolved.as_mut()?;
5952 resolved.reveal = reveal_strategy;
5953
5954 workspace
5955 .update(&mut cx, |workspace, cx| {
5956 workspace::tasks::schedule_resolved_task(
5957 workspace,
5958 task_source_kind,
5959 resolved_task,
5960 false,
5961 cx,
5962 );
5963 })
5964 .ok()
5965 })
5966 .detach();
5967 }
5968
5969 fn find_closest_task(
5970 &mut self,
5971 cx: &mut Context<Self>,
5972 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5973 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5974
5975 let ((buffer_id, row), tasks) = self
5976 .tasks
5977 .iter()
5978 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5979
5980 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5981 let tasks = Arc::new(tasks.to_owned());
5982 Some((buffer, *row, tasks))
5983 }
5984
5985 fn find_enclosing_node_task(
5986 &mut self,
5987 cx: &mut Context<Self>,
5988 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5989 let snapshot = self.buffer.read(cx).snapshot(cx);
5990 let offset = self.selections.newest::<usize>(cx).head();
5991 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5992 let buffer_id = excerpt.buffer().remote_id();
5993
5994 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5995 let mut cursor = layer.node().walk();
5996
5997 while cursor.goto_first_child_for_byte(offset).is_some() {
5998 if cursor.node().end_byte() == offset {
5999 cursor.goto_next_sibling();
6000 }
6001 }
6002
6003 // Ascend to the smallest ancestor that contains the range and has a task.
6004 loop {
6005 let node = cursor.node();
6006 let node_range = node.byte_range();
6007 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6008
6009 // Check if this node contains our offset
6010 if node_range.start <= offset && node_range.end >= offset {
6011 // If it contains offset, check for task
6012 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6013 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6014 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6015 }
6016 }
6017
6018 if !cursor.goto_parent() {
6019 break;
6020 }
6021 }
6022 None
6023 }
6024
6025 fn render_run_indicator(
6026 &self,
6027 _style: &EditorStyle,
6028 is_active: bool,
6029 row: DisplayRow,
6030 cx: &mut Context<Self>,
6031 ) -> IconButton {
6032 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6033 .shape(ui::IconButtonShape::Square)
6034 .icon_size(IconSize::XSmall)
6035 .icon_color(Color::Muted)
6036 .toggle_state(is_active)
6037 .on_click(cx.listener(move |editor, _e, window, cx| {
6038 window.focus(&editor.focus_handle(cx));
6039 editor.toggle_code_actions(
6040 &ToggleCodeActions {
6041 deployed_from_indicator: Some(row),
6042 },
6043 window,
6044 cx,
6045 );
6046 }))
6047 }
6048
6049 pub fn context_menu_visible(&self) -> bool {
6050 !self.edit_prediction_preview_is_active()
6051 && self
6052 .context_menu
6053 .borrow()
6054 .as_ref()
6055 .map_or(false, |menu| menu.visible())
6056 }
6057
6058 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6059 self.context_menu
6060 .borrow()
6061 .as_ref()
6062 .map(|menu| menu.origin())
6063 }
6064
6065 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6066 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6067
6068 fn render_edit_prediction_popover(
6069 &mut self,
6070 text_bounds: &Bounds<Pixels>,
6071 content_origin: gpui::Point<Pixels>,
6072 editor_snapshot: &EditorSnapshot,
6073 visible_row_range: Range<DisplayRow>,
6074 scroll_top: f32,
6075 scroll_bottom: f32,
6076 line_layouts: &[LineWithInvisibles],
6077 line_height: Pixels,
6078 scroll_pixel_position: gpui::Point<Pixels>,
6079 newest_selection_head: Option<DisplayPoint>,
6080 editor_width: Pixels,
6081 style: &EditorStyle,
6082 window: &mut Window,
6083 cx: &mut App,
6084 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6085 let active_inline_completion = self.active_inline_completion.as_ref()?;
6086
6087 if self.edit_prediction_visible_in_cursor_popover(true) {
6088 return None;
6089 }
6090
6091 match &active_inline_completion.completion {
6092 InlineCompletion::Move { target, .. } => {
6093 let target_display_point = target.to_display_point(editor_snapshot);
6094
6095 if self.edit_prediction_requires_modifier() {
6096 if !self.edit_prediction_preview_is_active() {
6097 return None;
6098 }
6099
6100 self.render_edit_prediction_modifier_jump_popover(
6101 text_bounds,
6102 content_origin,
6103 visible_row_range,
6104 line_layouts,
6105 line_height,
6106 scroll_pixel_position,
6107 newest_selection_head,
6108 target_display_point,
6109 window,
6110 cx,
6111 )
6112 } else {
6113 self.render_edit_prediction_eager_jump_popover(
6114 text_bounds,
6115 content_origin,
6116 editor_snapshot,
6117 visible_row_range,
6118 scroll_top,
6119 scroll_bottom,
6120 line_height,
6121 scroll_pixel_position,
6122 target_display_point,
6123 editor_width,
6124 window,
6125 cx,
6126 )
6127 }
6128 }
6129 InlineCompletion::Edit {
6130 display_mode: EditDisplayMode::Inline,
6131 ..
6132 } => None,
6133 InlineCompletion::Edit {
6134 display_mode: EditDisplayMode::TabAccept,
6135 edits,
6136 ..
6137 } => {
6138 let range = &edits.first()?.0;
6139 let target_display_point = range.end.to_display_point(editor_snapshot);
6140
6141 self.render_edit_prediction_end_of_line_popover(
6142 "Accept",
6143 editor_snapshot,
6144 visible_row_range,
6145 target_display_point,
6146 line_height,
6147 scroll_pixel_position,
6148 content_origin,
6149 editor_width,
6150 window,
6151 cx,
6152 )
6153 }
6154 InlineCompletion::Edit {
6155 edits,
6156 edit_preview,
6157 display_mode: EditDisplayMode::DiffPopover,
6158 snapshot,
6159 } => self.render_edit_prediction_diff_popover(
6160 text_bounds,
6161 content_origin,
6162 editor_snapshot,
6163 visible_row_range,
6164 line_layouts,
6165 line_height,
6166 scroll_pixel_position,
6167 newest_selection_head,
6168 editor_width,
6169 style,
6170 edits,
6171 edit_preview,
6172 snapshot,
6173 window,
6174 cx,
6175 ),
6176 }
6177 }
6178
6179 fn render_edit_prediction_modifier_jump_popover(
6180 &mut self,
6181 text_bounds: &Bounds<Pixels>,
6182 content_origin: gpui::Point<Pixels>,
6183 visible_row_range: Range<DisplayRow>,
6184 line_layouts: &[LineWithInvisibles],
6185 line_height: Pixels,
6186 scroll_pixel_position: gpui::Point<Pixels>,
6187 newest_selection_head: Option<DisplayPoint>,
6188 target_display_point: DisplayPoint,
6189 window: &mut Window,
6190 cx: &mut App,
6191 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6192 let scrolled_content_origin =
6193 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6194
6195 const SCROLL_PADDING_Y: Pixels = px(12.);
6196
6197 if target_display_point.row() < visible_row_range.start {
6198 return self.render_edit_prediction_scroll_popover(
6199 |_| SCROLL_PADDING_Y,
6200 IconName::ArrowUp,
6201 visible_row_range,
6202 line_layouts,
6203 newest_selection_head,
6204 scrolled_content_origin,
6205 window,
6206 cx,
6207 );
6208 } else if target_display_point.row() >= visible_row_range.end {
6209 return self.render_edit_prediction_scroll_popover(
6210 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6211 IconName::ArrowDown,
6212 visible_row_range,
6213 line_layouts,
6214 newest_selection_head,
6215 scrolled_content_origin,
6216 window,
6217 cx,
6218 );
6219 }
6220
6221 const POLE_WIDTH: Pixels = px(2.);
6222
6223 let line_layout =
6224 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6225 let target_column = target_display_point.column() as usize;
6226
6227 let target_x = line_layout.x_for_index(target_column);
6228 let target_y =
6229 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6230
6231 let flag_on_right = target_x < text_bounds.size.width / 2.;
6232
6233 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6234 border_color.l += 0.001;
6235
6236 let mut element = v_flex()
6237 .items_end()
6238 .when(flag_on_right, |el| el.items_start())
6239 .child(if flag_on_right {
6240 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6241 .rounded_bl(px(0.))
6242 .rounded_tl(px(0.))
6243 .border_l_2()
6244 .border_color(border_color)
6245 } else {
6246 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6247 .rounded_br(px(0.))
6248 .rounded_tr(px(0.))
6249 .border_r_2()
6250 .border_color(border_color)
6251 })
6252 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6253 .into_any();
6254
6255 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6256
6257 let mut origin = scrolled_content_origin + point(target_x, target_y)
6258 - point(
6259 if flag_on_right {
6260 POLE_WIDTH
6261 } else {
6262 size.width - POLE_WIDTH
6263 },
6264 size.height - line_height,
6265 );
6266
6267 origin.x = origin.x.max(content_origin.x);
6268
6269 element.prepaint_at(origin, window, cx);
6270
6271 Some((element, origin))
6272 }
6273
6274 fn render_edit_prediction_scroll_popover(
6275 &mut self,
6276 to_y: impl Fn(Size<Pixels>) -> Pixels,
6277 scroll_icon: IconName,
6278 visible_row_range: Range<DisplayRow>,
6279 line_layouts: &[LineWithInvisibles],
6280 newest_selection_head: Option<DisplayPoint>,
6281 scrolled_content_origin: gpui::Point<Pixels>,
6282 window: &mut Window,
6283 cx: &mut App,
6284 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6285 let mut element = self
6286 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6287 .into_any();
6288
6289 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6290
6291 let cursor = newest_selection_head?;
6292 let cursor_row_layout =
6293 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6294 let cursor_column = cursor.column() as usize;
6295
6296 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6297
6298 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6299
6300 element.prepaint_at(origin, window, cx);
6301 Some((element, origin))
6302 }
6303
6304 fn render_edit_prediction_eager_jump_popover(
6305 &mut self,
6306 text_bounds: &Bounds<Pixels>,
6307 content_origin: gpui::Point<Pixels>,
6308 editor_snapshot: &EditorSnapshot,
6309 visible_row_range: Range<DisplayRow>,
6310 scroll_top: f32,
6311 scroll_bottom: f32,
6312 line_height: Pixels,
6313 scroll_pixel_position: gpui::Point<Pixels>,
6314 target_display_point: DisplayPoint,
6315 editor_width: Pixels,
6316 window: &mut Window,
6317 cx: &mut App,
6318 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6319 if target_display_point.row().as_f32() < scroll_top {
6320 let mut element = self
6321 .render_edit_prediction_line_popover(
6322 "Jump to Edit",
6323 Some(IconName::ArrowUp),
6324 window,
6325 cx,
6326 )?
6327 .into_any();
6328
6329 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6330 let offset = point(
6331 (text_bounds.size.width - size.width) / 2.,
6332 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6333 );
6334
6335 let origin = text_bounds.origin + offset;
6336 element.prepaint_at(origin, window, cx);
6337 Some((element, origin))
6338 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6339 let mut element = self
6340 .render_edit_prediction_line_popover(
6341 "Jump to Edit",
6342 Some(IconName::ArrowDown),
6343 window,
6344 cx,
6345 )?
6346 .into_any();
6347
6348 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6349 let offset = point(
6350 (text_bounds.size.width - size.width) / 2.,
6351 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6352 );
6353
6354 let origin = text_bounds.origin + offset;
6355 element.prepaint_at(origin, window, cx);
6356 Some((element, origin))
6357 } else {
6358 self.render_edit_prediction_end_of_line_popover(
6359 "Jump to Edit",
6360 editor_snapshot,
6361 visible_row_range,
6362 target_display_point,
6363 line_height,
6364 scroll_pixel_position,
6365 content_origin,
6366 editor_width,
6367 window,
6368 cx,
6369 )
6370 }
6371 }
6372
6373 fn render_edit_prediction_end_of_line_popover(
6374 self: &mut Editor,
6375 label: &'static str,
6376 editor_snapshot: &EditorSnapshot,
6377 visible_row_range: Range<DisplayRow>,
6378 target_display_point: DisplayPoint,
6379 line_height: Pixels,
6380 scroll_pixel_position: gpui::Point<Pixels>,
6381 content_origin: gpui::Point<Pixels>,
6382 editor_width: Pixels,
6383 window: &mut Window,
6384 cx: &mut App,
6385 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6386 let target_line_end = DisplayPoint::new(
6387 target_display_point.row(),
6388 editor_snapshot.line_len(target_display_point.row()),
6389 );
6390
6391 let mut element = self
6392 .render_edit_prediction_line_popover(label, None, window, cx)?
6393 .into_any();
6394
6395 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6396
6397 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6398
6399 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6400 let mut origin = start_point
6401 + line_origin
6402 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6403 origin.x = origin.x.max(content_origin.x);
6404
6405 let max_x = content_origin.x + editor_width - size.width;
6406
6407 if origin.x > max_x {
6408 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6409
6410 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6411 origin.y += offset;
6412 IconName::ArrowUp
6413 } else {
6414 origin.y -= offset;
6415 IconName::ArrowDown
6416 };
6417
6418 element = self
6419 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6420 .into_any();
6421
6422 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6423
6424 origin.x = content_origin.x + editor_width - size.width - px(2.);
6425 }
6426
6427 element.prepaint_at(origin, window, cx);
6428 Some((element, origin))
6429 }
6430
6431 fn render_edit_prediction_diff_popover(
6432 self: &Editor,
6433 text_bounds: &Bounds<Pixels>,
6434 content_origin: gpui::Point<Pixels>,
6435 editor_snapshot: &EditorSnapshot,
6436 visible_row_range: Range<DisplayRow>,
6437 line_layouts: &[LineWithInvisibles],
6438 line_height: Pixels,
6439 scroll_pixel_position: gpui::Point<Pixels>,
6440 newest_selection_head: Option<DisplayPoint>,
6441 editor_width: Pixels,
6442 style: &EditorStyle,
6443 edits: &Vec<(Range<Anchor>, String)>,
6444 edit_preview: &Option<language::EditPreview>,
6445 snapshot: &language::BufferSnapshot,
6446 window: &mut Window,
6447 cx: &mut App,
6448 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6449 let edit_start = edits
6450 .first()
6451 .unwrap()
6452 .0
6453 .start
6454 .to_display_point(editor_snapshot);
6455 let edit_end = edits
6456 .last()
6457 .unwrap()
6458 .0
6459 .end
6460 .to_display_point(editor_snapshot);
6461
6462 let is_visible = visible_row_range.contains(&edit_start.row())
6463 || visible_row_range.contains(&edit_end.row());
6464 if !is_visible {
6465 return None;
6466 }
6467
6468 let highlighted_edits =
6469 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6470
6471 let styled_text = highlighted_edits.to_styled_text(&style.text);
6472 let line_count = highlighted_edits.text.lines().count();
6473
6474 const BORDER_WIDTH: Pixels = px(1.);
6475
6476 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6477 let has_keybind = keybind.is_some();
6478
6479 let mut element = h_flex()
6480 .items_start()
6481 .child(
6482 h_flex()
6483 .bg(cx.theme().colors().editor_background)
6484 .border(BORDER_WIDTH)
6485 .shadow_sm()
6486 .border_color(cx.theme().colors().border)
6487 .rounded_l_lg()
6488 .when(line_count > 1, |el| el.rounded_br_lg())
6489 .pr_1()
6490 .child(styled_text),
6491 )
6492 .child(
6493 h_flex()
6494 .h(line_height + BORDER_WIDTH * px(2.))
6495 .px_1p5()
6496 .gap_1()
6497 // Workaround: For some reason, there's a gap if we don't do this
6498 .ml(-BORDER_WIDTH)
6499 .shadow(smallvec![gpui::BoxShadow {
6500 color: gpui::black().opacity(0.05),
6501 offset: point(px(1.), px(1.)),
6502 blur_radius: px(2.),
6503 spread_radius: px(0.),
6504 }])
6505 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6506 .border(BORDER_WIDTH)
6507 .border_color(cx.theme().colors().border)
6508 .rounded_r_lg()
6509 .id("edit_prediction_diff_popover_keybind")
6510 .when(!has_keybind, |el| {
6511 let status_colors = cx.theme().status();
6512
6513 el.bg(status_colors.error_background)
6514 .border_color(status_colors.error.opacity(0.6))
6515 .child(Icon::new(IconName::Info).color(Color::Error))
6516 .cursor_default()
6517 .hoverable_tooltip(move |_window, cx| {
6518 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6519 })
6520 })
6521 .children(keybind),
6522 )
6523 .into_any();
6524
6525 let longest_row =
6526 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6527 let longest_line_width = if visible_row_range.contains(&longest_row) {
6528 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6529 } else {
6530 layout_line(
6531 longest_row,
6532 editor_snapshot,
6533 style,
6534 editor_width,
6535 |_| false,
6536 window,
6537 cx,
6538 )
6539 .width
6540 };
6541
6542 let viewport_bounds =
6543 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6544 right: -EditorElement::SCROLLBAR_WIDTH,
6545 ..Default::default()
6546 });
6547
6548 let x_after_longest =
6549 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6550 - scroll_pixel_position.x;
6551
6552 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6553
6554 // Fully visible if it can be displayed within the window (allow overlapping other
6555 // panes). However, this is only allowed if the popover starts within text_bounds.
6556 let can_position_to_the_right = x_after_longest < text_bounds.right()
6557 && x_after_longest + element_bounds.width < viewport_bounds.right();
6558
6559 let mut origin = if can_position_to_the_right {
6560 point(
6561 x_after_longest,
6562 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6563 - scroll_pixel_position.y,
6564 )
6565 } else {
6566 let cursor_row = newest_selection_head.map(|head| head.row());
6567 let above_edit = edit_start
6568 .row()
6569 .0
6570 .checked_sub(line_count as u32)
6571 .map(DisplayRow);
6572 let below_edit = Some(edit_end.row() + 1);
6573 let above_cursor =
6574 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6575 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6576
6577 // Place the edit popover adjacent to the edit if there is a location
6578 // available that is onscreen and does not obscure the cursor. Otherwise,
6579 // place it adjacent to the cursor.
6580 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6581 .into_iter()
6582 .flatten()
6583 .find(|&start_row| {
6584 let end_row = start_row + line_count as u32;
6585 visible_row_range.contains(&start_row)
6586 && visible_row_range.contains(&end_row)
6587 && cursor_row.map_or(true, |cursor_row| {
6588 !((start_row..end_row).contains(&cursor_row))
6589 })
6590 })?;
6591
6592 content_origin
6593 + point(
6594 -scroll_pixel_position.x,
6595 row_target.as_f32() * line_height - scroll_pixel_position.y,
6596 )
6597 };
6598
6599 origin.x -= BORDER_WIDTH;
6600
6601 window.defer_draw(element, origin, 1);
6602
6603 // Do not return an element, since it will already be drawn due to defer_draw.
6604 None
6605 }
6606
6607 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6608 px(30.)
6609 }
6610
6611 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6612 if self.read_only(cx) {
6613 cx.theme().players().read_only()
6614 } else {
6615 self.style.as_ref().unwrap().local_player
6616 }
6617 }
6618
6619 fn render_edit_prediction_accept_keybind(
6620 &self,
6621 window: &mut Window,
6622 cx: &App,
6623 ) -> Option<AnyElement> {
6624 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6625 let accept_keystroke = accept_binding.keystroke()?;
6626
6627 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6628
6629 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6630 Color::Accent
6631 } else {
6632 Color::Muted
6633 };
6634
6635 h_flex()
6636 .px_0p5()
6637 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6638 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6639 .text_size(TextSize::XSmall.rems(cx))
6640 .child(h_flex().children(ui::render_modifiers(
6641 &accept_keystroke.modifiers,
6642 PlatformStyle::platform(),
6643 Some(modifiers_color),
6644 Some(IconSize::XSmall.rems().into()),
6645 true,
6646 )))
6647 .when(is_platform_style_mac, |parent| {
6648 parent.child(accept_keystroke.key.clone())
6649 })
6650 .when(!is_platform_style_mac, |parent| {
6651 parent.child(
6652 Key::new(
6653 util::capitalize(&accept_keystroke.key),
6654 Some(Color::Default),
6655 )
6656 .size(Some(IconSize::XSmall.rems().into())),
6657 )
6658 })
6659 .into_any()
6660 .into()
6661 }
6662
6663 fn render_edit_prediction_line_popover(
6664 &self,
6665 label: impl Into<SharedString>,
6666 icon: Option<IconName>,
6667 window: &mut Window,
6668 cx: &App,
6669 ) -> Option<Stateful<Div>> {
6670 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6671
6672 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6673 let has_keybind = keybind.is_some();
6674
6675 let result = h_flex()
6676 .id("ep-line-popover")
6677 .py_0p5()
6678 .pl_1()
6679 .pr(padding_right)
6680 .gap_1()
6681 .rounded_md()
6682 .border_1()
6683 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6684 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6685 .shadow_sm()
6686 .when(!has_keybind, |el| {
6687 let status_colors = cx.theme().status();
6688
6689 el.bg(status_colors.error_background)
6690 .border_color(status_colors.error.opacity(0.6))
6691 .pl_2()
6692 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
6693 .cursor_default()
6694 .hoverable_tooltip(move |_window, cx| {
6695 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6696 })
6697 })
6698 .children(keybind)
6699 .child(
6700 Label::new(label)
6701 .size(LabelSize::Small)
6702 .when(!has_keybind, |el| {
6703 el.color(cx.theme().status().error.into()).strikethrough()
6704 }),
6705 )
6706 .when(!has_keybind, |el| {
6707 el.child(
6708 h_flex().ml_1().child(
6709 Icon::new(IconName::Info)
6710 .size(IconSize::Small)
6711 .color(cx.theme().status().error.into()),
6712 ),
6713 )
6714 })
6715 .when_some(icon, |element, icon| {
6716 element.child(
6717 div()
6718 .mt(px(1.5))
6719 .child(Icon::new(icon).size(IconSize::Small)),
6720 )
6721 });
6722
6723 Some(result)
6724 }
6725
6726 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6727 let accent_color = cx.theme().colors().text_accent;
6728 let editor_bg_color = cx.theme().colors().editor_background;
6729 editor_bg_color.blend(accent_color.opacity(0.1))
6730 }
6731
6732 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6733 let accent_color = cx.theme().colors().text_accent;
6734 let editor_bg_color = cx.theme().colors().editor_background;
6735 editor_bg_color.blend(accent_color.opacity(0.6))
6736 }
6737
6738 fn render_edit_prediction_cursor_popover(
6739 &self,
6740 min_width: Pixels,
6741 max_width: Pixels,
6742 cursor_point: Point,
6743 style: &EditorStyle,
6744 accept_keystroke: Option<&gpui::Keystroke>,
6745 _window: &Window,
6746 cx: &mut Context<Editor>,
6747 ) -> Option<AnyElement> {
6748 let provider = self.edit_prediction_provider.as_ref()?;
6749
6750 if provider.provider.needs_terms_acceptance(cx) {
6751 return Some(
6752 h_flex()
6753 .min_w(min_width)
6754 .flex_1()
6755 .px_2()
6756 .py_1()
6757 .gap_3()
6758 .elevation_2(cx)
6759 .hover(|style| style.bg(cx.theme().colors().element_hover))
6760 .id("accept-terms")
6761 .cursor_pointer()
6762 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6763 .on_click(cx.listener(|this, _event, window, cx| {
6764 cx.stop_propagation();
6765 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6766 window.dispatch_action(
6767 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6768 cx,
6769 );
6770 }))
6771 .child(
6772 h_flex()
6773 .flex_1()
6774 .gap_2()
6775 .child(Icon::new(IconName::ZedPredict))
6776 .child(Label::new("Accept Terms of Service"))
6777 .child(div().w_full())
6778 .child(
6779 Icon::new(IconName::ArrowUpRight)
6780 .color(Color::Muted)
6781 .size(IconSize::Small),
6782 )
6783 .into_any_element(),
6784 )
6785 .into_any(),
6786 );
6787 }
6788
6789 let is_refreshing = provider.provider.is_refreshing(cx);
6790
6791 fn pending_completion_container() -> Div {
6792 h_flex()
6793 .h_full()
6794 .flex_1()
6795 .gap_2()
6796 .child(Icon::new(IconName::ZedPredict))
6797 }
6798
6799 let completion = match &self.active_inline_completion {
6800 Some(prediction) => {
6801 if !self.has_visible_completions_menu() {
6802 const RADIUS: Pixels = px(6.);
6803 const BORDER_WIDTH: Pixels = px(1.);
6804
6805 return Some(
6806 h_flex()
6807 .elevation_2(cx)
6808 .border(BORDER_WIDTH)
6809 .border_color(cx.theme().colors().border)
6810 .when(accept_keystroke.is_none(), |el| {
6811 el.border_color(cx.theme().status().error)
6812 })
6813 .rounded(RADIUS)
6814 .rounded_tl(px(0.))
6815 .overflow_hidden()
6816 .child(div().px_1p5().child(match &prediction.completion {
6817 InlineCompletion::Move { target, snapshot } => {
6818 use text::ToPoint as _;
6819 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6820 {
6821 Icon::new(IconName::ZedPredictDown)
6822 } else {
6823 Icon::new(IconName::ZedPredictUp)
6824 }
6825 }
6826 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6827 }))
6828 .child(
6829 h_flex()
6830 .gap_1()
6831 .py_1()
6832 .px_2()
6833 .rounded_r(RADIUS - BORDER_WIDTH)
6834 .border_l_1()
6835 .border_color(cx.theme().colors().border)
6836 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6837 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6838 el.child(
6839 Label::new("Hold")
6840 .size(LabelSize::Small)
6841 .when(accept_keystroke.is_none(), |el| {
6842 el.strikethrough()
6843 })
6844 .line_height_style(LineHeightStyle::UiLabel),
6845 )
6846 })
6847 .id("edit_prediction_cursor_popover_keybind")
6848 .when(accept_keystroke.is_none(), |el| {
6849 let status_colors = cx.theme().status();
6850
6851 el.bg(status_colors.error_background)
6852 .border_color(status_colors.error.opacity(0.6))
6853 .child(Icon::new(IconName::Info).color(Color::Error))
6854 .cursor_default()
6855 .hoverable_tooltip(move |_window, cx| {
6856 cx.new(|_| MissingEditPredictionKeybindingTooltip)
6857 .into()
6858 })
6859 })
6860 .when_some(
6861 accept_keystroke.as_ref(),
6862 |el, accept_keystroke| {
6863 el.child(h_flex().children(ui::render_modifiers(
6864 &accept_keystroke.modifiers,
6865 PlatformStyle::platform(),
6866 Some(Color::Default),
6867 Some(IconSize::XSmall.rems().into()),
6868 false,
6869 )))
6870 },
6871 ),
6872 )
6873 .into_any(),
6874 );
6875 }
6876
6877 self.render_edit_prediction_cursor_popover_preview(
6878 prediction,
6879 cursor_point,
6880 style,
6881 cx,
6882 )?
6883 }
6884
6885 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6886 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6887 stale_completion,
6888 cursor_point,
6889 style,
6890 cx,
6891 )?,
6892
6893 None => {
6894 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6895 }
6896 },
6897
6898 None => pending_completion_container().child(Label::new("No Prediction")),
6899 };
6900
6901 let completion = if is_refreshing {
6902 completion
6903 .with_animation(
6904 "loading-completion",
6905 Animation::new(Duration::from_secs(2))
6906 .repeat()
6907 .with_easing(pulsating_between(0.4, 0.8)),
6908 |label, delta| label.opacity(delta),
6909 )
6910 .into_any_element()
6911 } else {
6912 completion.into_any_element()
6913 };
6914
6915 let has_completion = self.active_inline_completion.is_some();
6916
6917 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6918 Some(
6919 h_flex()
6920 .min_w(min_width)
6921 .max_w(max_width)
6922 .flex_1()
6923 .elevation_2(cx)
6924 .border_color(cx.theme().colors().border)
6925 .child(
6926 div()
6927 .flex_1()
6928 .py_1()
6929 .px_2()
6930 .overflow_hidden()
6931 .child(completion),
6932 )
6933 .when_some(accept_keystroke, |el, accept_keystroke| {
6934 if !accept_keystroke.modifiers.modified() {
6935 return el;
6936 }
6937
6938 el.child(
6939 h_flex()
6940 .h_full()
6941 .border_l_1()
6942 .rounded_r_lg()
6943 .border_color(cx.theme().colors().border)
6944 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6945 .gap_1()
6946 .py_1()
6947 .px_2()
6948 .child(
6949 h_flex()
6950 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6951 .when(is_platform_style_mac, |parent| parent.gap_1())
6952 .child(h_flex().children(ui::render_modifiers(
6953 &accept_keystroke.modifiers,
6954 PlatformStyle::platform(),
6955 Some(if !has_completion {
6956 Color::Muted
6957 } else {
6958 Color::Default
6959 }),
6960 None,
6961 false,
6962 ))),
6963 )
6964 .child(Label::new("Preview").into_any_element())
6965 .opacity(if has_completion { 1.0 } else { 0.4 }),
6966 )
6967 })
6968 .into_any(),
6969 )
6970 }
6971
6972 fn render_edit_prediction_cursor_popover_preview(
6973 &self,
6974 completion: &InlineCompletionState,
6975 cursor_point: Point,
6976 style: &EditorStyle,
6977 cx: &mut Context<Editor>,
6978 ) -> Option<Div> {
6979 use text::ToPoint as _;
6980
6981 fn render_relative_row_jump(
6982 prefix: impl Into<String>,
6983 current_row: u32,
6984 target_row: u32,
6985 ) -> Div {
6986 let (row_diff, arrow) = if target_row < current_row {
6987 (current_row - target_row, IconName::ArrowUp)
6988 } else {
6989 (target_row - current_row, IconName::ArrowDown)
6990 };
6991
6992 h_flex()
6993 .child(
6994 Label::new(format!("{}{}", prefix.into(), row_diff))
6995 .color(Color::Muted)
6996 .size(LabelSize::Small),
6997 )
6998 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6999 }
7000
7001 match &completion.completion {
7002 InlineCompletion::Move {
7003 target, snapshot, ..
7004 } => Some(
7005 h_flex()
7006 .px_2()
7007 .gap_2()
7008 .flex_1()
7009 .child(
7010 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7011 Icon::new(IconName::ZedPredictDown)
7012 } else {
7013 Icon::new(IconName::ZedPredictUp)
7014 },
7015 )
7016 .child(Label::new("Jump to Edit")),
7017 ),
7018
7019 InlineCompletion::Edit {
7020 edits,
7021 edit_preview,
7022 snapshot,
7023 display_mode: _,
7024 } => {
7025 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7026
7027 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7028 &snapshot,
7029 &edits,
7030 edit_preview.as_ref()?,
7031 true,
7032 cx,
7033 )
7034 .first_line_preview();
7035
7036 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7037 .with_default_highlights(&style.text, highlighted_edits.highlights);
7038
7039 let preview = h_flex()
7040 .gap_1()
7041 .min_w_16()
7042 .child(styled_text)
7043 .when(has_more_lines, |parent| parent.child("…"));
7044
7045 let left = if first_edit_row != cursor_point.row {
7046 render_relative_row_jump("", cursor_point.row, first_edit_row)
7047 .into_any_element()
7048 } else {
7049 Icon::new(IconName::ZedPredict).into_any_element()
7050 };
7051
7052 Some(
7053 h_flex()
7054 .h_full()
7055 .flex_1()
7056 .gap_2()
7057 .pr_1()
7058 .overflow_x_hidden()
7059 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7060 .child(left)
7061 .child(preview),
7062 )
7063 }
7064 }
7065 }
7066
7067 fn render_context_menu(
7068 &self,
7069 style: &EditorStyle,
7070 max_height_in_lines: u32,
7071 y_flipped: bool,
7072 window: &mut Window,
7073 cx: &mut Context<Editor>,
7074 ) -> Option<AnyElement> {
7075 let menu = self.context_menu.borrow();
7076 let menu = menu.as_ref()?;
7077 if !menu.visible() {
7078 return None;
7079 };
7080 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7081 }
7082
7083 fn render_context_menu_aside(
7084 &mut self,
7085 max_size: Size<Pixels>,
7086 window: &mut Window,
7087 cx: &mut Context<Editor>,
7088 ) -> Option<AnyElement> {
7089 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7090 if menu.visible() {
7091 menu.render_aside(self, max_size, window, cx)
7092 } else {
7093 None
7094 }
7095 })
7096 }
7097
7098 fn hide_context_menu(
7099 &mut self,
7100 window: &mut Window,
7101 cx: &mut Context<Self>,
7102 ) -> Option<CodeContextMenu> {
7103 cx.notify();
7104 self.completion_tasks.clear();
7105 let context_menu = self.context_menu.borrow_mut().take();
7106 self.stale_inline_completion_in_menu.take();
7107 self.update_visible_inline_completion(window, cx);
7108 context_menu
7109 }
7110
7111 fn show_snippet_choices(
7112 &mut self,
7113 choices: &Vec<String>,
7114 selection: Range<Anchor>,
7115 cx: &mut Context<Self>,
7116 ) {
7117 if selection.start.buffer_id.is_none() {
7118 return;
7119 }
7120 let buffer_id = selection.start.buffer_id.unwrap();
7121 let buffer = self.buffer().read(cx).buffer(buffer_id);
7122 let id = post_inc(&mut self.next_completion_id);
7123
7124 if let Some(buffer) = buffer {
7125 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7126 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7127 ));
7128 }
7129 }
7130
7131 pub fn insert_snippet(
7132 &mut self,
7133 insertion_ranges: &[Range<usize>],
7134 snippet: Snippet,
7135 window: &mut Window,
7136 cx: &mut Context<Self>,
7137 ) -> Result<()> {
7138 struct Tabstop<T> {
7139 is_end_tabstop: bool,
7140 ranges: Vec<Range<T>>,
7141 choices: Option<Vec<String>>,
7142 }
7143
7144 let tabstops = self.buffer.update(cx, |buffer, cx| {
7145 let snippet_text: Arc<str> = snippet.text.clone().into();
7146 buffer.edit(
7147 insertion_ranges
7148 .iter()
7149 .cloned()
7150 .map(|range| (range, snippet_text.clone())),
7151 Some(AutoindentMode::EachLine),
7152 cx,
7153 );
7154
7155 let snapshot = &*buffer.read(cx);
7156 let snippet = &snippet;
7157 snippet
7158 .tabstops
7159 .iter()
7160 .map(|tabstop| {
7161 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7162 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7163 });
7164 let mut tabstop_ranges = tabstop
7165 .ranges
7166 .iter()
7167 .flat_map(|tabstop_range| {
7168 let mut delta = 0_isize;
7169 insertion_ranges.iter().map(move |insertion_range| {
7170 let insertion_start = insertion_range.start as isize + delta;
7171 delta +=
7172 snippet.text.len() as isize - insertion_range.len() as isize;
7173
7174 let start = ((insertion_start + tabstop_range.start) as usize)
7175 .min(snapshot.len());
7176 let end = ((insertion_start + tabstop_range.end) as usize)
7177 .min(snapshot.len());
7178 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7179 })
7180 })
7181 .collect::<Vec<_>>();
7182 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7183
7184 Tabstop {
7185 is_end_tabstop,
7186 ranges: tabstop_ranges,
7187 choices: tabstop.choices.clone(),
7188 }
7189 })
7190 .collect::<Vec<_>>()
7191 });
7192 if let Some(tabstop) = tabstops.first() {
7193 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7194 s.select_ranges(tabstop.ranges.iter().cloned());
7195 });
7196
7197 if let Some(choices) = &tabstop.choices {
7198 if let Some(selection) = tabstop.ranges.first() {
7199 self.show_snippet_choices(choices, selection.clone(), cx)
7200 }
7201 }
7202
7203 // If we're already at the last tabstop and it's at the end of the snippet,
7204 // we're done, we don't need to keep the state around.
7205 if !tabstop.is_end_tabstop {
7206 let choices = tabstops
7207 .iter()
7208 .map(|tabstop| tabstop.choices.clone())
7209 .collect();
7210
7211 let ranges = tabstops
7212 .into_iter()
7213 .map(|tabstop| tabstop.ranges)
7214 .collect::<Vec<_>>();
7215
7216 self.snippet_stack.push(SnippetState {
7217 active_index: 0,
7218 ranges,
7219 choices,
7220 });
7221 }
7222
7223 // Check whether the just-entered snippet ends with an auto-closable bracket.
7224 if self.autoclose_regions.is_empty() {
7225 let snapshot = self.buffer.read(cx).snapshot(cx);
7226 for selection in &mut self.selections.all::<Point>(cx) {
7227 let selection_head = selection.head();
7228 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7229 continue;
7230 };
7231
7232 let mut bracket_pair = None;
7233 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7234 let prev_chars = snapshot
7235 .reversed_chars_at(selection_head)
7236 .collect::<String>();
7237 for (pair, enabled) in scope.brackets() {
7238 if enabled
7239 && pair.close
7240 && prev_chars.starts_with(pair.start.as_str())
7241 && next_chars.starts_with(pair.end.as_str())
7242 {
7243 bracket_pair = Some(pair.clone());
7244 break;
7245 }
7246 }
7247 if let Some(pair) = bracket_pair {
7248 let start = snapshot.anchor_after(selection_head);
7249 let end = snapshot.anchor_after(selection_head);
7250 self.autoclose_regions.push(AutocloseRegion {
7251 selection_id: selection.id,
7252 range: start..end,
7253 pair,
7254 });
7255 }
7256 }
7257 }
7258 }
7259 Ok(())
7260 }
7261
7262 pub fn move_to_next_snippet_tabstop(
7263 &mut self,
7264 window: &mut Window,
7265 cx: &mut Context<Self>,
7266 ) -> bool {
7267 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7268 }
7269
7270 pub fn move_to_prev_snippet_tabstop(
7271 &mut self,
7272 window: &mut Window,
7273 cx: &mut Context<Self>,
7274 ) -> bool {
7275 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7276 }
7277
7278 pub fn move_to_snippet_tabstop(
7279 &mut self,
7280 bias: Bias,
7281 window: &mut Window,
7282 cx: &mut Context<Self>,
7283 ) -> bool {
7284 if let Some(mut snippet) = self.snippet_stack.pop() {
7285 match bias {
7286 Bias::Left => {
7287 if snippet.active_index > 0 {
7288 snippet.active_index -= 1;
7289 } else {
7290 self.snippet_stack.push(snippet);
7291 return false;
7292 }
7293 }
7294 Bias::Right => {
7295 if snippet.active_index + 1 < snippet.ranges.len() {
7296 snippet.active_index += 1;
7297 } else {
7298 self.snippet_stack.push(snippet);
7299 return false;
7300 }
7301 }
7302 }
7303 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7304 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7305 s.select_anchor_ranges(current_ranges.iter().cloned())
7306 });
7307
7308 if let Some(choices) = &snippet.choices[snippet.active_index] {
7309 if let Some(selection) = current_ranges.first() {
7310 self.show_snippet_choices(&choices, selection.clone(), cx);
7311 }
7312 }
7313
7314 // If snippet state is not at the last tabstop, push it back on the stack
7315 if snippet.active_index + 1 < snippet.ranges.len() {
7316 self.snippet_stack.push(snippet);
7317 }
7318 return true;
7319 }
7320 }
7321
7322 false
7323 }
7324
7325 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7326 self.transact(window, cx, |this, window, cx| {
7327 this.select_all(&SelectAll, window, cx);
7328 this.insert("", window, cx);
7329 });
7330 }
7331
7332 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7333 self.transact(window, cx, |this, window, cx| {
7334 this.select_autoclose_pair(window, cx);
7335 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7336 if !this.linked_edit_ranges.is_empty() {
7337 let selections = this.selections.all::<MultiBufferPoint>(cx);
7338 let snapshot = this.buffer.read(cx).snapshot(cx);
7339
7340 for selection in selections.iter() {
7341 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7342 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7343 if selection_start.buffer_id != selection_end.buffer_id {
7344 continue;
7345 }
7346 if let Some(ranges) =
7347 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7348 {
7349 for (buffer, entries) in ranges {
7350 linked_ranges.entry(buffer).or_default().extend(entries);
7351 }
7352 }
7353 }
7354 }
7355
7356 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7357 if !this.selections.line_mode {
7358 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7359 for selection in &mut selections {
7360 if selection.is_empty() {
7361 let old_head = selection.head();
7362 let mut new_head =
7363 movement::left(&display_map, old_head.to_display_point(&display_map))
7364 .to_point(&display_map);
7365 if let Some((buffer, line_buffer_range)) = display_map
7366 .buffer_snapshot
7367 .buffer_line_for_row(MultiBufferRow(old_head.row))
7368 {
7369 let indent_size =
7370 buffer.indent_size_for_line(line_buffer_range.start.row);
7371 let indent_len = match indent_size.kind {
7372 IndentKind::Space => {
7373 buffer.settings_at(line_buffer_range.start, cx).tab_size
7374 }
7375 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7376 };
7377 if old_head.column <= indent_size.len && old_head.column > 0 {
7378 let indent_len = indent_len.get();
7379 new_head = cmp::min(
7380 new_head,
7381 MultiBufferPoint::new(
7382 old_head.row,
7383 ((old_head.column - 1) / indent_len) * indent_len,
7384 ),
7385 );
7386 }
7387 }
7388
7389 selection.set_head(new_head, SelectionGoal::None);
7390 }
7391 }
7392 }
7393
7394 this.signature_help_state.set_backspace_pressed(true);
7395 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7396 s.select(selections)
7397 });
7398 this.insert("", window, cx);
7399 let empty_str: Arc<str> = Arc::from("");
7400 for (buffer, edits) in linked_ranges {
7401 let snapshot = buffer.read(cx).snapshot();
7402 use text::ToPoint as TP;
7403
7404 let edits = edits
7405 .into_iter()
7406 .map(|range| {
7407 let end_point = TP::to_point(&range.end, &snapshot);
7408 let mut start_point = TP::to_point(&range.start, &snapshot);
7409
7410 if end_point == start_point {
7411 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7412 .saturating_sub(1);
7413 start_point =
7414 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7415 };
7416
7417 (start_point..end_point, empty_str.clone())
7418 })
7419 .sorted_by_key(|(range, _)| range.start)
7420 .collect::<Vec<_>>();
7421 buffer.update(cx, |this, cx| {
7422 this.edit(edits, None, cx);
7423 })
7424 }
7425 this.refresh_inline_completion(true, false, window, cx);
7426 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7427 });
7428 }
7429
7430 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7431 self.transact(window, cx, |this, window, cx| {
7432 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7433 let line_mode = s.line_mode;
7434 s.move_with(|map, selection| {
7435 if selection.is_empty() && !line_mode {
7436 let cursor = movement::right(map, selection.head());
7437 selection.end = cursor;
7438 selection.reversed = true;
7439 selection.goal = SelectionGoal::None;
7440 }
7441 })
7442 });
7443 this.insert("", window, cx);
7444 this.refresh_inline_completion(true, false, window, cx);
7445 });
7446 }
7447
7448 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7449 if self.move_to_prev_snippet_tabstop(window, cx) {
7450 return;
7451 }
7452
7453 self.outdent(&Outdent, window, cx);
7454 }
7455
7456 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7457 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7458 return;
7459 }
7460
7461 let mut selections = self.selections.all_adjusted(cx);
7462 let buffer = self.buffer.read(cx);
7463 let snapshot = buffer.snapshot(cx);
7464 let rows_iter = selections.iter().map(|s| s.head().row);
7465 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7466
7467 let mut edits = Vec::new();
7468 let mut prev_edited_row = 0;
7469 let mut row_delta = 0;
7470 for selection in &mut selections {
7471 if selection.start.row != prev_edited_row {
7472 row_delta = 0;
7473 }
7474 prev_edited_row = selection.end.row;
7475
7476 // If the selection is non-empty, then increase the indentation of the selected lines.
7477 if !selection.is_empty() {
7478 row_delta =
7479 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7480 continue;
7481 }
7482
7483 // If the selection is empty and the cursor is in the leading whitespace before the
7484 // suggested indentation, then auto-indent the line.
7485 let cursor = selection.head();
7486 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7487 if let Some(suggested_indent) =
7488 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7489 {
7490 if cursor.column < suggested_indent.len
7491 && cursor.column <= current_indent.len
7492 && current_indent.len <= suggested_indent.len
7493 {
7494 selection.start = Point::new(cursor.row, suggested_indent.len);
7495 selection.end = selection.start;
7496 if row_delta == 0 {
7497 edits.extend(Buffer::edit_for_indent_size_adjustment(
7498 cursor.row,
7499 current_indent,
7500 suggested_indent,
7501 ));
7502 row_delta = suggested_indent.len - current_indent.len;
7503 }
7504 continue;
7505 }
7506 }
7507
7508 // Otherwise, insert a hard or soft tab.
7509 let settings = buffer.language_settings_at(cursor, cx);
7510 let tab_size = if settings.hard_tabs {
7511 IndentSize::tab()
7512 } else {
7513 let tab_size = settings.tab_size.get();
7514 let char_column = snapshot
7515 .text_for_range(Point::new(cursor.row, 0)..cursor)
7516 .flat_map(str::chars)
7517 .count()
7518 + row_delta as usize;
7519 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7520 IndentSize::spaces(chars_to_next_tab_stop)
7521 };
7522 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7523 selection.end = selection.start;
7524 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7525 row_delta += tab_size.len;
7526 }
7527
7528 self.transact(window, cx, |this, window, cx| {
7529 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7530 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7531 s.select(selections)
7532 });
7533 this.refresh_inline_completion(true, false, window, cx);
7534 });
7535 }
7536
7537 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7538 if self.read_only(cx) {
7539 return;
7540 }
7541 let mut selections = self.selections.all::<Point>(cx);
7542 let mut prev_edited_row = 0;
7543 let mut row_delta = 0;
7544 let mut edits = Vec::new();
7545 let buffer = self.buffer.read(cx);
7546 let snapshot = buffer.snapshot(cx);
7547 for selection in &mut selections {
7548 if selection.start.row != prev_edited_row {
7549 row_delta = 0;
7550 }
7551 prev_edited_row = selection.end.row;
7552
7553 row_delta =
7554 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7555 }
7556
7557 self.transact(window, cx, |this, window, cx| {
7558 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7559 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7560 s.select(selections)
7561 });
7562 });
7563 }
7564
7565 fn indent_selection(
7566 buffer: &MultiBuffer,
7567 snapshot: &MultiBufferSnapshot,
7568 selection: &mut Selection<Point>,
7569 edits: &mut Vec<(Range<Point>, String)>,
7570 delta_for_start_row: u32,
7571 cx: &App,
7572 ) -> u32 {
7573 let settings = buffer.language_settings_at(selection.start, cx);
7574 let tab_size = settings.tab_size.get();
7575 let indent_kind = if settings.hard_tabs {
7576 IndentKind::Tab
7577 } else {
7578 IndentKind::Space
7579 };
7580 let mut start_row = selection.start.row;
7581 let mut end_row = selection.end.row + 1;
7582
7583 // If a selection ends at the beginning of a line, don't indent
7584 // that last line.
7585 if selection.end.column == 0 && selection.end.row > selection.start.row {
7586 end_row -= 1;
7587 }
7588
7589 // Avoid re-indenting a row that has already been indented by a
7590 // previous selection, but still update this selection's column
7591 // to reflect that indentation.
7592 if delta_for_start_row > 0 {
7593 start_row += 1;
7594 selection.start.column += delta_for_start_row;
7595 if selection.end.row == selection.start.row {
7596 selection.end.column += delta_for_start_row;
7597 }
7598 }
7599
7600 let mut delta_for_end_row = 0;
7601 let has_multiple_rows = start_row + 1 != end_row;
7602 for row in start_row..end_row {
7603 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7604 let indent_delta = match (current_indent.kind, indent_kind) {
7605 (IndentKind::Space, IndentKind::Space) => {
7606 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7607 IndentSize::spaces(columns_to_next_tab_stop)
7608 }
7609 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7610 (_, IndentKind::Tab) => IndentSize::tab(),
7611 };
7612
7613 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7614 0
7615 } else {
7616 selection.start.column
7617 };
7618 let row_start = Point::new(row, start);
7619 edits.push((
7620 row_start..row_start,
7621 indent_delta.chars().collect::<String>(),
7622 ));
7623
7624 // Update this selection's endpoints to reflect the indentation.
7625 if row == selection.start.row {
7626 selection.start.column += indent_delta.len;
7627 }
7628 if row == selection.end.row {
7629 selection.end.column += indent_delta.len;
7630 delta_for_end_row = indent_delta.len;
7631 }
7632 }
7633
7634 if selection.start.row == selection.end.row {
7635 delta_for_start_row + delta_for_end_row
7636 } else {
7637 delta_for_end_row
7638 }
7639 }
7640
7641 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7642 if self.read_only(cx) {
7643 return;
7644 }
7645 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7646 let selections = self.selections.all::<Point>(cx);
7647 let mut deletion_ranges = Vec::new();
7648 let mut last_outdent = None;
7649 {
7650 let buffer = self.buffer.read(cx);
7651 let snapshot = buffer.snapshot(cx);
7652 for selection in &selections {
7653 let settings = buffer.language_settings_at(selection.start, cx);
7654 let tab_size = settings.tab_size.get();
7655 let mut rows = selection.spanned_rows(false, &display_map);
7656
7657 // Avoid re-outdenting a row that has already been outdented by a
7658 // previous selection.
7659 if let Some(last_row) = last_outdent {
7660 if last_row == rows.start {
7661 rows.start = rows.start.next_row();
7662 }
7663 }
7664 let has_multiple_rows = rows.len() > 1;
7665 for row in rows.iter_rows() {
7666 let indent_size = snapshot.indent_size_for_line(row);
7667 if indent_size.len > 0 {
7668 let deletion_len = match indent_size.kind {
7669 IndentKind::Space => {
7670 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7671 if columns_to_prev_tab_stop == 0 {
7672 tab_size
7673 } else {
7674 columns_to_prev_tab_stop
7675 }
7676 }
7677 IndentKind::Tab => 1,
7678 };
7679 let start = if has_multiple_rows
7680 || deletion_len > selection.start.column
7681 || indent_size.len < selection.start.column
7682 {
7683 0
7684 } else {
7685 selection.start.column - deletion_len
7686 };
7687 deletion_ranges.push(
7688 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7689 );
7690 last_outdent = Some(row);
7691 }
7692 }
7693 }
7694 }
7695
7696 self.transact(window, cx, |this, window, cx| {
7697 this.buffer.update(cx, |buffer, cx| {
7698 let empty_str: Arc<str> = Arc::default();
7699 buffer.edit(
7700 deletion_ranges
7701 .into_iter()
7702 .map(|range| (range, empty_str.clone())),
7703 None,
7704 cx,
7705 );
7706 });
7707 let selections = this.selections.all::<usize>(cx);
7708 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7709 s.select(selections)
7710 });
7711 });
7712 }
7713
7714 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7715 if self.read_only(cx) {
7716 return;
7717 }
7718 let selections = self
7719 .selections
7720 .all::<usize>(cx)
7721 .into_iter()
7722 .map(|s| s.range());
7723
7724 self.transact(window, cx, |this, window, cx| {
7725 this.buffer.update(cx, |buffer, cx| {
7726 buffer.autoindent_ranges(selections, cx);
7727 });
7728 let selections = this.selections.all::<usize>(cx);
7729 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7730 s.select(selections)
7731 });
7732 });
7733 }
7734
7735 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7736 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7737 let selections = self.selections.all::<Point>(cx);
7738
7739 let mut new_cursors = Vec::new();
7740 let mut edit_ranges = Vec::new();
7741 let mut selections = selections.iter().peekable();
7742 while let Some(selection) = selections.next() {
7743 let mut rows = selection.spanned_rows(false, &display_map);
7744 let goal_display_column = selection.head().to_display_point(&display_map).column();
7745
7746 // Accumulate contiguous regions of rows that we want to delete.
7747 while let Some(next_selection) = selections.peek() {
7748 let next_rows = next_selection.spanned_rows(false, &display_map);
7749 if next_rows.start <= rows.end {
7750 rows.end = next_rows.end;
7751 selections.next().unwrap();
7752 } else {
7753 break;
7754 }
7755 }
7756
7757 let buffer = &display_map.buffer_snapshot;
7758 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7759 let edit_end;
7760 let cursor_buffer_row;
7761 if buffer.max_point().row >= rows.end.0 {
7762 // If there's a line after the range, delete the \n from the end of the row range
7763 // and position the cursor on the next line.
7764 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7765 cursor_buffer_row = rows.end;
7766 } else {
7767 // If there isn't a line after the range, delete the \n from the line before the
7768 // start of the row range and position the cursor there.
7769 edit_start = edit_start.saturating_sub(1);
7770 edit_end = buffer.len();
7771 cursor_buffer_row = rows.start.previous_row();
7772 }
7773
7774 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7775 *cursor.column_mut() =
7776 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7777
7778 new_cursors.push((
7779 selection.id,
7780 buffer.anchor_after(cursor.to_point(&display_map)),
7781 ));
7782 edit_ranges.push(edit_start..edit_end);
7783 }
7784
7785 self.transact(window, cx, |this, window, cx| {
7786 let buffer = this.buffer.update(cx, |buffer, cx| {
7787 let empty_str: Arc<str> = Arc::default();
7788 buffer.edit(
7789 edit_ranges
7790 .into_iter()
7791 .map(|range| (range, empty_str.clone())),
7792 None,
7793 cx,
7794 );
7795 buffer.snapshot(cx)
7796 });
7797 let new_selections = new_cursors
7798 .into_iter()
7799 .map(|(id, cursor)| {
7800 let cursor = cursor.to_point(&buffer);
7801 Selection {
7802 id,
7803 start: cursor,
7804 end: cursor,
7805 reversed: false,
7806 goal: SelectionGoal::None,
7807 }
7808 })
7809 .collect();
7810
7811 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7812 s.select(new_selections);
7813 });
7814 });
7815 }
7816
7817 pub fn join_lines_impl(
7818 &mut self,
7819 insert_whitespace: bool,
7820 window: &mut Window,
7821 cx: &mut Context<Self>,
7822 ) {
7823 if self.read_only(cx) {
7824 return;
7825 }
7826 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7827 for selection in self.selections.all::<Point>(cx) {
7828 let start = MultiBufferRow(selection.start.row);
7829 // Treat single line selections as if they include the next line. Otherwise this action
7830 // would do nothing for single line selections individual cursors.
7831 let end = if selection.start.row == selection.end.row {
7832 MultiBufferRow(selection.start.row + 1)
7833 } else {
7834 MultiBufferRow(selection.end.row)
7835 };
7836
7837 if let Some(last_row_range) = row_ranges.last_mut() {
7838 if start <= last_row_range.end {
7839 last_row_range.end = end;
7840 continue;
7841 }
7842 }
7843 row_ranges.push(start..end);
7844 }
7845
7846 let snapshot = self.buffer.read(cx).snapshot(cx);
7847 let mut cursor_positions = Vec::new();
7848 for row_range in &row_ranges {
7849 let anchor = snapshot.anchor_before(Point::new(
7850 row_range.end.previous_row().0,
7851 snapshot.line_len(row_range.end.previous_row()),
7852 ));
7853 cursor_positions.push(anchor..anchor);
7854 }
7855
7856 self.transact(window, cx, |this, window, cx| {
7857 for row_range in row_ranges.into_iter().rev() {
7858 for row in row_range.iter_rows().rev() {
7859 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7860 let next_line_row = row.next_row();
7861 let indent = snapshot.indent_size_for_line(next_line_row);
7862 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7863
7864 let replace =
7865 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7866 " "
7867 } else {
7868 ""
7869 };
7870
7871 this.buffer.update(cx, |buffer, cx| {
7872 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7873 });
7874 }
7875 }
7876
7877 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7878 s.select_anchor_ranges(cursor_positions)
7879 });
7880 });
7881 }
7882
7883 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7884 self.join_lines_impl(true, window, cx);
7885 }
7886
7887 pub fn sort_lines_case_sensitive(
7888 &mut self,
7889 _: &SortLinesCaseSensitive,
7890 window: &mut Window,
7891 cx: &mut Context<Self>,
7892 ) {
7893 self.manipulate_lines(window, cx, |lines| lines.sort())
7894 }
7895
7896 pub fn sort_lines_case_insensitive(
7897 &mut self,
7898 _: &SortLinesCaseInsensitive,
7899 window: &mut Window,
7900 cx: &mut Context<Self>,
7901 ) {
7902 self.manipulate_lines(window, cx, |lines| {
7903 lines.sort_by_key(|line| line.to_lowercase())
7904 })
7905 }
7906
7907 pub fn unique_lines_case_insensitive(
7908 &mut self,
7909 _: &UniqueLinesCaseInsensitive,
7910 window: &mut Window,
7911 cx: &mut Context<Self>,
7912 ) {
7913 self.manipulate_lines(window, cx, |lines| {
7914 let mut seen = HashSet::default();
7915 lines.retain(|line| seen.insert(line.to_lowercase()));
7916 })
7917 }
7918
7919 pub fn unique_lines_case_sensitive(
7920 &mut self,
7921 _: &UniqueLinesCaseSensitive,
7922 window: &mut Window,
7923 cx: &mut Context<Self>,
7924 ) {
7925 self.manipulate_lines(window, cx, |lines| {
7926 let mut seen = HashSet::default();
7927 lines.retain(|line| seen.insert(*line));
7928 })
7929 }
7930
7931 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7932 let Some(project) = self.project.clone() else {
7933 return;
7934 };
7935 self.reload(project, window, cx)
7936 .detach_and_notify_err(window, cx);
7937 }
7938
7939 pub fn restore_file(
7940 &mut self,
7941 _: &::git::RestoreFile,
7942 window: &mut Window,
7943 cx: &mut Context<Self>,
7944 ) {
7945 let mut buffer_ids = HashSet::default();
7946 let snapshot = self.buffer().read(cx).snapshot(cx);
7947 for selection in self.selections.all::<usize>(cx) {
7948 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7949 }
7950
7951 let buffer = self.buffer().read(cx);
7952 let ranges = buffer_ids
7953 .into_iter()
7954 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7955 .collect::<Vec<_>>();
7956
7957 self.restore_hunks_in_ranges(ranges, window, cx);
7958 }
7959
7960 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7961 let selections = self
7962 .selections
7963 .all(cx)
7964 .into_iter()
7965 .map(|s| s.range())
7966 .collect();
7967 self.restore_hunks_in_ranges(selections, window, cx);
7968 }
7969
7970 fn restore_hunks_in_ranges(
7971 &mut self,
7972 ranges: Vec<Range<Point>>,
7973 window: &mut Window,
7974 cx: &mut Context<Editor>,
7975 ) {
7976 let mut revert_changes = HashMap::default();
7977 let chunk_by = self
7978 .snapshot(window, cx)
7979 .hunks_for_ranges(ranges)
7980 .into_iter()
7981 .chunk_by(|hunk| hunk.buffer_id);
7982 for (buffer_id, hunks) in &chunk_by {
7983 let hunks = hunks.collect::<Vec<_>>();
7984 for hunk in &hunks {
7985 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7986 }
7987 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7988 }
7989 drop(chunk_by);
7990 if !revert_changes.is_empty() {
7991 self.transact(window, cx, |editor, window, cx| {
7992 editor.restore(revert_changes, window, cx);
7993 });
7994 }
7995 }
7996
7997 pub fn open_active_item_in_terminal(
7998 &mut self,
7999 _: &OpenInTerminal,
8000 window: &mut Window,
8001 cx: &mut Context<Self>,
8002 ) {
8003 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8004 let project_path = buffer.read(cx).project_path(cx)?;
8005 let project = self.project.as_ref()?.read(cx);
8006 let entry = project.entry_for_path(&project_path, cx)?;
8007 let parent = match &entry.canonical_path {
8008 Some(canonical_path) => canonical_path.to_path_buf(),
8009 None => project.absolute_path(&project_path, cx)?,
8010 }
8011 .parent()?
8012 .to_path_buf();
8013 Some(parent)
8014 }) {
8015 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8016 }
8017 }
8018
8019 pub fn prepare_restore_change(
8020 &self,
8021 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8022 hunk: &MultiBufferDiffHunk,
8023 cx: &mut App,
8024 ) -> Option<()> {
8025 if hunk.is_created_file() {
8026 return None;
8027 }
8028 let buffer = self.buffer.read(cx);
8029 let diff = buffer.diff_for(hunk.buffer_id)?;
8030 let buffer = buffer.buffer(hunk.buffer_id)?;
8031 let buffer = buffer.read(cx);
8032 let original_text = diff
8033 .read(cx)
8034 .base_text()
8035 .as_rope()
8036 .slice(hunk.diff_base_byte_range.clone());
8037 let buffer_snapshot = buffer.snapshot();
8038 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8039 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8040 probe
8041 .0
8042 .start
8043 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8044 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8045 }) {
8046 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8047 Some(())
8048 } else {
8049 None
8050 }
8051 }
8052
8053 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8054 self.manipulate_lines(window, cx, |lines| lines.reverse())
8055 }
8056
8057 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8058 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8059 }
8060
8061 fn manipulate_lines<Fn>(
8062 &mut self,
8063 window: &mut Window,
8064 cx: &mut Context<Self>,
8065 mut callback: Fn,
8066 ) where
8067 Fn: FnMut(&mut Vec<&str>),
8068 {
8069 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8070 let buffer = self.buffer.read(cx).snapshot(cx);
8071
8072 let mut edits = Vec::new();
8073
8074 let selections = self.selections.all::<Point>(cx);
8075 let mut selections = selections.iter().peekable();
8076 let mut contiguous_row_selections = Vec::new();
8077 let mut new_selections = Vec::new();
8078 let mut added_lines = 0;
8079 let mut removed_lines = 0;
8080
8081 while let Some(selection) = selections.next() {
8082 let (start_row, end_row) = consume_contiguous_rows(
8083 &mut contiguous_row_selections,
8084 selection,
8085 &display_map,
8086 &mut selections,
8087 );
8088
8089 let start_point = Point::new(start_row.0, 0);
8090 let end_point = Point::new(
8091 end_row.previous_row().0,
8092 buffer.line_len(end_row.previous_row()),
8093 );
8094 let text = buffer
8095 .text_for_range(start_point..end_point)
8096 .collect::<String>();
8097
8098 let mut lines = text.split('\n').collect_vec();
8099
8100 let lines_before = lines.len();
8101 callback(&mut lines);
8102 let lines_after = lines.len();
8103
8104 edits.push((start_point..end_point, lines.join("\n")));
8105
8106 // Selections must change based on added and removed line count
8107 let start_row =
8108 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8109 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8110 new_selections.push(Selection {
8111 id: selection.id,
8112 start: start_row,
8113 end: end_row,
8114 goal: SelectionGoal::None,
8115 reversed: selection.reversed,
8116 });
8117
8118 if lines_after > lines_before {
8119 added_lines += lines_after - lines_before;
8120 } else if lines_before > lines_after {
8121 removed_lines += lines_before - lines_after;
8122 }
8123 }
8124
8125 self.transact(window, cx, |this, window, cx| {
8126 let buffer = this.buffer.update(cx, |buffer, cx| {
8127 buffer.edit(edits, None, cx);
8128 buffer.snapshot(cx)
8129 });
8130
8131 // Recalculate offsets on newly edited buffer
8132 let new_selections = new_selections
8133 .iter()
8134 .map(|s| {
8135 let start_point = Point::new(s.start.0, 0);
8136 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8137 Selection {
8138 id: s.id,
8139 start: buffer.point_to_offset(start_point),
8140 end: buffer.point_to_offset(end_point),
8141 goal: s.goal,
8142 reversed: s.reversed,
8143 }
8144 })
8145 .collect();
8146
8147 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8148 s.select(new_selections);
8149 });
8150
8151 this.request_autoscroll(Autoscroll::fit(), cx);
8152 });
8153 }
8154
8155 pub fn convert_to_upper_case(
8156 &mut self,
8157 _: &ConvertToUpperCase,
8158 window: &mut Window,
8159 cx: &mut Context<Self>,
8160 ) {
8161 self.manipulate_text(window, cx, |text| text.to_uppercase())
8162 }
8163
8164 pub fn convert_to_lower_case(
8165 &mut self,
8166 _: &ConvertToLowerCase,
8167 window: &mut Window,
8168 cx: &mut Context<Self>,
8169 ) {
8170 self.manipulate_text(window, cx, |text| text.to_lowercase())
8171 }
8172
8173 pub fn convert_to_title_case(
8174 &mut self,
8175 _: &ConvertToTitleCase,
8176 window: &mut Window,
8177 cx: &mut Context<Self>,
8178 ) {
8179 self.manipulate_text(window, cx, |text| {
8180 text.split('\n')
8181 .map(|line| line.to_case(Case::Title))
8182 .join("\n")
8183 })
8184 }
8185
8186 pub fn convert_to_snake_case(
8187 &mut self,
8188 _: &ConvertToSnakeCase,
8189 window: &mut Window,
8190 cx: &mut Context<Self>,
8191 ) {
8192 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8193 }
8194
8195 pub fn convert_to_kebab_case(
8196 &mut self,
8197 _: &ConvertToKebabCase,
8198 window: &mut Window,
8199 cx: &mut Context<Self>,
8200 ) {
8201 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8202 }
8203
8204 pub fn convert_to_upper_camel_case(
8205 &mut self,
8206 _: &ConvertToUpperCamelCase,
8207 window: &mut Window,
8208 cx: &mut Context<Self>,
8209 ) {
8210 self.manipulate_text(window, cx, |text| {
8211 text.split('\n')
8212 .map(|line| line.to_case(Case::UpperCamel))
8213 .join("\n")
8214 })
8215 }
8216
8217 pub fn convert_to_lower_camel_case(
8218 &mut self,
8219 _: &ConvertToLowerCamelCase,
8220 window: &mut Window,
8221 cx: &mut Context<Self>,
8222 ) {
8223 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8224 }
8225
8226 pub fn convert_to_opposite_case(
8227 &mut self,
8228 _: &ConvertToOppositeCase,
8229 window: &mut Window,
8230 cx: &mut Context<Self>,
8231 ) {
8232 self.manipulate_text(window, cx, |text| {
8233 text.chars()
8234 .fold(String::with_capacity(text.len()), |mut t, c| {
8235 if c.is_uppercase() {
8236 t.extend(c.to_lowercase());
8237 } else {
8238 t.extend(c.to_uppercase());
8239 }
8240 t
8241 })
8242 })
8243 }
8244
8245 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8246 where
8247 Fn: FnMut(&str) -> String,
8248 {
8249 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8250 let buffer = self.buffer.read(cx).snapshot(cx);
8251
8252 let mut new_selections = Vec::new();
8253 let mut edits = Vec::new();
8254 let mut selection_adjustment = 0i32;
8255
8256 for selection in self.selections.all::<usize>(cx) {
8257 let selection_is_empty = selection.is_empty();
8258
8259 let (start, end) = if selection_is_empty {
8260 let word_range = movement::surrounding_word(
8261 &display_map,
8262 selection.start.to_display_point(&display_map),
8263 );
8264 let start = word_range.start.to_offset(&display_map, Bias::Left);
8265 let end = word_range.end.to_offset(&display_map, Bias::Left);
8266 (start, end)
8267 } else {
8268 (selection.start, selection.end)
8269 };
8270
8271 let text = buffer.text_for_range(start..end).collect::<String>();
8272 let old_length = text.len() as i32;
8273 let text = callback(&text);
8274
8275 new_selections.push(Selection {
8276 start: (start as i32 - selection_adjustment) as usize,
8277 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8278 goal: SelectionGoal::None,
8279 ..selection
8280 });
8281
8282 selection_adjustment += old_length - text.len() as i32;
8283
8284 edits.push((start..end, text));
8285 }
8286
8287 self.transact(window, cx, |this, window, cx| {
8288 this.buffer.update(cx, |buffer, cx| {
8289 buffer.edit(edits, None, cx);
8290 });
8291
8292 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8293 s.select(new_selections);
8294 });
8295
8296 this.request_autoscroll(Autoscroll::fit(), cx);
8297 });
8298 }
8299
8300 pub fn duplicate(
8301 &mut self,
8302 upwards: bool,
8303 whole_lines: bool,
8304 window: &mut Window,
8305 cx: &mut Context<Self>,
8306 ) {
8307 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8308 let buffer = &display_map.buffer_snapshot;
8309 let selections = self.selections.all::<Point>(cx);
8310
8311 let mut edits = Vec::new();
8312 let mut selections_iter = selections.iter().peekable();
8313 while let Some(selection) = selections_iter.next() {
8314 let mut rows = selection.spanned_rows(false, &display_map);
8315 // duplicate line-wise
8316 if whole_lines || selection.start == selection.end {
8317 // Avoid duplicating the same lines twice.
8318 while let Some(next_selection) = selections_iter.peek() {
8319 let next_rows = next_selection.spanned_rows(false, &display_map);
8320 if next_rows.start < rows.end {
8321 rows.end = next_rows.end;
8322 selections_iter.next().unwrap();
8323 } else {
8324 break;
8325 }
8326 }
8327
8328 // Copy the text from the selected row region and splice it either at the start
8329 // or end of the region.
8330 let start = Point::new(rows.start.0, 0);
8331 let end = Point::new(
8332 rows.end.previous_row().0,
8333 buffer.line_len(rows.end.previous_row()),
8334 );
8335 let text = buffer
8336 .text_for_range(start..end)
8337 .chain(Some("\n"))
8338 .collect::<String>();
8339 let insert_location = if upwards {
8340 Point::new(rows.end.0, 0)
8341 } else {
8342 start
8343 };
8344 edits.push((insert_location..insert_location, text));
8345 } else {
8346 // duplicate character-wise
8347 let start = selection.start;
8348 let end = selection.end;
8349 let text = buffer.text_for_range(start..end).collect::<String>();
8350 edits.push((selection.end..selection.end, text));
8351 }
8352 }
8353
8354 self.transact(window, cx, |this, _, cx| {
8355 this.buffer.update(cx, |buffer, cx| {
8356 buffer.edit(edits, None, cx);
8357 });
8358
8359 this.request_autoscroll(Autoscroll::fit(), cx);
8360 });
8361 }
8362
8363 pub fn duplicate_line_up(
8364 &mut self,
8365 _: &DuplicateLineUp,
8366 window: &mut Window,
8367 cx: &mut Context<Self>,
8368 ) {
8369 self.duplicate(true, true, window, cx);
8370 }
8371
8372 pub fn duplicate_line_down(
8373 &mut self,
8374 _: &DuplicateLineDown,
8375 window: &mut Window,
8376 cx: &mut Context<Self>,
8377 ) {
8378 self.duplicate(false, true, window, cx);
8379 }
8380
8381 pub fn duplicate_selection(
8382 &mut self,
8383 _: &DuplicateSelection,
8384 window: &mut Window,
8385 cx: &mut Context<Self>,
8386 ) {
8387 self.duplicate(false, false, window, cx);
8388 }
8389
8390 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8391 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8392 let buffer = self.buffer.read(cx).snapshot(cx);
8393
8394 let mut edits = Vec::new();
8395 let mut unfold_ranges = Vec::new();
8396 let mut refold_creases = Vec::new();
8397
8398 let selections = self.selections.all::<Point>(cx);
8399 let mut selections = selections.iter().peekable();
8400 let mut contiguous_row_selections = Vec::new();
8401 let mut new_selections = Vec::new();
8402
8403 while let Some(selection) = selections.next() {
8404 // Find all the selections that span a contiguous row range
8405 let (start_row, end_row) = consume_contiguous_rows(
8406 &mut contiguous_row_selections,
8407 selection,
8408 &display_map,
8409 &mut selections,
8410 );
8411
8412 // Move the text spanned by the row range to be before the line preceding the row range
8413 if start_row.0 > 0 {
8414 let range_to_move = Point::new(
8415 start_row.previous_row().0,
8416 buffer.line_len(start_row.previous_row()),
8417 )
8418 ..Point::new(
8419 end_row.previous_row().0,
8420 buffer.line_len(end_row.previous_row()),
8421 );
8422 let insertion_point = display_map
8423 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8424 .0;
8425
8426 // Don't move lines across excerpts
8427 if buffer
8428 .excerpt_containing(insertion_point..range_to_move.end)
8429 .is_some()
8430 {
8431 let text = buffer
8432 .text_for_range(range_to_move.clone())
8433 .flat_map(|s| s.chars())
8434 .skip(1)
8435 .chain(['\n'])
8436 .collect::<String>();
8437
8438 edits.push((
8439 buffer.anchor_after(range_to_move.start)
8440 ..buffer.anchor_before(range_to_move.end),
8441 String::new(),
8442 ));
8443 let insertion_anchor = buffer.anchor_after(insertion_point);
8444 edits.push((insertion_anchor..insertion_anchor, text));
8445
8446 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8447
8448 // Move selections up
8449 new_selections.extend(contiguous_row_selections.drain(..).map(
8450 |mut selection| {
8451 selection.start.row -= row_delta;
8452 selection.end.row -= row_delta;
8453 selection
8454 },
8455 ));
8456
8457 // Move folds up
8458 unfold_ranges.push(range_to_move.clone());
8459 for fold in display_map.folds_in_range(
8460 buffer.anchor_before(range_to_move.start)
8461 ..buffer.anchor_after(range_to_move.end),
8462 ) {
8463 let mut start = fold.range.start.to_point(&buffer);
8464 let mut end = fold.range.end.to_point(&buffer);
8465 start.row -= row_delta;
8466 end.row -= row_delta;
8467 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8468 }
8469 }
8470 }
8471
8472 // If we didn't move line(s), preserve the existing selections
8473 new_selections.append(&mut contiguous_row_selections);
8474 }
8475
8476 self.transact(window, cx, |this, window, cx| {
8477 this.unfold_ranges(&unfold_ranges, true, true, cx);
8478 this.buffer.update(cx, |buffer, cx| {
8479 for (range, text) in edits {
8480 buffer.edit([(range, text)], None, cx);
8481 }
8482 });
8483 this.fold_creases(refold_creases, true, window, cx);
8484 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8485 s.select(new_selections);
8486 })
8487 });
8488 }
8489
8490 pub fn move_line_down(
8491 &mut self,
8492 _: &MoveLineDown,
8493 window: &mut Window,
8494 cx: &mut Context<Self>,
8495 ) {
8496 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8497 let buffer = self.buffer.read(cx).snapshot(cx);
8498
8499 let mut edits = Vec::new();
8500 let mut unfold_ranges = Vec::new();
8501 let mut refold_creases = Vec::new();
8502
8503 let selections = self.selections.all::<Point>(cx);
8504 let mut selections = selections.iter().peekable();
8505 let mut contiguous_row_selections = Vec::new();
8506 let mut new_selections = Vec::new();
8507
8508 while let Some(selection) = selections.next() {
8509 // Find all the selections that span a contiguous row range
8510 let (start_row, end_row) = consume_contiguous_rows(
8511 &mut contiguous_row_selections,
8512 selection,
8513 &display_map,
8514 &mut selections,
8515 );
8516
8517 // Move the text spanned by the row range to be after the last line of the row range
8518 if end_row.0 <= buffer.max_point().row {
8519 let range_to_move =
8520 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8521 let insertion_point = display_map
8522 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8523 .0;
8524
8525 // Don't move lines across excerpt boundaries
8526 if buffer
8527 .excerpt_containing(range_to_move.start..insertion_point)
8528 .is_some()
8529 {
8530 let mut text = String::from("\n");
8531 text.extend(buffer.text_for_range(range_to_move.clone()));
8532 text.pop(); // Drop trailing newline
8533 edits.push((
8534 buffer.anchor_after(range_to_move.start)
8535 ..buffer.anchor_before(range_to_move.end),
8536 String::new(),
8537 ));
8538 let insertion_anchor = buffer.anchor_after(insertion_point);
8539 edits.push((insertion_anchor..insertion_anchor, text));
8540
8541 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8542
8543 // Move selections down
8544 new_selections.extend(contiguous_row_selections.drain(..).map(
8545 |mut selection| {
8546 selection.start.row += row_delta;
8547 selection.end.row += row_delta;
8548 selection
8549 },
8550 ));
8551
8552 // Move folds down
8553 unfold_ranges.push(range_to_move.clone());
8554 for fold in display_map.folds_in_range(
8555 buffer.anchor_before(range_to_move.start)
8556 ..buffer.anchor_after(range_to_move.end),
8557 ) {
8558 let mut start = fold.range.start.to_point(&buffer);
8559 let mut end = fold.range.end.to_point(&buffer);
8560 start.row += row_delta;
8561 end.row += row_delta;
8562 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8563 }
8564 }
8565 }
8566
8567 // If we didn't move line(s), preserve the existing selections
8568 new_selections.append(&mut contiguous_row_selections);
8569 }
8570
8571 self.transact(window, cx, |this, window, cx| {
8572 this.unfold_ranges(&unfold_ranges, true, true, cx);
8573 this.buffer.update(cx, |buffer, cx| {
8574 for (range, text) in edits {
8575 buffer.edit([(range, text)], None, cx);
8576 }
8577 });
8578 this.fold_creases(refold_creases, true, window, cx);
8579 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8580 s.select(new_selections)
8581 });
8582 });
8583 }
8584
8585 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8586 let text_layout_details = &self.text_layout_details(window);
8587 self.transact(window, cx, |this, window, cx| {
8588 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8589 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8590 let line_mode = s.line_mode;
8591 s.move_with(|display_map, selection| {
8592 if !selection.is_empty() || line_mode {
8593 return;
8594 }
8595
8596 let mut head = selection.head();
8597 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8598 if head.column() == display_map.line_len(head.row()) {
8599 transpose_offset = display_map
8600 .buffer_snapshot
8601 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8602 }
8603
8604 if transpose_offset == 0 {
8605 return;
8606 }
8607
8608 *head.column_mut() += 1;
8609 head = display_map.clip_point(head, Bias::Right);
8610 let goal = SelectionGoal::HorizontalPosition(
8611 display_map
8612 .x_for_display_point(head, text_layout_details)
8613 .into(),
8614 );
8615 selection.collapse_to(head, goal);
8616
8617 let transpose_start = display_map
8618 .buffer_snapshot
8619 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8620 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8621 let transpose_end = display_map
8622 .buffer_snapshot
8623 .clip_offset(transpose_offset + 1, Bias::Right);
8624 if let Some(ch) =
8625 display_map.buffer_snapshot.chars_at(transpose_start).next()
8626 {
8627 edits.push((transpose_start..transpose_offset, String::new()));
8628 edits.push((transpose_end..transpose_end, ch.to_string()));
8629 }
8630 }
8631 });
8632 edits
8633 });
8634 this.buffer
8635 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8636 let selections = this.selections.all::<usize>(cx);
8637 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8638 s.select(selections);
8639 });
8640 });
8641 }
8642
8643 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8644 self.rewrap_impl(false, cx)
8645 }
8646
8647 pub fn rewrap_impl(&mut self, override_language_settings: bool, cx: &mut Context<Self>) {
8648 let buffer = self.buffer.read(cx).snapshot(cx);
8649 let selections = self.selections.all::<Point>(cx);
8650 let mut selections = selections.iter().peekable();
8651
8652 let mut edits = Vec::new();
8653 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8654
8655 while let Some(selection) = selections.next() {
8656 let mut start_row = selection.start.row;
8657 let mut end_row = selection.end.row;
8658
8659 // Skip selections that overlap with a range that has already been rewrapped.
8660 let selection_range = start_row..end_row;
8661 if rewrapped_row_ranges
8662 .iter()
8663 .any(|range| range.overlaps(&selection_range))
8664 {
8665 continue;
8666 }
8667
8668 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
8669
8670 // Since not all lines in the selection may be at the same indent
8671 // level, choose the indent size that is the most common between all
8672 // of the lines.
8673 //
8674 // If there is a tie, we use the deepest indent.
8675 let (indent_size, indent_end) = {
8676 let mut indent_size_occurrences = HashMap::default();
8677 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8678
8679 for row in start_row..=end_row {
8680 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8681 rows_by_indent_size.entry(indent).or_default().push(row);
8682 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8683 }
8684
8685 let indent_size = indent_size_occurrences
8686 .into_iter()
8687 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8688 .map(|(indent, _)| indent)
8689 .unwrap_or_default();
8690 let row = rows_by_indent_size[&indent_size][0];
8691 let indent_end = Point::new(row, indent_size.len);
8692
8693 (indent_size, indent_end)
8694 };
8695
8696 let mut line_prefix = indent_size.chars().collect::<String>();
8697
8698 let mut inside_comment = false;
8699 if let Some(comment_prefix) =
8700 buffer
8701 .language_scope_at(selection.head())
8702 .and_then(|language| {
8703 language
8704 .line_comment_prefixes()
8705 .iter()
8706 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8707 .cloned()
8708 })
8709 {
8710 line_prefix.push_str(&comment_prefix);
8711 inside_comment = true;
8712 }
8713
8714 let language_settings = buffer.language_settings_at(selection.head(), cx);
8715 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8716 RewrapBehavior::InComments => inside_comment,
8717 RewrapBehavior::InSelections => !selection.is_empty(),
8718 RewrapBehavior::Anywhere => true,
8719 };
8720
8721 let should_rewrap = override_language_settings
8722 || allow_rewrap_based_on_language
8723 || self.hard_wrap.is_some();
8724 if !should_rewrap {
8725 continue;
8726 }
8727
8728 if selection.is_empty() {
8729 'expand_upwards: while start_row > 0 {
8730 let prev_row = start_row - 1;
8731 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8732 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8733 {
8734 start_row = prev_row;
8735 } else {
8736 break 'expand_upwards;
8737 }
8738 }
8739
8740 'expand_downwards: while end_row < buffer.max_point().row {
8741 let next_row = end_row + 1;
8742 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8743 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8744 {
8745 end_row = next_row;
8746 } else {
8747 break 'expand_downwards;
8748 }
8749 }
8750 }
8751
8752 let start = Point::new(start_row, 0);
8753 let start_offset = start.to_offset(&buffer);
8754 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8755 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8756 let Some(lines_without_prefixes) = selection_text
8757 .lines()
8758 .map(|line| {
8759 line.strip_prefix(&line_prefix)
8760 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8761 .ok_or_else(|| {
8762 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8763 })
8764 })
8765 .collect::<Result<Vec<_>, _>>()
8766 .log_err()
8767 else {
8768 continue;
8769 };
8770
8771 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
8772 buffer
8773 .language_settings_at(Point::new(start_row, 0), cx)
8774 .preferred_line_length as usize
8775 });
8776 let wrapped_text = wrap_with_prefix(
8777 line_prefix,
8778 lines_without_prefixes.join(" "),
8779 wrap_column,
8780 tab_size,
8781 );
8782
8783 // TODO: should always use char-based diff while still supporting cursor behavior that
8784 // matches vim.
8785 let mut diff_options = DiffOptions::default();
8786 if override_language_settings {
8787 diff_options.max_word_diff_len = 0;
8788 diff_options.max_word_diff_line_count = 0;
8789 } else {
8790 diff_options.max_word_diff_len = usize::MAX;
8791 diff_options.max_word_diff_line_count = usize::MAX;
8792 }
8793
8794 for (old_range, new_text) in
8795 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8796 {
8797 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8798 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8799 edits.push((edit_start..edit_end, new_text));
8800 }
8801
8802 rewrapped_row_ranges.push(start_row..=end_row);
8803 }
8804
8805 self.buffer
8806 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8807 }
8808
8809 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8810 let mut text = String::new();
8811 let buffer = self.buffer.read(cx).snapshot(cx);
8812 let mut selections = self.selections.all::<Point>(cx);
8813 let mut clipboard_selections = Vec::with_capacity(selections.len());
8814 {
8815 let max_point = buffer.max_point();
8816 let mut is_first = true;
8817 for selection in &mut selections {
8818 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8819 if is_entire_line {
8820 selection.start = Point::new(selection.start.row, 0);
8821 if !selection.is_empty() && selection.end.column == 0 {
8822 selection.end = cmp::min(max_point, selection.end);
8823 } else {
8824 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8825 }
8826 selection.goal = SelectionGoal::None;
8827 }
8828 if is_first {
8829 is_first = false;
8830 } else {
8831 text += "\n";
8832 }
8833 let mut len = 0;
8834 for chunk in buffer.text_for_range(selection.start..selection.end) {
8835 text.push_str(chunk);
8836 len += chunk.len();
8837 }
8838 clipboard_selections.push(ClipboardSelection {
8839 len,
8840 is_entire_line,
8841 first_line_indent: buffer
8842 .indent_size_for_line(MultiBufferRow(selection.start.row))
8843 .len,
8844 });
8845 }
8846 }
8847
8848 self.transact(window, cx, |this, window, cx| {
8849 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8850 s.select(selections);
8851 });
8852 this.insert("", window, cx);
8853 });
8854 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8855 }
8856
8857 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8858 let item = self.cut_common(window, cx);
8859 cx.write_to_clipboard(item);
8860 }
8861
8862 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8863 self.change_selections(None, window, cx, |s| {
8864 s.move_with(|snapshot, sel| {
8865 if sel.is_empty() {
8866 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8867 }
8868 });
8869 });
8870 let item = self.cut_common(window, cx);
8871 cx.set_global(KillRing(item))
8872 }
8873
8874 pub fn kill_ring_yank(
8875 &mut self,
8876 _: &KillRingYank,
8877 window: &mut Window,
8878 cx: &mut Context<Self>,
8879 ) {
8880 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8881 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8882 (kill_ring.text().to_string(), kill_ring.metadata_json())
8883 } else {
8884 return;
8885 }
8886 } else {
8887 return;
8888 };
8889 self.do_paste(&text, metadata, false, window, cx);
8890 }
8891
8892 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8893 let selections = self.selections.all::<Point>(cx);
8894 let buffer = self.buffer.read(cx).read(cx);
8895 let mut text = String::new();
8896
8897 let mut clipboard_selections = Vec::with_capacity(selections.len());
8898 {
8899 let max_point = buffer.max_point();
8900 let mut is_first = true;
8901 for selection in selections.iter() {
8902 let mut start = selection.start;
8903 let mut end = selection.end;
8904 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8905 if is_entire_line {
8906 start = Point::new(start.row, 0);
8907 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8908 }
8909 if is_first {
8910 is_first = false;
8911 } else {
8912 text += "\n";
8913 }
8914 let mut len = 0;
8915 for chunk in buffer.text_for_range(start..end) {
8916 text.push_str(chunk);
8917 len += chunk.len();
8918 }
8919 clipboard_selections.push(ClipboardSelection {
8920 len,
8921 is_entire_line,
8922 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8923 });
8924 }
8925 }
8926
8927 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8928 text,
8929 clipboard_selections,
8930 ));
8931 }
8932
8933 pub fn do_paste(
8934 &mut self,
8935 text: &String,
8936 clipboard_selections: Option<Vec<ClipboardSelection>>,
8937 handle_entire_lines: bool,
8938 window: &mut Window,
8939 cx: &mut Context<Self>,
8940 ) {
8941 if self.read_only(cx) {
8942 return;
8943 }
8944
8945 let clipboard_text = Cow::Borrowed(text);
8946
8947 self.transact(window, cx, |this, window, cx| {
8948 if let Some(mut clipboard_selections) = clipboard_selections {
8949 let old_selections = this.selections.all::<usize>(cx);
8950 let all_selections_were_entire_line =
8951 clipboard_selections.iter().all(|s| s.is_entire_line);
8952 let first_selection_indent_column =
8953 clipboard_selections.first().map(|s| s.first_line_indent);
8954 if clipboard_selections.len() != old_selections.len() {
8955 clipboard_selections.drain(..);
8956 }
8957 let cursor_offset = this.selections.last::<usize>(cx).head();
8958 let mut auto_indent_on_paste = true;
8959
8960 this.buffer.update(cx, |buffer, cx| {
8961 let snapshot = buffer.read(cx);
8962 auto_indent_on_paste = snapshot
8963 .language_settings_at(cursor_offset, cx)
8964 .auto_indent_on_paste;
8965
8966 let mut start_offset = 0;
8967 let mut edits = Vec::new();
8968 let mut original_indent_columns = Vec::new();
8969 for (ix, selection) in old_selections.iter().enumerate() {
8970 let to_insert;
8971 let entire_line;
8972 let original_indent_column;
8973 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8974 let end_offset = start_offset + clipboard_selection.len;
8975 to_insert = &clipboard_text[start_offset..end_offset];
8976 entire_line = clipboard_selection.is_entire_line;
8977 start_offset = end_offset + 1;
8978 original_indent_column = Some(clipboard_selection.first_line_indent);
8979 } else {
8980 to_insert = clipboard_text.as_str();
8981 entire_line = all_selections_were_entire_line;
8982 original_indent_column = first_selection_indent_column
8983 }
8984
8985 // If the corresponding selection was empty when this slice of the
8986 // clipboard text was written, then the entire line containing the
8987 // selection was copied. If this selection is also currently empty,
8988 // then paste the line before the current line of the buffer.
8989 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8990 let column = selection.start.to_point(&snapshot).column as usize;
8991 let line_start = selection.start - column;
8992 line_start..line_start
8993 } else {
8994 selection.range()
8995 };
8996
8997 edits.push((range, to_insert));
8998 original_indent_columns.push(original_indent_column);
8999 }
9000 drop(snapshot);
9001
9002 buffer.edit(
9003 edits,
9004 if auto_indent_on_paste {
9005 Some(AutoindentMode::Block {
9006 original_indent_columns,
9007 })
9008 } else {
9009 None
9010 },
9011 cx,
9012 );
9013 });
9014
9015 let selections = this.selections.all::<usize>(cx);
9016 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9017 s.select(selections)
9018 });
9019 } else {
9020 this.insert(&clipboard_text, window, cx);
9021 }
9022 });
9023 }
9024
9025 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
9026 if let Some(item) = cx.read_from_clipboard() {
9027 let entries = item.entries();
9028
9029 match entries.first() {
9030 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
9031 // of all the pasted entries.
9032 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
9033 .do_paste(
9034 clipboard_string.text(),
9035 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9036 true,
9037 window,
9038 cx,
9039 ),
9040 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9041 }
9042 }
9043 }
9044
9045 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9046 if self.read_only(cx) {
9047 return;
9048 }
9049
9050 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9051 if let Some((selections, _)) =
9052 self.selection_history.transaction(transaction_id).cloned()
9053 {
9054 self.change_selections(None, window, cx, |s| {
9055 s.select_anchors(selections.to_vec());
9056 });
9057 } else {
9058 log::error!(
9059 "No entry in selection_history found for undo. \
9060 This may correspond to a bug where undo does not update the selection. \
9061 If this is occurring, please add details to \
9062 https://github.com/zed-industries/zed/issues/22692"
9063 );
9064 }
9065 self.request_autoscroll(Autoscroll::fit(), cx);
9066 self.unmark_text(window, cx);
9067 self.refresh_inline_completion(true, false, window, cx);
9068 cx.emit(EditorEvent::Edited { transaction_id });
9069 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9070 }
9071 }
9072
9073 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9074 if self.read_only(cx) {
9075 return;
9076 }
9077
9078 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9079 if let Some((_, Some(selections))) =
9080 self.selection_history.transaction(transaction_id).cloned()
9081 {
9082 self.change_selections(None, window, cx, |s| {
9083 s.select_anchors(selections.to_vec());
9084 });
9085 } else {
9086 log::error!(
9087 "No entry in selection_history found for redo. \
9088 This may correspond to a bug where undo does not update the selection. \
9089 If this is occurring, please add details to \
9090 https://github.com/zed-industries/zed/issues/22692"
9091 );
9092 }
9093 self.request_autoscroll(Autoscroll::fit(), cx);
9094 self.unmark_text(window, cx);
9095 self.refresh_inline_completion(true, false, window, cx);
9096 cx.emit(EditorEvent::Edited { transaction_id });
9097 }
9098 }
9099
9100 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9101 self.buffer
9102 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9103 }
9104
9105 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9106 self.buffer
9107 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9108 }
9109
9110 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9111 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9112 let line_mode = s.line_mode;
9113 s.move_with(|map, selection| {
9114 let cursor = if selection.is_empty() && !line_mode {
9115 movement::left(map, selection.start)
9116 } else {
9117 selection.start
9118 };
9119 selection.collapse_to(cursor, SelectionGoal::None);
9120 });
9121 })
9122 }
9123
9124 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9125 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9126 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9127 })
9128 }
9129
9130 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9131 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9132 let line_mode = s.line_mode;
9133 s.move_with(|map, selection| {
9134 let cursor = if selection.is_empty() && !line_mode {
9135 movement::right(map, selection.end)
9136 } else {
9137 selection.end
9138 };
9139 selection.collapse_to(cursor, SelectionGoal::None)
9140 });
9141 })
9142 }
9143
9144 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9145 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9146 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9147 })
9148 }
9149
9150 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9151 if self.take_rename(true, window, cx).is_some() {
9152 return;
9153 }
9154
9155 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9156 cx.propagate();
9157 return;
9158 }
9159
9160 let text_layout_details = &self.text_layout_details(window);
9161 let selection_count = self.selections.count();
9162 let first_selection = self.selections.first_anchor();
9163
9164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9165 let line_mode = s.line_mode;
9166 s.move_with(|map, selection| {
9167 if !selection.is_empty() && !line_mode {
9168 selection.goal = SelectionGoal::None;
9169 }
9170 let (cursor, goal) = movement::up(
9171 map,
9172 selection.start,
9173 selection.goal,
9174 false,
9175 text_layout_details,
9176 );
9177 selection.collapse_to(cursor, goal);
9178 });
9179 });
9180
9181 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9182 {
9183 cx.propagate();
9184 }
9185 }
9186
9187 pub fn move_up_by_lines(
9188 &mut self,
9189 action: &MoveUpByLines,
9190 window: &mut Window,
9191 cx: &mut Context<Self>,
9192 ) {
9193 if self.take_rename(true, window, cx).is_some() {
9194 return;
9195 }
9196
9197 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9198 cx.propagate();
9199 return;
9200 }
9201
9202 let text_layout_details = &self.text_layout_details(window);
9203
9204 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9205 let line_mode = s.line_mode;
9206 s.move_with(|map, selection| {
9207 if !selection.is_empty() && !line_mode {
9208 selection.goal = SelectionGoal::None;
9209 }
9210 let (cursor, goal) = movement::up_by_rows(
9211 map,
9212 selection.start,
9213 action.lines,
9214 selection.goal,
9215 false,
9216 text_layout_details,
9217 );
9218 selection.collapse_to(cursor, goal);
9219 });
9220 })
9221 }
9222
9223 pub fn move_down_by_lines(
9224 &mut self,
9225 action: &MoveDownByLines,
9226 window: &mut Window,
9227 cx: &mut Context<Self>,
9228 ) {
9229 if self.take_rename(true, window, cx).is_some() {
9230 return;
9231 }
9232
9233 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9234 cx.propagate();
9235 return;
9236 }
9237
9238 let text_layout_details = &self.text_layout_details(window);
9239
9240 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9241 let line_mode = s.line_mode;
9242 s.move_with(|map, selection| {
9243 if !selection.is_empty() && !line_mode {
9244 selection.goal = SelectionGoal::None;
9245 }
9246 let (cursor, goal) = movement::down_by_rows(
9247 map,
9248 selection.start,
9249 action.lines,
9250 selection.goal,
9251 false,
9252 text_layout_details,
9253 );
9254 selection.collapse_to(cursor, goal);
9255 });
9256 })
9257 }
9258
9259 pub fn select_down_by_lines(
9260 &mut self,
9261 action: &SelectDownByLines,
9262 window: &mut Window,
9263 cx: &mut Context<Self>,
9264 ) {
9265 let text_layout_details = &self.text_layout_details(window);
9266 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9267 s.move_heads_with(|map, head, goal| {
9268 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9269 })
9270 })
9271 }
9272
9273 pub fn select_up_by_lines(
9274 &mut self,
9275 action: &SelectUpByLines,
9276 window: &mut Window,
9277 cx: &mut Context<Self>,
9278 ) {
9279 let text_layout_details = &self.text_layout_details(window);
9280 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9281 s.move_heads_with(|map, head, goal| {
9282 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9283 })
9284 })
9285 }
9286
9287 pub fn select_page_up(
9288 &mut self,
9289 _: &SelectPageUp,
9290 window: &mut Window,
9291 cx: &mut Context<Self>,
9292 ) {
9293 let Some(row_count) = self.visible_row_count() else {
9294 return;
9295 };
9296
9297 let text_layout_details = &self.text_layout_details(window);
9298
9299 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9300 s.move_heads_with(|map, head, goal| {
9301 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9302 })
9303 })
9304 }
9305
9306 pub fn move_page_up(
9307 &mut self,
9308 action: &MovePageUp,
9309 window: &mut Window,
9310 cx: &mut Context<Self>,
9311 ) {
9312 if self.take_rename(true, window, cx).is_some() {
9313 return;
9314 }
9315
9316 if self
9317 .context_menu
9318 .borrow_mut()
9319 .as_mut()
9320 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9321 .unwrap_or(false)
9322 {
9323 return;
9324 }
9325
9326 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9327 cx.propagate();
9328 return;
9329 }
9330
9331 let Some(row_count) = self.visible_row_count() else {
9332 return;
9333 };
9334
9335 let autoscroll = if action.center_cursor {
9336 Autoscroll::center()
9337 } else {
9338 Autoscroll::fit()
9339 };
9340
9341 let text_layout_details = &self.text_layout_details(window);
9342
9343 self.change_selections(Some(autoscroll), window, cx, |s| {
9344 let line_mode = s.line_mode;
9345 s.move_with(|map, selection| {
9346 if !selection.is_empty() && !line_mode {
9347 selection.goal = SelectionGoal::None;
9348 }
9349 let (cursor, goal) = movement::up_by_rows(
9350 map,
9351 selection.end,
9352 row_count,
9353 selection.goal,
9354 false,
9355 text_layout_details,
9356 );
9357 selection.collapse_to(cursor, goal);
9358 });
9359 });
9360 }
9361
9362 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9363 let text_layout_details = &self.text_layout_details(window);
9364 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9365 s.move_heads_with(|map, head, goal| {
9366 movement::up(map, head, goal, false, text_layout_details)
9367 })
9368 })
9369 }
9370
9371 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9372 self.take_rename(true, window, cx);
9373
9374 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9375 cx.propagate();
9376 return;
9377 }
9378
9379 let text_layout_details = &self.text_layout_details(window);
9380 let selection_count = self.selections.count();
9381 let first_selection = self.selections.first_anchor();
9382
9383 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9384 let line_mode = s.line_mode;
9385 s.move_with(|map, selection| {
9386 if !selection.is_empty() && !line_mode {
9387 selection.goal = SelectionGoal::None;
9388 }
9389 let (cursor, goal) = movement::down(
9390 map,
9391 selection.end,
9392 selection.goal,
9393 false,
9394 text_layout_details,
9395 );
9396 selection.collapse_to(cursor, goal);
9397 });
9398 });
9399
9400 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9401 {
9402 cx.propagate();
9403 }
9404 }
9405
9406 pub fn select_page_down(
9407 &mut self,
9408 _: &SelectPageDown,
9409 window: &mut Window,
9410 cx: &mut Context<Self>,
9411 ) {
9412 let Some(row_count) = self.visible_row_count() else {
9413 return;
9414 };
9415
9416 let text_layout_details = &self.text_layout_details(window);
9417
9418 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9419 s.move_heads_with(|map, head, goal| {
9420 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9421 })
9422 })
9423 }
9424
9425 pub fn move_page_down(
9426 &mut self,
9427 action: &MovePageDown,
9428 window: &mut Window,
9429 cx: &mut Context<Self>,
9430 ) {
9431 if self.take_rename(true, window, cx).is_some() {
9432 return;
9433 }
9434
9435 if self
9436 .context_menu
9437 .borrow_mut()
9438 .as_mut()
9439 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9440 .unwrap_or(false)
9441 {
9442 return;
9443 }
9444
9445 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9446 cx.propagate();
9447 return;
9448 }
9449
9450 let Some(row_count) = self.visible_row_count() else {
9451 return;
9452 };
9453
9454 let autoscroll = if action.center_cursor {
9455 Autoscroll::center()
9456 } else {
9457 Autoscroll::fit()
9458 };
9459
9460 let text_layout_details = &self.text_layout_details(window);
9461 self.change_selections(Some(autoscroll), window, cx, |s| {
9462 let line_mode = s.line_mode;
9463 s.move_with(|map, selection| {
9464 if !selection.is_empty() && !line_mode {
9465 selection.goal = SelectionGoal::None;
9466 }
9467 let (cursor, goal) = movement::down_by_rows(
9468 map,
9469 selection.end,
9470 row_count,
9471 selection.goal,
9472 false,
9473 text_layout_details,
9474 );
9475 selection.collapse_to(cursor, goal);
9476 });
9477 });
9478 }
9479
9480 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9481 let text_layout_details = &self.text_layout_details(window);
9482 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9483 s.move_heads_with(|map, head, goal| {
9484 movement::down(map, head, goal, false, text_layout_details)
9485 })
9486 });
9487 }
9488
9489 pub fn context_menu_first(
9490 &mut self,
9491 _: &ContextMenuFirst,
9492 _window: &mut Window,
9493 cx: &mut Context<Self>,
9494 ) {
9495 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9496 context_menu.select_first(self.completion_provider.as_deref(), cx);
9497 }
9498 }
9499
9500 pub fn context_menu_prev(
9501 &mut self,
9502 _: &ContextMenuPrevious,
9503 _window: &mut Window,
9504 cx: &mut Context<Self>,
9505 ) {
9506 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9507 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9508 }
9509 }
9510
9511 pub fn context_menu_next(
9512 &mut self,
9513 _: &ContextMenuNext,
9514 _window: &mut Window,
9515 cx: &mut Context<Self>,
9516 ) {
9517 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9518 context_menu.select_next(self.completion_provider.as_deref(), cx);
9519 }
9520 }
9521
9522 pub fn context_menu_last(
9523 &mut self,
9524 _: &ContextMenuLast,
9525 _window: &mut Window,
9526 cx: &mut Context<Self>,
9527 ) {
9528 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9529 context_menu.select_last(self.completion_provider.as_deref(), cx);
9530 }
9531 }
9532
9533 pub fn move_to_previous_word_start(
9534 &mut self,
9535 _: &MoveToPreviousWordStart,
9536 window: &mut Window,
9537 cx: &mut Context<Self>,
9538 ) {
9539 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9540 s.move_cursors_with(|map, head, _| {
9541 (
9542 movement::previous_word_start(map, head),
9543 SelectionGoal::None,
9544 )
9545 });
9546 })
9547 }
9548
9549 pub fn move_to_previous_subword_start(
9550 &mut self,
9551 _: &MoveToPreviousSubwordStart,
9552 window: &mut Window,
9553 cx: &mut Context<Self>,
9554 ) {
9555 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9556 s.move_cursors_with(|map, head, _| {
9557 (
9558 movement::previous_subword_start(map, head),
9559 SelectionGoal::None,
9560 )
9561 });
9562 })
9563 }
9564
9565 pub fn select_to_previous_word_start(
9566 &mut self,
9567 _: &SelectToPreviousWordStart,
9568 window: &mut Window,
9569 cx: &mut Context<Self>,
9570 ) {
9571 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9572 s.move_heads_with(|map, head, _| {
9573 (
9574 movement::previous_word_start(map, head),
9575 SelectionGoal::None,
9576 )
9577 });
9578 })
9579 }
9580
9581 pub fn select_to_previous_subword_start(
9582 &mut self,
9583 _: &SelectToPreviousSubwordStart,
9584 window: &mut Window,
9585 cx: &mut Context<Self>,
9586 ) {
9587 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9588 s.move_heads_with(|map, head, _| {
9589 (
9590 movement::previous_subword_start(map, head),
9591 SelectionGoal::None,
9592 )
9593 });
9594 })
9595 }
9596
9597 pub fn delete_to_previous_word_start(
9598 &mut self,
9599 action: &DeleteToPreviousWordStart,
9600 window: &mut Window,
9601 cx: &mut Context<Self>,
9602 ) {
9603 self.transact(window, cx, |this, window, cx| {
9604 this.select_autoclose_pair(window, cx);
9605 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9606 let line_mode = s.line_mode;
9607 s.move_with(|map, selection| {
9608 if selection.is_empty() && !line_mode {
9609 let cursor = if action.ignore_newlines {
9610 movement::previous_word_start(map, selection.head())
9611 } else {
9612 movement::previous_word_start_or_newline(map, selection.head())
9613 };
9614 selection.set_head(cursor, SelectionGoal::None);
9615 }
9616 });
9617 });
9618 this.insert("", window, cx);
9619 });
9620 }
9621
9622 pub fn delete_to_previous_subword_start(
9623 &mut self,
9624 _: &DeleteToPreviousSubwordStart,
9625 window: &mut Window,
9626 cx: &mut Context<Self>,
9627 ) {
9628 self.transact(window, cx, |this, window, cx| {
9629 this.select_autoclose_pair(window, cx);
9630 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9631 let line_mode = s.line_mode;
9632 s.move_with(|map, selection| {
9633 if selection.is_empty() && !line_mode {
9634 let cursor = movement::previous_subword_start(map, selection.head());
9635 selection.set_head(cursor, SelectionGoal::None);
9636 }
9637 });
9638 });
9639 this.insert("", window, cx);
9640 });
9641 }
9642
9643 pub fn move_to_next_word_end(
9644 &mut self,
9645 _: &MoveToNextWordEnd,
9646 window: &mut Window,
9647 cx: &mut Context<Self>,
9648 ) {
9649 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9650 s.move_cursors_with(|map, head, _| {
9651 (movement::next_word_end(map, head), SelectionGoal::None)
9652 });
9653 })
9654 }
9655
9656 pub fn move_to_next_subword_end(
9657 &mut self,
9658 _: &MoveToNextSubwordEnd,
9659 window: &mut Window,
9660 cx: &mut Context<Self>,
9661 ) {
9662 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9663 s.move_cursors_with(|map, head, _| {
9664 (movement::next_subword_end(map, head), SelectionGoal::None)
9665 });
9666 })
9667 }
9668
9669 pub fn select_to_next_word_end(
9670 &mut self,
9671 _: &SelectToNextWordEnd,
9672 window: &mut Window,
9673 cx: &mut Context<Self>,
9674 ) {
9675 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9676 s.move_heads_with(|map, head, _| {
9677 (movement::next_word_end(map, head), SelectionGoal::None)
9678 });
9679 })
9680 }
9681
9682 pub fn select_to_next_subword_end(
9683 &mut self,
9684 _: &SelectToNextSubwordEnd,
9685 window: &mut Window,
9686 cx: &mut Context<Self>,
9687 ) {
9688 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9689 s.move_heads_with(|map, head, _| {
9690 (movement::next_subword_end(map, head), SelectionGoal::None)
9691 });
9692 })
9693 }
9694
9695 pub fn delete_to_next_word_end(
9696 &mut self,
9697 action: &DeleteToNextWordEnd,
9698 window: &mut Window,
9699 cx: &mut Context<Self>,
9700 ) {
9701 self.transact(window, cx, |this, window, cx| {
9702 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9703 let line_mode = s.line_mode;
9704 s.move_with(|map, selection| {
9705 if selection.is_empty() && !line_mode {
9706 let cursor = if action.ignore_newlines {
9707 movement::next_word_end(map, selection.head())
9708 } else {
9709 movement::next_word_end_or_newline(map, selection.head())
9710 };
9711 selection.set_head(cursor, SelectionGoal::None);
9712 }
9713 });
9714 });
9715 this.insert("", window, cx);
9716 });
9717 }
9718
9719 pub fn delete_to_next_subword_end(
9720 &mut self,
9721 _: &DeleteToNextSubwordEnd,
9722 window: &mut Window,
9723 cx: &mut Context<Self>,
9724 ) {
9725 self.transact(window, cx, |this, window, cx| {
9726 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9727 s.move_with(|map, selection| {
9728 if selection.is_empty() {
9729 let cursor = movement::next_subword_end(map, selection.head());
9730 selection.set_head(cursor, SelectionGoal::None);
9731 }
9732 });
9733 });
9734 this.insert("", window, cx);
9735 });
9736 }
9737
9738 pub fn move_to_beginning_of_line(
9739 &mut self,
9740 action: &MoveToBeginningOfLine,
9741 window: &mut Window,
9742 cx: &mut Context<Self>,
9743 ) {
9744 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9745 s.move_cursors_with(|map, head, _| {
9746 (
9747 movement::indented_line_beginning(
9748 map,
9749 head,
9750 action.stop_at_soft_wraps,
9751 action.stop_at_indent,
9752 ),
9753 SelectionGoal::None,
9754 )
9755 });
9756 })
9757 }
9758
9759 pub fn select_to_beginning_of_line(
9760 &mut self,
9761 action: &SelectToBeginningOfLine,
9762 window: &mut Window,
9763 cx: &mut Context<Self>,
9764 ) {
9765 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9766 s.move_heads_with(|map, head, _| {
9767 (
9768 movement::indented_line_beginning(
9769 map,
9770 head,
9771 action.stop_at_soft_wraps,
9772 action.stop_at_indent,
9773 ),
9774 SelectionGoal::None,
9775 )
9776 });
9777 });
9778 }
9779
9780 pub fn delete_to_beginning_of_line(
9781 &mut self,
9782 action: &DeleteToBeginningOfLine,
9783 window: &mut Window,
9784 cx: &mut Context<Self>,
9785 ) {
9786 self.transact(window, cx, |this, window, cx| {
9787 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9788 s.move_with(|_, selection| {
9789 selection.reversed = true;
9790 });
9791 });
9792
9793 this.select_to_beginning_of_line(
9794 &SelectToBeginningOfLine {
9795 stop_at_soft_wraps: false,
9796 stop_at_indent: action.stop_at_indent,
9797 },
9798 window,
9799 cx,
9800 );
9801 this.backspace(&Backspace, window, cx);
9802 });
9803 }
9804
9805 pub fn move_to_end_of_line(
9806 &mut self,
9807 action: &MoveToEndOfLine,
9808 window: &mut Window,
9809 cx: &mut Context<Self>,
9810 ) {
9811 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9812 s.move_cursors_with(|map, head, _| {
9813 (
9814 movement::line_end(map, head, action.stop_at_soft_wraps),
9815 SelectionGoal::None,
9816 )
9817 });
9818 })
9819 }
9820
9821 pub fn select_to_end_of_line(
9822 &mut self,
9823 action: &SelectToEndOfLine,
9824 window: &mut Window,
9825 cx: &mut Context<Self>,
9826 ) {
9827 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9828 s.move_heads_with(|map, head, _| {
9829 (
9830 movement::line_end(map, head, action.stop_at_soft_wraps),
9831 SelectionGoal::None,
9832 )
9833 });
9834 })
9835 }
9836
9837 pub fn delete_to_end_of_line(
9838 &mut self,
9839 _: &DeleteToEndOfLine,
9840 window: &mut Window,
9841 cx: &mut Context<Self>,
9842 ) {
9843 self.transact(window, cx, |this, window, cx| {
9844 this.select_to_end_of_line(
9845 &SelectToEndOfLine {
9846 stop_at_soft_wraps: false,
9847 },
9848 window,
9849 cx,
9850 );
9851 this.delete(&Delete, window, cx);
9852 });
9853 }
9854
9855 pub fn cut_to_end_of_line(
9856 &mut self,
9857 _: &CutToEndOfLine,
9858 window: &mut Window,
9859 cx: &mut Context<Self>,
9860 ) {
9861 self.transact(window, cx, |this, window, cx| {
9862 this.select_to_end_of_line(
9863 &SelectToEndOfLine {
9864 stop_at_soft_wraps: false,
9865 },
9866 window,
9867 cx,
9868 );
9869 this.cut(&Cut, window, cx);
9870 });
9871 }
9872
9873 pub fn move_to_start_of_paragraph(
9874 &mut self,
9875 _: &MoveToStartOfParagraph,
9876 window: &mut Window,
9877 cx: &mut Context<Self>,
9878 ) {
9879 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9880 cx.propagate();
9881 return;
9882 }
9883
9884 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9885 s.move_with(|map, selection| {
9886 selection.collapse_to(
9887 movement::start_of_paragraph(map, selection.head(), 1),
9888 SelectionGoal::None,
9889 )
9890 });
9891 })
9892 }
9893
9894 pub fn move_to_end_of_paragraph(
9895 &mut self,
9896 _: &MoveToEndOfParagraph,
9897 window: &mut Window,
9898 cx: &mut Context<Self>,
9899 ) {
9900 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9901 cx.propagate();
9902 return;
9903 }
9904
9905 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9906 s.move_with(|map, selection| {
9907 selection.collapse_to(
9908 movement::end_of_paragraph(map, selection.head(), 1),
9909 SelectionGoal::None,
9910 )
9911 });
9912 })
9913 }
9914
9915 pub fn select_to_start_of_paragraph(
9916 &mut self,
9917 _: &SelectToStartOfParagraph,
9918 window: &mut Window,
9919 cx: &mut Context<Self>,
9920 ) {
9921 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9922 cx.propagate();
9923 return;
9924 }
9925
9926 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9927 s.move_heads_with(|map, head, _| {
9928 (
9929 movement::start_of_paragraph(map, head, 1),
9930 SelectionGoal::None,
9931 )
9932 });
9933 })
9934 }
9935
9936 pub fn select_to_end_of_paragraph(
9937 &mut self,
9938 _: &SelectToEndOfParagraph,
9939 window: &mut Window,
9940 cx: &mut Context<Self>,
9941 ) {
9942 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9943 cx.propagate();
9944 return;
9945 }
9946
9947 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9948 s.move_heads_with(|map, head, _| {
9949 (
9950 movement::end_of_paragraph(map, head, 1),
9951 SelectionGoal::None,
9952 )
9953 });
9954 })
9955 }
9956
9957 pub fn move_to_start_of_excerpt(
9958 &mut self,
9959 _: &MoveToStartOfExcerpt,
9960 window: &mut Window,
9961 cx: &mut Context<Self>,
9962 ) {
9963 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9964 cx.propagate();
9965 return;
9966 }
9967
9968 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9969 s.move_with(|map, selection| {
9970 selection.collapse_to(
9971 movement::start_of_excerpt(
9972 map,
9973 selection.head(),
9974 workspace::searchable::Direction::Prev,
9975 ),
9976 SelectionGoal::None,
9977 )
9978 });
9979 })
9980 }
9981
9982 pub fn move_to_start_of_next_excerpt(
9983 &mut self,
9984 _: &MoveToStartOfNextExcerpt,
9985 window: &mut Window,
9986 cx: &mut Context<Self>,
9987 ) {
9988 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9989 cx.propagate();
9990 return;
9991 }
9992
9993 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9994 s.move_with(|map, selection| {
9995 selection.collapse_to(
9996 movement::start_of_excerpt(
9997 map,
9998 selection.head(),
9999 workspace::searchable::Direction::Next,
10000 ),
10001 SelectionGoal::None,
10002 )
10003 });
10004 })
10005 }
10006
10007 pub fn move_to_end_of_excerpt(
10008 &mut self,
10009 _: &MoveToEndOfExcerpt,
10010 window: &mut Window,
10011 cx: &mut Context<Self>,
10012 ) {
10013 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10014 cx.propagate();
10015 return;
10016 }
10017
10018 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10019 s.move_with(|map, selection| {
10020 selection.collapse_to(
10021 movement::end_of_excerpt(
10022 map,
10023 selection.head(),
10024 workspace::searchable::Direction::Next,
10025 ),
10026 SelectionGoal::None,
10027 )
10028 });
10029 })
10030 }
10031
10032 pub fn move_to_end_of_previous_excerpt(
10033 &mut self,
10034 _: &MoveToEndOfPreviousExcerpt,
10035 window: &mut Window,
10036 cx: &mut Context<Self>,
10037 ) {
10038 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10039 cx.propagate();
10040 return;
10041 }
10042
10043 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10044 s.move_with(|map, selection| {
10045 selection.collapse_to(
10046 movement::end_of_excerpt(
10047 map,
10048 selection.head(),
10049 workspace::searchable::Direction::Prev,
10050 ),
10051 SelectionGoal::None,
10052 )
10053 });
10054 })
10055 }
10056
10057 pub fn select_to_start_of_excerpt(
10058 &mut self,
10059 _: &SelectToStartOfExcerpt,
10060 window: &mut Window,
10061 cx: &mut Context<Self>,
10062 ) {
10063 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10064 cx.propagate();
10065 return;
10066 }
10067
10068 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10069 s.move_heads_with(|map, head, _| {
10070 (
10071 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10072 SelectionGoal::None,
10073 )
10074 });
10075 })
10076 }
10077
10078 pub fn select_to_start_of_next_excerpt(
10079 &mut self,
10080 _: &SelectToStartOfNextExcerpt,
10081 window: &mut Window,
10082 cx: &mut Context<Self>,
10083 ) {
10084 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10085 cx.propagate();
10086 return;
10087 }
10088
10089 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10090 s.move_heads_with(|map, head, _| {
10091 (
10092 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10093 SelectionGoal::None,
10094 )
10095 });
10096 })
10097 }
10098
10099 pub fn select_to_end_of_excerpt(
10100 &mut self,
10101 _: &SelectToEndOfExcerpt,
10102 window: &mut Window,
10103 cx: &mut Context<Self>,
10104 ) {
10105 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10106 cx.propagate();
10107 return;
10108 }
10109
10110 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10111 s.move_heads_with(|map, head, _| {
10112 (
10113 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10114 SelectionGoal::None,
10115 )
10116 });
10117 })
10118 }
10119
10120 pub fn select_to_end_of_previous_excerpt(
10121 &mut self,
10122 _: &SelectToEndOfPreviousExcerpt,
10123 window: &mut Window,
10124 cx: &mut Context<Self>,
10125 ) {
10126 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10127 cx.propagate();
10128 return;
10129 }
10130
10131 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10132 s.move_heads_with(|map, head, _| {
10133 (
10134 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10135 SelectionGoal::None,
10136 )
10137 });
10138 })
10139 }
10140
10141 pub fn move_to_beginning(
10142 &mut self,
10143 _: &MoveToBeginning,
10144 window: &mut Window,
10145 cx: &mut Context<Self>,
10146 ) {
10147 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10148 cx.propagate();
10149 return;
10150 }
10151
10152 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10153 s.select_ranges(vec![0..0]);
10154 });
10155 }
10156
10157 pub fn select_to_beginning(
10158 &mut self,
10159 _: &SelectToBeginning,
10160 window: &mut Window,
10161 cx: &mut Context<Self>,
10162 ) {
10163 let mut selection = self.selections.last::<Point>(cx);
10164 selection.set_head(Point::zero(), SelectionGoal::None);
10165
10166 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10167 s.select(vec![selection]);
10168 });
10169 }
10170
10171 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10172 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10173 cx.propagate();
10174 return;
10175 }
10176
10177 let cursor = self.buffer.read(cx).read(cx).len();
10178 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10179 s.select_ranges(vec![cursor..cursor])
10180 });
10181 }
10182
10183 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10184 self.nav_history = nav_history;
10185 }
10186
10187 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10188 self.nav_history.as_ref()
10189 }
10190
10191 fn push_to_nav_history(
10192 &mut self,
10193 cursor_anchor: Anchor,
10194 new_position: Option<Point>,
10195 cx: &mut Context<Self>,
10196 ) {
10197 if let Some(nav_history) = self.nav_history.as_mut() {
10198 let buffer = self.buffer.read(cx).read(cx);
10199 let cursor_position = cursor_anchor.to_point(&buffer);
10200 let scroll_state = self.scroll_manager.anchor();
10201 let scroll_top_row = scroll_state.top_row(&buffer);
10202 drop(buffer);
10203
10204 if let Some(new_position) = new_position {
10205 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10206 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10207 return;
10208 }
10209 }
10210
10211 nav_history.push(
10212 Some(NavigationData {
10213 cursor_anchor,
10214 cursor_position,
10215 scroll_anchor: scroll_state,
10216 scroll_top_row,
10217 }),
10218 cx,
10219 );
10220 }
10221 }
10222
10223 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10224 let buffer = self.buffer.read(cx).snapshot(cx);
10225 let mut selection = self.selections.first::<usize>(cx);
10226 selection.set_head(buffer.len(), SelectionGoal::None);
10227 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10228 s.select(vec![selection]);
10229 });
10230 }
10231
10232 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10233 let end = self.buffer.read(cx).read(cx).len();
10234 self.change_selections(None, window, cx, |s| {
10235 s.select_ranges(vec![0..end]);
10236 });
10237 }
10238
10239 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10240 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10241 let mut selections = self.selections.all::<Point>(cx);
10242 let max_point = display_map.buffer_snapshot.max_point();
10243 for selection in &mut selections {
10244 let rows = selection.spanned_rows(true, &display_map);
10245 selection.start = Point::new(rows.start.0, 0);
10246 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10247 selection.reversed = false;
10248 }
10249 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10250 s.select(selections);
10251 });
10252 }
10253
10254 pub fn split_selection_into_lines(
10255 &mut self,
10256 _: &SplitSelectionIntoLines,
10257 window: &mut Window,
10258 cx: &mut Context<Self>,
10259 ) {
10260 let selections = self
10261 .selections
10262 .all::<Point>(cx)
10263 .into_iter()
10264 .map(|selection| selection.start..selection.end)
10265 .collect::<Vec<_>>();
10266 self.unfold_ranges(&selections, true, true, cx);
10267
10268 let mut new_selection_ranges = Vec::new();
10269 {
10270 let buffer = self.buffer.read(cx).read(cx);
10271 for selection in selections {
10272 for row in selection.start.row..selection.end.row {
10273 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10274 new_selection_ranges.push(cursor..cursor);
10275 }
10276
10277 let is_multiline_selection = selection.start.row != selection.end.row;
10278 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10279 // so this action feels more ergonomic when paired with other selection operations
10280 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10281 if !should_skip_last {
10282 new_selection_ranges.push(selection.end..selection.end);
10283 }
10284 }
10285 }
10286 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10287 s.select_ranges(new_selection_ranges);
10288 });
10289 }
10290
10291 pub fn add_selection_above(
10292 &mut self,
10293 _: &AddSelectionAbove,
10294 window: &mut Window,
10295 cx: &mut Context<Self>,
10296 ) {
10297 self.add_selection(true, window, cx);
10298 }
10299
10300 pub fn add_selection_below(
10301 &mut self,
10302 _: &AddSelectionBelow,
10303 window: &mut Window,
10304 cx: &mut Context<Self>,
10305 ) {
10306 self.add_selection(false, window, cx);
10307 }
10308
10309 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10310 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10311 let mut selections = self.selections.all::<Point>(cx);
10312 let text_layout_details = self.text_layout_details(window);
10313 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10314 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10315 let range = oldest_selection.display_range(&display_map).sorted();
10316
10317 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10318 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10319 let positions = start_x.min(end_x)..start_x.max(end_x);
10320
10321 selections.clear();
10322 let mut stack = Vec::new();
10323 for row in range.start.row().0..=range.end.row().0 {
10324 if let Some(selection) = self.selections.build_columnar_selection(
10325 &display_map,
10326 DisplayRow(row),
10327 &positions,
10328 oldest_selection.reversed,
10329 &text_layout_details,
10330 ) {
10331 stack.push(selection.id);
10332 selections.push(selection);
10333 }
10334 }
10335
10336 if above {
10337 stack.reverse();
10338 }
10339
10340 AddSelectionsState { above, stack }
10341 });
10342
10343 let last_added_selection = *state.stack.last().unwrap();
10344 let mut new_selections = Vec::new();
10345 if above == state.above {
10346 let end_row = if above {
10347 DisplayRow(0)
10348 } else {
10349 display_map.max_point().row()
10350 };
10351
10352 'outer: for selection in selections {
10353 if selection.id == last_added_selection {
10354 let range = selection.display_range(&display_map).sorted();
10355 debug_assert_eq!(range.start.row(), range.end.row());
10356 let mut row = range.start.row();
10357 let positions =
10358 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10359 px(start)..px(end)
10360 } else {
10361 let start_x =
10362 display_map.x_for_display_point(range.start, &text_layout_details);
10363 let end_x =
10364 display_map.x_for_display_point(range.end, &text_layout_details);
10365 start_x.min(end_x)..start_x.max(end_x)
10366 };
10367
10368 while row != end_row {
10369 if above {
10370 row.0 -= 1;
10371 } else {
10372 row.0 += 1;
10373 }
10374
10375 if let Some(new_selection) = self.selections.build_columnar_selection(
10376 &display_map,
10377 row,
10378 &positions,
10379 selection.reversed,
10380 &text_layout_details,
10381 ) {
10382 state.stack.push(new_selection.id);
10383 if above {
10384 new_selections.push(new_selection);
10385 new_selections.push(selection);
10386 } else {
10387 new_selections.push(selection);
10388 new_selections.push(new_selection);
10389 }
10390
10391 continue 'outer;
10392 }
10393 }
10394 }
10395
10396 new_selections.push(selection);
10397 }
10398 } else {
10399 new_selections = selections;
10400 new_selections.retain(|s| s.id != last_added_selection);
10401 state.stack.pop();
10402 }
10403
10404 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10405 s.select(new_selections);
10406 });
10407 if state.stack.len() > 1 {
10408 self.add_selections_state = Some(state);
10409 }
10410 }
10411
10412 pub fn select_next_match_internal(
10413 &mut self,
10414 display_map: &DisplaySnapshot,
10415 replace_newest: bool,
10416 autoscroll: Option<Autoscroll>,
10417 window: &mut Window,
10418 cx: &mut Context<Self>,
10419 ) -> Result<()> {
10420 fn select_next_match_ranges(
10421 this: &mut Editor,
10422 range: Range<usize>,
10423 replace_newest: bool,
10424 auto_scroll: Option<Autoscroll>,
10425 window: &mut Window,
10426 cx: &mut Context<Editor>,
10427 ) {
10428 this.unfold_ranges(&[range.clone()], false, true, cx);
10429 this.change_selections(auto_scroll, window, cx, |s| {
10430 if replace_newest {
10431 s.delete(s.newest_anchor().id);
10432 }
10433 s.insert_range(range.clone());
10434 });
10435 }
10436
10437 let buffer = &display_map.buffer_snapshot;
10438 let mut selections = self.selections.all::<usize>(cx);
10439 if let Some(mut select_next_state) = self.select_next_state.take() {
10440 let query = &select_next_state.query;
10441 if !select_next_state.done {
10442 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10443 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10444 let mut next_selected_range = None;
10445
10446 let bytes_after_last_selection =
10447 buffer.bytes_in_range(last_selection.end..buffer.len());
10448 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10449 let query_matches = query
10450 .stream_find_iter(bytes_after_last_selection)
10451 .map(|result| (last_selection.end, result))
10452 .chain(
10453 query
10454 .stream_find_iter(bytes_before_first_selection)
10455 .map(|result| (0, result)),
10456 );
10457
10458 for (start_offset, query_match) in query_matches {
10459 let query_match = query_match.unwrap(); // can only fail due to I/O
10460 let offset_range =
10461 start_offset + query_match.start()..start_offset + query_match.end();
10462 let display_range = offset_range.start.to_display_point(display_map)
10463 ..offset_range.end.to_display_point(display_map);
10464
10465 if !select_next_state.wordwise
10466 || (!movement::is_inside_word(display_map, display_range.start)
10467 && !movement::is_inside_word(display_map, display_range.end))
10468 {
10469 // TODO: This is n^2, because we might check all the selections
10470 if !selections
10471 .iter()
10472 .any(|selection| selection.range().overlaps(&offset_range))
10473 {
10474 next_selected_range = Some(offset_range);
10475 break;
10476 }
10477 }
10478 }
10479
10480 if let Some(next_selected_range) = next_selected_range {
10481 select_next_match_ranges(
10482 self,
10483 next_selected_range,
10484 replace_newest,
10485 autoscroll,
10486 window,
10487 cx,
10488 );
10489 } else {
10490 select_next_state.done = true;
10491 }
10492 }
10493
10494 self.select_next_state = Some(select_next_state);
10495 } else {
10496 let mut only_carets = true;
10497 let mut same_text_selected = true;
10498 let mut selected_text = None;
10499
10500 let mut selections_iter = selections.iter().peekable();
10501 while let Some(selection) = selections_iter.next() {
10502 if selection.start != selection.end {
10503 only_carets = false;
10504 }
10505
10506 if same_text_selected {
10507 if selected_text.is_none() {
10508 selected_text =
10509 Some(buffer.text_for_range(selection.range()).collect::<String>());
10510 }
10511
10512 if let Some(next_selection) = selections_iter.peek() {
10513 if next_selection.range().len() == selection.range().len() {
10514 let next_selected_text = buffer
10515 .text_for_range(next_selection.range())
10516 .collect::<String>();
10517 if Some(next_selected_text) != selected_text {
10518 same_text_selected = false;
10519 selected_text = None;
10520 }
10521 } else {
10522 same_text_selected = false;
10523 selected_text = None;
10524 }
10525 }
10526 }
10527 }
10528
10529 if only_carets {
10530 for selection in &mut selections {
10531 let word_range = movement::surrounding_word(
10532 display_map,
10533 selection.start.to_display_point(display_map),
10534 );
10535 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10536 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10537 selection.goal = SelectionGoal::None;
10538 selection.reversed = false;
10539 select_next_match_ranges(
10540 self,
10541 selection.start..selection.end,
10542 replace_newest,
10543 autoscroll,
10544 window,
10545 cx,
10546 );
10547 }
10548
10549 if selections.len() == 1 {
10550 let selection = selections
10551 .last()
10552 .expect("ensured that there's only one selection");
10553 let query = buffer
10554 .text_for_range(selection.start..selection.end)
10555 .collect::<String>();
10556 let is_empty = query.is_empty();
10557 let select_state = SelectNextState {
10558 query: AhoCorasick::new(&[query])?,
10559 wordwise: true,
10560 done: is_empty,
10561 };
10562 self.select_next_state = Some(select_state);
10563 } else {
10564 self.select_next_state = None;
10565 }
10566 } else if let Some(selected_text) = selected_text {
10567 self.select_next_state = Some(SelectNextState {
10568 query: AhoCorasick::new(&[selected_text])?,
10569 wordwise: false,
10570 done: false,
10571 });
10572 self.select_next_match_internal(
10573 display_map,
10574 replace_newest,
10575 autoscroll,
10576 window,
10577 cx,
10578 )?;
10579 }
10580 }
10581 Ok(())
10582 }
10583
10584 pub fn select_all_matches(
10585 &mut self,
10586 _action: &SelectAllMatches,
10587 window: &mut Window,
10588 cx: &mut Context<Self>,
10589 ) -> Result<()> {
10590 self.push_to_selection_history();
10591 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10592
10593 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10594 let Some(select_next_state) = self.select_next_state.as_mut() else {
10595 return Ok(());
10596 };
10597 if select_next_state.done {
10598 return Ok(());
10599 }
10600
10601 let mut new_selections = self.selections.all::<usize>(cx);
10602
10603 let buffer = &display_map.buffer_snapshot;
10604 let query_matches = select_next_state
10605 .query
10606 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10607
10608 for query_match in query_matches {
10609 let query_match = query_match.unwrap(); // can only fail due to I/O
10610 let offset_range = query_match.start()..query_match.end();
10611 let display_range = offset_range.start.to_display_point(&display_map)
10612 ..offset_range.end.to_display_point(&display_map);
10613
10614 if !select_next_state.wordwise
10615 || (!movement::is_inside_word(&display_map, display_range.start)
10616 && !movement::is_inside_word(&display_map, display_range.end))
10617 {
10618 self.selections.change_with(cx, |selections| {
10619 new_selections.push(Selection {
10620 id: selections.new_selection_id(),
10621 start: offset_range.start,
10622 end: offset_range.end,
10623 reversed: false,
10624 goal: SelectionGoal::None,
10625 });
10626 });
10627 }
10628 }
10629
10630 new_selections.sort_by_key(|selection| selection.start);
10631 let mut ix = 0;
10632 while ix + 1 < new_selections.len() {
10633 let current_selection = &new_selections[ix];
10634 let next_selection = &new_selections[ix + 1];
10635 if current_selection.range().overlaps(&next_selection.range()) {
10636 if current_selection.id < next_selection.id {
10637 new_selections.remove(ix + 1);
10638 } else {
10639 new_selections.remove(ix);
10640 }
10641 } else {
10642 ix += 1;
10643 }
10644 }
10645
10646 let reversed = self.selections.oldest::<usize>(cx).reversed;
10647
10648 for selection in new_selections.iter_mut() {
10649 selection.reversed = reversed;
10650 }
10651
10652 select_next_state.done = true;
10653 self.unfold_ranges(
10654 &new_selections
10655 .iter()
10656 .map(|selection| selection.range())
10657 .collect::<Vec<_>>(),
10658 false,
10659 false,
10660 cx,
10661 );
10662 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10663 selections.select(new_selections)
10664 });
10665
10666 Ok(())
10667 }
10668
10669 pub fn select_next(
10670 &mut self,
10671 action: &SelectNext,
10672 window: &mut Window,
10673 cx: &mut Context<Self>,
10674 ) -> Result<()> {
10675 self.push_to_selection_history();
10676 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10677 self.select_next_match_internal(
10678 &display_map,
10679 action.replace_newest,
10680 Some(Autoscroll::newest()),
10681 window,
10682 cx,
10683 )?;
10684 Ok(())
10685 }
10686
10687 pub fn select_previous(
10688 &mut self,
10689 action: &SelectPrevious,
10690 window: &mut Window,
10691 cx: &mut Context<Self>,
10692 ) -> Result<()> {
10693 self.push_to_selection_history();
10694 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10695 let buffer = &display_map.buffer_snapshot;
10696 let mut selections = self.selections.all::<usize>(cx);
10697 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10698 let query = &select_prev_state.query;
10699 if !select_prev_state.done {
10700 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10701 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10702 let mut next_selected_range = None;
10703 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10704 let bytes_before_last_selection =
10705 buffer.reversed_bytes_in_range(0..last_selection.start);
10706 let bytes_after_first_selection =
10707 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10708 let query_matches = query
10709 .stream_find_iter(bytes_before_last_selection)
10710 .map(|result| (last_selection.start, result))
10711 .chain(
10712 query
10713 .stream_find_iter(bytes_after_first_selection)
10714 .map(|result| (buffer.len(), result)),
10715 );
10716 for (end_offset, query_match) in query_matches {
10717 let query_match = query_match.unwrap(); // can only fail due to I/O
10718 let offset_range =
10719 end_offset - query_match.end()..end_offset - query_match.start();
10720 let display_range = offset_range.start.to_display_point(&display_map)
10721 ..offset_range.end.to_display_point(&display_map);
10722
10723 if !select_prev_state.wordwise
10724 || (!movement::is_inside_word(&display_map, display_range.start)
10725 && !movement::is_inside_word(&display_map, display_range.end))
10726 {
10727 next_selected_range = Some(offset_range);
10728 break;
10729 }
10730 }
10731
10732 if let Some(next_selected_range) = next_selected_range {
10733 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10734 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10735 if action.replace_newest {
10736 s.delete(s.newest_anchor().id);
10737 }
10738 s.insert_range(next_selected_range);
10739 });
10740 } else {
10741 select_prev_state.done = true;
10742 }
10743 }
10744
10745 self.select_prev_state = Some(select_prev_state);
10746 } else {
10747 let mut only_carets = true;
10748 let mut same_text_selected = true;
10749 let mut selected_text = None;
10750
10751 let mut selections_iter = selections.iter().peekable();
10752 while let Some(selection) = selections_iter.next() {
10753 if selection.start != selection.end {
10754 only_carets = false;
10755 }
10756
10757 if same_text_selected {
10758 if selected_text.is_none() {
10759 selected_text =
10760 Some(buffer.text_for_range(selection.range()).collect::<String>());
10761 }
10762
10763 if let Some(next_selection) = selections_iter.peek() {
10764 if next_selection.range().len() == selection.range().len() {
10765 let next_selected_text = buffer
10766 .text_for_range(next_selection.range())
10767 .collect::<String>();
10768 if Some(next_selected_text) != selected_text {
10769 same_text_selected = false;
10770 selected_text = None;
10771 }
10772 } else {
10773 same_text_selected = false;
10774 selected_text = None;
10775 }
10776 }
10777 }
10778 }
10779
10780 if only_carets {
10781 for selection in &mut selections {
10782 let word_range = movement::surrounding_word(
10783 &display_map,
10784 selection.start.to_display_point(&display_map),
10785 );
10786 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10787 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10788 selection.goal = SelectionGoal::None;
10789 selection.reversed = false;
10790 }
10791 if selections.len() == 1 {
10792 let selection = selections
10793 .last()
10794 .expect("ensured that there's only one selection");
10795 let query = buffer
10796 .text_for_range(selection.start..selection.end)
10797 .collect::<String>();
10798 let is_empty = query.is_empty();
10799 let select_state = SelectNextState {
10800 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10801 wordwise: true,
10802 done: is_empty,
10803 };
10804 self.select_prev_state = Some(select_state);
10805 } else {
10806 self.select_prev_state = None;
10807 }
10808
10809 self.unfold_ranges(
10810 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10811 false,
10812 true,
10813 cx,
10814 );
10815 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10816 s.select(selections);
10817 });
10818 } else if let Some(selected_text) = selected_text {
10819 self.select_prev_state = Some(SelectNextState {
10820 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10821 wordwise: false,
10822 done: false,
10823 });
10824 self.select_previous(action, window, cx)?;
10825 }
10826 }
10827 Ok(())
10828 }
10829
10830 pub fn toggle_comments(
10831 &mut self,
10832 action: &ToggleComments,
10833 window: &mut Window,
10834 cx: &mut Context<Self>,
10835 ) {
10836 if self.read_only(cx) {
10837 return;
10838 }
10839 let text_layout_details = &self.text_layout_details(window);
10840 self.transact(window, cx, |this, window, cx| {
10841 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10842 let mut edits = Vec::new();
10843 let mut selection_edit_ranges = Vec::new();
10844 let mut last_toggled_row = None;
10845 let snapshot = this.buffer.read(cx).read(cx);
10846 let empty_str: Arc<str> = Arc::default();
10847 let mut suffixes_inserted = Vec::new();
10848 let ignore_indent = action.ignore_indent;
10849
10850 fn comment_prefix_range(
10851 snapshot: &MultiBufferSnapshot,
10852 row: MultiBufferRow,
10853 comment_prefix: &str,
10854 comment_prefix_whitespace: &str,
10855 ignore_indent: bool,
10856 ) -> Range<Point> {
10857 let indent_size = if ignore_indent {
10858 0
10859 } else {
10860 snapshot.indent_size_for_line(row).len
10861 };
10862
10863 let start = Point::new(row.0, indent_size);
10864
10865 let mut line_bytes = snapshot
10866 .bytes_in_range(start..snapshot.max_point())
10867 .flatten()
10868 .copied();
10869
10870 // If this line currently begins with the line comment prefix, then record
10871 // the range containing the prefix.
10872 if line_bytes
10873 .by_ref()
10874 .take(comment_prefix.len())
10875 .eq(comment_prefix.bytes())
10876 {
10877 // Include any whitespace that matches the comment prefix.
10878 let matching_whitespace_len = line_bytes
10879 .zip(comment_prefix_whitespace.bytes())
10880 .take_while(|(a, b)| a == b)
10881 .count() as u32;
10882 let end = Point::new(
10883 start.row,
10884 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10885 );
10886 start..end
10887 } else {
10888 start..start
10889 }
10890 }
10891
10892 fn comment_suffix_range(
10893 snapshot: &MultiBufferSnapshot,
10894 row: MultiBufferRow,
10895 comment_suffix: &str,
10896 comment_suffix_has_leading_space: bool,
10897 ) -> Range<Point> {
10898 let end = Point::new(row.0, snapshot.line_len(row));
10899 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10900
10901 let mut line_end_bytes = snapshot
10902 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10903 .flatten()
10904 .copied();
10905
10906 let leading_space_len = if suffix_start_column > 0
10907 && line_end_bytes.next() == Some(b' ')
10908 && comment_suffix_has_leading_space
10909 {
10910 1
10911 } else {
10912 0
10913 };
10914
10915 // If this line currently begins with the line comment prefix, then record
10916 // the range containing the prefix.
10917 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10918 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10919 start..end
10920 } else {
10921 end..end
10922 }
10923 }
10924
10925 // TODO: Handle selections that cross excerpts
10926 for selection in &mut selections {
10927 let start_column = snapshot
10928 .indent_size_for_line(MultiBufferRow(selection.start.row))
10929 .len;
10930 let language = if let Some(language) =
10931 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10932 {
10933 language
10934 } else {
10935 continue;
10936 };
10937
10938 selection_edit_ranges.clear();
10939
10940 // If multiple selections contain a given row, avoid processing that
10941 // row more than once.
10942 let mut start_row = MultiBufferRow(selection.start.row);
10943 if last_toggled_row == Some(start_row) {
10944 start_row = start_row.next_row();
10945 }
10946 let end_row =
10947 if selection.end.row > selection.start.row && selection.end.column == 0 {
10948 MultiBufferRow(selection.end.row - 1)
10949 } else {
10950 MultiBufferRow(selection.end.row)
10951 };
10952 last_toggled_row = Some(end_row);
10953
10954 if start_row > end_row {
10955 continue;
10956 }
10957
10958 // If the language has line comments, toggle those.
10959 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10960
10961 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10962 if ignore_indent {
10963 full_comment_prefixes = full_comment_prefixes
10964 .into_iter()
10965 .map(|s| Arc::from(s.trim_end()))
10966 .collect();
10967 }
10968
10969 if !full_comment_prefixes.is_empty() {
10970 let first_prefix = full_comment_prefixes
10971 .first()
10972 .expect("prefixes is non-empty");
10973 let prefix_trimmed_lengths = full_comment_prefixes
10974 .iter()
10975 .map(|p| p.trim_end_matches(' ').len())
10976 .collect::<SmallVec<[usize; 4]>>();
10977
10978 let mut all_selection_lines_are_comments = true;
10979
10980 for row in start_row.0..=end_row.0 {
10981 let row = MultiBufferRow(row);
10982 if start_row < end_row && snapshot.is_line_blank(row) {
10983 continue;
10984 }
10985
10986 let prefix_range = full_comment_prefixes
10987 .iter()
10988 .zip(prefix_trimmed_lengths.iter().copied())
10989 .map(|(prefix, trimmed_prefix_len)| {
10990 comment_prefix_range(
10991 snapshot.deref(),
10992 row,
10993 &prefix[..trimmed_prefix_len],
10994 &prefix[trimmed_prefix_len..],
10995 ignore_indent,
10996 )
10997 })
10998 .max_by_key(|range| range.end.column - range.start.column)
10999 .expect("prefixes is non-empty");
11000
11001 if prefix_range.is_empty() {
11002 all_selection_lines_are_comments = false;
11003 }
11004
11005 selection_edit_ranges.push(prefix_range);
11006 }
11007
11008 if all_selection_lines_are_comments {
11009 edits.extend(
11010 selection_edit_ranges
11011 .iter()
11012 .cloned()
11013 .map(|range| (range, empty_str.clone())),
11014 );
11015 } else {
11016 let min_column = selection_edit_ranges
11017 .iter()
11018 .map(|range| range.start.column)
11019 .min()
11020 .unwrap_or(0);
11021 edits.extend(selection_edit_ranges.iter().map(|range| {
11022 let position = Point::new(range.start.row, min_column);
11023 (position..position, first_prefix.clone())
11024 }));
11025 }
11026 } else if let Some((full_comment_prefix, comment_suffix)) =
11027 language.block_comment_delimiters()
11028 {
11029 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11030 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11031 let prefix_range = comment_prefix_range(
11032 snapshot.deref(),
11033 start_row,
11034 comment_prefix,
11035 comment_prefix_whitespace,
11036 ignore_indent,
11037 );
11038 let suffix_range = comment_suffix_range(
11039 snapshot.deref(),
11040 end_row,
11041 comment_suffix.trim_start_matches(' '),
11042 comment_suffix.starts_with(' '),
11043 );
11044
11045 if prefix_range.is_empty() || suffix_range.is_empty() {
11046 edits.push((
11047 prefix_range.start..prefix_range.start,
11048 full_comment_prefix.clone(),
11049 ));
11050 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11051 suffixes_inserted.push((end_row, comment_suffix.len()));
11052 } else {
11053 edits.push((prefix_range, empty_str.clone()));
11054 edits.push((suffix_range, empty_str.clone()));
11055 }
11056 } else {
11057 continue;
11058 }
11059 }
11060
11061 drop(snapshot);
11062 this.buffer.update(cx, |buffer, cx| {
11063 buffer.edit(edits, None, cx);
11064 });
11065
11066 // Adjust selections so that they end before any comment suffixes that
11067 // were inserted.
11068 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11069 let mut selections = this.selections.all::<Point>(cx);
11070 let snapshot = this.buffer.read(cx).read(cx);
11071 for selection in &mut selections {
11072 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11073 match row.cmp(&MultiBufferRow(selection.end.row)) {
11074 Ordering::Less => {
11075 suffixes_inserted.next();
11076 continue;
11077 }
11078 Ordering::Greater => break,
11079 Ordering::Equal => {
11080 if selection.end.column == snapshot.line_len(row) {
11081 if selection.is_empty() {
11082 selection.start.column -= suffix_len as u32;
11083 }
11084 selection.end.column -= suffix_len as u32;
11085 }
11086 break;
11087 }
11088 }
11089 }
11090 }
11091
11092 drop(snapshot);
11093 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11094 s.select(selections)
11095 });
11096
11097 let selections = this.selections.all::<Point>(cx);
11098 let selections_on_single_row = selections.windows(2).all(|selections| {
11099 selections[0].start.row == selections[1].start.row
11100 && selections[0].end.row == selections[1].end.row
11101 && selections[0].start.row == selections[0].end.row
11102 });
11103 let selections_selecting = selections
11104 .iter()
11105 .any(|selection| selection.start != selection.end);
11106 let advance_downwards = action.advance_downwards
11107 && selections_on_single_row
11108 && !selections_selecting
11109 && !matches!(this.mode, EditorMode::SingleLine { .. });
11110
11111 if advance_downwards {
11112 let snapshot = this.buffer.read(cx).snapshot(cx);
11113
11114 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11115 s.move_cursors_with(|display_snapshot, display_point, _| {
11116 let mut point = display_point.to_point(display_snapshot);
11117 point.row += 1;
11118 point = snapshot.clip_point(point, Bias::Left);
11119 let display_point = point.to_display_point(display_snapshot);
11120 let goal = SelectionGoal::HorizontalPosition(
11121 display_snapshot
11122 .x_for_display_point(display_point, text_layout_details)
11123 .into(),
11124 );
11125 (display_point, goal)
11126 })
11127 });
11128 }
11129 });
11130 }
11131
11132 pub fn select_enclosing_symbol(
11133 &mut self,
11134 _: &SelectEnclosingSymbol,
11135 window: &mut Window,
11136 cx: &mut Context<Self>,
11137 ) {
11138 let buffer = self.buffer.read(cx).snapshot(cx);
11139 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11140
11141 fn update_selection(
11142 selection: &Selection<usize>,
11143 buffer_snap: &MultiBufferSnapshot,
11144 ) -> Option<Selection<usize>> {
11145 let cursor = selection.head();
11146 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11147 for symbol in symbols.iter().rev() {
11148 let start = symbol.range.start.to_offset(buffer_snap);
11149 let end = symbol.range.end.to_offset(buffer_snap);
11150 let new_range = start..end;
11151 if start < selection.start || end > selection.end {
11152 return Some(Selection {
11153 id: selection.id,
11154 start: new_range.start,
11155 end: new_range.end,
11156 goal: SelectionGoal::None,
11157 reversed: selection.reversed,
11158 });
11159 }
11160 }
11161 None
11162 }
11163
11164 let mut selected_larger_symbol = false;
11165 let new_selections = old_selections
11166 .iter()
11167 .map(|selection| match update_selection(selection, &buffer) {
11168 Some(new_selection) => {
11169 if new_selection.range() != selection.range() {
11170 selected_larger_symbol = true;
11171 }
11172 new_selection
11173 }
11174 None => selection.clone(),
11175 })
11176 .collect::<Vec<_>>();
11177
11178 if selected_larger_symbol {
11179 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11180 s.select(new_selections);
11181 });
11182 }
11183 }
11184
11185 pub fn select_larger_syntax_node(
11186 &mut self,
11187 _: &SelectLargerSyntaxNode,
11188 window: &mut Window,
11189 cx: &mut Context<Self>,
11190 ) {
11191 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11192 let buffer = self.buffer.read(cx).snapshot(cx);
11193 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11194
11195 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11196 let mut selected_larger_node = false;
11197 let new_selections = old_selections
11198 .iter()
11199 .map(|selection| {
11200 let old_range = selection.start..selection.end;
11201 let mut new_range = old_range.clone();
11202 let mut new_node = None;
11203 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11204 {
11205 new_node = Some(node);
11206 new_range = match containing_range {
11207 MultiOrSingleBufferOffsetRange::Single(_) => break,
11208 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11209 };
11210 if !display_map.intersects_fold(new_range.start)
11211 && !display_map.intersects_fold(new_range.end)
11212 {
11213 break;
11214 }
11215 }
11216
11217 if let Some(node) = new_node {
11218 // Log the ancestor, to support using this action as a way to explore TreeSitter
11219 // nodes. Parent and grandparent are also logged because this operation will not
11220 // visit nodes that have the same range as their parent.
11221 log::info!("Node: {node:?}");
11222 let parent = node.parent();
11223 log::info!("Parent: {parent:?}");
11224 let grandparent = parent.and_then(|x| x.parent());
11225 log::info!("Grandparent: {grandparent:?}");
11226 }
11227
11228 selected_larger_node |= new_range != old_range;
11229 Selection {
11230 id: selection.id,
11231 start: new_range.start,
11232 end: new_range.end,
11233 goal: SelectionGoal::None,
11234 reversed: selection.reversed,
11235 }
11236 })
11237 .collect::<Vec<_>>();
11238
11239 if selected_larger_node {
11240 stack.push(old_selections);
11241 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11242 s.select(new_selections);
11243 });
11244 }
11245 self.select_larger_syntax_node_stack = stack;
11246 }
11247
11248 pub fn select_smaller_syntax_node(
11249 &mut self,
11250 _: &SelectSmallerSyntaxNode,
11251 window: &mut Window,
11252 cx: &mut Context<Self>,
11253 ) {
11254 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11255 if let Some(selections) = stack.pop() {
11256 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11257 s.select(selections.to_vec());
11258 });
11259 }
11260 self.select_larger_syntax_node_stack = stack;
11261 }
11262
11263 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11264 if !EditorSettings::get_global(cx).gutter.runnables {
11265 self.clear_tasks();
11266 return Task::ready(());
11267 }
11268 let project = self.project.as_ref().map(Entity::downgrade);
11269 cx.spawn_in(window, |this, mut cx| async move {
11270 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11271 let Some(project) = project.and_then(|p| p.upgrade()) else {
11272 return;
11273 };
11274 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11275 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11276 }) else {
11277 return;
11278 };
11279
11280 let hide_runnables = project
11281 .update(&mut cx, |project, cx| {
11282 // Do not display any test indicators in non-dev server remote projects.
11283 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11284 })
11285 .unwrap_or(true);
11286 if hide_runnables {
11287 return;
11288 }
11289 let new_rows =
11290 cx.background_spawn({
11291 let snapshot = display_snapshot.clone();
11292 async move {
11293 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11294 }
11295 })
11296 .await;
11297
11298 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11299 this.update(&mut cx, |this, _| {
11300 this.clear_tasks();
11301 for (key, value) in rows {
11302 this.insert_tasks(key, value);
11303 }
11304 })
11305 .ok();
11306 })
11307 }
11308 fn fetch_runnable_ranges(
11309 snapshot: &DisplaySnapshot,
11310 range: Range<Anchor>,
11311 ) -> Vec<language::RunnableRange> {
11312 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11313 }
11314
11315 fn runnable_rows(
11316 project: Entity<Project>,
11317 snapshot: DisplaySnapshot,
11318 runnable_ranges: Vec<RunnableRange>,
11319 mut cx: AsyncWindowContext,
11320 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11321 runnable_ranges
11322 .into_iter()
11323 .filter_map(|mut runnable| {
11324 let tasks = cx
11325 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11326 .ok()?;
11327 if tasks.is_empty() {
11328 return None;
11329 }
11330
11331 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11332
11333 let row = snapshot
11334 .buffer_snapshot
11335 .buffer_line_for_row(MultiBufferRow(point.row))?
11336 .1
11337 .start
11338 .row;
11339
11340 let context_range =
11341 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11342 Some((
11343 (runnable.buffer_id, row),
11344 RunnableTasks {
11345 templates: tasks,
11346 offset: snapshot
11347 .buffer_snapshot
11348 .anchor_before(runnable.run_range.start),
11349 context_range,
11350 column: point.column,
11351 extra_variables: runnable.extra_captures,
11352 },
11353 ))
11354 })
11355 .collect()
11356 }
11357
11358 fn templates_with_tags(
11359 project: &Entity<Project>,
11360 runnable: &mut Runnable,
11361 cx: &mut App,
11362 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11363 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11364 let (worktree_id, file) = project
11365 .buffer_for_id(runnable.buffer, cx)
11366 .and_then(|buffer| buffer.read(cx).file())
11367 .map(|file| (file.worktree_id(cx), file.clone()))
11368 .unzip();
11369
11370 (
11371 project.task_store().read(cx).task_inventory().cloned(),
11372 worktree_id,
11373 file,
11374 )
11375 });
11376
11377 let tags = mem::take(&mut runnable.tags);
11378 let mut tags: Vec<_> = tags
11379 .into_iter()
11380 .flat_map(|tag| {
11381 let tag = tag.0.clone();
11382 inventory
11383 .as_ref()
11384 .into_iter()
11385 .flat_map(|inventory| {
11386 inventory.read(cx).list_tasks(
11387 file.clone(),
11388 Some(runnable.language.clone()),
11389 worktree_id,
11390 cx,
11391 )
11392 })
11393 .filter(move |(_, template)| {
11394 template.tags.iter().any(|source_tag| source_tag == &tag)
11395 })
11396 })
11397 .sorted_by_key(|(kind, _)| kind.to_owned())
11398 .collect();
11399 if let Some((leading_tag_source, _)) = tags.first() {
11400 // Strongest source wins; if we have worktree tag binding, prefer that to
11401 // global and language bindings;
11402 // if we have a global binding, prefer that to language binding.
11403 let first_mismatch = tags
11404 .iter()
11405 .position(|(tag_source, _)| tag_source != leading_tag_source);
11406 if let Some(index) = first_mismatch {
11407 tags.truncate(index);
11408 }
11409 }
11410
11411 tags
11412 }
11413
11414 pub fn move_to_enclosing_bracket(
11415 &mut self,
11416 _: &MoveToEnclosingBracket,
11417 window: &mut Window,
11418 cx: &mut Context<Self>,
11419 ) {
11420 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11421 s.move_offsets_with(|snapshot, selection| {
11422 let Some(enclosing_bracket_ranges) =
11423 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11424 else {
11425 return;
11426 };
11427
11428 let mut best_length = usize::MAX;
11429 let mut best_inside = false;
11430 let mut best_in_bracket_range = false;
11431 let mut best_destination = None;
11432 for (open, close) in enclosing_bracket_ranges {
11433 let close = close.to_inclusive();
11434 let length = close.end() - open.start;
11435 let inside = selection.start >= open.end && selection.end <= *close.start();
11436 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11437 || close.contains(&selection.head());
11438
11439 // If best is next to a bracket and current isn't, skip
11440 if !in_bracket_range && best_in_bracket_range {
11441 continue;
11442 }
11443
11444 // Prefer smaller lengths unless best is inside and current isn't
11445 if length > best_length && (best_inside || !inside) {
11446 continue;
11447 }
11448
11449 best_length = length;
11450 best_inside = inside;
11451 best_in_bracket_range = in_bracket_range;
11452 best_destination = Some(
11453 if close.contains(&selection.start) && close.contains(&selection.end) {
11454 if inside {
11455 open.end
11456 } else {
11457 open.start
11458 }
11459 } else if inside {
11460 *close.start()
11461 } else {
11462 *close.end()
11463 },
11464 );
11465 }
11466
11467 if let Some(destination) = best_destination {
11468 selection.collapse_to(destination, SelectionGoal::None);
11469 }
11470 })
11471 });
11472 }
11473
11474 pub fn undo_selection(
11475 &mut self,
11476 _: &UndoSelection,
11477 window: &mut Window,
11478 cx: &mut Context<Self>,
11479 ) {
11480 self.end_selection(window, cx);
11481 self.selection_history.mode = SelectionHistoryMode::Undoing;
11482 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11483 self.change_selections(None, window, cx, |s| {
11484 s.select_anchors(entry.selections.to_vec())
11485 });
11486 self.select_next_state = entry.select_next_state;
11487 self.select_prev_state = entry.select_prev_state;
11488 self.add_selections_state = entry.add_selections_state;
11489 self.request_autoscroll(Autoscroll::newest(), cx);
11490 }
11491 self.selection_history.mode = SelectionHistoryMode::Normal;
11492 }
11493
11494 pub fn redo_selection(
11495 &mut self,
11496 _: &RedoSelection,
11497 window: &mut Window,
11498 cx: &mut Context<Self>,
11499 ) {
11500 self.end_selection(window, cx);
11501 self.selection_history.mode = SelectionHistoryMode::Redoing;
11502 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11503 self.change_selections(None, window, cx, |s| {
11504 s.select_anchors(entry.selections.to_vec())
11505 });
11506 self.select_next_state = entry.select_next_state;
11507 self.select_prev_state = entry.select_prev_state;
11508 self.add_selections_state = entry.add_selections_state;
11509 self.request_autoscroll(Autoscroll::newest(), cx);
11510 }
11511 self.selection_history.mode = SelectionHistoryMode::Normal;
11512 }
11513
11514 pub fn expand_excerpts(
11515 &mut self,
11516 action: &ExpandExcerpts,
11517 _: &mut Window,
11518 cx: &mut Context<Self>,
11519 ) {
11520 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11521 }
11522
11523 pub fn expand_excerpts_down(
11524 &mut self,
11525 action: &ExpandExcerptsDown,
11526 _: &mut Window,
11527 cx: &mut Context<Self>,
11528 ) {
11529 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11530 }
11531
11532 pub fn expand_excerpts_up(
11533 &mut self,
11534 action: &ExpandExcerptsUp,
11535 _: &mut Window,
11536 cx: &mut Context<Self>,
11537 ) {
11538 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11539 }
11540
11541 pub fn expand_excerpts_for_direction(
11542 &mut self,
11543 lines: u32,
11544 direction: ExpandExcerptDirection,
11545
11546 cx: &mut Context<Self>,
11547 ) {
11548 let selections = self.selections.disjoint_anchors();
11549
11550 let lines = if lines == 0 {
11551 EditorSettings::get_global(cx).expand_excerpt_lines
11552 } else {
11553 lines
11554 };
11555
11556 self.buffer.update(cx, |buffer, cx| {
11557 let snapshot = buffer.snapshot(cx);
11558 let mut excerpt_ids = selections
11559 .iter()
11560 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11561 .collect::<Vec<_>>();
11562 excerpt_ids.sort();
11563 excerpt_ids.dedup();
11564 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11565 })
11566 }
11567
11568 pub fn expand_excerpt(
11569 &mut self,
11570 excerpt: ExcerptId,
11571 direction: ExpandExcerptDirection,
11572 cx: &mut Context<Self>,
11573 ) {
11574 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11575 self.buffer.update(cx, |buffer, cx| {
11576 buffer.expand_excerpts([excerpt], lines, direction, cx)
11577 })
11578 }
11579
11580 pub fn go_to_singleton_buffer_point(
11581 &mut self,
11582 point: Point,
11583 window: &mut Window,
11584 cx: &mut Context<Self>,
11585 ) {
11586 self.go_to_singleton_buffer_range(point..point, window, cx);
11587 }
11588
11589 pub fn go_to_singleton_buffer_range(
11590 &mut self,
11591 range: Range<Point>,
11592 window: &mut Window,
11593 cx: &mut Context<Self>,
11594 ) {
11595 let multibuffer = self.buffer().read(cx);
11596 let Some(buffer) = multibuffer.as_singleton() else {
11597 return;
11598 };
11599 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11600 return;
11601 };
11602 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11603 return;
11604 };
11605 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11606 s.select_anchor_ranges([start..end])
11607 });
11608 }
11609
11610 fn go_to_diagnostic(
11611 &mut self,
11612 _: &GoToDiagnostic,
11613 window: &mut Window,
11614 cx: &mut Context<Self>,
11615 ) {
11616 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11617 }
11618
11619 fn go_to_prev_diagnostic(
11620 &mut self,
11621 _: &GoToPreviousDiagnostic,
11622 window: &mut Window,
11623 cx: &mut Context<Self>,
11624 ) {
11625 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11626 }
11627
11628 pub fn go_to_diagnostic_impl(
11629 &mut self,
11630 direction: Direction,
11631 window: &mut Window,
11632 cx: &mut Context<Self>,
11633 ) {
11634 let buffer = self.buffer.read(cx).snapshot(cx);
11635 let selection = self.selections.newest::<usize>(cx);
11636
11637 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11638 if direction == Direction::Next {
11639 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11640 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11641 return;
11642 };
11643 self.activate_diagnostics(
11644 buffer_id,
11645 popover.local_diagnostic.diagnostic.group_id,
11646 window,
11647 cx,
11648 );
11649 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11650 let primary_range_start = active_diagnostics.primary_range.start;
11651 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11652 let mut new_selection = s.newest_anchor().clone();
11653 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11654 s.select_anchors(vec![new_selection.clone()]);
11655 });
11656 self.refresh_inline_completion(false, true, window, cx);
11657 }
11658 return;
11659 }
11660 }
11661
11662 let active_group_id = self
11663 .active_diagnostics
11664 .as_ref()
11665 .map(|active_group| active_group.group_id);
11666 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11667 active_diagnostics
11668 .primary_range
11669 .to_offset(&buffer)
11670 .to_inclusive()
11671 });
11672 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11673 if active_primary_range.contains(&selection.head()) {
11674 *active_primary_range.start()
11675 } else {
11676 selection.head()
11677 }
11678 } else {
11679 selection.head()
11680 };
11681
11682 let snapshot = self.snapshot(window, cx);
11683 let primary_diagnostics_before = buffer
11684 .diagnostics_in_range::<usize>(0..search_start)
11685 .filter(|entry| entry.diagnostic.is_primary)
11686 .filter(|entry| entry.range.start != entry.range.end)
11687 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11688 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11689 .collect::<Vec<_>>();
11690 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11691 primary_diagnostics_before
11692 .iter()
11693 .position(|entry| entry.diagnostic.group_id == active_group_id)
11694 });
11695
11696 let primary_diagnostics_after = buffer
11697 .diagnostics_in_range::<usize>(search_start..buffer.len())
11698 .filter(|entry| entry.diagnostic.is_primary)
11699 .filter(|entry| entry.range.start != entry.range.end)
11700 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11701 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11702 .collect::<Vec<_>>();
11703 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11704 primary_diagnostics_after
11705 .iter()
11706 .enumerate()
11707 .rev()
11708 .find_map(|(i, entry)| {
11709 if entry.diagnostic.group_id == active_group_id {
11710 Some(i)
11711 } else {
11712 None
11713 }
11714 })
11715 });
11716
11717 let next_primary_diagnostic = match direction {
11718 Direction::Prev => primary_diagnostics_before
11719 .iter()
11720 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11721 .rev()
11722 .next(),
11723 Direction::Next => primary_diagnostics_after
11724 .iter()
11725 .skip(
11726 last_same_group_diagnostic_after
11727 .map(|index| index + 1)
11728 .unwrap_or(0),
11729 )
11730 .next(),
11731 };
11732
11733 // Cycle around to the start of the buffer, potentially moving back to the start of
11734 // the currently active diagnostic.
11735 let cycle_around = || match direction {
11736 Direction::Prev => primary_diagnostics_after
11737 .iter()
11738 .rev()
11739 .chain(primary_diagnostics_before.iter().rev())
11740 .next(),
11741 Direction::Next => primary_diagnostics_before
11742 .iter()
11743 .chain(primary_diagnostics_after.iter())
11744 .next(),
11745 };
11746
11747 if let Some((primary_range, group_id)) = next_primary_diagnostic
11748 .or_else(cycle_around)
11749 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11750 {
11751 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11752 return;
11753 };
11754 self.activate_diagnostics(buffer_id, group_id, window, cx);
11755 if self.active_diagnostics.is_some() {
11756 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11757 s.select(vec![Selection {
11758 id: selection.id,
11759 start: primary_range.start,
11760 end: primary_range.start,
11761 reversed: false,
11762 goal: SelectionGoal::None,
11763 }]);
11764 });
11765 self.refresh_inline_completion(false, true, window, cx);
11766 }
11767 }
11768 }
11769
11770 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11771 let snapshot = self.snapshot(window, cx);
11772 let selection = self.selections.newest::<Point>(cx);
11773 self.go_to_hunk_before_or_after_position(
11774 &snapshot,
11775 selection.head(),
11776 Direction::Next,
11777 window,
11778 cx,
11779 );
11780 }
11781
11782 fn go_to_hunk_before_or_after_position(
11783 &mut self,
11784 snapshot: &EditorSnapshot,
11785 position: Point,
11786 direction: Direction,
11787 window: &mut Window,
11788 cx: &mut Context<Editor>,
11789 ) {
11790 let row = if direction == Direction::Next {
11791 self.hunk_after_position(snapshot, position)
11792 .map(|hunk| hunk.row_range.start)
11793 } else {
11794 self.hunk_before_position(snapshot, position)
11795 };
11796
11797 if let Some(row) = row {
11798 let destination = Point::new(row.0, 0);
11799 let autoscroll = Autoscroll::center();
11800
11801 self.unfold_ranges(&[destination..destination], false, false, cx);
11802 self.change_selections(Some(autoscroll), window, cx, |s| {
11803 s.select_ranges([destination..destination]);
11804 });
11805 }
11806 }
11807
11808 fn hunk_after_position(
11809 &mut self,
11810 snapshot: &EditorSnapshot,
11811 position: Point,
11812 ) -> Option<MultiBufferDiffHunk> {
11813 snapshot
11814 .buffer_snapshot
11815 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11816 .find(|hunk| hunk.row_range.start.0 > position.row)
11817 .or_else(|| {
11818 snapshot
11819 .buffer_snapshot
11820 .diff_hunks_in_range(Point::zero()..position)
11821 .find(|hunk| hunk.row_range.end.0 < position.row)
11822 })
11823 }
11824
11825 fn go_to_prev_hunk(
11826 &mut self,
11827 _: &GoToPreviousHunk,
11828 window: &mut Window,
11829 cx: &mut Context<Self>,
11830 ) {
11831 let snapshot = self.snapshot(window, cx);
11832 let selection = self.selections.newest::<Point>(cx);
11833 self.go_to_hunk_before_or_after_position(
11834 &snapshot,
11835 selection.head(),
11836 Direction::Prev,
11837 window,
11838 cx,
11839 );
11840 }
11841
11842 fn hunk_before_position(
11843 &mut self,
11844 snapshot: &EditorSnapshot,
11845 position: Point,
11846 ) -> Option<MultiBufferRow> {
11847 snapshot
11848 .buffer_snapshot
11849 .diff_hunk_before(position)
11850 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11851 }
11852
11853 pub fn go_to_definition(
11854 &mut self,
11855 _: &GoToDefinition,
11856 window: &mut Window,
11857 cx: &mut Context<Self>,
11858 ) -> Task<Result<Navigated>> {
11859 let definition =
11860 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11861 cx.spawn_in(window, |editor, mut cx| async move {
11862 if definition.await? == Navigated::Yes {
11863 return Ok(Navigated::Yes);
11864 }
11865 match editor.update_in(&mut cx, |editor, window, cx| {
11866 editor.find_all_references(&FindAllReferences, window, cx)
11867 })? {
11868 Some(references) => references.await,
11869 None => Ok(Navigated::No),
11870 }
11871 })
11872 }
11873
11874 pub fn go_to_declaration(
11875 &mut self,
11876 _: &GoToDeclaration,
11877 window: &mut Window,
11878 cx: &mut Context<Self>,
11879 ) -> Task<Result<Navigated>> {
11880 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11881 }
11882
11883 pub fn go_to_declaration_split(
11884 &mut self,
11885 _: &GoToDeclaration,
11886 window: &mut Window,
11887 cx: &mut Context<Self>,
11888 ) -> Task<Result<Navigated>> {
11889 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11890 }
11891
11892 pub fn go_to_implementation(
11893 &mut self,
11894 _: &GoToImplementation,
11895 window: &mut Window,
11896 cx: &mut Context<Self>,
11897 ) -> Task<Result<Navigated>> {
11898 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11899 }
11900
11901 pub fn go_to_implementation_split(
11902 &mut self,
11903 _: &GoToImplementationSplit,
11904 window: &mut Window,
11905 cx: &mut Context<Self>,
11906 ) -> Task<Result<Navigated>> {
11907 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11908 }
11909
11910 pub fn go_to_type_definition(
11911 &mut self,
11912 _: &GoToTypeDefinition,
11913 window: &mut Window,
11914 cx: &mut Context<Self>,
11915 ) -> Task<Result<Navigated>> {
11916 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11917 }
11918
11919 pub fn go_to_definition_split(
11920 &mut self,
11921 _: &GoToDefinitionSplit,
11922 window: &mut Window,
11923 cx: &mut Context<Self>,
11924 ) -> Task<Result<Navigated>> {
11925 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11926 }
11927
11928 pub fn go_to_type_definition_split(
11929 &mut self,
11930 _: &GoToTypeDefinitionSplit,
11931 window: &mut Window,
11932 cx: &mut Context<Self>,
11933 ) -> Task<Result<Navigated>> {
11934 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11935 }
11936
11937 fn go_to_definition_of_kind(
11938 &mut self,
11939 kind: GotoDefinitionKind,
11940 split: bool,
11941 window: &mut Window,
11942 cx: &mut Context<Self>,
11943 ) -> Task<Result<Navigated>> {
11944 let Some(provider) = self.semantics_provider.clone() else {
11945 return Task::ready(Ok(Navigated::No));
11946 };
11947 let head = self.selections.newest::<usize>(cx).head();
11948 let buffer = self.buffer.read(cx);
11949 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11950 text_anchor
11951 } else {
11952 return Task::ready(Ok(Navigated::No));
11953 };
11954
11955 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11956 return Task::ready(Ok(Navigated::No));
11957 };
11958
11959 cx.spawn_in(window, |editor, mut cx| async move {
11960 let definitions = definitions.await?;
11961 let navigated = editor
11962 .update_in(&mut cx, |editor, window, cx| {
11963 editor.navigate_to_hover_links(
11964 Some(kind),
11965 definitions
11966 .into_iter()
11967 .filter(|location| {
11968 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11969 })
11970 .map(HoverLink::Text)
11971 .collect::<Vec<_>>(),
11972 split,
11973 window,
11974 cx,
11975 )
11976 })?
11977 .await?;
11978 anyhow::Ok(navigated)
11979 })
11980 }
11981
11982 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11983 let selection = self.selections.newest_anchor();
11984 let head = selection.head();
11985 let tail = selection.tail();
11986
11987 let Some((buffer, start_position)) =
11988 self.buffer.read(cx).text_anchor_for_position(head, cx)
11989 else {
11990 return;
11991 };
11992
11993 let end_position = if head != tail {
11994 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11995 return;
11996 };
11997 Some(pos)
11998 } else {
11999 None
12000 };
12001
12002 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
12003 let url = if let Some(end_pos) = end_position {
12004 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12005 } else {
12006 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12007 };
12008
12009 if let Some(url) = url {
12010 editor.update(&mut cx, |_, cx| {
12011 cx.open_url(&url);
12012 })
12013 } else {
12014 Ok(())
12015 }
12016 });
12017
12018 url_finder.detach();
12019 }
12020
12021 pub fn open_selected_filename(
12022 &mut self,
12023 _: &OpenSelectedFilename,
12024 window: &mut Window,
12025 cx: &mut Context<Self>,
12026 ) {
12027 let Some(workspace) = self.workspace() else {
12028 return;
12029 };
12030
12031 let position = self.selections.newest_anchor().head();
12032
12033 let Some((buffer, buffer_position)) =
12034 self.buffer.read(cx).text_anchor_for_position(position, cx)
12035 else {
12036 return;
12037 };
12038
12039 let project = self.project.clone();
12040
12041 cx.spawn_in(window, |_, mut cx| async move {
12042 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
12043
12044 if let Some((_, path)) = result {
12045 workspace
12046 .update_in(&mut cx, |workspace, window, cx| {
12047 workspace.open_resolved_path(path, window, cx)
12048 })?
12049 .await?;
12050 }
12051 anyhow::Ok(())
12052 })
12053 .detach();
12054 }
12055
12056 pub(crate) fn navigate_to_hover_links(
12057 &mut self,
12058 kind: Option<GotoDefinitionKind>,
12059 mut definitions: Vec<HoverLink>,
12060 split: bool,
12061 window: &mut Window,
12062 cx: &mut Context<Editor>,
12063 ) -> Task<Result<Navigated>> {
12064 // If there is one definition, just open it directly
12065 if definitions.len() == 1 {
12066 let definition = definitions.pop().unwrap();
12067
12068 enum TargetTaskResult {
12069 Location(Option<Location>),
12070 AlreadyNavigated,
12071 }
12072
12073 let target_task = match definition {
12074 HoverLink::Text(link) => {
12075 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12076 }
12077 HoverLink::InlayHint(lsp_location, server_id) => {
12078 let computation =
12079 self.compute_target_location(lsp_location, server_id, window, cx);
12080 cx.background_spawn(async move {
12081 let location = computation.await?;
12082 Ok(TargetTaskResult::Location(location))
12083 })
12084 }
12085 HoverLink::Url(url) => {
12086 cx.open_url(&url);
12087 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12088 }
12089 HoverLink::File(path) => {
12090 if let Some(workspace) = self.workspace() {
12091 cx.spawn_in(window, |_, mut cx| async move {
12092 workspace
12093 .update_in(&mut cx, |workspace, window, cx| {
12094 workspace.open_resolved_path(path, window, cx)
12095 })?
12096 .await
12097 .map(|_| TargetTaskResult::AlreadyNavigated)
12098 })
12099 } else {
12100 Task::ready(Ok(TargetTaskResult::Location(None)))
12101 }
12102 }
12103 };
12104 cx.spawn_in(window, |editor, mut cx| async move {
12105 let target = match target_task.await.context("target resolution task")? {
12106 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12107 TargetTaskResult::Location(None) => return Ok(Navigated::No),
12108 TargetTaskResult::Location(Some(target)) => target,
12109 };
12110
12111 editor.update_in(&mut cx, |editor, window, cx| {
12112 let Some(workspace) = editor.workspace() else {
12113 return Navigated::No;
12114 };
12115 let pane = workspace.read(cx).active_pane().clone();
12116
12117 let range = target.range.to_point(target.buffer.read(cx));
12118 let range = editor.range_for_match(&range);
12119 let range = collapse_multiline_range(range);
12120
12121 if !split
12122 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12123 {
12124 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12125 } else {
12126 window.defer(cx, move |window, cx| {
12127 let target_editor: Entity<Self> =
12128 workspace.update(cx, |workspace, cx| {
12129 let pane = if split {
12130 workspace.adjacent_pane(window, cx)
12131 } else {
12132 workspace.active_pane().clone()
12133 };
12134
12135 workspace.open_project_item(
12136 pane,
12137 target.buffer.clone(),
12138 true,
12139 true,
12140 window,
12141 cx,
12142 )
12143 });
12144 target_editor.update(cx, |target_editor, cx| {
12145 // When selecting a definition in a different buffer, disable the nav history
12146 // to avoid creating a history entry at the previous cursor location.
12147 pane.update(cx, |pane, _| pane.disable_history());
12148 target_editor.go_to_singleton_buffer_range(range, window, cx);
12149 pane.update(cx, |pane, _| pane.enable_history());
12150 });
12151 });
12152 }
12153 Navigated::Yes
12154 })
12155 })
12156 } else if !definitions.is_empty() {
12157 cx.spawn_in(window, |editor, mut cx| async move {
12158 let (title, location_tasks, workspace) = editor
12159 .update_in(&mut cx, |editor, window, cx| {
12160 let tab_kind = match kind {
12161 Some(GotoDefinitionKind::Implementation) => "Implementations",
12162 _ => "Definitions",
12163 };
12164 let title = definitions
12165 .iter()
12166 .find_map(|definition| match definition {
12167 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12168 let buffer = origin.buffer.read(cx);
12169 format!(
12170 "{} for {}",
12171 tab_kind,
12172 buffer
12173 .text_for_range(origin.range.clone())
12174 .collect::<String>()
12175 )
12176 }),
12177 HoverLink::InlayHint(_, _) => None,
12178 HoverLink::Url(_) => None,
12179 HoverLink::File(_) => None,
12180 })
12181 .unwrap_or(tab_kind.to_string());
12182 let location_tasks = definitions
12183 .into_iter()
12184 .map(|definition| match definition {
12185 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12186 HoverLink::InlayHint(lsp_location, server_id) => editor
12187 .compute_target_location(lsp_location, server_id, window, cx),
12188 HoverLink::Url(_) => Task::ready(Ok(None)),
12189 HoverLink::File(_) => Task::ready(Ok(None)),
12190 })
12191 .collect::<Vec<_>>();
12192 (title, location_tasks, editor.workspace().clone())
12193 })
12194 .context("location tasks preparation")?;
12195
12196 let locations = future::join_all(location_tasks)
12197 .await
12198 .into_iter()
12199 .filter_map(|location| location.transpose())
12200 .collect::<Result<_>>()
12201 .context("location tasks")?;
12202
12203 let Some(workspace) = workspace else {
12204 return Ok(Navigated::No);
12205 };
12206 let opened = workspace
12207 .update_in(&mut cx, |workspace, window, cx| {
12208 Self::open_locations_in_multibuffer(
12209 workspace,
12210 locations,
12211 title,
12212 split,
12213 MultibufferSelectionMode::First,
12214 window,
12215 cx,
12216 )
12217 })
12218 .ok();
12219
12220 anyhow::Ok(Navigated::from_bool(opened.is_some()))
12221 })
12222 } else {
12223 Task::ready(Ok(Navigated::No))
12224 }
12225 }
12226
12227 fn compute_target_location(
12228 &self,
12229 lsp_location: lsp::Location,
12230 server_id: LanguageServerId,
12231 window: &mut Window,
12232 cx: &mut Context<Self>,
12233 ) -> Task<anyhow::Result<Option<Location>>> {
12234 let Some(project) = self.project.clone() else {
12235 return Task::ready(Ok(None));
12236 };
12237
12238 cx.spawn_in(window, move |editor, mut cx| async move {
12239 let location_task = editor.update(&mut cx, |_, cx| {
12240 project.update(cx, |project, cx| {
12241 let language_server_name = project
12242 .language_server_statuses(cx)
12243 .find(|(id, _)| server_id == *id)
12244 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12245 language_server_name.map(|language_server_name| {
12246 project.open_local_buffer_via_lsp(
12247 lsp_location.uri.clone(),
12248 server_id,
12249 language_server_name,
12250 cx,
12251 )
12252 })
12253 })
12254 })?;
12255 let location = match location_task {
12256 Some(task) => Some({
12257 let target_buffer_handle = task.await.context("open local buffer")?;
12258 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12259 let target_start = target_buffer
12260 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12261 let target_end = target_buffer
12262 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12263 target_buffer.anchor_after(target_start)
12264 ..target_buffer.anchor_before(target_end)
12265 })?;
12266 Location {
12267 buffer: target_buffer_handle,
12268 range,
12269 }
12270 }),
12271 None => None,
12272 };
12273 Ok(location)
12274 })
12275 }
12276
12277 pub fn find_all_references(
12278 &mut self,
12279 _: &FindAllReferences,
12280 window: &mut Window,
12281 cx: &mut Context<Self>,
12282 ) -> Option<Task<Result<Navigated>>> {
12283 let selection = self.selections.newest::<usize>(cx);
12284 let multi_buffer = self.buffer.read(cx);
12285 let head = selection.head();
12286
12287 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12288 let head_anchor = multi_buffer_snapshot.anchor_at(
12289 head,
12290 if head < selection.tail() {
12291 Bias::Right
12292 } else {
12293 Bias::Left
12294 },
12295 );
12296
12297 match self
12298 .find_all_references_task_sources
12299 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12300 {
12301 Ok(_) => {
12302 log::info!(
12303 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12304 );
12305 return None;
12306 }
12307 Err(i) => {
12308 self.find_all_references_task_sources.insert(i, head_anchor);
12309 }
12310 }
12311
12312 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12313 let workspace = self.workspace()?;
12314 let project = workspace.read(cx).project().clone();
12315 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12316 Some(cx.spawn_in(window, |editor, mut cx| async move {
12317 let _cleanup = defer({
12318 let mut cx = cx.clone();
12319 move || {
12320 let _ = editor.update(&mut cx, |editor, _| {
12321 if let Ok(i) =
12322 editor
12323 .find_all_references_task_sources
12324 .binary_search_by(|anchor| {
12325 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12326 })
12327 {
12328 editor.find_all_references_task_sources.remove(i);
12329 }
12330 });
12331 }
12332 });
12333
12334 let locations = references.await?;
12335 if locations.is_empty() {
12336 return anyhow::Ok(Navigated::No);
12337 }
12338
12339 workspace.update_in(&mut cx, |workspace, window, cx| {
12340 let title = locations
12341 .first()
12342 .as_ref()
12343 .map(|location| {
12344 let buffer = location.buffer.read(cx);
12345 format!(
12346 "References to `{}`",
12347 buffer
12348 .text_for_range(location.range.clone())
12349 .collect::<String>()
12350 )
12351 })
12352 .unwrap();
12353 Self::open_locations_in_multibuffer(
12354 workspace,
12355 locations,
12356 title,
12357 false,
12358 MultibufferSelectionMode::First,
12359 window,
12360 cx,
12361 );
12362 Navigated::Yes
12363 })
12364 }))
12365 }
12366
12367 /// Opens a multibuffer with the given project locations in it
12368 pub fn open_locations_in_multibuffer(
12369 workspace: &mut Workspace,
12370 mut locations: Vec<Location>,
12371 title: String,
12372 split: bool,
12373 multibuffer_selection_mode: MultibufferSelectionMode,
12374 window: &mut Window,
12375 cx: &mut Context<Workspace>,
12376 ) {
12377 // If there are multiple definitions, open them in a multibuffer
12378 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12379 let mut locations = locations.into_iter().peekable();
12380 let mut ranges = Vec::new();
12381 let capability = workspace.project().read(cx).capability();
12382
12383 let excerpt_buffer = cx.new(|cx| {
12384 let mut multibuffer = MultiBuffer::new(capability);
12385 while let Some(location) = locations.next() {
12386 let buffer = location.buffer.read(cx);
12387 let mut ranges_for_buffer = Vec::new();
12388 let range = location.range.to_offset(buffer);
12389 ranges_for_buffer.push(range.clone());
12390
12391 while let Some(next_location) = locations.peek() {
12392 if next_location.buffer == location.buffer {
12393 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12394 locations.next();
12395 } else {
12396 break;
12397 }
12398 }
12399
12400 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12401 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12402 location.buffer.clone(),
12403 ranges_for_buffer,
12404 DEFAULT_MULTIBUFFER_CONTEXT,
12405 cx,
12406 ))
12407 }
12408
12409 multibuffer.with_title(title)
12410 });
12411
12412 let editor = cx.new(|cx| {
12413 Editor::for_multibuffer(
12414 excerpt_buffer,
12415 Some(workspace.project().clone()),
12416 window,
12417 cx,
12418 )
12419 });
12420 editor.update(cx, |editor, cx| {
12421 match multibuffer_selection_mode {
12422 MultibufferSelectionMode::First => {
12423 if let Some(first_range) = ranges.first() {
12424 editor.change_selections(None, window, cx, |selections| {
12425 selections.clear_disjoint();
12426 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12427 });
12428 }
12429 editor.highlight_background::<Self>(
12430 &ranges,
12431 |theme| theme.editor_highlighted_line_background,
12432 cx,
12433 );
12434 }
12435 MultibufferSelectionMode::All => {
12436 editor.change_selections(None, window, cx, |selections| {
12437 selections.clear_disjoint();
12438 selections.select_anchor_ranges(ranges);
12439 });
12440 }
12441 }
12442 editor.register_buffers_with_language_servers(cx);
12443 });
12444
12445 let item = Box::new(editor);
12446 let item_id = item.item_id();
12447
12448 if split {
12449 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12450 } else {
12451 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12452 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12453 pane.close_current_preview_item(window, cx)
12454 } else {
12455 None
12456 }
12457 });
12458 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12459 }
12460 workspace.active_pane().update(cx, |pane, cx| {
12461 pane.set_preview_item_id(Some(item_id), cx);
12462 });
12463 }
12464
12465 pub fn rename(
12466 &mut self,
12467 _: &Rename,
12468 window: &mut Window,
12469 cx: &mut Context<Self>,
12470 ) -> Option<Task<Result<()>>> {
12471 use language::ToOffset as _;
12472
12473 let provider = self.semantics_provider.clone()?;
12474 let selection = self.selections.newest_anchor().clone();
12475 let (cursor_buffer, cursor_buffer_position) = self
12476 .buffer
12477 .read(cx)
12478 .text_anchor_for_position(selection.head(), cx)?;
12479 let (tail_buffer, cursor_buffer_position_end) = self
12480 .buffer
12481 .read(cx)
12482 .text_anchor_for_position(selection.tail(), cx)?;
12483 if tail_buffer != cursor_buffer {
12484 return None;
12485 }
12486
12487 let snapshot = cursor_buffer.read(cx).snapshot();
12488 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12489 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12490 let prepare_rename = provider
12491 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12492 .unwrap_or_else(|| Task::ready(Ok(None)));
12493 drop(snapshot);
12494
12495 Some(cx.spawn_in(window, |this, mut cx| async move {
12496 let rename_range = if let Some(range) = prepare_rename.await? {
12497 Some(range)
12498 } else {
12499 this.update(&mut cx, |this, cx| {
12500 let buffer = this.buffer.read(cx).snapshot(cx);
12501 let mut buffer_highlights = this
12502 .document_highlights_for_position(selection.head(), &buffer)
12503 .filter(|highlight| {
12504 highlight.start.excerpt_id == selection.head().excerpt_id
12505 && highlight.end.excerpt_id == selection.head().excerpt_id
12506 });
12507 buffer_highlights
12508 .next()
12509 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12510 })?
12511 };
12512 if let Some(rename_range) = rename_range {
12513 this.update_in(&mut cx, |this, window, cx| {
12514 let snapshot = cursor_buffer.read(cx).snapshot();
12515 let rename_buffer_range = rename_range.to_offset(&snapshot);
12516 let cursor_offset_in_rename_range =
12517 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12518 let cursor_offset_in_rename_range_end =
12519 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12520
12521 this.take_rename(false, window, cx);
12522 let buffer = this.buffer.read(cx).read(cx);
12523 let cursor_offset = selection.head().to_offset(&buffer);
12524 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12525 let rename_end = rename_start + rename_buffer_range.len();
12526 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12527 let mut old_highlight_id = None;
12528 let old_name: Arc<str> = buffer
12529 .chunks(rename_start..rename_end, true)
12530 .map(|chunk| {
12531 if old_highlight_id.is_none() {
12532 old_highlight_id = chunk.syntax_highlight_id;
12533 }
12534 chunk.text
12535 })
12536 .collect::<String>()
12537 .into();
12538
12539 drop(buffer);
12540
12541 // Position the selection in the rename editor so that it matches the current selection.
12542 this.show_local_selections = false;
12543 let rename_editor = cx.new(|cx| {
12544 let mut editor = Editor::single_line(window, cx);
12545 editor.buffer.update(cx, |buffer, cx| {
12546 buffer.edit([(0..0, old_name.clone())], None, cx)
12547 });
12548 let rename_selection_range = match cursor_offset_in_rename_range
12549 .cmp(&cursor_offset_in_rename_range_end)
12550 {
12551 Ordering::Equal => {
12552 editor.select_all(&SelectAll, window, cx);
12553 return editor;
12554 }
12555 Ordering::Less => {
12556 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12557 }
12558 Ordering::Greater => {
12559 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12560 }
12561 };
12562 if rename_selection_range.end > old_name.len() {
12563 editor.select_all(&SelectAll, window, cx);
12564 } else {
12565 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12566 s.select_ranges([rename_selection_range]);
12567 });
12568 }
12569 editor
12570 });
12571 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12572 if e == &EditorEvent::Focused {
12573 cx.emit(EditorEvent::FocusedIn)
12574 }
12575 })
12576 .detach();
12577
12578 let write_highlights =
12579 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12580 let read_highlights =
12581 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12582 let ranges = write_highlights
12583 .iter()
12584 .flat_map(|(_, ranges)| ranges.iter())
12585 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12586 .cloned()
12587 .collect();
12588
12589 this.highlight_text::<Rename>(
12590 ranges,
12591 HighlightStyle {
12592 fade_out: Some(0.6),
12593 ..Default::default()
12594 },
12595 cx,
12596 );
12597 let rename_focus_handle = rename_editor.focus_handle(cx);
12598 window.focus(&rename_focus_handle);
12599 let block_id = this.insert_blocks(
12600 [BlockProperties {
12601 style: BlockStyle::Flex,
12602 placement: BlockPlacement::Below(range.start),
12603 height: 1,
12604 render: Arc::new({
12605 let rename_editor = rename_editor.clone();
12606 move |cx: &mut BlockContext| {
12607 let mut text_style = cx.editor_style.text.clone();
12608 if let Some(highlight_style) = old_highlight_id
12609 .and_then(|h| h.style(&cx.editor_style.syntax))
12610 {
12611 text_style = text_style.highlight(highlight_style);
12612 }
12613 div()
12614 .block_mouse_down()
12615 .pl(cx.anchor_x)
12616 .child(EditorElement::new(
12617 &rename_editor,
12618 EditorStyle {
12619 background: cx.theme().system().transparent,
12620 local_player: cx.editor_style.local_player,
12621 text: text_style,
12622 scrollbar_width: cx.editor_style.scrollbar_width,
12623 syntax: cx.editor_style.syntax.clone(),
12624 status: cx.editor_style.status.clone(),
12625 inlay_hints_style: HighlightStyle {
12626 font_weight: Some(FontWeight::BOLD),
12627 ..make_inlay_hints_style(cx.app)
12628 },
12629 inline_completion_styles: make_suggestion_styles(
12630 cx.app,
12631 ),
12632 ..EditorStyle::default()
12633 },
12634 ))
12635 .into_any_element()
12636 }
12637 }),
12638 priority: 0,
12639 }],
12640 Some(Autoscroll::fit()),
12641 cx,
12642 )[0];
12643 this.pending_rename = Some(RenameState {
12644 range,
12645 old_name,
12646 editor: rename_editor,
12647 block_id,
12648 });
12649 })?;
12650 }
12651
12652 Ok(())
12653 }))
12654 }
12655
12656 pub fn confirm_rename(
12657 &mut self,
12658 _: &ConfirmRename,
12659 window: &mut Window,
12660 cx: &mut Context<Self>,
12661 ) -> Option<Task<Result<()>>> {
12662 let rename = self.take_rename(false, window, cx)?;
12663 let workspace = self.workspace()?.downgrade();
12664 let (buffer, start) = self
12665 .buffer
12666 .read(cx)
12667 .text_anchor_for_position(rename.range.start, cx)?;
12668 let (end_buffer, _) = self
12669 .buffer
12670 .read(cx)
12671 .text_anchor_for_position(rename.range.end, cx)?;
12672 if buffer != end_buffer {
12673 return None;
12674 }
12675
12676 let old_name = rename.old_name;
12677 let new_name = rename.editor.read(cx).text(cx);
12678
12679 let rename = self.semantics_provider.as_ref()?.perform_rename(
12680 &buffer,
12681 start,
12682 new_name.clone(),
12683 cx,
12684 )?;
12685
12686 Some(cx.spawn_in(window, |editor, mut cx| async move {
12687 let project_transaction = rename.await?;
12688 Self::open_project_transaction(
12689 &editor,
12690 workspace,
12691 project_transaction,
12692 format!("Rename: {} → {}", old_name, new_name),
12693 cx.clone(),
12694 )
12695 .await?;
12696
12697 editor.update(&mut cx, |editor, cx| {
12698 editor.refresh_document_highlights(cx);
12699 })?;
12700 Ok(())
12701 }))
12702 }
12703
12704 fn take_rename(
12705 &mut self,
12706 moving_cursor: bool,
12707 window: &mut Window,
12708 cx: &mut Context<Self>,
12709 ) -> Option<RenameState> {
12710 let rename = self.pending_rename.take()?;
12711 if rename.editor.focus_handle(cx).is_focused(window) {
12712 window.focus(&self.focus_handle);
12713 }
12714
12715 self.remove_blocks(
12716 [rename.block_id].into_iter().collect(),
12717 Some(Autoscroll::fit()),
12718 cx,
12719 );
12720 self.clear_highlights::<Rename>(cx);
12721 self.show_local_selections = true;
12722
12723 if moving_cursor {
12724 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12725 editor.selections.newest::<usize>(cx).head()
12726 });
12727
12728 // Update the selection to match the position of the selection inside
12729 // the rename editor.
12730 let snapshot = self.buffer.read(cx).read(cx);
12731 let rename_range = rename.range.to_offset(&snapshot);
12732 let cursor_in_editor = snapshot
12733 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12734 .min(rename_range.end);
12735 drop(snapshot);
12736
12737 self.change_selections(None, window, cx, |s| {
12738 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12739 });
12740 } else {
12741 self.refresh_document_highlights(cx);
12742 }
12743
12744 Some(rename)
12745 }
12746
12747 pub fn pending_rename(&self) -> Option<&RenameState> {
12748 self.pending_rename.as_ref()
12749 }
12750
12751 fn format(
12752 &mut self,
12753 _: &Format,
12754 window: &mut Window,
12755 cx: &mut Context<Self>,
12756 ) -> Option<Task<Result<()>>> {
12757 let project = match &self.project {
12758 Some(project) => project.clone(),
12759 None => return None,
12760 };
12761
12762 Some(self.perform_format(
12763 project,
12764 FormatTrigger::Manual,
12765 FormatTarget::Buffers,
12766 window,
12767 cx,
12768 ))
12769 }
12770
12771 fn format_selections(
12772 &mut self,
12773 _: &FormatSelections,
12774 window: &mut Window,
12775 cx: &mut Context<Self>,
12776 ) -> Option<Task<Result<()>>> {
12777 let project = match &self.project {
12778 Some(project) => project.clone(),
12779 None => return None,
12780 };
12781
12782 let ranges = self
12783 .selections
12784 .all_adjusted(cx)
12785 .into_iter()
12786 .map(|selection| selection.range())
12787 .collect_vec();
12788
12789 Some(self.perform_format(
12790 project,
12791 FormatTrigger::Manual,
12792 FormatTarget::Ranges(ranges),
12793 window,
12794 cx,
12795 ))
12796 }
12797
12798 fn perform_format(
12799 &mut self,
12800 project: Entity<Project>,
12801 trigger: FormatTrigger,
12802 target: FormatTarget,
12803 window: &mut Window,
12804 cx: &mut Context<Self>,
12805 ) -> Task<Result<()>> {
12806 let buffer = self.buffer.clone();
12807 let (buffers, target) = match target {
12808 FormatTarget::Buffers => {
12809 let mut buffers = buffer.read(cx).all_buffers();
12810 if trigger == FormatTrigger::Save {
12811 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12812 }
12813 (buffers, LspFormatTarget::Buffers)
12814 }
12815 FormatTarget::Ranges(selection_ranges) => {
12816 let multi_buffer = buffer.read(cx);
12817 let snapshot = multi_buffer.read(cx);
12818 let mut buffers = HashSet::default();
12819 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12820 BTreeMap::new();
12821 for selection_range in selection_ranges {
12822 for (buffer, buffer_range, _) in
12823 snapshot.range_to_buffer_ranges(selection_range)
12824 {
12825 let buffer_id = buffer.remote_id();
12826 let start = buffer.anchor_before(buffer_range.start);
12827 let end = buffer.anchor_after(buffer_range.end);
12828 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12829 buffer_id_to_ranges
12830 .entry(buffer_id)
12831 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12832 .or_insert_with(|| vec![start..end]);
12833 }
12834 }
12835 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12836 }
12837 };
12838
12839 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12840 let format = project.update(cx, |project, cx| {
12841 project.format(buffers, target, true, trigger, cx)
12842 });
12843
12844 cx.spawn_in(window, |_, mut cx| async move {
12845 let transaction = futures::select_biased! {
12846 transaction = format.log_err().fuse() => transaction,
12847 () = timeout => {
12848 log::warn!("timed out waiting for formatting");
12849 None
12850 }
12851 };
12852
12853 buffer
12854 .update(&mut cx, |buffer, cx| {
12855 if let Some(transaction) = transaction {
12856 if !buffer.is_singleton() {
12857 buffer.push_transaction(&transaction.0, cx);
12858 }
12859 }
12860 cx.notify();
12861 })
12862 .ok();
12863
12864 Ok(())
12865 })
12866 }
12867
12868 fn organize_imports(
12869 &mut self,
12870 _: &OrganizeImports,
12871 window: &mut Window,
12872 cx: &mut Context<Self>,
12873 ) -> Option<Task<Result<()>>> {
12874 let project = match &self.project {
12875 Some(project) => project.clone(),
12876 None => return None,
12877 };
12878 Some(self.perform_code_action_kind(
12879 project,
12880 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12881 window,
12882 cx,
12883 ))
12884 }
12885
12886 fn perform_code_action_kind(
12887 &mut self,
12888 project: Entity<Project>,
12889 kind: CodeActionKind,
12890 window: &mut Window,
12891 cx: &mut Context<Self>,
12892 ) -> Task<Result<()>> {
12893 let buffer = self.buffer.clone();
12894 let buffers = buffer.read(cx).all_buffers();
12895 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12896 let apply_action = project.update(cx, |project, cx| {
12897 project.apply_code_action_kind(buffers, kind, true, cx)
12898 });
12899 cx.spawn_in(window, |_, mut cx| async move {
12900 let transaction = futures::select_biased! {
12901 () = timeout => {
12902 log::warn!("timed out waiting for executing code action");
12903 None
12904 }
12905 transaction = apply_action.log_err().fuse() => transaction,
12906 };
12907 buffer
12908 .update(&mut cx, |buffer, cx| {
12909 // check if we need this
12910 if let Some(transaction) = transaction {
12911 if !buffer.is_singleton() {
12912 buffer.push_transaction(&transaction.0, cx);
12913 }
12914 }
12915 cx.notify();
12916 })
12917 .ok();
12918 Ok(())
12919 })
12920 }
12921
12922 fn restart_language_server(
12923 &mut self,
12924 _: &RestartLanguageServer,
12925 _: &mut Window,
12926 cx: &mut Context<Self>,
12927 ) {
12928 if let Some(project) = self.project.clone() {
12929 self.buffer.update(cx, |multi_buffer, cx| {
12930 project.update(cx, |project, cx| {
12931 project.restart_language_servers_for_buffers(
12932 multi_buffer.all_buffers().into_iter().collect(),
12933 cx,
12934 );
12935 });
12936 })
12937 }
12938 }
12939
12940 fn cancel_language_server_work(
12941 workspace: &mut Workspace,
12942 _: &actions::CancelLanguageServerWork,
12943 _: &mut Window,
12944 cx: &mut Context<Workspace>,
12945 ) {
12946 let project = workspace.project();
12947 let buffers = workspace
12948 .active_item(cx)
12949 .and_then(|item| item.act_as::<Editor>(cx))
12950 .map_or(HashSet::default(), |editor| {
12951 editor.read(cx).buffer.read(cx).all_buffers()
12952 });
12953 project.update(cx, |project, cx| {
12954 project.cancel_language_server_work_for_buffers(buffers, cx);
12955 });
12956 }
12957
12958 fn show_character_palette(
12959 &mut self,
12960 _: &ShowCharacterPalette,
12961 window: &mut Window,
12962 _: &mut Context<Self>,
12963 ) {
12964 window.show_character_palette();
12965 }
12966
12967 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12968 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12969 let buffer = self.buffer.read(cx).snapshot(cx);
12970 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12971 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12972 let is_valid = buffer
12973 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12974 .any(|entry| {
12975 entry.diagnostic.is_primary
12976 && !entry.range.is_empty()
12977 && entry.range.start == primary_range_start
12978 && entry.diagnostic.message == active_diagnostics.primary_message
12979 });
12980
12981 if is_valid != active_diagnostics.is_valid {
12982 active_diagnostics.is_valid = is_valid;
12983 if is_valid {
12984 let mut new_styles = HashMap::default();
12985 for (block_id, diagnostic) in &active_diagnostics.blocks {
12986 new_styles.insert(
12987 *block_id,
12988 diagnostic_block_renderer(diagnostic.clone(), None, true),
12989 );
12990 }
12991 self.display_map.update(cx, |display_map, _cx| {
12992 display_map.replace_blocks(new_styles);
12993 });
12994 } else {
12995 self.dismiss_diagnostics(cx);
12996 }
12997 }
12998 }
12999 }
13000
13001 fn activate_diagnostics(
13002 &mut self,
13003 buffer_id: BufferId,
13004 group_id: usize,
13005 window: &mut Window,
13006 cx: &mut Context<Self>,
13007 ) {
13008 self.dismiss_diagnostics(cx);
13009 let snapshot = self.snapshot(window, cx);
13010 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13011 let buffer = self.buffer.read(cx).snapshot(cx);
13012
13013 let mut primary_range = None;
13014 let mut primary_message = None;
13015 let diagnostic_group = buffer
13016 .diagnostic_group(buffer_id, group_id)
13017 .filter_map(|entry| {
13018 let start = entry.range.start;
13019 let end = entry.range.end;
13020 if snapshot.is_line_folded(MultiBufferRow(start.row))
13021 && (start.row == end.row
13022 || snapshot.is_line_folded(MultiBufferRow(end.row)))
13023 {
13024 return None;
13025 }
13026 if entry.diagnostic.is_primary {
13027 primary_range = Some(entry.range.clone());
13028 primary_message = Some(entry.diagnostic.message.clone());
13029 }
13030 Some(entry)
13031 })
13032 .collect::<Vec<_>>();
13033 let primary_range = primary_range?;
13034 let primary_message = primary_message?;
13035
13036 let blocks = display_map
13037 .insert_blocks(
13038 diagnostic_group.iter().map(|entry| {
13039 let diagnostic = entry.diagnostic.clone();
13040 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13041 BlockProperties {
13042 style: BlockStyle::Fixed,
13043 placement: BlockPlacement::Below(
13044 buffer.anchor_after(entry.range.start),
13045 ),
13046 height: message_height,
13047 render: diagnostic_block_renderer(diagnostic, None, true),
13048 priority: 0,
13049 }
13050 }),
13051 cx,
13052 )
13053 .into_iter()
13054 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13055 .collect();
13056
13057 Some(ActiveDiagnosticGroup {
13058 primary_range: buffer.anchor_before(primary_range.start)
13059 ..buffer.anchor_after(primary_range.end),
13060 primary_message,
13061 group_id,
13062 blocks,
13063 is_valid: true,
13064 })
13065 });
13066 }
13067
13068 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13069 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13070 self.display_map.update(cx, |display_map, cx| {
13071 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13072 });
13073 cx.notify();
13074 }
13075 }
13076
13077 /// Disable inline diagnostics rendering for this editor.
13078 pub fn disable_inline_diagnostics(&mut self) {
13079 self.inline_diagnostics_enabled = false;
13080 self.inline_diagnostics_update = Task::ready(());
13081 self.inline_diagnostics.clear();
13082 }
13083
13084 pub fn inline_diagnostics_enabled(&self) -> bool {
13085 self.inline_diagnostics_enabled
13086 }
13087
13088 pub fn show_inline_diagnostics(&self) -> bool {
13089 self.show_inline_diagnostics
13090 }
13091
13092 pub fn toggle_inline_diagnostics(
13093 &mut self,
13094 _: &ToggleInlineDiagnostics,
13095 window: &mut Window,
13096 cx: &mut Context<'_, Editor>,
13097 ) {
13098 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13099 self.refresh_inline_diagnostics(false, window, cx);
13100 }
13101
13102 fn refresh_inline_diagnostics(
13103 &mut self,
13104 debounce: bool,
13105 window: &mut Window,
13106 cx: &mut Context<Self>,
13107 ) {
13108 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13109 self.inline_diagnostics_update = Task::ready(());
13110 self.inline_diagnostics.clear();
13111 return;
13112 }
13113
13114 let debounce_ms = ProjectSettings::get_global(cx)
13115 .diagnostics
13116 .inline
13117 .update_debounce_ms;
13118 let debounce = if debounce && debounce_ms > 0 {
13119 Some(Duration::from_millis(debounce_ms))
13120 } else {
13121 None
13122 };
13123 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
13124 if let Some(debounce) = debounce {
13125 cx.background_executor().timer(debounce).await;
13126 }
13127 let Some(snapshot) = editor
13128 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13129 .ok()
13130 else {
13131 return;
13132 };
13133
13134 let new_inline_diagnostics = cx
13135 .background_spawn(async move {
13136 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13137 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13138 let message = diagnostic_entry
13139 .diagnostic
13140 .message
13141 .split_once('\n')
13142 .map(|(line, _)| line)
13143 .map(SharedString::new)
13144 .unwrap_or_else(|| {
13145 SharedString::from(diagnostic_entry.diagnostic.message)
13146 });
13147 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13148 let (Ok(i) | Err(i)) = inline_diagnostics
13149 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13150 inline_diagnostics.insert(
13151 i,
13152 (
13153 start_anchor,
13154 InlineDiagnostic {
13155 message,
13156 group_id: diagnostic_entry.diagnostic.group_id,
13157 start: diagnostic_entry.range.start.to_point(&snapshot),
13158 is_primary: diagnostic_entry.diagnostic.is_primary,
13159 severity: diagnostic_entry.diagnostic.severity,
13160 },
13161 ),
13162 );
13163 }
13164 inline_diagnostics
13165 })
13166 .await;
13167
13168 editor
13169 .update(&mut cx, |editor, cx| {
13170 editor.inline_diagnostics = new_inline_diagnostics;
13171 cx.notify();
13172 })
13173 .ok();
13174 });
13175 }
13176
13177 pub fn set_selections_from_remote(
13178 &mut self,
13179 selections: Vec<Selection<Anchor>>,
13180 pending_selection: Option<Selection<Anchor>>,
13181 window: &mut Window,
13182 cx: &mut Context<Self>,
13183 ) {
13184 let old_cursor_position = self.selections.newest_anchor().head();
13185 self.selections.change_with(cx, |s| {
13186 s.select_anchors(selections);
13187 if let Some(pending_selection) = pending_selection {
13188 s.set_pending(pending_selection, SelectMode::Character);
13189 } else {
13190 s.clear_pending();
13191 }
13192 });
13193 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13194 }
13195
13196 fn push_to_selection_history(&mut self) {
13197 self.selection_history.push(SelectionHistoryEntry {
13198 selections: self.selections.disjoint_anchors(),
13199 select_next_state: self.select_next_state.clone(),
13200 select_prev_state: self.select_prev_state.clone(),
13201 add_selections_state: self.add_selections_state.clone(),
13202 });
13203 }
13204
13205 pub fn transact(
13206 &mut self,
13207 window: &mut Window,
13208 cx: &mut Context<Self>,
13209 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13210 ) -> Option<TransactionId> {
13211 self.start_transaction_at(Instant::now(), window, cx);
13212 update(self, window, cx);
13213 self.end_transaction_at(Instant::now(), cx)
13214 }
13215
13216 pub fn start_transaction_at(
13217 &mut self,
13218 now: Instant,
13219 window: &mut Window,
13220 cx: &mut Context<Self>,
13221 ) {
13222 self.end_selection(window, cx);
13223 if let Some(tx_id) = self
13224 .buffer
13225 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13226 {
13227 self.selection_history
13228 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13229 cx.emit(EditorEvent::TransactionBegun {
13230 transaction_id: tx_id,
13231 })
13232 }
13233 }
13234
13235 pub fn end_transaction_at(
13236 &mut self,
13237 now: Instant,
13238 cx: &mut Context<Self>,
13239 ) -> Option<TransactionId> {
13240 if let Some(transaction_id) = self
13241 .buffer
13242 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13243 {
13244 if let Some((_, end_selections)) =
13245 self.selection_history.transaction_mut(transaction_id)
13246 {
13247 *end_selections = Some(self.selections.disjoint_anchors());
13248 } else {
13249 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13250 }
13251
13252 cx.emit(EditorEvent::Edited { transaction_id });
13253 Some(transaction_id)
13254 } else {
13255 None
13256 }
13257 }
13258
13259 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13260 if self.selection_mark_mode {
13261 self.change_selections(None, window, cx, |s| {
13262 s.move_with(|_, sel| {
13263 sel.collapse_to(sel.head(), SelectionGoal::None);
13264 });
13265 })
13266 }
13267 self.selection_mark_mode = true;
13268 cx.notify();
13269 }
13270
13271 pub fn swap_selection_ends(
13272 &mut self,
13273 _: &actions::SwapSelectionEnds,
13274 window: &mut Window,
13275 cx: &mut Context<Self>,
13276 ) {
13277 self.change_selections(None, window, cx, |s| {
13278 s.move_with(|_, sel| {
13279 if sel.start != sel.end {
13280 sel.reversed = !sel.reversed
13281 }
13282 });
13283 });
13284 self.request_autoscroll(Autoscroll::newest(), cx);
13285 cx.notify();
13286 }
13287
13288 pub fn toggle_fold(
13289 &mut self,
13290 _: &actions::ToggleFold,
13291 window: &mut Window,
13292 cx: &mut Context<Self>,
13293 ) {
13294 if self.is_singleton(cx) {
13295 let selection = self.selections.newest::<Point>(cx);
13296
13297 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13298 let range = if selection.is_empty() {
13299 let point = selection.head().to_display_point(&display_map);
13300 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13301 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13302 .to_point(&display_map);
13303 start..end
13304 } else {
13305 selection.range()
13306 };
13307 if display_map.folds_in_range(range).next().is_some() {
13308 self.unfold_lines(&Default::default(), window, cx)
13309 } else {
13310 self.fold(&Default::default(), window, cx)
13311 }
13312 } else {
13313 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13314 let buffer_ids: HashSet<_> = self
13315 .selections
13316 .disjoint_anchor_ranges()
13317 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13318 .collect();
13319
13320 let should_unfold = buffer_ids
13321 .iter()
13322 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13323
13324 for buffer_id in buffer_ids {
13325 if should_unfold {
13326 self.unfold_buffer(buffer_id, cx);
13327 } else {
13328 self.fold_buffer(buffer_id, cx);
13329 }
13330 }
13331 }
13332 }
13333
13334 pub fn toggle_fold_recursive(
13335 &mut self,
13336 _: &actions::ToggleFoldRecursive,
13337 window: &mut Window,
13338 cx: &mut Context<Self>,
13339 ) {
13340 let selection = self.selections.newest::<Point>(cx);
13341
13342 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13343 let range = if selection.is_empty() {
13344 let point = selection.head().to_display_point(&display_map);
13345 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13346 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13347 .to_point(&display_map);
13348 start..end
13349 } else {
13350 selection.range()
13351 };
13352 if display_map.folds_in_range(range).next().is_some() {
13353 self.unfold_recursive(&Default::default(), window, cx)
13354 } else {
13355 self.fold_recursive(&Default::default(), window, cx)
13356 }
13357 }
13358
13359 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13360 if self.is_singleton(cx) {
13361 let mut to_fold = Vec::new();
13362 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13363 let selections = self.selections.all_adjusted(cx);
13364
13365 for selection in selections {
13366 let range = selection.range().sorted();
13367 let buffer_start_row = range.start.row;
13368
13369 if range.start.row != range.end.row {
13370 let mut found = false;
13371 let mut row = range.start.row;
13372 while row <= range.end.row {
13373 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13374 {
13375 found = true;
13376 row = crease.range().end.row + 1;
13377 to_fold.push(crease);
13378 } else {
13379 row += 1
13380 }
13381 }
13382 if found {
13383 continue;
13384 }
13385 }
13386
13387 for row in (0..=range.start.row).rev() {
13388 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13389 if crease.range().end.row >= buffer_start_row {
13390 to_fold.push(crease);
13391 if row <= range.start.row {
13392 break;
13393 }
13394 }
13395 }
13396 }
13397 }
13398
13399 self.fold_creases(to_fold, true, window, cx);
13400 } else {
13401 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13402 let buffer_ids = self
13403 .selections
13404 .disjoint_anchor_ranges()
13405 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13406 .collect::<HashSet<_>>();
13407 for buffer_id in buffer_ids {
13408 self.fold_buffer(buffer_id, cx);
13409 }
13410 }
13411 }
13412
13413 fn fold_at_level(
13414 &mut self,
13415 fold_at: &FoldAtLevel,
13416 window: &mut Window,
13417 cx: &mut Context<Self>,
13418 ) {
13419 if !self.buffer.read(cx).is_singleton() {
13420 return;
13421 }
13422
13423 let fold_at_level = fold_at.0;
13424 let snapshot = self.buffer.read(cx).snapshot(cx);
13425 let mut to_fold = Vec::new();
13426 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13427
13428 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13429 while start_row < end_row {
13430 match self
13431 .snapshot(window, cx)
13432 .crease_for_buffer_row(MultiBufferRow(start_row))
13433 {
13434 Some(crease) => {
13435 let nested_start_row = crease.range().start.row + 1;
13436 let nested_end_row = crease.range().end.row;
13437
13438 if current_level < fold_at_level {
13439 stack.push((nested_start_row, nested_end_row, current_level + 1));
13440 } else if current_level == fold_at_level {
13441 to_fold.push(crease);
13442 }
13443
13444 start_row = nested_end_row + 1;
13445 }
13446 None => start_row += 1,
13447 }
13448 }
13449 }
13450
13451 self.fold_creases(to_fold, true, window, cx);
13452 }
13453
13454 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13455 if self.buffer.read(cx).is_singleton() {
13456 let mut fold_ranges = Vec::new();
13457 let snapshot = self.buffer.read(cx).snapshot(cx);
13458
13459 for row in 0..snapshot.max_row().0 {
13460 if let Some(foldable_range) = self
13461 .snapshot(window, cx)
13462 .crease_for_buffer_row(MultiBufferRow(row))
13463 {
13464 fold_ranges.push(foldable_range);
13465 }
13466 }
13467
13468 self.fold_creases(fold_ranges, true, window, cx);
13469 } else {
13470 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13471 editor
13472 .update_in(&mut cx, |editor, _, cx| {
13473 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13474 editor.fold_buffer(buffer_id, cx);
13475 }
13476 })
13477 .ok();
13478 });
13479 }
13480 }
13481
13482 pub fn fold_function_bodies(
13483 &mut self,
13484 _: &actions::FoldFunctionBodies,
13485 window: &mut Window,
13486 cx: &mut Context<Self>,
13487 ) {
13488 let snapshot = self.buffer.read(cx).snapshot(cx);
13489
13490 let ranges = snapshot
13491 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13492 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13493 .collect::<Vec<_>>();
13494
13495 let creases = ranges
13496 .into_iter()
13497 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13498 .collect();
13499
13500 self.fold_creases(creases, true, window, cx);
13501 }
13502
13503 pub fn fold_recursive(
13504 &mut self,
13505 _: &actions::FoldRecursive,
13506 window: &mut Window,
13507 cx: &mut Context<Self>,
13508 ) {
13509 let mut to_fold = Vec::new();
13510 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13511 let selections = self.selections.all_adjusted(cx);
13512
13513 for selection in selections {
13514 let range = selection.range().sorted();
13515 let buffer_start_row = range.start.row;
13516
13517 if range.start.row != range.end.row {
13518 let mut found = false;
13519 for row in range.start.row..=range.end.row {
13520 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13521 found = true;
13522 to_fold.push(crease);
13523 }
13524 }
13525 if found {
13526 continue;
13527 }
13528 }
13529
13530 for row in (0..=range.start.row).rev() {
13531 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13532 if crease.range().end.row >= buffer_start_row {
13533 to_fold.push(crease);
13534 } else {
13535 break;
13536 }
13537 }
13538 }
13539 }
13540
13541 self.fold_creases(to_fold, true, window, cx);
13542 }
13543
13544 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13545 let buffer_row = fold_at.buffer_row;
13546 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13547
13548 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13549 let autoscroll = self
13550 .selections
13551 .all::<Point>(cx)
13552 .iter()
13553 .any(|selection| crease.range().overlaps(&selection.range()));
13554
13555 self.fold_creases(vec![crease], autoscroll, window, cx);
13556 }
13557 }
13558
13559 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13560 if self.is_singleton(cx) {
13561 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13562 let buffer = &display_map.buffer_snapshot;
13563 let selections = self.selections.all::<Point>(cx);
13564 let ranges = selections
13565 .iter()
13566 .map(|s| {
13567 let range = s.display_range(&display_map).sorted();
13568 let mut start = range.start.to_point(&display_map);
13569 let mut end = range.end.to_point(&display_map);
13570 start.column = 0;
13571 end.column = buffer.line_len(MultiBufferRow(end.row));
13572 start..end
13573 })
13574 .collect::<Vec<_>>();
13575
13576 self.unfold_ranges(&ranges, true, true, cx);
13577 } else {
13578 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13579 let buffer_ids = self
13580 .selections
13581 .disjoint_anchor_ranges()
13582 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13583 .collect::<HashSet<_>>();
13584 for buffer_id in buffer_ids {
13585 self.unfold_buffer(buffer_id, cx);
13586 }
13587 }
13588 }
13589
13590 pub fn unfold_recursive(
13591 &mut self,
13592 _: &UnfoldRecursive,
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 let selections = self.selections.all::<Point>(cx);
13598 let ranges = selections
13599 .iter()
13600 .map(|s| {
13601 let mut range = s.display_range(&display_map).sorted();
13602 *range.start.column_mut() = 0;
13603 *range.end.column_mut() = display_map.line_len(range.end.row());
13604 let start = range.start.to_point(&display_map);
13605 let end = range.end.to_point(&display_map);
13606 start..end
13607 })
13608 .collect::<Vec<_>>();
13609
13610 self.unfold_ranges(&ranges, true, true, cx);
13611 }
13612
13613 pub fn unfold_at(
13614 &mut self,
13615 unfold_at: &UnfoldAt,
13616 _window: &mut Window,
13617 cx: &mut Context<Self>,
13618 ) {
13619 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13620
13621 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13622 ..Point::new(
13623 unfold_at.buffer_row.0,
13624 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13625 );
13626
13627 let autoscroll = self
13628 .selections
13629 .all::<Point>(cx)
13630 .iter()
13631 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13632
13633 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13634 }
13635
13636 pub fn unfold_all(
13637 &mut self,
13638 _: &actions::UnfoldAll,
13639 _window: &mut Window,
13640 cx: &mut Context<Self>,
13641 ) {
13642 if self.buffer.read(cx).is_singleton() {
13643 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13644 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13645 } else {
13646 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13647 editor
13648 .update(&mut cx, |editor, cx| {
13649 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13650 editor.unfold_buffer(buffer_id, cx);
13651 }
13652 })
13653 .ok();
13654 });
13655 }
13656 }
13657
13658 pub fn fold_selected_ranges(
13659 &mut self,
13660 _: &FoldSelectedRanges,
13661 window: &mut Window,
13662 cx: &mut Context<Self>,
13663 ) {
13664 let selections = self.selections.all::<Point>(cx);
13665 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13666 let line_mode = self.selections.line_mode;
13667 let ranges = selections
13668 .into_iter()
13669 .map(|s| {
13670 if line_mode {
13671 let start = Point::new(s.start.row, 0);
13672 let end = Point::new(
13673 s.end.row,
13674 display_map
13675 .buffer_snapshot
13676 .line_len(MultiBufferRow(s.end.row)),
13677 );
13678 Crease::simple(start..end, display_map.fold_placeholder.clone())
13679 } else {
13680 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13681 }
13682 })
13683 .collect::<Vec<_>>();
13684 self.fold_creases(ranges, true, window, cx);
13685 }
13686
13687 pub fn fold_ranges<T: ToOffset + Clone>(
13688 &mut self,
13689 ranges: Vec<Range<T>>,
13690 auto_scroll: bool,
13691 window: &mut Window,
13692 cx: &mut Context<Self>,
13693 ) {
13694 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13695 let ranges = ranges
13696 .into_iter()
13697 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13698 .collect::<Vec<_>>();
13699 self.fold_creases(ranges, auto_scroll, window, cx);
13700 }
13701
13702 pub fn fold_creases<T: ToOffset + Clone>(
13703 &mut self,
13704 creases: Vec<Crease<T>>,
13705 auto_scroll: bool,
13706 window: &mut Window,
13707 cx: &mut Context<Self>,
13708 ) {
13709 if creases.is_empty() {
13710 return;
13711 }
13712
13713 let mut buffers_affected = HashSet::default();
13714 let multi_buffer = self.buffer().read(cx);
13715 for crease in &creases {
13716 if let Some((_, buffer, _)) =
13717 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13718 {
13719 buffers_affected.insert(buffer.read(cx).remote_id());
13720 };
13721 }
13722
13723 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13724
13725 if auto_scroll {
13726 self.request_autoscroll(Autoscroll::fit(), cx);
13727 }
13728
13729 cx.notify();
13730
13731 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13732 // Clear diagnostics block when folding a range that contains it.
13733 let snapshot = self.snapshot(window, cx);
13734 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13735 drop(snapshot);
13736 self.active_diagnostics = Some(active_diagnostics);
13737 self.dismiss_diagnostics(cx);
13738 } else {
13739 self.active_diagnostics = Some(active_diagnostics);
13740 }
13741 }
13742
13743 self.scrollbar_marker_state.dirty = true;
13744 }
13745
13746 /// Removes any folds whose ranges intersect any of the given ranges.
13747 pub fn unfold_ranges<T: ToOffset + Clone>(
13748 &mut self,
13749 ranges: &[Range<T>],
13750 inclusive: bool,
13751 auto_scroll: bool,
13752 cx: &mut Context<Self>,
13753 ) {
13754 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13755 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13756 });
13757 }
13758
13759 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13760 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13761 return;
13762 }
13763 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13764 self.display_map.update(cx, |display_map, cx| {
13765 display_map.fold_buffers([buffer_id], cx)
13766 });
13767 cx.emit(EditorEvent::BufferFoldToggled {
13768 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13769 folded: true,
13770 });
13771 cx.notify();
13772 }
13773
13774 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13775 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13776 return;
13777 }
13778 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13779 self.display_map.update(cx, |display_map, cx| {
13780 display_map.unfold_buffers([buffer_id], cx);
13781 });
13782 cx.emit(EditorEvent::BufferFoldToggled {
13783 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13784 folded: false,
13785 });
13786 cx.notify();
13787 }
13788
13789 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13790 self.display_map.read(cx).is_buffer_folded(buffer)
13791 }
13792
13793 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13794 self.display_map.read(cx).folded_buffers()
13795 }
13796
13797 /// Removes any folds with the given ranges.
13798 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13799 &mut self,
13800 ranges: &[Range<T>],
13801 type_id: TypeId,
13802 auto_scroll: bool,
13803 cx: &mut Context<Self>,
13804 ) {
13805 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13806 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13807 });
13808 }
13809
13810 fn remove_folds_with<T: ToOffset + Clone>(
13811 &mut self,
13812 ranges: &[Range<T>],
13813 auto_scroll: bool,
13814 cx: &mut Context<Self>,
13815 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13816 ) {
13817 if ranges.is_empty() {
13818 return;
13819 }
13820
13821 let mut buffers_affected = HashSet::default();
13822 let multi_buffer = self.buffer().read(cx);
13823 for range in ranges {
13824 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13825 buffers_affected.insert(buffer.read(cx).remote_id());
13826 };
13827 }
13828
13829 self.display_map.update(cx, update);
13830
13831 if auto_scroll {
13832 self.request_autoscroll(Autoscroll::fit(), cx);
13833 }
13834
13835 cx.notify();
13836 self.scrollbar_marker_state.dirty = true;
13837 self.active_indent_guides_state.dirty = true;
13838 }
13839
13840 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13841 self.display_map.read(cx).fold_placeholder.clone()
13842 }
13843
13844 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13845 self.buffer.update(cx, |buffer, cx| {
13846 buffer.set_all_diff_hunks_expanded(cx);
13847 });
13848 }
13849
13850 pub fn expand_all_diff_hunks(
13851 &mut self,
13852 _: &ExpandAllDiffHunks,
13853 _window: &mut Window,
13854 cx: &mut Context<Self>,
13855 ) {
13856 self.buffer.update(cx, |buffer, cx| {
13857 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13858 });
13859 }
13860
13861 pub fn toggle_selected_diff_hunks(
13862 &mut self,
13863 _: &ToggleSelectedDiffHunks,
13864 _window: &mut Window,
13865 cx: &mut Context<Self>,
13866 ) {
13867 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13868 self.toggle_diff_hunks_in_ranges(ranges, cx);
13869 }
13870
13871 pub fn diff_hunks_in_ranges<'a>(
13872 &'a self,
13873 ranges: &'a [Range<Anchor>],
13874 buffer: &'a MultiBufferSnapshot,
13875 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13876 ranges.iter().flat_map(move |range| {
13877 let end_excerpt_id = range.end.excerpt_id;
13878 let range = range.to_point(buffer);
13879 let mut peek_end = range.end;
13880 if range.end.row < buffer.max_row().0 {
13881 peek_end = Point::new(range.end.row + 1, 0);
13882 }
13883 buffer
13884 .diff_hunks_in_range(range.start..peek_end)
13885 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13886 })
13887 }
13888
13889 pub fn has_stageable_diff_hunks_in_ranges(
13890 &self,
13891 ranges: &[Range<Anchor>],
13892 snapshot: &MultiBufferSnapshot,
13893 ) -> bool {
13894 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13895 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13896 }
13897
13898 pub fn toggle_staged_selected_diff_hunks(
13899 &mut self,
13900 _: &::git::ToggleStaged,
13901 _: &mut Window,
13902 cx: &mut Context<Self>,
13903 ) {
13904 let snapshot = self.buffer.read(cx).snapshot(cx);
13905 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13906 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13907 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13908 }
13909
13910 pub fn stage_and_next(
13911 &mut self,
13912 _: &::git::StageAndNext,
13913 window: &mut Window,
13914 cx: &mut Context<Self>,
13915 ) {
13916 self.do_stage_or_unstage_and_next(true, window, cx);
13917 }
13918
13919 pub fn unstage_and_next(
13920 &mut self,
13921 _: &::git::UnstageAndNext,
13922 window: &mut Window,
13923 cx: &mut Context<Self>,
13924 ) {
13925 self.do_stage_or_unstage_and_next(false, window, cx);
13926 }
13927
13928 pub fn stage_or_unstage_diff_hunks(
13929 &mut self,
13930 stage: bool,
13931 ranges: Vec<Range<Anchor>>,
13932 cx: &mut Context<Self>,
13933 ) {
13934 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13935 cx.spawn(|this, mut cx| async move {
13936 task.await?;
13937 this.update(&mut cx, |this, cx| {
13938 let snapshot = this.buffer.read(cx).snapshot(cx);
13939 let chunk_by = this
13940 .diff_hunks_in_ranges(&ranges, &snapshot)
13941 .chunk_by(|hunk| hunk.buffer_id);
13942 for (buffer_id, hunks) in &chunk_by {
13943 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13944 }
13945 })
13946 })
13947 .detach_and_log_err(cx);
13948 }
13949
13950 fn save_buffers_for_ranges_if_needed(
13951 &mut self,
13952 ranges: &[Range<Anchor>],
13953 cx: &mut Context<'_, Editor>,
13954 ) -> Task<Result<()>> {
13955 let multibuffer = self.buffer.read(cx);
13956 let snapshot = multibuffer.read(cx);
13957 let buffer_ids: HashSet<_> = ranges
13958 .iter()
13959 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13960 .collect();
13961 drop(snapshot);
13962
13963 let mut buffers = HashSet::default();
13964 for buffer_id in buffer_ids {
13965 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13966 let buffer = buffer_entity.read(cx);
13967 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13968 {
13969 buffers.insert(buffer_entity);
13970 }
13971 }
13972 }
13973
13974 if let Some(project) = &self.project {
13975 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13976 } else {
13977 Task::ready(Ok(()))
13978 }
13979 }
13980
13981 fn do_stage_or_unstage_and_next(
13982 &mut self,
13983 stage: bool,
13984 window: &mut Window,
13985 cx: &mut Context<Self>,
13986 ) {
13987 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13988
13989 if ranges.iter().any(|range| range.start != range.end) {
13990 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13991 return;
13992 }
13993
13994 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13995 let snapshot = self.snapshot(window, cx);
13996 let position = self.selections.newest::<Point>(cx).head();
13997 let mut row = snapshot
13998 .buffer_snapshot
13999 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14000 .find(|hunk| hunk.row_range.start.0 > position.row)
14001 .map(|hunk| hunk.row_range.start);
14002
14003 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14004 // Outside of the project diff editor, wrap around to the beginning.
14005 if !all_diff_hunks_expanded {
14006 row = row.or_else(|| {
14007 snapshot
14008 .buffer_snapshot
14009 .diff_hunks_in_range(Point::zero()..position)
14010 .find(|hunk| hunk.row_range.end.0 < position.row)
14011 .map(|hunk| hunk.row_range.start)
14012 });
14013 }
14014
14015 if let Some(row) = row {
14016 let destination = Point::new(row.0, 0);
14017 let autoscroll = Autoscroll::center();
14018
14019 self.unfold_ranges(&[destination..destination], false, false, cx);
14020 self.change_selections(Some(autoscroll), window, cx, |s| {
14021 s.select_ranges([destination..destination]);
14022 });
14023 } else if all_diff_hunks_expanded {
14024 window.dispatch_action(::git::ExpandCommitEditor.boxed_clone(), cx);
14025 }
14026 }
14027
14028 fn do_stage_or_unstage(
14029 &self,
14030 stage: bool,
14031 buffer_id: BufferId,
14032 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14033 cx: &mut App,
14034 ) -> Option<()> {
14035 let project = self.project.as_ref()?;
14036 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14037 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14038 let buffer_snapshot = buffer.read(cx).snapshot();
14039 let file_exists = buffer_snapshot
14040 .file()
14041 .is_some_and(|file| file.disk_state().exists());
14042 diff.update(cx, |diff, cx| {
14043 diff.stage_or_unstage_hunks(
14044 stage,
14045 &hunks
14046 .map(|hunk| buffer_diff::DiffHunk {
14047 buffer_range: hunk.buffer_range,
14048 diff_base_byte_range: hunk.diff_base_byte_range,
14049 secondary_status: hunk.secondary_status,
14050 range: Point::zero()..Point::zero(), // unused
14051 })
14052 .collect::<Vec<_>>(),
14053 &buffer_snapshot,
14054 file_exists,
14055 cx,
14056 )
14057 });
14058 None
14059 }
14060
14061 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14062 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14063 self.buffer
14064 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14065 }
14066
14067 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14068 self.buffer.update(cx, |buffer, cx| {
14069 let ranges = vec![Anchor::min()..Anchor::max()];
14070 if !buffer.all_diff_hunks_expanded()
14071 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14072 {
14073 buffer.collapse_diff_hunks(ranges, cx);
14074 true
14075 } else {
14076 false
14077 }
14078 })
14079 }
14080
14081 fn toggle_diff_hunks_in_ranges(
14082 &mut self,
14083 ranges: Vec<Range<Anchor>>,
14084 cx: &mut Context<'_, Editor>,
14085 ) {
14086 self.buffer.update(cx, |buffer, cx| {
14087 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14088 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14089 })
14090 }
14091
14092 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14093 self.buffer.update(cx, |buffer, cx| {
14094 let snapshot = buffer.snapshot(cx);
14095 let excerpt_id = range.end.excerpt_id;
14096 let point_range = range.to_point(&snapshot);
14097 let expand = !buffer.single_hunk_is_expanded(range, cx);
14098 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14099 })
14100 }
14101
14102 pub(crate) fn apply_all_diff_hunks(
14103 &mut self,
14104 _: &ApplyAllDiffHunks,
14105 window: &mut Window,
14106 cx: &mut Context<Self>,
14107 ) {
14108 let buffers = self.buffer.read(cx).all_buffers();
14109 for branch_buffer in buffers {
14110 branch_buffer.update(cx, |branch_buffer, cx| {
14111 branch_buffer.merge_into_base(Vec::new(), cx);
14112 });
14113 }
14114
14115 if let Some(project) = self.project.clone() {
14116 self.save(true, project, window, cx).detach_and_log_err(cx);
14117 }
14118 }
14119
14120 pub(crate) fn apply_selected_diff_hunks(
14121 &mut self,
14122 _: &ApplyDiffHunk,
14123 window: &mut Window,
14124 cx: &mut Context<Self>,
14125 ) {
14126 let snapshot = self.snapshot(window, cx);
14127 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14128 let mut ranges_by_buffer = HashMap::default();
14129 self.transact(window, cx, |editor, _window, cx| {
14130 for hunk in hunks {
14131 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14132 ranges_by_buffer
14133 .entry(buffer.clone())
14134 .or_insert_with(Vec::new)
14135 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14136 }
14137 }
14138
14139 for (buffer, ranges) in ranges_by_buffer {
14140 buffer.update(cx, |buffer, cx| {
14141 buffer.merge_into_base(ranges, cx);
14142 });
14143 }
14144 });
14145
14146 if let Some(project) = self.project.clone() {
14147 self.save(true, project, window, cx).detach_and_log_err(cx);
14148 }
14149 }
14150
14151 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14152 if hovered != self.gutter_hovered {
14153 self.gutter_hovered = hovered;
14154 cx.notify();
14155 }
14156 }
14157
14158 pub fn insert_blocks(
14159 &mut self,
14160 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14161 autoscroll: Option<Autoscroll>,
14162 cx: &mut Context<Self>,
14163 ) -> Vec<CustomBlockId> {
14164 let blocks = self
14165 .display_map
14166 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14167 if let Some(autoscroll) = autoscroll {
14168 self.request_autoscroll(autoscroll, cx);
14169 }
14170 cx.notify();
14171 blocks
14172 }
14173
14174 pub fn resize_blocks(
14175 &mut self,
14176 heights: HashMap<CustomBlockId, u32>,
14177 autoscroll: Option<Autoscroll>,
14178 cx: &mut Context<Self>,
14179 ) {
14180 self.display_map
14181 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14182 if let Some(autoscroll) = autoscroll {
14183 self.request_autoscroll(autoscroll, cx);
14184 }
14185 cx.notify();
14186 }
14187
14188 pub fn replace_blocks(
14189 &mut self,
14190 renderers: HashMap<CustomBlockId, RenderBlock>,
14191 autoscroll: Option<Autoscroll>,
14192 cx: &mut Context<Self>,
14193 ) {
14194 self.display_map
14195 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14196 if let Some(autoscroll) = autoscroll {
14197 self.request_autoscroll(autoscroll, cx);
14198 }
14199 cx.notify();
14200 }
14201
14202 pub fn remove_blocks(
14203 &mut self,
14204 block_ids: HashSet<CustomBlockId>,
14205 autoscroll: Option<Autoscroll>,
14206 cx: &mut Context<Self>,
14207 ) {
14208 self.display_map.update(cx, |display_map, cx| {
14209 display_map.remove_blocks(block_ids, cx)
14210 });
14211 if let Some(autoscroll) = autoscroll {
14212 self.request_autoscroll(autoscroll, cx);
14213 }
14214 cx.notify();
14215 }
14216
14217 pub fn row_for_block(
14218 &self,
14219 block_id: CustomBlockId,
14220 cx: &mut Context<Self>,
14221 ) -> Option<DisplayRow> {
14222 self.display_map
14223 .update(cx, |map, cx| map.row_for_block(block_id, cx))
14224 }
14225
14226 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14227 self.focused_block = Some(focused_block);
14228 }
14229
14230 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14231 self.focused_block.take()
14232 }
14233
14234 pub fn insert_creases(
14235 &mut self,
14236 creases: impl IntoIterator<Item = Crease<Anchor>>,
14237 cx: &mut Context<Self>,
14238 ) -> Vec<CreaseId> {
14239 self.display_map
14240 .update(cx, |map, cx| map.insert_creases(creases, cx))
14241 }
14242
14243 pub fn remove_creases(
14244 &mut self,
14245 ids: impl IntoIterator<Item = CreaseId>,
14246 cx: &mut Context<Self>,
14247 ) {
14248 self.display_map
14249 .update(cx, |map, cx| map.remove_creases(ids, cx));
14250 }
14251
14252 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14253 self.display_map
14254 .update(cx, |map, cx| map.snapshot(cx))
14255 .longest_row()
14256 }
14257
14258 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14259 self.display_map
14260 .update(cx, |map, cx| map.snapshot(cx))
14261 .max_point()
14262 }
14263
14264 pub fn text(&self, cx: &App) -> String {
14265 self.buffer.read(cx).read(cx).text()
14266 }
14267
14268 pub fn is_empty(&self, cx: &App) -> bool {
14269 self.buffer.read(cx).read(cx).is_empty()
14270 }
14271
14272 pub fn text_option(&self, cx: &App) -> Option<String> {
14273 let text = self.text(cx);
14274 let text = text.trim();
14275
14276 if text.is_empty() {
14277 return None;
14278 }
14279
14280 Some(text.to_string())
14281 }
14282
14283 pub fn set_text(
14284 &mut self,
14285 text: impl Into<Arc<str>>,
14286 window: &mut Window,
14287 cx: &mut Context<Self>,
14288 ) {
14289 self.transact(window, cx, |this, _, cx| {
14290 this.buffer
14291 .read(cx)
14292 .as_singleton()
14293 .expect("you can only call set_text on editors for singleton buffers")
14294 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14295 });
14296 }
14297
14298 pub fn display_text(&self, cx: &mut App) -> String {
14299 self.display_map
14300 .update(cx, |map, cx| map.snapshot(cx))
14301 .text()
14302 }
14303
14304 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14305 let mut wrap_guides = smallvec::smallvec![];
14306
14307 if self.show_wrap_guides == Some(false) {
14308 return wrap_guides;
14309 }
14310
14311 let settings = self.buffer.read(cx).language_settings(cx);
14312 if settings.show_wrap_guides {
14313 match self.soft_wrap_mode(cx) {
14314 SoftWrap::Column(soft_wrap) => {
14315 wrap_guides.push((soft_wrap as usize, true));
14316 }
14317 SoftWrap::Bounded(soft_wrap) => {
14318 wrap_guides.push((soft_wrap as usize, true));
14319 }
14320 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14321 }
14322 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14323 }
14324
14325 wrap_guides
14326 }
14327
14328 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14329 let settings = self.buffer.read(cx).language_settings(cx);
14330 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14331 match mode {
14332 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14333 SoftWrap::None
14334 }
14335 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14336 language_settings::SoftWrap::PreferredLineLength => {
14337 SoftWrap::Column(settings.preferred_line_length)
14338 }
14339 language_settings::SoftWrap::Bounded => {
14340 SoftWrap::Bounded(settings.preferred_line_length)
14341 }
14342 }
14343 }
14344
14345 pub fn set_soft_wrap_mode(
14346 &mut self,
14347 mode: language_settings::SoftWrap,
14348
14349 cx: &mut Context<Self>,
14350 ) {
14351 self.soft_wrap_mode_override = Some(mode);
14352 cx.notify();
14353 }
14354
14355 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14356 self.hard_wrap = hard_wrap;
14357 cx.notify();
14358 }
14359
14360 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14361 self.text_style_refinement = Some(style);
14362 }
14363
14364 /// called by the Element so we know what style we were most recently rendered with.
14365 pub(crate) fn set_style(
14366 &mut self,
14367 style: EditorStyle,
14368 window: &mut Window,
14369 cx: &mut Context<Self>,
14370 ) {
14371 let rem_size = window.rem_size();
14372 self.display_map.update(cx, |map, cx| {
14373 map.set_font(
14374 style.text.font(),
14375 style.text.font_size.to_pixels(rem_size),
14376 cx,
14377 )
14378 });
14379 self.style = Some(style);
14380 }
14381
14382 pub fn style(&self) -> Option<&EditorStyle> {
14383 self.style.as_ref()
14384 }
14385
14386 // Called by the element. This method is not designed to be called outside of the editor
14387 // element's layout code because it does not notify when rewrapping is computed synchronously.
14388 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14389 self.display_map
14390 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14391 }
14392
14393 pub fn set_soft_wrap(&mut self) {
14394 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14395 }
14396
14397 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14398 if self.soft_wrap_mode_override.is_some() {
14399 self.soft_wrap_mode_override.take();
14400 } else {
14401 let soft_wrap = match self.soft_wrap_mode(cx) {
14402 SoftWrap::GitDiff => return,
14403 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14404 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14405 language_settings::SoftWrap::None
14406 }
14407 };
14408 self.soft_wrap_mode_override = Some(soft_wrap);
14409 }
14410 cx.notify();
14411 }
14412
14413 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14414 let Some(workspace) = self.workspace() else {
14415 return;
14416 };
14417 let fs = workspace.read(cx).app_state().fs.clone();
14418 let current_show = TabBarSettings::get_global(cx).show;
14419 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14420 setting.show = Some(!current_show);
14421 });
14422 }
14423
14424 pub fn toggle_indent_guides(
14425 &mut self,
14426 _: &ToggleIndentGuides,
14427 _: &mut Window,
14428 cx: &mut Context<Self>,
14429 ) {
14430 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14431 self.buffer
14432 .read(cx)
14433 .language_settings(cx)
14434 .indent_guides
14435 .enabled
14436 });
14437 self.show_indent_guides = Some(!currently_enabled);
14438 cx.notify();
14439 }
14440
14441 fn should_show_indent_guides(&self) -> Option<bool> {
14442 self.show_indent_guides
14443 }
14444
14445 pub fn toggle_line_numbers(
14446 &mut self,
14447 _: &ToggleLineNumbers,
14448 _: &mut Window,
14449 cx: &mut Context<Self>,
14450 ) {
14451 let mut editor_settings = EditorSettings::get_global(cx).clone();
14452 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14453 EditorSettings::override_global(editor_settings, cx);
14454 }
14455
14456 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
14457 if let Some(show_line_numbers) = self.show_line_numbers {
14458 return show_line_numbers;
14459 }
14460 EditorSettings::get_global(cx).gutter.line_numbers
14461 }
14462
14463 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14464 self.use_relative_line_numbers
14465 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14466 }
14467
14468 pub fn toggle_relative_line_numbers(
14469 &mut self,
14470 _: &ToggleRelativeLineNumbers,
14471 _: &mut Window,
14472 cx: &mut Context<Self>,
14473 ) {
14474 let is_relative = self.should_use_relative_line_numbers(cx);
14475 self.set_relative_line_number(Some(!is_relative), cx)
14476 }
14477
14478 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14479 self.use_relative_line_numbers = is_relative;
14480 cx.notify();
14481 }
14482
14483 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14484 self.show_gutter = show_gutter;
14485 cx.notify();
14486 }
14487
14488 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14489 self.show_scrollbars = show_scrollbars;
14490 cx.notify();
14491 }
14492
14493 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14494 self.show_line_numbers = Some(show_line_numbers);
14495 cx.notify();
14496 }
14497
14498 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14499 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14500 cx.notify();
14501 }
14502
14503 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14504 self.show_code_actions = Some(show_code_actions);
14505 cx.notify();
14506 }
14507
14508 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14509 self.show_runnables = Some(show_runnables);
14510 cx.notify();
14511 }
14512
14513 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14514 if self.display_map.read(cx).masked != masked {
14515 self.display_map.update(cx, |map, _| map.masked = masked);
14516 }
14517 cx.notify()
14518 }
14519
14520 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14521 self.show_wrap_guides = Some(show_wrap_guides);
14522 cx.notify();
14523 }
14524
14525 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14526 self.show_indent_guides = Some(show_indent_guides);
14527 cx.notify();
14528 }
14529
14530 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14531 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14532 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14533 if let Some(dir) = file.abs_path(cx).parent() {
14534 return Some(dir.to_owned());
14535 }
14536 }
14537
14538 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14539 return Some(project_path.path.to_path_buf());
14540 }
14541 }
14542
14543 None
14544 }
14545
14546 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14547 self.active_excerpt(cx)?
14548 .1
14549 .read(cx)
14550 .file()
14551 .and_then(|f| f.as_local())
14552 }
14553
14554 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14555 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14556 let buffer = buffer.read(cx);
14557 if let Some(project_path) = buffer.project_path(cx) {
14558 let project = self.project.as_ref()?.read(cx);
14559 project.absolute_path(&project_path, cx)
14560 } else {
14561 buffer
14562 .file()
14563 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14564 }
14565 })
14566 }
14567
14568 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14569 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14570 let project_path = buffer.read(cx).project_path(cx)?;
14571 let project = self.project.as_ref()?.read(cx);
14572 let entry = project.entry_for_path(&project_path, cx)?;
14573 let path = entry.path.to_path_buf();
14574 Some(path)
14575 })
14576 }
14577
14578 pub fn reveal_in_finder(
14579 &mut self,
14580 _: &RevealInFileManager,
14581 _window: &mut Window,
14582 cx: &mut Context<Self>,
14583 ) {
14584 if let Some(target) = self.target_file(cx) {
14585 cx.reveal_path(&target.abs_path(cx));
14586 }
14587 }
14588
14589 pub fn copy_path(
14590 &mut self,
14591 _: &zed_actions::workspace::CopyPath,
14592 _window: &mut Window,
14593 cx: &mut Context<Self>,
14594 ) {
14595 if let Some(path) = self.target_file_abs_path(cx) {
14596 if let Some(path) = path.to_str() {
14597 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14598 }
14599 }
14600 }
14601
14602 pub fn copy_relative_path(
14603 &mut self,
14604 _: &zed_actions::workspace::CopyRelativePath,
14605 _window: &mut Window,
14606 cx: &mut Context<Self>,
14607 ) {
14608 if let Some(path) = self.target_file_path(cx) {
14609 if let Some(path) = path.to_str() {
14610 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14611 }
14612 }
14613 }
14614
14615 pub fn copy_file_name_without_extension(
14616 &mut self,
14617 _: &CopyFileNameWithoutExtension,
14618 _: &mut Window,
14619 cx: &mut Context<Self>,
14620 ) {
14621 if let Some(file) = self.target_file(cx) {
14622 if let Some(file_stem) = file.path().file_stem() {
14623 if let Some(name) = file_stem.to_str() {
14624 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14625 }
14626 }
14627 }
14628 }
14629
14630 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14631 if let Some(file) = self.target_file(cx) {
14632 if let Some(file_name) = file.path().file_name() {
14633 if let Some(name) = file_name.to_str() {
14634 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14635 }
14636 }
14637 }
14638 }
14639
14640 pub fn toggle_git_blame(
14641 &mut self,
14642 _: &::git::Blame,
14643 window: &mut Window,
14644 cx: &mut Context<Self>,
14645 ) {
14646 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14647
14648 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14649 self.start_git_blame(true, window, cx);
14650 }
14651
14652 cx.notify();
14653 }
14654
14655 pub fn toggle_git_blame_inline(
14656 &mut self,
14657 _: &ToggleGitBlameInline,
14658 window: &mut Window,
14659 cx: &mut Context<Self>,
14660 ) {
14661 self.toggle_git_blame_inline_internal(true, window, cx);
14662 cx.notify();
14663 }
14664
14665 pub fn git_blame_inline_enabled(&self) -> bool {
14666 self.git_blame_inline_enabled
14667 }
14668
14669 pub fn toggle_selection_menu(
14670 &mut self,
14671 _: &ToggleSelectionMenu,
14672 _: &mut Window,
14673 cx: &mut Context<Self>,
14674 ) {
14675 self.show_selection_menu = self
14676 .show_selection_menu
14677 .map(|show_selections_menu| !show_selections_menu)
14678 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14679
14680 cx.notify();
14681 }
14682
14683 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14684 self.show_selection_menu
14685 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14686 }
14687
14688 fn start_git_blame(
14689 &mut self,
14690 user_triggered: bool,
14691 window: &mut Window,
14692 cx: &mut Context<Self>,
14693 ) {
14694 if let Some(project) = self.project.as_ref() {
14695 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14696 return;
14697 };
14698
14699 if buffer.read(cx).file().is_none() {
14700 return;
14701 }
14702
14703 let focused = self.focus_handle(cx).contains_focused(window, cx);
14704
14705 let project = project.clone();
14706 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14707 self.blame_subscription =
14708 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14709 self.blame = Some(blame);
14710 }
14711 }
14712
14713 fn toggle_git_blame_inline_internal(
14714 &mut self,
14715 user_triggered: bool,
14716 window: &mut Window,
14717 cx: &mut Context<Self>,
14718 ) {
14719 if self.git_blame_inline_enabled {
14720 self.git_blame_inline_enabled = false;
14721 self.show_git_blame_inline = false;
14722 self.show_git_blame_inline_delay_task.take();
14723 } else {
14724 self.git_blame_inline_enabled = true;
14725 self.start_git_blame_inline(user_triggered, window, cx);
14726 }
14727
14728 cx.notify();
14729 }
14730
14731 fn start_git_blame_inline(
14732 &mut self,
14733 user_triggered: bool,
14734 window: &mut Window,
14735 cx: &mut Context<Self>,
14736 ) {
14737 self.start_git_blame(user_triggered, window, cx);
14738
14739 if ProjectSettings::get_global(cx)
14740 .git
14741 .inline_blame_delay()
14742 .is_some()
14743 {
14744 self.start_inline_blame_timer(window, cx);
14745 } else {
14746 self.show_git_blame_inline = true
14747 }
14748 }
14749
14750 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14751 self.blame.as_ref()
14752 }
14753
14754 pub fn show_git_blame_gutter(&self) -> bool {
14755 self.show_git_blame_gutter
14756 }
14757
14758 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14759 self.show_git_blame_gutter && self.has_blame_entries(cx)
14760 }
14761
14762 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14763 self.show_git_blame_inline
14764 && (self.focus_handle.is_focused(window)
14765 || self
14766 .git_blame_inline_tooltip
14767 .as_ref()
14768 .and_then(|t| t.upgrade())
14769 .is_some())
14770 && !self.newest_selection_head_on_empty_line(cx)
14771 && self.has_blame_entries(cx)
14772 }
14773
14774 fn has_blame_entries(&self, cx: &App) -> bool {
14775 self.blame()
14776 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14777 }
14778
14779 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14780 let cursor_anchor = self.selections.newest_anchor().head();
14781
14782 let snapshot = self.buffer.read(cx).snapshot(cx);
14783 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14784
14785 snapshot.line_len(buffer_row) == 0
14786 }
14787
14788 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14789 let buffer_and_selection = maybe!({
14790 let selection = self.selections.newest::<Point>(cx);
14791 let selection_range = selection.range();
14792
14793 let multi_buffer = self.buffer().read(cx);
14794 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14795 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14796
14797 let (buffer, range, _) = if selection.reversed {
14798 buffer_ranges.first()
14799 } else {
14800 buffer_ranges.last()
14801 }?;
14802
14803 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14804 ..text::ToPoint::to_point(&range.end, &buffer).row;
14805 Some((
14806 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14807 selection,
14808 ))
14809 });
14810
14811 let Some((buffer, selection)) = buffer_and_selection else {
14812 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14813 };
14814
14815 let Some(project) = self.project.as_ref() else {
14816 return Task::ready(Err(anyhow!("editor does not have project")));
14817 };
14818
14819 project.update(cx, |project, cx| {
14820 project.get_permalink_to_line(&buffer, selection, cx)
14821 })
14822 }
14823
14824 pub fn copy_permalink_to_line(
14825 &mut self,
14826 _: &CopyPermalinkToLine,
14827 window: &mut Window,
14828 cx: &mut Context<Self>,
14829 ) {
14830 let permalink_task = self.get_permalink_to_line(cx);
14831 let workspace = self.workspace();
14832
14833 cx.spawn_in(window, |_, mut cx| async move {
14834 match permalink_task.await {
14835 Ok(permalink) => {
14836 cx.update(|_, cx| {
14837 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14838 })
14839 .ok();
14840 }
14841 Err(err) => {
14842 let message = format!("Failed to copy permalink: {err}");
14843
14844 Err::<(), anyhow::Error>(err).log_err();
14845
14846 if let Some(workspace) = workspace {
14847 workspace
14848 .update_in(&mut cx, |workspace, _, cx| {
14849 struct CopyPermalinkToLine;
14850
14851 workspace.show_toast(
14852 Toast::new(
14853 NotificationId::unique::<CopyPermalinkToLine>(),
14854 message,
14855 ),
14856 cx,
14857 )
14858 })
14859 .ok();
14860 }
14861 }
14862 }
14863 })
14864 .detach();
14865 }
14866
14867 pub fn copy_file_location(
14868 &mut self,
14869 _: &CopyFileLocation,
14870 _: &mut Window,
14871 cx: &mut Context<Self>,
14872 ) {
14873 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14874 if let Some(file) = self.target_file(cx) {
14875 if let Some(path) = file.path().to_str() {
14876 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14877 }
14878 }
14879 }
14880
14881 pub fn open_permalink_to_line(
14882 &mut self,
14883 _: &OpenPermalinkToLine,
14884 window: &mut Window,
14885 cx: &mut Context<Self>,
14886 ) {
14887 let permalink_task = self.get_permalink_to_line(cx);
14888 let workspace = self.workspace();
14889
14890 cx.spawn_in(window, |_, mut cx| async move {
14891 match permalink_task.await {
14892 Ok(permalink) => {
14893 cx.update(|_, cx| {
14894 cx.open_url(permalink.as_ref());
14895 })
14896 .ok();
14897 }
14898 Err(err) => {
14899 let message = format!("Failed to open permalink: {err}");
14900
14901 Err::<(), anyhow::Error>(err).log_err();
14902
14903 if let Some(workspace) = workspace {
14904 workspace
14905 .update(&mut cx, |workspace, cx| {
14906 struct OpenPermalinkToLine;
14907
14908 workspace.show_toast(
14909 Toast::new(
14910 NotificationId::unique::<OpenPermalinkToLine>(),
14911 message,
14912 ),
14913 cx,
14914 )
14915 })
14916 .ok();
14917 }
14918 }
14919 }
14920 })
14921 .detach();
14922 }
14923
14924 pub fn insert_uuid_v4(
14925 &mut self,
14926 _: &InsertUuidV4,
14927 window: &mut Window,
14928 cx: &mut Context<Self>,
14929 ) {
14930 self.insert_uuid(UuidVersion::V4, window, cx);
14931 }
14932
14933 pub fn insert_uuid_v7(
14934 &mut self,
14935 _: &InsertUuidV7,
14936 window: &mut Window,
14937 cx: &mut Context<Self>,
14938 ) {
14939 self.insert_uuid(UuidVersion::V7, window, cx);
14940 }
14941
14942 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14943 self.transact(window, cx, |this, window, cx| {
14944 let edits = this
14945 .selections
14946 .all::<Point>(cx)
14947 .into_iter()
14948 .map(|selection| {
14949 let uuid = match version {
14950 UuidVersion::V4 => uuid::Uuid::new_v4(),
14951 UuidVersion::V7 => uuid::Uuid::now_v7(),
14952 };
14953
14954 (selection.range(), uuid.to_string())
14955 });
14956 this.edit(edits, cx);
14957 this.refresh_inline_completion(true, false, window, cx);
14958 });
14959 }
14960
14961 pub fn open_selections_in_multibuffer(
14962 &mut self,
14963 _: &OpenSelectionsInMultibuffer,
14964 window: &mut Window,
14965 cx: &mut Context<Self>,
14966 ) {
14967 let multibuffer = self.buffer.read(cx);
14968
14969 let Some(buffer) = multibuffer.as_singleton() else {
14970 return;
14971 };
14972
14973 let Some(workspace) = self.workspace() else {
14974 return;
14975 };
14976
14977 let locations = self
14978 .selections
14979 .disjoint_anchors()
14980 .iter()
14981 .map(|range| Location {
14982 buffer: buffer.clone(),
14983 range: range.start.text_anchor..range.end.text_anchor,
14984 })
14985 .collect::<Vec<_>>();
14986
14987 let title = multibuffer.title(cx).to_string();
14988
14989 cx.spawn_in(window, |_, mut cx| async move {
14990 workspace.update_in(&mut cx, |workspace, window, cx| {
14991 Self::open_locations_in_multibuffer(
14992 workspace,
14993 locations,
14994 format!("Selections for '{title}'"),
14995 false,
14996 MultibufferSelectionMode::All,
14997 window,
14998 cx,
14999 );
15000 })
15001 })
15002 .detach();
15003 }
15004
15005 /// Adds a row highlight for the given range. If a row has multiple highlights, the
15006 /// last highlight added will be used.
15007 ///
15008 /// If the range ends at the beginning of a line, then that line will not be highlighted.
15009 pub fn highlight_rows<T: 'static>(
15010 &mut self,
15011 range: Range<Anchor>,
15012 color: Hsla,
15013 should_autoscroll: bool,
15014 cx: &mut Context<Self>,
15015 ) {
15016 let snapshot = self.buffer().read(cx).snapshot(cx);
15017 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15018 let ix = row_highlights.binary_search_by(|highlight| {
15019 Ordering::Equal
15020 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15021 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15022 });
15023
15024 if let Err(mut ix) = ix {
15025 let index = post_inc(&mut self.highlight_order);
15026
15027 // If this range intersects with the preceding highlight, then merge it with
15028 // the preceding highlight. Otherwise insert a new highlight.
15029 let mut merged = false;
15030 if ix > 0 {
15031 let prev_highlight = &mut row_highlights[ix - 1];
15032 if prev_highlight
15033 .range
15034 .end
15035 .cmp(&range.start, &snapshot)
15036 .is_ge()
15037 {
15038 ix -= 1;
15039 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15040 prev_highlight.range.end = range.end;
15041 }
15042 merged = true;
15043 prev_highlight.index = index;
15044 prev_highlight.color = color;
15045 prev_highlight.should_autoscroll = should_autoscroll;
15046 }
15047 }
15048
15049 if !merged {
15050 row_highlights.insert(
15051 ix,
15052 RowHighlight {
15053 range: range.clone(),
15054 index,
15055 color,
15056 should_autoscroll,
15057 },
15058 );
15059 }
15060
15061 // If any of the following highlights intersect with this one, merge them.
15062 while let Some(next_highlight) = row_highlights.get(ix + 1) {
15063 let highlight = &row_highlights[ix];
15064 if next_highlight
15065 .range
15066 .start
15067 .cmp(&highlight.range.end, &snapshot)
15068 .is_le()
15069 {
15070 if next_highlight
15071 .range
15072 .end
15073 .cmp(&highlight.range.end, &snapshot)
15074 .is_gt()
15075 {
15076 row_highlights[ix].range.end = next_highlight.range.end;
15077 }
15078 row_highlights.remove(ix + 1);
15079 } else {
15080 break;
15081 }
15082 }
15083 }
15084 }
15085
15086 /// Remove any highlighted row ranges of the given type that intersect the
15087 /// given ranges.
15088 pub fn remove_highlighted_rows<T: 'static>(
15089 &mut self,
15090 ranges_to_remove: Vec<Range<Anchor>>,
15091 cx: &mut Context<Self>,
15092 ) {
15093 let snapshot = self.buffer().read(cx).snapshot(cx);
15094 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15095 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15096 row_highlights.retain(|highlight| {
15097 while let Some(range_to_remove) = ranges_to_remove.peek() {
15098 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15099 Ordering::Less | Ordering::Equal => {
15100 ranges_to_remove.next();
15101 }
15102 Ordering::Greater => {
15103 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15104 Ordering::Less | Ordering::Equal => {
15105 return false;
15106 }
15107 Ordering::Greater => break,
15108 }
15109 }
15110 }
15111 }
15112
15113 true
15114 })
15115 }
15116
15117 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15118 pub fn clear_row_highlights<T: 'static>(&mut self) {
15119 self.highlighted_rows.remove(&TypeId::of::<T>());
15120 }
15121
15122 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15123 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15124 self.highlighted_rows
15125 .get(&TypeId::of::<T>())
15126 .map_or(&[] as &[_], |vec| vec.as_slice())
15127 .iter()
15128 .map(|highlight| (highlight.range.clone(), highlight.color))
15129 }
15130
15131 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15132 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15133 /// Allows to ignore certain kinds of highlights.
15134 pub fn highlighted_display_rows(
15135 &self,
15136 window: &mut Window,
15137 cx: &mut App,
15138 ) -> BTreeMap<DisplayRow, LineHighlight> {
15139 let snapshot = self.snapshot(window, cx);
15140 let mut used_highlight_orders = HashMap::default();
15141 self.highlighted_rows
15142 .iter()
15143 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15144 .fold(
15145 BTreeMap::<DisplayRow, LineHighlight>::new(),
15146 |mut unique_rows, highlight| {
15147 let start = highlight.range.start.to_display_point(&snapshot);
15148 let end = highlight.range.end.to_display_point(&snapshot);
15149 let start_row = start.row().0;
15150 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15151 && end.column() == 0
15152 {
15153 end.row().0.saturating_sub(1)
15154 } else {
15155 end.row().0
15156 };
15157 for row in start_row..=end_row {
15158 let used_index =
15159 used_highlight_orders.entry(row).or_insert(highlight.index);
15160 if highlight.index >= *used_index {
15161 *used_index = highlight.index;
15162 unique_rows.insert(DisplayRow(row), highlight.color.into());
15163 }
15164 }
15165 unique_rows
15166 },
15167 )
15168 }
15169
15170 pub fn highlighted_display_row_for_autoscroll(
15171 &self,
15172 snapshot: &DisplaySnapshot,
15173 ) -> Option<DisplayRow> {
15174 self.highlighted_rows
15175 .values()
15176 .flat_map(|highlighted_rows| highlighted_rows.iter())
15177 .filter_map(|highlight| {
15178 if highlight.should_autoscroll {
15179 Some(highlight.range.start.to_display_point(snapshot).row())
15180 } else {
15181 None
15182 }
15183 })
15184 .min()
15185 }
15186
15187 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15188 self.highlight_background::<SearchWithinRange>(
15189 ranges,
15190 |colors| colors.editor_document_highlight_read_background,
15191 cx,
15192 )
15193 }
15194
15195 pub fn set_breadcrumb_header(&mut self, new_header: String) {
15196 self.breadcrumb_header = Some(new_header);
15197 }
15198
15199 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15200 self.clear_background_highlights::<SearchWithinRange>(cx);
15201 }
15202
15203 pub fn highlight_background<T: 'static>(
15204 &mut self,
15205 ranges: &[Range<Anchor>],
15206 color_fetcher: fn(&ThemeColors) -> Hsla,
15207 cx: &mut Context<Self>,
15208 ) {
15209 self.background_highlights
15210 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15211 self.scrollbar_marker_state.dirty = true;
15212 cx.notify();
15213 }
15214
15215 pub fn clear_background_highlights<T: 'static>(
15216 &mut self,
15217 cx: &mut Context<Self>,
15218 ) -> Option<BackgroundHighlight> {
15219 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15220 if !text_highlights.1.is_empty() {
15221 self.scrollbar_marker_state.dirty = true;
15222 cx.notify();
15223 }
15224 Some(text_highlights)
15225 }
15226
15227 pub fn highlight_gutter<T: 'static>(
15228 &mut self,
15229 ranges: &[Range<Anchor>],
15230 color_fetcher: fn(&App) -> Hsla,
15231 cx: &mut Context<Self>,
15232 ) {
15233 self.gutter_highlights
15234 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15235 cx.notify();
15236 }
15237
15238 pub fn clear_gutter_highlights<T: 'static>(
15239 &mut self,
15240 cx: &mut Context<Self>,
15241 ) -> Option<GutterHighlight> {
15242 cx.notify();
15243 self.gutter_highlights.remove(&TypeId::of::<T>())
15244 }
15245
15246 #[cfg(feature = "test-support")]
15247 pub fn all_text_background_highlights(
15248 &self,
15249 window: &mut Window,
15250 cx: &mut Context<Self>,
15251 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15252 let snapshot = self.snapshot(window, cx);
15253 let buffer = &snapshot.buffer_snapshot;
15254 let start = buffer.anchor_before(0);
15255 let end = buffer.anchor_after(buffer.len());
15256 let theme = cx.theme().colors();
15257 self.background_highlights_in_range(start..end, &snapshot, theme)
15258 }
15259
15260 #[cfg(feature = "test-support")]
15261 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15262 let snapshot = self.buffer().read(cx).snapshot(cx);
15263
15264 let highlights = self
15265 .background_highlights
15266 .get(&TypeId::of::<items::BufferSearchHighlights>());
15267
15268 if let Some((_color, ranges)) = highlights {
15269 ranges
15270 .iter()
15271 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15272 .collect_vec()
15273 } else {
15274 vec![]
15275 }
15276 }
15277
15278 fn document_highlights_for_position<'a>(
15279 &'a self,
15280 position: Anchor,
15281 buffer: &'a MultiBufferSnapshot,
15282 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15283 let read_highlights = self
15284 .background_highlights
15285 .get(&TypeId::of::<DocumentHighlightRead>())
15286 .map(|h| &h.1);
15287 let write_highlights = self
15288 .background_highlights
15289 .get(&TypeId::of::<DocumentHighlightWrite>())
15290 .map(|h| &h.1);
15291 let left_position = position.bias_left(buffer);
15292 let right_position = position.bias_right(buffer);
15293 read_highlights
15294 .into_iter()
15295 .chain(write_highlights)
15296 .flat_map(move |ranges| {
15297 let start_ix = match ranges.binary_search_by(|probe| {
15298 let cmp = probe.end.cmp(&left_position, buffer);
15299 if cmp.is_ge() {
15300 Ordering::Greater
15301 } else {
15302 Ordering::Less
15303 }
15304 }) {
15305 Ok(i) | Err(i) => i,
15306 };
15307
15308 ranges[start_ix..]
15309 .iter()
15310 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15311 })
15312 }
15313
15314 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15315 self.background_highlights
15316 .get(&TypeId::of::<T>())
15317 .map_or(false, |(_, highlights)| !highlights.is_empty())
15318 }
15319
15320 pub fn background_highlights_in_range(
15321 &self,
15322 search_range: Range<Anchor>,
15323 display_snapshot: &DisplaySnapshot,
15324 theme: &ThemeColors,
15325 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15326 let mut results = Vec::new();
15327 for (color_fetcher, ranges) in self.background_highlights.values() {
15328 let color = color_fetcher(theme);
15329 let start_ix = match ranges.binary_search_by(|probe| {
15330 let cmp = probe
15331 .end
15332 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15333 if cmp.is_gt() {
15334 Ordering::Greater
15335 } else {
15336 Ordering::Less
15337 }
15338 }) {
15339 Ok(i) | Err(i) => i,
15340 };
15341 for range in &ranges[start_ix..] {
15342 if range
15343 .start
15344 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15345 .is_ge()
15346 {
15347 break;
15348 }
15349
15350 let start = range.start.to_display_point(display_snapshot);
15351 let end = range.end.to_display_point(display_snapshot);
15352 results.push((start..end, color))
15353 }
15354 }
15355 results
15356 }
15357
15358 pub fn background_highlight_row_ranges<T: 'static>(
15359 &self,
15360 search_range: Range<Anchor>,
15361 display_snapshot: &DisplaySnapshot,
15362 count: usize,
15363 ) -> Vec<RangeInclusive<DisplayPoint>> {
15364 let mut results = Vec::new();
15365 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15366 return vec![];
15367 };
15368
15369 let start_ix = match ranges.binary_search_by(|probe| {
15370 let cmp = probe
15371 .end
15372 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15373 if cmp.is_gt() {
15374 Ordering::Greater
15375 } else {
15376 Ordering::Less
15377 }
15378 }) {
15379 Ok(i) | Err(i) => i,
15380 };
15381 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15382 if let (Some(start_display), Some(end_display)) = (start, end) {
15383 results.push(
15384 start_display.to_display_point(display_snapshot)
15385 ..=end_display.to_display_point(display_snapshot),
15386 );
15387 }
15388 };
15389 let mut start_row: Option<Point> = None;
15390 let mut end_row: Option<Point> = None;
15391 if ranges.len() > count {
15392 return Vec::new();
15393 }
15394 for range in &ranges[start_ix..] {
15395 if range
15396 .start
15397 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15398 .is_ge()
15399 {
15400 break;
15401 }
15402 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15403 if let Some(current_row) = &end_row {
15404 if end.row == current_row.row {
15405 continue;
15406 }
15407 }
15408 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15409 if start_row.is_none() {
15410 assert_eq!(end_row, None);
15411 start_row = Some(start);
15412 end_row = Some(end);
15413 continue;
15414 }
15415 if let Some(current_end) = end_row.as_mut() {
15416 if start.row > current_end.row + 1 {
15417 push_region(start_row, end_row);
15418 start_row = Some(start);
15419 end_row = Some(end);
15420 } else {
15421 // Merge two hunks.
15422 *current_end = end;
15423 }
15424 } else {
15425 unreachable!();
15426 }
15427 }
15428 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15429 push_region(start_row, end_row);
15430 results
15431 }
15432
15433 pub fn gutter_highlights_in_range(
15434 &self,
15435 search_range: Range<Anchor>,
15436 display_snapshot: &DisplaySnapshot,
15437 cx: &App,
15438 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15439 let mut results = Vec::new();
15440 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15441 let color = color_fetcher(cx);
15442 let start_ix = match ranges.binary_search_by(|probe| {
15443 let cmp = probe
15444 .end
15445 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15446 if cmp.is_gt() {
15447 Ordering::Greater
15448 } else {
15449 Ordering::Less
15450 }
15451 }) {
15452 Ok(i) | Err(i) => i,
15453 };
15454 for range in &ranges[start_ix..] {
15455 if range
15456 .start
15457 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15458 .is_ge()
15459 {
15460 break;
15461 }
15462
15463 let start = range.start.to_display_point(display_snapshot);
15464 let end = range.end.to_display_point(display_snapshot);
15465 results.push((start..end, color))
15466 }
15467 }
15468 results
15469 }
15470
15471 /// Get the text ranges corresponding to the redaction query
15472 pub fn redacted_ranges(
15473 &self,
15474 search_range: Range<Anchor>,
15475 display_snapshot: &DisplaySnapshot,
15476 cx: &App,
15477 ) -> Vec<Range<DisplayPoint>> {
15478 display_snapshot
15479 .buffer_snapshot
15480 .redacted_ranges(search_range, |file| {
15481 if let Some(file) = file {
15482 file.is_private()
15483 && EditorSettings::get(
15484 Some(SettingsLocation {
15485 worktree_id: file.worktree_id(cx),
15486 path: file.path().as_ref(),
15487 }),
15488 cx,
15489 )
15490 .redact_private_values
15491 } else {
15492 false
15493 }
15494 })
15495 .map(|range| {
15496 range.start.to_display_point(display_snapshot)
15497 ..range.end.to_display_point(display_snapshot)
15498 })
15499 .collect()
15500 }
15501
15502 pub fn highlight_text<T: 'static>(
15503 &mut self,
15504 ranges: Vec<Range<Anchor>>,
15505 style: HighlightStyle,
15506 cx: &mut Context<Self>,
15507 ) {
15508 self.display_map.update(cx, |map, _| {
15509 map.highlight_text(TypeId::of::<T>(), ranges, style)
15510 });
15511 cx.notify();
15512 }
15513
15514 pub(crate) fn highlight_inlays<T: 'static>(
15515 &mut self,
15516 highlights: Vec<InlayHighlight>,
15517 style: HighlightStyle,
15518 cx: &mut Context<Self>,
15519 ) {
15520 self.display_map.update(cx, |map, _| {
15521 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15522 });
15523 cx.notify();
15524 }
15525
15526 pub fn text_highlights<'a, T: 'static>(
15527 &'a self,
15528 cx: &'a App,
15529 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15530 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15531 }
15532
15533 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15534 let cleared = self
15535 .display_map
15536 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15537 if cleared {
15538 cx.notify();
15539 }
15540 }
15541
15542 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15543 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15544 && self.focus_handle.is_focused(window)
15545 }
15546
15547 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15548 self.show_cursor_when_unfocused = is_enabled;
15549 cx.notify();
15550 }
15551
15552 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15553 cx.notify();
15554 }
15555
15556 fn on_buffer_event(
15557 &mut self,
15558 multibuffer: &Entity<MultiBuffer>,
15559 event: &multi_buffer::Event,
15560 window: &mut Window,
15561 cx: &mut Context<Self>,
15562 ) {
15563 match event {
15564 multi_buffer::Event::Edited {
15565 singleton_buffer_edited,
15566 edited_buffer: buffer_edited,
15567 } => {
15568 self.scrollbar_marker_state.dirty = true;
15569 self.active_indent_guides_state.dirty = true;
15570 self.refresh_active_diagnostics(cx);
15571 self.refresh_code_actions(window, cx);
15572 if self.has_active_inline_completion() {
15573 self.update_visible_inline_completion(window, cx);
15574 }
15575 if let Some(buffer) = buffer_edited {
15576 let buffer_id = buffer.read(cx).remote_id();
15577 if !self.registered_buffers.contains_key(&buffer_id) {
15578 if let Some(project) = self.project.as_ref() {
15579 project.update(cx, |project, cx| {
15580 self.registered_buffers.insert(
15581 buffer_id,
15582 project.register_buffer_with_language_servers(&buffer, cx),
15583 );
15584 })
15585 }
15586 }
15587 }
15588 cx.emit(EditorEvent::BufferEdited);
15589 cx.emit(SearchEvent::MatchesInvalidated);
15590 if *singleton_buffer_edited {
15591 if let Some(project) = &self.project {
15592 #[allow(clippy::mutable_key_type)]
15593 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15594 multibuffer
15595 .all_buffers()
15596 .into_iter()
15597 .filter_map(|buffer| {
15598 buffer.update(cx, |buffer, cx| {
15599 let language = buffer.language()?;
15600 let should_discard = project.update(cx, |project, cx| {
15601 project.is_local()
15602 && !project.has_language_servers_for(buffer, cx)
15603 });
15604 should_discard.not().then_some(language.clone())
15605 })
15606 })
15607 .collect::<HashSet<_>>()
15608 });
15609 if !languages_affected.is_empty() {
15610 self.refresh_inlay_hints(
15611 InlayHintRefreshReason::BufferEdited(languages_affected),
15612 cx,
15613 );
15614 }
15615 }
15616 }
15617
15618 let Some(project) = &self.project else { return };
15619 let (telemetry, is_via_ssh) = {
15620 let project = project.read(cx);
15621 let telemetry = project.client().telemetry().clone();
15622 let is_via_ssh = project.is_via_ssh();
15623 (telemetry, is_via_ssh)
15624 };
15625 refresh_linked_ranges(self, window, cx);
15626 telemetry.log_edit_event("editor", is_via_ssh);
15627 }
15628 multi_buffer::Event::ExcerptsAdded {
15629 buffer,
15630 predecessor,
15631 excerpts,
15632 } => {
15633 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15634 let buffer_id = buffer.read(cx).remote_id();
15635 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15636 if let Some(project) = &self.project {
15637 get_uncommitted_diff_for_buffer(
15638 project,
15639 [buffer.clone()],
15640 self.buffer.clone(),
15641 cx,
15642 )
15643 .detach();
15644 }
15645 }
15646 cx.emit(EditorEvent::ExcerptsAdded {
15647 buffer: buffer.clone(),
15648 predecessor: *predecessor,
15649 excerpts: excerpts.clone(),
15650 });
15651 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15652 }
15653 multi_buffer::Event::ExcerptsRemoved { ids } => {
15654 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15655 let buffer = self.buffer.read(cx);
15656 self.registered_buffers
15657 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15658 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15659 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15660 }
15661 multi_buffer::Event::ExcerptsEdited {
15662 excerpt_ids,
15663 buffer_ids,
15664 } => {
15665 self.display_map.update(cx, |map, cx| {
15666 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15667 });
15668 cx.emit(EditorEvent::ExcerptsEdited {
15669 ids: excerpt_ids.clone(),
15670 })
15671 }
15672 multi_buffer::Event::ExcerptsExpanded { ids } => {
15673 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15674 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15675 }
15676 multi_buffer::Event::Reparsed(buffer_id) => {
15677 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15678 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15679
15680 cx.emit(EditorEvent::Reparsed(*buffer_id));
15681 }
15682 multi_buffer::Event::DiffHunksToggled => {
15683 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15684 }
15685 multi_buffer::Event::LanguageChanged(buffer_id) => {
15686 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15687 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15688 cx.emit(EditorEvent::Reparsed(*buffer_id));
15689 cx.notify();
15690 }
15691 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15692 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15693 multi_buffer::Event::FileHandleChanged
15694 | multi_buffer::Event::Reloaded
15695 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15696 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15697 multi_buffer::Event::DiagnosticsUpdated => {
15698 self.refresh_active_diagnostics(cx);
15699 self.refresh_inline_diagnostics(true, window, cx);
15700 self.scrollbar_marker_state.dirty = true;
15701 cx.notify();
15702 }
15703 _ => {}
15704 };
15705 }
15706
15707 fn on_display_map_changed(
15708 &mut self,
15709 _: Entity<DisplayMap>,
15710 _: &mut Window,
15711 cx: &mut Context<Self>,
15712 ) {
15713 cx.notify();
15714 }
15715
15716 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15717 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15718 self.update_edit_prediction_settings(cx);
15719 self.refresh_inline_completion(true, false, window, cx);
15720 self.refresh_inlay_hints(
15721 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15722 self.selections.newest_anchor().head(),
15723 &self.buffer.read(cx).snapshot(cx),
15724 cx,
15725 )),
15726 cx,
15727 );
15728
15729 let old_cursor_shape = self.cursor_shape;
15730
15731 {
15732 let editor_settings = EditorSettings::get_global(cx);
15733 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15734 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15735 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15736 }
15737
15738 if old_cursor_shape != self.cursor_shape {
15739 cx.emit(EditorEvent::CursorShapeChanged);
15740 }
15741
15742 let project_settings = ProjectSettings::get_global(cx);
15743 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15744
15745 if self.mode == EditorMode::Full {
15746 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15747 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15748 if self.show_inline_diagnostics != show_inline_diagnostics {
15749 self.show_inline_diagnostics = show_inline_diagnostics;
15750 self.refresh_inline_diagnostics(false, window, cx);
15751 }
15752
15753 if self.git_blame_inline_enabled != inline_blame_enabled {
15754 self.toggle_git_blame_inline_internal(false, window, cx);
15755 }
15756 }
15757
15758 cx.notify();
15759 }
15760
15761 pub fn set_searchable(&mut self, searchable: bool) {
15762 self.searchable = searchable;
15763 }
15764
15765 pub fn searchable(&self) -> bool {
15766 self.searchable
15767 }
15768
15769 fn open_proposed_changes_editor(
15770 &mut self,
15771 _: &OpenProposedChangesEditor,
15772 window: &mut Window,
15773 cx: &mut Context<Self>,
15774 ) {
15775 let Some(workspace) = self.workspace() else {
15776 cx.propagate();
15777 return;
15778 };
15779
15780 let selections = self.selections.all::<usize>(cx);
15781 let multi_buffer = self.buffer.read(cx);
15782 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15783 let mut new_selections_by_buffer = HashMap::default();
15784 for selection in selections {
15785 for (buffer, range, _) in
15786 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15787 {
15788 let mut range = range.to_point(buffer);
15789 range.start.column = 0;
15790 range.end.column = buffer.line_len(range.end.row);
15791 new_selections_by_buffer
15792 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15793 .or_insert(Vec::new())
15794 .push(range)
15795 }
15796 }
15797
15798 let proposed_changes_buffers = new_selections_by_buffer
15799 .into_iter()
15800 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15801 .collect::<Vec<_>>();
15802 let proposed_changes_editor = cx.new(|cx| {
15803 ProposedChangesEditor::new(
15804 "Proposed changes",
15805 proposed_changes_buffers,
15806 self.project.clone(),
15807 window,
15808 cx,
15809 )
15810 });
15811
15812 window.defer(cx, move |window, cx| {
15813 workspace.update(cx, |workspace, cx| {
15814 workspace.active_pane().update(cx, |pane, cx| {
15815 pane.add_item(
15816 Box::new(proposed_changes_editor),
15817 true,
15818 true,
15819 None,
15820 window,
15821 cx,
15822 );
15823 });
15824 });
15825 });
15826 }
15827
15828 pub fn open_excerpts_in_split(
15829 &mut self,
15830 _: &OpenExcerptsSplit,
15831 window: &mut Window,
15832 cx: &mut Context<Self>,
15833 ) {
15834 self.open_excerpts_common(None, true, window, cx)
15835 }
15836
15837 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15838 self.open_excerpts_common(None, false, window, cx)
15839 }
15840
15841 fn open_excerpts_common(
15842 &mut self,
15843 jump_data: Option<JumpData>,
15844 split: bool,
15845 window: &mut Window,
15846 cx: &mut Context<Self>,
15847 ) {
15848 let Some(workspace) = self.workspace() else {
15849 cx.propagate();
15850 return;
15851 };
15852
15853 if self.buffer.read(cx).is_singleton() {
15854 cx.propagate();
15855 return;
15856 }
15857
15858 let mut new_selections_by_buffer = HashMap::default();
15859 match &jump_data {
15860 Some(JumpData::MultiBufferPoint {
15861 excerpt_id,
15862 position,
15863 anchor,
15864 line_offset_from_top,
15865 }) => {
15866 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15867 if let Some(buffer) = multi_buffer_snapshot
15868 .buffer_id_for_excerpt(*excerpt_id)
15869 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15870 {
15871 let buffer_snapshot = buffer.read(cx).snapshot();
15872 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15873 language::ToPoint::to_point(anchor, &buffer_snapshot)
15874 } else {
15875 buffer_snapshot.clip_point(*position, Bias::Left)
15876 };
15877 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15878 new_selections_by_buffer.insert(
15879 buffer,
15880 (
15881 vec![jump_to_offset..jump_to_offset],
15882 Some(*line_offset_from_top),
15883 ),
15884 );
15885 }
15886 }
15887 Some(JumpData::MultiBufferRow {
15888 row,
15889 line_offset_from_top,
15890 }) => {
15891 let point = MultiBufferPoint::new(row.0, 0);
15892 if let Some((buffer, buffer_point, _)) =
15893 self.buffer.read(cx).point_to_buffer_point(point, cx)
15894 {
15895 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15896 new_selections_by_buffer
15897 .entry(buffer)
15898 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15899 .0
15900 .push(buffer_offset..buffer_offset)
15901 }
15902 }
15903 None => {
15904 let selections = self.selections.all::<usize>(cx);
15905 let multi_buffer = self.buffer.read(cx);
15906 for selection in selections {
15907 for (snapshot, range, _, anchor) in multi_buffer
15908 .snapshot(cx)
15909 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15910 {
15911 if let Some(anchor) = anchor {
15912 // selection is in a deleted hunk
15913 let Some(buffer_id) = anchor.buffer_id else {
15914 continue;
15915 };
15916 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15917 continue;
15918 };
15919 let offset = text::ToOffset::to_offset(
15920 &anchor.text_anchor,
15921 &buffer_handle.read(cx).snapshot(),
15922 );
15923 let range = offset..offset;
15924 new_selections_by_buffer
15925 .entry(buffer_handle)
15926 .or_insert((Vec::new(), None))
15927 .0
15928 .push(range)
15929 } else {
15930 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15931 else {
15932 continue;
15933 };
15934 new_selections_by_buffer
15935 .entry(buffer_handle)
15936 .or_insert((Vec::new(), None))
15937 .0
15938 .push(range)
15939 }
15940 }
15941 }
15942 }
15943 }
15944
15945 if new_selections_by_buffer.is_empty() {
15946 return;
15947 }
15948
15949 // We defer the pane interaction because we ourselves are a workspace item
15950 // and activating a new item causes the pane to call a method on us reentrantly,
15951 // which panics if we're on the stack.
15952 window.defer(cx, move |window, cx| {
15953 workspace.update(cx, |workspace, cx| {
15954 let pane = if split {
15955 workspace.adjacent_pane(window, cx)
15956 } else {
15957 workspace.active_pane().clone()
15958 };
15959
15960 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15961 let editor = buffer
15962 .read(cx)
15963 .file()
15964 .is_none()
15965 .then(|| {
15966 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15967 // so `workspace.open_project_item` will never find them, always opening a new editor.
15968 // Instead, we try to activate the existing editor in the pane first.
15969 let (editor, pane_item_index) =
15970 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15971 let editor = item.downcast::<Editor>()?;
15972 let singleton_buffer =
15973 editor.read(cx).buffer().read(cx).as_singleton()?;
15974 if singleton_buffer == buffer {
15975 Some((editor, i))
15976 } else {
15977 None
15978 }
15979 })?;
15980 pane.update(cx, |pane, cx| {
15981 pane.activate_item(pane_item_index, true, true, window, cx)
15982 });
15983 Some(editor)
15984 })
15985 .flatten()
15986 .unwrap_or_else(|| {
15987 workspace.open_project_item::<Self>(
15988 pane.clone(),
15989 buffer,
15990 true,
15991 true,
15992 window,
15993 cx,
15994 )
15995 });
15996
15997 editor.update(cx, |editor, cx| {
15998 let autoscroll = match scroll_offset {
15999 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16000 None => Autoscroll::newest(),
16001 };
16002 let nav_history = editor.nav_history.take();
16003 editor.change_selections(Some(autoscroll), window, cx, |s| {
16004 s.select_ranges(ranges);
16005 });
16006 editor.nav_history = nav_history;
16007 });
16008 }
16009 })
16010 });
16011 }
16012
16013 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16014 let snapshot = self.buffer.read(cx).read(cx);
16015 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16016 Some(
16017 ranges
16018 .iter()
16019 .map(move |range| {
16020 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16021 })
16022 .collect(),
16023 )
16024 }
16025
16026 fn selection_replacement_ranges(
16027 &self,
16028 range: Range<OffsetUtf16>,
16029 cx: &mut App,
16030 ) -> Vec<Range<OffsetUtf16>> {
16031 let selections = self.selections.all::<OffsetUtf16>(cx);
16032 let newest_selection = selections
16033 .iter()
16034 .max_by_key(|selection| selection.id)
16035 .unwrap();
16036 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16037 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16038 let snapshot = self.buffer.read(cx).read(cx);
16039 selections
16040 .into_iter()
16041 .map(|mut selection| {
16042 selection.start.0 =
16043 (selection.start.0 as isize).saturating_add(start_delta) as usize;
16044 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16045 snapshot.clip_offset_utf16(selection.start, Bias::Left)
16046 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16047 })
16048 .collect()
16049 }
16050
16051 fn report_editor_event(
16052 &self,
16053 event_type: &'static str,
16054 file_extension: Option<String>,
16055 cx: &App,
16056 ) {
16057 if cfg!(any(test, feature = "test-support")) {
16058 return;
16059 }
16060
16061 let Some(project) = &self.project else { return };
16062
16063 // If None, we are in a file without an extension
16064 let file = self
16065 .buffer
16066 .read(cx)
16067 .as_singleton()
16068 .and_then(|b| b.read(cx).file());
16069 let file_extension = file_extension.or(file
16070 .as_ref()
16071 .and_then(|file| Path::new(file.file_name(cx)).extension())
16072 .and_then(|e| e.to_str())
16073 .map(|a| a.to_string()));
16074
16075 let vim_mode = cx
16076 .global::<SettingsStore>()
16077 .raw_user_settings()
16078 .get("vim_mode")
16079 == Some(&serde_json::Value::Bool(true));
16080
16081 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16082 let copilot_enabled = edit_predictions_provider
16083 == language::language_settings::EditPredictionProvider::Copilot;
16084 let copilot_enabled_for_language = self
16085 .buffer
16086 .read(cx)
16087 .language_settings(cx)
16088 .show_edit_predictions;
16089
16090 let project = project.read(cx);
16091 telemetry::event!(
16092 event_type,
16093 file_extension,
16094 vim_mode,
16095 copilot_enabled,
16096 copilot_enabled_for_language,
16097 edit_predictions_provider,
16098 is_via_ssh = project.is_via_ssh(),
16099 );
16100 }
16101
16102 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16103 /// with each line being an array of {text, highlight} objects.
16104 fn copy_highlight_json(
16105 &mut self,
16106 _: &CopyHighlightJson,
16107 window: &mut Window,
16108 cx: &mut Context<Self>,
16109 ) {
16110 #[derive(Serialize)]
16111 struct Chunk<'a> {
16112 text: String,
16113 highlight: Option<&'a str>,
16114 }
16115
16116 let snapshot = self.buffer.read(cx).snapshot(cx);
16117 let range = self
16118 .selected_text_range(false, window, cx)
16119 .and_then(|selection| {
16120 if selection.range.is_empty() {
16121 None
16122 } else {
16123 Some(selection.range)
16124 }
16125 })
16126 .unwrap_or_else(|| 0..snapshot.len());
16127
16128 let chunks = snapshot.chunks(range, true);
16129 let mut lines = Vec::new();
16130 let mut line: VecDeque<Chunk> = VecDeque::new();
16131
16132 let Some(style) = self.style.as_ref() else {
16133 return;
16134 };
16135
16136 for chunk in chunks {
16137 let highlight = chunk
16138 .syntax_highlight_id
16139 .and_then(|id| id.name(&style.syntax));
16140 let mut chunk_lines = chunk.text.split('\n').peekable();
16141 while let Some(text) = chunk_lines.next() {
16142 let mut merged_with_last_token = false;
16143 if let Some(last_token) = line.back_mut() {
16144 if last_token.highlight == highlight {
16145 last_token.text.push_str(text);
16146 merged_with_last_token = true;
16147 }
16148 }
16149
16150 if !merged_with_last_token {
16151 line.push_back(Chunk {
16152 text: text.into(),
16153 highlight,
16154 });
16155 }
16156
16157 if chunk_lines.peek().is_some() {
16158 if line.len() > 1 && line.front().unwrap().text.is_empty() {
16159 line.pop_front();
16160 }
16161 if line.len() > 1 && line.back().unwrap().text.is_empty() {
16162 line.pop_back();
16163 }
16164
16165 lines.push(mem::take(&mut line));
16166 }
16167 }
16168 }
16169
16170 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16171 return;
16172 };
16173 cx.write_to_clipboard(ClipboardItem::new_string(lines));
16174 }
16175
16176 pub fn open_context_menu(
16177 &mut self,
16178 _: &OpenContextMenu,
16179 window: &mut Window,
16180 cx: &mut Context<Self>,
16181 ) {
16182 self.request_autoscroll(Autoscroll::newest(), cx);
16183 let position = self.selections.newest_display(cx).start;
16184 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16185 }
16186
16187 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16188 &self.inlay_hint_cache
16189 }
16190
16191 pub fn replay_insert_event(
16192 &mut self,
16193 text: &str,
16194 relative_utf16_range: Option<Range<isize>>,
16195 window: &mut Window,
16196 cx: &mut Context<Self>,
16197 ) {
16198 if !self.input_enabled {
16199 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16200 return;
16201 }
16202 if let Some(relative_utf16_range) = relative_utf16_range {
16203 let selections = self.selections.all::<OffsetUtf16>(cx);
16204 self.change_selections(None, window, cx, |s| {
16205 let new_ranges = selections.into_iter().map(|range| {
16206 let start = OffsetUtf16(
16207 range
16208 .head()
16209 .0
16210 .saturating_add_signed(relative_utf16_range.start),
16211 );
16212 let end = OffsetUtf16(
16213 range
16214 .head()
16215 .0
16216 .saturating_add_signed(relative_utf16_range.end),
16217 );
16218 start..end
16219 });
16220 s.select_ranges(new_ranges);
16221 });
16222 }
16223
16224 self.handle_input(text, window, cx);
16225 }
16226
16227 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16228 let Some(provider) = self.semantics_provider.as_ref() else {
16229 return false;
16230 };
16231
16232 let mut supports = false;
16233 self.buffer().update(cx, |this, cx| {
16234 this.for_each_buffer(|buffer| {
16235 supports |= provider.supports_inlay_hints(buffer, cx);
16236 });
16237 });
16238
16239 supports
16240 }
16241
16242 pub fn is_focused(&self, window: &Window) -> bool {
16243 self.focus_handle.is_focused(window)
16244 }
16245
16246 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16247 cx.emit(EditorEvent::Focused);
16248
16249 if let Some(descendant) = self
16250 .last_focused_descendant
16251 .take()
16252 .and_then(|descendant| descendant.upgrade())
16253 {
16254 window.focus(&descendant);
16255 } else {
16256 if let Some(blame) = self.blame.as_ref() {
16257 blame.update(cx, GitBlame::focus)
16258 }
16259
16260 self.blink_manager.update(cx, BlinkManager::enable);
16261 self.show_cursor_names(window, cx);
16262 self.buffer.update(cx, |buffer, cx| {
16263 buffer.finalize_last_transaction(cx);
16264 if self.leader_peer_id.is_none() {
16265 buffer.set_active_selections(
16266 &self.selections.disjoint_anchors(),
16267 self.selections.line_mode,
16268 self.cursor_shape,
16269 cx,
16270 );
16271 }
16272 });
16273 }
16274 }
16275
16276 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16277 cx.emit(EditorEvent::FocusedIn)
16278 }
16279
16280 fn handle_focus_out(
16281 &mut self,
16282 event: FocusOutEvent,
16283 _window: &mut Window,
16284 cx: &mut Context<Self>,
16285 ) {
16286 if event.blurred != self.focus_handle {
16287 self.last_focused_descendant = Some(event.blurred);
16288 }
16289 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16290 }
16291
16292 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16293 self.blink_manager.update(cx, BlinkManager::disable);
16294 self.buffer
16295 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16296
16297 if let Some(blame) = self.blame.as_ref() {
16298 blame.update(cx, GitBlame::blur)
16299 }
16300 if !self.hover_state.focused(window, cx) {
16301 hide_hover(self, cx);
16302 }
16303 if !self
16304 .context_menu
16305 .borrow()
16306 .as_ref()
16307 .is_some_and(|context_menu| context_menu.focused(window, cx))
16308 {
16309 self.hide_context_menu(window, cx);
16310 }
16311 self.discard_inline_completion(false, cx);
16312 cx.emit(EditorEvent::Blurred);
16313 cx.notify();
16314 }
16315
16316 pub fn register_action<A: Action>(
16317 &mut self,
16318 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16319 ) -> Subscription {
16320 let id = self.next_editor_action_id.post_inc();
16321 let listener = Arc::new(listener);
16322 self.editor_actions.borrow_mut().insert(
16323 id,
16324 Box::new(move |window, _| {
16325 let listener = listener.clone();
16326 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16327 let action = action.downcast_ref().unwrap();
16328 if phase == DispatchPhase::Bubble {
16329 listener(action, window, cx)
16330 }
16331 })
16332 }),
16333 );
16334
16335 let editor_actions = self.editor_actions.clone();
16336 Subscription::new(move || {
16337 editor_actions.borrow_mut().remove(&id);
16338 })
16339 }
16340
16341 pub fn file_header_size(&self) -> u32 {
16342 FILE_HEADER_HEIGHT
16343 }
16344
16345 pub fn restore(
16346 &mut self,
16347 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16348 window: &mut Window,
16349 cx: &mut Context<Self>,
16350 ) {
16351 let workspace = self.workspace();
16352 let project = self.project.as_ref();
16353 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16354 let mut tasks = Vec::new();
16355 for (buffer_id, changes) in revert_changes {
16356 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16357 buffer.update(cx, |buffer, cx| {
16358 buffer.edit(
16359 changes
16360 .into_iter()
16361 .map(|(range, text)| (range, text.to_string())),
16362 None,
16363 cx,
16364 );
16365 });
16366
16367 if let Some(project) =
16368 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16369 {
16370 project.update(cx, |project, cx| {
16371 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16372 })
16373 }
16374 }
16375 }
16376 tasks
16377 });
16378 cx.spawn_in(window, |_, mut cx| async move {
16379 for (buffer, task) in save_tasks {
16380 let result = task.await;
16381 if result.is_err() {
16382 let Some(path) = buffer
16383 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16384 .ok()
16385 else {
16386 continue;
16387 };
16388 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16389 let Some(task) = cx
16390 .update_window_entity(&workspace, |workspace, window, cx| {
16391 workspace
16392 .open_path_preview(path, None, false, false, false, window, cx)
16393 })
16394 .ok()
16395 else {
16396 continue;
16397 };
16398 task.await.log_err();
16399 }
16400 }
16401 }
16402 })
16403 .detach();
16404 self.change_selections(None, window, cx, |selections| selections.refresh());
16405 }
16406
16407 pub fn to_pixel_point(
16408 &self,
16409 source: multi_buffer::Anchor,
16410 editor_snapshot: &EditorSnapshot,
16411 window: &mut Window,
16412 ) -> Option<gpui::Point<Pixels>> {
16413 let source_point = source.to_display_point(editor_snapshot);
16414 self.display_to_pixel_point(source_point, editor_snapshot, window)
16415 }
16416
16417 pub fn display_to_pixel_point(
16418 &self,
16419 source: DisplayPoint,
16420 editor_snapshot: &EditorSnapshot,
16421 window: &mut Window,
16422 ) -> Option<gpui::Point<Pixels>> {
16423 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16424 let text_layout_details = self.text_layout_details(window);
16425 let scroll_top = text_layout_details
16426 .scroll_anchor
16427 .scroll_position(editor_snapshot)
16428 .y;
16429
16430 if source.row().as_f32() < scroll_top.floor() {
16431 return None;
16432 }
16433 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16434 let source_y = line_height * (source.row().as_f32() - scroll_top);
16435 Some(gpui::Point::new(source_x, source_y))
16436 }
16437
16438 pub fn has_visible_completions_menu(&self) -> bool {
16439 !self.edit_prediction_preview_is_active()
16440 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16441 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16442 })
16443 }
16444
16445 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16446 self.addons
16447 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16448 }
16449
16450 pub fn unregister_addon<T: Addon>(&mut self) {
16451 self.addons.remove(&std::any::TypeId::of::<T>());
16452 }
16453
16454 pub fn addon<T: Addon>(&self) -> Option<&T> {
16455 let type_id = std::any::TypeId::of::<T>();
16456 self.addons
16457 .get(&type_id)
16458 .and_then(|item| item.to_any().downcast_ref::<T>())
16459 }
16460
16461 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16462 let text_layout_details = self.text_layout_details(window);
16463 let style = &text_layout_details.editor_style;
16464 let font_id = window.text_system().resolve_font(&style.text.font());
16465 let font_size = style.text.font_size.to_pixels(window.rem_size());
16466 let line_height = style.text.line_height_in_pixels(window.rem_size());
16467 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16468
16469 gpui::Size::new(em_width, line_height)
16470 }
16471
16472 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16473 self.load_diff_task.clone()
16474 }
16475
16476 fn read_selections_from_db(
16477 &mut self,
16478 item_id: u64,
16479 workspace_id: WorkspaceId,
16480 window: &mut Window,
16481 cx: &mut Context<Editor>,
16482 ) {
16483 if !self.is_singleton(cx)
16484 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16485 {
16486 return;
16487 }
16488 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16489 return;
16490 };
16491 if selections.is_empty() {
16492 return;
16493 }
16494
16495 let snapshot = self.buffer.read(cx).snapshot(cx);
16496 self.change_selections(None, window, cx, |s| {
16497 s.select_ranges(selections.into_iter().map(|(start, end)| {
16498 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16499 }));
16500 });
16501 }
16502}
16503
16504fn insert_extra_newline_brackets(
16505 buffer: &MultiBufferSnapshot,
16506 range: Range<usize>,
16507 language: &language::LanguageScope,
16508) -> bool {
16509 let leading_whitespace_len = buffer
16510 .reversed_chars_at(range.start)
16511 .take_while(|c| c.is_whitespace() && *c != '\n')
16512 .map(|c| c.len_utf8())
16513 .sum::<usize>();
16514 let trailing_whitespace_len = buffer
16515 .chars_at(range.end)
16516 .take_while(|c| c.is_whitespace() && *c != '\n')
16517 .map(|c| c.len_utf8())
16518 .sum::<usize>();
16519 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16520
16521 language.brackets().any(|(pair, enabled)| {
16522 let pair_start = pair.start.trim_end();
16523 let pair_end = pair.end.trim_start();
16524
16525 enabled
16526 && pair.newline
16527 && buffer.contains_str_at(range.end, pair_end)
16528 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16529 })
16530}
16531
16532fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16533 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16534 [(buffer, range, _)] => (*buffer, range.clone()),
16535 _ => return false,
16536 };
16537 let pair = {
16538 let mut result: Option<BracketMatch> = None;
16539
16540 for pair in buffer
16541 .all_bracket_ranges(range.clone())
16542 .filter(move |pair| {
16543 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16544 })
16545 {
16546 let len = pair.close_range.end - pair.open_range.start;
16547
16548 if let Some(existing) = &result {
16549 let existing_len = existing.close_range.end - existing.open_range.start;
16550 if len > existing_len {
16551 continue;
16552 }
16553 }
16554
16555 result = Some(pair);
16556 }
16557
16558 result
16559 };
16560 let Some(pair) = pair else {
16561 return false;
16562 };
16563 pair.newline_only
16564 && buffer
16565 .chars_for_range(pair.open_range.end..range.start)
16566 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16567 .all(|c| c.is_whitespace() && c != '\n')
16568}
16569
16570fn get_uncommitted_diff_for_buffer(
16571 project: &Entity<Project>,
16572 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16573 buffer: Entity<MultiBuffer>,
16574 cx: &mut App,
16575) -> Task<()> {
16576 let mut tasks = Vec::new();
16577 project.update(cx, |project, cx| {
16578 for buffer in buffers {
16579 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16580 }
16581 });
16582 cx.spawn(|mut cx| async move {
16583 let diffs = future::join_all(tasks).await;
16584 buffer
16585 .update(&mut cx, |buffer, cx| {
16586 for diff in diffs.into_iter().flatten() {
16587 buffer.add_diff(diff, cx);
16588 }
16589 })
16590 .ok();
16591 })
16592}
16593
16594fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16595 let tab_size = tab_size.get() as usize;
16596 let mut width = offset;
16597
16598 for ch in text.chars() {
16599 width += if ch == '\t' {
16600 tab_size - (width % tab_size)
16601 } else {
16602 1
16603 };
16604 }
16605
16606 width - offset
16607}
16608
16609#[cfg(test)]
16610mod tests {
16611 use super::*;
16612
16613 #[test]
16614 fn test_string_size_with_expanded_tabs() {
16615 let nz = |val| NonZeroU32::new(val).unwrap();
16616 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16617 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16618 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16619 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16620 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16621 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16622 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16623 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16624 }
16625}
16626
16627/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16628struct WordBreakingTokenizer<'a> {
16629 input: &'a str,
16630}
16631
16632impl<'a> WordBreakingTokenizer<'a> {
16633 fn new(input: &'a str) -> Self {
16634 Self { input }
16635 }
16636}
16637
16638fn is_char_ideographic(ch: char) -> bool {
16639 use unicode_script::Script::*;
16640 use unicode_script::UnicodeScript;
16641 matches!(ch.script(), Han | Tangut | Yi)
16642}
16643
16644fn is_grapheme_ideographic(text: &str) -> bool {
16645 text.chars().any(is_char_ideographic)
16646}
16647
16648fn is_grapheme_whitespace(text: &str) -> bool {
16649 text.chars().any(|x| x.is_whitespace())
16650}
16651
16652fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16653 text.chars().next().map_or(false, |ch| {
16654 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16655 })
16656}
16657
16658#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16659struct WordBreakToken<'a> {
16660 token: &'a str,
16661 grapheme_len: usize,
16662 is_whitespace: bool,
16663}
16664
16665impl<'a> Iterator for WordBreakingTokenizer<'a> {
16666 /// Yields a span, the count of graphemes in the token, and whether it was
16667 /// whitespace. Note that it also breaks at word boundaries.
16668 type Item = WordBreakToken<'a>;
16669
16670 fn next(&mut self) -> Option<Self::Item> {
16671 use unicode_segmentation::UnicodeSegmentation;
16672 if self.input.is_empty() {
16673 return None;
16674 }
16675
16676 let mut iter = self.input.graphemes(true).peekable();
16677 let mut offset = 0;
16678 let mut graphemes = 0;
16679 if let Some(first_grapheme) = iter.next() {
16680 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16681 offset += first_grapheme.len();
16682 graphemes += 1;
16683 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16684 if let Some(grapheme) = iter.peek().copied() {
16685 if should_stay_with_preceding_ideograph(grapheme) {
16686 offset += grapheme.len();
16687 graphemes += 1;
16688 }
16689 }
16690 } else {
16691 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16692 let mut next_word_bound = words.peek().copied();
16693 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16694 next_word_bound = words.next();
16695 }
16696 while let Some(grapheme) = iter.peek().copied() {
16697 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16698 break;
16699 };
16700 if is_grapheme_whitespace(grapheme) != is_whitespace {
16701 break;
16702 };
16703 offset += grapheme.len();
16704 graphemes += 1;
16705 iter.next();
16706 }
16707 }
16708 let token = &self.input[..offset];
16709 self.input = &self.input[offset..];
16710 if is_whitespace {
16711 Some(WordBreakToken {
16712 token: " ",
16713 grapheme_len: 1,
16714 is_whitespace: true,
16715 })
16716 } else {
16717 Some(WordBreakToken {
16718 token,
16719 grapheme_len: graphemes,
16720 is_whitespace: false,
16721 })
16722 }
16723 } else {
16724 None
16725 }
16726 }
16727}
16728
16729#[test]
16730fn test_word_breaking_tokenizer() {
16731 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16732 ("", &[]),
16733 (" ", &[(" ", 1, true)]),
16734 ("Ʒ", &[("Ʒ", 1, false)]),
16735 ("Ǽ", &[("Ǽ", 1, false)]),
16736 ("⋑", &[("⋑", 1, false)]),
16737 ("⋑⋑", &[("⋑⋑", 2, false)]),
16738 (
16739 "原理,进而",
16740 &[
16741 ("原", 1, false),
16742 ("理,", 2, false),
16743 ("进", 1, false),
16744 ("而", 1, false),
16745 ],
16746 ),
16747 (
16748 "hello world",
16749 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16750 ),
16751 (
16752 "hello, world",
16753 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16754 ),
16755 (
16756 " hello world",
16757 &[
16758 (" ", 1, true),
16759 ("hello", 5, false),
16760 (" ", 1, true),
16761 ("world", 5, false),
16762 ],
16763 ),
16764 (
16765 "这是什么 \n 钢笔",
16766 &[
16767 ("这", 1, false),
16768 ("是", 1, false),
16769 ("什", 1, false),
16770 ("么", 1, false),
16771 (" ", 1, true),
16772 ("钢", 1, false),
16773 ("笔", 1, false),
16774 ],
16775 ),
16776 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16777 ];
16778
16779 for (input, result) in tests {
16780 assert_eq!(
16781 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16782 result
16783 .iter()
16784 .copied()
16785 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16786 token,
16787 grapheme_len,
16788 is_whitespace,
16789 })
16790 .collect::<Vec<_>>()
16791 );
16792 }
16793}
16794
16795fn wrap_with_prefix(
16796 line_prefix: String,
16797 unwrapped_text: String,
16798 wrap_column: usize,
16799 tab_size: NonZeroU32,
16800) -> String {
16801 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16802 let mut wrapped_text = String::new();
16803 let mut current_line = line_prefix.clone();
16804
16805 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16806 let mut current_line_len = line_prefix_len;
16807 for WordBreakToken {
16808 token,
16809 grapheme_len,
16810 is_whitespace,
16811 } in tokenizer
16812 {
16813 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16814 wrapped_text.push_str(current_line.trim_end());
16815 wrapped_text.push('\n');
16816 current_line.truncate(line_prefix.len());
16817 current_line_len = line_prefix_len;
16818 if !is_whitespace {
16819 current_line.push_str(token);
16820 current_line_len += grapheme_len;
16821 }
16822 } else if !is_whitespace {
16823 current_line.push_str(token);
16824 current_line_len += grapheme_len;
16825 } else if current_line_len != line_prefix_len {
16826 current_line.push(' ');
16827 current_line_len += 1;
16828 }
16829 }
16830
16831 if !current_line.is_empty() {
16832 wrapped_text.push_str(¤t_line);
16833 }
16834 wrapped_text
16835}
16836
16837#[test]
16838fn test_wrap_with_prefix() {
16839 assert_eq!(
16840 wrap_with_prefix(
16841 "# ".to_string(),
16842 "abcdefg".to_string(),
16843 4,
16844 NonZeroU32::new(4).unwrap()
16845 ),
16846 "# abcdefg"
16847 );
16848 assert_eq!(
16849 wrap_with_prefix(
16850 "".to_string(),
16851 "\thello world".to_string(),
16852 8,
16853 NonZeroU32::new(4).unwrap()
16854 ),
16855 "hello\nworld"
16856 );
16857 assert_eq!(
16858 wrap_with_prefix(
16859 "// ".to_string(),
16860 "xx \nyy zz aa bb cc".to_string(),
16861 12,
16862 NonZeroU32::new(4).unwrap()
16863 ),
16864 "// xx yy zz\n// aa bb cc"
16865 );
16866 assert_eq!(
16867 wrap_with_prefix(
16868 String::new(),
16869 "这是什么 \n 钢笔".to_string(),
16870 3,
16871 NonZeroU32::new(4).unwrap()
16872 ),
16873 "这是什\n么 钢\n笔"
16874 );
16875}
16876
16877pub trait CollaborationHub {
16878 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16879 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16880 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16881}
16882
16883impl CollaborationHub for Entity<Project> {
16884 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16885 self.read(cx).collaborators()
16886 }
16887
16888 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16889 self.read(cx).user_store().read(cx).participant_indices()
16890 }
16891
16892 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16893 let this = self.read(cx);
16894 let user_ids = this.collaborators().values().map(|c| c.user_id);
16895 this.user_store().read_with(cx, |user_store, cx| {
16896 user_store.participant_names(user_ids, cx)
16897 })
16898 }
16899}
16900
16901pub trait SemanticsProvider {
16902 fn hover(
16903 &self,
16904 buffer: &Entity<Buffer>,
16905 position: text::Anchor,
16906 cx: &mut App,
16907 ) -> Option<Task<Vec<project::Hover>>>;
16908
16909 fn inlay_hints(
16910 &self,
16911 buffer_handle: Entity<Buffer>,
16912 range: Range<text::Anchor>,
16913 cx: &mut App,
16914 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16915
16916 fn resolve_inlay_hint(
16917 &self,
16918 hint: InlayHint,
16919 buffer_handle: Entity<Buffer>,
16920 server_id: LanguageServerId,
16921 cx: &mut App,
16922 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16923
16924 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16925
16926 fn document_highlights(
16927 &self,
16928 buffer: &Entity<Buffer>,
16929 position: text::Anchor,
16930 cx: &mut App,
16931 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16932
16933 fn definitions(
16934 &self,
16935 buffer: &Entity<Buffer>,
16936 position: text::Anchor,
16937 kind: GotoDefinitionKind,
16938 cx: &mut App,
16939 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16940
16941 fn range_for_rename(
16942 &self,
16943 buffer: &Entity<Buffer>,
16944 position: text::Anchor,
16945 cx: &mut App,
16946 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16947
16948 fn perform_rename(
16949 &self,
16950 buffer: &Entity<Buffer>,
16951 position: text::Anchor,
16952 new_name: String,
16953 cx: &mut App,
16954 ) -> Option<Task<Result<ProjectTransaction>>>;
16955}
16956
16957pub trait CompletionProvider {
16958 fn completions(
16959 &self,
16960 buffer: &Entity<Buffer>,
16961 buffer_position: text::Anchor,
16962 trigger: CompletionContext,
16963 window: &mut Window,
16964 cx: &mut Context<Editor>,
16965 ) -> Task<Result<Option<Vec<Completion>>>>;
16966
16967 fn resolve_completions(
16968 &self,
16969 buffer: Entity<Buffer>,
16970 completion_indices: Vec<usize>,
16971 completions: Rc<RefCell<Box<[Completion]>>>,
16972 cx: &mut Context<Editor>,
16973 ) -> Task<Result<bool>>;
16974
16975 fn apply_additional_edits_for_completion(
16976 &self,
16977 _buffer: Entity<Buffer>,
16978 _completions: Rc<RefCell<Box<[Completion]>>>,
16979 _completion_index: usize,
16980 _push_to_history: bool,
16981 _cx: &mut Context<Editor>,
16982 ) -> Task<Result<Option<language::Transaction>>> {
16983 Task::ready(Ok(None))
16984 }
16985
16986 fn is_completion_trigger(
16987 &self,
16988 buffer: &Entity<Buffer>,
16989 position: language::Anchor,
16990 text: &str,
16991 trigger_in_words: bool,
16992 cx: &mut Context<Editor>,
16993 ) -> bool;
16994
16995 fn sort_completions(&self) -> bool {
16996 true
16997 }
16998}
16999
17000pub trait CodeActionProvider {
17001 fn id(&self) -> Arc<str>;
17002
17003 fn code_actions(
17004 &self,
17005 buffer: &Entity<Buffer>,
17006 range: Range<text::Anchor>,
17007 window: &mut Window,
17008 cx: &mut App,
17009 ) -> Task<Result<Vec<CodeAction>>>;
17010
17011 fn apply_code_action(
17012 &self,
17013 buffer_handle: Entity<Buffer>,
17014 action: CodeAction,
17015 excerpt_id: ExcerptId,
17016 push_to_history: bool,
17017 window: &mut Window,
17018 cx: &mut App,
17019 ) -> Task<Result<ProjectTransaction>>;
17020}
17021
17022impl CodeActionProvider for Entity<Project> {
17023 fn id(&self) -> Arc<str> {
17024 "project".into()
17025 }
17026
17027 fn code_actions(
17028 &self,
17029 buffer: &Entity<Buffer>,
17030 range: Range<text::Anchor>,
17031 _window: &mut Window,
17032 cx: &mut App,
17033 ) -> Task<Result<Vec<CodeAction>>> {
17034 self.update(cx, |project, cx| {
17035 let code_lens = project.code_lens(buffer, range.clone(), cx);
17036 let code_actions = project.code_actions(buffer, range, None, cx);
17037 cx.background_spawn(async move {
17038 let (code_lens, code_actions) = join(code_lens, code_actions).await;
17039 Ok(code_lens
17040 .context("code lens fetch")?
17041 .into_iter()
17042 .chain(code_actions.context("code action fetch")?)
17043 .collect())
17044 })
17045 })
17046 }
17047
17048 fn apply_code_action(
17049 &self,
17050 buffer_handle: Entity<Buffer>,
17051 action: CodeAction,
17052 _excerpt_id: ExcerptId,
17053 push_to_history: bool,
17054 _window: &mut Window,
17055 cx: &mut App,
17056 ) -> Task<Result<ProjectTransaction>> {
17057 self.update(cx, |project, cx| {
17058 project.apply_code_action(buffer_handle, action, push_to_history, cx)
17059 })
17060 }
17061}
17062
17063fn snippet_completions(
17064 project: &Project,
17065 buffer: &Entity<Buffer>,
17066 buffer_position: text::Anchor,
17067 cx: &mut App,
17068) -> Task<Result<Vec<Completion>>> {
17069 let language = buffer.read(cx).language_at(buffer_position);
17070 let language_name = language.as_ref().map(|language| language.lsp_id());
17071 let snippet_store = project.snippets().read(cx);
17072 let snippets = snippet_store.snippets_for(language_name, cx);
17073
17074 if snippets.is_empty() {
17075 return Task::ready(Ok(vec![]));
17076 }
17077 let snapshot = buffer.read(cx).text_snapshot();
17078 let chars: String = snapshot
17079 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17080 .collect();
17081
17082 let scope = language.map(|language| language.default_scope());
17083 let executor = cx.background_executor().clone();
17084
17085 cx.background_spawn(async move {
17086 let classifier = CharClassifier::new(scope).for_completion(true);
17087 let mut last_word = chars
17088 .chars()
17089 .take_while(|c| classifier.is_word(*c))
17090 .collect::<String>();
17091 last_word = last_word.chars().rev().collect();
17092
17093 if last_word.is_empty() {
17094 return Ok(vec![]);
17095 }
17096
17097 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17098 let to_lsp = |point: &text::Anchor| {
17099 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
17100 point_to_lsp(end)
17101 };
17102 let lsp_end = to_lsp(&buffer_position);
17103
17104 let candidates = snippets
17105 .iter()
17106 .enumerate()
17107 .flat_map(|(ix, snippet)| {
17108 snippet
17109 .prefix
17110 .iter()
17111 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
17112 })
17113 .collect::<Vec<StringMatchCandidate>>();
17114
17115 let mut matches = fuzzy::match_strings(
17116 &candidates,
17117 &last_word,
17118 last_word.chars().any(|c| c.is_uppercase()),
17119 100,
17120 &Default::default(),
17121 executor,
17122 )
17123 .await;
17124
17125 // Remove all candidates where the query's start does not match the start of any word in the candidate
17126 if let Some(query_start) = last_word.chars().next() {
17127 matches.retain(|string_match| {
17128 split_words(&string_match.string).any(|word| {
17129 // Check that the first codepoint of the word as lowercase matches the first
17130 // codepoint of the query as lowercase
17131 word.chars()
17132 .flat_map(|codepoint| codepoint.to_lowercase())
17133 .zip(query_start.to_lowercase())
17134 .all(|(word_cp, query_cp)| word_cp == query_cp)
17135 })
17136 });
17137 }
17138
17139 let matched_strings = matches
17140 .into_iter()
17141 .map(|m| m.string)
17142 .collect::<HashSet<_>>();
17143
17144 let result: Vec<Completion> = snippets
17145 .into_iter()
17146 .filter_map(|snippet| {
17147 let matching_prefix = snippet
17148 .prefix
17149 .iter()
17150 .find(|prefix| matched_strings.contains(*prefix))?;
17151 let start = as_offset - last_word.len();
17152 let start = snapshot.anchor_before(start);
17153 let range = start..buffer_position;
17154 let lsp_start = to_lsp(&start);
17155 let lsp_range = lsp::Range {
17156 start: lsp_start,
17157 end: lsp_end,
17158 };
17159 Some(Completion {
17160 old_range: range,
17161 new_text: snippet.body.clone(),
17162 source: CompletionSource::Lsp {
17163 server_id: LanguageServerId(usize::MAX),
17164 resolved: true,
17165 lsp_completion: Box::new(lsp::CompletionItem {
17166 label: snippet.prefix.first().unwrap().clone(),
17167 kind: Some(CompletionItemKind::SNIPPET),
17168 label_details: snippet.description.as_ref().map(|description| {
17169 lsp::CompletionItemLabelDetails {
17170 detail: Some(description.clone()),
17171 description: None,
17172 }
17173 }),
17174 insert_text_format: Some(InsertTextFormat::SNIPPET),
17175 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17176 lsp::InsertReplaceEdit {
17177 new_text: snippet.body.clone(),
17178 insert: lsp_range,
17179 replace: lsp_range,
17180 },
17181 )),
17182 filter_text: Some(snippet.body.clone()),
17183 sort_text: Some(char::MAX.to_string()),
17184 ..lsp::CompletionItem::default()
17185 }),
17186 lsp_defaults: None,
17187 },
17188 label: CodeLabel {
17189 text: matching_prefix.clone(),
17190 runs: Vec::new(),
17191 filter_range: 0..matching_prefix.len(),
17192 },
17193 documentation: snippet
17194 .description
17195 .clone()
17196 .map(|description| CompletionDocumentation::SingleLine(description.into())),
17197 confirm: None,
17198 })
17199 })
17200 .collect();
17201
17202 Ok(result)
17203 })
17204}
17205
17206impl CompletionProvider for Entity<Project> {
17207 fn completions(
17208 &self,
17209 buffer: &Entity<Buffer>,
17210 buffer_position: text::Anchor,
17211 options: CompletionContext,
17212 _window: &mut Window,
17213 cx: &mut Context<Editor>,
17214 ) -> Task<Result<Option<Vec<Completion>>>> {
17215 self.update(cx, |project, cx| {
17216 let snippets = snippet_completions(project, buffer, buffer_position, cx);
17217 let project_completions = project.completions(buffer, buffer_position, options, cx);
17218 cx.background_spawn(async move {
17219 let snippets_completions = snippets.await?;
17220 match project_completions.await? {
17221 Some(mut completions) => {
17222 completions.extend(snippets_completions);
17223 Ok(Some(completions))
17224 }
17225 None => {
17226 if snippets_completions.is_empty() {
17227 Ok(None)
17228 } else {
17229 Ok(Some(snippets_completions))
17230 }
17231 }
17232 }
17233 })
17234 })
17235 }
17236
17237 fn resolve_completions(
17238 &self,
17239 buffer: Entity<Buffer>,
17240 completion_indices: Vec<usize>,
17241 completions: Rc<RefCell<Box<[Completion]>>>,
17242 cx: &mut Context<Editor>,
17243 ) -> Task<Result<bool>> {
17244 self.update(cx, |project, cx| {
17245 project.lsp_store().update(cx, |lsp_store, cx| {
17246 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17247 })
17248 })
17249 }
17250
17251 fn apply_additional_edits_for_completion(
17252 &self,
17253 buffer: Entity<Buffer>,
17254 completions: Rc<RefCell<Box<[Completion]>>>,
17255 completion_index: usize,
17256 push_to_history: bool,
17257 cx: &mut Context<Editor>,
17258 ) -> Task<Result<Option<language::Transaction>>> {
17259 self.update(cx, |project, cx| {
17260 project.lsp_store().update(cx, |lsp_store, cx| {
17261 lsp_store.apply_additional_edits_for_completion(
17262 buffer,
17263 completions,
17264 completion_index,
17265 push_to_history,
17266 cx,
17267 )
17268 })
17269 })
17270 }
17271
17272 fn is_completion_trigger(
17273 &self,
17274 buffer: &Entity<Buffer>,
17275 position: language::Anchor,
17276 text: &str,
17277 trigger_in_words: bool,
17278 cx: &mut Context<Editor>,
17279 ) -> bool {
17280 let mut chars = text.chars();
17281 let char = if let Some(char) = chars.next() {
17282 char
17283 } else {
17284 return false;
17285 };
17286 if chars.next().is_some() {
17287 return false;
17288 }
17289
17290 let buffer = buffer.read(cx);
17291 let snapshot = buffer.snapshot();
17292 if !snapshot.settings_at(position, cx).show_completions_on_input {
17293 return false;
17294 }
17295 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17296 if trigger_in_words && classifier.is_word(char) {
17297 return true;
17298 }
17299
17300 buffer.completion_triggers().contains(text)
17301 }
17302}
17303
17304impl SemanticsProvider for Entity<Project> {
17305 fn hover(
17306 &self,
17307 buffer: &Entity<Buffer>,
17308 position: text::Anchor,
17309 cx: &mut App,
17310 ) -> Option<Task<Vec<project::Hover>>> {
17311 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17312 }
17313
17314 fn document_highlights(
17315 &self,
17316 buffer: &Entity<Buffer>,
17317 position: text::Anchor,
17318 cx: &mut App,
17319 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17320 Some(self.update(cx, |project, cx| {
17321 project.document_highlights(buffer, position, cx)
17322 }))
17323 }
17324
17325 fn definitions(
17326 &self,
17327 buffer: &Entity<Buffer>,
17328 position: text::Anchor,
17329 kind: GotoDefinitionKind,
17330 cx: &mut App,
17331 ) -> Option<Task<Result<Vec<LocationLink>>>> {
17332 Some(self.update(cx, |project, cx| match kind {
17333 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17334 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17335 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17336 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17337 }))
17338 }
17339
17340 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17341 // TODO: make this work for remote projects
17342 self.update(cx, |this, cx| {
17343 buffer.update(cx, |buffer, cx| {
17344 this.any_language_server_supports_inlay_hints(buffer, cx)
17345 })
17346 })
17347 }
17348
17349 fn inlay_hints(
17350 &self,
17351 buffer_handle: Entity<Buffer>,
17352 range: Range<text::Anchor>,
17353 cx: &mut App,
17354 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17355 Some(self.update(cx, |project, cx| {
17356 project.inlay_hints(buffer_handle, range, cx)
17357 }))
17358 }
17359
17360 fn resolve_inlay_hint(
17361 &self,
17362 hint: InlayHint,
17363 buffer_handle: Entity<Buffer>,
17364 server_id: LanguageServerId,
17365 cx: &mut App,
17366 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17367 Some(self.update(cx, |project, cx| {
17368 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17369 }))
17370 }
17371
17372 fn range_for_rename(
17373 &self,
17374 buffer: &Entity<Buffer>,
17375 position: text::Anchor,
17376 cx: &mut App,
17377 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17378 Some(self.update(cx, |project, cx| {
17379 let buffer = buffer.clone();
17380 let task = project.prepare_rename(buffer.clone(), position, cx);
17381 cx.spawn(|_, mut cx| async move {
17382 Ok(match task.await? {
17383 PrepareRenameResponse::Success(range) => Some(range),
17384 PrepareRenameResponse::InvalidPosition => None,
17385 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17386 // Fallback on using TreeSitter info to determine identifier range
17387 buffer.update(&mut cx, |buffer, _| {
17388 let snapshot = buffer.snapshot();
17389 let (range, kind) = snapshot.surrounding_word(position);
17390 if kind != Some(CharKind::Word) {
17391 return None;
17392 }
17393 Some(
17394 snapshot.anchor_before(range.start)
17395 ..snapshot.anchor_after(range.end),
17396 )
17397 })?
17398 }
17399 })
17400 })
17401 }))
17402 }
17403
17404 fn perform_rename(
17405 &self,
17406 buffer: &Entity<Buffer>,
17407 position: text::Anchor,
17408 new_name: String,
17409 cx: &mut App,
17410 ) -> Option<Task<Result<ProjectTransaction>>> {
17411 Some(self.update(cx, |project, cx| {
17412 project.perform_rename(buffer.clone(), position, new_name, cx)
17413 }))
17414 }
17415}
17416
17417fn inlay_hint_settings(
17418 location: Anchor,
17419 snapshot: &MultiBufferSnapshot,
17420 cx: &mut Context<Editor>,
17421) -> InlayHintSettings {
17422 let file = snapshot.file_at(location);
17423 let language = snapshot.language_at(location).map(|l| l.name());
17424 language_settings(language, file, cx).inlay_hints
17425}
17426
17427fn consume_contiguous_rows(
17428 contiguous_row_selections: &mut Vec<Selection<Point>>,
17429 selection: &Selection<Point>,
17430 display_map: &DisplaySnapshot,
17431 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17432) -> (MultiBufferRow, MultiBufferRow) {
17433 contiguous_row_selections.push(selection.clone());
17434 let start_row = MultiBufferRow(selection.start.row);
17435 let mut end_row = ending_row(selection, display_map);
17436
17437 while let Some(next_selection) = selections.peek() {
17438 if next_selection.start.row <= end_row.0 {
17439 end_row = ending_row(next_selection, display_map);
17440 contiguous_row_selections.push(selections.next().unwrap().clone());
17441 } else {
17442 break;
17443 }
17444 }
17445 (start_row, end_row)
17446}
17447
17448fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17449 if next_selection.end.column > 0 || next_selection.is_empty() {
17450 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17451 } else {
17452 MultiBufferRow(next_selection.end.row)
17453 }
17454}
17455
17456impl EditorSnapshot {
17457 pub fn remote_selections_in_range<'a>(
17458 &'a self,
17459 range: &'a Range<Anchor>,
17460 collaboration_hub: &dyn CollaborationHub,
17461 cx: &'a App,
17462 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17463 let participant_names = collaboration_hub.user_names(cx);
17464 let participant_indices = collaboration_hub.user_participant_indices(cx);
17465 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17466 let collaborators_by_replica_id = collaborators_by_peer_id
17467 .iter()
17468 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17469 .collect::<HashMap<_, _>>();
17470 self.buffer_snapshot
17471 .selections_in_range(range, false)
17472 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17473 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17474 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17475 let user_name = participant_names.get(&collaborator.user_id).cloned();
17476 Some(RemoteSelection {
17477 replica_id,
17478 selection,
17479 cursor_shape,
17480 line_mode,
17481 participant_index,
17482 peer_id: collaborator.peer_id,
17483 user_name,
17484 })
17485 })
17486 }
17487
17488 pub fn hunks_for_ranges(
17489 &self,
17490 ranges: impl IntoIterator<Item = Range<Point>>,
17491 ) -> Vec<MultiBufferDiffHunk> {
17492 let mut hunks = Vec::new();
17493 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17494 HashMap::default();
17495 for query_range in ranges {
17496 let query_rows =
17497 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17498 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17499 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17500 ) {
17501 // Include deleted hunks that are adjacent to the query range, because
17502 // otherwise they would be missed.
17503 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17504 if hunk.status().is_deleted() {
17505 intersects_range |= hunk.row_range.start == query_rows.end;
17506 intersects_range |= hunk.row_range.end == query_rows.start;
17507 }
17508 if intersects_range {
17509 if !processed_buffer_rows
17510 .entry(hunk.buffer_id)
17511 .or_default()
17512 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17513 {
17514 continue;
17515 }
17516 hunks.push(hunk);
17517 }
17518 }
17519 }
17520
17521 hunks
17522 }
17523
17524 fn display_diff_hunks_for_rows<'a>(
17525 &'a self,
17526 display_rows: Range<DisplayRow>,
17527 folded_buffers: &'a HashSet<BufferId>,
17528 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17529 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17530 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17531
17532 self.buffer_snapshot
17533 .diff_hunks_in_range(buffer_start..buffer_end)
17534 .filter_map(|hunk| {
17535 if folded_buffers.contains(&hunk.buffer_id) {
17536 return None;
17537 }
17538
17539 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17540 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17541
17542 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17543 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17544
17545 let display_hunk = if hunk_display_start.column() != 0 {
17546 DisplayDiffHunk::Folded {
17547 display_row: hunk_display_start.row(),
17548 }
17549 } else {
17550 let mut end_row = hunk_display_end.row();
17551 if hunk_display_end.column() > 0 {
17552 end_row.0 += 1;
17553 }
17554 let is_created_file = hunk.is_created_file();
17555 DisplayDiffHunk::Unfolded {
17556 status: hunk.status(),
17557 diff_base_byte_range: hunk.diff_base_byte_range,
17558 display_row_range: hunk_display_start.row()..end_row,
17559 multi_buffer_range: Anchor::range_in_buffer(
17560 hunk.excerpt_id,
17561 hunk.buffer_id,
17562 hunk.buffer_range,
17563 ),
17564 is_created_file,
17565 }
17566 };
17567
17568 Some(display_hunk)
17569 })
17570 }
17571
17572 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17573 self.display_snapshot.buffer_snapshot.language_at(position)
17574 }
17575
17576 pub fn is_focused(&self) -> bool {
17577 self.is_focused
17578 }
17579
17580 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17581 self.placeholder_text.as_ref()
17582 }
17583
17584 pub fn scroll_position(&self) -> gpui::Point<f32> {
17585 self.scroll_anchor.scroll_position(&self.display_snapshot)
17586 }
17587
17588 fn gutter_dimensions(
17589 &self,
17590 font_id: FontId,
17591 font_size: Pixels,
17592 max_line_number_width: Pixels,
17593 cx: &App,
17594 ) -> Option<GutterDimensions> {
17595 if !self.show_gutter {
17596 return None;
17597 }
17598
17599 let descent = cx.text_system().descent(font_id, font_size);
17600 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17601 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17602
17603 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17604 matches!(
17605 ProjectSettings::get_global(cx).git.git_gutter,
17606 Some(GitGutterSetting::TrackedFiles)
17607 )
17608 });
17609 let gutter_settings = EditorSettings::get_global(cx).gutter;
17610 let show_line_numbers = self
17611 .show_line_numbers
17612 .unwrap_or(gutter_settings.line_numbers);
17613 let line_gutter_width = if show_line_numbers {
17614 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17615 let min_width_for_number_on_gutter = em_advance * 4.0;
17616 max_line_number_width.max(min_width_for_number_on_gutter)
17617 } else {
17618 0.0.into()
17619 };
17620
17621 let show_code_actions = self
17622 .show_code_actions
17623 .unwrap_or(gutter_settings.code_actions);
17624
17625 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17626
17627 let git_blame_entries_width =
17628 self.git_blame_gutter_max_author_length
17629 .map(|max_author_length| {
17630 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17631
17632 /// The number of characters to dedicate to gaps and margins.
17633 const SPACING_WIDTH: usize = 4;
17634
17635 let max_char_count = max_author_length
17636 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17637 + ::git::SHORT_SHA_LENGTH
17638 + MAX_RELATIVE_TIMESTAMP.len()
17639 + SPACING_WIDTH;
17640
17641 em_advance * max_char_count
17642 });
17643
17644 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17645 left_padding += if show_code_actions || show_runnables {
17646 em_width * 3.0
17647 } else if show_git_gutter && show_line_numbers {
17648 em_width * 2.0
17649 } else if show_git_gutter || show_line_numbers {
17650 em_width
17651 } else {
17652 px(0.)
17653 };
17654
17655 let right_padding = if gutter_settings.folds && show_line_numbers {
17656 em_width * 4.0
17657 } else if gutter_settings.folds {
17658 em_width * 3.0
17659 } else if show_line_numbers {
17660 em_width
17661 } else {
17662 px(0.)
17663 };
17664
17665 Some(GutterDimensions {
17666 left_padding,
17667 right_padding,
17668 width: line_gutter_width + left_padding + right_padding,
17669 margin: -descent,
17670 git_blame_entries_width,
17671 })
17672 }
17673
17674 pub fn render_crease_toggle(
17675 &self,
17676 buffer_row: MultiBufferRow,
17677 row_contains_cursor: bool,
17678 editor: Entity<Editor>,
17679 window: &mut Window,
17680 cx: &mut App,
17681 ) -> Option<AnyElement> {
17682 let folded = self.is_line_folded(buffer_row);
17683 let mut is_foldable = false;
17684
17685 if let Some(crease) = self
17686 .crease_snapshot
17687 .query_row(buffer_row, &self.buffer_snapshot)
17688 {
17689 is_foldable = true;
17690 match crease {
17691 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17692 if let Some(render_toggle) = render_toggle {
17693 let toggle_callback =
17694 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17695 if folded {
17696 editor.update(cx, |editor, cx| {
17697 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17698 });
17699 } else {
17700 editor.update(cx, |editor, cx| {
17701 editor.unfold_at(
17702 &crate::UnfoldAt { buffer_row },
17703 window,
17704 cx,
17705 )
17706 });
17707 }
17708 });
17709 return Some((render_toggle)(
17710 buffer_row,
17711 folded,
17712 toggle_callback,
17713 window,
17714 cx,
17715 ));
17716 }
17717 }
17718 }
17719 }
17720
17721 is_foldable |= self.starts_indent(buffer_row);
17722
17723 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17724 Some(
17725 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17726 .toggle_state(folded)
17727 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17728 if folded {
17729 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17730 } else {
17731 this.fold_at(&FoldAt { buffer_row }, window, cx);
17732 }
17733 }))
17734 .into_any_element(),
17735 )
17736 } else {
17737 None
17738 }
17739 }
17740
17741 pub fn render_crease_trailer(
17742 &self,
17743 buffer_row: MultiBufferRow,
17744 window: &mut Window,
17745 cx: &mut App,
17746 ) -> Option<AnyElement> {
17747 let folded = self.is_line_folded(buffer_row);
17748 if let Crease::Inline { render_trailer, .. } = self
17749 .crease_snapshot
17750 .query_row(buffer_row, &self.buffer_snapshot)?
17751 {
17752 let render_trailer = render_trailer.as_ref()?;
17753 Some(render_trailer(buffer_row, folded, window, cx))
17754 } else {
17755 None
17756 }
17757 }
17758}
17759
17760impl Deref for EditorSnapshot {
17761 type Target = DisplaySnapshot;
17762
17763 fn deref(&self) -> &Self::Target {
17764 &self.display_snapshot
17765 }
17766}
17767
17768#[derive(Clone, Debug, PartialEq, Eq)]
17769pub enum EditorEvent {
17770 InputIgnored {
17771 text: Arc<str>,
17772 },
17773 InputHandled {
17774 utf16_range_to_replace: Option<Range<isize>>,
17775 text: Arc<str>,
17776 },
17777 ExcerptsAdded {
17778 buffer: Entity<Buffer>,
17779 predecessor: ExcerptId,
17780 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17781 },
17782 ExcerptsRemoved {
17783 ids: Vec<ExcerptId>,
17784 },
17785 BufferFoldToggled {
17786 ids: Vec<ExcerptId>,
17787 folded: bool,
17788 },
17789 ExcerptsEdited {
17790 ids: Vec<ExcerptId>,
17791 },
17792 ExcerptsExpanded {
17793 ids: Vec<ExcerptId>,
17794 },
17795 BufferEdited,
17796 Edited {
17797 transaction_id: clock::Lamport,
17798 },
17799 Reparsed(BufferId),
17800 Focused,
17801 FocusedIn,
17802 Blurred,
17803 DirtyChanged,
17804 Saved,
17805 TitleChanged,
17806 DiffBaseChanged,
17807 SelectionsChanged {
17808 local: bool,
17809 },
17810 ScrollPositionChanged {
17811 local: bool,
17812 autoscroll: bool,
17813 },
17814 Closed,
17815 TransactionUndone {
17816 transaction_id: clock::Lamport,
17817 },
17818 TransactionBegun {
17819 transaction_id: clock::Lamport,
17820 },
17821 Reloaded,
17822 CursorShapeChanged,
17823}
17824
17825impl EventEmitter<EditorEvent> for Editor {}
17826
17827impl Focusable for Editor {
17828 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17829 self.focus_handle.clone()
17830 }
17831}
17832
17833impl Render for Editor {
17834 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17835 let settings = ThemeSettings::get_global(cx);
17836
17837 let mut text_style = match self.mode {
17838 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17839 color: cx.theme().colors().editor_foreground,
17840 font_family: settings.ui_font.family.clone(),
17841 font_features: settings.ui_font.features.clone(),
17842 font_fallbacks: settings.ui_font.fallbacks.clone(),
17843 font_size: rems(0.875).into(),
17844 font_weight: settings.ui_font.weight,
17845 line_height: relative(settings.buffer_line_height.value()),
17846 ..Default::default()
17847 },
17848 EditorMode::Full => TextStyle {
17849 color: cx.theme().colors().editor_foreground,
17850 font_family: settings.buffer_font.family.clone(),
17851 font_features: settings.buffer_font.features.clone(),
17852 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17853 font_size: settings.buffer_font_size(cx).into(),
17854 font_weight: settings.buffer_font.weight,
17855 line_height: relative(settings.buffer_line_height.value()),
17856 ..Default::default()
17857 },
17858 };
17859 if let Some(text_style_refinement) = &self.text_style_refinement {
17860 text_style.refine(text_style_refinement)
17861 }
17862
17863 let background = match self.mode {
17864 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17865 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17866 EditorMode::Full => cx.theme().colors().editor_background,
17867 };
17868
17869 EditorElement::new(
17870 &cx.entity(),
17871 EditorStyle {
17872 background,
17873 local_player: cx.theme().players().local(),
17874 text: text_style,
17875 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17876 syntax: cx.theme().syntax().clone(),
17877 status: cx.theme().status().clone(),
17878 inlay_hints_style: make_inlay_hints_style(cx),
17879 inline_completion_styles: make_suggestion_styles(cx),
17880 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17881 },
17882 )
17883 }
17884}
17885
17886impl EntityInputHandler for Editor {
17887 fn text_for_range(
17888 &mut self,
17889 range_utf16: Range<usize>,
17890 adjusted_range: &mut Option<Range<usize>>,
17891 _: &mut Window,
17892 cx: &mut Context<Self>,
17893 ) -> Option<String> {
17894 let snapshot = self.buffer.read(cx).read(cx);
17895 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17896 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17897 if (start.0..end.0) != range_utf16 {
17898 adjusted_range.replace(start.0..end.0);
17899 }
17900 Some(snapshot.text_for_range(start..end).collect())
17901 }
17902
17903 fn selected_text_range(
17904 &mut self,
17905 ignore_disabled_input: bool,
17906 _: &mut Window,
17907 cx: &mut Context<Self>,
17908 ) -> Option<UTF16Selection> {
17909 // Prevent the IME menu from appearing when holding down an alphabetic key
17910 // while input is disabled.
17911 if !ignore_disabled_input && !self.input_enabled {
17912 return None;
17913 }
17914
17915 let selection = self.selections.newest::<OffsetUtf16>(cx);
17916 let range = selection.range();
17917
17918 Some(UTF16Selection {
17919 range: range.start.0..range.end.0,
17920 reversed: selection.reversed,
17921 })
17922 }
17923
17924 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17925 let snapshot = self.buffer.read(cx).read(cx);
17926 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17927 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17928 }
17929
17930 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17931 self.clear_highlights::<InputComposition>(cx);
17932 self.ime_transaction.take();
17933 }
17934
17935 fn replace_text_in_range(
17936 &mut self,
17937 range_utf16: Option<Range<usize>>,
17938 text: &str,
17939 window: &mut Window,
17940 cx: &mut Context<Self>,
17941 ) {
17942 if !self.input_enabled {
17943 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17944 return;
17945 }
17946
17947 self.transact(window, cx, |this, window, cx| {
17948 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17949 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17950 Some(this.selection_replacement_ranges(range_utf16, cx))
17951 } else {
17952 this.marked_text_ranges(cx)
17953 };
17954
17955 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17956 let newest_selection_id = this.selections.newest_anchor().id;
17957 this.selections
17958 .all::<OffsetUtf16>(cx)
17959 .iter()
17960 .zip(ranges_to_replace.iter())
17961 .find_map(|(selection, range)| {
17962 if selection.id == newest_selection_id {
17963 Some(
17964 (range.start.0 as isize - selection.head().0 as isize)
17965 ..(range.end.0 as isize - selection.head().0 as isize),
17966 )
17967 } else {
17968 None
17969 }
17970 })
17971 });
17972
17973 cx.emit(EditorEvent::InputHandled {
17974 utf16_range_to_replace: range_to_replace,
17975 text: text.into(),
17976 });
17977
17978 if let Some(new_selected_ranges) = new_selected_ranges {
17979 this.change_selections(None, window, cx, |selections| {
17980 selections.select_ranges(new_selected_ranges)
17981 });
17982 this.backspace(&Default::default(), window, cx);
17983 }
17984
17985 this.handle_input(text, window, cx);
17986 });
17987
17988 if let Some(transaction) = self.ime_transaction {
17989 self.buffer.update(cx, |buffer, cx| {
17990 buffer.group_until_transaction(transaction, cx);
17991 });
17992 }
17993
17994 self.unmark_text(window, cx);
17995 }
17996
17997 fn replace_and_mark_text_in_range(
17998 &mut self,
17999 range_utf16: Option<Range<usize>>,
18000 text: &str,
18001 new_selected_range_utf16: Option<Range<usize>>,
18002 window: &mut Window,
18003 cx: &mut Context<Self>,
18004 ) {
18005 if !self.input_enabled {
18006 return;
18007 }
18008
18009 let transaction = self.transact(window, cx, |this, window, cx| {
18010 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
18011 let snapshot = this.buffer.read(cx).read(cx);
18012 if let Some(relative_range_utf16) = range_utf16.as_ref() {
18013 for marked_range in &mut marked_ranges {
18014 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
18015 marked_range.start.0 += relative_range_utf16.start;
18016 marked_range.start =
18017 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
18018 marked_range.end =
18019 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
18020 }
18021 }
18022 Some(marked_ranges)
18023 } else if let Some(range_utf16) = range_utf16 {
18024 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18025 Some(this.selection_replacement_ranges(range_utf16, cx))
18026 } else {
18027 None
18028 };
18029
18030 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
18031 let newest_selection_id = this.selections.newest_anchor().id;
18032 this.selections
18033 .all::<OffsetUtf16>(cx)
18034 .iter()
18035 .zip(ranges_to_replace.iter())
18036 .find_map(|(selection, range)| {
18037 if selection.id == newest_selection_id {
18038 Some(
18039 (range.start.0 as isize - selection.head().0 as isize)
18040 ..(range.end.0 as isize - selection.head().0 as isize),
18041 )
18042 } else {
18043 None
18044 }
18045 })
18046 });
18047
18048 cx.emit(EditorEvent::InputHandled {
18049 utf16_range_to_replace: range_to_replace,
18050 text: text.into(),
18051 });
18052
18053 if let Some(ranges) = ranges_to_replace {
18054 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18055 }
18056
18057 let marked_ranges = {
18058 let snapshot = this.buffer.read(cx).read(cx);
18059 this.selections
18060 .disjoint_anchors()
18061 .iter()
18062 .map(|selection| {
18063 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18064 })
18065 .collect::<Vec<_>>()
18066 };
18067
18068 if text.is_empty() {
18069 this.unmark_text(window, cx);
18070 } else {
18071 this.highlight_text::<InputComposition>(
18072 marked_ranges.clone(),
18073 HighlightStyle {
18074 underline: Some(UnderlineStyle {
18075 thickness: px(1.),
18076 color: None,
18077 wavy: false,
18078 }),
18079 ..Default::default()
18080 },
18081 cx,
18082 );
18083 }
18084
18085 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18086 let use_autoclose = this.use_autoclose;
18087 let use_auto_surround = this.use_auto_surround;
18088 this.set_use_autoclose(false);
18089 this.set_use_auto_surround(false);
18090 this.handle_input(text, window, cx);
18091 this.set_use_autoclose(use_autoclose);
18092 this.set_use_auto_surround(use_auto_surround);
18093
18094 if let Some(new_selected_range) = new_selected_range_utf16 {
18095 let snapshot = this.buffer.read(cx).read(cx);
18096 let new_selected_ranges = marked_ranges
18097 .into_iter()
18098 .map(|marked_range| {
18099 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
18100 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
18101 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
18102 snapshot.clip_offset_utf16(new_start, Bias::Left)
18103 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
18104 })
18105 .collect::<Vec<_>>();
18106
18107 drop(snapshot);
18108 this.change_selections(None, window, cx, |selections| {
18109 selections.select_ranges(new_selected_ranges)
18110 });
18111 }
18112 });
18113
18114 self.ime_transaction = self.ime_transaction.or(transaction);
18115 if let Some(transaction) = self.ime_transaction {
18116 self.buffer.update(cx, |buffer, cx| {
18117 buffer.group_until_transaction(transaction, cx);
18118 });
18119 }
18120
18121 if self.text_highlights::<InputComposition>(cx).is_none() {
18122 self.ime_transaction.take();
18123 }
18124 }
18125
18126 fn bounds_for_range(
18127 &mut self,
18128 range_utf16: Range<usize>,
18129 element_bounds: gpui::Bounds<Pixels>,
18130 window: &mut Window,
18131 cx: &mut Context<Self>,
18132 ) -> Option<gpui::Bounds<Pixels>> {
18133 let text_layout_details = self.text_layout_details(window);
18134 let gpui::Size {
18135 width: em_width,
18136 height: line_height,
18137 } = self.character_size(window);
18138
18139 let snapshot = self.snapshot(window, cx);
18140 let scroll_position = snapshot.scroll_position();
18141 let scroll_left = scroll_position.x * em_width;
18142
18143 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
18144 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
18145 + self.gutter_dimensions.width
18146 + self.gutter_dimensions.margin;
18147 let y = line_height * (start.row().as_f32() - scroll_position.y);
18148
18149 Some(Bounds {
18150 origin: element_bounds.origin + point(x, y),
18151 size: size(em_width, line_height),
18152 })
18153 }
18154
18155 fn character_index_for_point(
18156 &mut self,
18157 point: gpui::Point<Pixels>,
18158 _window: &mut Window,
18159 _cx: &mut Context<Self>,
18160 ) -> Option<usize> {
18161 let position_map = self.last_position_map.as_ref()?;
18162 if !position_map.text_hitbox.contains(&point) {
18163 return None;
18164 }
18165 let display_point = position_map.point_for_position(point).previous_valid;
18166 let anchor = position_map
18167 .snapshot
18168 .display_point_to_anchor(display_point, Bias::Left);
18169 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18170 Some(utf16_offset.0)
18171 }
18172}
18173
18174trait SelectionExt {
18175 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18176 fn spanned_rows(
18177 &self,
18178 include_end_if_at_line_start: bool,
18179 map: &DisplaySnapshot,
18180 ) -> Range<MultiBufferRow>;
18181}
18182
18183impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18184 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18185 let start = self
18186 .start
18187 .to_point(&map.buffer_snapshot)
18188 .to_display_point(map);
18189 let end = self
18190 .end
18191 .to_point(&map.buffer_snapshot)
18192 .to_display_point(map);
18193 if self.reversed {
18194 end..start
18195 } else {
18196 start..end
18197 }
18198 }
18199
18200 fn spanned_rows(
18201 &self,
18202 include_end_if_at_line_start: bool,
18203 map: &DisplaySnapshot,
18204 ) -> Range<MultiBufferRow> {
18205 let start = self.start.to_point(&map.buffer_snapshot);
18206 let mut end = self.end.to_point(&map.buffer_snapshot);
18207 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18208 end.row -= 1;
18209 }
18210
18211 let buffer_start = map.prev_line_boundary(start).0;
18212 let buffer_end = map.next_line_boundary(end).0;
18213 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18214 }
18215}
18216
18217impl<T: InvalidationRegion> InvalidationStack<T> {
18218 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18219 where
18220 S: Clone + ToOffset,
18221 {
18222 while let Some(region) = self.last() {
18223 let all_selections_inside_invalidation_ranges =
18224 if selections.len() == region.ranges().len() {
18225 selections
18226 .iter()
18227 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18228 .all(|(selection, invalidation_range)| {
18229 let head = selection.head().to_offset(buffer);
18230 invalidation_range.start <= head && invalidation_range.end >= head
18231 })
18232 } else {
18233 false
18234 };
18235
18236 if all_selections_inside_invalidation_ranges {
18237 break;
18238 } else {
18239 self.pop();
18240 }
18241 }
18242 }
18243}
18244
18245impl<T> Default for InvalidationStack<T> {
18246 fn default() -> Self {
18247 Self(Default::default())
18248 }
18249}
18250
18251impl<T> Deref for InvalidationStack<T> {
18252 type Target = Vec<T>;
18253
18254 fn deref(&self) -> &Self::Target {
18255 &self.0
18256 }
18257}
18258
18259impl<T> DerefMut for InvalidationStack<T> {
18260 fn deref_mut(&mut self) -> &mut Self::Target {
18261 &mut self.0
18262 }
18263}
18264
18265impl InvalidationRegion for SnippetState {
18266 fn ranges(&self) -> &[Range<Anchor>] {
18267 &self.ranges[self.active_index]
18268 }
18269}
18270
18271pub fn diagnostic_block_renderer(
18272 diagnostic: Diagnostic,
18273 max_message_rows: Option<u8>,
18274 allow_closing: bool,
18275) -> RenderBlock {
18276 let (text_without_backticks, code_ranges) =
18277 highlight_diagnostic_message(&diagnostic, max_message_rows);
18278
18279 Arc::new(move |cx: &mut BlockContext| {
18280 let group_id: SharedString = cx.block_id.to_string().into();
18281
18282 let mut text_style = cx.window.text_style().clone();
18283 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18284 let theme_settings = ThemeSettings::get_global(cx);
18285 text_style.font_family = theme_settings.buffer_font.family.clone();
18286 text_style.font_style = theme_settings.buffer_font.style;
18287 text_style.font_features = theme_settings.buffer_font.features.clone();
18288 text_style.font_weight = theme_settings.buffer_font.weight;
18289
18290 let multi_line_diagnostic = diagnostic.message.contains('\n');
18291
18292 let buttons = |diagnostic: &Diagnostic| {
18293 if multi_line_diagnostic {
18294 v_flex()
18295 } else {
18296 h_flex()
18297 }
18298 .when(allow_closing, |div| {
18299 div.children(diagnostic.is_primary.then(|| {
18300 IconButton::new("close-block", IconName::XCircle)
18301 .icon_color(Color::Muted)
18302 .size(ButtonSize::Compact)
18303 .style(ButtonStyle::Transparent)
18304 .visible_on_hover(group_id.clone())
18305 .on_click(move |_click, window, cx| {
18306 window.dispatch_action(Box::new(Cancel), cx)
18307 })
18308 .tooltip(|window, cx| {
18309 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18310 })
18311 }))
18312 })
18313 .child(
18314 IconButton::new("copy-block", IconName::Copy)
18315 .icon_color(Color::Muted)
18316 .size(ButtonSize::Compact)
18317 .style(ButtonStyle::Transparent)
18318 .visible_on_hover(group_id.clone())
18319 .on_click({
18320 let message = diagnostic.message.clone();
18321 move |_click, _, cx| {
18322 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18323 }
18324 })
18325 .tooltip(Tooltip::text("Copy diagnostic message")),
18326 )
18327 };
18328
18329 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18330 AvailableSpace::min_size(),
18331 cx.window,
18332 cx.app,
18333 );
18334
18335 h_flex()
18336 .id(cx.block_id)
18337 .group(group_id.clone())
18338 .relative()
18339 .size_full()
18340 .block_mouse_down()
18341 .pl(cx.gutter_dimensions.width)
18342 .w(cx.max_width - cx.gutter_dimensions.full_width())
18343 .child(
18344 div()
18345 .flex()
18346 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18347 .flex_shrink(),
18348 )
18349 .child(buttons(&diagnostic))
18350 .child(div().flex().flex_shrink_0().child(
18351 StyledText::new(text_without_backticks.clone()).with_default_highlights(
18352 &text_style,
18353 code_ranges.iter().map(|range| {
18354 (
18355 range.clone(),
18356 HighlightStyle {
18357 font_weight: Some(FontWeight::BOLD),
18358 ..Default::default()
18359 },
18360 )
18361 }),
18362 ),
18363 ))
18364 .into_any_element()
18365 })
18366}
18367
18368fn inline_completion_edit_text(
18369 current_snapshot: &BufferSnapshot,
18370 edits: &[(Range<Anchor>, String)],
18371 edit_preview: &EditPreview,
18372 include_deletions: bool,
18373 cx: &App,
18374) -> HighlightedText {
18375 let edits = edits
18376 .iter()
18377 .map(|(anchor, text)| {
18378 (
18379 anchor.start.text_anchor..anchor.end.text_anchor,
18380 text.clone(),
18381 )
18382 })
18383 .collect::<Vec<_>>();
18384
18385 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18386}
18387
18388pub fn highlight_diagnostic_message(
18389 diagnostic: &Diagnostic,
18390 mut max_message_rows: Option<u8>,
18391) -> (SharedString, Vec<Range<usize>>) {
18392 let mut text_without_backticks = String::new();
18393 let mut code_ranges = Vec::new();
18394
18395 if let Some(source) = &diagnostic.source {
18396 text_without_backticks.push_str(source);
18397 code_ranges.push(0..source.len());
18398 text_without_backticks.push_str(": ");
18399 }
18400
18401 let mut prev_offset = 0;
18402 let mut in_code_block = false;
18403 let has_row_limit = max_message_rows.is_some();
18404 let mut newline_indices = diagnostic
18405 .message
18406 .match_indices('\n')
18407 .filter(|_| has_row_limit)
18408 .map(|(ix, _)| ix)
18409 .fuse()
18410 .peekable();
18411
18412 for (quote_ix, _) in diagnostic
18413 .message
18414 .match_indices('`')
18415 .chain([(diagnostic.message.len(), "")])
18416 {
18417 let mut first_newline_ix = None;
18418 let mut last_newline_ix = None;
18419 while let Some(newline_ix) = newline_indices.peek() {
18420 if *newline_ix < quote_ix {
18421 if first_newline_ix.is_none() {
18422 first_newline_ix = Some(*newline_ix);
18423 }
18424 last_newline_ix = Some(*newline_ix);
18425
18426 if let Some(rows_left) = &mut max_message_rows {
18427 if *rows_left == 0 {
18428 break;
18429 } else {
18430 *rows_left -= 1;
18431 }
18432 }
18433 let _ = newline_indices.next();
18434 } else {
18435 break;
18436 }
18437 }
18438 let prev_len = text_without_backticks.len();
18439 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18440 text_without_backticks.push_str(new_text);
18441 if in_code_block {
18442 code_ranges.push(prev_len..text_without_backticks.len());
18443 }
18444 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18445 in_code_block = !in_code_block;
18446 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18447 text_without_backticks.push_str("...");
18448 break;
18449 }
18450 }
18451
18452 (text_without_backticks.into(), code_ranges)
18453}
18454
18455fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18456 match severity {
18457 DiagnosticSeverity::ERROR => colors.error,
18458 DiagnosticSeverity::WARNING => colors.warning,
18459 DiagnosticSeverity::INFORMATION => colors.info,
18460 DiagnosticSeverity::HINT => colors.info,
18461 _ => colors.ignored,
18462 }
18463}
18464
18465pub fn styled_runs_for_code_label<'a>(
18466 label: &'a CodeLabel,
18467 syntax_theme: &'a theme::SyntaxTheme,
18468) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18469 let fade_out = HighlightStyle {
18470 fade_out: Some(0.35),
18471 ..Default::default()
18472 };
18473
18474 let mut prev_end = label.filter_range.end;
18475 label
18476 .runs
18477 .iter()
18478 .enumerate()
18479 .flat_map(move |(ix, (range, highlight_id))| {
18480 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18481 style
18482 } else {
18483 return Default::default();
18484 };
18485 let mut muted_style = style;
18486 muted_style.highlight(fade_out);
18487
18488 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18489 if range.start >= label.filter_range.end {
18490 if range.start > prev_end {
18491 runs.push((prev_end..range.start, fade_out));
18492 }
18493 runs.push((range.clone(), muted_style));
18494 } else if range.end <= label.filter_range.end {
18495 runs.push((range.clone(), style));
18496 } else {
18497 runs.push((range.start..label.filter_range.end, style));
18498 runs.push((label.filter_range.end..range.end, muted_style));
18499 }
18500 prev_end = cmp::max(prev_end, range.end);
18501
18502 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18503 runs.push((prev_end..label.text.len(), fade_out));
18504 }
18505
18506 runs
18507 })
18508}
18509
18510pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18511 let mut prev_index = 0;
18512 let mut prev_codepoint: Option<char> = None;
18513 text.char_indices()
18514 .chain([(text.len(), '\0')])
18515 .filter_map(move |(index, codepoint)| {
18516 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18517 let is_boundary = index == text.len()
18518 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18519 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18520 if is_boundary {
18521 let chunk = &text[prev_index..index];
18522 prev_index = index;
18523 Some(chunk)
18524 } else {
18525 None
18526 }
18527 })
18528}
18529
18530pub trait RangeToAnchorExt: Sized {
18531 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18532
18533 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18534 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18535 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18536 }
18537}
18538
18539impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18540 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18541 let start_offset = self.start.to_offset(snapshot);
18542 let end_offset = self.end.to_offset(snapshot);
18543 if start_offset == end_offset {
18544 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18545 } else {
18546 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18547 }
18548 }
18549}
18550
18551pub trait RowExt {
18552 fn as_f32(&self) -> f32;
18553
18554 fn next_row(&self) -> Self;
18555
18556 fn previous_row(&self) -> Self;
18557
18558 fn minus(&self, other: Self) -> u32;
18559}
18560
18561impl RowExt for DisplayRow {
18562 fn as_f32(&self) -> f32 {
18563 self.0 as f32
18564 }
18565
18566 fn next_row(&self) -> Self {
18567 Self(self.0 + 1)
18568 }
18569
18570 fn previous_row(&self) -> Self {
18571 Self(self.0.saturating_sub(1))
18572 }
18573
18574 fn minus(&self, other: Self) -> u32 {
18575 self.0 - other.0
18576 }
18577}
18578
18579impl RowExt for MultiBufferRow {
18580 fn as_f32(&self) -> f32 {
18581 self.0 as f32
18582 }
18583
18584 fn next_row(&self) -> Self {
18585 Self(self.0 + 1)
18586 }
18587
18588 fn previous_row(&self) -> Self {
18589 Self(self.0.saturating_sub(1))
18590 }
18591
18592 fn minus(&self, other: Self) -> u32 {
18593 self.0 - other.0
18594 }
18595}
18596
18597trait RowRangeExt {
18598 type Row;
18599
18600 fn len(&self) -> usize;
18601
18602 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18603}
18604
18605impl RowRangeExt for Range<MultiBufferRow> {
18606 type Row = MultiBufferRow;
18607
18608 fn len(&self) -> usize {
18609 (self.end.0 - self.start.0) as usize
18610 }
18611
18612 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18613 (self.start.0..self.end.0).map(MultiBufferRow)
18614 }
18615}
18616
18617impl RowRangeExt for Range<DisplayRow> {
18618 type Row = DisplayRow;
18619
18620 fn len(&self) -> usize {
18621 (self.end.0 - self.start.0) as usize
18622 }
18623
18624 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18625 (self.start.0..self.end.0).map(DisplayRow)
18626 }
18627}
18628
18629/// If select range has more than one line, we
18630/// just point the cursor to range.start.
18631fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18632 if range.start.row == range.end.row {
18633 range
18634 } else {
18635 range.start..range.start
18636 }
18637}
18638pub struct KillRing(ClipboardItem);
18639impl Global for KillRing {}
18640
18641const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18642
18643fn all_edits_insertions_or_deletions(
18644 edits: &Vec<(Range<Anchor>, String)>,
18645 snapshot: &MultiBufferSnapshot,
18646) -> bool {
18647 let mut all_insertions = true;
18648 let mut all_deletions = true;
18649
18650 for (range, new_text) in edits.iter() {
18651 let range_is_empty = range.to_offset(&snapshot).is_empty();
18652 let text_is_empty = new_text.is_empty();
18653
18654 if range_is_empty != text_is_empty {
18655 if range_is_empty {
18656 all_deletions = false;
18657 } else {
18658 all_insertions = false;
18659 }
18660 } else {
18661 return false;
18662 }
18663
18664 if !all_insertions && !all_deletions {
18665 return false;
18666 }
18667 }
18668 all_insertions || all_deletions
18669}
18670
18671struct MissingEditPredictionKeybindingTooltip;
18672
18673impl Render for MissingEditPredictionKeybindingTooltip {
18674 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18675 ui::tooltip_container(window, cx, |container, _, cx| {
18676 container
18677 .flex_shrink_0()
18678 .max_w_80()
18679 .min_h(rems_from_px(124.))
18680 .justify_between()
18681 .child(
18682 v_flex()
18683 .flex_1()
18684 .text_ui_sm(cx)
18685 .child(Label::new("Conflict with Accept Keybinding"))
18686 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18687 )
18688 .child(
18689 h_flex()
18690 .pb_1()
18691 .gap_1()
18692 .items_end()
18693 .w_full()
18694 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18695 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18696 }))
18697 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18698 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18699 })),
18700 )
18701 })
18702 }
18703}
18704
18705#[derive(Debug, Clone, Copy, PartialEq)]
18706pub struct LineHighlight {
18707 pub background: Background,
18708 pub border: Option<gpui::Hsla>,
18709}
18710
18711impl From<Hsla> for LineHighlight {
18712 fn from(hsla: Hsla) -> Self {
18713 Self {
18714 background: hsla.into(),
18715 border: None,
18716 }
18717 }
18718}
18719
18720impl From<Background> for LineHighlight {
18721 fn from(background: Background) -> Self {
18722 Self {
18723 background,
18724 border: None,
18725 }
18726 }
18727}