1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod jsx_tag_auto_close;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51pub(crate) use actions::*;
52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use buffer_diff::DiffHunkStatus;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{
72 future::{self, Shared},
73 FutureExt,
74};
75use fuzzy::StringMatchCandidate;
76
77use ::git::Restore;
78use code_context_menus::{
79 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
80 CompletionsMenu, ContextMenuOrigin,
81};
82use git::blame::GitBlame;
83use gpui::{
84 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
85 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
86 ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler,
87 EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
88 HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
89 ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
90 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
91 WeakEntity, WeakFocusHandle, Window,
92};
93use highlight_matching_bracket::refresh_matching_bracket_highlights;
94use hover_popover::{hide_hover, HoverState};
95use indent_guides::ActiveIndentGuidesState;
96use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
97pub use inline_completion::Direction;
98use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
99pub use items::MAX_TAB_TITLE_LEN;
100use itertools::Itertools;
101use language::{
102 language_settings::{
103 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
104 },
105 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
106 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
107 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
108 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
109};
110use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
111use linked_editing_ranges::refresh_linked_ranges;
112use mouse_context_menu::MouseContextMenu;
113use persistence::DB;
114pub use proposed_changes_editor::{
115 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
116};
117use smallvec::smallvec;
118use std::iter::Peekable;
119use task::{ResolvedTask, TaskTemplate, TaskVariables};
120
121use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
122pub use lsp::CompletionContext;
123use lsp::{
124 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
125 InsertTextFormat, LanguageServerId, LanguageServerName,
126};
127
128use language::BufferSnapshot;
129use movement::TextLayoutDetails;
130pub use multi_buffer::{
131 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
132 ToOffset, ToPoint,
133};
134use multi_buffer::{
135 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
136 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
137};
138use project::{
139 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
140 project_settings::{GitGutterSetting, ProjectSettings},
141 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
142 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
143 TaskSourceKind,
144};
145use rand::prelude::*;
146use rpc::{proto::*, ErrorExt};
147use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
148use selections_collection::{
149 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
150};
151use serde::{Deserialize, Serialize};
152use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
153use smallvec::SmallVec;
154use snippet::Snippet;
155use std::{
156 any::TypeId,
157 borrow::Cow,
158 cell::RefCell,
159 cmp::{self, Ordering, Reverse},
160 mem,
161 num::NonZeroU32,
162 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
163 path::{Path, PathBuf},
164 rc::Rc,
165 sync::Arc,
166 time::{Duration, Instant},
167};
168pub use sum_tree::Bias;
169use sum_tree::TreeMap;
170use text::{BufferId, OffsetUtf16, Rope};
171use theme::{
172 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
173 ThemeColors, ThemeSettings,
174};
175use ui::{
176 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
177 Tooltip,
178};
179use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
180use workspace::{
181 item::{ItemHandle, PreviewTabsSettings},
182 ItemId, RestoreOnStartupBehavior,
183};
184use workspace::{
185 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
186 WorkspaceSettings,
187};
188use workspace::{
189 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
190};
191use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
192
193use crate::hover_links::{find_url, find_url_from_range};
194use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
195
196pub const FILE_HEADER_HEIGHT: u32 = 2;
197pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
198pub const MULTI_BUFFER_EXCERPT_FOOTER_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#[derive(Debug, Copy, Clone, PartialEq, Eq)]
611pub enum IsVimMode {
612 Yes,
613 No,
614}
615
616/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
617///
618/// See the [module level documentation](self) for more information.
619pub struct Editor {
620 focus_handle: FocusHandle,
621 last_focused_descendant: Option<WeakFocusHandle>,
622 /// The text buffer being edited
623 buffer: Entity<MultiBuffer>,
624 /// Map of how text in the buffer should be displayed.
625 /// Handles soft wraps, folds, fake inlay text insertions, etc.
626 pub display_map: Entity<DisplayMap>,
627 pub selections: SelectionsCollection,
628 pub scroll_manager: ScrollManager,
629 /// When inline assist editors are linked, they all render cursors because
630 /// typing enters text into each of them, even the ones that aren't focused.
631 pub(crate) show_cursor_when_unfocused: bool,
632 columnar_selection_tail: Option<Anchor>,
633 add_selections_state: Option<AddSelectionsState>,
634 select_next_state: Option<SelectNextState>,
635 select_prev_state: Option<SelectNextState>,
636 selection_history: SelectionHistory,
637 autoclose_regions: Vec<AutocloseRegion>,
638 snippet_stack: InvalidationStack<SnippetState>,
639 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
640 ime_transaction: Option<TransactionId>,
641 active_diagnostics: Option<ActiveDiagnosticGroup>,
642 show_inline_diagnostics: bool,
643 inline_diagnostics_update: Task<()>,
644 inline_diagnostics_enabled: bool,
645 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
646 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
647
648 // TODO: make this a access method
649 pub project: Option<Entity<Project>>,
650 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
651 completion_provider: Option<Box<dyn CompletionProvider>>,
652 collaboration_hub: Option<Box<dyn CollaborationHub>>,
653 blink_manager: Entity<BlinkManager>,
654 show_cursor_names: bool,
655 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
656 pub show_local_selections: bool,
657 mode: EditorMode,
658 show_breadcrumbs: bool,
659 show_gutter: bool,
660 show_scrollbars: bool,
661 show_line_numbers: Option<bool>,
662 use_relative_line_numbers: Option<bool>,
663 show_git_diff_gutter: Option<bool>,
664 show_code_actions: Option<bool>,
665 show_runnables: Option<bool>,
666 show_wrap_guides: Option<bool>,
667 show_indent_guides: Option<bool>,
668 placeholder_text: Option<Arc<str>>,
669 highlight_order: usize,
670 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
671 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
672 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
673 scrollbar_marker_state: ScrollbarMarkerState,
674 active_indent_guides_state: ActiveIndentGuidesState,
675 nav_history: Option<ItemNavHistory>,
676 context_menu: RefCell<Option<CodeContextMenu>>,
677 mouse_context_menu: Option<MouseContextMenu>,
678 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
679 signature_help_state: SignatureHelpState,
680 auto_signature_help: Option<bool>,
681 find_all_references_task_sources: Vec<Anchor>,
682 next_completion_id: CompletionId,
683 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
684 code_actions_task: Option<Task<Result<()>>>,
685 selection_highlight_task: Option<Task<()>>,
686 document_highlights_task: Option<Task<()>>,
687 linked_editing_range_task: Option<Task<Option<()>>>,
688 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
689 pending_rename: Option<RenameState>,
690 searchable: bool,
691 cursor_shape: CursorShape,
692 current_line_highlight: Option<CurrentLineHighlight>,
693 collapse_matches: bool,
694 autoindent_mode: Option<AutoindentMode>,
695 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
696 input_enabled: bool,
697 use_modal_editing: bool,
698 read_only: bool,
699 leader_peer_id: Option<PeerId>,
700 remote_id: Option<ViewId>,
701 hover_state: HoverState,
702 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
703 gutter_hovered: bool,
704 hovered_link_state: Option<HoveredLinkState>,
705 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
706 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
707 active_inline_completion: Option<InlineCompletionState>,
708 /// Used to prevent flickering as the user types while the menu is open
709 stale_inline_completion_in_menu: Option<InlineCompletionState>,
710 edit_prediction_settings: EditPredictionSettings,
711 inline_completions_hidden_for_vim_mode: bool,
712 show_inline_completions_override: Option<bool>,
713 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
714 edit_prediction_preview: EditPredictionPreview,
715 edit_prediction_indent_conflict: bool,
716 edit_prediction_requires_modifier_in_indent_conflict: bool,
717 inlay_hint_cache: InlayHintCache,
718 next_inlay_id: usize,
719 _subscriptions: Vec<Subscription>,
720 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
721 gutter_dimensions: GutterDimensions,
722 style: Option<EditorStyle>,
723 text_style_refinement: Option<TextStyleRefinement>,
724 next_editor_action_id: EditorActionId,
725 editor_actions:
726 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
727 use_autoclose: bool,
728 use_auto_surround: bool,
729 auto_replace_emoji_shortcode: bool,
730 jsx_tag_auto_close_enabled_in_any_buffer: bool,
731 show_git_blame_gutter: bool,
732 show_git_blame_inline: bool,
733 show_git_blame_inline_delay_task: Option<Task<()>>,
734 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
735 git_blame_inline_enabled: bool,
736 serialize_dirty_buffers: bool,
737 show_selection_menu: Option<bool>,
738 blame: Option<Entity<GitBlame>>,
739 blame_subscription: Option<Subscription>,
740 custom_context_menu: Option<
741 Box<
742 dyn 'static
743 + Fn(
744 &mut Self,
745 DisplayPoint,
746 &mut Window,
747 &mut Context<Self>,
748 ) -> Option<Entity<ui::ContextMenu>>,
749 >,
750 >,
751 last_bounds: Option<Bounds<Pixels>>,
752 last_position_map: Option<Rc<PositionMap>>,
753 expect_bounds_change: Option<Bounds<Pixels>>,
754 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
755 tasks_update_task: Option<Task<()>>,
756 in_project_search: bool,
757 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
758 breadcrumb_header: Option<String>,
759 focused_block: Option<FocusedBlock>,
760 next_scroll_position: NextScrollCursorCenterTopBottom,
761 addons: HashMap<TypeId, Box<dyn Addon>>,
762 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
763 load_diff_task: Option<Shared<Task<()>>>,
764 selection_mark_mode: bool,
765 toggle_fold_multiple_buffers: Task<()>,
766 _scroll_cursor_center_top_bottom_task: Task<()>,
767 serialize_selections: Task<()>,
768}
769
770#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
771enum NextScrollCursorCenterTopBottom {
772 #[default]
773 Center,
774 Top,
775 Bottom,
776}
777
778impl NextScrollCursorCenterTopBottom {
779 fn next(&self) -> Self {
780 match self {
781 Self::Center => Self::Top,
782 Self::Top => Self::Bottom,
783 Self::Bottom => Self::Center,
784 }
785 }
786}
787
788#[derive(Clone)]
789pub struct EditorSnapshot {
790 pub mode: EditorMode,
791 show_gutter: bool,
792 show_line_numbers: Option<bool>,
793 show_git_diff_gutter: Option<bool>,
794 show_code_actions: Option<bool>,
795 show_runnables: Option<bool>,
796 git_blame_gutter_max_author_length: Option<usize>,
797 pub display_snapshot: DisplaySnapshot,
798 pub placeholder_text: Option<Arc<str>>,
799 is_focused: bool,
800 scroll_anchor: ScrollAnchor,
801 ongoing_scroll: OngoingScroll,
802 current_line_highlight: CurrentLineHighlight,
803 gutter_hovered: bool,
804}
805
806const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
807
808#[derive(Default, Debug, Clone, Copy)]
809pub struct GutterDimensions {
810 pub left_padding: Pixels,
811 pub right_padding: Pixels,
812 pub width: Pixels,
813 pub margin: Pixels,
814 pub git_blame_entries_width: Option<Pixels>,
815}
816
817impl GutterDimensions {
818 /// The full width of the space taken up by the gutter.
819 pub fn full_width(&self) -> Pixels {
820 self.margin + self.width
821 }
822
823 /// The width of the space reserved for the fold indicators,
824 /// use alongside 'justify_end' and `gutter_width` to
825 /// right align content with the line numbers
826 pub fn fold_area_width(&self) -> Pixels {
827 self.margin + self.right_padding
828 }
829}
830
831#[derive(Debug)]
832pub struct RemoteSelection {
833 pub replica_id: ReplicaId,
834 pub selection: Selection<Anchor>,
835 pub cursor_shape: CursorShape,
836 pub peer_id: PeerId,
837 pub line_mode: bool,
838 pub participant_index: Option<ParticipantIndex>,
839 pub user_name: Option<SharedString>,
840}
841
842#[derive(Clone, Debug)]
843struct SelectionHistoryEntry {
844 selections: Arc<[Selection<Anchor>]>,
845 select_next_state: Option<SelectNextState>,
846 select_prev_state: Option<SelectNextState>,
847 add_selections_state: Option<AddSelectionsState>,
848}
849
850enum SelectionHistoryMode {
851 Normal,
852 Undoing,
853 Redoing,
854}
855
856#[derive(Clone, PartialEq, Eq, Hash)]
857struct HoveredCursor {
858 replica_id: u16,
859 selection_id: usize,
860}
861
862impl Default for SelectionHistoryMode {
863 fn default() -> Self {
864 Self::Normal
865 }
866}
867
868#[derive(Default)]
869struct SelectionHistory {
870 #[allow(clippy::type_complexity)]
871 selections_by_transaction:
872 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
873 mode: SelectionHistoryMode,
874 undo_stack: VecDeque<SelectionHistoryEntry>,
875 redo_stack: VecDeque<SelectionHistoryEntry>,
876}
877
878impl SelectionHistory {
879 fn insert_transaction(
880 &mut self,
881 transaction_id: TransactionId,
882 selections: Arc<[Selection<Anchor>]>,
883 ) {
884 self.selections_by_transaction
885 .insert(transaction_id, (selections, None));
886 }
887
888 #[allow(clippy::type_complexity)]
889 fn transaction(
890 &self,
891 transaction_id: TransactionId,
892 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
893 self.selections_by_transaction.get(&transaction_id)
894 }
895
896 #[allow(clippy::type_complexity)]
897 fn transaction_mut(
898 &mut self,
899 transaction_id: TransactionId,
900 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
901 self.selections_by_transaction.get_mut(&transaction_id)
902 }
903
904 fn push(&mut self, entry: SelectionHistoryEntry) {
905 if !entry.selections.is_empty() {
906 match self.mode {
907 SelectionHistoryMode::Normal => {
908 self.push_undo(entry);
909 self.redo_stack.clear();
910 }
911 SelectionHistoryMode::Undoing => self.push_redo(entry),
912 SelectionHistoryMode::Redoing => self.push_undo(entry),
913 }
914 }
915 }
916
917 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
918 if self
919 .undo_stack
920 .back()
921 .map_or(true, |e| e.selections != entry.selections)
922 {
923 self.undo_stack.push_back(entry);
924 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
925 self.undo_stack.pop_front();
926 }
927 }
928 }
929
930 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
931 if self
932 .redo_stack
933 .back()
934 .map_or(true, |e| e.selections != entry.selections)
935 {
936 self.redo_stack.push_back(entry);
937 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
938 self.redo_stack.pop_front();
939 }
940 }
941 }
942}
943
944struct RowHighlight {
945 index: usize,
946 range: Range<Anchor>,
947 color: Hsla,
948 should_autoscroll: bool,
949}
950
951#[derive(Clone, Debug)]
952struct AddSelectionsState {
953 above: bool,
954 stack: Vec<usize>,
955}
956
957#[derive(Clone)]
958struct SelectNextState {
959 query: AhoCorasick,
960 wordwise: bool,
961 done: bool,
962}
963
964impl std::fmt::Debug for SelectNextState {
965 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
966 f.debug_struct(std::any::type_name::<Self>())
967 .field("wordwise", &self.wordwise)
968 .field("done", &self.done)
969 .finish()
970 }
971}
972
973#[derive(Debug)]
974struct AutocloseRegion {
975 selection_id: usize,
976 range: Range<Anchor>,
977 pair: BracketPair,
978}
979
980#[derive(Debug)]
981struct SnippetState {
982 ranges: Vec<Vec<Range<Anchor>>>,
983 active_index: usize,
984 choices: Vec<Option<Vec<String>>>,
985}
986
987#[doc(hidden)]
988pub struct RenameState {
989 pub range: Range<Anchor>,
990 pub old_name: Arc<str>,
991 pub editor: Entity<Editor>,
992 block_id: CustomBlockId,
993}
994
995struct InvalidationStack<T>(Vec<T>);
996
997struct RegisteredInlineCompletionProvider {
998 provider: Arc<dyn InlineCompletionProviderHandle>,
999 _subscription: Subscription,
1000}
1001
1002#[derive(Debug, PartialEq, Eq)]
1003struct ActiveDiagnosticGroup {
1004 primary_range: Range<Anchor>,
1005 primary_message: String,
1006 group_id: usize,
1007 blocks: HashMap<CustomBlockId, Diagnostic>,
1008 is_valid: bool,
1009}
1010
1011#[derive(Serialize, Deserialize, Clone, Debug)]
1012pub struct ClipboardSelection {
1013 /// The number of bytes in this selection.
1014 pub len: usize,
1015 /// Whether this was a full-line selection.
1016 pub is_entire_line: bool,
1017 /// The indentation of the first line when this content was originally copied.
1018 pub first_line_indent: u32,
1019}
1020
1021#[derive(Debug)]
1022pub(crate) struct NavigationData {
1023 cursor_anchor: Anchor,
1024 cursor_position: Point,
1025 scroll_anchor: ScrollAnchor,
1026 scroll_top_row: u32,
1027}
1028
1029#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1030pub enum GotoDefinitionKind {
1031 Symbol,
1032 Declaration,
1033 Type,
1034 Implementation,
1035}
1036
1037#[derive(Debug, Clone)]
1038enum InlayHintRefreshReason {
1039 ModifiersChanged(bool),
1040 Toggle(bool),
1041 SettingsChange(InlayHintSettings),
1042 NewLinesShown,
1043 BufferEdited(HashSet<Arc<Language>>),
1044 RefreshRequested,
1045 ExcerptsRemoved(Vec<ExcerptId>),
1046}
1047
1048impl InlayHintRefreshReason {
1049 fn description(&self) -> &'static str {
1050 match self {
1051 Self::ModifiersChanged(_) => "modifiers changed",
1052 Self::Toggle(_) => "toggle",
1053 Self::SettingsChange(_) => "settings change",
1054 Self::NewLinesShown => "new lines shown",
1055 Self::BufferEdited(_) => "buffer edited",
1056 Self::RefreshRequested => "refresh requested",
1057 Self::ExcerptsRemoved(_) => "excerpts removed",
1058 }
1059 }
1060}
1061
1062pub enum FormatTarget {
1063 Buffers,
1064 Ranges(Vec<Range<MultiBufferPoint>>),
1065}
1066
1067pub(crate) struct FocusedBlock {
1068 id: BlockId,
1069 focus_handle: WeakFocusHandle,
1070}
1071
1072#[derive(Clone)]
1073enum JumpData {
1074 MultiBufferRow {
1075 row: MultiBufferRow,
1076 line_offset_from_top: u32,
1077 },
1078 MultiBufferPoint {
1079 excerpt_id: ExcerptId,
1080 position: Point,
1081 anchor: text::Anchor,
1082 line_offset_from_top: u32,
1083 },
1084}
1085
1086pub enum MultibufferSelectionMode {
1087 First,
1088 All,
1089}
1090
1091impl Editor {
1092 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1093 let buffer = cx.new(|cx| Buffer::local("", cx));
1094 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1095 Self::new(
1096 EditorMode::SingleLine { auto_width: false },
1097 buffer,
1098 None,
1099 false,
1100 window,
1101 cx,
1102 )
1103 }
1104
1105 pub fn multi_line(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(EditorMode::Full, buffer, None, false, window, cx)
1109 }
1110
1111 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1112 let buffer = cx.new(|cx| Buffer::local("", cx));
1113 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1114 Self::new(
1115 EditorMode::SingleLine { auto_width: true },
1116 buffer,
1117 None,
1118 false,
1119 window,
1120 cx,
1121 )
1122 }
1123
1124 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1125 let buffer = cx.new(|cx| Buffer::local("", cx));
1126 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1127 Self::new(
1128 EditorMode::AutoHeight { max_lines },
1129 buffer,
1130 None,
1131 false,
1132 window,
1133 cx,
1134 )
1135 }
1136
1137 pub fn for_buffer(
1138 buffer: Entity<Buffer>,
1139 project: Option<Entity<Project>>,
1140 window: &mut Window,
1141 cx: &mut Context<Self>,
1142 ) -> Self {
1143 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1144 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1145 }
1146
1147 pub fn for_multibuffer(
1148 buffer: Entity<MultiBuffer>,
1149 project: Option<Entity<Project>>,
1150 show_excerpt_controls: bool,
1151 window: &mut Window,
1152 cx: &mut Context<Self>,
1153 ) -> Self {
1154 Self::new(
1155 EditorMode::Full,
1156 buffer,
1157 project,
1158 show_excerpt_controls,
1159 window,
1160 cx,
1161 )
1162 }
1163
1164 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1165 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1166 let mut clone = Self::new(
1167 self.mode,
1168 self.buffer.clone(),
1169 self.project.clone(),
1170 show_excerpt_controls,
1171 window,
1172 cx,
1173 );
1174 self.display_map.update(cx, |display_map, cx| {
1175 let snapshot = display_map.snapshot(cx);
1176 clone.display_map.update(cx, |display_map, cx| {
1177 display_map.set_state(&snapshot, cx);
1178 });
1179 });
1180 clone.selections.clone_state(&self.selections);
1181 clone.scroll_manager.clone_state(&self.scroll_manager);
1182 clone.searchable = self.searchable;
1183 clone
1184 }
1185
1186 pub fn new(
1187 mode: EditorMode,
1188 buffer: Entity<MultiBuffer>,
1189 project: Option<Entity<Project>>,
1190 show_excerpt_controls: bool,
1191 window: &mut Window,
1192 cx: &mut Context<Self>,
1193 ) -> Self {
1194 let style = window.text_style();
1195 let font_size = style.font_size.to_pixels(window.rem_size());
1196 let editor = cx.entity().downgrade();
1197 let fold_placeholder = FoldPlaceholder {
1198 constrain_width: true,
1199 render: Arc::new(move |fold_id, fold_range, cx| {
1200 let editor = editor.clone();
1201 div()
1202 .id(fold_id)
1203 .bg(cx.theme().colors().ghost_element_background)
1204 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1205 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1206 .rounded_xs()
1207 .size_full()
1208 .cursor_pointer()
1209 .child("⋯")
1210 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1211 .on_click(move |_, _window, cx| {
1212 editor
1213 .update(cx, |editor, cx| {
1214 editor.unfold_ranges(
1215 &[fold_range.start..fold_range.end],
1216 true,
1217 false,
1218 cx,
1219 );
1220 cx.stop_propagation();
1221 })
1222 .ok();
1223 })
1224 .into_any()
1225 }),
1226 merge_adjacent: true,
1227 ..Default::default()
1228 };
1229 let display_map = cx.new(|cx| {
1230 DisplayMap::new(
1231 buffer.clone(),
1232 style.font(),
1233 font_size,
1234 None,
1235 show_excerpt_controls,
1236 FILE_HEADER_HEIGHT,
1237 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1238 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1239 fold_placeholder,
1240 cx,
1241 )
1242 });
1243
1244 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1245
1246 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1247
1248 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1249 .then(|| language_settings::SoftWrap::None);
1250
1251 let mut project_subscriptions = Vec::new();
1252 if mode == EditorMode::Full {
1253 if let Some(project) = project.as_ref() {
1254 project_subscriptions.push(cx.subscribe_in(
1255 project,
1256 window,
1257 |editor, _, event, window, cx| {
1258 if let project::Event::RefreshInlayHints = event {
1259 editor
1260 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1261 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1262 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1263 let focus_handle = editor.focus_handle(cx);
1264 if focus_handle.is_focused(window) {
1265 let snapshot = buffer.read(cx).snapshot();
1266 for (range, snippet) in snippet_edits {
1267 let editor_range =
1268 language::range_from_lsp(*range).to_offset(&snapshot);
1269 editor
1270 .insert_snippet(
1271 &[editor_range],
1272 snippet.clone(),
1273 window,
1274 cx,
1275 )
1276 .ok();
1277 }
1278 }
1279 }
1280 }
1281 },
1282 ));
1283 if let Some(task_inventory) = project
1284 .read(cx)
1285 .task_store()
1286 .read(cx)
1287 .task_inventory()
1288 .cloned()
1289 {
1290 project_subscriptions.push(cx.observe_in(
1291 &task_inventory,
1292 window,
1293 |editor, _, window, cx| {
1294 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1295 },
1296 ));
1297 }
1298 }
1299 }
1300
1301 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1302
1303 let inlay_hint_settings =
1304 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1305 let focus_handle = cx.focus_handle();
1306 cx.on_focus(&focus_handle, window, Self::handle_focus)
1307 .detach();
1308 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1309 .detach();
1310 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1311 .detach();
1312 cx.on_blur(&focus_handle, window, Self::handle_blur)
1313 .detach();
1314
1315 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1316 Some(false)
1317 } else {
1318 None
1319 };
1320
1321 let mut code_action_providers = Vec::new();
1322 let mut load_uncommitted_diff = None;
1323 if let Some(project) = project.clone() {
1324 load_uncommitted_diff = Some(
1325 get_uncommitted_diff_for_buffer(
1326 &project,
1327 buffer.read(cx).all_buffers(),
1328 buffer.clone(),
1329 cx,
1330 )
1331 .shared(),
1332 );
1333 code_action_providers.push(Rc::new(project) as Rc<_>);
1334 }
1335
1336 let mut this = Self {
1337 focus_handle,
1338 show_cursor_when_unfocused: false,
1339 last_focused_descendant: None,
1340 buffer: buffer.clone(),
1341 display_map: display_map.clone(),
1342 selections,
1343 scroll_manager: ScrollManager::new(cx),
1344 columnar_selection_tail: None,
1345 add_selections_state: None,
1346 select_next_state: None,
1347 select_prev_state: None,
1348 selection_history: Default::default(),
1349 autoclose_regions: Default::default(),
1350 snippet_stack: Default::default(),
1351 select_larger_syntax_node_stack: Vec::new(),
1352 ime_transaction: Default::default(),
1353 active_diagnostics: None,
1354 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1355 inline_diagnostics_update: Task::ready(()),
1356 inline_diagnostics: Vec::new(),
1357 soft_wrap_mode_override,
1358 completion_provider: project.clone().map(|project| Box::new(project) as _),
1359 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1360 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1361 project,
1362 blink_manager: blink_manager.clone(),
1363 show_local_selections: true,
1364 show_scrollbars: true,
1365 mode,
1366 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1367 show_gutter: mode == EditorMode::Full,
1368 show_line_numbers: None,
1369 use_relative_line_numbers: None,
1370 show_git_diff_gutter: None,
1371 show_code_actions: None,
1372 show_runnables: None,
1373 show_wrap_guides: None,
1374 show_indent_guides,
1375 placeholder_text: None,
1376 highlight_order: 0,
1377 highlighted_rows: HashMap::default(),
1378 background_highlights: Default::default(),
1379 gutter_highlights: TreeMap::default(),
1380 scrollbar_marker_state: ScrollbarMarkerState::default(),
1381 active_indent_guides_state: ActiveIndentGuidesState::default(),
1382 nav_history: None,
1383 context_menu: RefCell::new(None),
1384 mouse_context_menu: None,
1385 completion_tasks: Default::default(),
1386 signature_help_state: SignatureHelpState::default(),
1387 auto_signature_help: None,
1388 find_all_references_task_sources: Vec::new(),
1389 next_completion_id: 0,
1390 next_inlay_id: 0,
1391 code_action_providers,
1392 available_code_actions: Default::default(),
1393 code_actions_task: Default::default(),
1394 selection_highlight_task: Default::default(),
1395 document_highlights_task: Default::default(),
1396 linked_editing_range_task: Default::default(),
1397 pending_rename: Default::default(),
1398 searchable: true,
1399 cursor_shape: EditorSettings::get_global(cx)
1400 .cursor_shape
1401 .unwrap_or_default(),
1402 current_line_highlight: None,
1403 autoindent_mode: Some(AutoindentMode::EachLine),
1404 collapse_matches: false,
1405 workspace: None,
1406 input_enabled: true,
1407 use_modal_editing: mode == EditorMode::Full,
1408 read_only: false,
1409 use_autoclose: true,
1410 use_auto_surround: true,
1411 auto_replace_emoji_shortcode: false,
1412 jsx_tag_auto_close_enabled_in_any_buffer: false,
1413 leader_peer_id: None,
1414 remote_id: None,
1415 hover_state: Default::default(),
1416 pending_mouse_down: None,
1417 hovered_link_state: Default::default(),
1418 edit_prediction_provider: None,
1419 active_inline_completion: None,
1420 stale_inline_completion_in_menu: None,
1421 edit_prediction_preview: EditPredictionPreview::Inactive {
1422 released_too_fast: false,
1423 },
1424 inline_diagnostics_enabled: mode == EditorMode::Full,
1425 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1426
1427 gutter_hovered: false,
1428 pixel_position_of_newest_cursor: None,
1429 last_bounds: None,
1430 last_position_map: None,
1431 expect_bounds_change: None,
1432 gutter_dimensions: GutterDimensions::default(),
1433 style: None,
1434 show_cursor_names: false,
1435 hovered_cursors: Default::default(),
1436 next_editor_action_id: EditorActionId::default(),
1437 editor_actions: Rc::default(),
1438 inline_completions_hidden_for_vim_mode: false,
1439 show_inline_completions_override: None,
1440 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1441 edit_prediction_settings: EditPredictionSettings::Disabled,
1442 edit_prediction_indent_conflict: false,
1443 edit_prediction_requires_modifier_in_indent_conflict: true,
1444 custom_context_menu: None,
1445 show_git_blame_gutter: false,
1446 show_git_blame_inline: false,
1447 show_selection_menu: None,
1448 show_git_blame_inline_delay_task: None,
1449 git_blame_inline_tooltip: None,
1450 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1451 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1452 .session
1453 .restore_unsaved_buffers,
1454 blame: None,
1455 blame_subscription: None,
1456 tasks: Default::default(),
1457 _subscriptions: vec![
1458 cx.observe(&buffer, Self::on_buffer_changed),
1459 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1460 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1461 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1462 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1463 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1464 cx.observe_window_activation(window, |editor, window, cx| {
1465 let active = window.is_window_active();
1466 editor.blink_manager.update(cx, |blink_manager, cx| {
1467 if active {
1468 blink_manager.enable(cx);
1469 } else {
1470 blink_manager.disable(cx);
1471 }
1472 });
1473 }),
1474 ],
1475 tasks_update_task: None,
1476 linked_edit_ranges: Default::default(),
1477 in_project_search: false,
1478 previous_search_ranges: None,
1479 breadcrumb_header: None,
1480 focused_block: None,
1481 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1482 addons: HashMap::default(),
1483 registered_buffers: HashMap::default(),
1484 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1485 selection_mark_mode: false,
1486 toggle_fold_multiple_buffers: Task::ready(()),
1487 serialize_selections: Task::ready(()),
1488 text_style_refinement: None,
1489 load_diff_task: load_uncommitted_diff,
1490 };
1491 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1492 this._subscriptions.extend(project_subscriptions);
1493
1494 this.end_selection(window, cx);
1495 this.scroll_manager.show_scrollbar(window, cx);
1496 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1497
1498 if mode == EditorMode::Full {
1499 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1500 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1501
1502 if this.git_blame_inline_enabled {
1503 this.git_blame_inline_enabled = true;
1504 this.start_git_blame_inline(false, window, cx);
1505 }
1506
1507 if let Some(buffer) = buffer.read(cx).as_singleton() {
1508 if let Some(project) = this.project.as_ref() {
1509 let handle = project.update(cx, |project, cx| {
1510 project.register_buffer_with_language_servers(&buffer, cx)
1511 });
1512 this.registered_buffers
1513 .insert(buffer.read(cx).remote_id(), handle);
1514 }
1515 }
1516 }
1517
1518 this.report_editor_event("Editor Opened", None, cx);
1519 this
1520 }
1521
1522 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1523 self.mouse_context_menu
1524 .as_ref()
1525 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1526 }
1527
1528 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1529 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1530 }
1531
1532 fn key_context_internal(
1533 &self,
1534 has_active_edit_prediction: bool,
1535 window: &Window,
1536 cx: &App,
1537 ) -> KeyContext {
1538 let mut key_context = KeyContext::new_with_defaults();
1539 key_context.add("Editor");
1540 let mode = match self.mode {
1541 EditorMode::SingleLine { .. } => "single_line",
1542 EditorMode::AutoHeight { .. } => "auto_height",
1543 EditorMode::Full => "full",
1544 };
1545
1546 if EditorSettings::jupyter_enabled(cx) {
1547 key_context.add("jupyter");
1548 }
1549
1550 key_context.set("mode", mode);
1551 if self.pending_rename.is_some() {
1552 key_context.add("renaming");
1553 }
1554
1555 match self.context_menu.borrow().as_ref() {
1556 Some(CodeContextMenu::Completions(_)) => {
1557 key_context.add("menu");
1558 key_context.add("showing_completions");
1559 }
1560 Some(CodeContextMenu::CodeActions(_)) => {
1561 key_context.add("menu");
1562 key_context.add("showing_code_actions")
1563 }
1564 None => {}
1565 }
1566
1567 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1568 if !self.focus_handle(cx).contains_focused(window, cx)
1569 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1570 {
1571 for addon in self.addons.values() {
1572 addon.extend_key_context(&mut key_context, cx)
1573 }
1574 }
1575
1576 if let Some(extension) = self
1577 .buffer
1578 .read(cx)
1579 .as_singleton()
1580 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1581 {
1582 key_context.set("extension", extension.to_string());
1583 }
1584
1585 if has_active_edit_prediction {
1586 if self.edit_prediction_in_conflict() {
1587 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1588 } else {
1589 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1590 key_context.add("copilot_suggestion");
1591 }
1592 }
1593
1594 if self.selection_mark_mode {
1595 key_context.add("selection_mode");
1596 }
1597
1598 key_context
1599 }
1600
1601 pub fn edit_prediction_in_conflict(&self) -> bool {
1602 if !self.show_edit_predictions_in_menu() {
1603 return false;
1604 }
1605
1606 let showing_completions = self
1607 .context_menu
1608 .borrow()
1609 .as_ref()
1610 .map_or(false, |context| {
1611 matches!(context, CodeContextMenu::Completions(_))
1612 });
1613
1614 showing_completions
1615 || self.edit_prediction_requires_modifier()
1616 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1617 // bindings to insert tab characters.
1618 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1619 }
1620
1621 pub fn accept_edit_prediction_keybind(
1622 &self,
1623 window: &Window,
1624 cx: &App,
1625 ) -> AcceptEditPredictionBinding {
1626 let key_context = self.key_context_internal(true, window, cx);
1627 let in_conflict = self.edit_prediction_in_conflict();
1628
1629 AcceptEditPredictionBinding(
1630 window
1631 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1632 .into_iter()
1633 .filter(|binding| {
1634 !in_conflict
1635 || binding
1636 .keystrokes()
1637 .first()
1638 .map_or(false, |keystroke| keystroke.modifiers.modified())
1639 })
1640 .rev()
1641 .min_by_key(|binding| {
1642 binding
1643 .keystrokes()
1644 .first()
1645 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1646 }),
1647 )
1648 }
1649
1650 pub fn new_file(
1651 workspace: &mut Workspace,
1652 _: &workspace::NewFile,
1653 window: &mut Window,
1654 cx: &mut Context<Workspace>,
1655 ) {
1656 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1657 "Failed to create buffer",
1658 window,
1659 cx,
1660 |e, _, _| match e.error_code() {
1661 ErrorCode::RemoteUpgradeRequired => Some(format!(
1662 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1663 e.error_tag("required").unwrap_or("the latest version")
1664 )),
1665 _ => None,
1666 },
1667 );
1668 }
1669
1670 pub fn new_in_workspace(
1671 workspace: &mut Workspace,
1672 window: &mut Window,
1673 cx: &mut Context<Workspace>,
1674 ) -> Task<Result<Entity<Editor>>> {
1675 let project = workspace.project().clone();
1676 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1677
1678 cx.spawn_in(window, |workspace, mut cx| async move {
1679 let buffer = create.await?;
1680 workspace.update_in(&mut cx, |workspace, window, cx| {
1681 let editor =
1682 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1683 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1684 editor
1685 })
1686 })
1687 }
1688
1689 fn new_file_vertical(
1690 workspace: &mut Workspace,
1691 _: &workspace::NewFileSplitVertical,
1692 window: &mut Window,
1693 cx: &mut Context<Workspace>,
1694 ) {
1695 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1696 }
1697
1698 fn new_file_horizontal(
1699 workspace: &mut Workspace,
1700 _: &workspace::NewFileSplitHorizontal,
1701 window: &mut Window,
1702 cx: &mut Context<Workspace>,
1703 ) {
1704 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1705 }
1706
1707 fn new_file_in_direction(
1708 workspace: &mut Workspace,
1709 direction: SplitDirection,
1710 window: &mut Window,
1711 cx: &mut Context<Workspace>,
1712 ) {
1713 let project = workspace.project().clone();
1714 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1715
1716 cx.spawn_in(window, |workspace, mut cx| async move {
1717 let buffer = create.await?;
1718 workspace.update_in(&mut cx, move |workspace, window, cx| {
1719 workspace.split_item(
1720 direction,
1721 Box::new(
1722 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1723 ),
1724 window,
1725 cx,
1726 )
1727 })?;
1728 anyhow::Ok(())
1729 })
1730 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1731 match e.error_code() {
1732 ErrorCode::RemoteUpgradeRequired => Some(format!(
1733 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1734 e.error_tag("required").unwrap_or("the latest version")
1735 )),
1736 _ => None,
1737 }
1738 });
1739 }
1740
1741 pub fn leader_peer_id(&self) -> Option<PeerId> {
1742 self.leader_peer_id
1743 }
1744
1745 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1746 &self.buffer
1747 }
1748
1749 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1750 self.workspace.as_ref()?.0.upgrade()
1751 }
1752
1753 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1754 self.buffer().read(cx).title(cx)
1755 }
1756
1757 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1758 let git_blame_gutter_max_author_length = self
1759 .render_git_blame_gutter(cx)
1760 .then(|| {
1761 if let Some(blame) = self.blame.as_ref() {
1762 let max_author_length =
1763 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1764 Some(max_author_length)
1765 } else {
1766 None
1767 }
1768 })
1769 .flatten();
1770
1771 EditorSnapshot {
1772 mode: self.mode,
1773 show_gutter: self.show_gutter,
1774 show_line_numbers: self.show_line_numbers,
1775 show_git_diff_gutter: self.show_git_diff_gutter,
1776 show_code_actions: self.show_code_actions,
1777 show_runnables: self.show_runnables,
1778 git_blame_gutter_max_author_length,
1779 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1780 scroll_anchor: self.scroll_manager.anchor(),
1781 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1782 placeholder_text: self.placeholder_text.clone(),
1783 is_focused: self.focus_handle.is_focused(window),
1784 current_line_highlight: self
1785 .current_line_highlight
1786 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1787 gutter_hovered: self.gutter_hovered,
1788 }
1789 }
1790
1791 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1792 self.buffer.read(cx).language_at(point, cx)
1793 }
1794
1795 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1796 self.buffer.read(cx).read(cx).file_at(point).cloned()
1797 }
1798
1799 pub fn active_excerpt(
1800 &self,
1801 cx: &App,
1802 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1803 self.buffer
1804 .read(cx)
1805 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1806 }
1807
1808 pub fn mode(&self) -> EditorMode {
1809 self.mode
1810 }
1811
1812 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1813 self.collaboration_hub.as_deref()
1814 }
1815
1816 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1817 self.collaboration_hub = Some(hub);
1818 }
1819
1820 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1821 self.in_project_search = in_project_search;
1822 }
1823
1824 pub fn set_custom_context_menu(
1825 &mut self,
1826 f: impl 'static
1827 + Fn(
1828 &mut Self,
1829 DisplayPoint,
1830 &mut Window,
1831 &mut Context<Self>,
1832 ) -> Option<Entity<ui::ContextMenu>>,
1833 ) {
1834 self.custom_context_menu = Some(Box::new(f))
1835 }
1836
1837 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1838 self.completion_provider = provider;
1839 }
1840
1841 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1842 self.semantics_provider.clone()
1843 }
1844
1845 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1846 self.semantics_provider = provider;
1847 }
1848
1849 pub fn set_edit_prediction_provider<T>(
1850 &mut self,
1851 provider: Option<Entity<T>>,
1852 window: &mut Window,
1853 cx: &mut Context<Self>,
1854 ) where
1855 T: EditPredictionProvider,
1856 {
1857 self.edit_prediction_provider =
1858 provider.map(|provider| RegisteredInlineCompletionProvider {
1859 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1860 if this.focus_handle.is_focused(window) {
1861 this.update_visible_inline_completion(window, cx);
1862 }
1863 }),
1864 provider: Arc::new(provider),
1865 });
1866 self.update_edit_prediction_settings(cx);
1867 self.refresh_inline_completion(false, false, window, cx);
1868 }
1869
1870 pub fn placeholder_text(&self) -> Option<&str> {
1871 self.placeholder_text.as_deref()
1872 }
1873
1874 pub fn set_placeholder_text(
1875 &mut self,
1876 placeholder_text: impl Into<Arc<str>>,
1877 cx: &mut Context<Self>,
1878 ) {
1879 let placeholder_text = Some(placeholder_text.into());
1880 if self.placeholder_text != placeholder_text {
1881 self.placeholder_text = placeholder_text;
1882 cx.notify();
1883 }
1884 }
1885
1886 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1887 self.cursor_shape = cursor_shape;
1888
1889 // Disrupt blink for immediate user feedback that the cursor shape has changed
1890 self.blink_manager.update(cx, BlinkManager::show_cursor);
1891
1892 cx.notify();
1893 }
1894
1895 pub fn set_current_line_highlight(
1896 &mut self,
1897 current_line_highlight: Option<CurrentLineHighlight>,
1898 ) {
1899 self.current_line_highlight = current_line_highlight;
1900 }
1901
1902 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1903 self.collapse_matches = collapse_matches;
1904 }
1905
1906 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1907 let buffers = self.buffer.read(cx).all_buffers();
1908 let Some(project) = self.project.as_ref() else {
1909 return;
1910 };
1911 project.update(cx, |project, cx| {
1912 for buffer in buffers {
1913 self.registered_buffers
1914 .entry(buffer.read(cx).remote_id())
1915 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1916 }
1917 })
1918 }
1919
1920 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1921 if self.collapse_matches {
1922 return range.start..range.start;
1923 }
1924 range.clone()
1925 }
1926
1927 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1928 if self.display_map.read(cx).clip_at_line_ends != clip {
1929 self.display_map
1930 .update(cx, |map, _| map.clip_at_line_ends = clip);
1931 }
1932 }
1933
1934 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1935 self.input_enabled = input_enabled;
1936 }
1937
1938 pub fn set_inline_completions_hidden_for_vim_mode(
1939 &mut self,
1940 hidden: bool,
1941 window: &mut Window,
1942 cx: &mut Context<Self>,
1943 ) {
1944 if hidden != self.inline_completions_hidden_for_vim_mode {
1945 self.inline_completions_hidden_for_vim_mode = hidden;
1946 if hidden {
1947 self.update_visible_inline_completion(window, cx);
1948 } else {
1949 self.refresh_inline_completion(true, false, window, cx);
1950 }
1951 }
1952 }
1953
1954 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1955 self.menu_inline_completions_policy = value;
1956 }
1957
1958 pub fn set_autoindent(&mut self, autoindent: bool) {
1959 if autoindent {
1960 self.autoindent_mode = Some(AutoindentMode::EachLine);
1961 } else {
1962 self.autoindent_mode = None;
1963 }
1964 }
1965
1966 pub fn read_only(&self, cx: &App) -> bool {
1967 self.read_only || self.buffer.read(cx).read_only()
1968 }
1969
1970 pub fn set_read_only(&mut self, read_only: bool) {
1971 self.read_only = read_only;
1972 }
1973
1974 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1975 self.use_autoclose = autoclose;
1976 }
1977
1978 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1979 self.use_auto_surround = auto_surround;
1980 }
1981
1982 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1983 self.auto_replace_emoji_shortcode = auto_replace;
1984 }
1985
1986 pub fn toggle_edit_predictions(
1987 &mut self,
1988 _: &ToggleEditPrediction,
1989 window: &mut Window,
1990 cx: &mut Context<Self>,
1991 ) {
1992 if self.show_inline_completions_override.is_some() {
1993 self.set_show_edit_predictions(None, window, cx);
1994 } else {
1995 let show_edit_predictions = !self.edit_predictions_enabled();
1996 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
1997 }
1998 }
1999
2000 pub fn set_show_edit_predictions(
2001 &mut self,
2002 show_edit_predictions: Option<bool>,
2003 window: &mut Window,
2004 cx: &mut Context<Self>,
2005 ) {
2006 self.show_inline_completions_override = show_edit_predictions;
2007 self.update_edit_prediction_settings(cx);
2008
2009 if let Some(false) = show_edit_predictions {
2010 self.discard_inline_completion(false, cx);
2011 } else {
2012 self.refresh_inline_completion(false, true, window, cx);
2013 }
2014 }
2015
2016 fn inline_completions_disabled_in_scope(
2017 &self,
2018 buffer: &Entity<Buffer>,
2019 buffer_position: language::Anchor,
2020 cx: &App,
2021 ) -> bool {
2022 let snapshot = buffer.read(cx).snapshot();
2023 let settings = snapshot.settings_at(buffer_position, cx);
2024
2025 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2026 return false;
2027 };
2028
2029 scope.override_name().map_or(false, |scope_name| {
2030 settings
2031 .edit_predictions_disabled_in
2032 .iter()
2033 .any(|s| s == scope_name)
2034 })
2035 }
2036
2037 pub fn set_use_modal_editing(&mut self, to: bool) {
2038 self.use_modal_editing = to;
2039 }
2040
2041 pub fn use_modal_editing(&self) -> bool {
2042 self.use_modal_editing
2043 }
2044
2045 fn selections_did_change(
2046 &mut self,
2047 local: bool,
2048 old_cursor_position: &Anchor,
2049 show_completions: bool,
2050 window: &mut Window,
2051 cx: &mut Context<Self>,
2052 ) {
2053 window.invalidate_character_coordinates();
2054
2055 // Copy selections to primary selection buffer
2056 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2057 if local {
2058 let selections = self.selections.all::<usize>(cx);
2059 let buffer_handle = self.buffer.read(cx).read(cx);
2060
2061 let mut text = String::new();
2062 for (index, selection) in selections.iter().enumerate() {
2063 let text_for_selection = buffer_handle
2064 .text_for_range(selection.start..selection.end)
2065 .collect::<String>();
2066
2067 text.push_str(&text_for_selection);
2068 if index != selections.len() - 1 {
2069 text.push('\n');
2070 }
2071 }
2072
2073 if !text.is_empty() {
2074 cx.write_to_primary(ClipboardItem::new_string(text));
2075 }
2076 }
2077
2078 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2079 self.buffer.update(cx, |buffer, cx| {
2080 buffer.set_active_selections(
2081 &self.selections.disjoint_anchors(),
2082 self.selections.line_mode,
2083 self.cursor_shape,
2084 cx,
2085 )
2086 });
2087 }
2088 let display_map = self
2089 .display_map
2090 .update(cx, |display_map, cx| display_map.snapshot(cx));
2091 let buffer = &display_map.buffer_snapshot;
2092 self.add_selections_state = None;
2093 self.select_next_state = None;
2094 self.select_prev_state = None;
2095 self.select_larger_syntax_node_stack.clear();
2096 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2097 self.snippet_stack
2098 .invalidate(&self.selections.disjoint_anchors(), buffer);
2099 self.take_rename(false, window, cx);
2100
2101 let new_cursor_position = self.selections.newest_anchor().head();
2102
2103 self.push_to_nav_history(
2104 *old_cursor_position,
2105 Some(new_cursor_position.to_point(buffer)),
2106 cx,
2107 );
2108
2109 if local {
2110 let new_cursor_position = self.selections.newest_anchor().head();
2111 let mut context_menu = self.context_menu.borrow_mut();
2112 let completion_menu = match context_menu.as_ref() {
2113 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2114 _ => {
2115 *context_menu = None;
2116 None
2117 }
2118 };
2119 if let Some(buffer_id) = new_cursor_position.buffer_id {
2120 if !self.registered_buffers.contains_key(&buffer_id) {
2121 if let Some(project) = self.project.as_ref() {
2122 project.update(cx, |project, cx| {
2123 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2124 return;
2125 };
2126 self.registered_buffers.insert(
2127 buffer_id,
2128 project.register_buffer_with_language_servers(&buffer, cx),
2129 );
2130 })
2131 }
2132 }
2133 }
2134
2135 if let Some(completion_menu) = completion_menu {
2136 let cursor_position = new_cursor_position.to_offset(buffer);
2137 let (word_range, kind) =
2138 buffer.surrounding_word(completion_menu.initial_position, true);
2139 if kind == Some(CharKind::Word)
2140 && word_range.to_inclusive().contains(&cursor_position)
2141 {
2142 let mut completion_menu = completion_menu.clone();
2143 drop(context_menu);
2144
2145 let query = Self::completion_query(buffer, cursor_position);
2146 cx.spawn(move |this, mut cx| async move {
2147 completion_menu
2148 .filter(query.as_deref(), cx.background_executor().clone())
2149 .await;
2150
2151 this.update(&mut cx, |this, cx| {
2152 let mut context_menu = this.context_menu.borrow_mut();
2153 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2154 else {
2155 return;
2156 };
2157
2158 if menu.id > completion_menu.id {
2159 return;
2160 }
2161
2162 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2163 drop(context_menu);
2164 cx.notify();
2165 })
2166 })
2167 .detach();
2168
2169 if show_completions {
2170 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2171 }
2172 } else {
2173 drop(context_menu);
2174 self.hide_context_menu(window, cx);
2175 }
2176 } else {
2177 drop(context_menu);
2178 }
2179
2180 hide_hover(self, cx);
2181
2182 if old_cursor_position.to_display_point(&display_map).row()
2183 != new_cursor_position.to_display_point(&display_map).row()
2184 {
2185 self.available_code_actions.take();
2186 }
2187 self.refresh_code_actions(window, cx);
2188 self.refresh_document_highlights(cx);
2189 self.refresh_selected_text_highlights(window, cx);
2190 refresh_matching_bracket_highlights(self, window, cx);
2191 self.update_visible_inline_completion(window, cx);
2192 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2193 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2194 if self.git_blame_inline_enabled {
2195 self.start_inline_blame_timer(window, cx);
2196 }
2197 }
2198
2199 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2200 cx.emit(EditorEvent::SelectionsChanged { local });
2201
2202 let selections = &self.selections.disjoint;
2203 if selections.len() == 1 {
2204 cx.emit(SearchEvent::ActiveMatchChanged)
2205 }
2206 if local
2207 && self.is_singleton(cx)
2208 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2209 {
2210 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2211 let background_executor = cx.background_executor().clone();
2212 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2213 let snapshot = self.buffer().read(cx).snapshot(cx);
2214 let selections = selections.clone();
2215 self.serialize_selections = cx.background_spawn(async move {
2216 background_executor.timer(Duration::from_millis(100)).await;
2217 let selections = selections
2218 .iter()
2219 .map(|selection| {
2220 (
2221 selection.start.to_offset(&snapshot),
2222 selection.end.to_offset(&snapshot),
2223 )
2224 })
2225 .collect();
2226 DB.save_editor_selections(editor_id, workspace_id, selections)
2227 .await
2228 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2229 .log_err();
2230 });
2231 }
2232 }
2233
2234 cx.notify();
2235 }
2236
2237 pub fn sync_selections(
2238 &mut self,
2239 other: Entity<Editor>,
2240 cx: &mut Context<Self>,
2241 ) -> gpui::Subscription {
2242 let other_selections = other.read(cx).selections.disjoint.to_vec();
2243 self.selections.change_with(cx, |selections| {
2244 selections.select_anchors(other_selections);
2245 });
2246
2247 let other_subscription =
2248 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2249 EditorEvent::SelectionsChanged { local: true } => {
2250 let other_selections = other.read(cx).selections.disjoint.to_vec();
2251 if other_selections.is_empty() {
2252 return;
2253 }
2254 this.selections.change_with(cx, |selections| {
2255 selections.select_anchors(other_selections);
2256 });
2257 }
2258 _ => {}
2259 });
2260
2261 let this_subscription =
2262 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2263 EditorEvent::SelectionsChanged { local: true } => {
2264 let these_selections = this.selections.disjoint.to_vec();
2265 if these_selections.is_empty() {
2266 return;
2267 }
2268 other.update(cx, |other_editor, cx| {
2269 other_editor.selections.change_with(cx, |selections| {
2270 selections.select_anchors(these_selections);
2271 })
2272 });
2273 }
2274 _ => {}
2275 });
2276
2277 Subscription::join(other_subscription, this_subscription)
2278 }
2279
2280 pub fn change_selections<R>(
2281 &mut self,
2282 autoscroll: Option<Autoscroll>,
2283 window: &mut Window,
2284 cx: &mut Context<Self>,
2285 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2286 ) -> R {
2287 self.change_selections_inner(autoscroll, true, window, cx, change)
2288 }
2289
2290 fn change_selections_inner<R>(
2291 &mut self,
2292 autoscroll: Option<Autoscroll>,
2293 request_completions: bool,
2294 window: &mut Window,
2295 cx: &mut Context<Self>,
2296 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2297 ) -> R {
2298 let old_cursor_position = self.selections.newest_anchor().head();
2299 self.push_to_selection_history();
2300
2301 let (changed, result) = self.selections.change_with(cx, change);
2302
2303 if changed {
2304 if let Some(autoscroll) = autoscroll {
2305 self.request_autoscroll(autoscroll, cx);
2306 }
2307 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2308
2309 if self.should_open_signature_help_automatically(
2310 &old_cursor_position,
2311 self.signature_help_state.backspace_pressed(),
2312 cx,
2313 ) {
2314 self.show_signature_help(&ShowSignatureHelp, window, cx);
2315 }
2316 self.signature_help_state.set_backspace_pressed(false);
2317 }
2318
2319 result
2320 }
2321
2322 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2323 where
2324 I: IntoIterator<Item = (Range<S>, T)>,
2325 S: ToOffset,
2326 T: Into<Arc<str>>,
2327 {
2328 if self.read_only(cx) {
2329 return;
2330 }
2331
2332 self.buffer
2333 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2334 }
2335
2336 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2337 where
2338 I: IntoIterator<Item = (Range<S>, T)>,
2339 S: ToOffset,
2340 T: Into<Arc<str>>,
2341 {
2342 if self.read_only(cx) {
2343 return;
2344 }
2345
2346 self.buffer.update(cx, |buffer, cx| {
2347 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2348 });
2349 }
2350
2351 pub fn edit_with_block_indent<I, S, T>(
2352 &mut self,
2353 edits: I,
2354 original_indent_columns: Vec<Option<u32>>,
2355 cx: &mut Context<Self>,
2356 ) where
2357 I: IntoIterator<Item = (Range<S>, T)>,
2358 S: ToOffset,
2359 T: Into<Arc<str>>,
2360 {
2361 if self.read_only(cx) {
2362 return;
2363 }
2364
2365 self.buffer.update(cx, |buffer, cx| {
2366 buffer.edit(
2367 edits,
2368 Some(AutoindentMode::Block {
2369 original_indent_columns,
2370 }),
2371 cx,
2372 )
2373 });
2374 }
2375
2376 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2377 self.hide_context_menu(window, cx);
2378
2379 match phase {
2380 SelectPhase::Begin {
2381 position,
2382 add,
2383 click_count,
2384 } => self.begin_selection(position, add, click_count, window, cx),
2385 SelectPhase::BeginColumnar {
2386 position,
2387 goal_column,
2388 reset,
2389 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2390 SelectPhase::Extend {
2391 position,
2392 click_count,
2393 } => self.extend_selection(position, click_count, window, cx),
2394 SelectPhase::Update {
2395 position,
2396 goal_column,
2397 scroll_delta,
2398 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2399 SelectPhase::End => self.end_selection(window, cx),
2400 }
2401 }
2402
2403 fn extend_selection(
2404 &mut self,
2405 position: DisplayPoint,
2406 click_count: usize,
2407 window: &mut Window,
2408 cx: &mut Context<Self>,
2409 ) {
2410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2411 let tail = self.selections.newest::<usize>(cx).tail();
2412 self.begin_selection(position, false, click_count, window, cx);
2413
2414 let position = position.to_offset(&display_map, Bias::Left);
2415 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2416
2417 let mut pending_selection = self
2418 .selections
2419 .pending_anchor()
2420 .expect("extend_selection not called with pending selection");
2421 if position >= tail {
2422 pending_selection.start = tail_anchor;
2423 } else {
2424 pending_selection.end = tail_anchor;
2425 pending_selection.reversed = true;
2426 }
2427
2428 let mut pending_mode = self.selections.pending_mode().unwrap();
2429 match &mut pending_mode {
2430 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2431 _ => {}
2432 }
2433
2434 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2435 s.set_pending(pending_selection, pending_mode)
2436 });
2437 }
2438
2439 fn begin_selection(
2440 &mut self,
2441 position: DisplayPoint,
2442 add: bool,
2443 click_count: usize,
2444 window: &mut Window,
2445 cx: &mut Context<Self>,
2446 ) {
2447 if !self.focus_handle.is_focused(window) {
2448 self.last_focused_descendant = None;
2449 window.focus(&self.focus_handle);
2450 }
2451
2452 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2453 let buffer = &display_map.buffer_snapshot;
2454 let newest_selection = self.selections.newest_anchor().clone();
2455 let position = display_map.clip_point(position, Bias::Left);
2456
2457 let start;
2458 let end;
2459 let mode;
2460 let mut auto_scroll;
2461 match click_count {
2462 1 => {
2463 start = buffer.anchor_before(position.to_point(&display_map));
2464 end = start;
2465 mode = SelectMode::Character;
2466 auto_scroll = true;
2467 }
2468 2 => {
2469 let range = movement::surrounding_word(&display_map, position);
2470 start = buffer.anchor_before(range.start.to_point(&display_map));
2471 end = buffer.anchor_before(range.end.to_point(&display_map));
2472 mode = SelectMode::Word(start..end);
2473 auto_scroll = true;
2474 }
2475 3 => {
2476 let position = display_map
2477 .clip_point(position, Bias::Left)
2478 .to_point(&display_map);
2479 let line_start = display_map.prev_line_boundary(position).0;
2480 let next_line_start = buffer.clip_point(
2481 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2482 Bias::Left,
2483 );
2484 start = buffer.anchor_before(line_start);
2485 end = buffer.anchor_before(next_line_start);
2486 mode = SelectMode::Line(start..end);
2487 auto_scroll = true;
2488 }
2489 _ => {
2490 start = buffer.anchor_before(0);
2491 end = buffer.anchor_before(buffer.len());
2492 mode = SelectMode::All;
2493 auto_scroll = false;
2494 }
2495 }
2496 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2497
2498 let point_to_delete: Option<usize> = {
2499 let selected_points: Vec<Selection<Point>> =
2500 self.selections.disjoint_in_range(start..end, cx);
2501
2502 if !add || click_count > 1 {
2503 None
2504 } else if !selected_points.is_empty() {
2505 Some(selected_points[0].id)
2506 } else {
2507 let clicked_point_already_selected =
2508 self.selections.disjoint.iter().find(|selection| {
2509 selection.start.to_point(buffer) == start.to_point(buffer)
2510 || selection.end.to_point(buffer) == end.to_point(buffer)
2511 });
2512
2513 clicked_point_already_selected.map(|selection| selection.id)
2514 }
2515 };
2516
2517 let selections_count = self.selections.count();
2518
2519 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2520 if let Some(point_to_delete) = point_to_delete {
2521 s.delete(point_to_delete);
2522
2523 if selections_count == 1 {
2524 s.set_pending_anchor_range(start..end, mode);
2525 }
2526 } else {
2527 if !add {
2528 s.clear_disjoint();
2529 } else if click_count > 1 {
2530 s.delete(newest_selection.id)
2531 }
2532
2533 s.set_pending_anchor_range(start..end, mode);
2534 }
2535 });
2536 }
2537
2538 fn begin_columnar_selection(
2539 &mut self,
2540 position: DisplayPoint,
2541 goal_column: u32,
2542 reset: bool,
2543 window: &mut Window,
2544 cx: &mut Context<Self>,
2545 ) {
2546 if !self.focus_handle.is_focused(window) {
2547 self.last_focused_descendant = None;
2548 window.focus(&self.focus_handle);
2549 }
2550
2551 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2552
2553 if reset {
2554 let pointer_position = display_map
2555 .buffer_snapshot
2556 .anchor_before(position.to_point(&display_map));
2557
2558 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2559 s.clear_disjoint();
2560 s.set_pending_anchor_range(
2561 pointer_position..pointer_position,
2562 SelectMode::Character,
2563 );
2564 });
2565 }
2566
2567 let tail = self.selections.newest::<Point>(cx).tail();
2568 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2569
2570 if !reset {
2571 self.select_columns(
2572 tail.to_display_point(&display_map),
2573 position,
2574 goal_column,
2575 &display_map,
2576 window,
2577 cx,
2578 );
2579 }
2580 }
2581
2582 fn update_selection(
2583 &mut self,
2584 position: DisplayPoint,
2585 goal_column: u32,
2586 scroll_delta: gpui::Point<f32>,
2587 window: &mut Window,
2588 cx: &mut Context<Self>,
2589 ) {
2590 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2591
2592 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2593 let tail = tail.to_display_point(&display_map);
2594 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2595 } else if let Some(mut pending) = self.selections.pending_anchor() {
2596 let buffer = self.buffer.read(cx).snapshot(cx);
2597 let head;
2598 let tail;
2599 let mode = self.selections.pending_mode().unwrap();
2600 match &mode {
2601 SelectMode::Character => {
2602 head = position.to_point(&display_map);
2603 tail = pending.tail().to_point(&buffer);
2604 }
2605 SelectMode::Word(original_range) => {
2606 let original_display_range = original_range.start.to_display_point(&display_map)
2607 ..original_range.end.to_display_point(&display_map);
2608 let original_buffer_range = original_display_range.start.to_point(&display_map)
2609 ..original_display_range.end.to_point(&display_map);
2610 if movement::is_inside_word(&display_map, position)
2611 || original_display_range.contains(&position)
2612 {
2613 let word_range = movement::surrounding_word(&display_map, position);
2614 if word_range.start < original_display_range.start {
2615 head = word_range.start.to_point(&display_map);
2616 } else {
2617 head = word_range.end.to_point(&display_map);
2618 }
2619 } else {
2620 head = position.to_point(&display_map);
2621 }
2622
2623 if head <= original_buffer_range.start {
2624 tail = original_buffer_range.end;
2625 } else {
2626 tail = original_buffer_range.start;
2627 }
2628 }
2629 SelectMode::Line(original_range) => {
2630 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2631
2632 let position = display_map
2633 .clip_point(position, Bias::Left)
2634 .to_point(&display_map);
2635 let line_start = display_map.prev_line_boundary(position).0;
2636 let next_line_start = buffer.clip_point(
2637 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2638 Bias::Left,
2639 );
2640
2641 if line_start < original_range.start {
2642 head = line_start
2643 } else {
2644 head = next_line_start
2645 }
2646
2647 if head <= original_range.start {
2648 tail = original_range.end;
2649 } else {
2650 tail = original_range.start;
2651 }
2652 }
2653 SelectMode::All => {
2654 return;
2655 }
2656 };
2657
2658 if head < tail {
2659 pending.start = buffer.anchor_before(head);
2660 pending.end = buffer.anchor_before(tail);
2661 pending.reversed = true;
2662 } else {
2663 pending.start = buffer.anchor_before(tail);
2664 pending.end = buffer.anchor_before(head);
2665 pending.reversed = false;
2666 }
2667
2668 self.change_selections(None, window, cx, |s| {
2669 s.set_pending(pending, mode);
2670 });
2671 } else {
2672 log::error!("update_selection dispatched with no pending selection");
2673 return;
2674 }
2675
2676 self.apply_scroll_delta(scroll_delta, window, cx);
2677 cx.notify();
2678 }
2679
2680 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2681 self.columnar_selection_tail.take();
2682 if self.selections.pending_anchor().is_some() {
2683 let selections = self.selections.all::<usize>(cx);
2684 self.change_selections(None, window, cx, |s| {
2685 s.select(selections);
2686 s.clear_pending();
2687 });
2688 }
2689 }
2690
2691 fn select_columns(
2692 &mut self,
2693 tail: DisplayPoint,
2694 head: DisplayPoint,
2695 goal_column: u32,
2696 display_map: &DisplaySnapshot,
2697 window: &mut Window,
2698 cx: &mut Context<Self>,
2699 ) {
2700 let start_row = cmp::min(tail.row(), head.row());
2701 let end_row = cmp::max(tail.row(), head.row());
2702 let start_column = cmp::min(tail.column(), goal_column);
2703 let end_column = cmp::max(tail.column(), goal_column);
2704 let reversed = start_column < tail.column();
2705
2706 let selection_ranges = (start_row.0..=end_row.0)
2707 .map(DisplayRow)
2708 .filter_map(|row| {
2709 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2710 let start = display_map
2711 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2712 .to_point(display_map);
2713 let end = display_map
2714 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2715 .to_point(display_map);
2716 if reversed {
2717 Some(end..start)
2718 } else {
2719 Some(start..end)
2720 }
2721 } else {
2722 None
2723 }
2724 })
2725 .collect::<Vec<_>>();
2726
2727 self.change_selections(None, window, cx, |s| {
2728 s.select_ranges(selection_ranges);
2729 });
2730 cx.notify();
2731 }
2732
2733 pub fn has_pending_nonempty_selection(&self) -> bool {
2734 let pending_nonempty_selection = match self.selections.pending_anchor() {
2735 Some(Selection { start, end, .. }) => start != end,
2736 None => false,
2737 };
2738
2739 pending_nonempty_selection
2740 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2741 }
2742
2743 pub fn has_pending_selection(&self) -> bool {
2744 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2745 }
2746
2747 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2748 self.selection_mark_mode = false;
2749
2750 if self.clear_expanded_diff_hunks(cx) {
2751 cx.notify();
2752 return;
2753 }
2754 if self.dismiss_menus_and_popups(true, window, cx) {
2755 return;
2756 }
2757
2758 if self.mode == EditorMode::Full
2759 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2760 {
2761 return;
2762 }
2763
2764 cx.propagate();
2765 }
2766
2767 pub fn dismiss_menus_and_popups(
2768 &mut self,
2769 is_user_requested: bool,
2770 window: &mut Window,
2771 cx: &mut Context<Self>,
2772 ) -> bool {
2773 if self.take_rename(false, window, cx).is_some() {
2774 return true;
2775 }
2776
2777 if hide_hover(self, cx) {
2778 return true;
2779 }
2780
2781 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2782 return true;
2783 }
2784
2785 if self.hide_context_menu(window, cx).is_some() {
2786 return true;
2787 }
2788
2789 if self.mouse_context_menu.take().is_some() {
2790 return true;
2791 }
2792
2793 if is_user_requested && self.discard_inline_completion(true, cx) {
2794 return true;
2795 }
2796
2797 if self.snippet_stack.pop().is_some() {
2798 return true;
2799 }
2800
2801 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2802 self.dismiss_diagnostics(cx);
2803 return true;
2804 }
2805
2806 false
2807 }
2808
2809 fn linked_editing_ranges_for(
2810 &self,
2811 selection: Range<text::Anchor>,
2812 cx: &App,
2813 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2814 if self.linked_edit_ranges.is_empty() {
2815 return None;
2816 }
2817 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2818 selection.end.buffer_id.and_then(|end_buffer_id| {
2819 if selection.start.buffer_id != Some(end_buffer_id) {
2820 return None;
2821 }
2822 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2823 let snapshot = buffer.read(cx).snapshot();
2824 self.linked_edit_ranges
2825 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2826 .map(|ranges| (ranges, snapshot, buffer))
2827 })?;
2828 use text::ToOffset as TO;
2829 // find offset from the start of current range to current cursor position
2830 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2831
2832 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2833 let start_difference = start_offset - start_byte_offset;
2834 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2835 let end_difference = end_offset - start_byte_offset;
2836 // Current range has associated linked ranges.
2837 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2838 for range in linked_ranges.iter() {
2839 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2840 let end_offset = start_offset + end_difference;
2841 let start_offset = start_offset + start_difference;
2842 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2843 continue;
2844 }
2845 if self.selections.disjoint_anchor_ranges().any(|s| {
2846 if s.start.buffer_id != selection.start.buffer_id
2847 || s.end.buffer_id != selection.end.buffer_id
2848 {
2849 return false;
2850 }
2851 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2852 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2853 }) {
2854 continue;
2855 }
2856 let start = buffer_snapshot.anchor_after(start_offset);
2857 let end = buffer_snapshot.anchor_after(end_offset);
2858 linked_edits
2859 .entry(buffer.clone())
2860 .or_default()
2861 .push(start..end);
2862 }
2863 Some(linked_edits)
2864 }
2865
2866 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2867 let text: Arc<str> = text.into();
2868
2869 if self.read_only(cx) {
2870 return;
2871 }
2872
2873 let selections = self.selections.all_adjusted(cx);
2874 let mut bracket_inserted = false;
2875 let mut edits = Vec::new();
2876 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2877 let mut new_selections = Vec::with_capacity(selections.len());
2878 let mut new_autoclose_regions = Vec::new();
2879 let snapshot = self.buffer.read(cx).read(cx);
2880
2881 for (selection, autoclose_region) in
2882 self.selections_with_autoclose_regions(selections, &snapshot)
2883 {
2884 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2885 // Determine if the inserted text matches the opening or closing
2886 // bracket of any of this language's bracket pairs.
2887 let mut bracket_pair = None;
2888 let mut is_bracket_pair_start = false;
2889 let mut is_bracket_pair_end = false;
2890 if !text.is_empty() {
2891 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2892 // and they are removing the character that triggered IME popup.
2893 for (pair, enabled) in scope.brackets() {
2894 if !pair.close && !pair.surround {
2895 continue;
2896 }
2897
2898 if enabled && pair.start.ends_with(text.as_ref()) {
2899 let prefix_len = pair.start.len() - text.len();
2900 let preceding_text_matches_prefix = prefix_len == 0
2901 || (selection.start.column >= (prefix_len as u32)
2902 && snapshot.contains_str_at(
2903 Point::new(
2904 selection.start.row,
2905 selection.start.column - (prefix_len as u32),
2906 ),
2907 &pair.start[..prefix_len],
2908 ));
2909 if preceding_text_matches_prefix {
2910 bracket_pair = Some(pair.clone());
2911 is_bracket_pair_start = true;
2912 break;
2913 }
2914 }
2915 if pair.end.as_str() == text.as_ref() {
2916 bracket_pair = Some(pair.clone());
2917 is_bracket_pair_end = true;
2918 break;
2919 }
2920 }
2921 }
2922
2923 if let Some(bracket_pair) = bracket_pair {
2924 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
2925 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2926 let auto_surround =
2927 self.use_auto_surround && snapshot_settings.use_auto_surround;
2928 if selection.is_empty() {
2929 if is_bracket_pair_start {
2930 // If the inserted text is a suffix of an opening bracket and the
2931 // selection is preceded by the rest of the opening bracket, then
2932 // insert the closing bracket.
2933 let following_text_allows_autoclose = snapshot
2934 .chars_at(selection.start)
2935 .next()
2936 .map_or(true, |c| scope.should_autoclose_before(c));
2937
2938 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2939 && bracket_pair.start.len() == 1
2940 {
2941 let target = bracket_pair.start.chars().next().unwrap();
2942 let current_line_count = snapshot
2943 .reversed_chars_at(selection.start)
2944 .take_while(|&c| c != '\n')
2945 .filter(|&c| c == target)
2946 .count();
2947 current_line_count % 2 == 1
2948 } else {
2949 false
2950 };
2951
2952 if autoclose
2953 && bracket_pair.close
2954 && following_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 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3193 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3194 this.refresh_inline_completion(true, false, window, cx);
3195 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3196 });
3197 }
3198
3199 fn find_possible_emoji_shortcode_at_position(
3200 snapshot: &MultiBufferSnapshot,
3201 position: Point,
3202 ) -> Option<String> {
3203 let mut chars = Vec::new();
3204 let mut found_colon = false;
3205 for char in snapshot.reversed_chars_at(position).take(100) {
3206 // Found a possible emoji shortcode in the middle of the buffer
3207 if found_colon {
3208 if char.is_whitespace() {
3209 chars.reverse();
3210 return Some(chars.iter().collect());
3211 }
3212 // If the previous character is not a whitespace, we are in the middle of a word
3213 // and we only want to complete the shortcode if the word is made up of other emojis
3214 let mut containing_word = String::new();
3215 for ch in snapshot
3216 .reversed_chars_at(position)
3217 .skip(chars.len() + 1)
3218 .take(100)
3219 {
3220 if ch.is_whitespace() {
3221 break;
3222 }
3223 containing_word.push(ch);
3224 }
3225 let containing_word = containing_word.chars().rev().collect::<String>();
3226 if util::word_consists_of_emojis(containing_word.as_str()) {
3227 chars.reverse();
3228 return Some(chars.iter().collect());
3229 }
3230 }
3231
3232 if char.is_whitespace() || !char.is_ascii() {
3233 return None;
3234 }
3235 if char == ':' {
3236 found_colon = true;
3237 } else {
3238 chars.push(char);
3239 }
3240 }
3241 // Found a possible emoji shortcode at the beginning of the buffer
3242 chars.reverse();
3243 Some(chars.iter().collect())
3244 }
3245
3246 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3247 self.transact(window, cx, |this, window, cx| {
3248 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3249 let selections = this.selections.all::<usize>(cx);
3250 let multi_buffer = this.buffer.read(cx);
3251 let buffer = multi_buffer.snapshot(cx);
3252 selections
3253 .iter()
3254 .map(|selection| {
3255 let start_point = selection.start.to_point(&buffer);
3256 let mut indent =
3257 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3258 indent.len = cmp::min(indent.len, start_point.column);
3259 let start = selection.start;
3260 let end = selection.end;
3261 let selection_is_empty = start == end;
3262 let language_scope = buffer.language_scope_at(start);
3263 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3264 &language_scope
3265 {
3266 let insert_extra_newline =
3267 insert_extra_newline_brackets(&buffer, start..end, language)
3268 || insert_extra_newline_tree_sitter(&buffer, start..end);
3269
3270 // Comment extension on newline is allowed only for cursor selections
3271 let comment_delimiter = maybe!({
3272 if !selection_is_empty {
3273 return None;
3274 }
3275
3276 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3277 return None;
3278 }
3279
3280 let delimiters = language.line_comment_prefixes();
3281 let max_len_of_delimiter =
3282 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3283 let (snapshot, range) =
3284 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3285
3286 let mut index_of_first_non_whitespace = 0;
3287 let comment_candidate = snapshot
3288 .chars_for_range(range)
3289 .skip_while(|c| {
3290 let should_skip = c.is_whitespace();
3291 if should_skip {
3292 index_of_first_non_whitespace += 1;
3293 }
3294 should_skip
3295 })
3296 .take(max_len_of_delimiter)
3297 .collect::<String>();
3298 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3299 comment_candidate.starts_with(comment_prefix.as_ref())
3300 })?;
3301 let cursor_is_placed_after_comment_marker =
3302 index_of_first_non_whitespace + comment_prefix.len()
3303 <= start_point.column as usize;
3304 if cursor_is_placed_after_comment_marker {
3305 Some(comment_prefix.clone())
3306 } else {
3307 None
3308 }
3309 });
3310 (comment_delimiter, insert_extra_newline)
3311 } else {
3312 (None, false)
3313 };
3314
3315 let capacity_for_delimiter = comment_delimiter
3316 .as_deref()
3317 .map(str::len)
3318 .unwrap_or_default();
3319 let mut new_text =
3320 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3321 new_text.push('\n');
3322 new_text.extend(indent.chars());
3323 if let Some(delimiter) = &comment_delimiter {
3324 new_text.push_str(delimiter);
3325 }
3326 if insert_extra_newline {
3327 new_text = new_text.repeat(2);
3328 }
3329
3330 let anchor = buffer.anchor_after(end);
3331 let new_selection = selection.map(|_| anchor);
3332 (
3333 (start..end, new_text),
3334 (insert_extra_newline, new_selection),
3335 )
3336 })
3337 .unzip()
3338 };
3339
3340 this.edit_with_autoindent(edits, cx);
3341 let buffer = this.buffer.read(cx).snapshot(cx);
3342 let new_selections = selection_fixup_info
3343 .into_iter()
3344 .map(|(extra_newline_inserted, new_selection)| {
3345 let mut cursor = new_selection.end.to_point(&buffer);
3346 if extra_newline_inserted {
3347 cursor.row -= 1;
3348 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3349 }
3350 new_selection.map(|_| cursor)
3351 })
3352 .collect();
3353
3354 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3355 s.select(new_selections)
3356 });
3357 this.refresh_inline_completion(true, false, window, cx);
3358 });
3359 }
3360
3361 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3362 let buffer = self.buffer.read(cx);
3363 let snapshot = buffer.snapshot(cx);
3364
3365 let mut edits = Vec::new();
3366 let mut rows = Vec::new();
3367
3368 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3369 let cursor = selection.head();
3370 let row = cursor.row;
3371
3372 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3373
3374 let newline = "\n".to_string();
3375 edits.push((start_of_line..start_of_line, newline));
3376
3377 rows.push(row + rows_inserted as u32);
3378 }
3379
3380 self.transact(window, cx, |editor, window, cx| {
3381 editor.edit(edits, cx);
3382
3383 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3384 let mut index = 0;
3385 s.move_cursors_with(|map, _, _| {
3386 let row = rows[index];
3387 index += 1;
3388
3389 let point = Point::new(row, 0);
3390 let boundary = map.next_line_boundary(point).1;
3391 let clipped = map.clip_point(boundary, Bias::Left);
3392
3393 (clipped, SelectionGoal::None)
3394 });
3395 });
3396
3397 let mut indent_edits = Vec::new();
3398 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3399 for row in rows {
3400 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3401 for (row, indent) in indents {
3402 if indent.len == 0 {
3403 continue;
3404 }
3405
3406 let text = match indent.kind {
3407 IndentKind::Space => " ".repeat(indent.len as usize),
3408 IndentKind::Tab => "\t".repeat(indent.len as usize),
3409 };
3410 let point = Point::new(row.0, 0);
3411 indent_edits.push((point..point, text));
3412 }
3413 }
3414 editor.edit(indent_edits, cx);
3415 });
3416 }
3417
3418 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3419 let buffer = self.buffer.read(cx);
3420 let snapshot = buffer.snapshot(cx);
3421
3422 let mut edits = Vec::new();
3423 let mut rows = Vec::new();
3424 let mut rows_inserted = 0;
3425
3426 for selection in self.selections.all_adjusted(cx) {
3427 let cursor = selection.head();
3428 let row = cursor.row;
3429
3430 let point = Point::new(row + 1, 0);
3431 let start_of_line = snapshot.clip_point(point, Bias::Left);
3432
3433 let newline = "\n".to_string();
3434 edits.push((start_of_line..start_of_line, newline));
3435
3436 rows_inserted += 1;
3437 rows.push(row + rows_inserted);
3438 }
3439
3440 self.transact(window, cx, |editor, window, cx| {
3441 editor.edit(edits, cx);
3442
3443 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3444 let mut index = 0;
3445 s.move_cursors_with(|map, _, _| {
3446 let row = rows[index];
3447 index += 1;
3448
3449 let point = Point::new(row, 0);
3450 let boundary = map.next_line_boundary(point).1;
3451 let clipped = map.clip_point(boundary, Bias::Left);
3452
3453 (clipped, SelectionGoal::None)
3454 });
3455 });
3456
3457 let mut indent_edits = Vec::new();
3458 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3459 for row in rows {
3460 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3461 for (row, indent) in indents {
3462 if indent.len == 0 {
3463 continue;
3464 }
3465
3466 let text = match indent.kind {
3467 IndentKind::Space => " ".repeat(indent.len as usize),
3468 IndentKind::Tab => "\t".repeat(indent.len as usize),
3469 };
3470 let point = Point::new(row.0, 0);
3471 indent_edits.push((point..point, text));
3472 }
3473 }
3474 editor.edit(indent_edits, cx);
3475 });
3476 }
3477
3478 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3479 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3480 original_indent_columns: Vec::new(),
3481 });
3482 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3483 }
3484
3485 fn insert_with_autoindent_mode(
3486 &mut self,
3487 text: &str,
3488 autoindent_mode: Option<AutoindentMode>,
3489 window: &mut Window,
3490 cx: &mut Context<Self>,
3491 ) {
3492 if self.read_only(cx) {
3493 return;
3494 }
3495
3496 let text: Arc<str> = text.into();
3497 self.transact(window, cx, |this, window, cx| {
3498 let old_selections = this.selections.all_adjusted(cx);
3499 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3500 let anchors = {
3501 let snapshot = buffer.read(cx);
3502 old_selections
3503 .iter()
3504 .map(|s| {
3505 let anchor = snapshot.anchor_after(s.head());
3506 s.map(|_| anchor)
3507 })
3508 .collect::<Vec<_>>()
3509 };
3510 buffer.edit(
3511 old_selections
3512 .iter()
3513 .map(|s| (s.start..s.end, text.clone())),
3514 autoindent_mode,
3515 cx,
3516 );
3517 anchors
3518 });
3519
3520 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3521 s.select_anchors(selection_anchors);
3522 });
3523
3524 cx.notify();
3525 });
3526 }
3527
3528 fn trigger_completion_on_input(
3529 &mut self,
3530 text: &str,
3531 trigger_in_words: bool,
3532 window: &mut Window,
3533 cx: &mut Context<Self>,
3534 ) {
3535 if self.is_completion_trigger(text, trigger_in_words, cx) {
3536 self.show_completions(
3537 &ShowCompletions {
3538 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3539 },
3540 window,
3541 cx,
3542 );
3543 } else {
3544 self.hide_context_menu(window, cx);
3545 }
3546 }
3547
3548 fn is_completion_trigger(
3549 &self,
3550 text: &str,
3551 trigger_in_words: bool,
3552 cx: &mut Context<Self>,
3553 ) -> bool {
3554 let position = self.selections.newest_anchor().head();
3555 let multibuffer = self.buffer.read(cx);
3556 let Some(buffer) = position
3557 .buffer_id
3558 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3559 else {
3560 return false;
3561 };
3562
3563 if let Some(completion_provider) = &self.completion_provider {
3564 completion_provider.is_completion_trigger(
3565 &buffer,
3566 position.text_anchor,
3567 text,
3568 trigger_in_words,
3569 cx,
3570 )
3571 } else {
3572 false
3573 }
3574 }
3575
3576 /// If any empty selections is touching the start of its innermost containing autoclose
3577 /// region, expand it to select the brackets.
3578 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3579 let selections = self.selections.all::<usize>(cx);
3580 let buffer = self.buffer.read(cx).read(cx);
3581 let new_selections = self
3582 .selections_with_autoclose_regions(selections, &buffer)
3583 .map(|(mut selection, region)| {
3584 if !selection.is_empty() {
3585 return selection;
3586 }
3587
3588 if let Some(region) = region {
3589 let mut range = region.range.to_offset(&buffer);
3590 if selection.start == range.start && range.start >= region.pair.start.len() {
3591 range.start -= region.pair.start.len();
3592 if buffer.contains_str_at(range.start, ®ion.pair.start)
3593 && buffer.contains_str_at(range.end, ®ion.pair.end)
3594 {
3595 range.end += region.pair.end.len();
3596 selection.start = range.start;
3597 selection.end = range.end;
3598
3599 return selection;
3600 }
3601 }
3602 }
3603
3604 let always_treat_brackets_as_autoclosed = buffer
3605 .language_settings_at(selection.start, cx)
3606 .always_treat_brackets_as_autoclosed;
3607
3608 if !always_treat_brackets_as_autoclosed {
3609 return selection;
3610 }
3611
3612 if let Some(scope) = buffer.language_scope_at(selection.start) {
3613 for (pair, enabled) in scope.brackets() {
3614 if !enabled || !pair.close {
3615 continue;
3616 }
3617
3618 if buffer.contains_str_at(selection.start, &pair.end) {
3619 let pair_start_len = pair.start.len();
3620 if buffer.contains_str_at(
3621 selection.start.saturating_sub(pair_start_len),
3622 &pair.start,
3623 ) {
3624 selection.start -= pair_start_len;
3625 selection.end += pair.end.len();
3626
3627 return selection;
3628 }
3629 }
3630 }
3631 }
3632
3633 selection
3634 })
3635 .collect();
3636
3637 drop(buffer);
3638 self.change_selections(None, window, cx, |selections| {
3639 selections.select(new_selections)
3640 });
3641 }
3642
3643 /// Iterate the given selections, and for each one, find the smallest surrounding
3644 /// autoclose region. This uses the ordering of the selections and the autoclose
3645 /// regions to avoid repeated comparisons.
3646 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3647 &'a self,
3648 selections: impl IntoIterator<Item = Selection<D>>,
3649 buffer: &'a MultiBufferSnapshot,
3650 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3651 let mut i = 0;
3652 let mut regions = self.autoclose_regions.as_slice();
3653 selections.into_iter().map(move |selection| {
3654 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3655
3656 let mut enclosing = None;
3657 while let Some(pair_state) = regions.get(i) {
3658 if pair_state.range.end.to_offset(buffer) < range.start {
3659 regions = ®ions[i + 1..];
3660 i = 0;
3661 } else if pair_state.range.start.to_offset(buffer) > range.end {
3662 break;
3663 } else {
3664 if pair_state.selection_id == selection.id {
3665 enclosing = Some(pair_state);
3666 }
3667 i += 1;
3668 }
3669 }
3670
3671 (selection, enclosing)
3672 })
3673 }
3674
3675 /// Remove any autoclose regions that no longer contain their selection.
3676 fn invalidate_autoclose_regions(
3677 &mut self,
3678 mut selections: &[Selection<Anchor>],
3679 buffer: &MultiBufferSnapshot,
3680 ) {
3681 self.autoclose_regions.retain(|state| {
3682 let mut i = 0;
3683 while let Some(selection) = selections.get(i) {
3684 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3685 selections = &selections[1..];
3686 continue;
3687 }
3688 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3689 break;
3690 }
3691 if selection.id == state.selection_id {
3692 return true;
3693 } else {
3694 i += 1;
3695 }
3696 }
3697 false
3698 });
3699 }
3700
3701 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3702 let offset = position.to_offset(buffer);
3703 let (word_range, kind) = buffer.surrounding_word(offset, true);
3704 if offset > word_range.start && kind == Some(CharKind::Word) {
3705 Some(
3706 buffer
3707 .text_for_range(word_range.start..offset)
3708 .collect::<String>(),
3709 )
3710 } else {
3711 None
3712 }
3713 }
3714
3715 pub fn toggle_inlay_hints(
3716 &mut self,
3717 _: &ToggleInlayHints,
3718 _: &mut Window,
3719 cx: &mut Context<Self>,
3720 ) {
3721 self.refresh_inlay_hints(
3722 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3723 cx,
3724 );
3725 }
3726
3727 pub fn inlay_hints_enabled(&self) -> bool {
3728 self.inlay_hint_cache.enabled
3729 }
3730
3731 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3732 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3733 return;
3734 }
3735
3736 let reason_description = reason.description();
3737 let ignore_debounce = matches!(
3738 reason,
3739 InlayHintRefreshReason::SettingsChange(_)
3740 | InlayHintRefreshReason::Toggle(_)
3741 | InlayHintRefreshReason::ExcerptsRemoved(_)
3742 | InlayHintRefreshReason::ModifiersChanged(_)
3743 );
3744 let (invalidate_cache, required_languages) = match reason {
3745 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3746 match self.inlay_hint_cache.modifiers_override(enabled) {
3747 Some(enabled) => {
3748 if enabled {
3749 (InvalidationStrategy::RefreshRequested, None)
3750 } else {
3751 self.splice_inlays(
3752 &self
3753 .visible_inlay_hints(cx)
3754 .iter()
3755 .map(|inlay| inlay.id)
3756 .collect::<Vec<InlayId>>(),
3757 Vec::new(),
3758 cx,
3759 );
3760 return;
3761 }
3762 }
3763 None => return,
3764 }
3765 }
3766 InlayHintRefreshReason::Toggle(enabled) => {
3767 if self.inlay_hint_cache.toggle(enabled) {
3768 if enabled {
3769 (InvalidationStrategy::RefreshRequested, None)
3770 } else {
3771 self.splice_inlays(
3772 &self
3773 .visible_inlay_hints(cx)
3774 .iter()
3775 .map(|inlay| inlay.id)
3776 .collect::<Vec<InlayId>>(),
3777 Vec::new(),
3778 cx,
3779 );
3780 return;
3781 }
3782 } else {
3783 return;
3784 }
3785 }
3786 InlayHintRefreshReason::SettingsChange(new_settings) => {
3787 match self.inlay_hint_cache.update_settings(
3788 &self.buffer,
3789 new_settings,
3790 self.visible_inlay_hints(cx),
3791 cx,
3792 ) {
3793 ControlFlow::Break(Some(InlaySplice {
3794 to_remove,
3795 to_insert,
3796 })) => {
3797 self.splice_inlays(&to_remove, to_insert, cx);
3798 return;
3799 }
3800 ControlFlow::Break(None) => return,
3801 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3802 }
3803 }
3804 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3805 if let Some(InlaySplice {
3806 to_remove,
3807 to_insert,
3808 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3809 {
3810 self.splice_inlays(&to_remove, to_insert, cx);
3811 }
3812 return;
3813 }
3814 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3815 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3816 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3817 }
3818 InlayHintRefreshReason::RefreshRequested => {
3819 (InvalidationStrategy::RefreshRequested, None)
3820 }
3821 };
3822
3823 if let Some(InlaySplice {
3824 to_remove,
3825 to_insert,
3826 }) = self.inlay_hint_cache.spawn_hint_refresh(
3827 reason_description,
3828 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3829 invalidate_cache,
3830 ignore_debounce,
3831 cx,
3832 ) {
3833 self.splice_inlays(&to_remove, to_insert, cx);
3834 }
3835 }
3836
3837 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3838 self.display_map
3839 .read(cx)
3840 .current_inlays()
3841 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3842 .cloned()
3843 .collect()
3844 }
3845
3846 pub fn excerpts_for_inlay_hints_query(
3847 &self,
3848 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3849 cx: &mut Context<Editor>,
3850 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3851 let Some(project) = self.project.as_ref() else {
3852 return HashMap::default();
3853 };
3854 let project = project.read(cx);
3855 let multi_buffer = self.buffer().read(cx);
3856 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3857 let multi_buffer_visible_start = self
3858 .scroll_manager
3859 .anchor()
3860 .anchor
3861 .to_point(&multi_buffer_snapshot);
3862 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3863 multi_buffer_visible_start
3864 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3865 Bias::Left,
3866 );
3867 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3868 multi_buffer_snapshot
3869 .range_to_buffer_ranges(multi_buffer_visible_range)
3870 .into_iter()
3871 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3872 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3873 let buffer_file = project::File::from_dyn(buffer.file())?;
3874 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3875 let worktree_entry = buffer_worktree
3876 .read(cx)
3877 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3878 if worktree_entry.is_ignored {
3879 return None;
3880 }
3881
3882 let language = buffer.language()?;
3883 if let Some(restrict_to_languages) = restrict_to_languages {
3884 if !restrict_to_languages.contains(language) {
3885 return None;
3886 }
3887 }
3888 Some((
3889 excerpt_id,
3890 (
3891 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3892 buffer.version().clone(),
3893 excerpt_visible_range,
3894 ),
3895 ))
3896 })
3897 .collect()
3898 }
3899
3900 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3901 TextLayoutDetails {
3902 text_system: window.text_system().clone(),
3903 editor_style: self.style.clone().unwrap(),
3904 rem_size: window.rem_size(),
3905 scroll_anchor: self.scroll_manager.anchor(),
3906 visible_rows: self.visible_line_count(),
3907 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3908 }
3909 }
3910
3911 pub fn splice_inlays(
3912 &self,
3913 to_remove: &[InlayId],
3914 to_insert: Vec<Inlay>,
3915 cx: &mut Context<Self>,
3916 ) {
3917 self.display_map.update(cx, |display_map, cx| {
3918 display_map.splice_inlays(to_remove, to_insert, cx)
3919 });
3920 cx.notify();
3921 }
3922
3923 fn trigger_on_type_formatting(
3924 &self,
3925 input: String,
3926 window: &mut Window,
3927 cx: &mut Context<Self>,
3928 ) -> Option<Task<Result<()>>> {
3929 if input.len() != 1 {
3930 return None;
3931 }
3932
3933 let project = self.project.as_ref()?;
3934 let position = self.selections.newest_anchor().head();
3935 let (buffer, buffer_position) = self
3936 .buffer
3937 .read(cx)
3938 .text_anchor_for_position(position, cx)?;
3939
3940 let settings = language_settings::language_settings(
3941 buffer
3942 .read(cx)
3943 .language_at(buffer_position)
3944 .map(|l| l.name()),
3945 buffer.read(cx).file(),
3946 cx,
3947 );
3948 if !settings.use_on_type_format {
3949 return None;
3950 }
3951
3952 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3953 // hence we do LSP request & edit on host side only — add formats to host's history.
3954 let push_to_lsp_host_history = true;
3955 // If this is not the host, append its history with new edits.
3956 let push_to_client_history = project.read(cx).is_via_collab();
3957
3958 let on_type_formatting = project.update(cx, |project, cx| {
3959 project.on_type_format(
3960 buffer.clone(),
3961 buffer_position,
3962 input,
3963 push_to_lsp_host_history,
3964 cx,
3965 )
3966 });
3967 Some(cx.spawn_in(window, |editor, mut cx| async move {
3968 if let Some(transaction) = on_type_formatting.await? {
3969 if push_to_client_history {
3970 buffer
3971 .update(&mut cx, |buffer, _| {
3972 buffer.push_transaction(transaction, Instant::now());
3973 })
3974 .ok();
3975 }
3976 editor.update(&mut cx, |editor, cx| {
3977 editor.refresh_document_highlights(cx);
3978 })?;
3979 }
3980 Ok(())
3981 }))
3982 }
3983
3984 pub fn show_completions(
3985 &mut self,
3986 options: &ShowCompletions,
3987 window: &mut Window,
3988 cx: &mut Context<Self>,
3989 ) {
3990 if self.pending_rename.is_some() {
3991 return;
3992 }
3993
3994 let Some(provider) = self.completion_provider.as_ref() else {
3995 return;
3996 };
3997
3998 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3999 return;
4000 }
4001
4002 let position = self.selections.newest_anchor().head();
4003 if position.diff_base_anchor.is_some() {
4004 return;
4005 }
4006 let (buffer, buffer_position) =
4007 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4008 output
4009 } else {
4010 return;
4011 };
4012 let show_completion_documentation = buffer
4013 .read(cx)
4014 .snapshot()
4015 .settings_at(buffer_position, cx)
4016 .show_completion_documentation;
4017
4018 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4019
4020 let trigger_kind = match &options.trigger {
4021 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4022 CompletionTriggerKind::TRIGGER_CHARACTER
4023 }
4024 _ => CompletionTriggerKind::INVOKED,
4025 };
4026 let completion_context = CompletionContext {
4027 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4028 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4029 Some(String::from(trigger))
4030 } else {
4031 None
4032 }
4033 }),
4034 trigger_kind,
4035 };
4036 let completions =
4037 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4038 let sort_completions = provider.sort_completions();
4039
4040 let id = post_inc(&mut self.next_completion_id);
4041 let task = cx.spawn_in(window, |editor, mut cx| {
4042 async move {
4043 editor.update(&mut cx, |this, _| {
4044 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4045 })?;
4046 let completions = completions.await.log_err();
4047 let menu = if let Some(completions) = completions {
4048 let mut menu = CompletionsMenu::new(
4049 id,
4050 sort_completions,
4051 show_completion_documentation,
4052 position,
4053 buffer.clone(),
4054 completions.into(),
4055 );
4056
4057 menu.filter(query.as_deref(), cx.background_executor().clone())
4058 .await;
4059
4060 menu.visible().then_some(menu)
4061 } else {
4062 None
4063 };
4064
4065 editor.update_in(&mut cx, |editor, window, cx| {
4066 match editor.context_menu.borrow().as_ref() {
4067 None => {}
4068 Some(CodeContextMenu::Completions(prev_menu)) => {
4069 if prev_menu.id > id {
4070 return;
4071 }
4072 }
4073 _ => return,
4074 }
4075
4076 if editor.focus_handle.is_focused(window) && menu.is_some() {
4077 let mut menu = menu.unwrap();
4078 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4079
4080 *editor.context_menu.borrow_mut() =
4081 Some(CodeContextMenu::Completions(menu));
4082
4083 if editor.show_edit_predictions_in_menu() {
4084 editor.update_visible_inline_completion(window, cx);
4085 } else {
4086 editor.discard_inline_completion(false, cx);
4087 }
4088
4089 cx.notify();
4090 } else if editor.completion_tasks.len() <= 1 {
4091 // If there are no more completion tasks and the last menu was
4092 // empty, we should hide it.
4093 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4094 // If it was already hidden and we don't show inline
4095 // completions in the menu, we should also show the
4096 // inline-completion when available.
4097 if was_hidden && editor.show_edit_predictions_in_menu() {
4098 editor.update_visible_inline_completion(window, cx);
4099 }
4100 }
4101 })?;
4102
4103 Ok::<_, anyhow::Error>(())
4104 }
4105 .log_err()
4106 });
4107
4108 self.completion_tasks.push((id, task));
4109 }
4110
4111 pub fn confirm_completion(
4112 &mut self,
4113 action: &ConfirmCompletion,
4114 window: &mut Window,
4115 cx: &mut Context<Self>,
4116 ) -> Option<Task<Result<()>>> {
4117 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4118 }
4119
4120 pub fn compose_completion(
4121 &mut self,
4122 action: &ComposeCompletion,
4123 window: &mut Window,
4124 cx: &mut Context<Self>,
4125 ) -> Option<Task<Result<()>>> {
4126 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4127 }
4128
4129 fn do_completion(
4130 &mut self,
4131 item_ix: Option<usize>,
4132 intent: CompletionIntent,
4133 window: &mut Window,
4134 cx: &mut Context<Editor>,
4135 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4136 use language::ToOffset as _;
4137
4138 let completions_menu =
4139 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4140 menu
4141 } else {
4142 return None;
4143 };
4144
4145 let entries = completions_menu.entries.borrow();
4146 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4147 if self.show_edit_predictions_in_menu() {
4148 self.discard_inline_completion(true, cx);
4149 }
4150 let candidate_id = mat.candidate_id;
4151 drop(entries);
4152
4153 let buffer_handle = completions_menu.buffer;
4154 let completion = completions_menu
4155 .completions
4156 .borrow()
4157 .get(candidate_id)?
4158 .clone();
4159 cx.stop_propagation();
4160
4161 let snippet;
4162 let text;
4163
4164 if completion.is_snippet() {
4165 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4166 text = snippet.as_ref().unwrap().text.clone();
4167 } else {
4168 snippet = None;
4169 text = completion.new_text.clone();
4170 };
4171 let selections = self.selections.all::<usize>(cx);
4172 let buffer = buffer_handle.read(cx);
4173 let old_range = completion.old_range.to_offset(buffer);
4174 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4175
4176 let newest_selection = self.selections.newest_anchor();
4177 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4178 return None;
4179 }
4180
4181 let lookbehind = newest_selection
4182 .start
4183 .text_anchor
4184 .to_offset(buffer)
4185 .saturating_sub(old_range.start);
4186 let lookahead = old_range
4187 .end
4188 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4189 let mut common_prefix_len = old_text
4190 .bytes()
4191 .zip(text.bytes())
4192 .take_while(|(a, b)| a == b)
4193 .count();
4194
4195 let snapshot = self.buffer.read(cx).snapshot(cx);
4196 let mut range_to_replace: Option<Range<isize>> = None;
4197 let mut ranges = Vec::new();
4198 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4199 for selection in &selections {
4200 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4201 let start = selection.start.saturating_sub(lookbehind);
4202 let end = selection.end + lookahead;
4203 if selection.id == newest_selection.id {
4204 range_to_replace = Some(
4205 ((start + common_prefix_len) as isize - selection.start as isize)
4206 ..(end as isize - selection.start as isize),
4207 );
4208 }
4209 ranges.push(start + common_prefix_len..end);
4210 } else {
4211 common_prefix_len = 0;
4212 ranges.clear();
4213 ranges.extend(selections.iter().map(|s| {
4214 if s.id == newest_selection.id {
4215 range_to_replace = Some(
4216 old_range.start.to_offset_utf16(&snapshot).0 as isize
4217 - selection.start as isize
4218 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4219 - selection.start as isize,
4220 );
4221 old_range.clone()
4222 } else {
4223 s.start..s.end
4224 }
4225 }));
4226 break;
4227 }
4228 if !self.linked_edit_ranges.is_empty() {
4229 let start_anchor = snapshot.anchor_before(selection.head());
4230 let end_anchor = snapshot.anchor_after(selection.tail());
4231 if let Some(ranges) = self
4232 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4233 {
4234 for (buffer, edits) in ranges {
4235 linked_edits.entry(buffer.clone()).or_default().extend(
4236 edits
4237 .into_iter()
4238 .map(|range| (range, text[common_prefix_len..].to_owned())),
4239 );
4240 }
4241 }
4242 }
4243 }
4244 let text = &text[common_prefix_len..];
4245
4246 cx.emit(EditorEvent::InputHandled {
4247 utf16_range_to_replace: range_to_replace,
4248 text: text.into(),
4249 });
4250
4251 self.transact(window, cx, |this, window, cx| {
4252 if let Some(mut snippet) = snippet {
4253 snippet.text = text.to_string();
4254 for tabstop in snippet
4255 .tabstops
4256 .iter_mut()
4257 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4258 {
4259 tabstop.start -= common_prefix_len as isize;
4260 tabstop.end -= common_prefix_len as isize;
4261 }
4262
4263 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4264 } else {
4265 this.buffer.update(cx, |buffer, cx| {
4266 buffer.edit(
4267 ranges.iter().map(|range| (range.clone(), text)),
4268 this.autoindent_mode.clone(),
4269 cx,
4270 );
4271 });
4272 }
4273 for (buffer, edits) in linked_edits {
4274 buffer.update(cx, |buffer, cx| {
4275 let snapshot = buffer.snapshot();
4276 let edits = edits
4277 .into_iter()
4278 .map(|(range, text)| {
4279 use text::ToPoint as TP;
4280 let end_point = TP::to_point(&range.end, &snapshot);
4281 let start_point = TP::to_point(&range.start, &snapshot);
4282 (start_point..end_point, text)
4283 })
4284 .sorted_by_key(|(range, _)| range.start)
4285 .collect::<Vec<_>>();
4286 buffer.edit(edits, None, cx);
4287 })
4288 }
4289
4290 this.refresh_inline_completion(true, false, window, cx);
4291 });
4292
4293 let show_new_completions_on_confirm = completion
4294 .confirm
4295 .as_ref()
4296 .map_or(false, |confirm| confirm(intent, window, cx));
4297 if show_new_completions_on_confirm {
4298 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4299 }
4300
4301 let provider = self.completion_provider.as_ref()?;
4302 drop(completion);
4303 let apply_edits = provider.apply_additional_edits_for_completion(
4304 buffer_handle,
4305 completions_menu.completions.clone(),
4306 candidate_id,
4307 true,
4308 cx,
4309 );
4310
4311 let editor_settings = EditorSettings::get_global(cx);
4312 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4313 // After the code completion is finished, users often want to know what signatures are needed.
4314 // so we should automatically call signature_help
4315 self.show_signature_help(&ShowSignatureHelp, window, cx);
4316 }
4317
4318 Some(cx.foreground_executor().spawn(async move {
4319 apply_edits.await?;
4320 Ok(())
4321 }))
4322 }
4323
4324 pub fn toggle_code_actions(
4325 &mut self,
4326 action: &ToggleCodeActions,
4327 window: &mut Window,
4328 cx: &mut Context<Self>,
4329 ) {
4330 let mut context_menu = self.context_menu.borrow_mut();
4331 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4332 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4333 // Toggle if we're selecting the same one
4334 *context_menu = None;
4335 cx.notify();
4336 return;
4337 } else {
4338 // Otherwise, clear it and start a new one
4339 *context_menu = None;
4340 cx.notify();
4341 }
4342 }
4343 drop(context_menu);
4344 let snapshot = self.snapshot(window, cx);
4345 let deployed_from_indicator = action.deployed_from_indicator;
4346 let mut task = self.code_actions_task.take();
4347 let action = action.clone();
4348 cx.spawn_in(window, |editor, mut cx| async move {
4349 while let Some(prev_task) = task {
4350 prev_task.await.log_err();
4351 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4352 }
4353
4354 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4355 if editor.focus_handle.is_focused(window) {
4356 let multibuffer_point = action
4357 .deployed_from_indicator
4358 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4359 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4360 let (buffer, buffer_row) = snapshot
4361 .buffer_snapshot
4362 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4363 .and_then(|(buffer_snapshot, range)| {
4364 editor
4365 .buffer
4366 .read(cx)
4367 .buffer(buffer_snapshot.remote_id())
4368 .map(|buffer| (buffer, range.start.row))
4369 })?;
4370 let (_, code_actions) = editor
4371 .available_code_actions
4372 .clone()
4373 .and_then(|(location, code_actions)| {
4374 let snapshot = location.buffer.read(cx).snapshot();
4375 let point_range = location.range.to_point(&snapshot);
4376 let point_range = point_range.start.row..=point_range.end.row;
4377 if point_range.contains(&buffer_row) {
4378 Some((location, code_actions))
4379 } else {
4380 None
4381 }
4382 })
4383 .unzip();
4384 let buffer_id = buffer.read(cx).remote_id();
4385 let tasks = editor
4386 .tasks
4387 .get(&(buffer_id, buffer_row))
4388 .map(|t| Arc::new(t.to_owned()));
4389 if tasks.is_none() && code_actions.is_none() {
4390 return None;
4391 }
4392
4393 editor.completion_tasks.clear();
4394 editor.discard_inline_completion(false, cx);
4395 let task_context =
4396 tasks
4397 .as_ref()
4398 .zip(editor.project.clone())
4399 .map(|(tasks, project)| {
4400 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4401 });
4402
4403 Some(cx.spawn_in(window, |editor, mut cx| async move {
4404 let task_context = match task_context {
4405 Some(task_context) => task_context.await,
4406 None => None,
4407 };
4408 let resolved_tasks =
4409 tasks.zip(task_context).map(|(tasks, task_context)| {
4410 Rc::new(ResolvedTasks {
4411 templates: tasks.resolve(&task_context).collect(),
4412 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4413 multibuffer_point.row,
4414 tasks.column,
4415 )),
4416 })
4417 });
4418 let spawn_straight_away = resolved_tasks
4419 .as_ref()
4420 .map_or(false, |tasks| tasks.templates.len() == 1)
4421 && code_actions
4422 .as_ref()
4423 .map_or(true, |actions| actions.is_empty());
4424 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4425 *editor.context_menu.borrow_mut() =
4426 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4427 buffer,
4428 actions: CodeActionContents {
4429 tasks: resolved_tasks,
4430 actions: code_actions,
4431 },
4432 selected_item: Default::default(),
4433 scroll_handle: UniformListScrollHandle::default(),
4434 deployed_from_indicator,
4435 }));
4436 if spawn_straight_away {
4437 if let Some(task) = editor.confirm_code_action(
4438 &ConfirmCodeAction { item_ix: Some(0) },
4439 window,
4440 cx,
4441 ) {
4442 cx.notify();
4443 return task;
4444 }
4445 }
4446 cx.notify();
4447 Task::ready(Ok(()))
4448 }) {
4449 task.await
4450 } else {
4451 Ok(())
4452 }
4453 }))
4454 } else {
4455 Some(Task::ready(Ok(())))
4456 }
4457 })?;
4458 if let Some(task) = spawned_test_task {
4459 task.await?;
4460 }
4461
4462 Ok::<_, anyhow::Error>(())
4463 })
4464 .detach_and_log_err(cx);
4465 }
4466
4467 pub fn confirm_code_action(
4468 &mut self,
4469 action: &ConfirmCodeAction,
4470 window: &mut Window,
4471 cx: &mut Context<Self>,
4472 ) -> Option<Task<Result<()>>> {
4473 let actions_menu =
4474 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4475 menu
4476 } else {
4477 return None;
4478 };
4479 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4480 let action = actions_menu.actions.get(action_ix)?;
4481 let title = action.label();
4482 let buffer = actions_menu.buffer;
4483 let workspace = self.workspace()?;
4484
4485 match action {
4486 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4487 workspace.update(cx, |workspace, cx| {
4488 workspace::tasks::schedule_resolved_task(
4489 workspace,
4490 task_source_kind,
4491 resolved_task,
4492 false,
4493 cx,
4494 );
4495
4496 Some(Task::ready(Ok(())))
4497 })
4498 }
4499 CodeActionsItem::CodeAction {
4500 excerpt_id,
4501 action,
4502 provider,
4503 } => {
4504 let apply_code_action =
4505 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4506 let workspace = workspace.downgrade();
4507 Some(cx.spawn_in(window, |editor, cx| async move {
4508 let project_transaction = apply_code_action.await?;
4509 Self::open_project_transaction(
4510 &editor,
4511 workspace,
4512 project_transaction,
4513 title,
4514 cx,
4515 )
4516 .await
4517 }))
4518 }
4519 }
4520 }
4521
4522 pub async fn open_project_transaction(
4523 this: &WeakEntity<Editor>,
4524 workspace: WeakEntity<Workspace>,
4525 transaction: ProjectTransaction,
4526 title: String,
4527 mut cx: AsyncWindowContext,
4528 ) -> Result<()> {
4529 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4530 cx.update(|_, cx| {
4531 entries.sort_unstable_by_key(|(buffer, _)| {
4532 buffer.read(cx).file().map(|f| f.path().clone())
4533 });
4534 })?;
4535
4536 // If the project transaction's edits are all contained within this editor, then
4537 // avoid opening a new editor to display them.
4538
4539 if let Some((buffer, transaction)) = entries.first() {
4540 if entries.len() == 1 {
4541 let excerpt = this.update(&mut cx, |editor, cx| {
4542 editor
4543 .buffer()
4544 .read(cx)
4545 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4546 })?;
4547 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4548 if excerpted_buffer == *buffer {
4549 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4550 let excerpt_range = excerpt_range.to_offset(buffer);
4551 buffer
4552 .edited_ranges_for_transaction::<usize>(transaction)
4553 .all(|range| {
4554 excerpt_range.start <= range.start
4555 && excerpt_range.end >= range.end
4556 })
4557 })?;
4558
4559 if all_edits_within_excerpt {
4560 return Ok(());
4561 }
4562 }
4563 }
4564 }
4565 } else {
4566 return Ok(());
4567 }
4568
4569 let mut ranges_to_highlight = Vec::new();
4570 let excerpt_buffer = cx.new(|cx| {
4571 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4572 for (buffer_handle, transaction) in &entries {
4573 let buffer = buffer_handle.read(cx);
4574 ranges_to_highlight.extend(
4575 multibuffer.push_excerpts_with_context_lines(
4576 buffer_handle.clone(),
4577 buffer
4578 .edited_ranges_for_transaction::<usize>(transaction)
4579 .collect(),
4580 DEFAULT_MULTIBUFFER_CONTEXT,
4581 cx,
4582 ),
4583 );
4584 }
4585 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4586 multibuffer
4587 })?;
4588
4589 workspace.update_in(&mut cx, |workspace, window, cx| {
4590 let project = workspace.project().clone();
4591 let editor = cx
4592 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4593 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4594 editor.update(cx, |editor, cx| {
4595 editor.highlight_background::<Self>(
4596 &ranges_to_highlight,
4597 |theme| theme.editor_highlighted_line_background,
4598 cx,
4599 );
4600 });
4601 })?;
4602
4603 Ok(())
4604 }
4605
4606 pub fn clear_code_action_providers(&mut self) {
4607 self.code_action_providers.clear();
4608 self.available_code_actions.take();
4609 }
4610
4611 pub fn add_code_action_provider(
4612 &mut self,
4613 provider: Rc<dyn CodeActionProvider>,
4614 window: &mut Window,
4615 cx: &mut Context<Self>,
4616 ) {
4617 if self
4618 .code_action_providers
4619 .iter()
4620 .any(|existing_provider| existing_provider.id() == provider.id())
4621 {
4622 return;
4623 }
4624
4625 self.code_action_providers.push(provider);
4626 self.refresh_code_actions(window, cx);
4627 }
4628
4629 pub fn remove_code_action_provider(
4630 &mut self,
4631 id: Arc<str>,
4632 window: &mut Window,
4633 cx: &mut Context<Self>,
4634 ) {
4635 self.code_action_providers
4636 .retain(|provider| provider.id() != id);
4637 self.refresh_code_actions(window, cx);
4638 }
4639
4640 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4641 let buffer = self.buffer.read(cx);
4642 let newest_selection = self.selections.newest_anchor().clone();
4643 if newest_selection.head().diff_base_anchor.is_some() {
4644 return None;
4645 }
4646 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4647 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4648 if start_buffer != end_buffer {
4649 return None;
4650 }
4651
4652 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4653 cx.background_executor()
4654 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4655 .await;
4656
4657 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4658 let providers = this.code_action_providers.clone();
4659 let tasks = this
4660 .code_action_providers
4661 .iter()
4662 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4663 .collect::<Vec<_>>();
4664 (providers, tasks)
4665 })?;
4666
4667 let mut actions = Vec::new();
4668 for (provider, provider_actions) in
4669 providers.into_iter().zip(future::join_all(tasks).await)
4670 {
4671 if let Some(provider_actions) = provider_actions.log_err() {
4672 actions.extend(provider_actions.into_iter().map(|action| {
4673 AvailableCodeAction {
4674 excerpt_id: newest_selection.start.excerpt_id,
4675 action,
4676 provider: provider.clone(),
4677 }
4678 }));
4679 }
4680 }
4681
4682 this.update(&mut cx, |this, cx| {
4683 this.available_code_actions = if actions.is_empty() {
4684 None
4685 } else {
4686 Some((
4687 Location {
4688 buffer: start_buffer,
4689 range: start..end,
4690 },
4691 actions.into(),
4692 ))
4693 };
4694 cx.notify();
4695 })
4696 }));
4697 None
4698 }
4699
4700 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4701 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4702 self.show_git_blame_inline = false;
4703
4704 self.show_git_blame_inline_delay_task =
4705 Some(cx.spawn_in(window, |this, mut cx| async move {
4706 cx.background_executor().timer(delay).await;
4707
4708 this.update(&mut cx, |this, cx| {
4709 this.show_git_blame_inline = true;
4710 cx.notify();
4711 })
4712 .log_err();
4713 }));
4714 }
4715 }
4716
4717 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4718 if self.pending_rename.is_some() {
4719 return None;
4720 }
4721
4722 let provider = self.semantics_provider.clone()?;
4723 let buffer = self.buffer.read(cx);
4724 let newest_selection = self.selections.newest_anchor().clone();
4725 let cursor_position = newest_selection.head();
4726 let (cursor_buffer, cursor_buffer_position) =
4727 buffer.text_anchor_for_position(cursor_position, cx)?;
4728 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4729 if cursor_buffer != tail_buffer {
4730 return None;
4731 }
4732 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4733 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4734 cx.background_executor()
4735 .timer(Duration::from_millis(debounce))
4736 .await;
4737
4738 let highlights = if let Some(highlights) = cx
4739 .update(|cx| {
4740 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4741 })
4742 .ok()
4743 .flatten()
4744 {
4745 highlights.await.log_err()
4746 } else {
4747 None
4748 };
4749
4750 if let Some(highlights) = highlights {
4751 this.update(&mut cx, |this, cx| {
4752 if this.pending_rename.is_some() {
4753 return;
4754 }
4755
4756 let buffer_id = cursor_position.buffer_id;
4757 let buffer = this.buffer.read(cx);
4758 if !buffer
4759 .text_anchor_for_position(cursor_position, cx)
4760 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4761 {
4762 return;
4763 }
4764
4765 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4766 let mut write_ranges = Vec::new();
4767 let mut read_ranges = Vec::new();
4768 for highlight in highlights {
4769 for (excerpt_id, excerpt_range) in
4770 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4771 {
4772 let start = highlight
4773 .range
4774 .start
4775 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4776 let end = highlight
4777 .range
4778 .end
4779 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4780 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4781 continue;
4782 }
4783
4784 let range = Anchor {
4785 buffer_id,
4786 excerpt_id,
4787 text_anchor: start,
4788 diff_base_anchor: None,
4789 }..Anchor {
4790 buffer_id,
4791 excerpt_id,
4792 text_anchor: end,
4793 diff_base_anchor: None,
4794 };
4795 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4796 write_ranges.push(range);
4797 } else {
4798 read_ranges.push(range);
4799 }
4800 }
4801 }
4802
4803 this.highlight_background::<DocumentHighlightRead>(
4804 &read_ranges,
4805 |theme| theme.editor_document_highlight_read_background,
4806 cx,
4807 );
4808 this.highlight_background::<DocumentHighlightWrite>(
4809 &write_ranges,
4810 |theme| theme.editor_document_highlight_write_background,
4811 cx,
4812 );
4813 cx.notify();
4814 })
4815 .log_err();
4816 }
4817 }));
4818 None
4819 }
4820
4821 pub fn refresh_selected_text_highlights(
4822 &mut self,
4823 window: &mut Window,
4824 cx: &mut Context<Editor>,
4825 ) {
4826 self.selection_highlight_task.take();
4827 if !EditorSettings::get_global(cx).selection_highlight {
4828 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4829 return;
4830 }
4831 if self.selections.count() != 1 || self.selections.line_mode {
4832 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4833 return;
4834 }
4835 let selection = self.selections.newest::<Point>(cx);
4836 if selection.is_empty() || selection.start.row != selection.end.row {
4837 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4838 return;
4839 }
4840 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4841 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4842 cx.background_executor()
4843 .timer(Duration::from_millis(debounce))
4844 .await;
4845 let Some(Some(matches_task)) = editor
4846 .update_in(&mut cx, |editor, _, cx| {
4847 if editor.selections.count() != 1 || editor.selections.line_mode {
4848 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4849 return None;
4850 }
4851 let selection = editor.selections.newest::<Point>(cx);
4852 if selection.is_empty() || selection.start.row != selection.end.row {
4853 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4854 return None;
4855 }
4856 let buffer = editor.buffer().read(cx).snapshot(cx);
4857 let query = buffer.text_for_range(selection.range()).collect::<String>();
4858 if query.trim().is_empty() {
4859 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4860 return None;
4861 }
4862 Some(cx.background_spawn(async move {
4863 let mut ranges = Vec::new();
4864 let selection_anchors = selection.range().to_anchors(&buffer);
4865 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4866 for (search_buffer, search_range, excerpt_id) in
4867 buffer.range_to_buffer_ranges(range)
4868 {
4869 ranges.extend(
4870 project::search::SearchQuery::text(
4871 query.clone(),
4872 false,
4873 false,
4874 false,
4875 Default::default(),
4876 Default::default(),
4877 None,
4878 )
4879 .unwrap()
4880 .search(search_buffer, Some(search_range.clone()))
4881 .await
4882 .into_iter()
4883 .filter_map(
4884 |match_range| {
4885 let start = search_buffer.anchor_after(
4886 search_range.start + match_range.start,
4887 );
4888 let end = search_buffer.anchor_before(
4889 search_range.start + match_range.end,
4890 );
4891 let range = Anchor::range_in_buffer(
4892 excerpt_id,
4893 search_buffer.remote_id(),
4894 start..end,
4895 );
4896 (range != selection_anchors).then_some(range)
4897 },
4898 ),
4899 );
4900 }
4901 }
4902 ranges
4903 }))
4904 })
4905 .log_err()
4906 else {
4907 return;
4908 };
4909 let matches = matches_task.await;
4910 editor
4911 .update_in(&mut cx, |editor, _, cx| {
4912 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4913 if !matches.is_empty() {
4914 editor.highlight_background::<SelectedTextHighlight>(
4915 &matches,
4916 |theme| theme.editor_document_highlight_bracket_background,
4917 cx,
4918 )
4919 }
4920 })
4921 .log_err();
4922 }));
4923 }
4924
4925 pub fn refresh_inline_completion(
4926 &mut self,
4927 debounce: bool,
4928 user_requested: bool,
4929 window: &mut Window,
4930 cx: &mut Context<Self>,
4931 ) -> Option<()> {
4932 let provider = self.edit_prediction_provider()?;
4933 let cursor = self.selections.newest_anchor().head();
4934 let (buffer, cursor_buffer_position) =
4935 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4936
4937 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4938 self.discard_inline_completion(false, cx);
4939 return None;
4940 }
4941
4942 if !user_requested
4943 && (!self.should_show_edit_predictions()
4944 || !self.is_focused(window)
4945 || buffer.read(cx).is_empty())
4946 {
4947 self.discard_inline_completion(false, cx);
4948 return None;
4949 }
4950
4951 self.update_visible_inline_completion(window, cx);
4952 provider.refresh(
4953 self.project.clone(),
4954 buffer,
4955 cursor_buffer_position,
4956 debounce,
4957 cx,
4958 );
4959 Some(())
4960 }
4961
4962 fn show_edit_predictions_in_menu(&self) -> bool {
4963 match self.edit_prediction_settings {
4964 EditPredictionSettings::Disabled => false,
4965 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4966 }
4967 }
4968
4969 pub fn edit_predictions_enabled(&self) -> bool {
4970 match self.edit_prediction_settings {
4971 EditPredictionSettings::Disabled => false,
4972 EditPredictionSettings::Enabled { .. } => true,
4973 }
4974 }
4975
4976 fn edit_prediction_requires_modifier(&self) -> bool {
4977 match self.edit_prediction_settings {
4978 EditPredictionSettings::Disabled => false,
4979 EditPredictionSettings::Enabled {
4980 preview_requires_modifier,
4981 ..
4982 } => preview_requires_modifier,
4983 }
4984 }
4985
4986 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4987 if self.edit_prediction_provider.is_none() {
4988 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4989 } else {
4990 let selection = self.selections.newest_anchor();
4991 let cursor = selection.head();
4992
4993 if let Some((buffer, cursor_buffer_position)) =
4994 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4995 {
4996 self.edit_prediction_settings =
4997 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
4998 }
4999 }
5000 }
5001
5002 fn edit_prediction_settings_at_position(
5003 &self,
5004 buffer: &Entity<Buffer>,
5005 buffer_position: language::Anchor,
5006 cx: &App,
5007 ) -> EditPredictionSettings {
5008 if self.mode != EditorMode::Full
5009 || !self.show_inline_completions_override.unwrap_or(true)
5010 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5011 {
5012 return EditPredictionSettings::Disabled;
5013 }
5014
5015 let buffer = buffer.read(cx);
5016
5017 let file = buffer.file();
5018
5019 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5020 return EditPredictionSettings::Disabled;
5021 };
5022
5023 let by_provider = matches!(
5024 self.menu_inline_completions_policy,
5025 MenuInlineCompletionsPolicy::ByProvider
5026 );
5027
5028 let show_in_menu = by_provider
5029 && self
5030 .edit_prediction_provider
5031 .as_ref()
5032 .map_or(false, |provider| {
5033 provider.provider.show_completions_in_menu()
5034 });
5035
5036 let preview_requires_modifier =
5037 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5038
5039 EditPredictionSettings::Enabled {
5040 show_in_menu,
5041 preview_requires_modifier,
5042 }
5043 }
5044
5045 fn should_show_edit_predictions(&self) -> bool {
5046 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5047 }
5048
5049 pub fn edit_prediction_preview_is_active(&self) -> bool {
5050 matches!(
5051 self.edit_prediction_preview,
5052 EditPredictionPreview::Active { .. }
5053 )
5054 }
5055
5056 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5057 let cursor = self.selections.newest_anchor().head();
5058 if let Some((buffer, cursor_position)) =
5059 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5060 {
5061 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5062 } else {
5063 false
5064 }
5065 }
5066
5067 fn edit_predictions_enabled_in_buffer(
5068 &self,
5069 buffer: &Entity<Buffer>,
5070 buffer_position: language::Anchor,
5071 cx: &App,
5072 ) -> bool {
5073 maybe!({
5074 let provider = self.edit_prediction_provider()?;
5075 if !provider.is_enabled(&buffer, buffer_position, cx) {
5076 return Some(false);
5077 }
5078 let buffer = buffer.read(cx);
5079 let Some(file) = buffer.file() else {
5080 return Some(true);
5081 };
5082 let settings = all_language_settings(Some(file), cx);
5083 Some(settings.edit_predictions_enabled_for_file(file, cx))
5084 })
5085 .unwrap_or(false)
5086 }
5087
5088 fn cycle_inline_completion(
5089 &mut self,
5090 direction: Direction,
5091 window: &mut Window,
5092 cx: &mut Context<Self>,
5093 ) -> Option<()> {
5094 let provider = self.edit_prediction_provider()?;
5095 let cursor = self.selections.newest_anchor().head();
5096 let (buffer, cursor_buffer_position) =
5097 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5098 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5099 return None;
5100 }
5101
5102 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5103 self.update_visible_inline_completion(window, cx);
5104
5105 Some(())
5106 }
5107
5108 pub fn show_inline_completion(
5109 &mut self,
5110 _: &ShowEditPrediction,
5111 window: &mut Window,
5112 cx: &mut Context<Self>,
5113 ) {
5114 if !self.has_active_inline_completion() {
5115 self.refresh_inline_completion(false, true, window, cx);
5116 return;
5117 }
5118
5119 self.update_visible_inline_completion(window, cx);
5120 }
5121
5122 pub fn display_cursor_names(
5123 &mut self,
5124 _: &DisplayCursorNames,
5125 window: &mut Window,
5126 cx: &mut Context<Self>,
5127 ) {
5128 self.show_cursor_names(window, cx);
5129 }
5130
5131 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5132 self.show_cursor_names = true;
5133 cx.notify();
5134 cx.spawn_in(window, |this, mut cx| async move {
5135 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5136 this.update(&mut cx, |this, cx| {
5137 this.show_cursor_names = false;
5138 cx.notify()
5139 })
5140 .ok()
5141 })
5142 .detach();
5143 }
5144
5145 pub fn next_edit_prediction(
5146 &mut self,
5147 _: &NextEditPrediction,
5148 window: &mut Window,
5149 cx: &mut Context<Self>,
5150 ) {
5151 if self.has_active_inline_completion() {
5152 self.cycle_inline_completion(Direction::Next, window, cx);
5153 } else {
5154 let is_copilot_disabled = self
5155 .refresh_inline_completion(false, true, window, cx)
5156 .is_none();
5157 if is_copilot_disabled {
5158 cx.propagate();
5159 }
5160 }
5161 }
5162
5163 pub fn previous_edit_prediction(
5164 &mut self,
5165 _: &PreviousEditPrediction,
5166 window: &mut Window,
5167 cx: &mut Context<Self>,
5168 ) {
5169 if self.has_active_inline_completion() {
5170 self.cycle_inline_completion(Direction::Prev, window, cx);
5171 } else {
5172 let is_copilot_disabled = self
5173 .refresh_inline_completion(false, true, window, cx)
5174 .is_none();
5175 if is_copilot_disabled {
5176 cx.propagate();
5177 }
5178 }
5179 }
5180
5181 pub fn accept_edit_prediction(
5182 &mut self,
5183 _: &AcceptEditPrediction,
5184 window: &mut Window,
5185 cx: &mut Context<Self>,
5186 ) {
5187 if self.show_edit_predictions_in_menu() {
5188 self.hide_context_menu(window, cx);
5189 }
5190
5191 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5192 return;
5193 };
5194
5195 self.report_inline_completion_event(
5196 active_inline_completion.completion_id.clone(),
5197 true,
5198 cx,
5199 );
5200
5201 match &active_inline_completion.completion {
5202 InlineCompletion::Move { target, .. } => {
5203 let target = *target;
5204
5205 if let Some(position_map) = &self.last_position_map {
5206 if position_map
5207 .visible_row_range
5208 .contains(&target.to_display_point(&position_map.snapshot).row())
5209 || !self.edit_prediction_requires_modifier()
5210 {
5211 self.unfold_ranges(&[target..target], true, false, cx);
5212 // Note that this is also done in vim's handler of the Tab action.
5213 self.change_selections(
5214 Some(Autoscroll::newest()),
5215 window,
5216 cx,
5217 |selections| {
5218 selections.select_anchor_ranges([target..target]);
5219 },
5220 );
5221 self.clear_row_highlights::<EditPredictionPreview>();
5222
5223 self.edit_prediction_preview
5224 .set_previous_scroll_position(None);
5225 } else {
5226 self.edit_prediction_preview
5227 .set_previous_scroll_position(Some(
5228 position_map.snapshot.scroll_anchor,
5229 ));
5230
5231 self.highlight_rows::<EditPredictionPreview>(
5232 target..target,
5233 cx.theme().colors().editor_highlighted_line_background,
5234 true,
5235 cx,
5236 );
5237 self.request_autoscroll(Autoscroll::fit(), cx);
5238 }
5239 }
5240 }
5241 InlineCompletion::Edit { edits, .. } => {
5242 if let Some(provider) = self.edit_prediction_provider() {
5243 provider.accept(cx);
5244 }
5245
5246 let snapshot = self.buffer.read(cx).snapshot(cx);
5247 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5248
5249 self.buffer.update(cx, |buffer, cx| {
5250 buffer.edit(edits.iter().cloned(), None, cx)
5251 });
5252
5253 self.change_selections(None, window, cx, |s| {
5254 s.select_anchor_ranges([last_edit_end..last_edit_end])
5255 });
5256
5257 self.update_visible_inline_completion(window, cx);
5258 if self.active_inline_completion.is_none() {
5259 self.refresh_inline_completion(true, true, window, cx);
5260 }
5261
5262 cx.notify();
5263 }
5264 }
5265
5266 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5267 }
5268
5269 pub fn accept_partial_inline_completion(
5270 &mut self,
5271 _: &AcceptPartialEditPrediction,
5272 window: &mut Window,
5273 cx: &mut Context<Self>,
5274 ) {
5275 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5276 return;
5277 };
5278 if self.selections.count() != 1 {
5279 return;
5280 }
5281
5282 self.report_inline_completion_event(
5283 active_inline_completion.completion_id.clone(),
5284 true,
5285 cx,
5286 );
5287
5288 match &active_inline_completion.completion {
5289 InlineCompletion::Move { target, .. } => {
5290 let target = *target;
5291 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5292 selections.select_anchor_ranges([target..target]);
5293 });
5294 }
5295 InlineCompletion::Edit { edits, .. } => {
5296 // Find an insertion that starts at the cursor position.
5297 let snapshot = self.buffer.read(cx).snapshot(cx);
5298 let cursor_offset = self.selections.newest::<usize>(cx).head();
5299 let insertion = edits.iter().find_map(|(range, text)| {
5300 let range = range.to_offset(&snapshot);
5301 if range.is_empty() && range.start == cursor_offset {
5302 Some(text)
5303 } else {
5304 None
5305 }
5306 });
5307
5308 if let Some(text) = insertion {
5309 let mut partial_completion = text
5310 .chars()
5311 .by_ref()
5312 .take_while(|c| c.is_alphabetic())
5313 .collect::<String>();
5314 if partial_completion.is_empty() {
5315 partial_completion = text
5316 .chars()
5317 .by_ref()
5318 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5319 .collect::<String>();
5320 }
5321
5322 cx.emit(EditorEvent::InputHandled {
5323 utf16_range_to_replace: None,
5324 text: partial_completion.clone().into(),
5325 });
5326
5327 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5328
5329 self.refresh_inline_completion(true, true, window, cx);
5330 cx.notify();
5331 } else {
5332 self.accept_edit_prediction(&Default::default(), window, cx);
5333 }
5334 }
5335 }
5336 }
5337
5338 fn discard_inline_completion(
5339 &mut self,
5340 should_report_inline_completion_event: bool,
5341 cx: &mut Context<Self>,
5342 ) -> bool {
5343 if should_report_inline_completion_event {
5344 let completion_id = self
5345 .active_inline_completion
5346 .as_ref()
5347 .and_then(|active_completion| active_completion.completion_id.clone());
5348
5349 self.report_inline_completion_event(completion_id, false, cx);
5350 }
5351
5352 if let Some(provider) = self.edit_prediction_provider() {
5353 provider.discard(cx);
5354 }
5355
5356 self.take_active_inline_completion(cx)
5357 }
5358
5359 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5360 let Some(provider) = self.edit_prediction_provider() else {
5361 return;
5362 };
5363
5364 let Some((_, buffer, _)) = self
5365 .buffer
5366 .read(cx)
5367 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5368 else {
5369 return;
5370 };
5371
5372 let extension = buffer
5373 .read(cx)
5374 .file()
5375 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5376
5377 let event_type = match accepted {
5378 true => "Edit Prediction Accepted",
5379 false => "Edit Prediction Discarded",
5380 };
5381 telemetry::event!(
5382 event_type,
5383 provider = provider.name(),
5384 prediction_id = id,
5385 suggestion_accepted = accepted,
5386 file_extension = extension,
5387 );
5388 }
5389
5390 pub fn has_active_inline_completion(&self) -> bool {
5391 self.active_inline_completion.is_some()
5392 }
5393
5394 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5395 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5396 return false;
5397 };
5398
5399 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5400 self.clear_highlights::<InlineCompletionHighlight>(cx);
5401 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5402 true
5403 }
5404
5405 /// Returns true when we're displaying the edit prediction popover below the cursor
5406 /// like we are not previewing and the LSP autocomplete menu is visible
5407 /// or we are in `when_holding_modifier` mode.
5408 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5409 if self.edit_prediction_preview_is_active()
5410 || !self.show_edit_predictions_in_menu()
5411 || !self.edit_predictions_enabled()
5412 {
5413 return false;
5414 }
5415
5416 if self.has_visible_completions_menu() {
5417 return true;
5418 }
5419
5420 has_completion && self.edit_prediction_requires_modifier()
5421 }
5422
5423 fn handle_modifiers_changed(
5424 &mut self,
5425 modifiers: Modifiers,
5426 position_map: &PositionMap,
5427 window: &mut Window,
5428 cx: &mut Context<Self>,
5429 ) {
5430 if self.show_edit_predictions_in_menu() {
5431 self.update_edit_prediction_preview(&modifiers, window, cx);
5432 }
5433
5434 self.update_selection_mode(&modifiers, position_map, window, cx);
5435
5436 let mouse_position = window.mouse_position();
5437 if !position_map.text_hitbox.is_hovered(window) {
5438 return;
5439 }
5440
5441 self.update_hovered_link(
5442 position_map.point_for_position(mouse_position),
5443 &position_map.snapshot,
5444 modifiers,
5445 window,
5446 cx,
5447 )
5448 }
5449
5450 fn update_selection_mode(
5451 &mut self,
5452 modifiers: &Modifiers,
5453 position_map: &PositionMap,
5454 window: &mut Window,
5455 cx: &mut Context<Self>,
5456 ) {
5457 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5458 return;
5459 }
5460
5461 let mouse_position = window.mouse_position();
5462 let point_for_position = position_map.point_for_position(mouse_position);
5463 let position = point_for_position.previous_valid;
5464
5465 self.select(
5466 SelectPhase::BeginColumnar {
5467 position,
5468 reset: false,
5469 goal_column: point_for_position.exact_unclipped.column(),
5470 },
5471 window,
5472 cx,
5473 );
5474 }
5475
5476 fn update_edit_prediction_preview(
5477 &mut self,
5478 modifiers: &Modifiers,
5479 window: &mut Window,
5480 cx: &mut Context<Self>,
5481 ) {
5482 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5483 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5484 return;
5485 };
5486
5487 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5488 if matches!(
5489 self.edit_prediction_preview,
5490 EditPredictionPreview::Inactive { .. }
5491 ) {
5492 self.edit_prediction_preview = EditPredictionPreview::Active {
5493 previous_scroll_position: None,
5494 since: Instant::now(),
5495 };
5496
5497 self.update_visible_inline_completion(window, cx);
5498 cx.notify();
5499 }
5500 } else if let EditPredictionPreview::Active {
5501 previous_scroll_position,
5502 since,
5503 } = self.edit_prediction_preview
5504 {
5505 if let (Some(previous_scroll_position), Some(position_map)) =
5506 (previous_scroll_position, self.last_position_map.as_ref())
5507 {
5508 self.set_scroll_position(
5509 previous_scroll_position
5510 .scroll_position(&position_map.snapshot.display_snapshot),
5511 window,
5512 cx,
5513 );
5514 }
5515
5516 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5517 released_too_fast: since.elapsed() < Duration::from_millis(200),
5518 };
5519 self.clear_row_highlights::<EditPredictionPreview>();
5520 self.update_visible_inline_completion(window, cx);
5521 cx.notify();
5522 }
5523 }
5524
5525 fn update_visible_inline_completion(
5526 &mut self,
5527 _window: &mut Window,
5528 cx: &mut Context<Self>,
5529 ) -> Option<()> {
5530 let selection = self.selections.newest_anchor();
5531 let cursor = selection.head();
5532 let multibuffer = self.buffer.read(cx).snapshot(cx);
5533 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5534 let excerpt_id = cursor.excerpt_id;
5535
5536 let show_in_menu = self.show_edit_predictions_in_menu();
5537 let completions_menu_has_precedence = !show_in_menu
5538 && (self.context_menu.borrow().is_some()
5539 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5540
5541 if completions_menu_has_precedence
5542 || !offset_selection.is_empty()
5543 || self
5544 .active_inline_completion
5545 .as_ref()
5546 .map_or(false, |completion| {
5547 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5548 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5549 !invalidation_range.contains(&offset_selection.head())
5550 })
5551 {
5552 self.discard_inline_completion(false, cx);
5553 return None;
5554 }
5555
5556 self.take_active_inline_completion(cx);
5557 let Some(provider) = self.edit_prediction_provider() else {
5558 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5559 return None;
5560 };
5561
5562 let (buffer, cursor_buffer_position) =
5563 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5564
5565 self.edit_prediction_settings =
5566 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5567
5568 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5569
5570 if self.edit_prediction_indent_conflict {
5571 let cursor_point = cursor.to_point(&multibuffer);
5572
5573 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5574
5575 if let Some((_, indent)) = indents.iter().next() {
5576 if indent.len == cursor_point.column {
5577 self.edit_prediction_indent_conflict = false;
5578 }
5579 }
5580 }
5581
5582 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5583 let edits = inline_completion
5584 .edits
5585 .into_iter()
5586 .flat_map(|(range, new_text)| {
5587 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5588 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5589 Some((start..end, new_text))
5590 })
5591 .collect::<Vec<_>>();
5592 if edits.is_empty() {
5593 return None;
5594 }
5595
5596 let first_edit_start = edits.first().unwrap().0.start;
5597 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5598 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5599
5600 let last_edit_end = edits.last().unwrap().0.end;
5601 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5602 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5603
5604 let cursor_row = cursor.to_point(&multibuffer).row;
5605
5606 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5607
5608 let mut inlay_ids = Vec::new();
5609 let invalidation_row_range;
5610 let move_invalidation_row_range = if cursor_row < edit_start_row {
5611 Some(cursor_row..edit_end_row)
5612 } else if cursor_row > edit_end_row {
5613 Some(edit_start_row..cursor_row)
5614 } else {
5615 None
5616 };
5617 let is_move =
5618 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5619 let completion = if is_move {
5620 invalidation_row_range =
5621 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5622 let target = first_edit_start;
5623 InlineCompletion::Move { target, snapshot }
5624 } else {
5625 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5626 && !self.inline_completions_hidden_for_vim_mode;
5627
5628 if show_completions_in_buffer {
5629 if edits
5630 .iter()
5631 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5632 {
5633 let mut inlays = Vec::new();
5634 for (range, new_text) in &edits {
5635 let inlay = Inlay::inline_completion(
5636 post_inc(&mut self.next_inlay_id),
5637 range.start,
5638 new_text.as_str(),
5639 );
5640 inlay_ids.push(inlay.id);
5641 inlays.push(inlay);
5642 }
5643
5644 self.splice_inlays(&[], inlays, cx);
5645 } else {
5646 let background_color = cx.theme().status().deleted_background;
5647 self.highlight_text::<InlineCompletionHighlight>(
5648 edits.iter().map(|(range, _)| range.clone()).collect(),
5649 HighlightStyle {
5650 background_color: Some(background_color),
5651 ..Default::default()
5652 },
5653 cx,
5654 );
5655 }
5656 }
5657
5658 invalidation_row_range = edit_start_row..edit_end_row;
5659
5660 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5661 if provider.show_tab_accept_marker() {
5662 EditDisplayMode::TabAccept
5663 } else {
5664 EditDisplayMode::Inline
5665 }
5666 } else {
5667 EditDisplayMode::DiffPopover
5668 };
5669
5670 InlineCompletion::Edit {
5671 edits,
5672 edit_preview: inline_completion.edit_preview,
5673 display_mode,
5674 snapshot,
5675 }
5676 };
5677
5678 let invalidation_range = multibuffer
5679 .anchor_before(Point::new(invalidation_row_range.start, 0))
5680 ..multibuffer.anchor_after(Point::new(
5681 invalidation_row_range.end,
5682 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5683 ));
5684
5685 self.stale_inline_completion_in_menu = None;
5686 self.active_inline_completion = Some(InlineCompletionState {
5687 inlay_ids,
5688 completion,
5689 completion_id: inline_completion.id,
5690 invalidation_range,
5691 });
5692
5693 cx.notify();
5694
5695 Some(())
5696 }
5697
5698 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5699 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5700 }
5701
5702 fn render_code_actions_indicator(
5703 &self,
5704 _style: &EditorStyle,
5705 row: DisplayRow,
5706 is_active: bool,
5707 cx: &mut Context<Self>,
5708 ) -> Option<IconButton> {
5709 if self.available_code_actions.is_some() {
5710 Some(
5711 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5712 .shape(ui::IconButtonShape::Square)
5713 .icon_size(IconSize::XSmall)
5714 .icon_color(Color::Muted)
5715 .toggle_state(is_active)
5716 .tooltip({
5717 let focus_handle = self.focus_handle.clone();
5718 move |window, cx| {
5719 Tooltip::for_action_in(
5720 "Toggle Code Actions",
5721 &ToggleCodeActions {
5722 deployed_from_indicator: None,
5723 },
5724 &focus_handle,
5725 window,
5726 cx,
5727 )
5728 }
5729 })
5730 .on_click(cx.listener(move |editor, _e, window, cx| {
5731 window.focus(&editor.focus_handle(cx));
5732 editor.toggle_code_actions(
5733 &ToggleCodeActions {
5734 deployed_from_indicator: Some(row),
5735 },
5736 window,
5737 cx,
5738 );
5739 })),
5740 )
5741 } else {
5742 None
5743 }
5744 }
5745
5746 fn clear_tasks(&mut self) {
5747 self.tasks.clear()
5748 }
5749
5750 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5751 if self.tasks.insert(key, value).is_some() {
5752 // This case should hopefully be rare, but just in case...
5753 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5754 }
5755 }
5756
5757 fn build_tasks_context(
5758 project: &Entity<Project>,
5759 buffer: &Entity<Buffer>,
5760 buffer_row: u32,
5761 tasks: &Arc<RunnableTasks>,
5762 cx: &mut Context<Self>,
5763 ) -> Task<Option<task::TaskContext>> {
5764 let position = Point::new(buffer_row, tasks.column);
5765 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5766 let location = Location {
5767 buffer: buffer.clone(),
5768 range: range_start..range_start,
5769 };
5770 // Fill in the environmental variables from the tree-sitter captures
5771 let mut captured_task_variables = TaskVariables::default();
5772 for (capture_name, value) in tasks.extra_variables.clone() {
5773 captured_task_variables.insert(
5774 task::VariableName::Custom(capture_name.into()),
5775 value.clone(),
5776 );
5777 }
5778 project.update(cx, |project, cx| {
5779 project.task_store().update(cx, |task_store, cx| {
5780 task_store.task_context_for_location(captured_task_variables, location, cx)
5781 })
5782 })
5783 }
5784
5785 pub fn spawn_nearest_task(
5786 &mut self,
5787 action: &SpawnNearestTask,
5788 window: &mut Window,
5789 cx: &mut Context<Self>,
5790 ) {
5791 let Some((workspace, _)) = self.workspace.clone() else {
5792 return;
5793 };
5794 let Some(project) = self.project.clone() else {
5795 return;
5796 };
5797
5798 // Try to find a closest, enclosing node using tree-sitter that has a
5799 // task
5800 let Some((buffer, buffer_row, tasks)) = self
5801 .find_enclosing_node_task(cx)
5802 // Or find the task that's closest in row-distance.
5803 .or_else(|| self.find_closest_task(cx))
5804 else {
5805 return;
5806 };
5807
5808 let reveal_strategy = action.reveal;
5809 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5810 cx.spawn_in(window, |_, mut cx| async move {
5811 let context = task_context.await?;
5812 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5813
5814 let resolved = resolved_task.resolved.as_mut()?;
5815 resolved.reveal = reveal_strategy;
5816
5817 workspace
5818 .update(&mut cx, |workspace, cx| {
5819 workspace::tasks::schedule_resolved_task(
5820 workspace,
5821 task_source_kind,
5822 resolved_task,
5823 false,
5824 cx,
5825 );
5826 })
5827 .ok()
5828 })
5829 .detach();
5830 }
5831
5832 fn find_closest_task(
5833 &mut self,
5834 cx: &mut Context<Self>,
5835 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5836 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5837
5838 let ((buffer_id, row), tasks) = self
5839 .tasks
5840 .iter()
5841 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5842
5843 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5844 let tasks = Arc::new(tasks.to_owned());
5845 Some((buffer, *row, tasks))
5846 }
5847
5848 fn find_enclosing_node_task(
5849 &mut self,
5850 cx: &mut Context<Self>,
5851 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5852 let snapshot = self.buffer.read(cx).snapshot(cx);
5853 let offset = self.selections.newest::<usize>(cx).head();
5854 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5855 let buffer_id = excerpt.buffer().remote_id();
5856
5857 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5858 let mut cursor = layer.node().walk();
5859
5860 while cursor.goto_first_child_for_byte(offset).is_some() {
5861 if cursor.node().end_byte() == offset {
5862 cursor.goto_next_sibling();
5863 }
5864 }
5865
5866 // Ascend to the smallest ancestor that contains the range and has a task.
5867 loop {
5868 let node = cursor.node();
5869 let node_range = node.byte_range();
5870 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5871
5872 // Check if this node contains our offset
5873 if node_range.start <= offset && node_range.end >= offset {
5874 // If it contains offset, check for task
5875 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5876 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5877 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5878 }
5879 }
5880
5881 if !cursor.goto_parent() {
5882 break;
5883 }
5884 }
5885 None
5886 }
5887
5888 fn render_run_indicator(
5889 &self,
5890 _style: &EditorStyle,
5891 is_active: bool,
5892 row: DisplayRow,
5893 cx: &mut Context<Self>,
5894 ) -> IconButton {
5895 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5896 .shape(ui::IconButtonShape::Square)
5897 .icon_size(IconSize::XSmall)
5898 .icon_color(Color::Muted)
5899 .toggle_state(is_active)
5900 .on_click(cx.listener(move |editor, _e, window, cx| {
5901 window.focus(&editor.focus_handle(cx));
5902 editor.toggle_code_actions(
5903 &ToggleCodeActions {
5904 deployed_from_indicator: Some(row),
5905 },
5906 window,
5907 cx,
5908 );
5909 }))
5910 }
5911
5912 pub fn context_menu_visible(&self) -> bool {
5913 !self.edit_prediction_preview_is_active()
5914 && self
5915 .context_menu
5916 .borrow()
5917 .as_ref()
5918 .map_or(false, |menu| menu.visible())
5919 }
5920
5921 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5922 self.context_menu
5923 .borrow()
5924 .as_ref()
5925 .map(|menu| menu.origin())
5926 }
5927
5928 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5929 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5930
5931 #[allow(clippy::too_many_arguments)]
5932 fn render_edit_prediction_popover(
5933 &mut self,
5934 text_bounds: &Bounds<Pixels>,
5935 content_origin: gpui::Point<Pixels>,
5936 editor_snapshot: &EditorSnapshot,
5937 visible_row_range: Range<DisplayRow>,
5938 scroll_top: f32,
5939 scroll_bottom: f32,
5940 line_layouts: &[LineWithInvisibles],
5941 line_height: Pixels,
5942 scroll_pixel_position: gpui::Point<Pixels>,
5943 newest_selection_head: Option<DisplayPoint>,
5944 editor_width: Pixels,
5945 style: &EditorStyle,
5946 window: &mut Window,
5947 cx: &mut App,
5948 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5949 let active_inline_completion = self.active_inline_completion.as_ref()?;
5950
5951 if self.edit_prediction_visible_in_cursor_popover(true) {
5952 return None;
5953 }
5954
5955 match &active_inline_completion.completion {
5956 InlineCompletion::Move { target, .. } => {
5957 let target_display_point = target.to_display_point(editor_snapshot);
5958
5959 if self.edit_prediction_requires_modifier() {
5960 if !self.edit_prediction_preview_is_active() {
5961 return None;
5962 }
5963
5964 self.render_edit_prediction_modifier_jump_popover(
5965 text_bounds,
5966 content_origin,
5967 visible_row_range,
5968 line_layouts,
5969 line_height,
5970 scroll_pixel_position,
5971 newest_selection_head,
5972 target_display_point,
5973 window,
5974 cx,
5975 )
5976 } else {
5977 self.render_edit_prediction_eager_jump_popover(
5978 text_bounds,
5979 content_origin,
5980 editor_snapshot,
5981 visible_row_range,
5982 scroll_top,
5983 scroll_bottom,
5984 line_height,
5985 scroll_pixel_position,
5986 target_display_point,
5987 editor_width,
5988 window,
5989 cx,
5990 )
5991 }
5992 }
5993 InlineCompletion::Edit {
5994 display_mode: EditDisplayMode::Inline,
5995 ..
5996 } => None,
5997 InlineCompletion::Edit {
5998 display_mode: EditDisplayMode::TabAccept,
5999 edits,
6000 ..
6001 } => {
6002 let range = &edits.first()?.0;
6003 let target_display_point = range.end.to_display_point(editor_snapshot);
6004
6005 self.render_edit_prediction_end_of_line_popover(
6006 "Accept",
6007 editor_snapshot,
6008 visible_row_range,
6009 target_display_point,
6010 line_height,
6011 scroll_pixel_position,
6012 content_origin,
6013 editor_width,
6014 window,
6015 cx,
6016 )
6017 }
6018 InlineCompletion::Edit {
6019 edits,
6020 edit_preview,
6021 display_mode: EditDisplayMode::DiffPopover,
6022 snapshot,
6023 } => self.render_edit_prediction_diff_popover(
6024 text_bounds,
6025 content_origin,
6026 editor_snapshot,
6027 visible_row_range,
6028 line_layouts,
6029 line_height,
6030 scroll_pixel_position,
6031 newest_selection_head,
6032 editor_width,
6033 style,
6034 edits,
6035 edit_preview,
6036 snapshot,
6037 window,
6038 cx,
6039 ),
6040 }
6041 }
6042
6043 #[allow(clippy::too_many_arguments)]
6044 fn render_edit_prediction_modifier_jump_popover(
6045 &mut self,
6046 text_bounds: &Bounds<Pixels>,
6047 content_origin: gpui::Point<Pixels>,
6048 visible_row_range: Range<DisplayRow>,
6049 line_layouts: &[LineWithInvisibles],
6050 line_height: Pixels,
6051 scroll_pixel_position: gpui::Point<Pixels>,
6052 newest_selection_head: Option<DisplayPoint>,
6053 target_display_point: DisplayPoint,
6054 window: &mut Window,
6055 cx: &mut App,
6056 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6057 let scrolled_content_origin =
6058 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6059
6060 const SCROLL_PADDING_Y: Pixels = px(12.);
6061
6062 if target_display_point.row() < visible_row_range.start {
6063 return self.render_edit_prediction_scroll_popover(
6064 |_| SCROLL_PADDING_Y,
6065 IconName::ArrowUp,
6066 visible_row_range,
6067 line_layouts,
6068 newest_selection_head,
6069 scrolled_content_origin,
6070 window,
6071 cx,
6072 );
6073 } else if target_display_point.row() >= visible_row_range.end {
6074 return self.render_edit_prediction_scroll_popover(
6075 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6076 IconName::ArrowDown,
6077 visible_row_range,
6078 line_layouts,
6079 newest_selection_head,
6080 scrolled_content_origin,
6081 window,
6082 cx,
6083 );
6084 }
6085
6086 const POLE_WIDTH: Pixels = px(2.);
6087
6088 let line_layout =
6089 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6090 let target_column = target_display_point.column() as usize;
6091
6092 let target_x = line_layout.x_for_index(target_column);
6093 let target_y =
6094 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6095
6096 let flag_on_right = target_x < text_bounds.size.width / 2.;
6097
6098 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6099 border_color.l += 0.001;
6100
6101 let mut element = v_flex()
6102 .items_end()
6103 .when(flag_on_right, |el| el.items_start())
6104 .child(if flag_on_right {
6105 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6106 .rounded_bl(px(0.))
6107 .rounded_tl(px(0.))
6108 .border_l_2()
6109 .border_color(border_color)
6110 } else {
6111 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6112 .rounded_br(px(0.))
6113 .rounded_tr(px(0.))
6114 .border_r_2()
6115 .border_color(border_color)
6116 })
6117 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6118 .into_any();
6119
6120 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6121
6122 let mut origin = scrolled_content_origin + point(target_x, target_y)
6123 - point(
6124 if flag_on_right {
6125 POLE_WIDTH
6126 } else {
6127 size.width - POLE_WIDTH
6128 },
6129 size.height - line_height,
6130 );
6131
6132 origin.x = origin.x.max(content_origin.x);
6133
6134 element.prepaint_at(origin, window, cx);
6135
6136 Some((element, origin))
6137 }
6138
6139 #[allow(clippy::too_many_arguments)]
6140 fn render_edit_prediction_scroll_popover(
6141 &mut self,
6142 to_y: impl Fn(Size<Pixels>) -> Pixels,
6143 scroll_icon: IconName,
6144 visible_row_range: Range<DisplayRow>,
6145 line_layouts: &[LineWithInvisibles],
6146 newest_selection_head: Option<DisplayPoint>,
6147 scrolled_content_origin: gpui::Point<Pixels>,
6148 window: &mut Window,
6149 cx: &mut App,
6150 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6151 let mut element = self
6152 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6153 .into_any();
6154
6155 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6156
6157 let cursor = newest_selection_head?;
6158 let cursor_row_layout =
6159 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6160 let cursor_column = cursor.column() as usize;
6161
6162 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6163
6164 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6165
6166 element.prepaint_at(origin, window, cx);
6167 Some((element, origin))
6168 }
6169
6170 #[allow(clippy::too_many_arguments)]
6171 fn render_edit_prediction_eager_jump_popover(
6172 &mut self,
6173 text_bounds: &Bounds<Pixels>,
6174 content_origin: gpui::Point<Pixels>,
6175 editor_snapshot: &EditorSnapshot,
6176 visible_row_range: Range<DisplayRow>,
6177 scroll_top: f32,
6178 scroll_bottom: f32,
6179 line_height: Pixels,
6180 scroll_pixel_position: gpui::Point<Pixels>,
6181 target_display_point: DisplayPoint,
6182 editor_width: Pixels,
6183 window: &mut Window,
6184 cx: &mut App,
6185 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6186 if target_display_point.row().as_f32() < scroll_top {
6187 let mut element = self
6188 .render_edit_prediction_line_popover(
6189 "Jump to Edit",
6190 Some(IconName::ArrowUp),
6191 window,
6192 cx,
6193 )?
6194 .into_any();
6195
6196 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6197 let offset = point(
6198 (text_bounds.size.width - size.width) / 2.,
6199 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6200 );
6201
6202 let origin = text_bounds.origin + offset;
6203 element.prepaint_at(origin, window, cx);
6204 Some((element, origin))
6205 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6206 let mut element = self
6207 .render_edit_prediction_line_popover(
6208 "Jump to Edit",
6209 Some(IconName::ArrowDown),
6210 window,
6211 cx,
6212 )?
6213 .into_any();
6214
6215 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6216 let offset = point(
6217 (text_bounds.size.width - size.width) / 2.,
6218 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6219 );
6220
6221 let origin = text_bounds.origin + offset;
6222 element.prepaint_at(origin, window, cx);
6223 Some((element, origin))
6224 } else {
6225 self.render_edit_prediction_end_of_line_popover(
6226 "Jump to Edit",
6227 editor_snapshot,
6228 visible_row_range,
6229 target_display_point,
6230 line_height,
6231 scroll_pixel_position,
6232 content_origin,
6233 editor_width,
6234 window,
6235 cx,
6236 )
6237 }
6238 }
6239
6240 #[allow(clippy::too_many_arguments)]
6241 fn render_edit_prediction_end_of_line_popover(
6242 self: &mut Editor,
6243 label: &'static str,
6244 editor_snapshot: &EditorSnapshot,
6245 visible_row_range: Range<DisplayRow>,
6246 target_display_point: DisplayPoint,
6247 line_height: Pixels,
6248 scroll_pixel_position: gpui::Point<Pixels>,
6249 content_origin: gpui::Point<Pixels>,
6250 editor_width: Pixels,
6251 window: &mut Window,
6252 cx: &mut App,
6253 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6254 let target_line_end = DisplayPoint::new(
6255 target_display_point.row(),
6256 editor_snapshot.line_len(target_display_point.row()),
6257 );
6258
6259 let mut element = self
6260 .render_edit_prediction_line_popover(label, None, window, cx)?
6261 .into_any();
6262
6263 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6264
6265 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6266
6267 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6268 let mut origin = start_point
6269 + line_origin
6270 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6271 origin.x = origin.x.max(content_origin.x);
6272
6273 let max_x = content_origin.x + editor_width - size.width;
6274
6275 if origin.x > max_x {
6276 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6277
6278 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6279 origin.y += offset;
6280 IconName::ArrowUp
6281 } else {
6282 origin.y -= offset;
6283 IconName::ArrowDown
6284 };
6285
6286 element = self
6287 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6288 .into_any();
6289
6290 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6291
6292 origin.x = content_origin.x + editor_width - size.width - px(2.);
6293 }
6294
6295 element.prepaint_at(origin, window, cx);
6296 Some((element, origin))
6297 }
6298
6299 #[allow(clippy::too_many_arguments)]
6300 fn render_edit_prediction_diff_popover(
6301 self: &Editor,
6302 text_bounds: &Bounds<Pixels>,
6303 content_origin: gpui::Point<Pixels>,
6304 editor_snapshot: &EditorSnapshot,
6305 visible_row_range: Range<DisplayRow>,
6306 line_layouts: &[LineWithInvisibles],
6307 line_height: Pixels,
6308 scroll_pixel_position: gpui::Point<Pixels>,
6309 newest_selection_head: Option<DisplayPoint>,
6310 editor_width: Pixels,
6311 style: &EditorStyle,
6312 edits: &Vec<(Range<Anchor>, String)>,
6313 edit_preview: &Option<language::EditPreview>,
6314 snapshot: &language::BufferSnapshot,
6315 window: &mut Window,
6316 cx: &mut App,
6317 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6318 let edit_start = edits
6319 .first()
6320 .unwrap()
6321 .0
6322 .start
6323 .to_display_point(editor_snapshot);
6324 let edit_end = edits
6325 .last()
6326 .unwrap()
6327 .0
6328 .end
6329 .to_display_point(editor_snapshot);
6330
6331 let is_visible = visible_row_range.contains(&edit_start.row())
6332 || visible_row_range.contains(&edit_end.row());
6333 if !is_visible {
6334 return None;
6335 }
6336
6337 let highlighted_edits =
6338 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6339
6340 let styled_text = highlighted_edits.to_styled_text(&style.text);
6341 let line_count = highlighted_edits.text.lines().count();
6342
6343 const BORDER_WIDTH: Pixels = px(1.);
6344
6345 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6346 let has_keybind = keybind.is_some();
6347
6348 let mut element = h_flex()
6349 .items_start()
6350 .child(
6351 h_flex()
6352 .bg(cx.theme().colors().editor_background)
6353 .border(BORDER_WIDTH)
6354 .shadow_sm()
6355 .border_color(cx.theme().colors().border)
6356 .rounded_l_lg()
6357 .when(line_count > 1, |el| el.rounded_br_lg())
6358 .pr_1()
6359 .child(styled_text),
6360 )
6361 .child(
6362 h_flex()
6363 .h(line_height + BORDER_WIDTH * px(2.))
6364 .px_1p5()
6365 .gap_1()
6366 // Workaround: For some reason, there's a gap if we don't do this
6367 .ml(-BORDER_WIDTH)
6368 .shadow(smallvec![gpui::BoxShadow {
6369 color: gpui::black().opacity(0.05),
6370 offset: point(px(1.), px(1.)),
6371 blur_radius: px(2.),
6372 spread_radius: px(0.),
6373 }])
6374 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6375 .border(BORDER_WIDTH)
6376 .border_color(cx.theme().colors().border)
6377 .rounded_r_lg()
6378 .id("edit_prediction_diff_popover_keybind")
6379 .when(!has_keybind, |el| {
6380 let status_colors = cx.theme().status();
6381
6382 el.bg(status_colors.error_background)
6383 .border_color(status_colors.error.opacity(0.6))
6384 .child(Icon::new(IconName::Info).color(Color::Error))
6385 .cursor_default()
6386 .hoverable_tooltip(move |_window, cx| {
6387 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6388 })
6389 })
6390 .children(keybind),
6391 )
6392 .into_any();
6393
6394 let longest_row =
6395 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6396 let longest_line_width = if visible_row_range.contains(&longest_row) {
6397 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6398 } else {
6399 layout_line(
6400 longest_row,
6401 editor_snapshot,
6402 style,
6403 editor_width,
6404 |_| false,
6405 window,
6406 cx,
6407 )
6408 .width
6409 };
6410
6411 let viewport_bounds =
6412 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6413 right: -EditorElement::SCROLLBAR_WIDTH,
6414 ..Default::default()
6415 });
6416
6417 let x_after_longest =
6418 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6419 - scroll_pixel_position.x;
6420
6421 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6422
6423 // Fully visible if it can be displayed within the window (allow overlapping other
6424 // panes). However, this is only allowed if the popover starts within text_bounds.
6425 let can_position_to_the_right = x_after_longest < text_bounds.right()
6426 && x_after_longest + element_bounds.width < viewport_bounds.right();
6427
6428 let mut origin = if can_position_to_the_right {
6429 point(
6430 x_after_longest,
6431 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6432 - scroll_pixel_position.y,
6433 )
6434 } else {
6435 let cursor_row = newest_selection_head.map(|head| head.row());
6436 let above_edit = edit_start
6437 .row()
6438 .0
6439 .checked_sub(line_count as u32)
6440 .map(DisplayRow);
6441 let below_edit = Some(edit_end.row() + 1);
6442 let above_cursor =
6443 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6444 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6445
6446 // Place the edit popover adjacent to the edit if there is a location
6447 // available that is onscreen and does not obscure the cursor. Otherwise,
6448 // place it adjacent to the cursor.
6449 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6450 .into_iter()
6451 .flatten()
6452 .find(|&start_row| {
6453 let end_row = start_row + line_count as u32;
6454 visible_row_range.contains(&start_row)
6455 && visible_row_range.contains(&end_row)
6456 && cursor_row.map_or(true, |cursor_row| {
6457 !((start_row..end_row).contains(&cursor_row))
6458 })
6459 })?;
6460
6461 content_origin
6462 + point(
6463 -scroll_pixel_position.x,
6464 row_target.as_f32() * line_height - scroll_pixel_position.y,
6465 )
6466 };
6467
6468 origin.x -= BORDER_WIDTH;
6469
6470 window.defer_draw(element, origin, 1);
6471
6472 // Do not return an element, since it will already be drawn due to defer_draw.
6473 None
6474 }
6475
6476 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6477 px(30.)
6478 }
6479
6480 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6481 if self.read_only(cx) {
6482 cx.theme().players().read_only()
6483 } else {
6484 self.style.as_ref().unwrap().local_player
6485 }
6486 }
6487
6488 fn render_edit_prediction_accept_keybind(
6489 &self,
6490 window: &mut Window,
6491 cx: &App,
6492 ) -> Option<AnyElement> {
6493 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6494 let accept_keystroke = accept_binding.keystroke()?;
6495
6496 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6497
6498 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6499 Color::Accent
6500 } else {
6501 Color::Muted
6502 };
6503
6504 h_flex()
6505 .px_0p5()
6506 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6507 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6508 .text_size(TextSize::XSmall.rems(cx))
6509 .child(h_flex().children(ui::render_modifiers(
6510 &accept_keystroke.modifiers,
6511 PlatformStyle::platform(),
6512 Some(modifiers_color),
6513 Some(IconSize::XSmall.rems().into()),
6514 true,
6515 )))
6516 .when(is_platform_style_mac, |parent| {
6517 parent.child(accept_keystroke.key.clone())
6518 })
6519 .when(!is_platform_style_mac, |parent| {
6520 parent.child(
6521 Key::new(
6522 util::capitalize(&accept_keystroke.key),
6523 Some(Color::Default),
6524 )
6525 .size(Some(IconSize::XSmall.rems().into())),
6526 )
6527 })
6528 .into_any()
6529 .into()
6530 }
6531
6532 fn render_edit_prediction_line_popover(
6533 &self,
6534 label: impl Into<SharedString>,
6535 icon: Option<IconName>,
6536 window: &mut Window,
6537 cx: &App,
6538 ) -> Option<Stateful<Div>> {
6539 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6540
6541 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6542 let has_keybind = keybind.is_some();
6543
6544 let result = h_flex()
6545 .id("ep-line-popover")
6546 .py_0p5()
6547 .pl_1()
6548 .pr(padding_right)
6549 .gap_1()
6550 .rounded_md()
6551 .border_1()
6552 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6553 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6554 .shadow_sm()
6555 .when(!has_keybind, |el| {
6556 let status_colors = cx.theme().status();
6557
6558 el.bg(status_colors.error_background)
6559 .border_color(status_colors.error.opacity(0.6))
6560 .pl_2()
6561 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
6562 .cursor_default()
6563 .hoverable_tooltip(move |_window, cx| {
6564 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6565 })
6566 })
6567 .children(keybind)
6568 .child(
6569 Label::new(label)
6570 .size(LabelSize::Small)
6571 .when(!has_keybind, |el| {
6572 el.color(cx.theme().status().error.into()).strikethrough()
6573 }),
6574 )
6575 .when(!has_keybind, |el| {
6576 el.child(
6577 h_flex().ml_1().child(
6578 Icon::new(IconName::Info)
6579 .size(IconSize::Small)
6580 .color(cx.theme().status().error.into()),
6581 ),
6582 )
6583 })
6584 .when_some(icon, |element, icon| {
6585 element.child(
6586 div()
6587 .mt(px(1.5))
6588 .child(Icon::new(icon).size(IconSize::Small)),
6589 )
6590 });
6591
6592 Some(result)
6593 }
6594
6595 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6596 let accent_color = cx.theme().colors().text_accent;
6597 let editor_bg_color = cx.theme().colors().editor_background;
6598 editor_bg_color.blend(accent_color.opacity(0.1))
6599 }
6600
6601 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6602 let accent_color = cx.theme().colors().text_accent;
6603 let editor_bg_color = cx.theme().colors().editor_background;
6604 editor_bg_color.blend(accent_color.opacity(0.6))
6605 }
6606
6607 #[allow(clippy::too_many_arguments)]
6608 fn render_edit_prediction_cursor_popover(
6609 &self,
6610 min_width: Pixels,
6611 max_width: Pixels,
6612 cursor_point: Point,
6613 style: &EditorStyle,
6614 accept_keystroke: Option<&gpui::Keystroke>,
6615 _window: &Window,
6616 cx: &mut Context<Editor>,
6617 ) -> Option<AnyElement> {
6618 let provider = self.edit_prediction_provider.as_ref()?;
6619
6620 if provider.provider.needs_terms_acceptance(cx) {
6621 return Some(
6622 h_flex()
6623 .min_w(min_width)
6624 .flex_1()
6625 .px_2()
6626 .py_1()
6627 .gap_3()
6628 .elevation_2(cx)
6629 .hover(|style| style.bg(cx.theme().colors().element_hover))
6630 .id("accept-terms")
6631 .cursor_pointer()
6632 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6633 .on_click(cx.listener(|this, _event, window, cx| {
6634 cx.stop_propagation();
6635 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6636 window.dispatch_action(
6637 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6638 cx,
6639 );
6640 }))
6641 .child(
6642 h_flex()
6643 .flex_1()
6644 .gap_2()
6645 .child(Icon::new(IconName::ZedPredict))
6646 .child(Label::new("Accept Terms of Service"))
6647 .child(div().w_full())
6648 .child(
6649 Icon::new(IconName::ArrowUpRight)
6650 .color(Color::Muted)
6651 .size(IconSize::Small),
6652 )
6653 .into_any_element(),
6654 )
6655 .into_any(),
6656 );
6657 }
6658
6659 let is_refreshing = provider.provider.is_refreshing(cx);
6660
6661 fn pending_completion_container() -> Div {
6662 h_flex()
6663 .h_full()
6664 .flex_1()
6665 .gap_2()
6666 .child(Icon::new(IconName::ZedPredict))
6667 }
6668
6669 let completion = match &self.active_inline_completion {
6670 Some(prediction) => {
6671 if !self.has_visible_completions_menu() {
6672 const RADIUS: Pixels = px(6.);
6673 const BORDER_WIDTH: Pixels = px(1.);
6674
6675 return Some(
6676 h_flex()
6677 .elevation_2(cx)
6678 .border(BORDER_WIDTH)
6679 .border_color(cx.theme().colors().border)
6680 .when(accept_keystroke.is_none(), |el| {
6681 el.border_color(cx.theme().status().error)
6682 })
6683 .rounded(RADIUS)
6684 .rounded_tl(px(0.))
6685 .overflow_hidden()
6686 .child(div().px_1p5().child(match &prediction.completion {
6687 InlineCompletion::Move { target, snapshot } => {
6688 use text::ToPoint as _;
6689 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6690 {
6691 Icon::new(IconName::ZedPredictDown)
6692 } else {
6693 Icon::new(IconName::ZedPredictUp)
6694 }
6695 }
6696 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6697 }))
6698 .child(
6699 h_flex()
6700 .gap_1()
6701 .py_1()
6702 .px_2()
6703 .rounded_r(RADIUS - BORDER_WIDTH)
6704 .border_l_1()
6705 .border_color(cx.theme().colors().border)
6706 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6707 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6708 el.child(
6709 Label::new("Hold")
6710 .size(LabelSize::Small)
6711 .when(accept_keystroke.is_none(), |el| {
6712 el.strikethrough()
6713 })
6714 .line_height_style(LineHeightStyle::UiLabel),
6715 )
6716 })
6717 .id("edit_prediction_cursor_popover_keybind")
6718 .when(accept_keystroke.is_none(), |el| {
6719 let status_colors = cx.theme().status();
6720
6721 el.bg(status_colors.error_background)
6722 .border_color(status_colors.error.opacity(0.6))
6723 .child(Icon::new(IconName::Info).color(Color::Error))
6724 .cursor_default()
6725 .hoverable_tooltip(move |_window, cx| {
6726 cx.new(|_| MissingEditPredictionKeybindingTooltip)
6727 .into()
6728 })
6729 })
6730 .when_some(
6731 accept_keystroke.as_ref(),
6732 |el, accept_keystroke| {
6733 el.child(h_flex().children(ui::render_modifiers(
6734 &accept_keystroke.modifiers,
6735 PlatformStyle::platform(),
6736 Some(Color::Default),
6737 Some(IconSize::XSmall.rems().into()),
6738 false,
6739 )))
6740 },
6741 ),
6742 )
6743 .into_any(),
6744 );
6745 }
6746
6747 self.render_edit_prediction_cursor_popover_preview(
6748 prediction,
6749 cursor_point,
6750 style,
6751 cx,
6752 )?
6753 }
6754
6755 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6756 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6757 stale_completion,
6758 cursor_point,
6759 style,
6760 cx,
6761 )?,
6762
6763 None => {
6764 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6765 }
6766 },
6767
6768 None => pending_completion_container().child(Label::new("No Prediction")),
6769 };
6770
6771 let completion = if is_refreshing {
6772 completion
6773 .with_animation(
6774 "loading-completion",
6775 Animation::new(Duration::from_secs(2))
6776 .repeat()
6777 .with_easing(pulsating_between(0.4, 0.8)),
6778 |label, delta| label.opacity(delta),
6779 )
6780 .into_any_element()
6781 } else {
6782 completion.into_any_element()
6783 };
6784
6785 let has_completion = self.active_inline_completion.is_some();
6786
6787 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6788 Some(
6789 h_flex()
6790 .min_w(min_width)
6791 .max_w(max_width)
6792 .flex_1()
6793 .elevation_2(cx)
6794 .border_color(cx.theme().colors().border)
6795 .child(
6796 div()
6797 .flex_1()
6798 .py_1()
6799 .px_2()
6800 .overflow_hidden()
6801 .child(completion),
6802 )
6803 .when_some(accept_keystroke, |el, accept_keystroke| {
6804 if !accept_keystroke.modifiers.modified() {
6805 return el;
6806 }
6807
6808 el.child(
6809 h_flex()
6810 .h_full()
6811 .border_l_1()
6812 .rounded_r_lg()
6813 .border_color(cx.theme().colors().border)
6814 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6815 .gap_1()
6816 .py_1()
6817 .px_2()
6818 .child(
6819 h_flex()
6820 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6821 .when(is_platform_style_mac, |parent| parent.gap_1())
6822 .child(h_flex().children(ui::render_modifiers(
6823 &accept_keystroke.modifiers,
6824 PlatformStyle::platform(),
6825 Some(if !has_completion {
6826 Color::Muted
6827 } else {
6828 Color::Default
6829 }),
6830 None,
6831 false,
6832 ))),
6833 )
6834 .child(Label::new("Preview").into_any_element())
6835 .opacity(if has_completion { 1.0 } else { 0.4 }),
6836 )
6837 })
6838 .into_any(),
6839 )
6840 }
6841
6842 fn render_edit_prediction_cursor_popover_preview(
6843 &self,
6844 completion: &InlineCompletionState,
6845 cursor_point: Point,
6846 style: &EditorStyle,
6847 cx: &mut Context<Editor>,
6848 ) -> Option<Div> {
6849 use text::ToPoint as _;
6850
6851 fn render_relative_row_jump(
6852 prefix: impl Into<String>,
6853 current_row: u32,
6854 target_row: u32,
6855 ) -> Div {
6856 let (row_diff, arrow) = if target_row < current_row {
6857 (current_row - target_row, IconName::ArrowUp)
6858 } else {
6859 (target_row - current_row, IconName::ArrowDown)
6860 };
6861
6862 h_flex()
6863 .child(
6864 Label::new(format!("{}{}", prefix.into(), row_diff))
6865 .color(Color::Muted)
6866 .size(LabelSize::Small),
6867 )
6868 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6869 }
6870
6871 match &completion.completion {
6872 InlineCompletion::Move {
6873 target, snapshot, ..
6874 } => Some(
6875 h_flex()
6876 .px_2()
6877 .gap_2()
6878 .flex_1()
6879 .child(
6880 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6881 Icon::new(IconName::ZedPredictDown)
6882 } else {
6883 Icon::new(IconName::ZedPredictUp)
6884 },
6885 )
6886 .child(Label::new("Jump to Edit")),
6887 ),
6888
6889 InlineCompletion::Edit {
6890 edits,
6891 edit_preview,
6892 snapshot,
6893 display_mode: _,
6894 } => {
6895 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6896
6897 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6898 &snapshot,
6899 &edits,
6900 edit_preview.as_ref()?,
6901 true,
6902 cx,
6903 )
6904 .first_line_preview();
6905
6906 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6907 .with_default_highlights(&style.text, highlighted_edits.highlights);
6908
6909 let preview = h_flex()
6910 .gap_1()
6911 .min_w_16()
6912 .child(styled_text)
6913 .when(has_more_lines, |parent| parent.child("…"));
6914
6915 let left = if first_edit_row != cursor_point.row {
6916 render_relative_row_jump("", cursor_point.row, first_edit_row)
6917 .into_any_element()
6918 } else {
6919 Icon::new(IconName::ZedPredict).into_any_element()
6920 };
6921
6922 Some(
6923 h_flex()
6924 .h_full()
6925 .flex_1()
6926 .gap_2()
6927 .pr_1()
6928 .overflow_x_hidden()
6929 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6930 .child(left)
6931 .child(preview),
6932 )
6933 }
6934 }
6935 }
6936
6937 fn render_context_menu(
6938 &self,
6939 style: &EditorStyle,
6940 max_height_in_lines: u32,
6941 y_flipped: bool,
6942 window: &mut Window,
6943 cx: &mut Context<Editor>,
6944 ) -> Option<AnyElement> {
6945 let menu = self.context_menu.borrow();
6946 let menu = menu.as_ref()?;
6947 if !menu.visible() {
6948 return None;
6949 };
6950 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6951 }
6952
6953 fn render_context_menu_aside(
6954 &mut self,
6955 max_size: Size<Pixels>,
6956 window: &mut Window,
6957 cx: &mut Context<Editor>,
6958 ) -> Option<AnyElement> {
6959 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6960 if menu.visible() {
6961 menu.render_aside(self, max_size, window, cx)
6962 } else {
6963 None
6964 }
6965 })
6966 }
6967
6968 fn hide_context_menu(
6969 &mut self,
6970 window: &mut Window,
6971 cx: &mut Context<Self>,
6972 ) -> Option<CodeContextMenu> {
6973 cx.notify();
6974 self.completion_tasks.clear();
6975 let context_menu = self.context_menu.borrow_mut().take();
6976 self.stale_inline_completion_in_menu.take();
6977 self.update_visible_inline_completion(window, cx);
6978 context_menu
6979 }
6980
6981 fn show_snippet_choices(
6982 &mut self,
6983 choices: &Vec<String>,
6984 selection: Range<Anchor>,
6985 cx: &mut Context<Self>,
6986 ) {
6987 if selection.start.buffer_id.is_none() {
6988 return;
6989 }
6990 let buffer_id = selection.start.buffer_id.unwrap();
6991 let buffer = self.buffer().read(cx).buffer(buffer_id);
6992 let id = post_inc(&mut self.next_completion_id);
6993
6994 if let Some(buffer) = buffer {
6995 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6996 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6997 ));
6998 }
6999 }
7000
7001 pub fn insert_snippet(
7002 &mut self,
7003 insertion_ranges: &[Range<usize>],
7004 snippet: Snippet,
7005 window: &mut Window,
7006 cx: &mut Context<Self>,
7007 ) -> Result<()> {
7008 struct Tabstop<T> {
7009 is_end_tabstop: bool,
7010 ranges: Vec<Range<T>>,
7011 choices: Option<Vec<String>>,
7012 }
7013
7014 let tabstops = self.buffer.update(cx, |buffer, cx| {
7015 let snippet_text: Arc<str> = snippet.text.clone().into();
7016 buffer.edit(
7017 insertion_ranges
7018 .iter()
7019 .cloned()
7020 .map(|range| (range, snippet_text.clone())),
7021 Some(AutoindentMode::EachLine),
7022 cx,
7023 );
7024
7025 let snapshot = &*buffer.read(cx);
7026 let snippet = &snippet;
7027 snippet
7028 .tabstops
7029 .iter()
7030 .map(|tabstop| {
7031 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7032 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7033 });
7034 let mut tabstop_ranges = tabstop
7035 .ranges
7036 .iter()
7037 .flat_map(|tabstop_range| {
7038 let mut delta = 0_isize;
7039 insertion_ranges.iter().map(move |insertion_range| {
7040 let insertion_start = insertion_range.start as isize + delta;
7041 delta +=
7042 snippet.text.len() as isize - insertion_range.len() as isize;
7043
7044 let start = ((insertion_start + tabstop_range.start) as usize)
7045 .min(snapshot.len());
7046 let end = ((insertion_start + tabstop_range.end) as usize)
7047 .min(snapshot.len());
7048 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7049 })
7050 })
7051 .collect::<Vec<_>>();
7052 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7053
7054 Tabstop {
7055 is_end_tabstop,
7056 ranges: tabstop_ranges,
7057 choices: tabstop.choices.clone(),
7058 }
7059 })
7060 .collect::<Vec<_>>()
7061 });
7062 if let Some(tabstop) = tabstops.first() {
7063 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7064 s.select_ranges(tabstop.ranges.iter().cloned());
7065 });
7066
7067 if let Some(choices) = &tabstop.choices {
7068 if let Some(selection) = tabstop.ranges.first() {
7069 self.show_snippet_choices(choices, selection.clone(), cx)
7070 }
7071 }
7072
7073 // If we're already at the last tabstop and it's at the end of the snippet,
7074 // we're done, we don't need to keep the state around.
7075 if !tabstop.is_end_tabstop {
7076 let choices = tabstops
7077 .iter()
7078 .map(|tabstop| tabstop.choices.clone())
7079 .collect();
7080
7081 let ranges = tabstops
7082 .into_iter()
7083 .map(|tabstop| tabstop.ranges)
7084 .collect::<Vec<_>>();
7085
7086 self.snippet_stack.push(SnippetState {
7087 active_index: 0,
7088 ranges,
7089 choices,
7090 });
7091 }
7092
7093 // Check whether the just-entered snippet ends with an auto-closable bracket.
7094 if self.autoclose_regions.is_empty() {
7095 let snapshot = self.buffer.read(cx).snapshot(cx);
7096 for selection in &mut self.selections.all::<Point>(cx) {
7097 let selection_head = selection.head();
7098 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7099 continue;
7100 };
7101
7102 let mut bracket_pair = None;
7103 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7104 let prev_chars = snapshot
7105 .reversed_chars_at(selection_head)
7106 .collect::<String>();
7107 for (pair, enabled) in scope.brackets() {
7108 if enabled
7109 && pair.close
7110 && prev_chars.starts_with(pair.start.as_str())
7111 && next_chars.starts_with(pair.end.as_str())
7112 {
7113 bracket_pair = Some(pair.clone());
7114 break;
7115 }
7116 }
7117 if let Some(pair) = bracket_pair {
7118 let start = snapshot.anchor_after(selection_head);
7119 let end = snapshot.anchor_after(selection_head);
7120 self.autoclose_regions.push(AutocloseRegion {
7121 selection_id: selection.id,
7122 range: start..end,
7123 pair,
7124 });
7125 }
7126 }
7127 }
7128 }
7129 Ok(())
7130 }
7131
7132 pub fn move_to_next_snippet_tabstop(
7133 &mut self,
7134 window: &mut Window,
7135 cx: &mut Context<Self>,
7136 ) -> bool {
7137 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7138 }
7139
7140 pub fn move_to_prev_snippet_tabstop(
7141 &mut self,
7142 window: &mut Window,
7143 cx: &mut Context<Self>,
7144 ) -> bool {
7145 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7146 }
7147
7148 pub fn move_to_snippet_tabstop(
7149 &mut self,
7150 bias: Bias,
7151 window: &mut Window,
7152 cx: &mut Context<Self>,
7153 ) -> bool {
7154 if let Some(mut snippet) = self.snippet_stack.pop() {
7155 match bias {
7156 Bias::Left => {
7157 if snippet.active_index > 0 {
7158 snippet.active_index -= 1;
7159 } else {
7160 self.snippet_stack.push(snippet);
7161 return false;
7162 }
7163 }
7164 Bias::Right => {
7165 if snippet.active_index + 1 < snippet.ranges.len() {
7166 snippet.active_index += 1;
7167 } else {
7168 self.snippet_stack.push(snippet);
7169 return false;
7170 }
7171 }
7172 }
7173 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7174 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7175 s.select_anchor_ranges(current_ranges.iter().cloned())
7176 });
7177
7178 if let Some(choices) = &snippet.choices[snippet.active_index] {
7179 if let Some(selection) = current_ranges.first() {
7180 self.show_snippet_choices(&choices, selection.clone(), cx);
7181 }
7182 }
7183
7184 // If snippet state is not at the last tabstop, push it back on the stack
7185 if snippet.active_index + 1 < snippet.ranges.len() {
7186 self.snippet_stack.push(snippet);
7187 }
7188 return true;
7189 }
7190 }
7191
7192 false
7193 }
7194
7195 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7196 self.transact(window, cx, |this, window, cx| {
7197 this.select_all(&SelectAll, window, cx);
7198 this.insert("", window, cx);
7199 });
7200 }
7201
7202 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7203 self.transact(window, cx, |this, window, cx| {
7204 this.select_autoclose_pair(window, cx);
7205 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7206 if !this.linked_edit_ranges.is_empty() {
7207 let selections = this.selections.all::<MultiBufferPoint>(cx);
7208 let snapshot = this.buffer.read(cx).snapshot(cx);
7209
7210 for selection in selections.iter() {
7211 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7212 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7213 if selection_start.buffer_id != selection_end.buffer_id {
7214 continue;
7215 }
7216 if let Some(ranges) =
7217 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7218 {
7219 for (buffer, entries) in ranges {
7220 linked_ranges.entry(buffer).or_default().extend(entries);
7221 }
7222 }
7223 }
7224 }
7225
7226 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7227 if !this.selections.line_mode {
7228 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7229 for selection in &mut selections {
7230 if selection.is_empty() {
7231 let old_head = selection.head();
7232 let mut new_head =
7233 movement::left(&display_map, old_head.to_display_point(&display_map))
7234 .to_point(&display_map);
7235 if let Some((buffer, line_buffer_range)) = display_map
7236 .buffer_snapshot
7237 .buffer_line_for_row(MultiBufferRow(old_head.row))
7238 {
7239 let indent_size =
7240 buffer.indent_size_for_line(line_buffer_range.start.row);
7241 let indent_len = match indent_size.kind {
7242 IndentKind::Space => {
7243 buffer.settings_at(line_buffer_range.start, cx).tab_size
7244 }
7245 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7246 };
7247 if old_head.column <= indent_size.len && old_head.column > 0 {
7248 let indent_len = indent_len.get();
7249 new_head = cmp::min(
7250 new_head,
7251 MultiBufferPoint::new(
7252 old_head.row,
7253 ((old_head.column - 1) / indent_len) * indent_len,
7254 ),
7255 );
7256 }
7257 }
7258
7259 selection.set_head(new_head, SelectionGoal::None);
7260 }
7261 }
7262 }
7263
7264 this.signature_help_state.set_backspace_pressed(true);
7265 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7266 s.select(selections)
7267 });
7268 this.insert("", window, cx);
7269 let empty_str: Arc<str> = Arc::from("");
7270 for (buffer, edits) in linked_ranges {
7271 let snapshot = buffer.read(cx).snapshot();
7272 use text::ToPoint as TP;
7273
7274 let edits = edits
7275 .into_iter()
7276 .map(|range| {
7277 let end_point = TP::to_point(&range.end, &snapshot);
7278 let mut start_point = TP::to_point(&range.start, &snapshot);
7279
7280 if end_point == start_point {
7281 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7282 .saturating_sub(1);
7283 start_point =
7284 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7285 };
7286
7287 (start_point..end_point, empty_str.clone())
7288 })
7289 .sorted_by_key(|(range, _)| range.start)
7290 .collect::<Vec<_>>();
7291 buffer.update(cx, |this, cx| {
7292 this.edit(edits, None, cx);
7293 })
7294 }
7295 this.refresh_inline_completion(true, false, window, cx);
7296 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7297 });
7298 }
7299
7300 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7301 self.transact(window, cx, |this, window, cx| {
7302 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7303 let line_mode = s.line_mode;
7304 s.move_with(|map, selection| {
7305 if selection.is_empty() && !line_mode {
7306 let cursor = movement::right(map, selection.head());
7307 selection.end = cursor;
7308 selection.reversed = true;
7309 selection.goal = SelectionGoal::None;
7310 }
7311 })
7312 });
7313 this.insert("", window, cx);
7314 this.refresh_inline_completion(true, false, window, cx);
7315 });
7316 }
7317
7318 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7319 if self.move_to_prev_snippet_tabstop(window, cx) {
7320 return;
7321 }
7322
7323 self.outdent(&Outdent, window, cx);
7324 }
7325
7326 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7327 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7328 return;
7329 }
7330
7331 let mut selections = self.selections.all_adjusted(cx);
7332 let buffer = self.buffer.read(cx);
7333 let snapshot = buffer.snapshot(cx);
7334 let rows_iter = selections.iter().map(|s| s.head().row);
7335 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7336
7337 let mut edits = Vec::new();
7338 let mut prev_edited_row = 0;
7339 let mut row_delta = 0;
7340 for selection in &mut selections {
7341 if selection.start.row != prev_edited_row {
7342 row_delta = 0;
7343 }
7344 prev_edited_row = selection.end.row;
7345
7346 // If the selection is non-empty, then increase the indentation of the selected lines.
7347 if !selection.is_empty() {
7348 row_delta =
7349 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7350 continue;
7351 }
7352
7353 // If the selection is empty and the cursor is in the leading whitespace before the
7354 // suggested indentation, then auto-indent the line.
7355 let cursor = selection.head();
7356 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7357 if let Some(suggested_indent) =
7358 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7359 {
7360 if cursor.column < suggested_indent.len
7361 && cursor.column <= current_indent.len
7362 && current_indent.len <= suggested_indent.len
7363 {
7364 selection.start = Point::new(cursor.row, suggested_indent.len);
7365 selection.end = selection.start;
7366 if row_delta == 0 {
7367 edits.extend(Buffer::edit_for_indent_size_adjustment(
7368 cursor.row,
7369 current_indent,
7370 suggested_indent,
7371 ));
7372 row_delta = suggested_indent.len - current_indent.len;
7373 }
7374 continue;
7375 }
7376 }
7377
7378 // Otherwise, insert a hard or soft tab.
7379 let settings = buffer.language_settings_at(cursor, cx);
7380 let tab_size = if settings.hard_tabs {
7381 IndentSize::tab()
7382 } else {
7383 let tab_size = settings.tab_size.get();
7384 let char_column = snapshot
7385 .text_for_range(Point::new(cursor.row, 0)..cursor)
7386 .flat_map(str::chars)
7387 .count()
7388 + row_delta as usize;
7389 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7390 IndentSize::spaces(chars_to_next_tab_stop)
7391 };
7392 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7393 selection.end = selection.start;
7394 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7395 row_delta += tab_size.len;
7396 }
7397
7398 self.transact(window, cx, |this, window, cx| {
7399 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7400 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7401 s.select(selections)
7402 });
7403 this.refresh_inline_completion(true, false, window, cx);
7404 });
7405 }
7406
7407 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7408 if self.read_only(cx) {
7409 return;
7410 }
7411 let mut selections = self.selections.all::<Point>(cx);
7412 let mut prev_edited_row = 0;
7413 let mut row_delta = 0;
7414 let mut edits = Vec::new();
7415 let buffer = self.buffer.read(cx);
7416 let snapshot = buffer.snapshot(cx);
7417 for selection in &mut selections {
7418 if selection.start.row != prev_edited_row {
7419 row_delta = 0;
7420 }
7421 prev_edited_row = selection.end.row;
7422
7423 row_delta =
7424 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7425 }
7426
7427 self.transact(window, cx, |this, window, cx| {
7428 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7429 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7430 s.select(selections)
7431 });
7432 });
7433 }
7434
7435 fn indent_selection(
7436 buffer: &MultiBuffer,
7437 snapshot: &MultiBufferSnapshot,
7438 selection: &mut Selection<Point>,
7439 edits: &mut Vec<(Range<Point>, String)>,
7440 delta_for_start_row: u32,
7441 cx: &App,
7442 ) -> u32 {
7443 let settings = buffer.language_settings_at(selection.start, cx);
7444 let tab_size = settings.tab_size.get();
7445 let indent_kind = if settings.hard_tabs {
7446 IndentKind::Tab
7447 } else {
7448 IndentKind::Space
7449 };
7450 let mut start_row = selection.start.row;
7451 let mut end_row = selection.end.row + 1;
7452
7453 // If a selection ends at the beginning of a line, don't indent
7454 // that last line.
7455 if selection.end.column == 0 && selection.end.row > selection.start.row {
7456 end_row -= 1;
7457 }
7458
7459 // Avoid re-indenting a row that has already been indented by a
7460 // previous selection, but still update this selection's column
7461 // to reflect that indentation.
7462 if delta_for_start_row > 0 {
7463 start_row += 1;
7464 selection.start.column += delta_for_start_row;
7465 if selection.end.row == selection.start.row {
7466 selection.end.column += delta_for_start_row;
7467 }
7468 }
7469
7470 let mut delta_for_end_row = 0;
7471 let has_multiple_rows = start_row + 1 != end_row;
7472 for row in start_row..end_row {
7473 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7474 let indent_delta = match (current_indent.kind, indent_kind) {
7475 (IndentKind::Space, IndentKind::Space) => {
7476 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7477 IndentSize::spaces(columns_to_next_tab_stop)
7478 }
7479 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7480 (_, IndentKind::Tab) => IndentSize::tab(),
7481 };
7482
7483 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7484 0
7485 } else {
7486 selection.start.column
7487 };
7488 let row_start = Point::new(row, start);
7489 edits.push((
7490 row_start..row_start,
7491 indent_delta.chars().collect::<String>(),
7492 ));
7493
7494 // Update this selection's endpoints to reflect the indentation.
7495 if row == selection.start.row {
7496 selection.start.column += indent_delta.len;
7497 }
7498 if row == selection.end.row {
7499 selection.end.column += indent_delta.len;
7500 delta_for_end_row = indent_delta.len;
7501 }
7502 }
7503
7504 if selection.start.row == selection.end.row {
7505 delta_for_start_row + delta_for_end_row
7506 } else {
7507 delta_for_end_row
7508 }
7509 }
7510
7511 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7512 if self.read_only(cx) {
7513 return;
7514 }
7515 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7516 let selections = self.selections.all::<Point>(cx);
7517 let mut deletion_ranges = Vec::new();
7518 let mut last_outdent = None;
7519 {
7520 let buffer = self.buffer.read(cx);
7521 let snapshot = buffer.snapshot(cx);
7522 for selection in &selections {
7523 let settings = buffer.language_settings_at(selection.start, cx);
7524 let tab_size = settings.tab_size.get();
7525 let mut rows = selection.spanned_rows(false, &display_map);
7526
7527 // Avoid re-outdenting a row that has already been outdented by a
7528 // previous selection.
7529 if let Some(last_row) = last_outdent {
7530 if last_row == rows.start {
7531 rows.start = rows.start.next_row();
7532 }
7533 }
7534 let has_multiple_rows = rows.len() > 1;
7535 for row in rows.iter_rows() {
7536 let indent_size = snapshot.indent_size_for_line(row);
7537 if indent_size.len > 0 {
7538 let deletion_len = match indent_size.kind {
7539 IndentKind::Space => {
7540 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7541 if columns_to_prev_tab_stop == 0 {
7542 tab_size
7543 } else {
7544 columns_to_prev_tab_stop
7545 }
7546 }
7547 IndentKind::Tab => 1,
7548 };
7549 let start = if has_multiple_rows
7550 || deletion_len > selection.start.column
7551 || indent_size.len < selection.start.column
7552 {
7553 0
7554 } else {
7555 selection.start.column - deletion_len
7556 };
7557 deletion_ranges.push(
7558 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7559 );
7560 last_outdent = Some(row);
7561 }
7562 }
7563 }
7564 }
7565
7566 self.transact(window, cx, |this, window, cx| {
7567 this.buffer.update(cx, |buffer, cx| {
7568 let empty_str: Arc<str> = Arc::default();
7569 buffer.edit(
7570 deletion_ranges
7571 .into_iter()
7572 .map(|range| (range, empty_str.clone())),
7573 None,
7574 cx,
7575 );
7576 });
7577 let selections = this.selections.all::<usize>(cx);
7578 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7579 s.select(selections)
7580 });
7581 });
7582 }
7583
7584 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7585 if self.read_only(cx) {
7586 return;
7587 }
7588 let selections = self
7589 .selections
7590 .all::<usize>(cx)
7591 .into_iter()
7592 .map(|s| s.range());
7593
7594 self.transact(window, cx, |this, window, cx| {
7595 this.buffer.update(cx, |buffer, cx| {
7596 buffer.autoindent_ranges(selections, cx);
7597 });
7598 let selections = this.selections.all::<usize>(cx);
7599 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7600 s.select(selections)
7601 });
7602 });
7603 }
7604
7605 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7606 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7607 let selections = self.selections.all::<Point>(cx);
7608
7609 let mut new_cursors = Vec::new();
7610 let mut edit_ranges = Vec::new();
7611 let mut selections = selections.iter().peekable();
7612 while let Some(selection) = selections.next() {
7613 let mut rows = selection.spanned_rows(false, &display_map);
7614 let goal_display_column = selection.head().to_display_point(&display_map).column();
7615
7616 // Accumulate contiguous regions of rows that we want to delete.
7617 while let Some(next_selection) = selections.peek() {
7618 let next_rows = next_selection.spanned_rows(false, &display_map);
7619 if next_rows.start <= rows.end {
7620 rows.end = next_rows.end;
7621 selections.next().unwrap();
7622 } else {
7623 break;
7624 }
7625 }
7626
7627 let buffer = &display_map.buffer_snapshot;
7628 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7629 let edit_end;
7630 let cursor_buffer_row;
7631 if buffer.max_point().row >= rows.end.0 {
7632 // If there's a line after the range, delete the \n from the end of the row range
7633 // and position the cursor on the next line.
7634 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7635 cursor_buffer_row = rows.end;
7636 } else {
7637 // If there isn't a line after the range, delete the \n from the line before the
7638 // start of the row range and position the cursor there.
7639 edit_start = edit_start.saturating_sub(1);
7640 edit_end = buffer.len();
7641 cursor_buffer_row = rows.start.previous_row();
7642 }
7643
7644 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7645 *cursor.column_mut() =
7646 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7647
7648 new_cursors.push((
7649 selection.id,
7650 buffer.anchor_after(cursor.to_point(&display_map)),
7651 ));
7652 edit_ranges.push(edit_start..edit_end);
7653 }
7654
7655 self.transact(window, cx, |this, window, cx| {
7656 let buffer = this.buffer.update(cx, |buffer, cx| {
7657 let empty_str: Arc<str> = Arc::default();
7658 buffer.edit(
7659 edit_ranges
7660 .into_iter()
7661 .map(|range| (range, empty_str.clone())),
7662 None,
7663 cx,
7664 );
7665 buffer.snapshot(cx)
7666 });
7667 let new_selections = new_cursors
7668 .into_iter()
7669 .map(|(id, cursor)| {
7670 let cursor = cursor.to_point(&buffer);
7671 Selection {
7672 id,
7673 start: cursor,
7674 end: cursor,
7675 reversed: false,
7676 goal: SelectionGoal::None,
7677 }
7678 })
7679 .collect();
7680
7681 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7682 s.select(new_selections);
7683 });
7684 });
7685 }
7686
7687 pub fn join_lines_impl(
7688 &mut self,
7689 insert_whitespace: bool,
7690 window: &mut Window,
7691 cx: &mut Context<Self>,
7692 ) {
7693 if self.read_only(cx) {
7694 return;
7695 }
7696 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7697 for selection in self.selections.all::<Point>(cx) {
7698 let start = MultiBufferRow(selection.start.row);
7699 // Treat single line selections as if they include the next line. Otherwise this action
7700 // would do nothing for single line selections individual cursors.
7701 let end = if selection.start.row == selection.end.row {
7702 MultiBufferRow(selection.start.row + 1)
7703 } else {
7704 MultiBufferRow(selection.end.row)
7705 };
7706
7707 if let Some(last_row_range) = row_ranges.last_mut() {
7708 if start <= last_row_range.end {
7709 last_row_range.end = end;
7710 continue;
7711 }
7712 }
7713 row_ranges.push(start..end);
7714 }
7715
7716 let snapshot = self.buffer.read(cx).snapshot(cx);
7717 let mut cursor_positions = Vec::new();
7718 for row_range in &row_ranges {
7719 let anchor = snapshot.anchor_before(Point::new(
7720 row_range.end.previous_row().0,
7721 snapshot.line_len(row_range.end.previous_row()),
7722 ));
7723 cursor_positions.push(anchor..anchor);
7724 }
7725
7726 self.transact(window, cx, |this, window, cx| {
7727 for row_range in row_ranges.into_iter().rev() {
7728 for row in row_range.iter_rows().rev() {
7729 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7730 let next_line_row = row.next_row();
7731 let indent = snapshot.indent_size_for_line(next_line_row);
7732 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7733
7734 let replace =
7735 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7736 " "
7737 } else {
7738 ""
7739 };
7740
7741 this.buffer.update(cx, |buffer, cx| {
7742 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7743 });
7744 }
7745 }
7746
7747 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7748 s.select_anchor_ranges(cursor_positions)
7749 });
7750 });
7751 }
7752
7753 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7754 self.join_lines_impl(true, window, cx);
7755 }
7756
7757 pub fn sort_lines_case_sensitive(
7758 &mut self,
7759 _: &SortLinesCaseSensitive,
7760 window: &mut Window,
7761 cx: &mut Context<Self>,
7762 ) {
7763 self.manipulate_lines(window, cx, |lines| lines.sort())
7764 }
7765
7766 pub fn sort_lines_case_insensitive(
7767 &mut self,
7768 _: &SortLinesCaseInsensitive,
7769 window: &mut Window,
7770 cx: &mut Context<Self>,
7771 ) {
7772 self.manipulate_lines(window, cx, |lines| {
7773 lines.sort_by_key(|line| line.to_lowercase())
7774 })
7775 }
7776
7777 pub fn unique_lines_case_insensitive(
7778 &mut self,
7779 _: &UniqueLinesCaseInsensitive,
7780 window: &mut Window,
7781 cx: &mut Context<Self>,
7782 ) {
7783 self.manipulate_lines(window, cx, |lines| {
7784 let mut seen = HashSet::default();
7785 lines.retain(|line| seen.insert(line.to_lowercase()));
7786 })
7787 }
7788
7789 pub fn unique_lines_case_sensitive(
7790 &mut self,
7791 _: &UniqueLinesCaseSensitive,
7792 window: &mut Window,
7793 cx: &mut Context<Self>,
7794 ) {
7795 self.manipulate_lines(window, cx, |lines| {
7796 let mut seen = HashSet::default();
7797 lines.retain(|line| seen.insert(*line));
7798 })
7799 }
7800
7801 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7802 let Some(project) = self.project.clone() else {
7803 return;
7804 };
7805 self.reload(project, window, cx)
7806 .detach_and_notify_err(window, cx);
7807 }
7808
7809 pub fn restore_file(
7810 &mut self,
7811 _: &::git::RestoreFile,
7812 window: &mut Window,
7813 cx: &mut Context<Self>,
7814 ) {
7815 let mut buffer_ids = HashSet::default();
7816 let snapshot = self.buffer().read(cx).snapshot(cx);
7817 for selection in self.selections.all::<usize>(cx) {
7818 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7819 }
7820
7821 let buffer = self.buffer().read(cx);
7822 let ranges = buffer_ids
7823 .into_iter()
7824 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7825 .collect::<Vec<_>>();
7826
7827 self.restore_hunks_in_ranges(ranges, window, cx);
7828 }
7829
7830 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7831 let selections = self
7832 .selections
7833 .all(cx)
7834 .into_iter()
7835 .map(|s| s.range())
7836 .collect();
7837 self.restore_hunks_in_ranges(selections, window, cx);
7838 }
7839
7840 fn restore_hunks_in_ranges(
7841 &mut self,
7842 ranges: Vec<Range<Point>>,
7843 window: &mut Window,
7844 cx: &mut Context<Editor>,
7845 ) {
7846 let mut revert_changes = HashMap::default();
7847 let chunk_by = self
7848 .snapshot(window, cx)
7849 .hunks_for_ranges(ranges)
7850 .into_iter()
7851 .chunk_by(|hunk| hunk.buffer_id);
7852 for (buffer_id, hunks) in &chunk_by {
7853 let hunks = hunks.collect::<Vec<_>>();
7854 for hunk in &hunks {
7855 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7856 }
7857 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7858 }
7859 drop(chunk_by);
7860 if !revert_changes.is_empty() {
7861 self.transact(window, cx, |editor, window, cx| {
7862 editor.restore(revert_changes, window, cx);
7863 });
7864 }
7865 }
7866
7867 pub fn open_active_item_in_terminal(
7868 &mut self,
7869 _: &OpenInTerminal,
7870 window: &mut Window,
7871 cx: &mut Context<Self>,
7872 ) {
7873 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7874 let project_path = buffer.read(cx).project_path(cx)?;
7875 let project = self.project.as_ref()?.read(cx);
7876 let entry = project.entry_for_path(&project_path, cx)?;
7877 let parent = match &entry.canonical_path {
7878 Some(canonical_path) => canonical_path.to_path_buf(),
7879 None => project.absolute_path(&project_path, cx)?,
7880 }
7881 .parent()?
7882 .to_path_buf();
7883 Some(parent)
7884 }) {
7885 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7886 }
7887 }
7888
7889 pub fn prepare_restore_change(
7890 &self,
7891 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7892 hunk: &MultiBufferDiffHunk,
7893 cx: &mut App,
7894 ) -> Option<()> {
7895 if hunk.is_created_file() {
7896 return None;
7897 }
7898 let buffer = self.buffer.read(cx);
7899 let diff = buffer.diff_for(hunk.buffer_id)?;
7900 let buffer = buffer.buffer(hunk.buffer_id)?;
7901 let buffer = buffer.read(cx);
7902 let original_text = diff
7903 .read(cx)
7904 .base_text()
7905 .as_rope()
7906 .slice(hunk.diff_base_byte_range.clone());
7907 let buffer_snapshot = buffer.snapshot();
7908 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7909 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7910 probe
7911 .0
7912 .start
7913 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7914 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7915 }) {
7916 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7917 Some(())
7918 } else {
7919 None
7920 }
7921 }
7922
7923 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7924 self.manipulate_lines(window, cx, |lines| lines.reverse())
7925 }
7926
7927 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7928 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7929 }
7930
7931 fn manipulate_lines<Fn>(
7932 &mut self,
7933 window: &mut Window,
7934 cx: &mut Context<Self>,
7935 mut callback: Fn,
7936 ) where
7937 Fn: FnMut(&mut Vec<&str>),
7938 {
7939 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7940 let buffer = self.buffer.read(cx).snapshot(cx);
7941
7942 let mut edits = Vec::new();
7943
7944 let selections = self.selections.all::<Point>(cx);
7945 let mut selections = selections.iter().peekable();
7946 let mut contiguous_row_selections = Vec::new();
7947 let mut new_selections = Vec::new();
7948 let mut added_lines = 0;
7949 let mut removed_lines = 0;
7950
7951 while let Some(selection) = selections.next() {
7952 let (start_row, end_row) = consume_contiguous_rows(
7953 &mut contiguous_row_selections,
7954 selection,
7955 &display_map,
7956 &mut selections,
7957 );
7958
7959 let start_point = Point::new(start_row.0, 0);
7960 let end_point = Point::new(
7961 end_row.previous_row().0,
7962 buffer.line_len(end_row.previous_row()),
7963 );
7964 let text = buffer
7965 .text_for_range(start_point..end_point)
7966 .collect::<String>();
7967
7968 let mut lines = text.split('\n').collect_vec();
7969
7970 let lines_before = lines.len();
7971 callback(&mut lines);
7972 let lines_after = lines.len();
7973
7974 edits.push((start_point..end_point, lines.join("\n")));
7975
7976 // Selections must change based on added and removed line count
7977 let start_row =
7978 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7979 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7980 new_selections.push(Selection {
7981 id: selection.id,
7982 start: start_row,
7983 end: end_row,
7984 goal: SelectionGoal::None,
7985 reversed: selection.reversed,
7986 });
7987
7988 if lines_after > lines_before {
7989 added_lines += lines_after - lines_before;
7990 } else if lines_before > lines_after {
7991 removed_lines += lines_before - lines_after;
7992 }
7993 }
7994
7995 self.transact(window, cx, |this, window, cx| {
7996 let buffer = this.buffer.update(cx, |buffer, cx| {
7997 buffer.edit(edits, None, cx);
7998 buffer.snapshot(cx)
7999 });
8000
8001 // Recalculate offsets on newly edited buffer
8002 let new_selections = new_selections
8003 .iter()
8004 .map(|s| {
8005 let start_point = Point::new(s.start.0, 0);
8006 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8007 Selection {
8008 id: s.id,
8009 start: buffer.point_to_offset(start_point),
8010 end: buffer.point_to_offset(end_point),
8011 goal: s.goal,
8012 reversed: s.reversed,
8013 }
8014 })
8015 .collect();
8016
8017 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8018 s.select(new_selections);
8019 });
8020
8021 this.request_autoscroll(Autoscroll::fit(), cx);
8022 });
8023 }
8024
8025 pub fn convert_to_upper_case(
8026 &mut self,
8027 _: &ConvertToUpperCase,
8028 window: &mut Window,
8029 cx: &mut Context<Self>,
8030 ) {
8031 self.manipulate_text(window, cx, |text| text.to_uppercase())
8032 }
8033
8034 pub fn convert_to_lower_case(
8035 &mut self,
8036 _: &ConvertToLowerCase,
8037 window: &mut Window,
8038 cx: &mut Context<Self>,
8039 ) {
8040 self.manipulate_text(window, cx, |text| text.to_lowercase())
8041 }
8042
8043 pub fn convert_to_title_case(
8044 &mut self,
8045 _: &ConvertToTitleCase,
8046 window: &mut Window,
8047 cx: &mut Context<Self>,
8048 ) {
8049 self.manipulate_text(window, cx, |text| {
8050 text.split('\n')
8051 .map(|line| line.to_case(Case::Title))
8052 .join("\n")
8053 })
8054 }
8055
8056 pub fn convert_to_snake_case(
8057 &mut self,
8058 _: &ConvertToSnakeCase,
8059 window: &mut Window,
8060 cx: &mut Context<Self>,
8061 ) {
8062 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8063 }
8064
8065 pub fn convert_to_kebab_case(
8066 &mut self,
8067 _: &ConvertToKebabCase,
8068 window: &mut Window,
8069 cx: &mut Context<Self>,
8070 ) {
8071 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8072 }
8073
8074 pub fn convert_to_upper_camel_case(
8075 &mut self,
8076 _: &ConvertToUpperCamelCase,
8077 window: &mut Window,
8078 cx: &mut Context<Self>,
8079 ) {
8080 self.manipulate_text(window, cx, |text| {
8081 text.split('\n')
8082 .map(|line| line.to_case(Case::UpperCamel))
8083 .join("\n")
8084 })
8085 }
8086
8087 pub fn convert_to_lower_camel_case(
8088 &mut self,
8089 _: &ConvertToLowerCamelCase,
8090 window: &mut Window,
8091 cx: &mut Context<Self>,
8092 ) {
8093 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8094 }
8095
8096 pub fn convert_to_opposite_case(
8097 &mut self,
8098 _: &ConvertToOppositeCase,
8099 window: &mut Window,
8100 cx: &mut Context<Self>,
8101 ) {
8102 self.manipulate_text(window, cx, |text| {
8103 text.chars()
8104 .fold(String::with_capacity(text.len()), |mut t, c| {
8105 if c.is_uppercase() {
8106 t.extend(c.to_lowercase());
8107 } else {
8108 t.extend(c.to_uppercase());
8109 }
8110 t
8111 })
8112 })
8113 }
8114
8115 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8116 where
8117 Fn: FnMut(&str) -> String,
8118 {
8119 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8120 let buffer = self.buffer.read(cx).snapshot(cx);
8121
8122 let mut new_selections = Vec::new();
8123 let mut edits = Vec::new();
8124 let mut selection_adjustment = 0i32;
8125
8126 for selection in self.selections.all::<usize>(cx) {
8127 let selection_is_empty = selection.is_empty();
8128
8129 let (start, end) = if selection_is_empty {
8130 let word_range = movement::surrounding_word(
8131 &display_map,
8132 selection.start.to_display_point(&display_map),
8133 );
8134 let start = word_range.start.to_offset(&display_map, Bias::Left);
8135 let end = word_range.end.to_offset(&display_map, Bias::Left);
8136 (start, end)
8137 } else {
8138 (selection.start, selection.end)
8139 };
8140
8141 let text = buffer.text_for_range(start..end).collect::<String>();
8142 let old_length = text.len() as i32;
8143 let text = callback(&text);
8144
8145 new_selections.push(Selection {
8146 start: (start as i32 - selection_adjustment) as usize,
8147 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8148 goal: SelectionGoal::None,
8149 ..selection
8150 });
8151
8152 selection_adjustment += old_length - text.len() as i32;
8153
8154 edits.push((start..end, text));
8155 }
8156
8157 self.transact(window, cx, |this, window, cx| {
8158 this.buffer.update(cx, |buffer, cx| {
8159 buffer.edit(edits, None, cx);
8160 });
8161
8162 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8163 s.select(new_selections);
8164 });
8165
8166 this.request_autoscroll(Autoscroll::fit(), cx);
8167 });
8168 }
8169
8170 pub fn duplicate(
8171 &mut self,
8172 upwards: bool,
8173 whole_lines: bool,
8174 window: &mut Window,
8175 cx: &mut Context<Self>,
8176 ) {
8177 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8178 let buffer = &display_map.buffer_snapshot;
8179 let selections = self.selections.all::<Point>(cx);
8180
8181 let mut edits = Vec::new();
8182 let mut selections_iter = selections.iter().peekable();
8183 while let Some(selection) = selections_iter.next() {
8184 let mut rows = selection.spanned_rows(false, &display_map);
8185 // duplicate line-wise
8186 if whole_lines || selection.start == selection.end {
8187 // Avoid duplicating the same lines twice.
8188 while let Some(next_selection) = selections_iter.peek() {
8189 let next_rows = next_selection.spanned_rows(false, &display_map);
8190 if next_rows.start < rows.end {
8191 rows.end = next_rows.end;
8192 selections_iter.next().unwrap();
8193 } else {
8194 break;
8195 }
8196 }
8197
8198 // Copy the text from the selected row region and splice it either at the start
8199 // or end of the region.
8200 let start = Point::new(rows.start.0, 0);
8201 let end = Point::new(
8202 rows.end.previous_row().0,
8203 buffer.line_len(rows.end.previous_row()),
8204 );
8205 let text = buffer
8206 .text_for_range(start..end)
8207 .chain(Some("\n"))
8208 .collect::<String>();
8209 let insert_location = if upwards {
8210 Point::new(rows.end.0, 0)
8211 } else {
8212 start
8213 };
8214 edits.push((insert_location..insert_location, text));
8215 } else {
8216 // duplicate character-wise
8217 let start = selection.start;
8218 let end = selection.end;
8219 let text = buffer.text_for_range(start..end).collect::<String>();
8220 edits.push((selection.end..selection.end, text));
8221 }
8222 }
8223
8224 self.transact(window, cx, |this, _, cx| {
8225 this.buffer.update(cx, |buffer, cx| {
8226 buffer.edit(edits, None, cx);
8227 });
8228
8229 this.request_autoscroll(Autoscroll::fit(), cx);
8230 });
8231 }
8232
8233 pub fn duplicate_line_up(
8234 &mut self,
8235 _: &DuplicateLineUp,
8236 window: &mut Window,
8237 cx: &mut Context<Self>,
8238 ) {
8239 self.duplicate(true, true, window, cx);
8240 }
8241
8242 pub fn duplicate_line_down(
8243 &mut self,
8244 _: &DuplicateLineDown,
8245 window: &mut Window,
8246 cx: &mut Context<Self>,
8247 ) {
8248 self.duplicate(false, true, window, cx);
8249 }
8250
8251 pub fn duplicate_selection(
8252 &mut self,
8253 _: &DuplicateSelection,
8254 window: &mut Window,
8255 cx: &mut Context<Self>,
8256 ) {
8257 self.duplicate(false, false, window, cx);
8258 }
8259
8260 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8261 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8262 let buffer = self.buffer.read(cx).snapshot(cx);
8263
8264 let mut edits = Vec::new();
8265 let mut unfold_ranges = Vec::new();
8266 let mut refold_creases = Vec::new();
8267
8268 let selections = self.selections.all::<Point>(cx);
8269 let mut selections = selections.iter().peekable();
8270 let mut contiguous_row_selections = Vec::new();
8271 let mut new_selections = Vec::new();
8272
8273 while let Some(selection) = selections.next() {
8274 // Find all the selections that span a contiguous row range
8275 let (start_row, end_row) = consume_contiguous_rows(
8276 &mut contiguous_row_selections,
8277 selection,
8278 &display_map,
8279 &mut selections,
8280 );
8281
8282 // Move the text spanned by the row range to be before the line preceding the row range
8283 if start_row.0 > 0 {
8284 let range_to_move = Point::new(
8285 start_row.previous_row().0,
8286 buffer.line_len(start_row.previous_row()),
8287 )
8288 ..Point::new(
8289 end_row.previous_row().0,
8290 buffer.line_len(end_row.previous_row()),
8291 );
8292 let insertion_point = display_map
8293 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8294 .0;
8295
8296 // Don't move lines across excerpts
8297 if buffer
8298 .excerpt_containing(insertion_point..range_to_move.end)
8299 .is_some()
8300 {
8301 let text = buffer
8302 .text_for_range(range_to_move.clone())
8303 .flat_map(|s| s.chars())
8304 .skip(1)
8305 .chain(['\n'])
8306 .collect::<String>();
8307
8308 edits.push((
8309 buffer.anchor_after(range_to_move.start)
8310 ..buffer.anchor_before(range_to_move.end),
8311 String::new(),
8312 ));
8313 let insertion_anchor = buffer.anchor_after(insertion_point);
8314 edits.push((insertion_anchor..insertion_anchor, text));
8315
8316 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8317
8318 // Move selections up
8319 new_selections.extend(contiguous_row_selections.drain(..).map(
8320 |mut selection| {
8321 selection.start.row -= row_delta;
8322 selection.end.row -= row_delta;
8323 selection
8324 },
8325 ));
8326
8327 // Move folds up
8328 unfold_ranges.push(range_to_move.clone());
8329 for fold in display_map.folds_in_range(
8330 buffer.anchor_before(range_to_move.start)
8331 ..buffer.anchor_after(range_to_move.end),
8332 ) {
8333 let mut start = fold.range.start.to_point(&buffer);
8334 let mut end = fold.range.end.to_point(&buffer);
8335 start.row -= row_delta;
8336 end.row -= row_delta;
8337 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8338 }
8339 }
8340 }
8341
8342 // If we didn't move line(s), preserve the existing selections
8343 new_selections.append(&mut contiguous_row_selections);
8344 }
8345
8346 self.transact(window, cx, |this, window, cx| {
8347 this.unfold_ranges(&unfold_ranges, true, true, cx);
8348 this.buffer.update(cx, |buffer, cx| {
8349 for (range, text) in edits {
8350 buffer.edit([(range, text)], None, cx);
8351 }
8352 });
8353 this.fold_creases(refold_creases, true, window, cx);
8354 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8355 s.select(new_selections);
8356 })
8357 });
8358 }
8359
8360 pub fn move_line_down(
8361 &mut self,
8362 _: &MoveLineDown,
8363 window: &mut Window,
8364 cx: &mut Context<Self>,
8365 ) {
8366 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8367 let buffer = self.buffer.read(cx).snapshot(cx);
8368
8369 let mut edits = Vec::new();
8370 let mut unfold_ranges = Vec::new();
8371 let mut refold_creases = Vec::new();
8372
8373 let selections = self.selections.all::<Point>(cx);
8374 let mut selections = selections.iter().peekable();
8375 let mut contiguous_row_selections = Vec::new();
8376 let mut new_selections = Vec::new();
8377
8378 while let Some(selection) = selections.next() {
8379 // Find all the selections that span a contiguous row range
8380 let (start_row, end_row) = consume_contiguous_rows(
8381 &mut contiguous_row_selections,
8382 selection,
8383 &display_map,
8384 &mut selections,
8385 );
8386
8387 // Move the text spanned by the row range to be after the last line of the row range
8388 if end_row.0 <= buffer.max_point().row {
8389 let range_to_move =
8390 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8391 let insertion_point = display_map
8392 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8393 .0;
8394
8395 // Don't move lines across excerpt boundaries
8396 if buffer
8397 .excerpt_containing(range_to_move.start..insertion_point)
8398 .is_some()
8399 {
8400 let mut text = String::from("\n");
8401 text.extend(buffer.text_for_range(range_to_move.clone()));
8402 text.pop(); // Drop trailing newline
8403 edits.push((
8404 buffer.anchor_after(range_to_move.start)
8405 ..buffer.anchor_before(range_to_move.end),
8406 String::new(),
8407 ));
8408 let insertion_anchor = buffer.anchor_after(insertion_point);
8409 edits.push((insertion_anchor..insertion_anchor, text));
8410
8411 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8412
8413 // Move selections down
8414 new_selections.extend(contiguous_row_selections.drain(..).map(
8415 |mut selection| {
8416 selection.start.row += row_delta;
8417 selection.end.row += row_delta;
8418 selection
8419 },
8420 ));
8421
8422 // Move folds down
8423 unfold_ranges.push(range_to_move.clone());
8424 for fold in display_map.folds_in_range(
8425 buffer.anchor_before(range_to_move.start)
8426 ..buffer.anchor_after(range_to_move.end),
8427 ) {
8428 let mut start = fold.range.start.to_point(&buffer);
8429 let mut end = fold.range.end.to_point(&buffer);
8430 start.row += row_delta;
8431 end.row += row_delta;
8432 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8433 }
8434 }
8435 }
8436
8437 // If we didn't move line(s), preserve the existing selections
8438 new_selections.append(&mut contiguous_row_selections);
8439 }
8440
8441 self.transact(window, cx, |this, window, cx| {
8442 this.unfold_ranges(&unfold_ranges, true, true, cx);
8443 this.buffer.update(cx, |buffer, cx| {
8444 for (range, text) in edits {
8445 buffer.edit([(range, text)], None, cx);
8446 }
8447 });
8448 this.fold_creases(refold_creases, true, window, cx);
8449 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8450 s.select(new_selections)
8451 });
8452 });
8453 }
8454
8455 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8456 let text_layout_details = &self.text_layout_details(window);
8457 self.transact(window, cx, |this, window, cx| {
8458 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8459 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8460 let line_mode = s.line_mode;
8461 s.move_with(|display_map, selection| {
8462 if !selection.is_empty() || line_mode {
8463 return;
8464 }
8465
8466 let mut head = selection.head();
8467 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8468 if head.column() == display_map.line_len(head.row()) {
8469 transpose_offset = display_map
8470 .buffer_snapshot
8471 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8472 }
8473
8474 if transpose_offset == 0 {
8475 return;
8476 }
8477
8478 *head.column_mut() += 1;
8479 head = display_map.clip_point(head, Bias::Right);
8480 let goal = SelectionGoal::HorizontalPosition(
8481 display_map
8482 .x_for_display_point(head, text_layout_details)
8483 .into(),
8484 );
8485 selection.collapse_to(head, goal);
8486
8487 let transpose_start = display_map
8488 .buffer_snapshot
8489 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8490 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8491 let transpose_end = display_map
8492 .buffer_snapshot
8493 .clip_offset(transpose_offset + 1, Bias::Right);
8494 if let Some(ch) =
8495 display_map.buffer_snapshot.chars_at(transpose_start).next()
8496 {
8497 edits.push((transpose_start..transpose_offset, String::new()));
8498 edits.push((transpose_end..transpose_end, ch.to_string()));
8499 }
8500 }
8501 });
8502 edits
8503 });
8504 this.buffer
8505 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8506 let selections = this.selections.all::<usize>(cx);
8507 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8508 s.select(selections);
8509 });
8510 });
8511 }
8512
8513 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8514 self.rewrap_impl(IsVimMode::No, cx)
8515 }
8516
8517 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8518 let buffer = self.buffer.read(cx).snapshot(cx);
8519 let selections = self.selections.all::<Point>(cx);
8520 let mut selections = selections.iter().peekable();
8521
8522 let mut edits = Vec::new();
8523 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8524
8525 while let Some(selection) = selections.next() {
8526 let mut start_row = selection.start.row;
8527 let mut end_row = selection.end.row;
8528
8529 // Skip selections that overlap with a range that has already been rewrapped.
8530 let selection_range = start_row..end_row;
8531 if rewrapped_row_ranges
8532 .iter()
8533 .any(|range| range.overlaps(&selection_range))
8534 {
8535 continue;
8536 }
8537
8538 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
8539
8540 // Since not all lines in the selection may be at the same indent
8541 // level, choose the indent size that is the most common between all
8542 // of the lines.
8543 //
8544 // If there is a tie, we use the deepest indent.
8545 let (indent_size, indent_end) = {
8546 let mut indent_size_occurrences = HashMap::default();
8547 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8548
8549 for row in start_row..=end_row {
8550 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8551 rows_by_indent_size.entry(indent).or_default().push(row);
8552 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8553 }
8554
8555 let indent_size = indent_size_occurrences
8556 .into_iter()
8557 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8558 .map(|(indent, _)| indent)
8559 .unwrap_or_default();
8560 let row = rows_by_indent_size[&indent_size][0];
8561 let indent_end = Point::new(row, indent_size.len);
8562
8563 (indent_size, indent_end)
8564 };
8565
8566 let mut line_prefix = indent_size.chars().collect::<String>();
8567
8568 let mut inside_comment = false;
8569 if let Some(comment_prefix) =
8570 buffer
8571 .language_scope_at(selection.head())
8572 .and_then(|language| {
8573 language
8574 .line_comment_prefixes()
8575 .iter()
8576 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8577 .cloned()
8578 })
8579 {
8580 line_prefix.push_str(&comment_prefix);
8581 inside_comment = true;
8582 }
8583
8584 let language_settings = buffer.language_settings_at(selection.head(), cx);
8585 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8586 RewrapBehavior::InComments => inside_comment,
8587 RewrapBehavior::InSelections => !selection.is_empty(),
8588 RewrapBehavior::Anywhere => true,
8589 };
8590
8591 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8592 if !should_rewrap {
8593 continue;
8594 }
8595
8596 if selection.is_empty() {
8597 'expand_upwards: while start_row > 0 {
8598 let prev_row = start_row - 1;
8599 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8600 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8601 {
8602 start_row = prev_row;
8603 } else {
8604 break 'expand_upwards;
8605 }
8606 }
8607
8608 'expand_downwards: while end_row < buffer.max_point().row {
8609 let next_row = end_row + 1;
8610 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8611 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8612 {
8613 end_row = next_row;
8614 } else {
8615 break 'expand_downwards;
8616 }
8617 }
8618 }
8619
8620 let start = Point::new(start_row, 0);
8621 let start_offset = start.to_offset(&buffer);
8622 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8623 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8624 let Some(lines_without_prefixes) = selection_text
8625 .lines()
8626 .map(|line| {
8627 line.strip_prefix(&line_prefix)
8628 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8629 .ok_or_else(|| {
8630 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8631 })
8632 })
8633 .collect::<Result<Vec<_>, _>>()
8634 .log_err()
8635 else {
8636 continue;
8637 };
8638
8639 let wrap_column = buffer
8640 .language_settings_at(Point::new(start_row, 0), cx)
8641 .preferred_line_length as usize;
8642 let wrapped_text = wrap_with_prefix(
8643 line_prefix,
8644 lines_without_prefixes.join(" "),
8645 wrap_column,
8646 tab_size,
8647 );
8648
8649 // TODO: should always use char-based diff while still supporting cursor behavior that
8650 // matches vim.
8651 let mut diff_options = DiffOptions::default();
8652 if is_vim_mode == IsVimMode::Yes {
8653 diff_options.max_word_diff_len = 0;
8654 diff_options.max_word_diff_line_count = 0;
8655 } else {
8656 diff_options.max_word_diff_len = usize::MAX;
8657 diff_options.max_word_diff_line_count = usize::MAX;
8658 }
8659
8660 for (old_range, new_text) in
8661 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8662 {
8663 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8664 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8665 edits.push((edit_start..edit_end, new_text));
8666 }
8667
8668 rewrapped_row_ranges.push(start_row..=end_row);
8669 }
8670
8671 self.buffer
8672 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8673 }
8674
8675 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8676 let mut text = String::new();
8677 let buffer = self.buffer.read(cx).snapshot(cx);
8678 let mut selections = self.selections.all::<Point>(cx);
8679 let mut clipboard_selections = Vec::with_capacity(selections.len());
8680 {
8681 let max_point = buffer.max_point();
8682 let mut is_first = true;
8683 for selection in &mut selections {
8684 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8685 if is_entire_line {
8686 selection.start = Point::new(selection.start.row, 0);
8687 if !selection.is_empty() && selection.end.column == 0 {
8688 selection.end = cmp::min(max_point, selection.end);
8689 } else {
8690 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8691 }
8692 selection.goal = SelectionGoal::None;
8693 }
8694 if is_first {
8695 is_first = false;
8696 } else {
8697 text += "\n";
8698 }
8699 let mut len = 0;
8700 for chunk in buffer.text_for_range(selection.start..selection.end) {
8701 text.push_str(chunk);
8702 len += chunk.len();
8703 }
8704 clipboard_selections.push(ClipboardSelection {
8705 len,
8706 is_entire_line,
8707 first_line_indent: buffer
8708 .indent_size_for_line(MultiBufferRow(selection.start.row))
8709 .len,
8710 });
8711 }
8712 }
8713
8714 self.transact(window, cx, |this, window, cx| {
8715 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8716 s.select(selections);
8717 });
8718 this.insert("", window, cx);
8719 });
8720 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8721 }
8722
8723 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8724 let item = self.cut_common(window, cx);
8725 cx.write_to_clipboard(item);
8726 }
8727
8728 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8729 self.change_selections(None, window, cx, |s| {
8730 s.move_with(|snapshot, sel| {
8731 if sel.is_empty() {
8732 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8733 }
8734 });
8735 });
8736 let item = self.cut_common(window, cx);
8737 cx.set_global(KillRing(item))
8738 }
8739
8740 pub fn kill_ring_yank(
8741 &mut self,
8742 _: &KillRingYank,
8743 window: &mut Window,
8744 cx: &mut Context<Self>,
8745 ) {
8746 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8747 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8748 (kill_ring.text().to_string(), kill_ring.metadata_json())
8749 } else {
8750 return;
8751 }
8752 } else {
8753 return;
8754 };
8755 self.do_paste(&text, metadata, false, window, cx);
8756 }
8757
8758 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8759 let selections = self.selections.all::<Point>(cx);
8760 let buffer = self.buffer.read(cx).read(cx);
8761 let mut text = String::new();
8762
8763 let mut clipboard_selections = Vec::with_capacity(selections.len());
8764 {
8765 let max_point = buffer.max_point();
8766 let mut is_first = true;
8767 for selection in selections.iter() {
8768 let mut start = selection.start;
8769 let mut end = selection.end;
8770 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8771 if is_entire_line {
8772 start = Point::new(start.row, 0);
8773 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8774 }
8775 if is_first {
8776 is_first = false;
8777 } else {
8778 text += "\n";
8779 }
8780 let mut len = 0;
8781 for chunk in buffer.text_for_range(start..end) {
8782 text.push_str(chunk);
8783 len += chunk.len();
8784 }
8785 clipboard_selections.push(ClipboardSelection {
8786 len,
8787 is_entire_line,
8788 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8789 });
8790 }
8791 }
8792
8793 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8794 text,
8795 clipboard_selections,
8796 ));
8797 }
8798
8799 pub fn do_paste(
8800 &mut self,
8801 text: &String,
8802 clipboard_selections: Option<Vec<ClipboardSelection>>,
8803 handle_entire_lines: bool,
8804 window: &mut Window,
8805 cx: &mut Context<Self>,
8806 ) {
8807 if self.read_only(cx) {
8808 return;
8809 }
8810
8811 let clipboard_text = Cow::Borrowed(text);
8812
8813 self.transact(window, cx, |this, window, cx| {
8814 if let Some(mut clipboard_selections) = clipboard_selections {
8815 let old_selections = this.selections.all::<usize>(cx);
8816 let all_selections_were_entire_line =
8817 clipboard_selections.iter().all(|s| s.is_entire_line);
8818 let first_selection_indent_column =
8819 clipboard_selections.first().map(|s| s.first_line_indent);
8820 if clipboard_selections.len() != old_selections.len() {
8821 clipboard_selections.drain(..);
8822 }
8823 let cursor_offset = this.selections.last::<usize>(cx).head();
8824 let mut auto_indent_on_paste = true;
8825
8826 this.buffer.update(cx, |buffer, cx| {
8827 let snapshot = buffer.read(cx);
8828 auto_indent_on_paste = snapshot
8829 .language_settings_at(cursor_offset, cx)
8830 .auto_indent_on_paste;
8831
8832 let mut start_offset = 0;
8833 let mut edits = Vec::new();
8834 let mut original_indent_columns = Vec::new();
8835 for (ix, selection) in old_selections.iter().enumerate() {
8836 let to_insert;
8837 let entire_line;
8838 let original_indent_column;
8839 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8840 let end_offset = start_offset + clipboard_selection.len;
8841 to_insert = &clipboard_text[start_offset..end_offset];
8842 entire_line = clipboard_selection.is_entire_line;
8843 start_offset = end_offset + 1;
8844 original_indent_column = Some(clipboard_selection.first_line_indent);
8845 } else {
8846 to_insert = clipboard_text.as_str();
8847 entire_line = all_selections_were_entire_line;
8848 original_indent_column = first_selection_indent_column
8849 }
8850
8851 // If the corresponding selection was empty when this slice of the
8852 // clipboard text was written, then the entire line containing the
8853 // selection was copied. If this selection is also currently empty,
8854 // then paste the line before the current line of the buffer.
8855 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8856 let column = selection.start.to_point(&snapshot).column as usize;
8857 let line_start = selection.start - column;
8858 line_start..line_start
8859 } else {
8860 selection.range()
8861 };
8862
8863 edits.push((range, to_insert));
8864 original_indent_columns.push(original_indent_column);
8865 }
8866 drop(snapshot);
8867
8868 buffer.edit(
8869 edits,
8870 if auto_indent_on_paste {
8871 Some(AutoindentMode::Block {
8872 original_indent_columns,
8873 })
8874 } else {
8875 None
8876 },
8877 cx,
8878 );
8879 });
8880
8881 let selections = this.selections.all::<usize>(cx);
8882 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8883 s.select(selections)
8884 });
8885 } else {
8886 this.insert(&clipboard_text, window, cx);
8887 }
8888 });
8889 }
8890
8891 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8892 if let Some(item) = cx.read_from_clipboard() {
8893 let entries = item.entries();
8894
8895 match entries.first() {
8896 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8897 // of all the pasted entries.
8898 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8899 .do_paste(
8900 clipboard_string.text(),
8901 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8902 true,
8903 window,
8904 cx,
8905 ),
8906 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8907 }
8908 }
8909 }
8910
8911 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8912 if self.read_only(cx) {
8913 return;
8914 }
8915
8916 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8917 if let Some((selections, _)) =
8918 self.selection_history.transaction(transaction_id).cloned()
8919 {
8920 self.change_selections(None, window, cx, |s| {
8921 s.select_anchors(selections.to_vec());
8922 });
8923 } else {
8924 log::error!(
8925 "No entry in selection_history found for undo. \
8926 This may correspond to a bug where undo does not update the selection. \
8927 If this is occurring, please add details to \
8928 https://github.com/zed-industries/zed/issues/22692"
8929 );
8930 }
8931 self.request_autoscroll(Autoscroll::fit(), cx);
8932 self.unmark_text(window, cx);
8933 self.refresh_inline_completion(true, false, window, cx);
8934 cx.emit(EditorEvent::Edited { transaction_id });
8935 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8936 }
8937 }
8938
8939 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8940 if self.read_only(cx) {
8941 return;
8942 }
8943
8944 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8945 if let Some((_, Some(selections))) =
8946 self.selection_history.transaction(transaction_id).cloned()
8947 {
8948 self.change_selections(None, window, cx, |s| {
8949 s.select_anchors(selections.to_vec());
8950 });
8951 } else {
8952 log::error!(
8953 "No entry in selection_history found for redo. \
8954 This may correspond to a bug where undo does not update the selection. \
8955 If this is occurring, please add details to \
8956 https://github.com/zed-industries/zed/issues/22692"
8957 );
8958 }
8959 self.request_autoscroll(Autoscroll::fit(), cx);
8960 self.unmark_text(window, cx);
8961 self.refresh_inline_completion(true, false, window, cx);
8962 cx.emit(EditorEvent::Edited { transaction_id });
8963 }
8964 }
8965
8966 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8967 self.buffer
8968 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8969 }
8970
8971 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8972 self.buffer
8973 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8974 }
8975
8976 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8977 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8978 let line_mode = s.line_mode;
8979 s.move_with(|map, selection| {
8980 let cursor = if selection.is_empty() && !line_mode {
8981 movement::left(map, selection.start)
8982 } else {
8983 selection.start
8984 };
8985 selection.collapse_to(cursor, SelectionGoal::None);
8986 });
8987 })
8988 }
8989
8990 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8991 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8992 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8993 })
8994 }
8995
8996 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8997 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8998 let line_mode = s.line_mode;
8999 s.move_with(|map, selection| {
9000 let cursor = if selection.is_empty() && !line_mode {
9001 movement::right(map, selection.end)
9002 } else {
9003 selection.end
9004 };
9005 selection.collapse_to(cursor, SelectionGoal::None)
9006 });
9007 })
9008 }
9009
9010 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9011 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9012 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9013 })
9014 }
9015
9016 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9017 if self.take_rename(true, window, cx).is_some() {
9018 return;
9019 }
9020
9021 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9022 cx.propagate();
9023 return;
9024 }
9025
9026 let text_layout_details = &self.text_layout_details(window);
9027 let selection_count = self.selections.count();
9028 let first_selection = self.selections.first_anchor();
9029
9030 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9031 let line_mode = s.line_mode;
9032 s.move_with(|map, selection| {
9033 if !selection.is_empty() && !line_mode {
9034 selection.goal = SelectionGoal::None;
9035 }
9036 let (cursor, goal) = movement::up(
9037 map,
9038 selection.start,
9039 selection.goal,
9040 false,
9041 text_layout_details,
9042 );
9043 selection.collapse_to(cursor, goal);
9044 });
9045 });
9046
9047 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9048 {
9049 cx.propagate();
9050 }
9051 }
9052
9053 pub fn move_up_by_lines(
9054 &mut self,
9055 action: &MoveUpByLines,
9056 window: &mut Window,
9057 cx: &mut Context<Self>,
9058 ) {
9059 if self.take_rename(true, window, cx).is_some() {
9060 return;
9061 }
9062
9063 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9064 cx.propagate();
9065 return;
9066 }
9067
9068 let text_layout_details = &self.text_layout_details(window);
9069
9070 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9071 let line_mode = s.line_mode;
9072 s.move_with(|map, selection| {
9073 if !selection.is_empty() && !line_mode {
9074 selection.goal = SelectionGoal::None;
9075 }
9076 let (cursor, goal) = movement::up_by_rows(
9077 map,
9078 selection.start,
9079 action.lines,
9080 selection.goal,
9081 false,
9082 text_layout_details,
9083 );
9084 selection.collapse_to(cursor, goal);
9085 });
9086 })
9087 }
9088
9089 pub fn move_down_by_lines(
9090 &mut self,
9091 action: &MoveDownByLines,
9092 window: &mut Window,
9093 cx: &mut Context<Self>,
9094 ) {
9095 if self.take_rename(true, window, cx).is_some() {
9096 return;
9097 }
9098
9099 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9100 cx.propagate();
9101 return;
9102 }
9103
9104 let text_layout_details = &self.text_layout_details(window);
9105
9106 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9107 let line_mode = s.line_mode;
9108 s.move_with(|map, selection| {
9109 if !selection.is_empty() && !line_mode {
9110 selection.goal = SelectionGoal::None;
9111 }
9112 let (cursor, goal) = movement::down_by_rows(
9113 map,
9114 selection.start,
9115 action.lines,
9116 selection.goal,
9117 false,
9118 text_layout_details,
9119 );
9120 selection.collapse_to(cursor, goal);
9121 });
9122 })
9123 }
9124
9125 pub fn select_down_by_lines(
9126 &mut self,
9127 action: &SelectDownByLines,
9128 window: &mut Window,
9129 cx: &mut Context<Self>,
9130 ) {
9131 let text_layout_details = &self.text_layout_details(window);
9132 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9133 s.move_heads_with(|map, head, goal| {
9134 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9135 })
9136 })
9137 }
9138
9139 pub fn select_up_by_lines(
9140 &mut self,
9141 action: &SelectUpByLines,
9142 window: &mut Window,
9143 cx: &mut Context<Self>,
9144 ) {
9145 let text_layout_details = &self.text_layout_details(window);
9146 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9147 s.move_heads_with(|map, head, goal| {
9148 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9149 })
9150 })
9151 }
9152
9153 pub fn select_page_up(
9154 &mut self,
9155 _: &SelectPageUp,
9156 window: &mut Window,
9157 cx: &mut Context<Self>,
9158 ) {
9159 let Some(row_count) = self.visible_row_count() else {
9160 return;
9161 };
9162
9163 let text_layout_details = &self.text_layout_details(window);
9164
9165 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9166 s.move_heads_with(|map, head, goal| {
9167 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9168 })
9169 })
9170 }
9171
9172 pub fn move_page_up(
9173 &mut self,
9174 action: &MovePageUp,
9175 window: &mut Window,
9176 cx: &mut Context<Self>,
9177 ) {
9178 if self.take_rename(true, window, cx).is_some() {
9179 return;
9180 }
9181
9182 if self
9183 .context_menu
9184 .borrow_mut()
9185 .as_mut()
9186 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9187 .unwrap_or(false)
9188 {
9189 return;
9190 }
9191
9192 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9193 cx.propagate();
9194 return;
9195 }
9196
9197 let Some(row_count) = self.visible_row_count() else {
9198 return;
9199 };
9200
9201 let autoscroll = if action.center_cursor {
9202 Autoscroll::center()
9203 } else {
9204 Autoscroll::fit()
9205 };
9206
9207 let text_layout_details = &self.text_layout_details(window);
9208
9209 self.change_selections(Some(autoscroll), window, cx, |s| {
9210 let line_mode = s.line_mode;
9211 s.move_with(|map, selection| {
9212 if !selection.is_empty() && !line_mode {
9213 selection.goal = SelectionGoal::None;
9214 }
9215 let (cursor, goal) = movement::up_by_rows(
9216 map,
9217 selection.end,
9218 row_count,
9219 selection.goal,
9220 false,
9221 text_layout_details,
9222 );
9223 selection.collapse_to(cursor, goal);
9224 });
9225 });
9226 }
9227
9228 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9229 let text_layout_details = &self.text_layout_details(window);
9230 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9231 s.move_heads_with(|map, head, goal| {
9232 movement::up(map, head, goal, false, text_layout_details)
9233 })
9234 })
9235 }
9236
9237 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9238 self.take_rename(true, window, cx);
9239
9240 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9241 cx.propagate();
9242 return;
9243 }
9244
9245 let text_layout_details = &self.text_layout_details(window);
9246 let selection_count = self.selections.count();
9247 let first_selection = self.selections.first_anchor();
9248
9249 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9250 let line_mode = s.line_mode;
9251 s.move_with(|map, selection| {
9252 if !selection.is_empty() && !line_mode {
9253 selection.goal = SelectionGoal::None;
9254 }
9255 let (cursor, goal) = movement::down(
9256 map,
9257 selection.end,
9258 selection.goal,
9259 false,
9260 text_layout_details,
9261 );
9262 selection.collapse_to(cursor, goal);
9263 });
9264 });
9265
9266 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9267 {
9268 cx.propagate();
9269 }
9270 }
9271
9272 pub fn select_page_down(
9273 &mut self,
9274 _: &SelectPageDown,
9275 window: &mut Window,
9276 cx: &mut Context<Self>,
9277 ) {
9278 let Some(row_count) = self.visible_row_count() else {
9279 return;
9280 };
9281
9282 let text_layout_details = &self.text_layout_details(window);
9283
9284 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9285 s.move_heads_with(|map, head, goal| {
9286 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9287 })
9288 })
9289 }
9290
9291 pub fn move_page_down(
9292 &mut self,
9293 action: &MovePageDown,
9294 window: &mut Window,
9295 cx: &mut Context<Self>,
9296 ) {
9297 if self.take_rename(true, window, cx).is_some() {
9298 return;
9299 }
9300
9301 if self
9302 .context_menu
9303 .borrow_mut()
9304 .as_mut()
9305 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9306 .unwrap_or(false)
9307 {
9308 return;
9309 }
9310
9311 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9312 cx.propagate();
9313 return;
9314 }
9315
9316 let Some(row_count) = self.visible_row_count() else {
9317 return;
9318 };
9319
9320 let autoscroll = if action.center_cursor {
9321 Autoscroll::center()
9322 } else {
9323 Autoscroll::fit()
9324 };
9325
9326 let text_layout_details = &self.text_layout_details(window);
9327 self.change_selections(Some(autoscroll), window, cx, |s| {
9328 let line_mode = s.line_mode;
9329 s.move_with(|map, selection| {
9330 if !selection.is_empty() && !line_mode {
9331 selection.goal = SelectionGoal::None;
9332 }
9333 let (cursor, goal) = movement::down_by_rows(
9334 map,
9335 selection.end,
9336 row_count,
9337 selection.goal,
9338 false,
9339 text_layout_details,
9340 );
9341 selection.collapse_to(cursor, goal);
9342 });
9343 });
9344 }
9345
9346 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9347 let text_layout_details = &self.text_layout_details(window);
9348 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9349 s.move_heads_with(|map, head, goal| {
9350 movement::down(map, head, goal, false, text_layout_details)
9351 })
9352 });
9353 }
9354
9355 pub fn context_menu_first(
9356 &mut self,
9357 _: &ContextMenuFirst,
9358 _window: &mut Window,
9359 cx: &mut Context<Self>,
9360 ) {
9361 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9362 context_menu.select_first(self.completion_provider.as_deref(), cx);
9363 }
9364 }
9365
9366 pub fn context_menu_prev(
9367 &mut self,
9368 _: &ContextMenuPrevious,
9369 _window: &mut Window,
9370 cx: &mut Context<Self>,
9371 ) {
9372 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9373 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9374 }
9375 }
9376
9377 pub fn context_menu_next(
9378 &mut self,
9379 _: &ContextMenuNext,
9380 _window: &mut Window,
9381 cx: &mut Context<Self>,
9382 ) {
9383 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9384 context_menu.select_next(self.completion_provider.as_deref(), cx);
9385 }
9386 }
9387
9388 pub fn context_menu_last(
9389 &mut self,
9390 _: &ContextMenuLast,
9391 _window: &mut Window,
9392 cx: &mut Context<Self>,
9393 ) {
9394 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9395 context_menu.select_last(self.completion_provider.as_deref(), cx);
9396 }
9397 }
9398
9399 pub fn move_to_previous_word_start(
9400 &mut self,
9401 _: &MoveToPreviousWordStart,
9402 window: &mut Window,
9403 cx: &mut Context<Self>,
9404 ) {
9405 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9406 s.move_cursors_with(|map, head, _| {
9407 (
9408 movement::previous_word_start(map, head),
9409 SelectionGoal::None,
9410 )
9411 });
9412 })
9413 }
9414
9415 pub fn move_to_previous_subword_start(
9416 &mut self,
9417 _: &MoveToPreviousSubwordStart,
9418 window: &mut Window,
9419 cx: &mut Context<Self>,
9420 ) {
9421 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9422 s.move_cursors_with(|map, head, _| {
9423 (
9424 movement::previous_subword_start(map, head),
9425 SelectionGoal::None,
9426 )
9427 });
9428 })
9429 }
9430
9431 pub fn select_to_previous_word_start(
9432 &mut self,
9433 _: &SelectToPreviousWordStart,
9434 window: &mut Window,
9435 cx: &mut Context<Self>,
9436 ) {
9437 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9438 s.move_heads_with(|map, head, _| {
9439 (
9440 movement::previous_word_start(map, head),
9441 SelectionGoal::None,
9442 )
9443 });
9444 })
9445 }
9446
9447 pub fn select_to_previous_subword_start(
9448 &mut self,
9449 _: &SelectToPreviousSubwordStart,
9450 window: &mut Window,
9451 cx: &mut Context<Self>,
9452 ) {
9453 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9454 s.move_heads_with(|map, head, _| {
9455 (
9456 movement::previous_subword_start(map, head),
9457 SelectionGoal::None,
9458 )
9459 });
9460 })
9461 }
9462
9463 pub fn delete_to_previous_word_start(
9464 &mut self,
9465 action: &DeleteToPreviousWordStart,
9466 window: &mut Window,
9467 cx: &mut Context<Self>,
9468 ) {
9469 self.transact(window, cx, |this, window, cx| {
9470 this.select_autoclose_pair(window, cx);
9471 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9472 let line_mode = s.line_mode;
9473 s.move_with(|map, selection| {
9474 if selection.is_empty() && !line_mode {
9475 let cursor = if action.ignore_newlines {
9476 movement::previous_word_start(map, selection.head())
9477 } else {
9478 movement::previous_word_start_or_newline(map, selection.head())
9479 };
9480 selection.set_head(cursor, SelectionGoal::None);
9481 }
9482 });
9483 });
9484 this.insert("", window, cx);
9485 });
9486 }
9487
9488 pub fn delete_to_previous_subword_start(
9489 &mut self,
9490 _: &DeleteToPreviousSubwordStart,
9491 window: &mut Window,
9492 cx: &mut Context<Self>,
9493 ) {
9494 self.transact(window, cx, |this, window, cx| {
9495 this.select_autoclose_pair(window, cx);
9496 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9497 let line_mode = s.line_mode;
9498 s.move_with(|map, selection| {
9499 if selection.is_empty() && !line_mode {
9500 let cursor = movement::previous_subword_start(map, selection.head());
9501 selection.set_head(cursor, SelectionGoal::None);
9502 }
9503 });
9504 });
9505 this.insert("", window, cx);
9506 });
9507 }
9508
9509 pub fn move_to_next_word_end(
9510 &mut self,
9511 _: &MoveToNextWordEnd,
9512 window: &mut Window,
9513 cx: &mut Context<Self>,
9514 ) {
9515 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9516 s.move_cursors_with(|map, head, _| {
9517 (movement::next_word_end(map, head), SelectionGoal::None)
9518 });
9519 })
9520 }
9521
9522 pub fn move_to_next_subword_end(
9523 &mut self,
9524 _: &MoveToNextSubwordEnd,
9525 window: &mut Window,
9526 cx: &mut Context<Self>,
9527 ) {
9528 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9529 s.move_cursors_with(|map, head, _| {
9530 (movement::next_subword_end(map, head), SelectionGoal::None)
9531 });
9532 })
9533 }
9534
9535 pub fn select_to_next_word_end(
9536 &mut self,
9537 _: &SelectToNextWordEnd,
9538 window: &mut Window,
9539 cx: &mut Context<Self>,
9540 ) {
9541 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9542 s.move_heads_with(|map, head, _| {
9543 (movement::next_word_end(map, head), SelectionGoal::None)
9544 });
9545 })
9546 }
9547
9548 pub fn select_to_next_subword_end(
9549 &mut self,
9550 _: &SelectToNextSubwordEnd,
9551 window: &mut Window,
9552 cx: &mut Context<Self>,
9553 ) {
9554 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9555 s.move_heads_with(|map, head, _| {
9556 (movement::next_subword_end(map, head), SelectionGoal::None)
9557 });
9558 })
9559 }
9560
9561 pub fn delete_to_next_word_end(
9562 &mut self,
9563 action: &DeleteToNextWordEnd,
9564 window: &mut Window,
9565 cx: &mut Context<Self>,
9566 ) {
9567 self.transact(window, cx, |this, window, cx| {
9568 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9569 let line_mode = s.line_mode;
9570 s.move_with(|map, selection| {
9571 if selection.is_empty() && !line_mode {
9572 let cursor = if action.ignore_newlines {
9573 movement::next_word_end(map, selection.head())
9574 } else {
9575 movement::next_word_end_or_newline(map, selection.head())
9576 };
9577 selection.set_head(cursor, SelectionGoal::None);
9578 }
9579 });
9580 });
9581 this.insert("", window, cx);
9582 });
9583 }
9584
9585 pub fn delete_to_next_subword_end(
9586 &mut self,
9587 _: &DeleteToNextSubwordEnd,
9588 window: &mut Window,
9589 cx: &mut Context<Self>,
9590 ) {
9591 self.transact(window, cx, |this, window, cx| {
9592 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9593 s.move_with(|map, selection| {
9594 if selection.is_empty() {
9595 let cursor = movement::next_subword_end(map, selection.head());
9596 selection.set_head(cursor, SelectionGoal::None);
9597 }
9598 });
9599 });
9600 this.insert("", window, cx);
9601 });
9602 }
9603
9604 pub fn move_to_beginning_of_line(
9605 &mut self,
9606 action: &MoveToBeginningOfLine,
9607 window: &mut Window,
9608 cx: &mut Context<Self>,
9609 ) {
9610 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9611 s.move_cursors_with(|map, head, _| {
9612 (
9613 movement::indented_line_beginning(
9614 map,
9615 head,
9616 action.stop_at_soft_wraps,
9617 action.stop_at_indent,
9618 ),
9619 SelectionGoal::None,
9620 )
9621 });
9622 })
9623 }
9624
9625 pub fn select_to_beginning_of_line(
9626 &mut self,
9627 action: &SelectToBeginningOfLine,
9628 window: &mut Window,
9629 cx: &mut Context<Self>,
9630 ) {
9631 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9632 s.move_heads_with(|map, head, _| {
9633 (
9634 movement::indented_line_beginning(
9635 map,
9636 head,
9637 action.stop_at_soft_wraps,
9638 action.stop_at_indent,
9639 ),
9640 SelectionGoal::None,
9641 )
9642 });
9643 });
9644 }
9645
9646 pub fn delete_to_beginning_of_line(
9647 &mut self,
9648 action: &DeleteToBeginningOfLine,
9649 window: &mut Window,
9650 cx: &mut Context<Self>,
9651 ) {
9652 self.transact(window, cx, |this, window, cx| {
9653 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9654 s.move_with(|_, selection| {
9655 selection.reversed = true;
9656 });
9657 });
9658
9659 this.select_to_beginning_of_line(
9660 &SelectToBeginningOfLine {
9661 stop_at_soft_wraps: false,
9662 stop_at_indent: action.stop_at_indent,
9663 },
9664 window,
9665 cx,
9666 );
9667 this.backspace(&Backspace, window, cx);
9668 });
9669 }
9670
9671 pub fn move_to_end_of_line(
9672 &mut self,
9673 action: &MoveToEndOfLine,
9674 window: &mut Window,
9675 cx: &mut Context<Self>,
9676 ) {
9677 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9678 s.move_cursors_with(|map, head, _| {
9679 (
9680 movement::line_end(map, head, action.stop_at_soft_wraps),
9681 SelectionGoal::None,
9682 )
9683 });
9684 })
9685 }
9686
9687 pub fn select_to_end_of_line(
9688 &mut self,
9689 action: &SelectToEndOfLine,
9690 window: &mut Window,
9691 cx: &mut Context<Self>,
9692 ) {
9693 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9694 s.move_heads_with(|map, head, _| {
9695 (
9696 movement::line_end(map, head, action.stop_at_soft_wraps),
9697 SelectionGoal::None,
9698 )
9699 });
9700 })
9701 }
9702
9703 pub fn delete_to_end_of_line(
9704 &mut self,
9705 _: &DeleteToEndOfLine,
9706 window: &mut Window,
9707 cx: &mut Context<Self>,
9708 ) {
9709 self.transact(window, cx, |this, window, cx| {
9710 this.select_to_end_of_line(
9711 &SelectToEndOfLine {
9712 stop_at_soft_wraps: false,
9713 },
9714 window,
9715 cx,
9716 );
9717 this.delete(&Delete, window, cx);
9718 });
9719 }
9720
9721 pub fn cut_to_end_of_line(
9722 &mut self,
9723 _: &CutToEndOfLine,
9724 window: &mut Window,
9725 cx: &mut Context<Self>,
9726 ) {
9727 self.transact(window, cx, |this, window, cx| {
9728 this.select_to_end_of_line(
9729 &SelectToEndOfLine {
9730 stop_at_soft_wraps: false,
9731 },
9732 window,
9733 cx,
9734 );
9735 this.cut(&Cut, window, cx);
9736 });
9737 }
9738
9739 pub fn move_to_start_of_paragraph(
9740 &mut self,
9741 _: &MoveToStartOfParagraph,
9742 window: &mut Window,
9743 cx: &mut Context<Self>,
9744 ) {
9745 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9746 cx.propagate();
9747 return;
9748 }
9749
9750 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9751 s.move_with(|map, selection| {
9752 selection.collapse_to(
9753 movement::start_of_paragraph(map, selection.head(), 1),
9754 SelectionGoal::None,
9755 )
9756 });
9757 })
9758 }
9759
9760 pub fn move_to_end_of_paragraph(
9761 &mut self,
9762 _: &MoveToEndOfParagraph,
9763 window: &mut Window,
9764 cx: &mut Context<Self>,
9765 ) {
9766 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9767 cx.propagate();
9768 return;
9769 }
9770
9771 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9772 s.move_with(|map, selection| {
9773 selection.collapse_to(
9774 movement::end_of_paragraph(map, selection.head(), 1),
9775 SelectionGoal::None,
9776 )
9777 });
9778 })
9779 }
9780
9781 pub fn select_to_start_of_paragraph(
9782 &mut self,
9783 _: &SelectToStartOfParagraph,
9784 window: &mut Window,
9785 cx: &mut Context<Self>,
9786 ) {
9787 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9788 cx.propagate();
9789 return;
9790 }
9791
9792 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9793 s.move_heads_with(|map, head, _| {
9794 (
9795 movement::start_of_paragraph(map, head, 1),
9796 SelectionGoal::None,
9797 )
9798 });
9799 })
9800 }
9801
9802 pub fn select_to_end_of_paragraph(
9803 &mut self,
9804 _: &SelectToEndOfParagraph,
9805 window: &mut Window,
9806 cx: &mut Context<Self>,
9807 ) {
9808 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9809 cx.propagate();
9810 return;
9811 }
9812
9813 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9814 s.move_heads_with(|map, head, _| {
9815 (
9816 movement::end_of_paragraph(map, head, 1),
9817 SelectionGoal::None,
9818 )
9819 });
9820 })
9821 }
9822
9823 pub fn move_to_start_of_excerpt(
9824 &mut self,
9825 _: &MoveToStartOfExcerpt,
9826 window: &mut Window,
9827 cx: &mut Context<Self>,
9828 ) {
9829 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9830 cx.propagate();
9831 return;
9832 }
9833
9834 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9835 s.move_with(|map, selection| {
9836 selection.collapse_to(
9837 movement::start_of_excerpt(
9838 map,
9839 selection.head(),
9840 workspace::searchable::Direction::Prev,
9841 ),
9842 SelectionGoal::None,
9843 )
9844 });
9845 })
9846 }
9847
9848 pub fn move_to_end_of_excerpt(
9849 &mut self,
9850 _: &MoveToEndOfExcerpt,
9851 window: &mut Window,
9852 cx: &mut Context<Self>,
9853 ) {
9854 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9855 cx.propagate();
9856 return;
9857 }
9858
9859 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9860 s.move_with(|map, selection| {
9861 selection.collapse_to(
9862 movement::end_of_excerpt(
9863 map,
9864 selection.head(),
9865 workspace::searchable::Direction::Next,
9866 ),
9867 SelectionGoal::None,
9868 )
9869 });
9870 })
9871 }
9872
9873 pub fn select_to_start_of_excerpt(
9874 &mut self,
9875 _: &SelectToStartOfExcerpt,
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_heads_with(|map, head, _| {
9886 (
9887 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9888 SelectionGoal::None,
9889 )
9890 });
9891 })
9892 }
9893
9894 pub fn select_to_end_of_excerpt(
9895 &mut self,
9896 _: &SelectToEndOfExcerpt,
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_heads_with(|map, head, _| {
9907 (
9908 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9909 SelectionGoal::None,
9910 )
9911 });
9912 })
9913 }
9914
9915 pub fn move_to_beginning(
9916 &mut self,
9917 _: &MoveToBeginning,
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.select_ranges(vec![0..0]);
9928 });
9929 }
9930
9931 pub fn select_to_beginning(
9932 &mut self,
9933 _: &SelectToBeginning,
9934 window: &mut Window,
9935 cx: &mut Context<Self>,
9936 ) {
9937 let mut selection = self.selections.last::<Point>(cx);
9938 selection.set_head(Point::zero(), SelectionGoal::None);
9939
9940 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9941 s.select(vec![selection]);
9942 });
9943 }
9944
9945 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
9946 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9947 cx.propagate();
9948 return;
9949 }
9950
9951 let cursor = self.buffer.read(cx).read(cx).len();
9952 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9953 s.select_ranges(vec![cursor..cursor])
9954 });
9955 }
9956
9957 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
9958 self.nav_history = nav_history;
9959 }
9960
9961 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
9962 self.nav_history.as_ref()
9963 }
9964
9965 fn push_to_nav_history(
9966 &mut self,
9967 cursor_anchor: Anchor,
9968 new_position: Option<Point>,
9969 cx: &mut Context<Self>,
9970 ) {
9971 if let Some(nav_history) = self.nav_history.as_mut() {
9972 let buffer = self.buffer.read(cx).read(cx);
9973 let cursor_position = cursor_anchor.to_point(&buffer);
9974 let scroll_state = self.scroll_manager.anchor();
9975 let scroll_top_row = scroll_state.top_row(&buffer);
9976 drop(buffer);
9977
9978 if let Some(new_position) = new_position {
9979 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
9980 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
9981 return;
9982 }
9983 }
9984
9985 nav_history.push(
9986 Some(NavigationData {
9987 cursor_anchor,
9988 cursor_position,
9989 scroll_anchor: scroll_state,
9990 scroll_top_row,
9991 }),
9992 cx,
9993 );
9994 }
9995 }
9996
9997 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
9998 let buffer = self.buffer.read(cx).snapshot(cx);
9999 let mut selection = self.selections.first::<usize>(cx);
10000 selection.set_head(buffer.len(), SelectionGoal::None);
10001 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10002 s.select(vec![selection]);
10003 });
10004 }
10005
10006 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10007 let end = self.buffer.read(cx).read(cx).len();
10008 self.change_selections(None, window, cx, |s| {
10009 s.select_ranges(vec![0..end]);
10010 });
10011 }
10012
10013 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10014 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10015 let mut selections = self.selections.all::<Point>(cx);
10016 let max_point = display_map.buffer_snapshot.max_point();
10017 for selection in &mut selections {
10018 let rows = selection.spanned_rows(true, &display_map);
10019 selection.start = Point::new(rows.start.0, 0);
10020 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10021 selection.reversed = false;
10022 }
10023 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10024 s.select(selections);
10025 });
10026 }
10027
10028 pub fn split_selection_into_lines(
10029 &mut self,
10030 _: &SplitSelectionIntoLines,
10031 window: &mut Window,
10032 cx: &mut Context<Self>,
10033 ) {
10034 let selections = self
10035 .selections
10036 .all::<Point>(cx)
10037 .into_iter()
10038 .map(|selection| selection.start..selection.end)
10039 .collect::<Vec<_>>();
10040 self.unfold_ranges(&selections, true, true, cx);
10041
10042 let mut new_selection_ranges = Vec::new();
10043 {
10044 let buffer = self.buffer.read(cx).read(cx);
10045 for selection in selections {
10046 for row in selection.start.row..selection.end.row {
10047 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10048 new_selection_ranges.push(cursor..cursor);
10049 }
10050
10051 let is_multiline_selection = selection.start.row != selection.end.row;
10052 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10053 // so this action feels more ergonomic when paired with other selection operations
10054 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10055 if !should_skip_last {
10056 new_selection_ranges.push(selection.end..selection.end);
10057 }
10058 }
10059 }
10060 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10061 s.select_ranges(new_selection_ranges);
10062 });
10063 }
10064
10065 pub fn add_selection_above(
10066 &mut self,
10067 _: &AddSelectionAbove,
10068 window: &mut Window,
10069 cx: &mut Context<Self>,
10070 ) {
10071 self.add_selection(true, window, cx);
10072 }
10073
10074 pub fn add_selection_below(
10075 &mut self,
10076 _: &AddSelectionBelow,
10077 window: &mut Window,
10078 cx: &mut Context<Self>,
10079 ) {
10080 self.add_selection(false, window, cx);
10081 }
10082
10083 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10084 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10085 let mut selections = self.selections.all::<Point>(cx);
10086 let text_layout_details = self.text_layout_details(window);
10087 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10088 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10089 let range = oldest_selection.display_range(&display_map).sorted();
10090
10091 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10092 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10093 let positions = start_x.min(end_x)..start_x.max(end_x);
10094
10095 selections.clear();
10096 let mut stack = Vec::new();
10097 for row in range.start.row().0..=range.end.row().0 {
10098 if let Some(selection) = self.selections.build_columnar_selection(
10099 &display_map,
10100 DisplayRow(row),
10101 &positions,
10102 oldest_selection.reversed,
10103 &text_layout_details,
10104 ) {
10105 stack.push(selection.id);
10106 selections.push(selection);
10107 }
10108 }
10109
10110 if above {
10111 stack.reverse();
10112 }
10113
10114 AddSelectionsState { above, stack }
10115 });
10116
10117 let last_added_selection = *state.stack.last().unwrap();
10118 let mut new_selections = Vec::new();
10119 if above == state.above {
10120 let end_row = if above {
10121 DisplayRow(0)
10122 } else {
10123 display_map.max_point().row()
10124 };
10125
10126 'outer: for selection in selections {
10127 if selection.id == last_added_selection {
10128 let range = selection.display_range(&display_map).sorted();
10129 debug_assert_eq!(range.start.row(), range.end.row());
10130 let mut row = range.start.row();
10131 let positions =
10132 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10133 px(start)..px(end)
10134 } else {
10135 let start_x =
10136 display_map.x_for_display_point(range.start, &text_layout_details);
10137 let end_x =
10138 display_map.x_for_display_point(range.end, &text_layout_details);
10139 start_x.min(end_x)..start_x.max(end_x)
10140 };
10141
10142 while row != end_row {
10143 if above {
10144 row.0 -= 1;
10145 } else {
10146 row.0 += 1;
10147 }
10148
10149 if let Some(new_selection) = self.selections.build_columnar_selection(
10150 &display_map,
10151 row,
10152 &positions,
10153 selection.reversed,
10154 &text_layout_details,
10155 ) {
10156 state.stack.push(new_selection.id);
10157 if above {
10158 new_selections.push(new_selection);
10159 new_selections.push(selection);
10160 } else {
10161 new_selections.push(selection);
10162 new_selections.push(new_selection);
10163 }
10164
10165 continue 'outer;
10166 }
10167 }
10168 }
10169
10170 new_selections.push(selection);
10171 }
10172 } else {
10173 new_selections = selections;
10174 new_selections.retain(|s| s.id != last_added_selection);
10175 state.stack.pop();
10176 }
10177
10178 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10179 s.select(new_selections);
10180 });
10181 if state.stack.len() > 1 {
10182 self.add_selections_state = Some(state);
10183 }
10184 }
10185
10186 pub fn select_next_match_internal(
10187 &mut self,
10188 display_map: &DisplaySnapshot,
10189 replace_newest: bool,
10190 autoscroll: Option<Autoscroll>,
10191 window: &mut Window,
10192 cx: &mut Context<Self>,
10193 ) -> Result<()> {
10194 fn select_next_match_ranges(
10195 this: &mut Editor,
10196 range: Range<usize>,
10197 replace_newest: bool,
10198 auto_scroll: Option<Autoscroll>,
10199 window: &mut Window,
10200 cx: &mut Context<Editor>,
10201 ) {
10202 this.unfold_ranges(&[range.clone()], false, true, cx);
10203 this.change_selections(auto_scroll, window, cx, |s| {
10204 if replace_newest {
10205 s.delete(s.newest_anchor().id);
10206 }
10207 s.insert_range(range.clone());
10208 });
10209 }
10210
10211 let buffer = &display_map.buffer_snapshot;
10212 let mut selections = self.selections.all::<usize>(cx);
10213 if let Some(mut select_next_state) = self.select_next_state.take() {
10214 let query = &select_next_state.query;
10215 if !select_next_state.done {
10216 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10217 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10218 let mut next_selected_range = None;
10219
10220 let bytes_after_last_selection =
10221 buffer.bytes_in_range(last_selection.end..buffer.len());
10222 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10223 let query_matches = query
10224 .stream_find_iter(bytes_after_last_selection)
10225 .map(|result| (last_selection.end, result))
10226 .chain(
10227 query
10228 .stream_find_iter(bytes_before_first_selection)
10229 .map(|result| (0, result)),
10230 );
10231
10232 for (start_offset, query_match) in query_matches {
10233 let query_match = query_match.unwrap(); // can only fail due to I/O
10234 let offset_range =
10235 start_offset + query_match.start()..start_offset + query_match.end();
10236 let display_range = offset_range.start.to_display_point(display_map)
10237 ..offset_range.end.to_display_point(display_map);
10238
10239 if !select_next_state.wordwise
10240 || (!movement::is_inside_word(display_map, display_range.start)
10241 && !movement::is_inside_word(display_map, display_range.end))
10242 {
10243 // TODO: This is n^2, because we might check all the selections
10244 if !selections
10245 .iter()
10246 .any(|selection| selection.range().overlaps(&offset_range))
10247 {
10248 next_selected_range = Some(offset_range);
10249 break;
10250 }
10251 }
10252 }
10253
10254 if let Some(next_selected_range) = next_selected_range {
10255 select_next_match_ranges(
10256 self,
10257 next_selected_range,
10258 replace_newest,
10259 autoscroll,
10260 window,
10261 cx,
10262 );
10263 } else {
10264 select_next_state.done = true;
10265 }
10266 }
10267
10268 self.select_next_state = Some(select_next_state);
10269 } else {
10270 let mut only_carets = true;
10271 let mut same_text_selected = true;
10272 let mut selected_text = None;
10273
10274 let mut selections_iter = selections.iter().peekable();
10275 while let Some(selection) = selections_iter.next() {
10276 if selection.start != selection.end {
10277 only_carets = false;
10278 }
10279
10280 if same_text_selected {
10281 if selected_text.is_none() {
10282 selected_text =
10283 Some(buffer.text_for_range(selection.range()).collect::<String>());
10284 }
10285
10286 if let Some(next_selection) = selections_iter.peek() {
10287 if next_selection.range().len() == selection.range().len() {
10288 let next_selected_text = buffer
10289 .text_for_range(next_selection.range())
10290 .collect::<String>();
10291 if Some(next_selected_text) != selected_text {
10292 same_text_selected = false;
10293 selected_text = None;
10294 }
10295 } else {
10296 same_text_selected = false;
10297 selected_text = None;
10298 }
10299 }
10300 }
10301 }
10302
10303 if only_carets {
10304 for selection in &mut selections {
10305 let word_range = movement::surrounding_word(
10306 display_map,
10307 selection.start.to_display_point(display_map),
10308 );
10309 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10310 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10311 selection.goal = SelectionGoal::None;
10312 selection.reversed = false;
10313 select_next_match_ranges(
10314 self,
10315 selection.start..selection.end,
10316 replace_newest,
10317 autoscroll,
10318 window,
10319 cx,
10320 );
10321 }
10322
10323 if selections.len() == 1 {
10324 let selection = selections
10325 .last()
10326 .expect("ensured that there's only one selection");
10327 let query = buffer
10328 .text_for_range(selection.start..selection.end)
10329 .collect::<String>();
10330 let is_empty = query.is_empty();
10331 let select_state = SelectNextState {
10332 query: AhoCorasick::new(&[query])?,
10333 wordwise: true,
10334 done: is_empty,
10335 };
10336 self.select_next_state = Some(select_state);
10337 } else {
10338 self.select_next_state = None;
10339 }
10340 } else if let Some(selected_text) = selected_text {
10341 self.select_next_state = Some(SelectNextState {
10342 query: AhoCorasick::new(&[selected_text])?,
10343 wordwise: false,
10344 done: false,
10345 });
10346 self.select_next_match_internal(
10347 display_map,
10348 replace_newest,
10349 autoscroll,
10350 window,
10351 cx,
10352 )?;
10353 }
10354 }
10355 Ok(())
10356 }
10357
10358 pub fn select_all_matches(
10359 &mut self,
10360 _action: &SelectAllMatches,
10361 window: &mut Window,
10362 cx: &mut Context<Self>,
10363 ) -> Result<()> {
10364 self.push_to_selection_history();
10365 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10366
10367 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10368 let Some(select_next_state) = self.select_next_state.as_mut() else {
10369 return Ok(());
10370 };
10371 if select_next_state.done {
10372 return Ok(());
10373 }
10374
10375 let mut new_selections = self.selections.all::<usize>(cx);
10376
10377 let buffer = &display_map.buffer_snapshot;
10378 let query_matches = select_next_state
10379 .query
10380 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10381
10382 for query_match in query_matches {
10383 let query_match = query_match.unwrap(); // can only fail due to I/O
10384 let offset_range = query_match.start()..query_match.end();
10385 let display_range = offset_range.start.to_display_point(&display_map)
10386 ..offset_range.end.to_display_point(&display_map);
10387
10388 if !select_next_state.wordwise
10389 || (!movement::is_inside_word(&display_map, display_range.start)
10390 && !movement::is_inside_word(&display_map, display_range.end))
10391 {
10392 self.selections.change_with(cx, |selections| {
10393 new_selections.push(Selection {
10394 id: selections.new_selection_id(),
10395 start: offset_range.start,
10396 end: offset_range.end,
10397 reversed: false,
10398 goal: SelectionGoal::None,
10399 });
10400 });
10401 }
10402 }
10403
10404 new_selections.sort_by_key(|selection| selection.start);
10405 let mut ix = 0;
10406 while ix + 1 < new_selections.len() {
10407 let current_selection = &new_selections[ix];
10408 let next_selection = &new_selections[ix + 1];
10409 if current_selection.range().overlaps(&next_selection.range()) {
10410 if current_selection.id < next_selection.id {
10411 new_selections.remove(ix + 1);
10412 } else {
10413 new_selections.remove(ix);
10414 }
10415 } else {
10416 ix += 1;
10417 }
10418 }
10419
10420 let reversed = self.selections.oldest::<usize>(cx).reversed;
10421
10422 for selection in new_selections.iter_mut() {
10423 selection.reversed = reversed;
10424 }
10425
10426 select_next_state.done = true;
10427 self.unfold_ranges(
10428 &new_selections
10429 .iter()
10430 .map(|selection| selection.range())
10431 .collect::<Vec<_>>(),
10432 false,
10433 false,
10434 cx,
10435 );
10436 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10437 selections.select(new_selections)
10438 });
10439
10440 Ok(())
10441 }
10442
10443 pub fn select_next(
10444 &mut self,
10445 action: &SelectNext,
10446 window: &mut Window,
10447 cx: &mut Context<Self>,
10448 ) -> Result<()> {
10449 self.push_to_selection_history();
10450 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10451 self.select_next_match_internal(
10452 &display_map,
10453 action.replace_newest,
10454 Some(Autoscroll::newest()),
10455 window,
10456 cx,
10457 )?;
10458 Ok(())
10459 }
10460
10461 pub fn select_previous(
10462 &mut self,
10463 action: &SelectPrevious,
10464 window: &mut Window,
10465 cx: &mut Context<Self>,
10466 ) -> Result<()> {
10467 self.push_to_selection_history();
10468 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10469 let buffer = &display_map.buffer_snapshot;
10470 let mut selections = self.selections.all::<usize>(cx);
10471 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10472 let query = &select_prev_state.query;
10473 if !select_prev_state.done {
10474 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10475 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10476 let mut next_selected_range = None;
10477 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10478 let bytes_before_last_selection =
10479 buffer.reversed_bytes_in_range(0..last_selection.start);
10480 let bytes_after_first_selection =
10481 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10482 let query_matches = query
10483 .stream_find_iter(bytes_before_last_selection)
10484 .map(|result| (last_selection.start, result))
10485 .chain(
10486 query
10487 .stream_find_iter(bytes_after_first_selection)
10488 .map(|result| (buffer.len(), result)),
10489 );
10490 for (end_offset, query_match) in query_matches {
10491 let query_match = query_match.unwrap(); // can only fail due to I/O
10492 let offset_range =
10493 end_offset - query_match.end()..end_offset - query_match.start();
10494 let display_range = offset_range.start.to_display_point(&display_map)
10495 ..offset_range.end.to_display_point(&display_map);
10496
10497 if !select_prev_state.wordwise
10498 || (!movement::is_inside_word(&display_map, display_range.start)
10499 && !movement::is_inside_word(&display_map, display_range.end))
10500 {
10501 next_selected_range = Some(offset_range);
10502 break;
10503 }
10504 }
10505
10506 if let Some(next_selected_range) = next_selected_range {
10507 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10508 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10509 if action.replace_newest {
10510 s.delete(s.newest_anchor().id);
10511 }
10512 s.insert_range(next_selected_range);
10513 });
10514 } else {
10515 select_prev_state.done = true;
10516 }
10517 }
10518
10519 self.select_prev_state = Some(select_prev_state);
10520 } else {
10521 let mut only_carets = true;
10522 let mut same_text_selected = true;
10523 let mut selected_text = None;
10524
10525 let mut selections_iter = selections.iter().peekable();
10526 while let Some(selection) = selections_iter.next() {
10527 if selection.start != selection.end {
10528 only_carets = false;
10529 }
10530
10531 if same_text_selected {
10532 if selected_text.is_none() {
10533 selected_text =
10534 Some(buffer.text_for_range(selection.range()).collect::<String>());
10535 }
10536
10537 if let Some(next_selection) = selections_iter.peek() {
10538 if next_selection.range().len() == selection.range().len() {
10539 let next_selected_text = buffer
10540 .text_for_range(next_selection.range())
10541 .collect::<String>();
10542 if Some(next_selected_text) != selected_text {
10543 same_text_selected = false;
10544 selected_text = None;
10545 }
10546 } else {
10547 same_text_selected = false;
10548 selected_text = None;
10549 }
10550 }
10551 }
10552 }
10553
10554 if only_carets {
10555 for selection in &mut selections {
10556 let word_range = movement::surrounding_word(
10557 &display_map,
10558 selection.start.to_display_point(&display_map),
10559 );
10560 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10561 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10562 selection.goal = SelectionGoal::None;
10563 selection.reversed = false;
10564 }
10565 if selections.len() == 1 {
10566 let selection = selections
10567 .last()
10568 .expect("ensured that there's only one selection");
10569 let query = buffer
10570 .text_for_range(selection.start..selection.end)
10571 .collect::<String>();
10572 let is_empty = query.is_empty();
10573 let select_state = SelectNextState {
10574 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10575 wordwise: true,
10576 done: is_empty,
10577 };
10578 self.select_prev_state = Some(select_state);
10579 } else {
10580 self.select_prev_state = None;
10581 }
10582
10583 self.unfold_ranges(
10584 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10585 false,
10586 true,
10587 cx,
10588 );
10589 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10590 s.select(selections);
10591 });
10592 } else if let Some(selected_text) = selected_text {
10593 self.select_prev_state = Some(SelectNextState {
10594 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10595 wordwise: false,
10596 done: false,
10597 });
10598 self.select_previous(action, window, cx)?;
10599 }
10600 }
10601 Ok(())
10602 }
10603
10604 pub fn toggle_comments(
10605 &mut self,
10606 action: &ToggleComments,
10607 window: &mut Window,
10608 cx: &mut Context<Self>,
10609 ) {
10610 if self.read_only(cx) {
10611 return;
10612 }
10613 let text_layout_details = &self.text_layout_details(window);
10614 self.transact(window, cx, |this, window, cx| {
10615 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10616 let mut edits = Vec::new();
10617 let mut selection_edit_ranges = Vec::new();
10618 let mut last_toggled_row = None;
10619 let snapshot = this.buffer.read(cx).read(cx);
10620 let empty_str: Arc<str> = Arc::default();
10621 let mut suffixes_inserted = Vec::new();
10622 let ignore_indent = action.ignore_indent;
10623
10624 fn comment_prefix_range(
10625 snapshot: &MultiBufferSnapshot,
10626 row: MultiBufferRow,
10627 comment_prefix: &str,
10628 comment_prefix_whitespace: &str,
10629 ignore_indent: bool,
10630 ) -> Range<Point> {
10631 let indent_size = if ignore_indent {
10632 0
10633 } else {
10634 snapshot.indent_size_for_line(row).len
10635 };
10636
10637 let start = Point::new(row.0, indent_size);
10638
10639 let mut line_bytes = snapshot
10640 .bytes_in_range(start..snapshot.max_point())
10641 .flatten()
10642 .copied();
10643
10644 // If this line currently begins with the line comment prefix, then record
10645 // the range containing the prefix.
10646 if line_bytes
10647 .by_ref()
10648 .take(comment_prefix.len())
10649 .eq(comment_prefix.bytes())
10650 {
10651 // Include any whitespace that matches the comment prefix.
10652 let matching_whitespace_len = line_bytes
10653 .zip(comment_prefix_whitespace.bytes())
10654 .take_while(|(a, b)| a == b)
10655 .count() as u32;
10656 let end = Point::new(
10657 start.row,
10658 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10659 );
10660 start..end
10661 } else {
10662 start..start
10663 }
10664 }
10665
10666 fn comment_suffix_range(
10667 snapshot: &MultiBufferSnapshot,
10668 row: MultiBufferRow,
10669 comment_suffix: &str,
10670 comment_suffix_has_leading_space: bool,
10671 ) -> Range<Point> {
10672 let end = Point::new(row.0, snapshot.line_len(row));
10673 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10674
10675 let mut line_end_bytes = snapshot
10676 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10677 .flatten()
10678 .copied();
10679
10680 let leading_space_len = if suffix_start_column > 0
10681 && line_end_bytes.next() == Some(b' ')
10682 && comment_suffix_has_leading_space
10683 {
10684 1
10685 } else {
10686 0
10687 };
10688
10689 // If this line currently begins with the line comment prefix, then record
10690 // the range containing the prefix.
10691 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10692 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10693 start..end
10694 } else {
10695 end..end
10696 }
10697 }
10698
10699 // TODO: Handle selections that cross excerpts
10700 for selection in &mut selections {
10701 let start_column = snapshot
10702 .indent_size_for_line(MultiBufferRow(selection.start.row))
10703 .len;
10704 let language = if let Some(language) =
10705 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10706 {
10707 language
10708 } else {
10709 continue;
10710 };
10711
10712 selection_edit_ranges.clear();
10713
10714 // If multiple selections contain a given row, avoid processing that
10715 // row more than once.
10716 let mut start_row = MultiBufferRow(selection.start.row);
10717 if last_toggled_row == Some(start_row) {
10718 start_row = start_row.next_row();
10719 }
10720 let end_row =
10721 if selection.end.row > selection.start.row && selection.end.column == 0 {
10722 MultiBufferRow(selection.end.row - 1)
10723 } else {
10724 MultiBufferRow(selection.end.row)
10725 };
10726 last_toggled_row = Some(end_row);
10727
10728 if start_row > end_row {
10729 continue;
10730 }
10731
10732 // If the language has line comments, toggle those.
10733 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10734
10735 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10736 if ignore_indent {
10737 full_comment_prefixes = full_comment_prefixes
10738 .into_iter()
10739 .map(|s| Arc::from(s.trim_end()))
10740 .collect();
10741 }
10742
10743 if !full_comment_prefixes.is_empty() {
10744 let first_prefix = full_comment_prefixes
10745 .first()
10746 .expect("prefixes is non-empty");
10747 let prefix_trimmed_lengths = full_comment_prefixes
10748 .iter()
10749 .map(|p| p.trim_end_matches(' ').len())
10750 .collect::<SmallVec<[usize; 4]>>();
10751
10752 let mut all_selection_lines_are_comments = true;
10753
10754 for row in start_row.0..=end_row.0 {
10755 let row = MultiBufferRow(row);
10756 if start_row < end_row && snapshot.is_line_blank(row) {
10757 continue;
10758 }
10759
10760 let prefix_range = full_comment_prefixes
10761 .iter()
10762 .zip(prefix_trimmed_lengths.iter().copied())
10763 .map(|(prefix, trimmed_prefix_len)| {
10764 comment_prefix_range(
10765 snapshot.deref(),
10766 row,
10767 &prefix[..trimmed_prefix_len],
10768 &prefix[trimmed_prefix_len..],
10769 ignore_indent,
10770 )
10771 })
10772 .max_by_key(|range| range.end.column - range.start.column)
10773 .expect("prefixes is non-empty");
10774
10775 if prefix_range.is_empty() {
10776 all_selection_lines_are_comments = false;
10777 }
10778
10779 selection_edit_ranges.push(prefix_range);
10780 }
10781
10782 if all_selection_lines_are_comments {
10783 edits.extend(
10784 selection_edit_ranges
10785 .iter()
10786 .cloned()
10787 .map(|range| (range, empty_str.clone())),
10788 );
10789 } else {
10790 let min_column = selection_edit_ranges
10791 .iter()
10792 .map(|range| range.start.column)
10793 .min()
10794 .unwrap_or(0);
10795 edits.extend(selection_edit_ranges.iter().map(|range| {
10796 let position = Point::new(range.start.row, min_column);
10797 (position..position, first_prefix.clone())
10798 }));
10799 }
10800 } else if let Some((full_comment_prefix, comment_suffix)) =
10801 language.block_comment_delimiters()
10802 {
10803 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10804 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10805 let prefix_range = comment_prefix_range(
10806 snapshot.deref(),
10807 start_row,
10808 comment_prefix,
10809 comment_prefix_whitespace,
10810 ignore_indent,
10811 );
10812 let suffix_range = comment_suffix_range(
10813 snapshot.deref(),
10814 end_row,
10815 comment_suffix.trim_start_matches(' '),
10816 comment_suffix.starts_with(' '),
10817 );
10818
10819 if prefix_range.is_empty() || suffix_range.is_empty() {
10820 edits.push((
10821 prefix_range.start..prefix_range.start,
10822 full_comment_prefix.clone(),
10823 ));
10824 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10825 suffixes_inserted.push((end_row, comment_suffix.len()));
10826 } else {
10827 edits.push((prefix_range, empty_str.clone()));
10828 edits.push((suffix_range, empty_str.clone()));
10829 }
10830 } else {
10831 continue;
10832 }
10833 }
10834
10835 drop(snapshot);
10836 this.buffer.update(cx, |buffer, cx| {
10837 buffer.edit(edits, None, cx);
10838 });
10839
10840 // Adjust selections so that they end before any comment suffixes that
10841 // were inserted.
10842 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10843 let mut selections = this.selections.all::<Point>(cx);
10844 let snapshot = this.buffer.read(cx).read(cx);
10845 for selection in &mut selections {
10846 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10847 match row.cmp(&MultiBufferRow(selection.end.row)) {
10848 Ordering::Less => {
10849 suffixes_inserted.next();
10850 continue;
10851 }
10852 Ordering::Greater => break,
10853 Ordering::Equal => {
10854 if selection.end.column == snapshot.line_len(row) {
10855 if selection.is_empty() {
10856 selection.start.column -= suffix_len as u32;
10857 }
10858 selection.end.column -= suffix_len as u32;
10859 }
10860 break;
10861 }
10862 }
10863 }
10864 }
10865
10866 drop(snapshot);
10867 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10868 s.select(selections)
10869 });
10870
10871 let selections = this.selections.all::<Point>(cx);
10872 let selections_on_single_row = selections.windows(2).all(|selections| {
10873 selections[0].start.row == selections[1].start.row
10874 && selections[0].end.row == selections[1].end.row
10875 && selections[0].start.row == selections[0].end.row
10876 });
10877 let selections_selecting = selections
10878 .iter()
10879 .any(|selection| selection.start != selection.end);
10880 let advance_downwards = action.advance_downwards
10881 && selections_on_single_row
10882 && !selections_selecting
10883 && !matches!(this.mode, EditorMode::SingleLine { .. });
10884
10885 if advance_downwards {
10886 let snapshot = this.buffer.read(cx).snapshot(cx);
10887
10888 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10889 s.move_cursors_with(|display_snapshot, display_point, _| {
10890 let mut point = display_point.to_point(display_snapshot);
10891 point.row += 1;
10892 point = snapshot.clip_point(point, Bias::Left);
10893 let display_point = point.to_display_point(display_snapshot);
10894 let goal = SelectionGoal::HorizontalPosition(
10895 display_snapshot
10896 .x_for_display_point(display_point, text_layout_details)
10897 .into(),
10898 );
10899 (display_point, goal)
10900 })
10901 });
10902 }
10903 });
10904 }
10905
10906 pub fn select_enclosing_symbol(
10907 &mut self,
10908 _: &SelectEnclosingSymbol,
10909 window: &mut Window,
10910 cx: &mut Context<Self>,
10911 ) {
10912 let buffer = self.buffer.read(cx).snapshot(cx);
10913 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10914
10915 fn update_selection(
10916 selection: &Selection<usize>,
10917 buffer_snap: &MultiBufferSnapshot,
10918 ) -> Option<Selection<usize>> {
10919 let cursor = selection.head();
10920 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10921 for symbol in symbols.iter().rev() {
10922 let start = symbol.range.start.to_offset(buffer_snap);
10923 let end = symbol.range.end.to_offset(buffer_snap);
10924 let new_range = start..end;
10925 if start < selection.start || end > selection.end {
10926 return Some(Selection {
10927 id: selection.id,
10928 start: new_range.start,
10929 end: new_range.end,
10930 goal: SelectionGoal::None,
10931 reversed: selection.reversed,
10932 });
10933 }
10934 }
10935 None
10936 }
10937
10938 let mut selected_larger_symbol = false;
10939 let new_selections = old_selections
10940 .iter()
10941 .map(|selection| match update_selection(selection, &buffer) {
10942 Some(new_selection) => {
10943 if new_selection.range() != selection.range() {
10944 selected_larger_symbol = true;
10945 }
10946 new_selection
10947 }
10948 None => selection.clone(),
10949 })
10950 .collect::<Vec<_>>();
10951
10952 if selected_larger_symbol {
10953 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10954 s.select(new_selections);
10955 });
10956 }
10957 }
10958
10959 pub fn select_larger_syntax_node(
10960 &mut self,
10961 _: &SelectLargerSyntaxNode,
10962 window: &mut Window,
10963 cx: &mut Context<Self>,
10964 ) {
10965 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10966 let buffer = self.buffer.read(cx).snapshot(cx);
10967 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10968
10969 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10970 let mut selected_larger_node = false;
10971 let new_selections = old_selections
10972 .iter()
10973 .map(|selection| {
10974 let old_range = selection.start..selection.end;
10975 let mut new_range = old_range.clone();
10976 let mut new_node = None;
10977 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10978 {
10979 new_node = Some(node);
10980 new_range = match containing_range {
10981 MultiOrSingleBufferOffsetRange::Single(_) => break,
10982 MultiOrSingleBufferOffsetRange::Multi(range) => range,
10983 };
10984 if !display_map.intersects_fold(new_range.start)
10985 && !display_map.intersects_fold(new_range.end)
10986 {
10987 break;
10988 }
10989 }
10990
10991 if let Some(node) = new_node {
10992 // Log the ancestor, to support using this action as a way to explore TreeSitter
10993 // nodes. Parent and grandparent are also logged because this operation will not
10994 // visit nodes that have the same range as their parent.
10995 log::info!("Node: {node:?}");
10996 let parent = node.parent();
10997 log::info!("Parent: {parent:?}");
10998 let grandparent = parent.and_then(|x| x.parent());
10999 log::info!("Grandparent: {grandparent:?}");
11000 }
11001
11002 selected_larger_node |= new_range != old_range;
11003 Selection {
11004 id: selection.id,
11005 start: new_range.start,
11006 end: new_range.end,
11007 goal: SelectionGoal::None,
11008 reversed: selection.reversed,
11009 }
11010 })
11011 .collect::<Vec<_>>();
11012
11013 if selected_larger_node {
11014 stack.push(old_selections);
11015 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11016 s.select(new_selections);
11017 });
11018 }
11019 self.select_larger_syntax_node_stack = stack;
11020 }
11021
11022 pub fn select_smaller_syntax_node(
11023 &mut self,
11024 _: &SelectSmallerSyntaxNode,
11025 window: &mut Window,
11026 cx: &mut Context<Self>,
11027 ) {
11028 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11029 if let Some(selections) = stack.pop() {
11030 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11031 s.select(selections.to_vec());
11032 });
11033 }
11034 self.select_larger_syntax_node_stack = stack;
11035 }
11036
11037 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11038 if !EditorSettings::get_global(cx).gutter.runnables {
11039 self.clear_tasks();
11040 return Task::ready(());
11041 }
11042 let project = self.project.as_ref().map(Entity::downgrade);
11043 cx.spawn_in(window, |this, mut cx| async move {
11044 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11045 let Some(project) = project.and_then(|p| p.upgrade()) else {
11046 return;
11047 };
11048 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11049 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11050 }) else {
11051 return;
11052 };
11053
11054 let hide_runnables = project
11055 .update(&mut cx, |project, cx| {
11056 // Do not display any test indicators in non-dev server remote projects.
11057 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11058 })
11059 .unwrap_or(true);
11060 if hide_runnables {
11061 return;
11062 }
11063 let new_rows =
11064 cx.background_spawn({
11065 let snapshot = display_snapshot.clone();
11066 async move {
11067 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11068 }
11069 })
11070 .await;
11071
11072 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11073 this.update(&mut cx, |this, _| {
11074 this.clear_tasks();
11075 for (key, value) in rows {
11076 this.insert_tasks(key, value);
11077 }
11078 })
11079 .ok();
11080 })
11081 }
11082 fn fetch_runnable_ranges(
11083 snapshot: &DisplaySnapshot,
11084 range: Range<Anchor>,
11085 ) -> Vec<language::RunnableRange> {
11086 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11087 }
11088
11089 fn runnable_rows(
11090 project: Entity<Project>,
11091 snapshot: DisplaySnapshot,
11092 runnable_ranges: Vec<RunnableRange>,
11093 mut cx: AsyncWindowContext,
11094 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11095 runnable_ranges
11096 .into_iter()
11097 .filter_map(|mut runnable| {
11098 let tasks = cx
11099 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11100 .ok()?;
11101 if tasks.is_empty() {
11102 return None;
11103 }
11104
11105 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11106
11107 let row = snapshot
11108 .buffer_snapshot
11109 .buffer_line_for_row(MultiBufferRow(point.row))?
11110 .1
11111 .start
11112 .row;
11113
11114 let context_range =
11115 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11116 Some((
11117 (runnable.buffer_id, row),
11118 RunnableTasks {
11119 templates: tasks,
11120 offset: snapshot
11121 .buffer_snapshot
11122 .anchor_before(runnable.run_range.start),
11123 context_range,
11124 column: point.column,
11125 extra_variables: runnable.extra_captures,
11126 },
11127 ))
11128 })
11129 .collect()
11130 }
11131
11132 fn templates_with_tags(
11133 project: &Entity<Project>,
11134 runnable: &mut Runnable,
11135 cx: &mut App,
11136 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11137 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11138 let (worktree_id, file) = project
11139 .buffer_for_id(runnable.buffer, cx)
11140 .and_then(|buffer| buffer.read(cx).file())
11141 .map(|file| (file.worktree_id(cx), file.clone()))
11142 .unzip();
11143
11144 (
11145 project.task_store().read(cx).task_inventory().cloned(),
11146 worktree_id,
11147 file,
11148 )
11149 });
11150
11151 let tags = mem::take(&mut runnable.tags);
11152 let mut tags: Vec<_> = tags
11153 .into_iter()
11154 .flat_map(|tag| {
11155 let tag = tag.0.clone();
11156 inventory
11157 .as_ref()
11158 .into_iter()
11159 .flat_map(|inventory| {
11160 inventory.read(cx).list_tasks(
11161 file.clone(),
11162 Some(runnable.language.clone()),
11163 worktree_id,
11164 cx,
11165 )
11166 })
11167 .filter(move |(_, template)| {
11168 template.tags.iter().any(|source_tag| source_tag == &tag)
11169 })
11170 })
11171 .sorted_by_key(|(kind, _)| kind.to_owned())
11172 .collect();
11173 if let Some((leading_tag_source, _)) = tags.first() {
11174 // Strongest source wins; if we have worktree tag binding, prefer that to
11175 // global and language bindings;
11176 // if we have a global binding, prefer that to language binding.
11177 let first_mismatch = tags
11178 .iter()
11179 .position(|(tag_source, _)| tag_source != leading_tag_source);
11180 if let Some(index) = first_mismatch {
11181 tags.truncate(index);
11182 }
11183 }
11184
11185 tags
11186 }
11187
11188 pub fn move_to_enclosing_bracket(
11189 &mut self,
11190 _: &MoveToEnclosingBracket,
11191 window: &mut Window,
11192 cx: &mut Context<Self>,
11193 ) {
11194 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11195 s.move_offsets_with(|snapshot, selection| {
11196 let Some(enclosing_bracket_ranges) =
11197 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11198 else {
11199 return;
11200 };
11201
11202 let mut best_length = usize::MAX;
11203 let mut best_inside = false;
11204 let mut best_in_bracket_range = false;
11205 let mut best_destination = None;
11206 for (open, close) in enclosing_bracket_ranges {
11207 let close = close.to_inclusive();
11208 let length = close.end() - open.start;
11209 let inside = selection.start >= open.end && selection.end <= *close.start();
11210 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11211 || close.contains(&selection.head());
11212
11213 // If best is next to a bracket and current isn't, skip
11214 if !in_bracket_range && best_in_bracket_range {
11215 continue;
11216 }
11217
11218 // Prefer smaller lengths unless best is inside and current isn't
11219 if length > best_length && (best_inside || !inside) {
11220 continue;
11221 }
11222
11223 best_length = length;
11224 best_inside = inside;
11225 best_in_bracket_range = in_bracket_range;
11226 best_destination = Some(
11227 if close.contains(&selection.start) && close.contains(&selection.end) {
11228 if inside {
11229 open.end
11230 } else {
11231 open.start
11232 }
11233 } else if inside {
11234 *close.start()
11235 } else {
11236 *close.end()
11237 },
11238 );
11239 }
11240
11241 if let Some(destination) = best_destination {
11242 selection.collapse_to(destination, SelectionGoal::None);
11243 }
11244 })
11245 });
11246 }
11247
11248 pub fn undo_selection(
11249 &mut self,
11250 _: &UndoSelection,
11251 window: &mut Window,
11252 cx: &mut Context<Self>,
11253 ) {
11254 self.end_selection(window, cx);
11255 self.selection_history.mode = SelectionHistoryMode::Undoing;
11256 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11257 self.change_selections(None, window, cx, |s| {
11258 s.select_anchors(entry.selections.to_vec())
11259 });
11260 self.select_next_state = entry.select_next_state;
11261 self.select_prev_state = entry.select_prev_state;
11262 self.add_selections_state = entry.add_selections_state;
11263 self.request_autoscroll(Autoscroll::newest(), cx);
11264 }
11265 self.selection_history.mode = SelectionHistoryMode::Normal;
11266 }
11267
11268 pub fn redo_selection(
11269 &mut self,
11270 _: &RedoSelection,
11271 window: &mut Window,
11272 cx: &mut Context<Self>,
11273 ) {
11274 self.end_selection(window, cx);
11275 self.selection_history.mode = SelectionHistoryMode::Redoing;
11276 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11277 self.change_selections(None, window, cx, |s| {
11278 s.select_anchors(entry.selections.to_vec())
11279 });
11280 self.select_next_state = entry.select_next_state;
11281 self.select_prev_state = entry.select_prev_state;
11282 self.add_selections_state = entry.add_selections_state;
11283 self.request_autoscroll(Autoscroll::newest(), cx);
11284 }
11285 self.selection_history.mode = SelectionHistoryMode::Normal;
11286 }
11287
11288 pub fn expand_excerpts(
11289 &mut self,
11290 action: &ExpandExcerpts,
11291 _: &mut Window,
11292 cx: &mut Context<Self>,
11293 ) {
11294 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11295 }
11296
11297 pub fn expand_excerpts_down(
11298 &mut self,
11299 action: &ExpandExcerptsDown,
11300 _: &mut Window,
11301 cx: &mut Context<Self>,
11302 ) {
11303 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11304 }
11305
11306 pub fn expand_excerpts_up(
11307 &mut self,
11308 action: &ExpandExcerptsUp,
11309 _: &mut Window,
11310 cx: &mut Context<Self>,
11311 ) {
11312 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11313 }
11314
11315 pub fn expand_excerpts_for_direction(
11316 &mut self,
11317 lines: u32,
11318 direction: ExpandExcerptDirection,
11319
11320 cx: &mut Context<Self>,
11321 ) {
11322 let selections = self.selections.disjoint_anchors();
11323
11324 let lines = if lines == 0 {
11325 EditorSettings::get_global(cx).expand_excerpt_lines
11326 } else {
11327 lines
11328 };
11329
11330 self.buffer.update(cx, |buffer, cx| {
11331 let snapshot = buffer.snapshot(cx);
11332 let mut excerpt_ids = selections
11333 .iter()
11334 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11335 .collect::<Vec<_>>();
11336 excerpt_ids.sort();
11337 excerpt_ids.dedup();
11338 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11339 })
11340 }
11341
11342 pub fn expand_excerpt(
11343 &mut self,
11344 excerpt: ExcerptId,
11345 direction: ExpandExcerptDirection,
11346 cx: &mut Context<Self>,
11347 ) {
11348 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11349 self.buffer.update(cx, |buffer, cx| {
11350 buffer.expand_excerpts([excerpt], lines, direction, cx)
11351 })
11352 }
11353
11354 pub fn go_to_singleton_buffer_point(
11355 &mut self,
11356 point: Point,
11357 window: &mut Window,
11358 cx: &mut Context<Self>,
11359 ) {
11360 self.go_to_singleton_buffer_range(point..point, window, cx);
11361 }
11362
11363 pub fn go_to_singleton_buffer_range(
11364 &mut self,
11365 range: Range<Point>,
11366 window: &mut Window,
11367 cx: &mut Context<Self>,
11368 ) {
11369 let multibuffer = self.buffer().read(cx);
11370 let Some(buffer) = multibuffer.as_singleton() else {
11371 return;
11372 };
11373 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11374 return;
11375 };
11376 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11377 return;
11378 };
11379 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11380 s.select_anchor_ranges([start..end])
11381 });
11382 }
11383
11384 fn go_to_diagnostic(
11385 &mut self,
11386 _: &GoToDiagnostic,
11387 window: &mut Window,
11388 cx: &mut Context<Self>,
11389 ) {
11390 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11391 }
11392
11393 fn go_to_prev_diagnostic(
11394 &mut self,
11395 _: &GoToPreviousDiagnostic,
11396 window: &mut Window,
11397 cx: &mut Context<Self>,
11398 ) {
11399 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11400 }
11401
11402 pub fn go_to_diagnostic_impl(
11403 &mut self,
11404 direction: Direction,
11405 window: &mut Window,
11406 cx: &mut Context<Self>,
11407 ) {
11408 let buffer = self.buffer.read(cx).snapshot(cx);
11409 let selection = self.selections.newest::<usize>(cx);
11410
11411 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11412 if direction == Direction::Next {
11413 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11414 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11415 return;
11416 };
11417 self.activate_diagnostics(
11418 buffer_id,
11419 popover.local_diagnostic.diagnostic.group_id,
11420 window,
11421 cx,
11422 );
11423 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11424 let primary_range_start = active_diagnostics.primary_range.start;
11425 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11426 let mut new_selection = s.newest_anchor().clone();
11427 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11428 s.select_anchors(vec![new_selection.clone()]);
11429 });
11430 self.refresh_inline_completion(false, true, window, cx);
11431 }
11432 return;
11433 }
11434 }
11435
11436 let active_group_id = self
11437 .active_diagnostics
11438 .as_ref()
11439 .map(|active_group| active_group.group_id);
11440 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11441 active_diagnostics
11442 .primary_range
11443 .to_offset(&buffer)
11444 .to_inclusive()
11445 });
11446 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11447 if active_primary_range.contains(&selection.head()) {
11448 *active_primary_range.start()
11449 } else {
11450 selection.head()
11451 }
11452 } else {
11453 selection.head()
11454 };
11455
11456 let snapshot = self.snapshot(window, cx);
11457 let primary_diagnostics_before = buffer
11458 .diagnostics_in_range::<usize>(0..search_start)
11459 .filter(|entry| entry.diagnostic.is_primary)
11460 .filter(|entry| entry.range.start != entry.range.end)
11461 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11462 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11463 .collect::<Vec<_>>();
11464 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11465 primary_diagnostics_before
11466 .iter()
11467 .position(|entry| entry.diagnostic.group_id == active_group_id)
11468 });
11469
11470 let primary_diagnostics_after = buffer
11471 .diagnostics_in_range::<usize>(search_start..buffer.len())
11472 .filter(|entry| entry.diagnostic.is_primary)
11473 .filter(|entry| entry.range.start != entry.range.end)
11474 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11475 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11476 .collect::<Vec<_>>();
11477 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11478 primary_diagnostics_after
11479 .iter()
11480 .enumerate()
11481 .rev()
11482 .find_map(|(i, entry)| {
11483 if entry.diagnostic.group_id == active_group_id {
11484 Some(i)
11485 } else {
11486 None
11487 }
11488 })
11489 });
11490
11491 let next_primary_diagnostic = match direction {
11492 Direction::Prev => primary_diagnostics_before
11493 .iter()
11494 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11495 .rev()
11496 .next(),
11497 Direction::Next => primary_diagnostics_after
11498 .iter()
11499 .skip(
11500 last_same_group_diagnostic_after
11501 .map(|index| index + 1)
11502 .unwrap_or(0),
11503 )
11504 .next(),
11505 };
11506
11507 // Cycle around to the start of the buffer, potentially moving back to the start of
11508 // the currently active diagnostic.
11509 let cycle_around = || match direction {
11510 Direction::Prev => primary_diagnostics_after
11511 .iter()
11512 .rev()
11513 .chain(primary_diagnostics_before.iter().rev())
11514 .next(),
11515 Direction::Next => primary_diagnostics_before
11516 .iter()
11517 .chain(primary_diagnostics_after.iter())
11518 .next(),
11519 };
11520
11521 if let Some((primary_range, group_id)) = next_primary_diagnostic
11522 .or_else(cycle_around)
11523 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11524 {
11525 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11526 return;
11527 };
11528 self.activate_diagnostics(buffer_id, group_id, window, cx);
11529 if self.active_diagnostics.is_some() {
11530 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11531 s.select(vec![Selection {
11532 id: selection.id,
11533 start: primary_range.start,
11534 end: primary_range.start,
11535 reversed: false,
11536 goal: SelectionGoal::None,
11537 }]);
11538 });
11539 self.refresh_inline_completion(false, true, window, cx);
11540 }
11541 }
11542 }
11543
11544 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11545 let snapshot = self.snapshot(window, cx);
11546 let selection = self.selections.newest::<Point>(cx);
11547 self.go_to_hunk_after_or_before_position(
11548 &snapshot,
11549 selection.head(),
11550 Direction::Next,
11551 window,
11552 cx,
11553 );
11554 }
11555
11556 fn go_to_hunk_after_or_before_position(
11557 &mut self,
11558 snapshot: &EditorSnapshot,
11559 position: Point,
11560 direction: Direction,
11561 window: &mut Window,
11562 cx: &mut Context<Editor>,
11563 ) {
11564 let row = if direction == Direction::Next {
11565 self.hunk_after_position(snapshot, position)
11566 .map(|hunk| hunk.row_range.start)
11567 } else {
11568 self.hunk_before_position(snapshot, position)
11569 };
11570
11571 if let Some(row) = row {
11572 let destination = Point::new(row.0, 0);
11573 let autoscroll = Autoscroll::center();
11574
11575 self.unfold_ranges(&[destination..destination], false, false, cx);
11576 self.change_selections(Some(autoscroll), window, cx, |s| {
11577 s.select_ranges([destination..destination]);
11578 });
11579 }
11580 }
11581
11582 fn hunk_after_position(
11583 &mut self,
11584 snapshot: &EditorSnapshot,
11585 position: Point,
11586 ) -> Option<MultiBufferDiffHunk> {
11587 snapshot
11588 .buffer_snapshot
11589 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11590 .find(|hunk| hunk.row_range.start.0 > position.row)
11591 .or_else(|| {
11592 snapshot
11593 .buffer_snapshot
11594 .diff_hunks_in_range(Point::zero()..position)
11595 .find(|hunk| hunk.row_range.end.0 < position.row)
11596 })
11597 }
11598
11599 fn go_to_prev_hunk(
11600 &mut self,
11601 _: &GoToPreviousHunk,
11602 window: &mut Window,
11603 cx: &mut Context<Self>,
11604 ) {
11605 let snapshot = self.snapshot(window, cx);
11606 let selection = self.selections.newest::<Point>(cx);
11607 self.go_to_hunk_after_or_before_position(
11608 &snapshot,
11609 selection.head(),
11610 Direction::Prev,
11611 window,
11612 cx,
11613 );
11614 }
11615
11616 fn hunk_before_position(
11617 &mut self,
11618 snapshot: &EditorSnapshot,
11619 position: Point,
11620 ) -> Option<MultiBufferRow> {
11621 snapshot
11622 .buffer_snapshot
11623 .diff_hunk_before(position)
11624 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11625 }
11626
11627 pub fn go_to_definition(
11628 &mut self,
11629 _: &GoToDefinition,
11630 window: &mut Window,
11631 cx: &mut Context<Self>,
11632 ) -> Task<Result<Navigated>> {
11633 let definition =
11634 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11635 cx.spawn_in(window, |editor, mut cx| async move {
11636 if definition.await? == Navigated::Yes {
11637 return Ok(Navigated::Yes);
11638 }
11639 match editor.update_in(&mut cx, |editor, window, cx| {
11640 editor.find_all_references(&FindAllReferences, window, cx)
11641 })? {
11642 Some(references) => references.await,
11643 None => Ok(Navigated::No),
11644 }
11645 })
11646 }
11647
11648 pub fn go_to_declaration(
11649 &mut self,
11650 _: &GoToDeclaration,
11651 window: &mut Window,
11652 cx: &mut Context<Self>,
11653 ) -> Task<Result<Navigated>> {
11654 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11655 }
11656
11657 pub fn go_to_declaration_split(
11658 &mut self,
11659 _: &GoToDeclaration,
11660 window: &mut Window,
11661 cx: &mut Context<Self>,
11662 ) -> Task<Result<Navigated>> {
11663 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11664 }
11665
11666 pub fn go_to_implementation(
11667 &mut self,
11668 _: &GoToImplementation,
11669 window: &mut Window,
11670 cx: &mut Context<Self>,
11671 ) -> Task<Result<Navigated>> {
11672 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11673 }
11674
11675 pub fn go_to_implementation_split(
11676 &mut self,
11677 _: &GoToImplementationSplit,
11678 window: &mut Window,
11679 cx: &mut Context<Self>,
11680 ) -> Task<Result<Navigated>> {
11681 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11682 }
11683
11684 pub fn go_to_type_definition(
11685 &mut self,
11686 _: &GoToTypeDefinition,
11687 window: &mut Window,
11688 cx: &mut Context<Self>,
11689 ) -> Task<Result<Navigated>> {
11690 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11691 }
11692
11693 pub fn go_to_definition_split(
11694 &mut self,
11695 _: &GoToDefinitionSplit,
11696 window: &mut Window,
11697 cx: &mut Context<Self>,
11698 ) -> Task<Result<Navigated>> {
11699 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11700 }
11701
11702 pub fn go_to_type_definition_split(
11703 &mut self,
11704 _: &GoToTypeDefinitionSplit,
11705 window: &mut Window,
11706 cx: &mut Context<Self>,
11707 ) -> Task<Result<Navigated>> {
11708 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11709 }
11710
11711 fn go_to_definition_of_kind(
11712 &mut self,
11713 kind: GotoDefinitionKind,
11714 split: bool,
11715 window: &mut Window,
11716 cx: &mut Context<Self>,
11717 ) -> Task<Result<Navigated>> {
11718 let Some(provider) = self.semantics_provider.clone() else {
11719 return Task::ready(Ok(Navigated::No));
11720 };
11721 let head = self.selections.newest::<usize>(cx).head();
11722 let buffer = self.buffer.read(cx);
11723 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11724 text_anchor
11725 } else {
11726 return Task::ready(Ok(Navigated::No));
11727 };
11728
11729 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11730 return Task::ready(Ok(Navigated::No));
11731 };
11732
11733 cx.spawn_in(window, |editor, mut cx| async move {
11734 let definitions = definitions.await?;
11735 let navigated = editor
11736 .update_in(&mut cx, |editor, window, cx| {
11737 editor.navigate_to_hover_links(
11738 Some(kind),
11739 definitions
11740 .into_iter()
11741 .filter(|location| {
11742 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11743 })
11744 .map(HoverLink::Text)
11745 .collect::<Vec<_>>(),
11746 split,
11747 window,
11748 cx,
11749 )
11750 })?
11751 .await?;
11752 anyhow::Ok(navigated)
11753 })
11754 }
11755
11756 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11757 let selection = self.selections.newest_anchor();
11758 let head = selection.head();
11759 let tail = selection.tail();
11760
11761 let Some((buffer, start_position)) =
11762 self.buffer.read(cx).text_anchor_for_position(head, cx)
11763 else {
11764 return;
11765 };
11766
11767 let end_position = if head != tail {
11768 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11769 return;
11770 };
11771 Some(pos)
11772 } else {
11773 None
11774 };
11775
11776 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11777 let url = if let Some(end_pos) = end_position {
11778 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11779 } else {
11780 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11781 };
11782
11783 if let Some(url) = url {
11784 editor.update(&mut cx, |_, cx| {
11785 cx.open_url(&url);
11786 })
11787 } else {
11788 Ok(())
11789 }
11790 });
11791
11792 url_finder.detach();
11793 }
11794
11795 pub fn open_selected_filename(
11796 &mut self,
11797 _: &OpenSelectedFilename,
11798 window: &mut Window,
11799 cx: &mut Context<Self>,
11800 ) {
11801 let Some(workspace) = self.workspace() else {
11802 return;
11803 };
11804
11805 let position = self.selections.newest_anchor().head();
11806
11807 let Some((buffer, buffer_position)) =
11808 self.buffer.read(cx).text_anchor_for_position(position, cx)
11809 else {
11810 return;
11811 };
11812
11813 let project = self.project.clone();
11814
11815 cx.spawn_in(window, |_, mut cx| async move {
11816 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11817
11818 if let Some((_, path)) = result {
11819 workspace
11820 .update_in(&mut cx, |workspace, window, cx| {
11821 workspace.open_resolved_path(path, window, cx)
11822 })?
11823 .await?;
11824 }
11825 anyhow::Ok(())
11826 })
11827 .detach();
11828 }
11829
11830 pub(crate) fn navigate_to_hover_links(
11831 &mut self,
11832 kind: Option<GotoDefinitionKind>,
11833 mut definitions: Vec<HoverLink>,
11834 split: bool,
11835 window: &mut Window,
11836 cx: &mut Context<Editor>,
11837 ) -> Task<Result<Navigated>> {
11838 // If there is one definition, just open it directly
11839 if definitions.len() == 1 {
11840 let definition = definitions.pop().unwrap();
11841
11842 enum TargetTaskResult {
11843 Location(Option<Location>),
11844 AlreadyNavigated,
11845 }
11846
11847 let target_task = match definition {
11848 HoverLink::Text(link) => {
11849 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11850 }
11851 HoverLink::InlayHint(lsp_location, server_id) => {
11852 let computation =
11853 self.compute_target_location(lsp_location, server_id, window, cx);
11854 cx.background_spawn(async move {
11855 let location = computation.await?;
11856 Ok(TargetTaskResult::Location(location))
11857 })
11858 }
11859 HoverLink::Url(url) => {
11860 cx.open_url(&url);
11861 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11862 }
11863 HoverLink::File(path) => {
11864 if let Some(workspace) = self.workspace() {
11865 cx.spawn_in(window, |_, mut cx| async move {
11866 workspace
11867 .update_in(&mut cx, |workspace, window, cx| {
11868 workspace.open_resolved_path(path, window, cx)
11869 })?
11870 .await
11871 .map(|_| TargetTaskResult::AlreadyNavigated)
11872 })
11873 } else {
11874 Task::ready(Ok(TargetTaskResult::Location(None)))
11875 }
11876 }
11877 };
11878 cx.spawn_in(window, |editor, mut cx| async move {
11879 let target = match target_task.await.context("target resolution task")? {
11880 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11881 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11882 TargetTaskResult::Location(Some(target)) => target,
11883 };
11884
11885 editor.update_in(&mut cx, |editor, window, cx| {
11886 let Some(workspace) = editor.workspace() else {
11887 return Navigated::No;
11888 };
11889 let pane = workspace.read(cx).active_pane().clone();
11890
11891 let range = target.range.to_point(target.buffer.read(cx));
11892 let range = editor.range_for_match(&range);
11893 let range = collapse_multiline_range(range);
11894
11895 if !split
11896 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11897 {
11898 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11899 } else {
11900 window.defer(cx, move |window, cx| {
11901 let target_editor: Entity<Self> =
11902 workspace.update(cx, |workspace, cx| {
11903 let pane = if split {
11904 workspace.adjacent_pane(window, cx)
11905 } else {
11906 workspace.active_pane().clone()
11907 };
11908
11909 workspace.open_project_item(
11910 pane,
11911 target.buffer.clone(),
11912 true,
11913 true,
11914 window,
11915 cx,
11916 )
11917 });
11918 target_editor.update(cx, |target_editor, cx| {
11919 // When selecting a definition in a different buffer, disable the nav history
11920 // to avoid creating a history entry at the previous cursor location.
11921 pane.update(cx, |pane, _| pane.disable_history());
11922 target_editor.go_to_singleton_buffer_range(range, window, cx);
11923 pane.update(cx, |pane, _| pane.enable_history());
11924 });
11925 });
11926 }
11927 Navigated::Yes
11928 })
11929 })
11930 } else if !definitions.is_empty() {
11931 cx.spawn_in(window, |editor, mut cx| async move {
11932 let (title, location_tasks, workspace) = editor
11933 .update_in(&mut cx, |editor, window, cx| {
11934 let tab_kind = match kind {
11935 Some(GotoDefinitionKind::Implementation) => "Implementations",
11936 _ => "Definitions",
11937 };
11938 let title = definitions
11939 .iter()
11940 .find_map(|definition| match definition {
11941 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11942 let buffer = origin.buffer.read(cx);
11943 format!(
11944 "{} for {}",
11945 tab_kind,
11946 buffer
11947 .text_for_range(origin.range.clone())
11948 .collect::<String>()
11949 )
11950 }),
11951 HoverLink::InlayHint(_, _) => None,
11952 HoverLink::Url(_) => None,
11953 HoverLink::File(_) => None,
11954 })
11955 .unwrap_or(tab_kind.to_string());
11956 let location_tasks = definitions
11957 .into_iter()
11958 .map(|definition| match definition {
11959 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11960 HoverLink::InlayHint(lsp_location, server_id) => editor
11961 .compute_target_location(lsp_location, server_id, window, cx),
11962 HoverLink::Url(_) => Task::ready(Ok(None)),
11963 HoverLink::File(_) => Task::ready(Ok(None)),
11964 })
11965 .collect::<Vec<_>>();
11966 (title, location_tasks, editor.workspace().clone())
11967 })
11968 .context("location tasks preparation")?;
11969
11970 let locations = future::join_all(location_tasks)
11971 .await
11972 .into_iter()
11973 .filter_map(|location| location.transpose())
11974 .collect::<Result<_>>()
11975 .context("location tasks")?;
11976
11977 let Some(workspace) = workspace else {
11978 return Ok(Navigated::No);
11979 };
11980 let opened = workspace
11981 .update_in(&mut cx, |workspace, window, cx| {
11982 Self::open_locations_in_multibuffer(
11983 workspace,
11984 locations,
11985 title,
11986 split,
11987 MultibufferSelectionMode::First,
11988 window,
11989 cx,
11990 )
11991 })
11992 .ok();
11993
11994 anyhow::Ok(Navigated::from_bool(opened.is_some()))
11995 })
11996 } else {
11997 Task::ready(Ok(Navigated::No))
11998 }
11999 }
12000
12001 fn compute_target_location(
12002 &self,
12003 lsp_location: lsp::Location,
12004 server_id: LanguageServerId,
12005 window: &mut Window,
12006 cx: &mut Context<Self>,
12007 ) -> Task<anyhow::Result<Option<Location>>> {
12008 let Some(project) = self.project.clone() else {
12009 return Task::ready(Ok(None));
12010 };
12011
12012 cx.spawn_in(window, move |editor, mut cx| async move {
12013 let location_task = editor.update(&mut cx, |_, cx| {
12014 project.update(cx, |project, cx| {
12015 let language_server_name = project
12016 .language_server_statuses(cx)
12017 .find(|(id, _)| server_id == *id)
12018 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12019 language_server_name.map(|language_server_name| {
12020 project.open_local_buffer_via_lsp(
12021 lsp_location.uri.clone(),
12022 server_id,
12023 language_server_name,
12024 cx,
12025 )
12026 })
12027 })
12028 })?;
12029 let location = match location_task {
12030 Some(task) => Some({
12031 let target_buffer_handle = task.await.context("open local buffer")?;
12032 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12033 let target_start = target_buffer
12034 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12035 let target_end = target_buffer
12036 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12037 target_buffer.anchor_after(target_start)
12038 ..target_buffer.anchor_before(target_end)
12039 })?;
12040 Location {
12041 buffer: target_buffer_handle,
12042 range,
12043 }
12044 }),
12045 None => None,
12046 };
12047 Ok(location)
12048 })
12049 }
12050
12051 pub fn find_all_references(
12052 &mut self,
12053 _: &FindAllReferences,
12054 window: &mut Window,
12055 cx: &mut Context<Self>,
12056 ) -> Option<Task<Result<Navigated>>> {
12057 let selection = self.selections.newest::<usize>(cx);
12058 let multi_buffer = self.buffer.read(cx);
12059 let head = selection.head();
12060
12061 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12062 let head_anchor = multi_buffer_snapshot.anchor_at(
12063 head,
12064 if head < selection.tail() {
12065 Bias::Right
12066 } else {
12067 Bias::Left
12068 },
12069 );
12070
12071 match self
12072 .find_all_references_task_sources
12073 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12074 {
12075 Ok(_) => {
12076 log::info!(
12077 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12078 );
12079 return None;
12080 }
12081 Err(i) => {
12082 self.find_all_references_task_sources.insert(i, head_anchor);
12083 }
12084 }
12085
12086 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12087 let workspace = self.workspace()?;
12088 let project = workspace.read(cx).project().clone();
12089 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12090 Some(cx.spawn_in(window, |editor, mut cx| async move {
12091 let _cleanup = defer({
12092 let mut cx = cx.clone();
12093 move || {
12094 let _ = editor.update(&mut cx, |editor, _| {
12095 if let Ok(i) =
12096 editor
12097 .find_all_references_task_sources
12098 .binary_search_by(|anchor| {
12099 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12100 })
12101 {
12102 editor.find_all_references_task_sources.remove(i);
12103 }
12104 });
12105 }
12106 });
12107
12108 let locations = references.await?;
12109 if locations.is_empty() {
12110 return anyhow::Ok(Navigated::No);
12111 }
12112
12113 workspace.update_in(&mut cx, |workspace, window, cx| {
12114 let title = locations
12115 .first()
12116 .as_ref()
12117 .map(|location| {
12118 let buffer = location.buffer.read(cx);
12119 format!(
12120 "References to `{}`",
12121 buffer
12122 .text_for_range(location.range.clone())
12123 .collect::<String>()
12124 )
12125 })
12126 .unwrap();
12127 Self::open_locations_in_multibuffer(
12128 workspace,
12129 locations,
12130 title,
12131 false,
12132 MultibufferSelectionMode::First,
12133 window,
12134 cx,
12135 );
12136 Navigated::Yes
12137 })
12138 }))
12139 }
12140
12141 /// Opens a multibuffer with the given project locations in it
12142 pub fn open_locations_in_multibuffer(
12143 workspace: &mut Workspace,
12144 mut locations: Vec<Location>,
12145 title: String,
12146 split: bool,
12147 multibuffer_selection_mode: MultibufferSelectionMode,
12148 window: &mut Window,
12149 cx: &mut Context<Workspace>,
12150 ) {
12151 // If there are multiple definitions, open them in a multibuffer
12152 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12153 let mut locations = locations.into_iter().peekable();
12154 let mut ranges = Vec::new();
12155 let capability = workspace.project().read(cx).capability();
12156
12157 let excerpt_buffer = cx.new(|cx| {
12158 let mut multibuffer = MultiBuffer::new(capability);
12159 while let Some(location) = locations.next() {
12160 let buffer = location.buffer.read(cx);
12161 let mut ranges_for_buffer = Vec::new();
12162 let range = location.range.to_offset(buffer);
12163 ranges_for_buffer.push(range.clone());
12164
12165 while let Some(next_location) = locations.peek() {
12166 if next_location.buffer == location.buffer {
12167 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12168 locations.next();
12169 } else {
12170 break;
12171 }
12172 }
12173
12174 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12175 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12176 location.buffer.clone(),
12177 ranges_for_buffer,
12178 DEFAULT_MULTIBUFFER_CONTEXT,
12179 cx,
12180 ))
12181 }
12182
12183 multibuffer.with_title(title)
12184 });
12185
12186 let editor = cx.new(|cx| {
12187 Editor::for_multibuffer(
12188 excerpt_buffer,
12189 Some(workspace.project().clone()),
12190 true,
12191 window,
12192 cx,
12193 )
12194 });
12195 editor.update(cx, |editor, cx| {
12196 match multibuffer_selection_mode {
12197 MultibufferSelectionMode::First => {
12198 if let Some(first_range) = ranges.first() {
12199 editor.change_selections(None, window, cx, |selections| {
12200 selections.clear_disjoint();
12201 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12202 });
12203 }
12204 editor.highlight_background::<Self>(
12205 &ranges,
12206 |theme| theme.editor_highlighted_line_background,
12207 cx,
12208 );
12209 }
12210 MultibufferSelectionMode::All => {
12211 editor.change_selections(None, window, cx, |selections| {
12212 selections.clear_disjoint();
12213 selections.select_anchor_ranges(ranges);
12214 });
12215 }
12216 }
12217 editor.register_buffers_with_language_servers(cx);
12218 });
12219
12220 let item = Box::new(editor);
12221 let item_id = item.item_id();
12222
12223 if split {
12224 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12225 } else {
12226 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12227 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12228 pane.close_current_preview_item(window, cx)
12229 } else {
12230 None
12231 }
12232 });
12233 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12234 }
12235 workspace.active_pane().update(cx, |pane, cx| {
12236 pane.set_preview_item_id(Some(item_id), cx);
12237 });
12238 }
12239
12240 pub fn rename(
12241 &mut self,
12242 _: &Rename,
12243 window: &mut Window,
12244 cx: &mut Context<Self>,
12245 ) -> Option<Task<Result<()>>> {
12246 use language::ToOffset as _;
12247
12248 let provider = self.semantics_provider.clone()?;
12249 let selection = self.selections.newest_anchor().clone();
12250 let (cursor_buffer, cursor_buffer_position) = self
12251 .buffer
12252 .read(cx)
12253 .text_anchor_for_position(selection.head(), cx)?;
12254 let (tail_buffer, cursor_buffer_position_end) = self
12255 .buffer
12256 .read(cx)
12257 .text_anchor_for_position(selection.tail(), cx)?;
12258 if tail_buffer != cursor_buffer {
12259 return None;
12260 }
12261
12262 let snapshot = cursor_buffer.read(cx).snapshot();
12263 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12264 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12265 let prepare_rename = provider
12266 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12267 .unwrap_or_else(|| Task::ready(Ok(None)));
12268 drop(snapshot);
12269
12270 Some(cx.spawn_in(window, |this, mut cx| async move {
12271 let rename_range = if let Some(range) = prepare_rename.await? {
12272 Some(range)
12273 } else {
12274 this.update(&mut cx, |this, cx| {
12275 let buffer = this.buffer.read(cx).snapshot(cx);
12276 let mut buffer_highlights = this
12277 .document_highlights_for_position(selection.head(), &buffer)
12278 .filter(|highlight| {
12279 highlight.start.excerpt_id == selection.head().excerpt_id
12280 && highlight.end.excerpt_id == selection.head().excerpt_id
12281 });
12282 buffer_highlights
12283 .next()
12284 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12285 })?
12286 };
12287 if let Some(rename_range) = rename_range {
12288 this.update_in(&mut cx, |this, window, cx| {
12289 let snapshot = cursor_buffer.read(cx).snapshot();
12290 let rename_buffer_range = rename_range.to_offset(&snapshot);
12291 let cursor_offset_in_rename_range =
12292 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12293 let cursor_offset_in_rename_range_end =
12294 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12295
12296 this.take_rename(false, window, cx);
12297 let buffer = this.buffer.read(cx).read(cx);
12298 let cursor_offset = selection.head().to_offset(&buffer);
12299 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12300 let rename_end = rename_start + rename_buffer_range.len();
12301 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12302 let mut old_highlight_id = None;
12303 let old_name: Arc<str> = buffer
12304 .chunks(rename_start..rename_end, true)
12305 .map(|chunk| {
12306 if old_highlight_id.is_none() {
12307 old_highlight_id = chunk.syntax_highlight_id;
12308 }
12309 chunk.text
12310 })
12311 .collect::<String>()
12312 .into();
12313
12314 drop(buffer);
12315
12316 // Position the selection in the rename editor so that it matches the current selection.
12317 this.show_local_selections = false;
12318 let rename_editor = cx.new(|cx| {
12319 let mut editor = Editor::single_line(window, cx);
12320 editor.buffer.update(cx, |buffer, cx| {
12321 buffer.edit([(0..0, old_name.clone())], None, cx)
12322 });
12323 let rename_selection_range = match cursor_offset_in_rename_range
12324 .cmp(&cursor_offset_in_rename_range_end)
12325 {
12326 Ordering::Equal => {
12327 editor.select_all(&SelectAll, window, cx);
12328 return editor;
12329 }
12330 Ordering::Less => {
12331 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12332 }
12333 Ordering::Greater => {
12334 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12335 }
12336 };
12337 if rename_selection_range.end > old_name.len() {
12338 editor.select_all(&SelectAll, window, cx);
12339 } else {
12340 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12341 s.select_ranges([rename_selection_range]);
12342 });
12343 }
12344 editor
12345 });
12346 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12347 if e == &EditorEvent::Focused {
12348 cx.emit(EditorEvent::FocusedIn)
12349 }
12350 })
12351 .detach();
12352
12353 let write_highlights =
12354 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12355 let read_highlights =
12356 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12357 let ranges = write_highlights
12358 .iter()
12359 .flat_map(|(_, ranges)| ranges.iter())
12360 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12361 .cloned()
12362 .collect();
12363
12364 this.highlight_text::<Rename>(
12365 ranges,
12366 HighlightStyle {
12367 fade_out: Some(0.6),
12368 ..Default::default()
12369 },
12370 cx,
12371 );
12372 let rename_focus_handle = rename_editor.focus_handle(cx);
12373 window.focus(&rename_focus_handle);
12374 let block_id = this.insert_blocks(
12375 [BlockProperties {
12376 style: BlockStyle::Flex,
12377 placement: BlockPlacement::Below(range.start),
12378 height: 1,
12379 render: Arc::new({
12380 let rename_editor = rename_editor.clone();
12381 move |cx: &mut BlockContext| {
12382 let mut text_style = cx.editor_style.text.clone();
12383 if let Some(highlight_style) = old_highlight_id
12384 .and_then(|h| h.style(&cx.editor_style.syntax))
12385 {
12386 text_style = text_style.highlight(highlight_style);
12387 }
12388 div()
12389 .block_mouse_down()
12390 .pl(cx.anchor_x)
12391 .child(EditorElement::new(
12392 &rename_editor,
12393 EditorStyle {
12394 background: cx.theme().system().transparent,
12395 local_player: cx.editor_style.local_player,
12396 text: text_style,
12397 scrollbar_width: cx.editor_style.scrollbar_width,
12398 syntax: cx.editor_style.syntax.clone(),
12399 status: cx.editor_style.status.clone(),
12400 inlay_hints_style: HighlightStyle {
12401 font_weight: Some(FontWeight::BOLD),
12402 ..make_inlay_hints_style(cx.app)
12403 },
12404 inline_completion_styles: make_suggestion_styles(
12405 cx.app,
12406 ),
12407 ..EditorStyle::default()
12408 },
12409 ))
12410 .into_any_element()
12411 }
12412 }),
12413 priority: 0,
12414 }],
12415 Some(Autoscroll::fit()),
12416 cx,
12417 )[0];
12418 this.pending_rename = Some(RenameState {
12419 range,
12420 old_name,
12421 editor: rename_editor,
12422 block_id,
12423 });
12424 })?;
12425 }
12426
12427 Ok(())
12428 }))
12429 }
12430
12431 pub fn confirm_rename(
12432 &mut self,
12433 _: &ConfirmRename,
12434 window: &mut Window,
12435 cx: &mut Context<Self>,
12436 ) -> Option<Task<Result<()>>> {
12437 let rename = self.take_rename(false, window, cx)?;
12438 let workspace = self.workspace()?.downgrade();
12439 let (buffer, start) = self
12440 .buffer
12441 .read(cx)
12442 .text_anchor_for_position(rename.range.start, cx)?;
12443 let (end_buffer, _) = self
12444 .buffer
12445 .read(cx)
12446 .text_anchor_for_position(rename.range.end, cx)?;
12447 if buffer != end_buffer {
12448 return None;
12449 }
12450
12451 let old_name = rename.old_name;
12452 let new_name = rename.editor.read(cx).text(cx);
12453
12454 let rename = self.semantics_provider.as_ref()?.perform_rename(
12455 &buffer,
12456 start,
12457 new_name.clone(),
12458 cx,
12459 )?;
12460
12461 Some(cx.spawn_in(window, |editor, mut cx| async move {
12462 let project_transaction = rename.await?;
12463 Self::open_project_transaction(
12464 &editor,
12465 workspace,
12466 project_transaction,
12467 format!("Rename: {} → {}", old_name, new_name),
12468 cx.clone(),
12469 )
12470 .await?;
12471
12472 editor.update(&mut cx, |editor, cx| {
12473 editor.refresh_document_highlights(cx);
12474 })?;
12475 Ok(())
12476 }))
12477 }
12478
12479 fn take_rename(
12480 &mut self,
12481 moving_cursor: bool,
12482 window: &mut Window,
12483 cx: &mut Context<Self>,
12484 ) -> Option<RenameState> {
12485 let rename = self.pending_rename.take()?;
12486 if rename.editor.focus_handle(cx).is_focused(window) {
12487 window.focus(&self.focus_handle);
12488 }
12489
12490 self.remove_blocks(
12491 [rename.block_id].into_iter().collect(),
12492 Some(Autoscroll::fit()),
12493 cx,
12494 );
12495 self.clear_highlights::<Rename>(cx);
12496 self.show_local_selections = true;
12497
12498 if moving_cursor {
12499 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12500 editor.selections.newest::<usize>(cx).head()
12501 });
12502
12503 // Update the selection to match the position of the selection inside
12504 // the rename editor.
12505 let snapshot = self.buffer.read(cx).read(cx);
12506 let rename_range = rename.range.to_offset(&snapshot);
12507 let cursor_in_editor = snapshot
12508 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12509 .min(rename_range.end);
12510 drop(snapshot);
12511
12512 self.change_selections(None, window, cx, |s| {
12513 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12514 });
12515 } else {
12516 self.refresh_document_highlights(cx);
12517 }
12518
12519 Some(rename)
12520 }
12521
12522 pub fn pending_rename(&self) -> Option<&RenameState> {
12523 self.pending_rename.as_ref()
12524 }
12525
12526 fn format(
12527 &mut self,
12528 _: &Format,
12529 window: &mut Window,
12530 cx: &mut Context<Self>,
12531 ) -> Option<Task<Result<()>>> {
12532 let project = match &self.project {
12533 Some(project) => project.clone(),
12534 None => return None,
12535 };
12536
12537 Some(self.perform_format(
12538 project,
12539 FormatTrigger::Manual,
12540 FormatTarget::Buffers,
12541 window,
12542 cx,
12543 ))
12544 }
12545
12546 fn format_selections(
12547 &mut self,
12548 _: &FormatSelections,
12549 window: &mut Window,
12550 cx: &mut Context<Self>,
12551 ) -> Option<Task<Result<()>>> {
12552 let project = match &self.project {
12553 Some(project) => project.clone(),
12554 None => return None,
12555 };
12556
12557 let ranges = self
12558 .selections
12559 .all_adjusted(cx)
12560 .into_iter()
12561 .map(|selection| selection.range())
12562 .collect_vec();
12563
12564 Some(self.perform_format(
12565 project,
12566 FormatTrigger::Manual,
12567 FormatTarget::Ranges(ranges),
12568 window,
12569 cx,
12570 ))
12571 }
12572
12573 fn perform_format(
12574 &mut self,
12575 project: Entity<Project>,
12576 trigger: FormatTrigger,
12577 target: FormatTarget,
12578 window: &mut Window,
12579 cx: &mut Context<Self>,
12580 ) -> Task<Result<()>> {
12581 let buffer = self.buffer.clone();
12582 let (buffers, target) = match target {
12583 FormatTarget::Buffers => {
12584 let mut buffers = buffer.read(cx).all_buffers();
12585 if trigger == FormatTrigger::Save {
12586 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12587 }
12588 (buffers, LspFormatTarget::Buffers)
12589 }
12590 FormatTarget::Ranges(selection_ranges) => {
12591 let multi_buffer = buffer.read(cx);
12592 let snapshot = multi_buffer.read(cx);
12593 let mut buffers = HashSet::default();
12594 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12595 BTreeMap::new();
12596 for selection_range in selection_ranges {
12597 for (buffer, buffer_range, _) in
12598 snapshot.range_to_buffer_ranges(selection_range)
12599 {
12600 let buffer_id = buffer.remote_id();
12601 let start = buffer.anchor_before(buffer_range.start);
12602 let end = buffer.anchor_after(buffer_range.end);
12603 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12604 buffer_id_to_ranges
12605 .entry(buffer_id)
12606 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12607 .or_insert_with(|| vec![start..end]);
12608 }
12609 }
12610 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12611 }
12612 };
12613
12614 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12615 let format = project.update(cx, |project, cx| {
12616 project.format(buffers, target, true, trigger, cx)
12617 });
12618
12619 cx.spawn_in(window, |_, mut cx| async move {
12620 let transaction = futures::select_biased! {
12621 () = timeout => {
12622 log::warn!("timed out waiting for formatting");
12623 None
12624 }
12625 transaction = format.log_err().fuse() => transaction,
12626 };
12627
12628 buffer
12629 .update(&mut cx, |buffer, cx| {
12630 if let Some(transaction) = transaction {
12631 if !buffer.is_singleton() {
12632 buffer.push_transaction(&transaction.0, cx);
12633 }
12634 }
12635 cx.notify();
12636 })
12637 .ok();
12638
12639 Ok(())
12640 })
12641 }
12642
12643 fn organize_imports(
12644 &mut self,
12645 _: &OrganizeImports,
12646 window: &mut Window,
12647 cx: &mut Context<Self>,
12648 ) -> Option<Task<Result<()>>> {
12649 let project = match &self.project {
12650 Some(project) => project.clone(),
12651 None => return None,
12652 };
12653 Some(self.perform_code_action_kind(
12654 project,
12655 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12656 window,
12657 cx,
12658 ))
12659 }
12660
12661 fn perform_code_action_kind(
12662 &mut self,
12663 project: Entity<Project>,
12664 kind: CodeActionKind,
12665 window: &mut Window,
12666 cx: &mut Context<Self>,
12667 ) -> Task<Result<()>> {
12668 let buffer = self.buffer.clone();
12669 let buffers = buffer.read(cx).all_buffers();
12670 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12671 let apply_action = project.update(cx, |project, cx| {
12672 project.apply_code_action_kind(buffers, kind, true, cx)
12673 });
12674 cx.spawn_in(window, |_, mut cx| async move {
12675 let transaction = futures::select_biased! {
12676 () = timeout => {
12677 log::warn!("timed out waiting for executing code action");
12678 None
12679 }
12680 transaction = apply_action.log_err().fuse() => transaction,
12681 };
12682 buffer
12683 .update(&mut cx, |buffer, cx| {
12684 // check if we need this
12685 if let Some(transaction) = transaction {
12686 if !buffer.is_singleton() {
12687 buffer.push_transaction(&transaction.0, cx);
12688 }
12689 }
12690 cx.notify();
12691 })
12692 .ok();
12693 Ok(())
12694 })
12695 }
12696
12697 fn restart_language_server(
12698 &mut self,
12699 _: &RestartLanguageServer,
12700 _: &mut Window,
12701 cx: &mut Context<Self>,
12702 ) {
12703 if let Some(project) = self.project.clone() {
12704 self.buffer.update(cx, |multi_buffer, cx| {
12705 project.update(cx, |project, cx| {
12706 project.restart_language_servers_for_buffers(
12707 multi_buffer.all_buffers().into_iter().collect(),
12708 cx,
12709 );
12710 });
12711 })
12712 }
12713 }
12714
12715 fn cancel_language_server_work(
12716 workspace: &mut Workspace,
12717 _: &actions::CancelLanguageServerWork,
12718 _: &mut Window,
12719 cx: &mut Context<Workspace>,
12720 ) {
12721 let project = workspace.project();
12722 let buffers = workspace
12723 .active_item(cx)
12724 .and_then(|item| item.act_as::<Editor>(cx))
12725 .map_or(HashSet::default(), |editor| {
12726 editor.read(cx).buffer.read(cx).all_buffers()
12727 });
12728 project.update(cx, |project, cx| {
12729 project.cancel_language_server_work_for_buffers(buffers, cx);
12730 });
12731 }
12732
12733 fn show_character_palette(
12734 &mut self,
12735 _: &ShowCharacterPalette,
12736 window: &mut Window,
12737 _: &mut Context<Self>,
12738 ) {
12739 window.show_character_palette();
12740 }
12741
12742 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12743 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12744 let buffer = self.buffer.read(cx).snapshot(cx);
12745 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12746 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12747 let is_valid = buffer
12748 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12749 .any(|entry| {
12750 entry.diagnostic.is_primary
12751 && !entry.range.is_empty()
12752 && entry.range.start == primary_range_start
12753 && entry.diagnostic.message == active_diagnostics.primary_message
12754 });
12755
12756 if is_valid != active_diagnostics.is_valid {
12757 active_diagnostics.is_valid = is_valid;
12758 if is_valid {
12759 let mut new_styles = HashMap::default();
12760 for (block_id, diagnostic) in &active_diagnostics.blocks {
12761 new_styles.insert(
12762 *block_id,
12763 diagnostic_block_renderer(diagnostic.clone(), None, true),
12764 );
12765 }
12766 self.display_map.update(cx, |display_map, _cx| {
12767 display_map.replace_blocks(new_styles);
12768 });
12769 } else {
12770 self.dismiss_diagnostics(cx);
12771 }
12772 }
12773 }
12774 }
12775
12776 fn activate_diagnostics(
12777 &mut self,
12778 buffer_id: BufferId,
12779 group_id: usize,
12780 window: &mut Window,
12781 cx: &mut Context<Self>,
12782 ) {
12783 self.dismiss_diagnostics(cx);
12784 let snapshot = self.snapshot(window, cx);
12785 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12786 let buffer = self.buffer.read(cx).snapshot(cx);
12787
12788 let mut primary_range = None;
12789 let mut primary_message = None;
12790 let diagnostic_group = buffer
12791 .diagnostic_group(buffer_id, group_id)
12792 .filter_map(|entry| {
12793 let start = entry.range.start;
12794 let end = entry.range.end;
12795 if snapshot.is_line_folded(MultiBufferRow(start.row))
12796 && (start.row == end.row
12797 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12798 {
12799 return None;
12800 }
12801 if entry.diagnostic.is_primary {
12802 primary_range = Some(entry.range.clone());
12803 primary_message = Some(entry.diagnostic.message.clone());
12804 }
12805 Some(entry)
12806 })
12807 .collect::<Vec<_>>();
12808 let primary_range = primary_range?;
12809 let primary_message = primary_message?;
12810
12811 let blocks = display_map
12812 .insert_blocks(
12813 diagnostic_group.iter().map(|entry| {
12814 let diagnostic = entry.diagnostic.clone();
12815 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12816 BlockProperties {
12817 style: BlockStyle::Fixed,
12818 placement: BlockPlacement::Below(
12819 buffer.anchor_after(entry.range.start),
12820 ),
12821 height: message_height,
12822 render: diagnostic_block_renderer(diagnostic, None, true),
12823 priority: 0,
12824 }
12825 }),
12826 cx,
12827 )
12828 .into_iter()
12829 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12830 .collect();
12831
12832 Some(ActiveDiagnosticGroup {
12833 primary_range: buffer.anchor_before(primary_range.start)
12834 ..buffer.anchor_after(primary_range.end),
12835 primary_message,
12836 group_id,
12837 blocks,
12838 is_valid: true,
12839 })
12840 });
12841 }
12842
12843 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12844 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12845 self.display_map.update(cx, |display_map, cx| {
12846 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12847 });
12848 cx.notify();
12849 }
12850 }
12851
12852 /// Disable inline diagnostics rendering for this editor.
12853 pub fn disable_inline_diagnostics(&mut self) {
12854 self.inline_diagnostics_enabled = false;
12855 self.inline_diagnostics_update = Task::ready(());
12856 self.inline_diagnostics.clear();
12857 }
12858
12859 pub fn inline_diagnostics_enabled(&self) -> bool {
12860 self.inline_diagnostics_enabled
12861 }
12862
12863 pub fn show_inline_diagnostics(&self) -> bool {
12864 self.show_inline_diagnostics
12865 }
12866
12867 pub fn toggle_inline_diagnostics(
12868 &mut self,
12869 _: &ToggleInlineDiagnostics,
12870 window: &mut Window,
12871 cx: &mut Context<'_, Editor>,
12872 ) {
12873 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12874 self.refresh_inline_diagnostics(false, window, cx);
12875 }
12876
12877 fn refresh_inline_diagnostics(
12878 &mut self,
12879 debounce: bool,
12880 window: &mut Window,
12881 cx: &mut Context<Self>,
12882 ) {
12883 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12884 self.inline_diagnostics_update = Task::ready(());
12885 self.inline_diagnostics.clear();
12886 return;
12887 }
12888
12889 let debounce_ms = ProjectSettings::get_global(cx)
12890 .diagnostics
12891 .inline
12892 .update_debounce_ms;
12893 let debounce = if debounce && debounce_ms > 0 {
12894 Some(Duration::from_millis(debounce_ms))
12895 } else {
12896 None
12897 };
12898 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12899 if let Some(debounce) = debounce {
12900 cx.background_executor().timer(debounce).await;
12901 }
12902 let Some(snapshot) = editor
12903 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12904 .ok()
12905 else {
12906 return;
12907 };
12908
12909 let new_inline_diagnostics = cx
12910 .background_spawn(async move {
12911 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
12912 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
12913 let message = diagnostic_entry
12914 .diagnostic
12915 .message
12916 .split_once('\n')
12917 .map(|(line, _)| line)
12918 .map(SharedString::new)
12919 .unwrap_or_else(|| {
12920 SharedString::from(diagnostic_entry.diagnostic.message)
12921 });
12922 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
12923 let (Ok(i) | Err(i)) = inline_diagnostics
12924 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
12925 inline_diagnostics.insert(
12926 i,
12927 (
12928 start_anchor,
12929 InlineDiagnostic {
12930 message,
12931 group_id: diagnostic_entry.diagnostic.group_id,
12932 start: diagnostic_entry.range.start.to_point(&snapshot),
12933 is_primary: diagnostic_entry.diagnostic.is_primary,
12934 severity: diagnostic_entry.diagnostic.severity,
12935 },
12936 ),
12937 );
12938 }
12939 inline_diagnostics
12940 })
12941 .await;
12942
12943 editor
12944 .update(&mut cx, |editor, cx| {
12945 editor.inline_diagnostics = new_inline_diagnostics;
12946 cx.notify();
12947 })
12948 .ok();
12949 });
12950 }
12951
12952 pub fn set_selections_from_remote(
12953 &mut self,
12954 selections: Vec<Selection<Anchor>>,
12955 pending_selection: Option<Selection<Anchor>>,
12956 window: &mut Window,
12957 cx: &mut Context<Self>,
12958 ) {
12959 let old_cursor_position = self.selections.newest_anchor().head();
12960 self.selections.change_with(cx, |s| {
12961 s.select_anchors(selections);
12962 if let Some(pending_selection) = pending_selection {
12963 s.set_pending(pending_selection, SelectMode::Character);
12964 } else {
12965 s.clear_pending();
12966 }
12967 });
12968 self.selections_did_change(false, &old_cursor_position, true, window, cx);
12969 }
12970
12971 fn push_to_selection_history(&mut self) {
12972 self.selection_history.push(SelectionHistoryEntry {
12973 selections: self.selections.disjoint_anchors(),
12974 select_next_state: self.select_next_state.clone(),
12975 select_prev_state: self.select_prev_state.clone(),
12976 add_selections_state: self.add_selections_state.clone(),
12977 });
12978 }
12979
12980 pub fn transact(
12981 &mut self,
12982 window: &mut Window,
12983 cx: &mut Context<Self>,
12984 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
12985 ) -> Option<TransactionId> {
12986 self.start_transaction_at(Instant::now(), window, cx);
12987 update(self, window, cx);
12988 self.end_transaction_at(Instant::now(), cx)
12989 }
12990
12991 pub fn start_transaction_at(
12992 &mut self,
12993 now: Instant,
12994 window: &mut Window,
12995 cx: &mut Context<Self>,
12996 ) {
12997 self.end_selection(window, cx);
12998 if let Some(tx_id) = self
12999 .buffer
13000 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13001 {
13002 self.selection_history
13003 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13004 cx.emit(EditorEvent::TransactionBegun {
13005 transaction_id: tx_id,
13006 })
13007 }
13008 }
13009
13010 pub fn end_transaction_at(
13011 &mut self,
13012 now: Instant,
13013 cx: &mut Context<Self>,
13014 ) -> Option<TransactionId> {
13015 if let Some(transaction_id) = self
13016 .buffer
13017 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13018 {
13019 if let Some((_, end_selections)) =
13020 self.selection_history.transaction_mut(transaction_id)
13021 {
13022 *end_selections = Some(self.selections.disjoint_anchors());
13023 } else {
13024 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13025 }
13026
13027 cx.emit(EditorEvent::Edited { transaction_id });
13028 Some(transaction_id)
13029 } else {
13030 None
13031 }
13032 }
13033
13034 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13035 if self.selection_mark_mode {
13036 self.change_selections(None, window, cx, |s| {
13037 s.move_with(|_, sel| {
13038 sel.collapse_to(sel.head(), SelectionGoal::None);
13039 });
13040 })
13041 }
13042 self.selection_mark_mode = true;
13043 cx.notify();
13044 }
13045
13046 pub fn swap_selection_ends(
13047 &mut self,
13048 _: &actions::SwapSelectionEnds,
13049 window: &mut Window,
13050 cx: &mut Context<Self>,
13051 ) {
13052 self.change_selections(None, window, cx, |s| {
13053 s.move_with(|_, sel| {
13054 if sel.start != sel.end {
13055 sel.reversed = !sel.reversed
13056 }
13057 });
13058 });
13059 self.request_autoscroll(Autoscroll::newest(), cx);
13060 cx.notify();
13061 }
13062
13063 pub fn toggle_fold(
13064 &mut self,
13065 _: &actions::ToggleFold,
13066 window: &mut Window,
13067 cx: &mut Context<Self>,
13068 ) {
13069 if self.is_singleton(cx) {
13070 let selection = self.selections.newest::<Point>(cx);
13071
13072 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13073 let range = if selection.is_empty() {
13074 let point = selection.head().to_display_point(&display_map);
13075 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13076 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13077 .to_point(&display_map);
13078 start..end
13079 } else {
13080 selection.range()
13081 };
13082 if display_map.folds_in_range(range).next().is_some() {
13083 self.unfold_lines(&Default::default(), window, cx)
13084 } else {
13085 self.fold(&Default::default(), window, cx)
13086 }
13087 } else {
13088 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13089 let buffer_ids: HashSet<_> = self
13090 .selections
13091 .disjoint_anchor_ranges()
13092 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13093 .collect();
13094
13095 let should_unfold = buffer_ids
13096 .iter()
13097 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13098
13099 for buffer_id in buffer_ids {
13100 if should_unfold {
13101 self.unfold_buffer(buffer_id, cx);
13102 } else {
13103 self.fold_buffer(buffer_id, cx);
13104 }
13105 }
13106 }
13107 }
13108
13109 pub fn toggle_fold_recursive(
13110 &mut self,
13111 _: &actions::ToggleFoldRecursive,
13112 window: &mut Window,
13113 cx: &mut Context<Self>,
13114 ) {
13115 let selection = self.selections.newest::<Point>(cx);
13116
13117 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13118 let range = if selection.is_empty() {
13119 let point = selection.head().to_display_point(&display_map);
13120 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13121 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13122 .to_point(&display_map);
13123 start..end
13124 } else {
13125 selection.range()
13126 };
13127 if display_map.folds_in_range(range).next().is_some() {
13128 self.unfold_recursive(&Default::default(), window, cx)
13129 } else {
13130 self.fold_recursive(&Default::default(), window, cx)
13131 }
13132 }
13133
13134 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13135 if self.is_singleton(cx) {
13136 let mut to_fold = Vec::new();
13137 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13138 let selections = self.selections.all_adjusted(cx);
13139
13140 for selection in selections {
13141 let range = selection.range().sorted();
13142 let buffer_start_row = range.start.row;
13143
13144 if range.start.row != range.end.row {
13145 let mut found = false;
13146 let mut row = range.start.row;
13147 while row <= range.end.row {
13148 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13149 {
13150 found = true;
13151 row = crease.range().end.row + 1;
13152 to_fold.push(crease);
13153 } else {
13154 row += 1
13155 }
13156 }
13157 if found {
13158 continue;
13159 }
13160 }
13161
13162 for row in (0..=range.start.row).rev() {
13163 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13164 if crease.range().end.row >= buffer_start_row {
13165 to_fold.push(crease);
13166 if row <= range.start.row {
13167 break;
13168 }
13169 }
13170 }
13171 }
13172 }
13173
13174 self.fold_creases(to_fold, true, window, cx);
13175 } else {
13176 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13177 let buffer_ids = self
13178 .selections
13179 .disjoint_anchor_ranges()
13180 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13181 .collect::<HashSet<_>>();
13182 for buffer_id in buffer_ids {
13183 self.fold_buffer(buffer_id, cx);
13184 }
13185 }
13186 }
13187
13188 fn fold_at_level(
13189 &mut self,
13190 fold_at: &FoldAtLevel,
13191 window: &mut Window,
13192 cx: &mut Context<Self>,
13193 ) {
13194 if !self.buffer.read(cx).is_singleton() {
13195 return;
13196 }
13197
13198 let fold_at_level = fold_at.0;
13199 let snapshot = self.buffer.read(cx).snapshot(cx);
13200 let mut to_fold = Vec::new();
13201 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13202
13203 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13204 while start_row < end_row {
13205 match self
13206 .snapshot(window, cx)
13207 .crease_for_buffer_row(MultiBufferRow(start_row))
13208 {
13209 Some(crease) => {
13210 let nested_start_row = crease.range().start.row + 1;
13211 let nested_end_row = crease.range().end.row;
13212
13213 if current_level < fold_at_level {
13214 stack.push((nested_start_row, nested_end_row, current_level + 1));
13215 } else if current_level == fold_at_level {
13216 to_fold.push(crease);
13217 }
13218
13219 start_row = nested_end_row + 1;
13220 }
13221 None => start_row += 1,
13222 }
13223 }
13224 }
13225
13226 self.fold_creases(to_fold, true, window, cx);
13227 }
13228
13229 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13230 if self.buffer.read(cx).is_singleton() {
13231 let mut fold_ranges = Vec::new();
13232 let snapshot = self.buffer.read(cx).snapshot(cx);
13233
13234 for row in 0..snapshot.max_row().0 {
13235 if let Some(foldable_range) = self
13236 .snapshot(window, cx)
13237 .crease_for_buffer_row(MultiBufferRow(row))
13238 {
13239 fold_ranges.push(foldable_range);
13240 }
13241 }
13242
13243 self.fold_creases(fold_ranges, true, window, cx);
13244 } else {
13245 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13246 editor
13247 .update_in(&mut cx, |editor, _, cx| {
13248 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13249 editor.fold_buffer(buffer_id, cx);
13250 }
13251 })
13252 .ok();
13253 });
13254 }
13255 }
13256
13257 pub fn fold_function_bodies(
13258 &mut self,
13259 _: &actions::FoldFunctionBodies,
13260 window: &mut Window,
13261 cx: &mut Context<Self>,
13262 ) {
13263 let snapshot = self.buffer.read(cx).snapshot(cx);
13264
13265 let ranges = snapshot
13266 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13267 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13268 .collect::<Vec<_>>();
13269
13270 let creases = ranges
13271 .into_iter()
13272 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13273 .collect();
13274
13275 self.fold_creases(creases, true, window, cx);
13276 }
13277
13278 pub fn fold_recursive(
13279 &mut self,
13280 _: &actions::FoldRecursive,
13281 window: &mut Window,
13282 cx: &mut Context<Self>,
13283 ) {
13284 let mut to_fold = Vec::new();
13285 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13286 let selections = self.selections.all_adjusted(cx);
13287
13288 for selection in selections {
13289 let range = selection.range().sorted();
13290 let buffer_start_row = range.start.row;
13291
13292 if range.start.row != range.end.row {
13293 let mut found = false;
13294 for row in range.start.row..=range.end.row {
13295 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13296 found = true;
13297 to_fold.push(crease);
13298 }
13299 }
13300 if found {
13301 continue;
13302 }
13303 }
13304
13305 for row in (0..=range.start.row).rev() {
13306 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13307 if crease.range().end.row >= buffer_start_row {
13308 to_fold.push(crease);
13309 } else {
13310 break;
13311 }
13312 }
13313 }
13314 }
13315
13316 self.fold_creases(to_fold, true, window, cx);
13317 }
13318
13319 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13320 let buffer_row = fold_at.buffer_row;
13321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13322
13323 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13324 let autoscroll = self
13325 .selections
13326 .all::<Point>(cx)
13327 .iter()
13328 .any(|selection| crease.range().overlaps(&selection.range()));
13329
13330 self.fold_creases(vec![crease], autoscroll, window, cx);
13331 }
13332 }
13333
13334 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13335 if self.is_singleton(cx) {
13336 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13337 let buffer = &display_map.buffer_snapshot;
13338 let selections = self.selections.all::<Point>(cx);
13339 let ranges = selections
13340 .iter()
13341 .map(|s| {
13342 let range = s.display_range(&display_map).sorted();
13343 let mut start = range.start.to_point(&display_map);
13344 let mut end = range.end.to_point(&display_map);
13345 start.column = 0;
13346 end.column = buffer.line_len(MultiBufferRow(end.row));
13347 start..end
13348 })
13349 .collect::<Vec<_>>();
13350
13351 self.unfold_ranges(&ranges, true, true, cx);
13352 } else {
13353 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13354 let buffer_ids = self
13355 .selections
13356 .disjoint_anchor_ranges()
13357 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13358 .collect::<HashSet<_>>();
13359 for buffer_id in buffer_ids {
13360 self.unfold_buffer(buffer_id, cx);
13361 }
13362 }
13363 }
13364
13365 pub fn unfold_recursive(
13366 &mut self,
13367 _: &UnfoldRecursive,
13368 _window: &mut Window,
13369 cx: &mut Context<Self>,
13370 ) {
13371 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13372 let selections = self.selections.all::<Point>(cx);
13373 let ranges = selections
13374 .iter()
13375 .map(|s| {
13376 let mut range = s.display_range(&display_map).sorted();
13377 *range.start.column_mut() = 0;
13378 *range.end.column_mut() = display_map.line_len(range.end.row());
13379 let start = range.start.to_point(&display_map);
13380 let end = range.end.to_point(&display_map);
13381 start..end
13382 })
13383 .collect::<Vec<_>>();
13384
13385 self.unfold_ranges(&ranges, true, true, cx);
13386 }
13387
13388 pub fn unfold_at(
13389 &mut self,
13390 unfold_at: &UnfoldAt,
13391 _window: &mut Window,
13392 cx: &mut Context<Self>,
13393 ) {
13394 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13395
13396 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13397 ..Point::new(
13398 unfold_at.buffer_row.0,
13399 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13400 );
13401
13402 let autoscroll = self
13403 .selections
13404 .all::<Point>(cx)
13405 .iter()
13406 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13407
13408 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13409 }
13410
13411 pub fn unfold_all(
13412 &mut self,
13413 _: &actions::UnfoldAll,
13414 _window: &mut Window,
13415 cx: &mut Context<Self>,
13416 ) {
13417 if self.buffer.read(cx).is_singleton() {
13418 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13419 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13420 } else {
13421 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13422 editor
13423 .update(&mut cx, |editor, cx| {
13424 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13425 editor.unfold_buffer(buffer_id, cx);
13426 }
13427 })
13428 .ok();
13429 });
13430 }
13431 }
13432
13433 pub fn fold_selected_ranges(
13434 &mut self,
13435 _: &FoldSelectedRanges,
13436 window: &mut Window,
13437 cx: &mut Context<Self>,
13438 ) {
13439 let selections = self.selections.all::<Point>(cx);
13440 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13441 let line_mode = self.selections.line_mode;
13442 let ranges = selections
13443 .into_iter()
13444 .map(|s| {
13445 if line_mode {
13446 let start = Point::new(s.start.row, 0);
13447 let end = Point::new(
13448 s.end.row,
13449 display_map
13450 .buffer_snapshot
13451 .line_len(MultiBufferRow(s.end.row)),
13452 );
13453 Crease::simple(start..end, display_map.fold_placeholder.clone())
13454 } else {
13455 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13456 }
13457 })
13458 .collect::<Vec<_>>();
13459 self.fold_creases(ranges, true, window, cx);
13460 }
13461
13462 pub fn fold_ranges<T: ToOffset + Clone>(
13463 &mut self,
13464 ranges: Vec<Range<T>>,
13465 auto_scroll: bool,
13466 window: &mut Window,
13467 cx: &mut Context<Self>,
13468 ) {
13469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13470 let ranges = ranges
13471 .into_iter()
13472 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13473 .collect::<Vec<_>>();
13474 self.fold_creases(ranges, auto_scroll, window, cx);
13475 }
13476
13477 pub fn fold_creases<T: ToOffset + Clone>(
13478 &mut self,
13479 creases: Vec<Crease<T>>,
13480 auto_scroll: bool,
13481 window: &mut Window,
13482 cx: &mut Context<Self>,
13483 ) {
13484 if creases.is_empty() {
13485 return;
13486 }
13487
13488 let mut buffers_affected = HashSet::default();
13489 let multi_buffer = self.buffer().read(cx);
13490 for crease in &creases {
13491 if let Some((_, buffer, _)) =
13492 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13493 {
13494 buffers_affected.insert(buffer.read(cx).remote_id());
13495 };
13496 }
13497
13498 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13499
13500 if auto_scroll {
13501 self.request_autoscroll(Autoscroll::fit(), cx);
13502 }
13503
13504 cx.notify();
13505
13506 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13507 // Clear diagnostics block when folding a range that contains it.
13508 let snapshot = self.snapshot(window, cx);
13509 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13510 drop(snapshot);
13511 self.active_diagnostics = Some(active_diagnostics);
13512 self.dismiss_diagnostics(cx);
13513 } else {
13514 self.active_diagnostics = Some(active_diagnostics);
13515 }
13516 }
13517
13518 self.scrollbar_marker_state.dirty = true;
13519 }
13520
13521 /// Removes any folds whose ranges intersect any of the given ranges.
13522 pub fn unfold_ranges<T: ToOffset + Clone>(
13523 &mut self,
13524 ranges: &[Range<T>],
13525 inclusive: bool,
13526 auto_scroll: bool,
13527 cx: &mut Context<Self>,
13528 ) {
13529 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13530 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13531 });
13532 }
13533
13534 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13535 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13536 return;
13537 }
13538 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13539 self.display_map.update(cx, |display_map, cx| {
13540 display_map.fold_buffers([buffer_id], cx)
13541 });
13542 cx.emit(EditorEvent::BufferFoldToggled {
13543 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13544 folded: true,
13545 });
13546 cx.notify();
13547 }
13548
13549 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13550 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13551 return;
13552 }
13553 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13554 self.display_map.update(cx, |display_map, cx| {
13555 display_map.unfold_buffers([buffer_id], cx);
13556 });
13557 cx.emit(EditorEvent::BufferFoldToggled {
13558 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13559 folded: false,
13560 });
13561 cx.notify();
13562 }
13563
13564 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13565 self.display_map.read(cx).is_buffer_folded(buffer)
13566 }
13567
13568 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13569 self.display_map.read(cx).folded_buffers()
13570 }
13571
13572 /// Removes any folds with the given ranges.
13573 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13574 &mut self,
13575 ranges: &[Range<T>],
13576 type_id: TypeId,
13577 auto_scroll: bool,
13578 cx: &mut Context<Self>,
13579 ) {
13580 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13581 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13582 });
13583 }
13584
13585 fn remove_folds_with<T: ToOffset + Clone>(
13586 &mut self,
13587 ranges: &[Range<T>],
13588 auto_scroll: bool,
13589 cx: &mut Context<Self>,
13590 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13591 ) {
13592 if ranges.is_empty() {
13593 return;
13594 }
13595
13596 let mut buffers_affected = HashSet::default();
13597 let multi_buffer = self.buffer().read(cx);
13598 for range in ranges {
13599 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13600 buffers_affected.insert(buffer.read(cx).remote_id());
13601 };
13602 }
13603
13604 self.display_map.update(cx, update);
13605
13606 if auto_scroll {
13607 self.request_autoscroll(Autoscroll::fit(), cx);
13608 }
13609
13610 cx.notify();
13611 self.scrollbar_marker_state.dirty = true;
13612 self.active_indent_guides_state.dirty = true;
13613 }
13614
13615 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13616 self.display_map.read(cx).fold_placeholder.clone()
13617 }
13618
13619 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13620 self.buffer.update(cx, |buffer, cx| {
13621 buffer.set_all_diff_hunks_expanded(cx);
13622 });
13623 }
13624
13625 pub fn expand_all_diff_hunks(
13626 &mut self,
13627 _: &ExpandAllDiffHunks,
13628 _window: &mut Window,
13629 cx: &mut Context<Self>,
13630 ) {
13631 self.buffer.update(cx, |buffer, cx| {
13632 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13633 });
13634 }
13635
13636 pub fn toggle_selected_diff_hunks(
13637 &mut self,
13638 _: &ToggleSelectedDiffHunks,
13639 _window: &mut Window,
13640 cx: &mut Context<Self>,
13641 ) {
13642 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13643 self.toggle_diff_hunks_in_ranges(ranges, cx);
13644 }
13645
13646 pub fn diff_hunks_in_ranges<'a>(
13647 &'a self,
13648 ranges: &'a [Range<Anchor>],
13649 buffer: &'a MultiBufferSnapshot,
13650 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13651 ranges.iter().flat_map(move |range| {
13652 let end_excerpt_id = range.end.excerpt_id;
13653 let range = range.to_point(buffer);
13654 let mut peek_end = range.end;
13655 if range.end.row < buffer.max_row().0 {
13656 peek_end = Point::new(range.end.row + 1, 0);
13657 }
13658 buffer
13659 .diff_hunks_in_range(range.start..peek_end)
13660 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13661 })
13662 }
13663
13664 pub fn has_stageable_diff_hunks_in_ranges(
13665 &self,
13666 ranges: &[Range<Anchor>],
13667 snapshot: &MultiBufferSnapshot,
13668 ) -> bool {
13669 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13670 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13671 }
13672
13673 pub fn toggle_staged_selected_diff_hunks(
13674 &mut self,
13675 _: &::git::ToggleStaged,
13676 _: &mut Window,
13677 cx: &mut Context<Self>,
13678 ) {
13679 let snapshot = self.buffer.read(cx).snapshot(cx);
13680 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13681 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13682 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13683 }
13684
13685 pub fn stage_and_next(
13686 &mut self,
13687 _: &::git::StageAndNext,
13688 window: &mut Window,
13689 cx: &mut Context<Self>,
13690 ) {
13691 self.do_stage_or_unstage_and_next(true, window, cx);
13692 }
13693
13694 pub fn unstage_and_next(
13695 &mut self,
13696 _: &::git::UnstageAndNext,
13697 window: &mut Window,
13698 cx: &mut Context<Self>,
13699 ) {
13700 self.do_stage_or_unstage_and_next(false, window, cx);
13701 }
13702
13703 pub fn stage_or_unstage_diff_hunks(
13704 &mut self,
13705 stage: bool,
13706 ranges: Vec<Range<Anchor>>,
13707 cx: &mut Context<Self>,
13708 ) {
13709 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13710 cx.spawn(|this, mut cx| async move {
13711 task.await?;
13712 this.update(&mut cx, |this, cx| {
13713 let snapshot = this.buffer.read(cx).snapshot(cx);
13714 let chunk_by = this
13715 .diff_hunks_in_ranges(&ranges, &snapshot)
13716 .chunk_by(|hunk| hunk.buffer_id);
13717 for (buffer_id, hunks) in &chunk_by {
13718 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13719 }
13720 })
13721 })
13722 .detach_and_log_err(cx);
13723 }
13724
13725 fn save_buffers_for_ranges_if_needed(
13726 &mut self,
13727 ranges: &[Range<Anchor>],
13728 cx: &mut Context<'_, Editor>,
13729 ) -> Task<Result<()>> {
13730 let multibuffer = self.buffer.read(cx);
13731 let snapshot = multibuffer.read(cx);
13732 let buffer_ids: HashSet<_> = ranges
13733 .iter()
13734 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13735 .collect();
13736 drop(snapshot);
13737
13738 let mut buffers = HashSet::default();
13739 for buffer_id in buffer_ids {
13740 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13741 let buffer = buffer_entity.read(cx);
13742 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13743 {
13744 buffers.insert(buffer_entity);
13745 }
13746 }
13747 }
13748
13749 if let Some(project) = &self.project {
13750 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13751 } else {
13752 Task::ready(Ok(()))
13753 }
13754 }
13755
13756 fn do_stage_or_unstage_and_next(
13757 &mut self,
13758 stage: bool,
13759 window: &mut Window,
13760 cx: &mut Context<Self>,
13761 ) {
13762 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13763
13764 if ranges.iter().any(|range| range.start != range.end) {
13765 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13766 return;
13767 }
13768
13769 let snapshot = self.snapshot(window, cx);
13770 let newest_range = self.selections.newest::<Point>(cx).range();
13771
13772 let run_twice = snapshot
13773 .hunks_for_ranges([newest_range])
13774 .first()
13775 .is_some_and(|hunk| {
13776 let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13777 self.hunk_after_position(&snapshot, next_line)
13778 .is_some_and(|other| other.row_range == hunk.row_range)
13779 });
13780
13781 if run_twice {
13782 self.go_to_next_hunk(&GoToHunk, window, cx);
13783 }
13784 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13785 self.go_to_next_hunk(&GoToHunk, window, cx);
13786 }
13787
13788 fn do_stage_or_unstage(
13789 &self,
13790 stage: bool,
13791 buffer_id: BufferId,
13792 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13793 cx: &mut App,
13794 ) -> Option<()> {
13795 let project = self.project.as_ref()?;
13796 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13797 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13798 let buffer_snapshot = buffer.read(cx).snapshot();
13799 let file_exists = buffer_snapshot
13800 .file()
13801 .is_some_and(|file| file.disk_state().exists());
13802 diff.update(cx, |diff, cx| {
13803 diff.stage_or_unstage_hunks(
13804 stage,
13805 &hunks
13806 .map(|hunk| buffer_diff::DiffHunk {
13807 buffer_range: hunk.buffer_range,
13808 diff_base_byte_range: hunk.diff_base_byte_range,
13809 secondary_status: hunk.secondary_status,
13810 range: Point::zero()..Point::zero(), // unused
13811 })
13812 .collect::<Vec<_>>(),
13813 &buffer_snapshot,
13814 file_exists,
13815 cx,
13816 )
13817 });
13818 None
13819 }
13820
13821 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13822 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13823 self.buffer
13824 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13825 }
13826
13827 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13828 self.buffer.update(cx, |buffer, cx| {
13829 let ranges = vec![Anchor::min()..Anchor::max()];
13830 if !buffer.all_diff_hunks_expanded()
13831 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13832 {
13833 buffer.collapse_diff_hunks(ranges, cx);
13834 true
13835 } else {
13836 false
13837 }
13838 })
13839 }
13840
13841 fn toggle_diff_hunks_in_ranges(
13842 &mut self,
13843 ranges: Vec<Range<Anchor>>,
13844 cx: &mut Context<'_, Editor>,
13845 ) {
13846 self.buffer.update(cx, |buffer, cx| {
13847 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13848 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13849 })
13850 }
13851
13852 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13853 self.buffer.update(cx, |buffer, cx| {
13854 let snapshot = buffer.snapshot(cx);
13855 let excerpt_id = range.end.excerpt_id;
13856 let point_range = range.to_point(&snapshot);
13857 let expand = !buffer.single_hunk_is_expanded(range, cx);
13858 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13859 })
13860 }
13861
13862 pub(crate) fn apply_all_diff_hunks(
13863 &mut self,
13864 _: &ApplyAllDiffHunks,
13865 window: &mut Window,
13866 cx: &mut Context<Self>,
13867 ) {
13868 let buffers = self.buffer.read(cx).all_buffers();
13869 for branch_buffer in buffers {
13870 branch_buffer.update(cx, |branch_buffer, cx| {
13871 branch_buffer.merge_into_base(Vec::new(), cx);
13872 });
13873 }
13874
13875 if let Some(project) = self.project.clone() {
13876 self.save(true, project, window, cx).detach_and_log_err(cx);
13877 }
13878 }
13879
13880 pub(crate) fn apply_selected_diff_hunks(
13881 &mut self,
13882 _: &ApplyDiffHunk,
13883 window: &mut Window,
13884 cx: &mut Context<Self>,
13885 ) {
13886 let snapshot = self.snapshot(window, cx);
13887 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13888 let mut ranges_by_buffer = HashMap::default();
13889 self.transact(window, cx, |editor, _window, cx| {
13890 for hunk in hunks {
13891 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13892 ranges_by_buffer
13893 .entry(buffer.clone())
13894 .or_insert_with(Vec::new)
13895 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13896 }
13897 }
13898
13899 for (buffer, ranges) in ranges_by_buffer {
13900 buffer.update(cx, |buffer, cx| {
13901 buffer.merge_into_base(ranges, cx);
13902 });
13903 }
13904 });
13905
13906 if let Some(project) = self.project.clone() {
13907 self.save(true, project, window, cx).detach_and_log_err(cx);
13908 }
13909 }
13910
13911 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13912 if hovered != self.gutter_hovered {
13913 self.gutter_hovered = hovered;
13914 cx.notify();
13915 }
13916 }
13917
13918 pub fn insert_blocks(
13919 &mut self,
13920 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13921 autoscroll: Option<Autoscroll>,
13922 cx: &mut Context<Self>,
13923 ) -> Vec<CustomBlockId> {
13924 let blocks = self
13925 .display_map
13926 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
13927 if let Some(autoscroll) = autoscroll {
13928 self.request_autoscroll(autoscroll, cx);
13929 }
13930 cx.notify();
13931 blocks
13932 }
13933
13934 pub fn resize_blocks(
13935 &mut self,
13936 heights: HashMap<CustomBlockId, u32>,
13937 autoscroll: Option<Autoscroll>,
13938 cx: &mut Context<Self>,
13939 ) {
13940 self.display_map
13941 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
13942 if let Some(autoscroll) = autoscroll {
13943 self.request_autoscroll(autoscroll, cx);
13944 }
13945 cx.notify();
13946 }
13947
13948 pub fn replace_blocks(
13949 &mut self,
13950 renderers: HashMap<CustomBlockId, RenderBlock>,
13951 autoscroll: Option<Autoscroll>,
13952 cx: &mut Context<Self>,
13953 ) {
13954 self.display_map
13955 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
13956 if let Some(autoscroll) = autoscroll {
13957 self.request_autoscroll(autoscroll, cx);
13958 }
13959 cx.notify();
13960 }
13961
13962 pub fn remove_blocks(
13963 &mut self,
13964 block_ids: HashSet<CustomBlockId>,
13965 autoscroll: Option<Autoscroll>,
13966 cx: &mut Context<Self>,
13967 ) {
13968 self.display_map.update(cx, |display_map, cx| {
13969 display_map.remove_blocks(block_ids, cx)
13970 });
13971 if let Some(autoscroll) = autoscroll {
13972 self.request_autoscroll(autoscroll, cx);
13973 }
13974 cx.notify();
13975 }
13976
13977 pub fn row_for_block(
13978 &self,
13979 block_id: CustomBlockId,
13980 cx: &mut Context<Self>,
13981 ) -> Option<DisplayRow> {
13982 self.display_map
13983 .update(cx, |map, cx| map.row_for_block(block_id, cx))
13984 }
13985
13986 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
13987 self.focused_block = Some(focused_block);
13988 }
13989
13990 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
13991 self.focused_block.take()
13992 }
13993
13994 pub fn insert_creases(
13995 &mut self,
13996 creases: impl IntoIterator<Item = Crease<Anchor>>,
13997 cx: &mut Context<Self>,
13998 ) -> Vec<CreaseId> {
13999 self.display_map
14000 .update(cx, |map, cx| map.insert_creases(creases, cx))
14001 }
14002
14003 pub fn remove_creases(
14004 &mut self,
14005 ids: impl IntoIterator<Item = CreaseId>,
14006 cx: &mut Context<Self>,
14007 ) {
14008 self.display_map
14009 .update(cx, |map, cx| map.remove_creases(ids, cx));
14010 }
14011
14012 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14013 self.display_map
14014 .update(cx, |map, cx| map.snapshot(cx))
14015 .longest_row()
14016 }
14017
14018 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14019 self.display_map
14020 .update(cx, |map, cx| map.snapshot(cx))
14021 .max_point()
14022 }
14023
14024 pub fn text(&self, cx: &App) -> String {
14025 self.buffer.read(cx).read(cx).text()
14026 }
14027
14028 pub fn is_empty(&self, cx: &App) -> bool {
14029 self.buffer.read(cx).read(cx).is_empty()
14030 }
14031
14032 pub fn text_option(&self, cx: &App) -> Option<String> {
14033 let text = self.text(cx);
14034 let text = text.trim();
14035
14036 if text.is_empty() {
14037 return None;
14038 }
14039
14040 Some(text.to_string())
14041 }
14042
14043 pub fn set_text(
14044 &mut self,
14045 text: impl Into<Arc<str>>,
14046 window: &mut Window,
14047 cx: &mut Context<Self>,
14048 ) {
14049 self.transact(window, cx, |this, _, cx| {
14050 this.buffer
14051 .read(cx)
14052 .as_singleton()
14053 .expect("you can only call set_text on editors for singleton buffers")
14054 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14055 });
14056 }
14057
14058 pub fn display_text(&self, cx: &mut App) -> String {
14059 self.display_map
14060 .update(cx, |map, cx| map.snapshot(cx))
14061 .text()
14062 }
14063
14064 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14065 let mut wrap_guides = smallvec::smallvec![];
14066
14067 if self.show_wrap_guides == Some(false) {
14068 return wrap_guides;
14069 }
14070
14071 let settings = self.buffer.read(cx).language_settings(cx);
14072 if settings.show_wrap_guides {
14073 match self.soft_wrap_mode(cx) {
14074 SoftWrap::Column(soft_wrap) => {
14075 wrap_guides.push((soft_wrap as usize, true));
14076 }
14077 SoftWrap::Bounded(soft_wrap) => {
14078 wrap_guides.push((soft_wrap as usize, true));
14079 }
14080 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14081 }
14082 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14083 }
14084
14085 wrap_guides
14086 }
14087
14088 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14089 let settings = self.buffer.read(cx).language_settings(cx);
14090 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14091 match mode {
14092 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14093 SoftWrap::None
14094 }
14095 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14096 language_settings::SoftWrap::PreferredLineLength => {
14097 SoftWrap::Column(settings.preferred_line_length)
14098 }
14099 language_settings::SoftWrap::Bounded => {
14100 SoftWrap::Bounded(settings.preferred_line_length)
14101 }
14102 }
14103 }
14104
14105 pub fn set_soft_wrap_mode(
14106 &mut self,
14107 mode: language_settings::SoftWrap,
14108
14109 cx: &mut Context<Self>,
14110 ) {
14111 self.soft_wrap_mode_override = Some(mode);
14112 cx.notify();
14113 }
14114
14115 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14116 self.text_style_refinement = Some(style);
14117 }
14118
14119 /// called by the Element so we know what style we were most recently rendered with.
14120 pub(crate) fn set_style(
14121 &mut self,
14122 style: EditorStyle,
14123 window: &mut Window,
14124 cx: &mut Context<Self>,
14125 ) {
14126 let rem_size = window.rem_size();
14127 self.display_map.update(cx, |map, cx| {
14128 map.set_font(
14129 style.text.font(),
14130 style.text.font_size.to_pixels(rem_size),
14131 cx,
14132 )
14133 });
14134 self.style = Some(style);
14135 }
14136
14137 pub fn style(&self) -> Option<&EditorStyle> {
14138 self.style.as_ref()
14139 }
14140
14141 // Called by the element. This method is not designed to be called outside of the editor
14142 // element's layout code because it does not notify when rewrapping is computed synchronously.
14143 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14144 self.display_map
14145 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14146 }
14147
14148 pub fn set_soft_wrap(&mut self) {
14149 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14150 }
14151
14152 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14153 if self.soft_wrap_mode_override.is_some() {
14154 self.soft_wrap_mode_override.take();
14155 } else {
14156 let soft_wrap = match self.soft_wrap_mode(cx) {
14157 SoftWrap::GitDiff => return,
14158 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14159 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14160 language_settings::SoftWrap::None
14161 }
14162 };
14163 self.soft_wrap_mode_override = Some(soft_wrap);
14164 }
14165 cx.notify();
14166 }
14167
14168 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14169 let Some(workspace) = self.workspace() else {
14170 return;
14171 };
14172 let fs = workspace.read(cx).app_state().fs.clone();
14173 let current_show = TabBarSettings::get_global(cx).show;
14174 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14175 setting.show = Some(!current_show);
14176 });
14177 }
14178
14179 pub fn toggle_indent_guides(
14180 &mut self,
14181 _: &ToggleIndentGuides,
14182 _: &mut Window,
14183 cx: &mut Context<Self>,
14184 ) {
14185 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14186 self.buffer
14187 .read(cx)
14188 .language_settings(cx)
14189 .indent_guides
14190 .enabled
14191 });
14192 self.show_indent_guides = Some(!currently_enabled);
14193 cx.notify();
14194 }
14195
14196 fn should_show_indent_guides(&self) -> Option<bool> {
14197 self.show_indent_guides
14198 }
14199
14200 pub fn toggle_line_numbers(
14201 &mut self,
14202 _: &ToggleLineNumbers,
14203 _: &mut Window,
14204 cx: &mut Context<Self>,
14205 ) {
14206 let mut editor_settings = EditorSettings::get_global(cx).clone();
14207 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14208 EditorSettings::override_global(editor_settings, cx);
14209 }
14210
14211 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14212 self.use_relative_line_numbers
14213 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14214 }
14215
14216 pub fn toggle_relative_line_numbers(
14217 &mut self,
14218 _: &ToggleRelativeLineNumbers,
14219 _: &mut Window,
14220 cx: &mut Context<Self>,
14221 ) {
14222 let is_relative = self.should_use_relative_line_numbers(cx);
14223 self.set_relative_line_number(Some(!is_relative), cx)
14224 }
14225
14226 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14227 self.use_relative_line_numbers = is_relative;
14228 cx.notify();
14229 }
14230
14231 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14232 self.show_gutter = show_gutter;
14233 cx.notify();
14234 }
14235
14236 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14237 self.show_scrollbars = show_scrollbars;
14238 cx.notify();
14239 }
14240
14241 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14242 self.show_line_numbers = Some(show_line_numbers);
14243 cx.notify();
14244 }
14245
14246 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14247 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14248 cx.notify();
14249 }
14250
14251 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14252 self.show_code_actions = Some(show_code_actions);
14253 cx.notify();
14254 }
14255
14256 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14257 self.show_runnables = Some(show_runnables);
14258 cx.notify();
14259 }
14260
14261 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14262 if self.display_map.read(cx).masked != masked {
14263 self.display_map.update(cx, |map, _| map.masked = masked);
14264 }
14265 cx.notify()
14266 }
14267
14268 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14269 self.show_wrap_guides = Some(show_wrap_guides);
14270 cx.notify();
14271 }
14272
14273 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14274 self.show_indent_guides = Some(show_indent_guides);
14275 cx.notify();
14276 }
14277
14278 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14279 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14280 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14281 if let Some(dir) = file.abs_path(cx).parent() {
14282 return Some(dir.to_owned());
14283 }
14284 }
14285
14286 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14287 return Some(project_path.path.to_path_buf());
14288 }
14289 }
14290
14291 None
14292 }
14293
14294 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14295 self.active_excerpt(cx)?
14296 .1
14297 .read(cx)
14298 .file()
14299 .and_then(|f| f.as_local())
14300 }
14301
14302 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14303 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14304 let buffer = buffer.read(cx);
14305 if let Some(project_path) = buffer.project_path(cx) {
14306 let project = self.project.as_ref()?.read(cx);
14307 project.absolute_path(&project_path, cx)
14308 } else {
14309 buffer
14310 .file()
14311 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14312 }
14313 })
14314 }
14315
14316 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14317 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14318 let project_path = buffer.read(cx).project_path(cx)?;
14319 let project = self.project.as_ref()?.read(cx);
14320 let entry = project.entry_for_path(&project_path, cx)?;
14321 let path = entry.path.to_path_buf();
14322 Some(path)
14323 })
14324 }
14325
14326 pub fn reveal_in_finder(
14327 &mut self,
14328 _: &RevealInFileManager,
14329 _window: &mut Window,
14330 cx: &mut Context<Self>,
14331 ) {
14332 if let Some(target) = self.target_file(cx) {
14333 cx.reveal_path(&target.abs_path(cx));
14334 }
14335 }
14336
14337 pub fn copy_path(
14338 &mut self,
14339 _: &zed_actions::workspace::CopyPath,
14340 _window: &mut Window,
14341 cx: &mut Context<Self>,
14342 ) {
14343 if let Some(path) = self.target_file_abs_path(cx) {
14344 if let Some(path) = path.to_str() {
14345 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14346 }
14347 }
14348 }
14349
14350 pub fn copy_relative_path(
14351 &mut self,
14352 _: &zed_actions::workspace::CopyRelativePath,
14353 _window: &mut Window,
14354 cx: &mut Context<Self>,
14355 ) {
14356 if let Some(path) = self.target_file_path(cx) {
14357 if let Some(path) = path.to_str() {
14358 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14359 }
14360 }
14361 }
14362
14363 pub fn copy_file_name_without_extension(
14364 &mut self,
14365 _: &CopyFileNameWithoutExtension,
14366 _: &mut Window,
14367 cx: &mut Context<Self>,
14368 ) {
14369 if let Some(file) = self.target_file(cx) {
14370 if let Some(file_stem) = file.path().file_stem() {
14371 if let Some(name) = file_stem.to_str() {
14372 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14373 }
14374 }
14375 }
14376 }
14377
14378 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14379 if let Some(file) = self.target_file(cx) {
14380 if let Some(file_name) = file.path().file_name() {
14381 if let Some(name) = file_name.to_str() {
14382 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14383 }
14384 }
14385 }
14386 }
14387
14388 pub fn toggle_git_blame(
14389 &mut self,
14390 _: &ToggleGitBlame,
14391 window: &mut Window,
14392 cx: &mut Context<Self>,
14393 ) {
14394 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14395
14396 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14397 self.start_git_blame(true, window, cx);
14398 }
14399
14400 cx.notify();
14401 }
14402
14403 pub fn toggle_git_blame_inline(
14404 &mut self,
14405 _: &ToggleGitBlameInline,
14406 window: &mut Window,
14407 cx: &mut Context<Self>,
14408 ) {
14409 self.toggle_git_blame_inline_internal(true, window, cx);
14410 cx.notify();
14411 }
14412
14413 pub fn git_blame_inline_enabled(&self) -> bool {
14414 self.git_blame_inline_enabled
14415 }
14416
14417 pub fn toggle_selection_menu(
14418 &mut self,
14419 _: &ToggleSelectionMenu,
14420 _: &mut Window,
14421 cx: &mut Context<Self>,
14422 ) {
14423 self.show_selection_menu = self
14424 .show_selection_menu
14425 .map(|show_selections_menu| !show_selections_menu)
14426 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14427
14428 cx.notify();
14429 }
14430
14431 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14432 self.show_selection_menu
14433 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14434 }
14435
14436 fn start_git_blame(
14437 &mut self,
14438 user_triggered: bool,
14439 window: &mut Window,
14440 cx: &mut Context<Self>,
14441 ) {
14442 if let Some(project) = self.project.as_ref() {
14443 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14444 return;
14445 };
14446
14447 if buffer.read(cx).file().is_none() {
14448 return;
14449 }
14450
14451 let focused = self.focus_handle(cx).contains_focused(window, cx);
14452
14453 let project = project.clone();
14454 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14455 self.blame_subscription =
14456 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14457 self.blame = Some(blame);
14458 }
14459 }
14460
14461 fn toggle_git_blame_inline_internal(
14462 &mut self,
14463 user_triggered: bool,
14464 window: &mut Window,
14465 cx: &mut Context<Self>,
14466 ) {
14467 if self.git_blame_inline_enabled {
14468 self.git_blame_inline_enabled = false;
14469 self.show_git_blame_inline = false;
14470 self.show_git_blame_inline_delay_task.take();
14471 } else {
14472 self.git_blame_inline_enabled = true;
14473 self.start_git_blame_inline(user_triggered, window, cx);
14474 }
14475
14476 cx.notify();
14477 }
14478
14479 fn start_git_blame_inline(
14480 &mut self,
14481 user_triggered: bool,
14482 window: &mut Window,
14483 cx: &mut Context<Self>,
14484 ) {
14485 self.start_git_blame(user_triggered, window, cx);
14486
14487 if ProjectSettings::get_global(cx)
14488 .git
14489 .inline_blame_delay()
14490 .is_some()
14491 {
14492 self.start_inline_blame_timer(window, cx);
14493 } else {
14494 self.show_git_blame_inline = true
14495 }
14496 }
14497
14498 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14499 self.blame.as_ref()
14500 }
14501
14502 pub fn show_git_blame_gutter(&self) -> bool {
14503 self.show_git_blame_gutter
14504 }
14505
14506 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14507 self.show_git_blame_gutter && self.has_blame_entries(cx)
14508 }
14509
14510 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14511 self.show_git_blame_inline
14512 && (self.focus_handle.is_focused(window)
14513 || self
14514 .git_blame_inline_tooltip
14515 .as_ref()
14516 .and_then(|t| t.upgrade())
14517 .is_some())
14518 && !self.newest_selection_head_on_empty_line(cx)
14519 && self.has_blame_entries(cx)
14520 }
14521
14522 fn has_blame_entries(&self, cx: &App) -> bool {
14523 self.blame()
14524 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14525 }
14526
14527 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14528 let cursor_anchor = self.selections.newest_anchor().head();
14529
14530 let snapshot = self.buffer.read(cx).snapshot(cx);
14531 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14532
14533 snapshot.line_len(buffer_row) == 0
14534 }
14535
14536 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14537 let buffer_and_selection = maybe!({
14538 let selection = self.selections.newest::<Point>(cx);
14539 let selection_range = selection.range();
14540
14541 let multi_buffer = self.buffer().read(cx);
14542 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14543 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14544
14545 let (buffer, range, _) = if selection.reversed {
14546 buffer_ranges.first()
14547 } else {
14548 buffer_ranges.last()
14549 }?;
14550
14551 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14552 ..text::ToPoint::to_point(&range.end, &buffer).row;
14553 Some((
14554 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14555 selection,
14556 ))
14557 });
14558
14559 let Some((buffer, selection)) = buffer_and_selection else {
14560 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14561 };
14562
14563 let Some(project) = self.project.as_ref() else {
14564 return Task::ready(Err(anyhow!("editor does not have project")));
14565 };
14566
14567 project.update(cx, |project, cx| {
14568 project.get_permalink_to_line(&buffer, selection, cx)
14569 })
14570 }
14571
14572 pub fn copy_permalink_to_line(
14573 &mut self,
14574 _: &CopyPermalinkToLine,
14575 window: &mut Window,
14576 cx: &mut Context<Self>,
14577 ) {
14578 let permalink_task = self.get_permalink_to_line(cx);
14579 let workspace = self.workspace();
14580
14581 cx.spawn_in(window, |_, mut cx| async move {
14582 match permalink_task.await {
14583 Ok(permalink) => {
14584 cx.update(|_, cx| {
14585 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14586 })
14587 .ok();
14588 }
14589 Err(err) => {
14590 let message = format!("Failed to copy permalink: {err}");
14591
14592 Err::<(), anyhow::Error>(err).log_err();
14593
14594 if let Some(workspace) = workspace {
14595 workspace
14596 .update_in(&mut cx, |workspace, _, cx| {
14597 struct CopyPermalinkToLine;
14598
14599 workspace.show_toast(
14600 Toast::new(
14601 NotificationId::unique::<CopyPermalinkToLine>(),
14602 message,
14603 ),
14604 cx,
14605 )
14606 })
14607 .ok();
14608 }
14609 }
14610 }
14611 })
14612 .detach();
14613 }
14614
14615 pub fn copy_file_location(
14616 &mut self,
14617 _: &CopyFileLocation,
14618 _: &mut Window,
14619 cx: &mut Context<Self>,
14620 ) {
14621 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14622 if let Some(file) = self.target_file(cx) {
14623 if let Some(path) = file.path().to_str() {
14624 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14625 }
14626 }
14627 }
14628
14629 pub fn open_permalink_to_line(
14630 &mut self,
14631 _: &OpenPermalinkToLine,
14632 window: &mut Window,
14633 cx: &mut Context<Self>,
14634 ) {
14635 let permalink_task = self.get_permalink_to_line(cx);
14636 let workspace = self.workspace();
14637
14638 cx.spawn_in(window, |_, mut cx| async move {
14639 match permalink_task.await {
14640 Ok(permalink) => {
14641 cx.update(|_, cx| {
14642 cx.open_url(permalink.as_ref());
14643 })
14644 .ok();
14645 }
14646 Err(err) => {
14647 let message = format!("Failed to open permalink: {err}");
14648
14649 Err::<(), anyhow::Error>(err).log_err();
14650
14651 if let Some(workspace) = workspace {
14652 workspace
14653 .update(&mut cx, |workspace, cx| {
14654 struct OpenPermalinkToLine;
14655
14656 workspace.show_toast(
14657 Toast::new(
14658 NotificationId::unique::<OpenPermalinkToLine>(),
14659 message,
14660 ),
14661 cx,
14662 )
14663 })
14664 .ok();
14665 }
14666 }
14667 }
14668 })
14669 .detach();
14670 }
14671
14672 pub fn insert_uuid_v4(
14673 &mut self,
14674 _: &InsertUuidV4,
14675 window: &mut Window,
14676 cx: &mut Context<Self>,
14677 ) {
14678 self.insert_uuid(UuidVersion::V4, window, cx);
14679 }
14680
14681 pub fn insert_uuid_v7(
14682 &mut self,
14683 _: &InsertUuidV7,
14684 window: &mut Window,
14685 cx: &mut Context<Self>,
14686 ) {
14687 self.insert_uuid(UuidVersion::V7, window, cx);
14688 }
14689
14690 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14691 self.transact(window, cx, |this, window, cx| {
14692 let edits = this
14693 .selections
14694 .all::<Point>(cx)
14695 .into_iter()
14696 .map(|selection| {
14697 let uuid = match version {
14698 UuidVersion::V4 => uuid::Uuid::new_v4(),
14699 UuidVersion::V7 => uuid::Uuid::now_v7(),
14700 };
14701
14702 (selection.range(), uuid.to_string())
14703 });
14704 this.edit(edits, cx);
14705 this.refresh_inline_completion(true, false, window, cx);
14706 });
14707 }
14708
14709 pub fn open_selections_in_multibuffer(
14710 &mut self,
14711 _: &OpenSelectionsInMultibuffer,
14712 window: &mut Window,
14713 cx: &mut Context<Self>,
14714 ) {
14715 let multibuffer = self.buffer.read(cx);
14716
14717 let Some(buffer) = multibuffer.as_singleton() else {
14718 return;
14719 };
14720
14721 let Some(workspace) = self.workspace() else {
14722 return;
14723 };
14724
14725 let locations = self
14726 .selections
14727 .disjoint_anchors()
14728 .iter()
14729 .map(|range| Location {
14730 buffer: buffer.clone(),
14731 range: range.start.text_anchor..range.end.text_anchor,
14732 })
14733 .collect::<Vec<_>>();
14734
14735 let title = multibuffer.title(cx).to_string();
14736
14737 cx.spawn_in(window, |_, mut cx| async move {
14738 workspace.update_in(&mut cx, |workspace, window, cx| {
14739 Self::open_locations_in_multibuffer(
14740 workspace,
14741 locations,
14742 format!("Selections for '{title}'"),
14743 false,
14744 MultibufferSelectionMode::All,
14745 window,
14746 cx,
14747 );
14748 })
14749 })
14750 .detach();
14751 }
14752
14753 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14754 /// last highlight added will be used.
14755 ///
14756 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14757 pub fn highlight_rows<T: 'static>(
14758 &mut self,
14759 range: Range<Anchor>,
14760 color: Hsla,
14761 should_autoscroll: bool,
14762 cx: &mut Context<Self>,
14763 ) {
14764 let snapshot = self.buffer().read(cx).snapshot(cx);
14765 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14766 let ix = row_highlights.binary_search_by(|highlight| {
14767 Ordering::Equal
14768 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14769 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14770 });
14771
14772 if let Err(mut ix) = ix {
14773 let index = post_inc(&mut self.highlight_order);
14774
14775 // If this range intersects with the preceding highlight, then merge it with
14776 // the preceding highlight. Otherwise insert a new highlight.
14777 let mut merged = false;
14778 if ix > 0 {
14779 let prev_highlight = &mut row_highlights[ix - 1];
14780 if prev_highlight
14781 .range
14782 .end
14783 .cmp(&range.start, &snapshot)
14784 .is_ge()
14785 {
14786 ix -= 1;
14787 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14788 prev_highlight.range.end = range.end;
14789 }
14790 merged = true;
14791 prev_highlight.index = index;
14792 prev_highlight.color = color;
14793 prev_highlight.should_autoscroll = should_autoscroll;
14794 }
14795 }
14796
14797 if !merged {
14798 row_highlights.insert(
14799 ix,
14800 RowHighlight {
14801 range: range.clone(),
14802 index,
14803 color,
14804 should_autoscroll,
14805 },
14806 );
14807 }
14808
14809 // If any of the following highlights intersect with this one, merge them.
14810 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14811 let highlight = &row_highlights[ix];
14812 if next_highlight
14813 .range
14814 .start
14815 .cmp(&highlight.range.end, &snapshot)
14816 .is_le()
14817 {
14818 if next_highlight
14819 .range
14820 .end
14821 .cmp(&highlight.range.end, &snapshot)
14822 .is_gt()
14823 {
14824 row_highlights[ix].range.end = next_highlight.range.end;
14825 }
14826 row_highlights.remove(ix + 1);
14827 } else {
14828 break;
14829 }
14830 }
14831 }
14832 }
14833
14834 /// Remove any highlighted row ranges of the given type that intersect the
14835 /// given ranges.
14836 pub fn remove_highlighted_rows<T: 'static>(
14837 &mut self,
14838 ranges_to_remove: Vec<Range<Anchor>>,
14839 cx: &mut Context<Self>,
14840 ) {
14841 let snapshot = self.buffer().read(cx).snapshot(cx);
14842 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14843 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14844 row_highlights.retain(|highlight| {
14845 while let Some(range_to_remove) = ranges_to_remove.peek() {
14846 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14847 Ordering::Less | Ordering::Equal => {
14848 ranges_to_remove.next();
14849 }
14850 Ordering::Greater => {
14851 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14852 Ordering::Less | Ordering::Equal => {
14853 return false;
14854 }
14855 Ordering::Greater => break,
14856 }
14857 }
14858 }
14859 }
14860
14861 true
14862 })
14863 }
14864
14865 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14866 pub fn clear_row_highlights<T: 'static>(&mut self) {
14867 self.highlighted_rows.remove(&TypeId::of::<T>());
14868 }
14869
14870 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14871 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14872 self.highlighted_rows
14873 .get(&TypeId::of::<T>())
14874 .map_or(&[] as &[_], |vec| vec.as_slice())
14875 .iter()
14876 .map(|highlight| (highlight.range.clone(), highlight.color))
14877 }
14878
14879 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14880 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14881 /// Allows to ignore certain kinds of highlights.
14882 pub fn highlighted_display_rows(
14883 &self,
14884 window: &mut Window,
14885 cx: &mut App,
14886 ) -> BTreeMap<DisplayRow, LineHighlight> {
14887 let snapshot = self.snapshot(window, cx);
14888 let mut used_highlight_orders = HashMap::default();
14889 self.highlighted_rows
14890 .iter()
14891 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14892 .fold(
14893 BTreeMap::<DisplayRow, LineHighlight>::new(),
14894 |mut unique_rows, highlight| {
14895 let start = highlight.range.start.to_display_point(&snapshot);
14896 let end = highlight.range.end.to_display_point(&snapshot);
14897 let start_row = start.row().0;
14898 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14899 && end.column() == 0
14900 {
14901 end.row().0.saturating_sub(1)
14902 } else {
14903 end.row().0
14904 };
14905 for row in start_row..=end_row {
14906 let used_index =
14907 used_highlight_orders.entry(row).or_insert(highlight.index);
14908 if highlight.index >= *used_index {
14909 *used_index = highlight.index;
14910 unique_rows.insert(DisplayRow(row), highlight.color.into());
14911 }
14912 }
14913 unique_rows
14914 },
14915 )
14916 }
14917
14918 pub fn highlighted_display_row_for_autoscroll(
14919 &self,
14920 snapshot: &DisplaySnapshot,
14921 ) -> Option<DisplayRow> {
14922 self.highlighted_rows
14923 .values()
14924 .flat_map(|highlighted_rows| highlighted_rows.iter())
14925 .filter_map(|highlight| {
14926 if highlight.should_autoscroll {
14927 Some(highlight.range.start.to_display_point(snapshot).row())
14928 } else {
14929 None
14930 }
14931 })
14932 .min()
14933 }
14934
14935 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
14936 self.highlight_background::<SearchWithinRange>(
14937 ranges,
14938 |colors| colors.editor_document_highlight_read_background,
14939 cx,
14940 )
14941 }
14942
14943 pub fn set_breadcrumb_header(&mut self, new_header: String) {
14944 self.breadcrumb_header = Some(new_header);
14945 }
14946
14947 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
14948 self.clear_background_highlights::<SearchWithinRange>(cx);
14949 }
14950
14951 pub fn highlight_background<T: 'static>(
14952 &mut self,
14953 ranges: &[Range<Anchor>],
14954 color_fetcher: fn(&ThemeColors) -> Hsla,
14955 cx: &mut Context<Self>,
14956 ) {
14957 self.background_highlights
14958 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14959 self.scrollbar_marker_state.dirty = true;
14960 cx.notify();
14961 }
14962
14963 pub fn clear_background_highlights<T: 'static>(
14964 &mut self,
14965 cx: &mut Context<Self>,
14966 ) -> Option<BackgroundHighlight> {
14967 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
14968 if !text_highlights.1.is_empty() {
14969 self.scrollbar_marker_state.dirty = true;
14970 cx.notify();
14971 }
14972 Some(text_highlights)
14973 }
14974
14975 pub fn highlight_gutter<T: 'static>(
14976 &mut self,
14977 ranges: &[Range<Anchor>],
14978 color_fetcher: fn(&App) -> Hsla,
14979 cx: &mut Context<Self>,
14980 ) {
14981 self.gutter_highlights
14982 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
14983 cx.notify();
14984 }
14985
14986 pub fn clear_gutter_highlights<T: 'static>(
14987 &mut self,
14988 cx: &mut Context<Self>,
14989 ) -> Option<GutterHighlight> {
14990 cx.notify();
14991 self.gutter_highlights.remove(&TypeId::of::<T>())
14992 }
14993
14994 #[cfg(feature = "test-support")]
14995 pub fn all_text_background_highlights(
14996 &self,
14997 window: &mut Window,
14998 cx: &mut Context<Self>,
14999 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15000 let snapshot = self.snapshot(window, cx);
15001 let buffer = &snapshot.buffer_snapshot;
15002 let start = buffer.anchor_before(0);
15003 let end = buffer.anchor_after(buffer.len());
15004 let theme = cx.theme().colors();
15005 self.background_highlights_in_range(start..end, &snapshot, theme)
15006 }
15007
15008 #[cfg(feature = "test-support")]
15009 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15010 let snapshot = self.buffer().read(cx).snapshot(cx);
15011
15012 let highlights = self
15013 .background_highlights
15014 .get(&TypeId::of::<items::BufferSearchHighlights>());
15015
15016 if let Some((_color, ranges)) = highlights {
15017 ranges
15018 .iter()
15019 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15020 .collect_vec()
15021 } else {
15022 vec![]
15023 }
15024 }
15025
15026 fn document_highlights_for_position<'a>(
15027 &'a self,
15028 position: Anchor,
15029 buffer: &'a MultiBufferSnapshot,
15030 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15031 let read_highlights = self
15032 .background_highlights
15033 .get(&TypeId::of::<DocumentHighlightRead>())
15034 .map(|h| &h.1);
15035 let write_highlights = self
15036 .background_highlights
15037 .get(&TypeId::of::<DocumentHighlightWrite>())
15038 .map(|h| &h.1);
15039 let left_position = position.bias_left(buffer);
15040 let right_position = position.bias_right(buffer);
15041 read_highlights
15042 .into_iter()
15043 .chain(write_highlights)
15044 .flat_map(move |ranges| {
15045 let start_ix = match ranges.binary_search_by(|probe| {
15046 let cmp = probe.end.cmp(&left_position, buffer);
15047 if cmp.is_ge() {
15048 Ordering::Greater
15049 } else {
15050 Ordering::Less
15051 }
15052 }) {
15053 Ok(i) | Err(i) => i,
15054 };
15055
15056 ranges[start_ix..]
15057 .iter()
15058 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15059 })
15060 }
15061
15062 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15063 self.background_highlights
15064 .get(&TypeId::of::<T>())
15065 .map_or(false, |(_, highlights)| !highlights.is_empty())
15066 }
15067
15068 pub fn background_highlights_in_range(
15069 &self,
15070 search_range: Range<Anchor>,
15071 display_snapshot: &DisplaySnapshot,
15072 theme: &ThemeColors,
15073 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15074 let mut results = Vec::new();
15075 for (color_fetcher, ranges) in self.background_highlights.values() {
15076 let color = color_fetcher(theme);
15077 let start_ix = match ranges.binary_search_by(|probe| {
15078 let cmp = probe
15079 .end
15080 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15081 if cmp.is_gt() {
15082 Ordering::Greater
15083 } else {
15084 Ordering::Less
15085 }
15086 }) {
15087 Ok(i) | Err(i) => i,
15088 };
15089 for range in &ranges[start_ix..] {
15090 if range
15091 .start
15092 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15093 .is_ge()
15094 {
15095 break;
15096 }
15097
15098 let start = range.start.to_display_point(display_snapshot);
15099 let end = range.end.to_display_point(display_snapshot);
15100 results.push((start..end, color))
15101 }
15102 }
15103 results
15104 }
15105
15106 pub fn background_highlight_row_ranges<T: 'static>(
15107 &self,
15108 search_range: Range<Anchor>,
15109 display_snapshot: &DisplaySnapshot,
15110 count: usize,
15111 ) -> Vec<RangeInclusive<DisplayPoint>> {
15112 let mut results = Vec::new();
15113 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15114 return vec![];
15115 };
15116
15117 let start_ix = match ranges.binary_search_by(|probe| {
15118 let cmp = probe
15119 .end
15120 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15121 if cmp.is_gt() {
15122 Ordering::Greater
15123 } else {
15124 Ordering::Less
15125 }
15126 }) {
15127 Ok(i) | Err(i) => i,
15128 };
15129 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15130 if let (Some(start_display), Some(end_display)) = (start, end) {
15131 results.push(
15132 start_display.to_display_point(display_snapshot)
15133 ..=end_display.to_display_point(display_snapshot),
15134 );
15135 }
15136 };
15137 let mut start_row: Option<Point> = None;
15138 let mut end_row: Option<Point> = None;
15139 if ranges.len() > count {
15140 return Vec::new();
15141 }
15142 for range in &ranges[start_ix..] {
15143 if range
15144 .start
15145 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15146 .is_ge()
15147 {
15148 break;
15149 }
15150 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15151 if let Some(current_row) = &end_row {
15152 if end.row == current_row.row {
15153 continue;
15154 }
15155 }
15156 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15157 if start_row.is_none() {
15158 assert_eq!(end_row, None);
15159 start_row = Some(start);
15160 end_row = Some(end);
15161 continue;
15162 }
15163 if let Some(current_end) = end_row.as_mut() {
15164 if start.row > current_end.row + 1 {
15165 push_region(start_row, end_row);
15166 start_row = Some(start);
15167 end_row = Some(end);
15168 } else {
15169 // Merge two hunks.
15170 *current_end = end;
15171 }
15172 } else {
15173 unreachable!();
15174 }
15175 }
15176 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15177 push_region(start_row, end_row);
15178 results
15179 }
15180
15181 pub fn gutter_highlights_in_range(
15182 &self,
15183 search_range: Range<Anchor>,
15184 display_snapshot: &DisplaySnapshot,
15185 cx: &App,
15186 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15187 let mut results = Vec::new();
15188 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15189 let color = color_fetcher(cx);
15190 let start_ix = match ranges.binary_search_by(|probe| {
15191 let cmp = probe
15192 .end
15193 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15194 if cmp.is_gt() {
15195 Ordering::Greater
15196 } else {
15197 Ordering::Less
15198 }
15199 }) {
15200 Ok(i) | Err(i) => i,
15201 };
15202 for range in &ranges[start_ix..] {
15203 if range
15204 .start
15205 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15206 .is_ge()
15207 {
15208 break;
15209 }
15210
15211 let start = range.start.to_display_point(display_snapshot);
15212 let end = range.end.to_display_point(display_snapshot);
15213 results.push((start..end, color))
15214 }
15215 }
15216 results
15217 }
15218
15219 /// Get the text ranges corresponding to the redaction query
15220 pub fn redacted_ranges(
15221 &self,
15222 search_range: Range<Anchor>,
15223 display_snapshot: &DisplaySnapshot,
15224 cx: &App,
15225 ) -> Vec<Range<DisplayPoint>> {
15226 display_snapshot
15227 .buffer_snapshot
15228 .redacted_ranges(search_range, |file| {
15229 if let Some(file) = file {
15230 file.is_private()
15231 && EditorSettings::get(
15232 Some(SettingsLocation {
15233 worktree_id: file.worktree_id(cx),
15234 path: file.path().as_ref(),
15235 }),
15236 cx,
15237 )
15238 .redact_private_values
15239 } else {
15240 false
15241 }
15242 })
15243 .map(|range| {
15244 range.start.to_display_point(display_snapshot)
15245 ..range.end.to_display_point(display_snapshot)
15246 })
15247 .collect()
15248 }
15249
15250 pub fn highlight_text<T: 'static>(
15251 &mut self,
15252 ranges: Vec<Range<Anchor>>,
15253 style: HighlightStyle,
15254 cx: &mut Context<Self>,
15255 ) {
15256 self.display_map.update(cx, |map, _| {
15257 map.highlight_text(TypeId::of::<T>(), ranges, style)
15258 });
15259 cx.notify();
15260 }
15261
15262 pub(crate) fn highlight_inlays<T: 'static>(
15263 &mut self,
15264 highlights: Vec<InlayHighlight>,
15265 style: HighlightStyle,
15266 cx: &mut Context<Self>,
15267 ) {
15268 self.display_map.update(cx, |map, _| {
15269 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15270 });
15271 cx.notify();
15272 }
15273
15274 pub fn text_highlights<'a, T: 'static>(
15275 &'a self,
15276 cx: &'a App,
15277 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15278 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15279 }
15280
15281 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15282 let cleared = self
15283 .display_map
15284 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15285 if cleared {
15286 cx.notify();
15287 }
15288 }
15289
15290 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15291 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15292 && self.focus_handle.is_focused(window)
15293 }
15294
15295 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15296 self.show_cursor_when_unfocused = is_enabled;
15297 cx.notify();
15298 }
15299
15300 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15301 cx.notify();
15302 }
15303
15304 fn on_buffer_event(
15305 &mut self,
15306 multibuffer: &Entity<MultiBuffer>,
15307 event: &multi_buffer::Event,
15308 window: &mut Window,
15309 cx: &mut Context<Self>,
15310 ) {
15311 match event {
15312 multi_buffer::Event::Edited {
15313 singleton_buffer_edited,
15314 edited_buffer: buffer_edited,
15315 } => {
15316 self.scrollbar_marker_state.dirty = true;
15317 self.active_indent_guides_state.dirty = true;
15318 self.refresh_active_diagnostics(cx);
15319 self.refresh_code_actions(window, cx);
15320 if self.has_active_inline_completion() {
15321 self.update_visible_inline_completion(window, cx);
15322 }
15323 if let Some(buffer) = buffer_edited {
15324 let buffer_id = buffer.read(cx).remote_id();
15325 if !self.registered_buffers.contains_key(&buffer_id) {
15326 if let Some(project) = self.project.as_ref() {
15327 project.update(cx, |project, cx| {
15328 self.registered_buffers.insert(
15329 buffer_id,
15330 project.register_buffer_with_language_servers(&buffer, cx),
15331 );
15332 })
15333 }
15334 }
15335 }
15336 cx.emit(EditorEvent::BufferEdited);
15337 cx.emit(SearchEvent::MatchesInvalidated);
15338 if *singleton_buffer_edited {
15339 if let Some(project) = &self.project {
15340 #[allow(clippy::mutable_key_type)]
15341 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15342 multibuffer
15343 .all_buffers()
15344 .into_iter()
15345 .filter_map(|buffer| {
15346 buffer.update(cx, |buffer, cx| {
15347 let language = buffer.language()?;
15348 let should_discard = project.update(cx, |project, cx| {
15349 project.is_local()
15350 && !project.has_language_servers_for(buffer, cx)
15351 });
15352 should_discard.not().then_some(language.clone())
15353 })
15354 })
15355 .collect::<HashSet<_>>()
15356 });
15357 if !languages_affected.is_empty() {
15358 self.refresh_inlay_hints(
15359 InlayHintRefreshReason::BufferEdited(languages_affected),
15360 cx,
15361 );
15362 }
15363 }
15364 }
15365
15366 let Some(project) = &self.project else { return };
15367 let (telemetry, is_via_ssh) = {
15368 let project = project.read(cx);
15369 let telemetry = project.client().telemetry().clone();
15370 let is_via_ssh = project.is_via_ssh();
15371 (telemetry, is_via_ssh)
15372 };
15373 refresh_linked_ranges(self, window, cx);
15374 telemetry.log_edit_event("editor", is_via_ssh);
15375 }
15376 multi_buffer::Event::ExcerptsAdded {
15377 buffer,
15378 predecessor,
15379 excerpts,
15380 } => {
15381 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15382 let buffer_id = buffer.read(cx).remote_id();
15383 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15384 if let Some(project) = &self.project {
15385 get_uncommitted_diff_for_buffer(
15386 project,
15387 [buffer.clone()],
15388 self.buffer.clone(),
15389 cx,
15390 )
15391 .detach();
15392 }
15393 }
15394 cx.emit(EditorEvent::ExcerptsAdded {
15395 buffer: buffer.clone(),
15396 predecessor: *predecessor,
15397 excerpts: excerpts.clone(),
15398 });
15399 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15400 }
15401 multi_buffer::Event::ExcerptsRemoved { ids } => {
15402 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15403 let buffer = self.buffer.read(cx);
15404 self.registered_buffers
15405 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15406 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15407 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15408 }
15409 multi_buffer::Event::ExcerptsEdited {
15410 excerpt_ids,
15411 buffer_ids,
15412 } => {
15413 self.display_map.update(cx, |map, cx| {
15414 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15415 });
15416 cx.emit(EditorEvent::ExcerptsEdited {
15417 ids: excerpt_ids.clone(),
15418 })
15419 }
15420 multi_buffer::Event::ExcerptsExpanded { ids } => {
15421 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15422 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15423 }
15424 multi_buffer::Event::Reparsed(buffer_id) => {
15425 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15426 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15427
15428 cx.emit(EditorEvent::Reparsed(*buffer_id));
15429 }
15430 multi_buffer::Event::DiffHunksToggled => {
15431 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15432 }
15433 multi_buffer::Event::LanguageChanged(buffer_id) => {
15434 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15435 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15436 cx.emit(EditorEvent::Reparsed(*buffer_id));
15437 cx.notify();
15438 }
15439 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15440 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15441 multi_buffer::Event::FileHandleChanged
15442 | multi_buffer::Event::Reloaded
15443 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15444 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15445 multi_buffer::Event::DiagnosticsUpdated => {
15446 self.refresh_active_diagnostics(cx);
15447 self.refresh_inline_diagnostics(true, window, cx);
15448 self.scrollbar_marker_state.dirty = true;
15449 cx.notify();
15450 }
15451 _ => {}
15452 };
15453 }
15454
15455 fn on_display_map_changed(
15456 &mut self,
15457 _: Entity<DisplayMap>,
15458 _: &mut Window,
15459 cx: &mut Context<Self>,
15460 ) {
15461 cx.notify();
15462 }
15463
15464 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15465 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15466 self.update_edit_prediction_settings(cx);
15467 self.refresh_inline_completion(true, false, window, cx);
15468 self.refresh_inlay_hints(
15469 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15470 self.selections.newest_anchor().head(),
15471 &self.buffer.read(cx).snapshot(cx),
15472 cx,
15473 )),
15474 cx,
15475 );
15476
15477 let old_cursor_shape = self.cursor_shape;
15478
15479 {
15480 let editor_settings = EditorSettings::get_global(cx);
15481 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15482 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15483 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15484 }
15485
15486 if old_cursor_shape != self.cursor_shape {
15487 cx.emit(EditorEvent::CursorShapeChanged);
15488 }
15489
15490 let project_settings = ProjectSettings::get_global(cx);
15491 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15492
15493 if self.mode == EditorMode::Full {
15494 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15495 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15496 if self.show_inline_diagnostics != show_inline_diagnostics {
15497 self.show_inline_diagnostics = show_inline_diagnostics;
15498 self.refresh_inline_diagnostics(false, window, cx);
15499 }
15500
15501 if self.git_blame_inline_enabled != inline_blame_enabled {
15502 self.toggle_git_blame_inline_internal(false, window, cx);
15503 }
15504 }
15505
15506 cx.notify();
15507 }
15508
15509 pub fn set_searchable(&mut self, searchable: bool) {
15510 self.searchable = searchable;
15511 }
15512
15513 pub fn searchable(&self) -> bool {
15514 self.searchable
15515 }
15516
15517 fn open_proposed_changes_editor(
15518 &mut self,
15519 _: &OpenProposedChangesEditor,
15520 window: &mut Window,
15521 cx: &mut Context<Self>,
15522 ) {
15523 let Some(workspace) = self.workspace() else {
15524 cx.propagate();
15525 return;
15526 };
15527
15528 let selections = self.selections.all::<usize>(cx);
15529 let multi_buffer = self.buffer.read(cx);
15530 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15531 let mut new_selections_by_buffer = HashMap::default();
15532 for selection in selections {
15533 for (buffer, range, _) in
15534 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15535 {
15536 let mut range = range.to_point(buffer);
15537 range.start.column = 0;
15538 range.end.column = buffer.line_len(range.end.row);
15539 new_selections_by_buffer
15540 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15541 .or_insert(Vec::new())
15542 .push(range)
15543 }
15544 }
15545
15546 let proposed_changes_buffers = new_selections_by_buffer
15547 .into_iter()
15548 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15549 .collect::<Vec<_>>();
15550 let proposed_changes_editor = cx.new(|cx| {
15551 ProposedChangesEditor::new(
15552 "Proposed changes",
15553 proposed_changes_buffers,
15554 self.project.clone(),
15555 window,
15556 cx,
15557 )
15558 });
15559
15560 window.defer(cx, move |window, cx| {
15561 workspace.update(cx, |workspace, cx| {
15562 workspace.active_pane().update(cx, |pane, cx| {
15563 pane.add_item(
15564 Box::new(proposed_changes_editor),
15565 true,
15566 true,
15567 None,
15568 window,
15569 cx,
15570 );
15571 });
15572 });
15573 });
15574 }
15575
15576 pub fn open_excerpts_in_split(
15577 &mut self,
15578 _: &OpenExcerptsSplit,
15579 window: &mut Window,
15580 cx: &mut Context<Self>,
15581 ) {
15582 self.open_excerpts_common(None, true, window, cx)
15583 }
15584
15585 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15586 self.open_excerpts_common(None, false, window, cx)
15587 }
15588
15589 fn open_excerpts_common(
15590 &mut self,
15591 jump_data: Option<JumpData>,
15592 split: bool,
15593 window: &mut Window,
15594 cx: &mut Context<Self>,
15595 ) {
15596 let Some(workspace) = self.workspace() else {
15597 cx.propagate();
15598 return;
15599 };
15600
15601 if self.buffer.read(cx).is_singleton() {
15602 cx.propagate();
15603 return;
15604 }
15605
15606 let mut new_selections_by_buffer = HashMap::default();
15607 match &jump_data {
15608 Some(JumpData::MultiBufferPoint {
15609 excerpt_id,
15610 position,
15611 anchor,
15612 line_offset_from_top,
15613 }) => {
15614 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15615 if let Some(buffer) = multi_buffer_snapshot
15616 .buffer_id_for_excerpt(*excerpt_id)
15617 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15618 {
15619 let buffer_snapshot = buffer.read(cx).snapshot();
15620 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15621 language::ToPoint::to_point(anchor, &buffer_snapshot)
15622 } else {
15623 buffer_snapshot.clip_point(*position, Bias::Left)
15624 };
15625 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15626 new_selections_by_buffer.insert(
15627 buffer,
15628 (
15629 vec![jump_to_offset..jump_to_offset],
15630 Some(*line_offset_from_top),
15631 ),
15632 );
15633 }
15634 }
15635 Some(JumpData::MultiBufferRow {
15636 row,
15637 line_offset_from_top,
15638 }) => {
15639 let point = MultiBufferPoint::new(row.0, 0);
15640 if let Some((buffer, buffer_point, _)) =
15641 self.buffer.read(cx).point_to_buffer_point(point, cx)
15642 {
15643 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15644 new_selections_by_buffer
15645 .entry(buffer)
15646 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15647 .0
15648 .push(buffer_offset..buffer_offset)
15649 }
15650 }
15651 None => {
15652 let selections = self.selections.all::<usize>(cx);
15653 let multi_buffer = self.buffer.read(cx);
15654 for selection in selections {
15655 for (snapshot, range, _, anchor) in multi_buffer
15656 .snapshot(cx)
15657 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15658 {
15659 if let Some(anchor) = anchor {
15660 // selection is in a deleted hunk
15661 let Some(buffer_id) = anchor.buffer_id else {
15662 continue;
15663 };
15664 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15665 continue;
15666 };
15667 let offset = text::ToOffset::to_offset(
15668 &anchor.text_anchor,
15669 &buffer_handle.read(cx).snapshot(),
15670 );
15671 let range = offset..offset;
15672 new_selections_by_buffer
15673 .entry(buffer_handle)
15674 .or_insert((Vec::new(), None))
15675 .0
15676 .push(range)
15677 } else {
15678 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15679 else {
15680 continue;
15681 };
15682 new_selections_by_buffer
15683 .entry(buffer_handle)
15684 .or_insert((Vec::new(), None))
15685 .0
15686 .push(range)
15687 }
15688 }
15689 }
15690 }
15691 }
15692
15693 if new_selections_by_buffer.is_empty() {
15694 return;
15695 }
15696
15697 // We defer the pane interaction because we ourselves are a workspace item
15698 // and activating a new item causes the pane to call a method on us reentrantly,
15699 // which panics if we're on the stack.
15700 window.defer(cx, move |window, cx| {
15701 workspace.update(cx, |workspace, cx| {
15702 let pane = if split {
15703 workspace.adjacent_pane(window, cx)
15704 } else {
15705 workspace.active_pane().clone()
15706 };
15707
15708 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15709 let editor = buffer
15710 .read(cx)
15711 .file()
15712 .is_none()
15713 .then(|| {
15714 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15715 // so `workspace.open_project_item` will never find them, always opening a new editor.
15716 // Instead, we try to activate the existing editor in the pane first.
15717 let (editor, pane_item_index) =
15718 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15719 let editor = item.downcast::<Editor>()?;
15720 let singleton_buffer =
15721 editor.read(cx).buffer().read(cx).as_singleton()?;
15722 if singleton_buffer == buffer {
15723 Some((editor, i))
15724 } else {
15725 None
15726 }
15727 })?;
15728 pane.update(cx, |pane, cx| {
15729 pane.activate_item(pane_item_index, true, true, window, cx)
15730 });
15731 Some(editor)
15732 })
15733 .flatten()
15734 .unwrap_or_else(|| {
15735 workspace.open_project_item::<Self>(
15736 pane.clone(),
15737 buffer,
15738 true,
15739 true,
15740 window,
15741 cx,
15742 )
15743 });
15744
15745 editor.update(cx, |editor, cx| {
15746 let autoscroll = match scroll_offset {
15747 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15748 None => Autoscroll::newest(),
15749 };
15750 let nav_history = editor.nav_history.take();
15751 editor.change_selections(Some(autoscroll), window, cx, |s| {
15752 s.select_ranges(ranges);
15753 });
15754 editor.nav_history = nav_history;
15755 });
15756 }
15757 })
15758 });
15759 }
15760
15761 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15762 let snapshot = self.buffer.read(cx).read(cx);
15763 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15764 Some(
15765 ranges
15766 .iter()
15767 .map(move |range| {
15768 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15769 })
15770 .collect(),
15771 )
15772 }
15773
15774 fn selection_replacement_ranges(
15775 &self,
15776 range: Range<OffsetUtf16>,
15777 cx: &mut App,
15778 ) -> Vec<Range<OffsetUtf16>> {
15779 let selections = self.selections.all::<OffsetUtf16>(cx);
15780 let newest_selection = selections
15781 .iter()
15782 .max_by_key(|selection| selection.id)
15783 .unwrap();
15784 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15785 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15786 let snapshot = self.buffer.read(cx).read(cx);
15787 selections
15788 .into_iter()
15789 .map(|mut selection| {
15790 selection.start.0 =
15791 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15792 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15793 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15794 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15795 })
15796 .collect()
15797 }
15798
15799 fn report_editor_event(
15800 &self,
15801 event_type: &'static str,
15802 file_extension: Option<String>,
15803 cx: &App,
15804 ) {
15805 if cfg!(any(test, feature = "test-support")) {
15806 return;
15807 }
15808
15809 let Some(project) = &self.project else { return };
15810
15811 // If None, we are in a file without an extension
15812 let file = self
15813 .buffer
15814 .read(cx)
15815 .as_singleton()
15816 .and_then(|b| b.read(cx).file());
15817 let file_extension = file_extension.or(file
15818 .as_ref()
15819 .and_then(|file| Path::new(file.file_name(cx)).extension())
15820 .and_then(|e| e.to_str())
15821 .map(|a| a.to_string()));
15822
15823 let vim_mode = cx
15824 .global::<SettingsStore>()
15825 .raw_user_settings()
15826 .get("vim_mode")
15827 == Some(&serde_json::Value::Bool(true));
15828
15829 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15830 let copilot_enabled = edit_predictions_provider
15831 == language::language_settings::EditPredictionProvider::Copilot;
15832 let copilot_enabled_for_language = self
15833 .buffer
15834 .read(cx)
15835 .language_settings(cx)
15836 .show_edit_predictions;
15837
15838 let project = project.read(cx);
15839 telemetry::event!(
15840 event_type,
15841 file_extension,
15842 vim_mode,
15843 copilot_enabled,
15844 copilot_enabled_for_language,
15845 edit_predictions_provider,
15846 is_via_ssh = project.is_via_ssh(),
15847 );
15848 }
15849
15850 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15851 /// with each line being an array of {text, highlight} objects.
15852 fn copy_highlight_json(
15853 &mut self,
15854 _: &CopyHighlightJson,
15855 window: &mut Window,
15856 cx: &mut Context<Self>,
15857 ) {
15858 #[derive(Serialize)]
15859 struct Chunk<'a> {
15860 text: String,
15861 highlight: Option<&'a str>,
15862 }
15863
15864 let snapshot = self.buffer.read(cx).snapshot(cx);
15865 let range = self
15866 .selected_text_range(false, window, cx)
15867 .and_then(|selection| {
15868 if selection.range.is_empty() {
15869 None
15870 } else {
15871 Some(selection.range)
15872 }
15873 })
15874 .unwrap_or_else(|| 0..snapshot.len());
15875
15876 let chunks = snapshot.chunks(range, true);
15877 let mut lines = Vec::new();
15878 let mut line: VecDeque<Chunk> = VecDeque::new();
15879
15880 let Some(style) = self.style.as_ref() else {
15881 return;
15882 };
15883
15884 for chunk in chunks {
15885 let highlight = chunk
15886 .syntax_highlight_id
15887 .and_then(|id| id.name(&style.syntax));
15888 let mut chunk_lines = chunk.text.split('\n').peekable();
15889 while let Some(text) = chunk_lines.next() {
15890 let mut merged_with_last_token = false;
15891 if let Some(last_token) = line.back_mut() {
15892 if last_token.highlight == highlight {
15893 last_token.text.push_str(text);
15894 merged_with_last_token = true;
15895 }
15896 }
15897
15898 if !merged_with_last_token {
15899 line.push_back(Chunk {
15900 text: text.into(),
15901 highlight,
15902 });
15903 }
15904
15905 if chunk_lines.peek().is_some() {
15906 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15907 line.pop_front();
15908 }
15909 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15910 line.pop_back();
15911 }
15912
15913 lines.push(mem::take(&mut line));
15914 }
15915 }
15916 }
15917
15918 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15919 return;
15920 };
15921 cx.write_to_clipboard(ClipboardItem::new_string(lines));
15922 }
15923
15924 pub fn open_context_menu(
15925 &mut self,
15926 _: &OpenContextMenu,
15927 window: &mut Window,
15928 cx: &mut Context<Self>,
15929 ) {
15930 self.request_autoscroll(Autoscroll::newest(), cx);
15931 let position = self.selections.newest_display(cx).start;
15932 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
15933 }
15934
15935 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
15936 &self.inlay_hint_cache
15937 }
15938
15939 pub fn replay_insert_event(
15940 &mut self,
15941 text: &str,
15942 relative_utf16_range: Option<Range<isize>>,
15943 window: &mut Window,
15944 cx: &mut Context<Self>,
15945 ) {
15946 if !self.input_enabled {
15947 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15948 return;
15949 }
15950 if let Some(relative_utf16_range) = relative_utf16_range {
15951 let selections = self.selections.all::<OffsetUtf16>(cx);
15952 self.change_selections(None, window, cx, |s| {
15953 let new_ranges = selections.into_iter().map(|range| {
15954 let start = OffsetUtf16(
15955 range
15956 .head()
15957 .0
15958 .saturating_add_signed(relative_utf16_range.start),
15959 );
15960 let end = OffsetUtf16(
15961 range
15962 .head()
15963 .0
15964 .saturating_add_signed(relative_utf16_range.end),
15965 );
15966 start..end
15967 });
15968 s.select_ranges(new_ranges);
15969 });
15970 }
15971
15972 self.handle_input(text, window, cx);
15973 }
15974
15975 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
15976 let Some(provider) = self.semantics_provider.as_ref() else {
15977 return false;
15978 };
15979
15980 let mut supports = false;
15981 self.buffer().update(cx, |this, cx| {
15982 this.for_each_buffer(|buffer| {
15983 supports |= provider.supports_inlay_hints(buffer, cx);
15984 });
15985 });
15986
15987 supports
15988 }
15989
15990 pub fn is_focused(&self, window: &Window) -> bool {
15991 self.focus_handle.is_focused(window)
15992 }
15993
15994 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15995 cx.emit(EditorEvent::Focused);
15996
15997 if let Some(descendant) = self
15998 .last_focused_descendant
15999 .take()
16000 .and_then(|descendant| descendant.upgrade())
16001 {
16002 window.focus(&descendant);
16003 } else {
16004 if let Some(blame) = self.blame.as_ref() {
16005 blame.update(cx, GitBlame::focus)
16006 }
16007
16008 self.blink_manager.update(cx, BlinkManager::enable);
16009 self.show_cursor_names(window, cx);
16010 self.buffer.update(cx, |buffer, cx| {
16011 buffer.finalize_last_transaction(cx);
16012 if self.leader_peer_id.is_none() {
16013 buffer.set_active_selections(
16014 &self.selections.disjoint_anchors(),
16015 self.selections.line_mode,
16016 self.cursor_shape,
16017 cx,
16018 );
16019 }
16020 });
16021 }
16022 }
16023
16024 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16025 cx.emit(EditorEvent::FocusedIn)
16026 }
16027
16028 fn handle_focus_out(
16029 &mut self,
16030 event: FocusOutEvent,
16031 _window: &mut Window,
16032 cx: &mut Context<Self>,
16033 ) {
16034 if event.blurred != self.focus_handle {
16035 self.last_focused_descendant = Some(event.blurred);
16036 }
16037 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16038 }
16039
16040 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16041 self.blink_manager.update(cx, BlinkManager::disable);
16042 self.buffer
16043 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16044
16045 if let Some(blame) = self.blame.as_ref() {
16046 blame.update(cx, GitBlame::blur)
16047 }
16048 if !self.hover_state.focused(window, cx) {
16049 hide_hover(self, cx);
16050 }
16051 if !self
16052 .context_menu
16053 .borrow()
16054 .as_ref()
16055 .is_some_and(|context_menu| context_menu.focused(window, cx))
16056 {
16057 self.hide_context_menu(window, cx);
16058 }
16059 self.discard_inline_completion(false, cx);
16060 cx.emit(EditorEvent::Blurred);
16061 cx.notify();
16062 }
16063
16064 pub fn register_action<A: Action>(
16065 &mut self,
16066 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16067 ) -> Subscription {
16068 let id = self.next_editor_action_id.post_inc();
16069 let listener = Arc::new(listener);
16070 self.editor_actions.borrow_mut().insert(
16071 id,
16072 Box::new(move |window, _| {
16073 let listener = listener.clone();
16074 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16075 let action = action.downcast_ref().unwrap();
16076 if phase == DispatchPhase::Bubble {
16077 listener(action, window, cx)
16078 }
16079 })
16080 }),
16081 );
16082
16083 let editor_actions = self.editor_actions.clone();
16084 Subscription::new(move || {
16085 editor_actions.borrow_mut().remove(&id);
16086 })
16087 }
16088
16089 pub fn file_header_size(&self) -> u32 {
16090 FILE_HEADER_HEIGHT
16091 }
16092
16093 pub fn restore(
16094 &mut self,
16095 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16096 window: &mut Window,
16097 cx: &mut Context<Self>,
16098 ) {
16099 let workspace = self.workspace();
16100 let project = self.project.as_ref();
16101 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16102 let mut tasks = Vec::new();
16103 for (buffer_id, changes) in revert_changes {
16104 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16105 buffer.update(cx, |buffer, cx| {
16106 buffer.edit(
16107 changes
16108 .into_iter()
16109 .map(|(range, text)| (range, text.to_string())),
16110 None,
16111 cx,
16112 );
16113 });
16114
16115 if let Some(project) =
16116 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16117 {
16118 project.update(cx, |project, cx| {
16119 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16120 })
16121 }
16122 }
16123 }
16124 tasks
16125 });
16126 cx.spawn_in(window, |_, mut cx| async move {
16127 for (buffer, task) in save_tasks {
16128 let result = task.await;
16129 if result.is_err() {
16130 let Some(path) = buffer
16131 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16132 .ok()
16133 else {
16134 continue;
16135 };
16136 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16137 let Some(task) = cx
16138 .update_window_entity(&workspace, |workspace, window, cx| {
16139 workspace
16140 .open_path_preview(path, None, false, false, false, window, cx)
16141 })
16142 .ok()
16143 else {
16144 continue;
16145 };
16146 task.await.log_err();
16147 }
16148 }
16149 }
16150 })
16151 .detach();
16152 self.change_selections(None, window, cx, |selections| selections.refresh());
16153 }
16154
16155 pub fn to_pixel_point(
16156 &self,
16157 source: multi_buffer::Anchor,
16158 editor_snapshot: &EditorSnapshot,
16159 window: &mut Window,
16160 ) -> Option<gpui::Point<Pixels>> {
16161 let source_point = source.to_display_point(editor_snapshot);
16162 self.display_to_pixel_point(source_point, editor_snapshot, window)
16163 }
16164
16165 pub fn display_to_pixel_point(
16166 &self,
16167 source: DisplayPoint,
16168 editor_snapshot: &EditorSnapshot,
16169 window: &mut Window,
16170 ) -> Option<gpui::Point<Pixels>> {
16171 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16172 let text_layout_details = self.text_layout_details(window);
16173 let scroll_top = text_layout_details
16174 .scroll_anchor
16175 .scroll_position(editor_snapshot)
16176 .y;
16177
16178 if source.row().as_f32() < scroll_top.floor() {
16179 return None;
16180 }
16181 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16182 let source_y = line_height * (source.row().as_f32() - scroll_top);
16183 Some(gpui::Point::new(source_x, source_y))
16184 }
16185
16186 pub fn has_visible_completions_menu(&self) -> bool {
16187 !self.edit_prediction_preview_is_active()
16188 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16189 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16190 })
16191 }
16192
16193 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16194 self.addons
16195 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16196 }
16197
16198 pub fn unregister_addon<T: Addon>(&mut self) {
16199 self.addons.remove(&std::any::TypeId::of::<T>());
16200 }
16201
16202 pub fn addon<T: Addon>(&self) -> Option<&T> {
16203 let type_id = std::any::TypeId::of::<T>();
16204 self.addons
16205 .get(&type_id)
16206 .and_then(|item| item.to_any().downcast_ref::<T>())
16207 }
16208
16209 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16210 let text_layout_details = self.text_layout_details(window);
16211 let style = &text_layout_details.editor_style;
16212 let font_id = window.text_system().resolve_font(&style.text.font());
16213 let font_size = style.text.font_size.to_pixels(window.rem_size());
16214 let line_height = style.text.line_height_in_pixels(window.rem_size());
16215 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16216
16217 gpui::Size::new(em_width, line_height)
16218 }
16219
16220 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16221 self.load_diff_task.clone()
16222 }
16223
16224 fn read_selections_from_db(
16225 &mut self,
16226 item_id: u64,
16227 workspace_id: WorkspaceId,
16228 window: &mut Window,
16229 cx: &mut Context<Editor>,
16230 ) {
16231 if !self.is_singleton(cx)
16232 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16233 {
16234 return;
16235 }
16236 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16237 return;
16238 };
16239 if selections.is_empty() {
16240 return;
16241 }
16242
16243 let snapshot = self.buffer.read(cx).snapshot(cx);
16244 self.change_selections(None, window, cx, |s| {
16245 s.select_ranges(selections.into_iter().map(|(start, end)| {
16246 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16247 }));
16248 });
16249 }
16250}
16251
16252fn insert_extra_newline_brackets(
16253 buffer: &MultiBufferSnapshot,
16254 range: Range<usize>,
16255 language: &language::LanguageScope,
16256) -> bool {
16257 let leading_whitespace_len = buffer
16258 .reversed_chars_at(range.start)
16259 .take_while(|c| c.is_whitespace() && *c != '\n')
16260 .map(|c| c.len_utf8())
16261 .sum::<usize>();
16262 let trailing_whitespace_len = buffer
16263 .chars_at(range.end)
16264 .take_while(|c| c.is_whitespace() && *c != '\n')
16265 .map(|c| c.len_utf8())
16266 .sum::<usize>();
16267 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16268
16269 language.brackets().any(|(pair, enabled)| {
16270 let pair_start = pair.start.trim_end();
16271 let pair_end = pair.end.trim_start();
16272
16273 enabled
16274 && pair.newline
16275 && buffer.contains_str_at(range.end, pair_end)
16276 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16277 })
16278}
16279
16280fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16281 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16282 [(buffer, range, _)] => (*buffer, range.clone()),
16283 _ => return false,
16284 };
16285 let pair = {
16286 let mut result: Option<BracketMatch> = None;
16287
16288 for pair in buffer
16289 .all_bracket_ranges(range.clone())
16290 .filter(move |pair| {
16291 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16292 })
16293 {
16294 let len = pair.close_range.end - pair.open_range.start;
16295
16296 if let Some(existing) = &result {
16297 let existing_len = existing.close_range.end - existing.open_range.start;
16298 if len > existing_len {
16299 continue;
16300 }
16301 }
16302
16303 result = Some(pair);
16304 }
16305
16306 result
16307 };
16308 let Some(pair) = pair else {
16309 return false;
16310 };
16311 pair.newline_only
16312 && buffer
16313 .chars_for_range(pair.open_range.end..range.start)
16314 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16315 .all(|c| c.is_whitespace() && c != '\n')
16316}
16317
16318fn get_uncommitted_diff_for_buffer(
16319 project: &Entity<Project>,
16320 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16321 buffer: Entity<MultiBuffer>,
16322 cx: &mut App,
16323) -> Task<()> {
16324 let mut tasks = Vec::new();
16325 project.update(cx, |project, cx| {
16326 for buffer in buffers {
16327 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16328 }
16329 });
16330 cx.spawn(|mut cx| async move {
16331 let diffs = future::join_all(tasks).await;
16332 buffer
16333 .update(&mut cx, |buffer, cx| {
16334 for diff in diffs.into_iter().flatten() {
16335 buffer.add_diff(diff, cx);
16336 }
16337 })
16338 .ok();
16339 })
16340}
16341
16342fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16343 let tab_size = tab_size.get() as usize;
16344 let mut width = offset;
16345
16346 for ch in text.chars() {
16347 width += if ch == '\t' {
16348 tab_size - (width % tab_size)
16349 } else {
16350 1
16351 };
16352 }
16353
16354 width - offset
16355}
16356
16357#[cfg(test)]
16358mod tests {
16359 use super::*;
16360
16361 #[test]
16362 fn test_string_size_with_expanded_tabs() {
16363 let nz = |val| NonZeroU32::new(val).unwrap();
16364 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16365 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16366 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16367 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16368 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16369 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16370 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16371 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16372 }
16373}
16374
16375/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16376struct WordBreakingTokenizer<'a> {
16377 input: &'a str,
16378}
16379
16380impl<'a> WordBreakingTokenizer<'a> {
16381 fn new(input: &'a str) -> Self {
16382 Self { input }
16383 }
16384}
16385
16386fn is_char_ideographic(ch: char) -> bool {
16387 use unicode_script::Script::*;
16388 use unicode_script::UnicodeScript;
16389 matches!(ch.script(), Han | Tangut | Yi)
16390}
16391
16392fn is_grapheme_ideographic(text: &str) -> bool {
16393 text.chars().any(is_char_ideographic)
16394}
16395
16396fn is_grapheme_whitespace(text: &str) -> bool {
16397 text.chars().any(|x| x.is_whitespace())
16398}
16399
16400fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16401 text.chars().next().map_or(false, |ch| {
16402 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16403 })
16404}
16405
16406#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16407struct WordBreakToken<'a> {
16408 token: &'a str,
16409 grapheme_len: usize,
16410 is_whitespace: bool,
16411}
16412
16413impl<'a> Iterator for WordBreakingTokenizer<'a> {
16414 /// Yields a span, the count of graphemes in the token, and whether it was
16415 /// whitespace. Note that it also breaks at word boundaries.
16416 type Item = WordBreakToken<'a>;
16417
16418 fn next(&mut self) -> Option<Self::Item> {
16419 use unicode_segmentation::UnicodeSegmentation;
16420 if self.input.is_empty() {
16421 return None;
16422 }
16423
16424 let mut iter = self.input.graphemes(true).peekable();
16425 let mut offset = 0;
16426 let mut graphemes = 0;
16427 if let Some(first_grapheme) = iter.next() {
16428 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16429 offset += first_grapheme.len();
16430 graphemes += 1;
16431 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16432 if let Some(grapheme) = iter.peek().copied() {
16433 if should_stay_with_preceding_ideograph(grapheme) {
16434 offset += grapheme.len();
16435 graphemes += 1;
16436 }
16437 }
16438 } else {
16439 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16440 let mut next_word_bound = words.peek().copied();
16441 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16442 next_word_bound = words.next();
16443 }
16444 while let Some(grapheme) = iter.peek().copied() {
16445 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16446 break;
16447 };
16448 if is_grapheme_whitespace(grapheme) != is_whitespace {
16449 break;
16450 };
16451 offset += grapheme.len();
16452 graphemes += 1;
16453 iter.next();
16454 }
16455 }
16456 let token = &self.input[..offset];
16457 self.input = &self.input[offset..];
16458 if is_whitespace {
16459 Some(WordBreakToken {
16460 token: " ",
16461 grapheme_len: 1,
16462 is_whitespace: true,
16463 })
16464 } else {
16465 Some(WordBreakToken {
16466 token,
16467 grapheme_len: graphemes,
16468 is_whitespace: false,
16469 })
16470 }
16471 } else {
16472 None
16473 }
16474 }
16475}
16476
16477#[test]
16478fn test_word_breaking_tokenizer() {
16479 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16480 ("", &[]),
16481 (" ", &[(" ", 1, true)]),
16482 ("Ʒ", &[("Ʒ", 1, false)]),
16483 ("Ǽ", &[("Ǽ", 1, false)]),
16484 ("⋑", &[("⋑", 1, false)]),
16485 ("⋑⋑", &[("⋑⋑", 2, false)]),
16486 (
16487 "原理,进而",
16488 &[
16489 ("原", 1, false),
16490 ("理,", 2, false),
16491 ("进", 1, false),
16492 ("而", 1, false),
16493 ],
16494 ),
16495 (
16496 "hello world",
16497 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16498 ),
16499 (
16500 "hello, world",
16501 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16502 ),
16503 (
16504 " hello world",
16505 &[
16506 (" ", 1, true),
16507 ("hello", 5, false),
16508 (" ", 1, true),
16509 ("world", 5, false),
16510 ],
16511 ),
16512 (
16513 "这是什么 \n 钢笔",
16514 &[
16515 ("这", 1, false),
16516 ("是", 1, false),
16517 ("什", 1, false),
16518 ("么", 1, false),
16519 (" ", 1, true),
16520 ("钢", 1, false),
16521 ("笔", 1, false),
16522 ],
16523 ),
16524 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16525 ];
16526
16527 for (input, result) in tests {
16528 assert_eq!(
16529 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16530 result
16531 .iter()
16532 .copied()
16533 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16534 token,
16535 grapheme_len,
16536 is_whitespace,
16537 })
16538 .collect::<Vec<_>>()
16539 );
16540 }
16541}
16542
16543fn wrap_with_prefix(
16544 line_prefix: String,
16545 unwrapped_text: String,
16546 wrap_column: usize,
16547 tab_size: NonZeroU32,
16548) -> String {
16549 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16550 let mut wrapped_text = String::new();
16551 let mut current_line = line_prefix.clone();
16552
16553 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16554 let mut current_line_len = line_prefix_len;
16555 for WordBreakToken {
16556 token,
16557 grapheme_len,
16558 is_whitespace,
16559 } in tokenizer
16560 {
16561 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16562 wrapped_text.push_str(current_line.trim_end());
16563 wrapped_text.push('\n');
16564 current_line.truncate(line_prefix.len());
16565 current_line_len = line_prefix_len;
16566 if !is_whitespace {
16567 current_line.push_str(token);
16568 current_line_len += grapheme_len;
16569 }
16570 } else if !is_whitespace {
16571 current_line.push_str(token);
16572 current_line_len += grapheme_len;
16573 } else if current_line_len != line_prefix_len {
16574 current_line.push(' ');
16575 current_line_len += 1;
16576 }
16577 }
16578
16579 if !current_line.is_empty() {
16580 wrapped_text.push_str(¤t_line);
16581 }
16582 wrapped_text
16583}
16584
16585#[test]
16586fn test_wrap_with_prefix() {
16587 assert_eq!(
16588 wrap_with_prefix(
16589 "# ".to_string(),
16590 "abcdefg".to_string(),
16591 4,
16592 NonZeroU32::new(4).unwrap()
16593 ),
16594 "# abcdefg"
16595 );
16596 assert_eq!(
16597 wrap_with_prefix(
16598 "".to_string(),
16599 "\thello world".to_string(),
16600 8,
16601 NonZeroU32::new(4).unwrap()
16602 ),
16603 "hello\nworld"
16604 );
16605 assert_eq!(
16606 wrap_with_prefix(
16607 "// ".to_string(),
16608 "xx \nyy zz aa bb cc".to_string(),
16609 12,
16610 NonZeroU32::new(4).unwrap()
16611 ),
16612 "// xx yy zz\n// aa bb cc"
16613 );
16614 assert_eq!(
16615 wrap_with_prefix(
16616 String::new(),
16617 "这是什么 \n 钢笔".to_string(),
16618 3,
16619 NonZeroU32::new(4).unwrap()
16620 ),
16621 "这是什\n么 钢\n笔"
16622 );
16623}
16624
16625pub trait CollaborationHub {
16626 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16627 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16628 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16629}
16630
16631impl CollaborationHub for Entity<Project> {
16632 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16633 self.read(cx).collaborators()
16634 }
16635
16636 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16637 self.read(cx).user_store().read(cx).participant_indices()
16638 }
16639
16640 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16641 let this = self.read(cx);
16642 let user_ids = this.collaborators().values().map(|c| c.user_id);
16643 this.user_store().read_with(cx, |user_store, cx| {
16644 user_store.participant_names(user_ids, cx)
16645 })
16646 }
16647}
16648
16649pub trait SemanticsProvider {
16650 fn hover(
16651 &self,
16652 buffer: &Entity<Buffer>,
16653 position: text::Anchor,
16654 cx: &mut App,
16655 ) -> Option<Task<Vec<project::Hover>>>;
16656
16657 fn inlay_hints(
16658 &self,
16659 buffer_handle: Entity<Buffer>,
16660 range: Range<text::Anchor>,
16661 cx: &mut App,
16662 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16663
16664 fn resolve_inlay_hint(
16665 &self,
16666 hint: InlayHint,
16667 buffer_handle: Entity<Buffer>,
16668 server_id: LanguageServerId,
16669 cx: &mut App,
16670 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16671
16672 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16673
16674 fn document_highlights(
16675 &self,
16676 buffer: &Entity<Buffer>,
16677 position: text::Anchor,
16678 cx: &mut App,
16679 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16680
16681 fn definitions(
16682 &self,
16683 buffer: &Entity<Buffer>,
16684 position: text::Anchor,
16685 kind: GotoDefinitionKind,
16686 cx: &mut App,
16687 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16688
16689 fn range_for_rename(
16690 &self,
16691 buffer: &Entity<Buffer>,
16692 position: text::Anchor,
16693 cx: &mut App,
16694 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16695
16696 fn perform_rename(
16697 &self,
16698 buffer: &Entity<Buffer>,
16699 position: text::Anchor,
16700 new_name: String,
16701 cx: &mut App,
16702 ) -> Option<Task<Result<ProjectTransaction>>>;
16703}
16704
16705pub trait CompletionProvider {
16706 fn completions(
16707 &self,
16708 buffer: &Entity<Buffer>,
16709 buffer_position: text::Anchor,
16710 trigger: CompletionContext,
16711 window: &mut Window,
16712 cx: &mut Context<Editor>,
16713 ) -> Task<Result<Vec<Completion>>>;
16714
16715 fn resolve_completions(
16716 &self,
16717 buffer: Entity<Buffer>,
16718 completion_indices: Vec<usize>,
16719 completions: Rc<RefCell<Box<[Completion]>>>,
16720 cx: &mut Context<Editor>,
16721 ) -> Task<Result<bool>>;
16722
16723 fn apply_additional_edits_for_completion(
16724 &self,
16725 _buffer: Entity<Buffer>,
16726 _completions: Rc<RefCell<Box<[Completion]>>>,
16727 _completion_index: usize,
16728 _push_to_history: bool,
16729 _cx: &mut Context<Editor>,
16730 ) -> Task<Result<Option<language::Transaction>>> {
16731 Task::ready(Ok(None))
16732 }
16733
16734 fn is_completion_trigger(
16735 &self,
16736 buffer: &Entity<Buffer>,
16737 position: language::Anchor,
16738 text: &str,
16739 trigger_in_words: bool,
16740 cx: &mut Context<Editor>,
16741 ) -> bool;
16742
16743 fn sort_completions(&self) -> bool {
16744 true
16745 }
16746}
16747
16748pub trait CodeActionProvider {
16749 fn id(&self) -> Arc<str>;
16750
16751 fn code_actions(
16752 &self,
16753 buffer: &Entity<Buffer>,
16754 range: Range<text::Anchor>,
16755 window: &mut Window,
16756 cx: &mut App,
16757 ) -> Task<Result<Vec<CodeAction>>>;
16758
16759 fn apply_code_action(
16760 &self,
16761 buffer_handle: Entity<Buffer>,
16762 action: CodeAction,
16763 excerpt_id: ExcerptId,
16764 push_to_history: bool,
16765 window: &mut Window,
16766 cx: &mut App,
16767 ) -> Task<Result<ProjectTransaction>>;
16768}
16769
16770impl CodeActionProvider for Entity<Project> {
16771 fn id(&self) -> Arc<str> {
16772 "project".into()
16773 }
16774
16775 fn code_actions(
16776 &self,
16777 buffer: &Entity<Buffer>,
16778 range: Range<text::Anchor>,
16779 _window: &mut Window,
16780 cx: &mut App,
16781 ) -> Task<Result<Vec<CodeAction>>> {
16782 self.update(cx, |project, cx| {
16783 project.code_actions(buffer, range, None, cx)
16784 })
16785 }
16786
16787 fn apply_code_action(
16788 &self,
16789 buffer_handle: Entity<Buffer>,
16790 action: CodeAction,
16791 _excerpt_id: ExcerptId,
16792 push_to_history: bool,
16793 _window: &mut Window,
16794 cx: &mut App,
16795 ) -> Task<Result<ProjectTransaction>> {
16796 self.update(cx, |project, cx| {
16797 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16798 })
16799 }
16800}
16801
16802fn snippet_completions(
16803 project: &Project,
16804 buffer: &Entity<Buffer>,
16805 buffer_position: text::Anchor,
16806 cx: &mut App,
16807) -> Task<Result<Vec<Completion>>> {
16808 let language = buffer.read(cx).language_at(buffer_position);
16809 let language_name = language.as_ref().map(|language| language.lsp_id());
16810 let snippet_store = project.snippets().read(cx);
16811 let snippets = snippet_store.snippets_for(language_name, cx);
16812
16813 if snippets.is_empty() {
16814 return Task::ready(Ok(vec![]));
16815 }
16816 let snapshot = buffer.read(cx).text_snapshot();
16817 let chars: String = snapshot
16818 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16819 .collect();
16820
16821 let scope = language.map(|language| language.default_scope());
16822 let executor = cx.background_executor().clone();
16823
16824 cx.background_spawn(async move {
16825 let classifier = CharClassifier::new(scope).for_completion(true);
16826 let mut last_word = chars
16827 .chars()
16828 .take_while(|c| classifier.is_word(*c))
16829 .collect::<String>();
16830 last_word = last_word.chars().rev().collect();
16831
16832 if last_word.is_empty() {
16833 return Ok(vec![]);
16834 }
16835
16836 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16837 let to_lsp = |point: &text::Anchor| {
16838 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16839 point_to_lsp(end)
16840 };
16841 let lsp_end = to_lsp(&buffer_position);
16842
16843 let candidates = snippets
16844 .iter()
16845 .enumerate()
16846 .flat_map(|(ix, snippet)| {
16847 snippet
16848 .prefix
16849 .iter()
16850 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16851 })
16852 .collect::<Vec<StringMatchCandidate>>();
16853
16854 let mut matches = fuzzy::match_strings(
16855 &candidates,
16856 &last_word,
16857 last_word.chars().any(|c| c.is_uppercase()),
16858 100,
16859 &Default::default(),
16860 executor,
16861 )
16862 .await;
16863
16864 // Remove all candidates where the query's start does not match the start of any word in the candidate
16865 if let Some(query_start) = last_word.chars().next() {
16866 matches.retain(|string_match| {
16867 split_words(&string_match.string).any(|word| {
16868 // Check that the first codepoint of the word as lowercase matches the first
16869 // codepoint of the query as lowercase
16870 word.chars()
16871 .flat_map(|codepoint| codepoint.to_lowercase())
16872 .zip(query_start.to_lowercase())
16873 .all(|(word_cp, query_cp)| word_cp == query_cp)
16874 })
16875 });
16876 }
16877
16878 let matched_strings = matches
16879 .into_iter()
16880 .map(|m| m.string)
16881 .collect::<HashSet<_>>();
16882
16883 let result: Vec<Completion> = snippets
16884 .into_iter()
16885 .filter_map(|snippet| {
16886 let matching_prefix = snippet
16887 .prefix
16888 .iter()
16889 .find(|prefix| matched_strings.contains(*prefix))?;
16890 let start = as_offset - last_word.len();
16891 let start = snapshot.anchor_before(start);
16892 let range = start..buffer_position;
16893 let lsp_start = to_lsp(&start);
16894 let lsp_range = lsp::Range {
16895 start: lsp_start,
16896 end: lsp_end,
16897 };
16898 Some(Completion {
16899 old_range: range,
16900 new_text: snippet.body.clone(),
16901 source: CompletionSource::Lsp {
16902 server_id: LanguageServerId(usize::MAX),
16903 resolved: true,
16904 lsp_completion: Box::new(lsp::CompletionItem {
16905 label: snippet.prefix.first().unwrap().clone(),
16906 kind: Some(CompletionItemKind::SNIPPET),
16907 label_details: snippet.description.as_ref().map(|description| {
16908 lsp::CompletionItemLabelDetails {
16909 detail: Some(description.clone()),
16910 description: None,
16911 }
16912 }),
16913 insert_text_format: Some(InsertTextFormat::SNIPPET),
16914 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16915 lsp::InsertReplaceEdit {
16916 new_text: snippet.body.clone(),
16917 insert: lsp_range,
16918 replace: lsp_range,
16919 },
16920 )),
16921 filter_text: Some(snippet.body.clone()),
16922 sort_text: Some(char::MAX.to_string()),
16923 ..lsp::CompletionItem::default()
16924 }),
16925 },
16926 label: CodeLabel {
16927 text: matching_prefix.clone(),
16928 runs: Vec::new(),
16929 filter_range: 0..matching_prefix.len(),
16930 },
16931 documentation: snippet
16932 .description
16933 .clone()
16934 .map(|description| CompletionDocumentation::SingleLine(description.into())),
16935 confirm: None,
16936 })
16937 })
16938 .collect();
16939
16940 Ok(result)
16941 })
16942}
16943
16944impl CompletionProvider for Entity<Project> {
16945 fn completions(
16946 &self,
16947 buffer: &Entity<Buffer>,
16948 buffer_position: text::Anchor,
16949 options: CompletionContext,
16950 _window: &mut Window,
16951 cx: &mut Context<Editor>,
16952 ) -> Task<Result<Vec<Completion>>> {
16953 self.update(cx, |project, cx| {
16954 let snippets = snippet_completions(project, buffer, buffer_position, cx);
16955 let project_completions = project.completions(buffer, buffer_position, options, cx);
16956 cx.background_spawn(async move {
16957 let mut completions = project_completions.await?;
16958 let snippets_completions = snippets.await?;
16959 completions.extend(snippets_completions);
16960 Ok(completions)
16961 })
16962 })
16963 }
16964
16965 fn resolve_completions(
16966 &self,
16967 buffer: Entity<Buffer>,
16968 completion_indices: Vec<usize>,
16969 completions: Rc<RefCell<Box<[Completion]>>>,
16970 cx: &mut Context<Editor>,
16971 ) -> Task<Result<bool>> {
16972 self.update(cx, |project, cx| {
16973 project.lsp_store().update(cx, |lsp_store, cx| {
16974 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
16975 })
16976 })
16977 }
16978
16979 fn apply_additional_edits_for_completion(
16980 &self,
16981 buffer: Entity<Buffer>,
16982 completions: Rc<RefCell<Box<[Completion]>>>,
16983 completion_index: usize,
16984 push_to_history: bool,
16985 cx: &mut Context<Editor>,
16986 ) -> Task<Result<Option<language::Transaction>>> {
16987 self.update(cx, |project, cx| {
16988 project.lsp_store().update(cx, |lsp_store, cx| {
16989 lsp_store.apply_additional_edits_for_completion(
16990 buffer,
16991 completions,
16992 completion_index,
16993 push_to_history,
16994 cx,
16995 )
16996 })
16997 })
16998 }
16999
17000 fn is_completion_trigger(
17001 &self,
17002 buffer: &Entity<Buffer>,
17003 position: language::Anchor,
17004 text: &str,
17005 trigger_in_words: bool,
17006 cx: &mut Context<Editor>,
17007 ) -> bool {
17008 let mut chars = text.chars();
17009 let char = if let Some(char) = chars.next() {
17010 char
17011 } else {
17012 return false;
17013 };
17014 if chars.next().is_some() {
17015 return false;
17016 }
17017
17018 let buffer = buffer.read(cx);
17019 let snapshot = buffer.snapshot();
17020 if !snapshot.settings_at(position, cx).show_completions_on_input {
17021 return false;
17022 }
17023 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17024 if trigger_in_words && classifier.is_word(char) {
17025 return true;
17026 }
17027
17028 buffer.completion_triggers().contains(text)
17029 }
17030}
17031
17032impl SemanticsProvider for Entity<Project> {
17033 fn hover(
17034 &self,
17035 buffer: &Entity<Buffer>,
17036 position: text::Anchor,
17037 cx: &mut App,
17038 ) -> Option<Task<Vec<project::Hover>>> {
17039 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17040 }
17041
17042 fn document_highlights(
17043 &self,
17044 buffer: &Entity<Buffer>,
17045 position: text::Anchor,
17046 cx: &mut App,
17047 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17048 Some(self.update(cx, |project, cx| {
17049 project.document_highlights(buffer, position, cx)
17050 }))
17051 }
17052
17053 fn definitions(
17054 &self,
17055 buffer: &Entity<Buffer>,
17056 position: text::Anchor,
17057 kind: GotoDefinitionKind,
17058 cx: &mut App,
17059 ) -> Option<Task<Result<Vec<LocationLink>>>> {
17060 Some(self.update(cx, |project, cx| match kind {
17061 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17062 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17063 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17064 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17065 }))
17066 }
17067
17068 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17069 // TODO: make this work for remote projects
17070 self.update(cx, |this, cx| {
17071 buffer.update(cx, |buffer, cx| {
17072 this.any_language_server_supports_inlay_hints(buffer, cx)
17073 })
17074 })
17075 }
17076
17077 fn inlay_hints(
17078 &self,
17079 buffer_handle: Entity<Buffer>,
17080 range: Range<text::Anchor>,
17081 cx: &mut App,
17082 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17083 Some(self.update(cx, |project, cx| {
17084 project.inlay_hints(buffer_handle, range, cx)
17085 }))
17086 }
17087
17088 fn resolve_inlay_hint(
17089 &self,
17090 hint: InlayHint,
17091 buffer_handle: Entity<Buffer>,
17092 server_id: LanguageServerId,
17093 cx: &mut App,
17094 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17095 Some(self.update(cx, |project, cx| {
17096 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17097 }))
17098 }
17099
17100 fn range_for_rename(
17101 &self,
17102 buffer: &Entity<Buffer>,
17103 position: text::Anchor,
17104 cx: &mut App,
17105 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17106 Some(self.update(cx, |project, cx| {
17107 let buffer = buffer.clone();
17108 let task = project.prepare_rename(buffer.clone(), position, cx);
17109 cx.spawn(|_, mut cx| async move {
17110 Ok(match task.await? {
17111 PrepareRenameResponse::Success(range) => Some(range),
17112 PrepareRenameResponse::InvalidPosition => None,
17113 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17114 // Fallback on using TreeSitter info to determine identifier range
17115 buffer.update(&mut cx, |buffer, _| {
17116 let snapshot = buffer.snapshot();
17117 let (range, kind) = snapshot.surrounding_word(position);
17118 if kind != Some(CharKind::Word) {
17119 return None;
17120 }
17121 Some(
17122 snapshot.anchor_before(range.start)
17123 ..snapshot.anchor_after(range.end),
17124 )
17125 })?
17126 }
17127 })
17128 })
17129 }))
17130 }
17131
17132 fn perform_rename(
17133 &self,
17134 buffer: &Entity<Buffer>,
17135 position: text::Anchor,
17136 new_name: String,
17137 cx: &mut App,
17138 ) -> Option<Task<Result<ProjectTransaction>>> {
17139 Some(self.update(cx, |project, cx| {
17140 project.perform_rename(buffer.clone(), position, new_name, cx)
17141 }))
17142 }
17143}
17144
17145fn inlay_hint_settings(
17146 location: Anchor,
17147 snapshot: &MultiBufferSnapshot,
17148 cx: &mut Context<Editor>,
17149) -> InlayHintSettings {
17150 let file = snapshot.file_at(location);
17151 let language = snapshot.language_at(location).map(|l| l.name());
17152 language_settings(language, file, cx).inlay_hints
17153}
17154
17155fn consume_contiguous_rows(
17156 contiguous_row_selections: &mut Vec<Selection<Point>>,
17157 selection: &Selection<Point>,
17158 display_map: &DisplaySnapshot,
17159 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17160) -> (MultiBufferRow, MultiBufferRow) {
17161 contiguous_row_selections.push(selection.clone());
17162 let start_row = MultiBufferRow(selection.start.row);
17163 let mut end_row = ending_row(selection, display_map);
17164
17165 while let Some(next_selection) = selections.peek() {
17166 if next_selection.start.row <= end_row.0 {
17167 end_row = ending_row(next_selection, display_map);
17168 contiguous_row_selections.push(selections.next().unwrap().clone());
17169 } else {
17170 break;
17171 }
17172 }
17173 (start_row, end_row)
17174}
17175
17176fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17177 if next_selection.end.column > 0 || next_selection.is_empty() {
17178 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17179 } else {
17180 MultiBufferRow(next_selection.end.row)
17181 }
17182}
17183
17184impl EditorSnapshot {
17185 pub fn remote_selections_in_range<'a>(
17186 &'a self,
17187 range: &'a Range<Anchor>,
17188 collaboration_hub: &dyn CollaborationHub,
17189 cx: &'a App,
17190 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17191 let participant_names = collaboration_hub.user_names(cx);
17192 let participant_indices = collaboration_hub.user_participant_indices(cx);
17193 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17194 let collaborators_by_replica_id = collaborators_by_peer_id
17195 .iter()
17196 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17197 .collect::<HashMap<_, _>>();
17198 self.buffer_snapshot
17199 .selections_in_range(range, false)
17200 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17201 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17202 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17203 let user_name = participant_names.get(&collaborator.user_id).cloned();
17204 Some(RemoteSelection {
17205 replica_id,
17206 selection,
17207 cursor_shape,
17208 line_mode,
17209 participant_index,
17210 peer_id: collaborator.peer_id,
17211 user_name,
17212 })
17213 })
17214 }
17215
17216 pub fn hunks_for_ranges(
17217 &self,
17218 ranges: impl IntoIterator<Item = Range<Point>>,
17219 ) -> Vec<MultiBufferDiffHunk> {
17220 let mut hunks = Vec::new();
17221 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17222 HashMap::default();
17223 for query_range in ranges {
17224 let query_rows =
17225 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17226 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17227 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17228 ) {
17229 // Include deleted hunks that are adjacent to the query range, because
17230 // otherwise they would be missed.
17231 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17232 if hunk.status().is_deleted() {
17233 intersects_range |= hunk.row_range.start == query_rows.end;
17234 intersects_range |= hunk.row_range.end == query_rows.start;
17235 }
17236 if intersects_range {
17237 if !processed_buffer_rows
17238 .entry(hunk.buffer_id)
17239 .or_default()
17240 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17241 {
17242 continue;
17243 }
17244 hunks.push(hunk);
17245 }
17246 }
17247 }
17248
17249 hunks
17250 }
17251
17252 fn display_diff_hunks_for_rows<'a>(
17253 &'a self,
17254 display_rows: Range<DisplayRow>,
17255 folded_buffers: &'a HashSet<BufferId>,
17256 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17257 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17258 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17259
17260 self.buffer_snapshot
17261 .diff_hunks_in_range(buffer_start..buffer_end)
17262 .filter_map(|hunk| {
17263 if folded_buffers.contains(&hunk.buffer_id) {
17264 return None;
17265 }
17266
17267 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17268 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17269
17270 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17271 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17272
17273 let display_hunk = if hunk_display_start.column() != 0 {
17274 DisplayDiffHunk::Folded {
17275 display_row: hunk_display_start.row(),
17276 }
17277 } else {
17278 let mut end_row = hunk_display_end.row();
17279 if hunk_display_end.column() > 0 {
17280 end_row.0 += 1;
17281 }
17282 let is_created_file = hunk.is_created_file();
17283 DisplayDiffHunk::Unfolded {
17284 status: hunk.status(),
17285 diff_base_byte_range: hunk.diff_base_byte_range,
17286 display_row_range: hunk_display_start.row()..end_row,
17287 multi_buffer_range: Anchor::range_in_buffer(
17288 hunk.excerpt_id,
17289 hunk.buffer_id,
17290 hunk.buffer_range,
17291 ),
17292 is_created_file,
17293 }
17294 };
17295
17296 Some(display_hunk)
17297 })
17298 }
17299
17300 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17301 self.display_snapshot.buffer_snapshot.language_at(position)
17302 }
17303
17304 pub fn is_focused(&self) -> bool {
17305 self.is_focused
17306 }
17307
17308 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17309 self.placeholder_text.as_ref()
17310 }
17311
17312 pub fn scroll_position(&self) -> gpui::Point<f32> {
17313 self.scroll_anchor.scroll_position(&self.display_snapshot)
17314 }
17315
17316 fn gutter_dimensions(
17317 &self,
17318 font_id: FontId,
17319 font_size: Pixels,
17320 max_line_number_width: Pixels,
17321 cx: &App,
17322 ) -> Option<GutterDimensions> {
17323 if !self.show_gutter {
17324 return None;
17325 }
17326
17327 let descent = cx.text_system().descent(font_id, font_size);
17328 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17329 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17330
17331 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17332 matches!(
17333 ProjectSettings::get_global(cx).git.git_gutter,
17334 Some(GitGutterSetting::TrackedFiles)
17335 )
17336 });
17337 let gutter_settings = EditorSettings::get_global(cx).gutter;
17338 let show_line_numbers = self
17339 .show_line_numbers
17340 .unwrap_or(gutter_settings.line_numbers);
17341 let line_gutter_width = if show_line_numbers {
17342 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17343 let min_width_for_number_on_gutter = em_advance * 4.0;
17344 max_line_number_width.max(min_width_for_number_on_gutter)
17345 } else {
17346 0.0.into()
17347 };
17348
17349 let show_code_actions = self
17350 .show_code_actions
17351 .unwrap_or(gutter_settings.code_actions);
17352
17353 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17354
17355 let git_blame_entries_width =
17356 self.git_blame_gutter_max_author_length
17357 .map(|max_author_length| {
17358 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17359
17360 /// The number of characters to dedicate to gaps and margins.
17361 const SPACING_WIDTH: usize = 4;
17362
17363 let max_char_count = max_author_length
17364 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17365 + ::git::SHORT_SHA_LENGTH
17366 + MAX_RELATIVE_TIMESTAMP.len()
17367 + SPACING_WIDTH;
17368
17369 em_advance * max_char_count
17370 });
17371
17372 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17373 left_padding += if show_code_actions || show_runnables {
17374 em_width * 3.0
17375 } else if show_git_gutter && show_line_numbers {
17376 em_width * 2.0
17377 } else if show_git_gutter || show_line_numbers {
17378 em_width
17379 } else {
17380 px(0.)
17381 };
17382
17383 let right_padding = if gutter_settings.folds && show_line_numbers {
17384 em_width * 4.0
17385 } else if gutter_settings.folds {
17386 em_width * 3.0
17387 } else if show_line_numbers {
17388 em_width
17389 } else {
17390 px(0.)
17391 };
17392
17393 Some(GutterDimensions {
17394 left_padding,
17395 right_padding,
17396 width: line_gutter_width + left_padding + right_padding,
17397 margin: -descent,
17398 git_blame_entries_width,
17399 })
17400 }
17401
17402 pub fn render_crease_toggle(
17403 &self,
17404 buffer_row: MultiBufferRow,
17405 row_contains_cursor: bool,
17406 editor: Entity<Editor>,
17407 window: &mut Window,
17408 cx: &mut App,
17409 ) -> Option<AnyElement> {
17410 let folded = self.is_line_folded(buffer_row);
17411 let mut is_foldable = false;
17412
17413 if let Some(crease) = self
17414 .crease_snapshot
17415 .query_row(buffer_row, &self.buffer_snapshot)
17416 {
17417 is_foldable = true;
17418 match crease {
17419 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17420 if let Some(render_toggle) = render_toggle {
17421 let toggle_callback =
17422 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17423 if folded {
17424 editor.update(cx, |editor, cx| {
17425 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17426 });
17427 } else {
17428 editor.update(cx, |editor, cx| {
17429 editor.unfold_at(
17430 &crate::UnfoldAt { buffer_row },
17431 window,
17432 cx,
17433 )
17434 });
17435 }
17436 });
17437 return Some((render_toggle)(
17438 buffer_row,
17439 folded,
17440 toggle_callback,
17441 window,
17442 cx,
17443 ));
17444 }
17445 }
17446 }
17447 }
17448
17449 is_foldable |= self.starts_indent(buffer_row);
17450
17451 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17452 Some(
17453 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17454 .toggle_state(folded)
17455 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17456 if folded {
17457 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17458 } else {
17459 this.fold_at(&FoldAt { buffer_row }, window, cx);
17460 }
17461 }))
17462 .into_any_element(),
17463 )
17464 } else {
17465 None
17466 }
17467 }
17468
17469 pub fn render_crease_trailer(
17470 &self,
17471 buffer_row: MultiBufferRow,
17472 window: &mut Window,
17473 cx: &mut App,
17474 ) -> Option<AnyElement> {
17475 let folded = self.is_line_folded(buffer_row);
17476 if let Crease::Inline { render_trailer, .. } = self
17477 .crease_snapshot
17478 .query_row(buffer_row, &self.buffer_snapshot)?
17479 {
17480 let render_trailer = render_trailer.as_ref()?;
17481 Some(render_trailer(buffer_row, folded, window, cx))
17482 } else {
17483 None
17484 }
17485 }
17486}
17487
17488impl Deref for EditorSnapshot {
17489 type Target = DisplaySnapshot;
17490
17491 fn deref(&self) -> &Self::Target {
17492 &self.display_snapshot
17493 }
17494}
17495
17496#[derive(Clone, Debug, PartialEq, Eq)]
17497pub enum EditorEvent {
17498 InputIgnored {
17499 text: Arc<str>,
17500 },
17501 InputHandled {
17502 utf16_range_to_replace: Option<Range<isize>>,
17503 text: Arc<str>,
17504 },
17505 ExcerptsAdded {
17506 buffer: Entity<Buffer>,
17507 predecessor: ExcerptId,
17508 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17509 },
17510 ExcerptsRemoved {
17511 ids: Vec<ExcerptId>,
17512 },
17513 BufferFoldToggled {
17514 ids: Vec<ExcerptId>,
17515 folded: bool,
17516 },
17517 ExcerptsEdited {
17518 ids: Vec<ExcerptId>,
17519 },
17520 ExcerptsExpanded {
17521 ids: Vec<ExcerptId>,
17522 },
17523 BufferEdited,
17524 Edited {
17525 transaction_id: clock::Lamport,
17526 },
17527 Reparsed(BufferId),
17528 Focused,
17529 FocusedIn,
17530 Blurred,
17531 DirtyChanged,
17532 Saved,
17533 TitleChanged,
17534 DiffBaseChanged,
17535 SelectionsChanged {
17536 local: bool,
17537 },
17538 ScrollPositionChanged {
17539 local: bool,
17540 autoscroll: bool,
17541 },
17542 Closed,
17543 TransactionUndone {
17544 transaction_id: clock::Lamport,
17545 },
17546 TransactionBegun {
17547 transaction_id: clock::Lamport,
17548 },
17549 Reloaded,
17550 CursorShapeChanged,
17551}
17552
17553impl EventEmitter<EditorEvent> for Editor {}
17554
17555impl Focusable for Editor {
17556 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17557 self.focus_handle.clone()
17558 }
17559}
17560
17561impl Render for Editor {
17562 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17563 let settings = ThemeSettings::get_global(cx);
17564
17565 let mut text_style = match self.mode {
17566 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17567 color: cx.theme().colors().editor_foreground,
17568 font_family: settings.ui_font.family.clone(),
17569 font_features: settings.ui_font.features.clone(),
17570 font_fallbacks: settings.ui_font.fallbacks.clone(),
17571 font_size: rems(0.875).into(),
17572 font_weight: settings.ui_font.weight,
17573 line_height: relative(settings.buffer_line_height.value()),
17574 ..Default::default()
17575 },
17576 EditorMode::Full => TextStyle {
17577 color: cx.theme().colors().editor_foreground,
17578 font_family: settings.buffer_font.family.clone(),
17579 font_features: settings.buffer_font.features.clone(),
17580 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17581 font_size: settings.buffer_font_size(cx).into(),
17582 font_weight: settings.buffer_font.weight,
17583 line_height: relative(settings.buffer_line_height.value()),
17584 ..Default::default()
17585 },
17586 };
17587 if let Some(text_style_refinement) = &self.text_style_refinement {
17588 text_style.refine(text_style_refinement)
17589 }
17590
17591 let background = match self.mode {
17592 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17593 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17594 EditorMode::Full => cx.theme().colors().editor_background,
17595 };
17596
17597 EditorElement::new(
17598 &cx.entity(),
17599 EditorStyle {
17600 background,
17601 local_player: cx.theme().players().local(),
17602 text: text_style,
17603 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17604 syntax: cx.theme().syntax().clone(),
17605 status: cx.theme().status().clone(),
17606 inlay_hints_style: make_inlay_hints_style(cx),
17607 inline_completion_styles: make_suggestion_styles(cx),
17608 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17609 },
17610 )
17611 }
17612}
17613
17614impl EntityInputHandler for Editor {
17615 fn text_for_range(
17616 &mut self,
17617 range_utf16: Range<usize>,
17618 adjusted_range: &mut Option<Range<usize>>,
17619 _: &mut Window,
17620 cx: &mut Context<Self>,
17621 ) -> Option<String> {
17622 let snapshot = self.buffer.read(cx).read(cx);
17623 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17624 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17625 if (start.0..end.0) != range_utf16 {
17626 adjusted_range.replace(start.0..end.0);
17627 }
17628 Some(snapshot.text_for_range(start..end).collect())
17629 }
17630
17631 fn selected_text_range(
17632 &mut self,
17633 ignore_disabled_input: bool,
17634 _: &mut Window,
17635 cx: &mut Context<Self>,
17636 ) -> Option<UTF16Selection> {
17637 // Prevent the IME menu from appearing when holding down an alphabetic key
17638 // while input is disabled.
17639 if !ignore_disabled_input && !self.input_enabled {
17640 return None;
17641 }
17642
17643 let selection = self.selections.newest::<OffsetUtf16>(cx);
17644 let range = selection.range();
17645
17646 Some(UTF16Selection {
17647 range: range.start.0..range.end.0,
17648 reversed: selection.reversed,
17649 })
17650 }
17651
17652 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17653 let snapshot = self.buffer.read(cx).read(cx);
17654 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17655 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17656 }
17657
17658 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17659 self.clear_highlights::<InputComposition>(cx);
17660 self.ime_transaction.take();
17661 }
17662
17663 fn replace_text_in_range(
17664 &mut self,
17665 range_utf16: Option<Range<usize>>,
17666 text: &str,
17667 window: &mut Window,
17668 cx: &mut Context<Self>,
17669 ) {
17670 if !self.input_enabled {
17671 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17672 return;
17673 }
17674
17675 self.transact(window, cx, |this, window, cx| {
17676 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17677 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17678 Some(this.selection_replacement_ranges(range_utf16, cx))
17679 } else {
17680 this.marked_text_ranges(cx)
17681 };
17682
17683 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17684 let newest_selection_id = this.selections.newest_anchor().id;
17685 this.selections
17686 .all::<OffsetUtf16>(cx)
17687 .iter()
17688 .zip(ranges_to_replace.iter())
17689 .find_map(|(selection, range)| {
17690 if selection.id == newest_selection_id {
17691 Some(
17692 (range.start.0 as isize - selection.head().0 as isize)
17693 ..(range.end.0 as isize - selection.head().0 as isize),
17694 )
17695 } else {
17696 None
17697 }
17698 })
17699 });
17700
17701 cx.emit(EditorEvent::InputHandled {
17702 utf16_range_to_replace: range_to_replace,
17703 text: text.into(),
17704 });
17705
17706 if let Some(new_selected_ranges) = new_selected_ranges {
17707 this.change_selections(None, window, cx, |selections| {
17708 selections.select_ranges(new_selected_ranges)
17709 });
17710 this.backspace(&Default::default(), window, cx);
17711 }
17712
17713 this.handle_input(text, window, cx);
17714 });
17715
17716 if let Some(transaction) = self.ime_transaction {
17717 self.buffer.update(cx, |buffer, cx| {
17718 buffer.group_until_transaction(transaction, cx);
17719 });
17720 }
17721
17722 self.unmark_text(window, cx);
17723 }
17724
17725 fn replace_and_mark_text_in_range(
17726 &mut self,
17727 range_utf16: Option<Range<usize>>,
17728 text: &str,
17729 new_selected_range_utf16: Option<Range<usize>>,
17730 window: &mut Window,
17731 cx: &mut Context<Self>,
17732 ) {
17733 if !self.input_enabled {
17734 return;
17735 }
17736
17737 let transaction = self.transact(window, cx, |this, window, cx| {
17738 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17739 let snapshot = this.buffer.read(cx).read(cx);
17740 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17741 for marked_range in &mut marked_ranges {
17742 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17743 marked_range.start.0 += relative_range_utf16.start;
17744 marked_range.start =
17745 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17746 marked_range.end =
17747 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17748 }
17749 }
17750 Some(marked_ranges)
17751 } else if let Some(range_utf16) = range_utf16 {
17752 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17753 Some(this.selection_replacement_ranges(range_utf16, cx))
17754 } else {
17755 None
17756 };
17757
17758 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17759 let newest_selection_id = this.selections.newest_anchor().id;
17760 this.selections
17761 .all::<OffsetUtf16>(cx)
17762 .iter()
17763 .zip(ranges_to_replace.iter())
17764 .find_map(|(selection, range)| {
17765 if selection.id == newest_selection_id {
17766 Some(
17767 (range.start.0 as isize - selection.head().0 as isize)
17768 ..(range.end.0 as isize - selection.head().0 as isize),
17769 )
17770 } else {
17771 None
17772 }
17773 })
17774 });
17775
17776 cx.emit(EditorEvent::InputHandled {
17777 utf16_range_to_replace: range_to_replace,
17778 text: text.into(),
17779 });
17780
17781 if let Some(ranges) = ranges_to_replace {
17782 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17783 }
17784
17785 let marked_ranges = {
17786 let snapshot = this.buffer.read(cx).read(cx);
17787 this.selections
17788 .disjoint_anchors()
17789 .iter()
17790 .map(|selection| {
17791 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17792 })
17793 .collect::<Vec<_>>()
17794 };
17795
17796 if text.is_empty() {
17797 this.unmark_text(window, cx);
17798 } else {
17799 this.highlight_text::<InputComposition>(
17800 marked_ranges.clone(),
17801 HighlightStyle {
17802 underline: Some(UnderlineStyle {
17803 thickness: px(1.),
17804 color: None,
17805 wavy: false,
17806 }),
17807 ..Default::default()
17808 },
17809 cx,
17810 );
17811 }
17812
17813 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17814 let use_autoclose = this.use_autoclose;
17815 let use_auto_surround = this.use_auto_surround;
17816 this.set_use_autoclose(false);
17817 this.set_use_auto_surround(false);
17818 this.handle_input(text, window, cx);
17819 this.set_use_autoclose(use_autoclose);
17820 this.set_use_auto_surround(use_auto_surround);
17821
17822 if let Some(new_selected_range) = new_selected_range_utf16 {
17823 let snapshot = this.buffer.read(cx).read(cx);
17824 let new_selected_ranges = marked_ranges
17825 .into_iter()
17826 .map(|marked_range| {
17827 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17828 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17829 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17830 snapshot.clip_offset_utf16(new_start, Bias::Left)
17831 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17832 })
17833 .collect::<Vec<_>>();
17834
17835 drop(snapshot);
17836 this.change_selections(None, window, cx, |selections| {
17837 selections.select_ranges(new_selected_ranges)
17838 });
17839 }
17840 });
17841
17842 self.ime_transaction = self.ime_transaction.or(transaction);
17843 if let Some(transaction) = self.ime_transaction {
17844 self.buffer.update(cx, |buffer, cx| {
17845 buffer.group_until_transaction(transaction, cx);
17846 });
17847 }
17848
17849 if self.text_highlights::<InputComposition>(cx).is_none() {
17850 self.ime_transaction.take();
17851 }
17852 }
17853
17854 fn bounds_for_range(
17855 &mut self,
17856 range_utf16: Range<usize>,
17857 element_bounds: gpui::Bounds<Pixels>,
17858 window: &mut Window,
17859 cx: &mut Context<Self>,
17860 ) -> Option<gpui::Bounds<Pixels>> {
17861 let text_layout_details = self.text_layout_details(window);
17862 let gpui::Size {
17863 width: em_width,
17864 height: line_height,
17865 } = self.character_size(window);
17866
17867 let snapshot = self.snapshot(window, cx);
17868 let scroll_position = snapshot.scroll_position();
17869 let scroll_left = scroll_position.x * em_width;
17870
17871 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17872 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17873 + self.gutter_dimensions.width
17874 + self.gutter_dimensions.margin;
17875 let y = line_height * (start.row().as_f32() - scroll_position.y);
17876
17877 Some(Bounds {
17878 origin: element_bounds.origin + point(x, y),
17879 size: size(em_width, line_height),
17880 })
17881 }
17882
17883 fn character_index_for_point(
17884 &mut self,
17885 point: gpui::Point<Pixels>,
17886 _window: &mut Window,
17887 _cx: &mut Context<Self>,
17888 ) -> Option<usize> {
17889 let position_map = self.last_position_map.as_ref()?;
17890 if !position_map.text_hitbox.contains(&point) {
17891 return None;
17892 }
17893 let display_point = position_map.point_for_position(point).previous_valid;
17894 let anchor = position_map
17895 .snapshot
17896 .display_point_to_anchor(display_point, Bias::Left);
17897 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17898 Some(utf16_offset.0)
17899 }
17900}
17901
17902trait SelectionExt {
17903 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17904 fn spanned_rows(
17905 &self,
17906 include_end_if_at_line_start: bool,
17907 map: &DisplaySnapshot,
17908 ) -> Range<MultiBufferRow>;
17909}
17910
17911impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17912 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17913 let start = self
17914 .start
17915 .to_point(&map.buffer_snapshot)
17916 .to_display_point(map);
17917 let end = self
17918 .end
17919 .to_point(&map.buffer_snapshot)
17920 .to_display_point(map);
17921 if self.reversed {
17922 end..start
17923 } else {
17924 start..end
17925 }
17926 }
17927
17928 fn spanned_rows(
17929 &self,
17930 include_end_if_at_line_start: bool,
17931 map: &DisplaySnapshot,
17932 ) -> Range<MultiBufferRow> {
17933 let start = self.start.to_point(&map.buffer_snapshot);
17934 let mut end = self.end.to_point(&map.buffer_snapshot);
17935 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
17936 end.row -= 1;
17937 }
17938
17939 let buffer_start = map.prev_line_boundary(start).0;
17940 let buffer_end = map.next_line_boundary(end).0;
17941 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
17942 }
17943}
17944
17945impl<T: InvalidationRegion> InvalidationStack<T> {
17946 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
17947 where
17948 S: Clone + ToOffset,
17949 {
17950 while let Some(region) = self.last() {
17951 let all_selections_inside_invalidation_ranges =
17952 if selections.len() == region.ranges().len() {
17953 selections
17954 .iter()
17955 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
17956 .all(|(selection, invalidation_range)| {
17957 let head = selection.head().to_offset(buffer);
17958 invalidation_range.start <= head && invalidation_range.end >= head
17959 })
17960 } else {
17961 false
17962 };
17963
17964 if all_selections_inside_invalidation_ranges {
17965 break;
17966 } else {
17967 self.pop();
17968 }
17969 }
17970 }
17971}
17972
17973impl<T> Default for InvalidationStack<T> {
17974 fn default() -> Self {
17975 Self(Default::default())
17976 }
17977}
17978
17979impl<T> Deref for InvalidationStack<T> {
17980 type Target = Vec<T>;
17981
17982 fn deref(&self) -> &Self::Target {
17983 &self.0
17984 }
17985}
17986
17987impl<T> DerefMut for InvalidationStack<T> {
17988 fn deref_mut(&mut self) -> &mut Self::Target {
17989 &mut self.0
17990 }
17991}
17992
17993impl InvalidationRegion for SnippetState {
17994 fn ranges(&self) -> &[Range<Anchor>] {
17995 &self.ranges[self.active_index]
17996 }
17997}
17998
17999pub fn diagnostic_block_renderer(
18000 diagnostic: Diagnostic,
18001 max_message_rows: Option<u8>,
18002 allow_closing: bool,
18003) -> RenderBlock {
18004 let (text_without_backticks, code_ranges) =
18005 highlight_diagnostic_message(&diagnostic, max_message_rows);
18006
18007 Arc::new(move |cx: &mut BlockContext| {
18008 let group_id: SharedString = cx.block_id.to_string().into();
18009
18010 let mut text_style = cx.window.text_style().clone();
18011 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18012 let theme_settings = ThemeSettings::get_global(cx);
18013 text_style.font_family = theme_settings.buffer_font.family.clone();
18014 text_style.font_style = theme_settings.buffer_font.style;
18015 text_style.font_features = theme_settings.buffer_font.features.clone();
18016 text_style.font_weight = theme_settings.buffer_font.weight;
18017
18018 let multi_line_diagnostic = diagnostic.message.contains('\n');
18019
18020 let buttons = |diagnostic: &Diagnostic| {
18021 if multi_line_diagnostic {
18022 v_flex()
18023 } else {
18024 h_flex()
18025 }
18026 .when(allow_closing, |div| {
18027 div.children(diagnostic.is_primary.then(|| {
18028 IconButton::new("close-block", IconName::XCircle)
18029 .icon_color(Color::Muted)
18030 .size(ButtonSize::Compact)
18031 .style(ButtonStyle::Transparent)
18032 .visible_on_hover(group_id.clone())
18033 .on_click(move |_click, window, cx| {
18034 window.dispatch_action(Box::new(Cancel), cx)
18035 })
18036 .tooltip(|window, cx| {
18037 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18038 })
18039 }))
18040 })
18041 .child(
18042 IconButton::new("copy-block", IconName::Copy)
18043 .icon_color(Color::Muted)
18044 .size(ButtonSize::Compact)
18045 .style(ButtonStyle::Transparent)
18046 .visible_on_hover(group_id.clone())
18047 .on_click({
18048 let message = diagnostic.message.clone();
18049 move |_click, _, cx| {
18050 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18051 }
18052 })
18053 .tooltip(Tooltip::text("Copy diagnostic message")),
18054 )
18055 };
18056
18057 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18058 AvailableSpace::min_size(),
18059 cx.window,
18060 cx.app,
18061 );
18062
18063 h_flex()
18064 .id(cx.block_id)
18065 .group(group_id.clone())
18066 .relative()
18067 .size_full()
18068 .block_mouse_down()
18069 .pl(cx.gutter_dimensions.width)
18070 .w(cx.max_width - cx.gutter_dimensions.full_width())
18071 .child(
18072 div()
18073 .flex()
18074 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18075 .flex_shrink(),
18076 )
18077 .child(buttons(&diagnostic))
18078 .child(div().flex().flex_shrink_0().child(
18079 StyledText::new(text_without_backticks.clone()).with_default_highlights(
18080 &text_style,
18081 code_ranges.iter().map(|range| {
18082 (
18083 range.clone(),
18084 HighlightStyle {
18085 font_weight: Some(FontWeight::BOLD),
18086 ..Default::default()
18087 },
18088 )
18089 }),
18090 ),
18091 ))
18092 .into_any_element()
18093 })
18094}
18095
18096fn inline_completion_edit_text(
18097 current_snapshot: &BufferSnapshot,
18098 edits: &[(Range<Anchor>, String)],
18099 edit_preview: &EditPreview,
18100 include_deletions: bool,
18101 cx: &App,
18102) -> HighlightedText {
18103 let edits = edits
18104 .iter()
18105 .map(|(anchor, text)| {
18106 (
18107 anchor.start.text_anchor..anchor.end.text_anchor,
18108 text.clone(),
18109 )
18110 })
18111 .collect::<Vec<_>>();
18112
18113 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18114}
18115
18116pub fn highlight_diagnostic_message(
18117 diagnostic: &Diagnostic,
18118 mut max_message_rows: Option<u8>,
18119) -> (SharedString, Vec<Range<usize>>) {
18120 let mut text_without_backticks = String::new();
18121 let mut code_ranges = Vec::new();
18122
18123 if let Some(source) = &diagnostic.source {
18124 text_without_backticks.push_str(source);
18125 code_ranges.push(0..source.len());
18126 text_without_backticks.push_str(": ");
18127 }
18128
18129 let mut prev_offset = 0;
18130 let mut in_code_block = false;
18131 let has_row_limit = max_message_rows.is_some();
18132 let mut newline_indices = diagnostic
18133 .message
18134 .match_indices('\n')
18135 .filter(|_| has_row_limit)
18136 .map(|(ix, _)| ix)
18137 .fuse()
18138 .peekable();
18139
18140 for (quote_ix, _) in diagnostic
18141 .message
18142 .match_indices('`')
18143 .chain([(diagnostic.message.len(), "")])
18144 {
18145 let mut first_newline_ix = None;
18146 let mut last_newline_ix = None;
18147 while let Some(newline_ix) = newline_indices.peek() {
18148 if *newline_ix < quote_ix {
18149 if first_newline_ix.is_none() {
18150 first_newline_ix = Some(*newline_ix);
18151 }
18152 last_newline_ix = Some(*newline_ix);
18153
18154 if let Some(rows_left) = &mut max_message_rows {
18155 if *rows_left == 0 {
18156 break;
18157 } else {
18158 *rows_left -= 1;
18159 }
18160 }
18161 let _ = newline_indices.next();
18162 } else {
18163 break;
18164 }
18165 }
18166 let prev_len = text_without_backticks.len();
18167 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18168 text_without_backticks.push_str(new_text);
18169 if in_code_block {
18170 code_ranges.push(prev_len..text_without_backticks.len());
18171 }
18172 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18173 in_code_block = !in_code_block;
18174 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18175 text_without_backticks.push_str("...");
18176 break;
18177 }
18178 }
18179
18180 (text_without_backticks.into(), code_ranges)
18181}
18182
18183fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18184 match severity {
18185 DiagnosticSeverity::ERROR => colors.error,
18186 DiagnosticSeverity::WARNING => colors.warning,
18187 DiagnosticSeverity::INFORMATION => colors.info,
18188 DiagnosticSeverity::HINT => colors.info,
18189 _ => colors.ignored,
18190 }
18191}
18192
18193pub fn styled_runs_for_code_label<'a>(
18194 label: &'a CodeLabel,
18195 syntax_theme: &'a theme::SyntaxTheme,
18196) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18197 let fade_out = HighlightStyle {
18198 fade_out: Some(0.35),
18199 ..Default::default()
18200 };
18201
18202 let mut prev_end = label.filter_range.end;
18203 label
18204 .runs
18205 .iter()
18206 .enumerate()
18207 .flat_map(move |(ix, (range, highlight_id))| {
18208 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18209 style
18210 } else {
18211 return Default::default();
18212 };
18213 let mut muted_style = style;
18214 muted_style.highlight(fade_out);
18215
18216 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18217 if range.start >= label.filter_range.end {
18218 if range.start > prev_end {
18219 runs.push((prev_end..range.start, fade_out));
18220 }
18221 runs.push((range.clone(), muted_style));
18222 } else if range.end <= label.filter_range.end {
18223 runs.push((range.clone(), style));
18224 } else {
18225 runs.push((range.start..label.filter_range.end, style));
18226 runs.push((label.filter_range.end..range.end, muted_style));
18227 }
18228 prev_end = cmp::max(prev_end, range.end);
18229
18230 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18231 runs.push((prev_end..label.text.len(), fade_out));
18232 }
18233
18234 runs
18235 })
18236}
18237
18238pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18239 let mut prev_index = 0;
18240 let mut prev_codepoint: Option<char> = None;
18241 text.char_indices()
18242 .chain([(text.len(), '\0')])
18243 .filter_map(move |(index, codepoint)| {
18244 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18245 let is_boundary = index == text.len()
18246 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18247 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18248 if is_boundary {
18249 let chunk = &text[prev_index..index];
18250 prev_index = index;
18251 Some(chunk)
18252 } else {
18253 None
18254 }
18255 })
18256}
18257
18258pub trait RangeToAnchorExt: Sized {
18259 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18260
18261 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18262 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18263 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18264 }
18265}
18266
18267impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18268 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18269 let start_offset = self.start.to_offset(snapshot);
18270 let end_offset = self.end.to_offset(snapshot);
18271 if start_offset == end_offset {
18272 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18273 } else {
18274 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18275 }
18276 }
18277}
18278
18279pub trait RowExt {
18280 fn as_f32(&self) -> f32;
18281
18282 fn next_row(&self) -> Self;
18283
18284 fn previous_row(&self) -> Self;
18285
18286 fn minus(&self, other: Self) -> u32;
18287}
18288
18289impl RowExt for DisplayRow {
18290 fn as_f32(&self) -> f32 {
18291 self.0 as f32
18292 }
18293
18294 fn next_row(&self) -> Self {
18295 Self(self.0 + 1)
18296 }
18297
18298 fn previous_row(&self) -> Self {
18299 Self(self.0.saturating_sub(1))
18300 }
18301
18302 fn minus(&self, other: Self) -> u32 {
18303 self.0 - other.0
18304 }
18305}
18306
18307impl RowExt for MultiBufferRow {
18308 fn as_f32(&self) -> f32 {
18309 self.0 as f32
18310 }
18311
18312 fn next_row(&self) -> Self {
18313 Self(self.0 + 1)
18314 }
18315
18316 fn previous_row(&self) -> Self {
18317 Self(self.0.saturating_sub(1))
18318 }
18319
18320 fn minus(&self, other: Self) -> u32 {
18321 self.0 - other.0
18322 }
18323}
18324
18325trait RowRangeExt {
18326 type Row;
18327
18328 fn len(&self) -> usize;
18329
18330 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18331}
18332
18333impl RowRangeExt for Range<MultiBufferRow> {
18334 type Row = MultiBufferRow;
18335
18336 fn len(&self) -> usize {
18337 (self.end.0 - self.start.0) as usize
18338 }
18339
18340 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18341 (self.start.0..self.end.0).map(MultiBufferRow)
18342 }
18343}
18344
18345impl RowRangeExt for Range<DisplayRow> {
18346 type Row = DisplayRow;
18347
18348 fn len(&self) -> usize {
18349 (self.end.0 - self.start.0) as usize
18350 }
18351
18352 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18353 (self.start.0..self.end.0).map(DisplayRow)
18354 }
18355}
18356
18357/// If select range has more than one line, we
18358/// just point the cursor to range.start.
18359fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18360 if range.start.row == range.end.row {
18361 range
18362 } else {
18363 range.start..range.start
18364 }
18365}
18366pub struct KillRing(ClipboardItem);
18367impl Global for KillRing {}
18368
18369const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18370
18371fn all_edits_insertions_or_deletions(
18372 edits: &Vec<(Range<Anchor>, String)>,
18373 snapshot: &MultiBufferSnapshot,
18374) -> bool {
18375 let mut all_insertions = true;
18376 let mut all_deletions = true;
18377
18378 for (range, new_text) in edits.iter() {
18379 let range_is_empty = range.to_offset(&snapshot).is_empty();
18380 let text_is_empty = new_text.is_empty();
18381
18382 if range_is_empty != text_is_empty {
18383 if range_is_empty {
18384 all_deletions = false;
18385 } else {
18386 all_insertions = false;
18387 }
18388 } else {
18389 return false;
18390 }
18391
18392 if !all_insertions && !all_deletions {
18393 return false;
18394 }
18395 }
18396 all_insertions || all_deletions
18397}
18398
18399struct MissingEditPredictionKeybindingTooltip;
18400
18401impl Render for MissingEditPredictionKeybindingTooltip {
18402 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18403 ui::tooltip_container(window, cx, |container, _, cx| {
18404 container
18405 .flex_shrink_0()
18406 .max_w_80()
18407 .min_h(rems_from_px(124.))
18408 .justify_between()
18409 .child(
18410 v_flex()
18411 .flex_1()
18412 .text_ui_sm(cx)
18413 .child(Label::new("Conflict with Accept Keybinding"))
18414 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18415 )
18416 .child(
18417 h_flex()
18418 .pb_1()
18419 .gap_1()
18420 .items_end()
18421 .w_full()
18422 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18423 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18424 }))
18425 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18426 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18427 })),
18428 )
18429 })
18430 }
18431}
18432
18433#[derive(Debug, Clone, Copy, PartialEq)]
18434pub struct LineHighlight {
18435 pub background: Background,
18436 pub border: Option<gpui::Hsla>,
18437}
18438
18439impl From<Hsla> for LineHighlight {
18440 fn from(hsla: Hsla) -> Self {
18441 Self {
18442 background: hsla.into(),
18443 border: None,
18444 }
18445 }
18446}
18447
18448impl From<Background> for LineHighlight {
18449 fn from(background: Background) -> Self {
18450 Self {
18451 background,
18452 border: None,
18453 }
18454 }
18455}