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(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1577 if let Some(extension) = singleton_buffer
1578 .read(cx)
1579 .file()
1580 .and_then(|file| file.path().extension()?.to_str())
1581 {
1582 key_context.set("extension", extension.to_string());
1583 }
1584 } else {
1585 key_context.add("multibuffer");
1586 }
1587
1588 if has_active_edit_prediction {
1589 if self.edit_prediction_in_conflict() {
1590 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1591 } else {
1592 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1593 key_context.add("copilot_suggestion");
1594 }
1595 }
1596
1597 if self.selection_mark_mode {
1598 key_context.add("selection_mode");
1599 }
1600
1601 key_context
1602 }
1603
1604 pub fn edit_prediction_in_conflict(&self) -> bool {
1605 if !self.show_edit_predictions_in_menu() {
1606 return false;
1607 }
1608
1609 let showing_completions = self
1610 .context_menu
1611 .borrow()
1612 .as_ref()
1613 .map_or(false, |context| {
1614 matches!(context, CodeContextMenu::Completions(_))
1615 });
1616
1617 showing_completions
1618 || self.edit_prediction_requires_modifier()
1619 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1620 // bindings to insert tab characters.
1621 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1622 }
1623
1624 pub fn accept_edit_prediction_keybind(
1625 &self,
1626 window: &Window,
1627 cx: &App,
1628 ) -> AcceptEditPredictionBinding {
1629 let key_context = self.key_context_internal(true, window, cx);
1630 let in_conflict = self.edit_prediction_in_conflict();
1631
1632 AcceptEditPredictionBinding(
1633 window
1634 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1635 .into_iter()
1636 .filter(|binding| {
1637 !in_conflict
1638 || binding
1639 .keystrokes()
1640 .first()
1641 .map_or(false, |keystroke| keystroke.modifiers.modified())
1642 })
1643 .rev()
1644 .min_by_key(|binding| {
1645 binding
1646 .keystrokes()
1647 .first()
1648 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1649 }),
1650 )
1651 }
1652
1653 pub fn new_file(
1654 workspace: &mut Workspace,
1655 _: &workspace::NewFile,
1656 window: &mut Window,
1657 cx: &mut Context<Workspace>,
1658 ) {
1659 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1660 "Failed to create buffer",
1661 window,
1662 cx,
1663 |e, _, _| match e.error_code() {
1664 ErrorCode::RemoteUpgradeRequired => Some(format!(
1665 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1666 e.error_tag("required").unwrap_or("the latest version")
1667 )),
1668 _ => None,
1669 },
1670 );
1671 }
1672
1673 pub fn new_in_workspace(
1674 workspace: &mut Workspace,
1675 window: &mut Window,
1676 cx: &mut Context<Workspace>,
1677 ) -> Task<Result<Entity<Editor>>> {
1678 let project = workspace.project().clone();
1679 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1680
1681 cx.spawn_in(window, |workspace, mut cx| async move {
1682 let buffer = create.await?;
1683 workspace.update_in(&mut cx, |workspace, window, cx| {
1684 let editor =
1685 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1686 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1687 editor
1688 })
1689 })
1690 }
1691
1692 fn new_file_vertical(
1693 workspace: &mut Workspace,
1694 _: &workspace::NewFileSplitVertical,
1695 window: &mut Window,
1696 cx: &mut Context<Workspace>,
1697 ) {
1698 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1699 }
1700
1701 fn new_file_horizontal(
1702 workspace: &mut Workspace,
1703 _: &workspace::NewFileSplitHorizontal,
1704 window: &mut Window,
1705 cx: &mut Context<Workspace>,
1706 ) {
1707 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1708 }
1709
1710 fn new_file_in_direction(
1711 workspace: &mut Workspace,
1712 direction: SplitDirection,
1713 window: &mut Window,
1714 cx: &mut Context<Workspace>,
1715 ) {
1716 let project = workspace.project().clone();
1717 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1718
1719 cx.spawn_in(window, |workspace, mut cx| async move {
1720 let buffer = create.await?;
1721 workspace.update_in(&mut cx, move |workspace, window, cx| {
1722 workspace.split_item(
1723 direction,
1724 Box::new(
1725 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1726 ),
1727 window,
1728 cx,
1729 )
1730 })?;
1731 anyhow::Ok(())
1732 })
1733 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1734 match e.error_code() {
1735 ErrorCode::RemoteUpgradeRequired => Some(format!(
1736 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1737 e.error_tag("required").unwrap_or("the latest version")
1738 )),
1739 _ => None,
1740 }
1741 });
1742 }
1743
1744 pub fn leader_peer_id(&self) -> Option<PeerId> {
1745 self.leader_peer_id
1746 }
1747
1748 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1749 &self.buffer
1750 }
1751
1752 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1753 self.workspace.as_ref()?.0.upgrade()
1754 }
1755
1756 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1757 self.buffer().read(cx).title(cx)
1758 }
1759
1760 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1761 let git_blame_gutter_max_author_length = self
1762 .render_git_blame_gutter(cx)
1763 .then(|| {
1764 if let Some(blame) = self.blame.as_ref() {
1765 let max_author_length =
1766 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1767 Some(max_author_length)
1768 } else {
1769 None
1770 }
1771 })
1772 .flatten();
1773
1774 EditorSnapshot {
1775 mode: self.mode,
1776 show_gutter: self.show_gutter,
1777 show_line_numbers: self.show_line_numbers,
1778 show_git_diff_gutter: self.show_git_diff_gutter,
1779 show_code_actions: self.show_code_actions,
1780 show_runnables: self.show_runnables,
1781 git_blame_gutter_max_author_length,
1782 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1783 scroll_anchor: self.scroll_manager.anchor(),
1784 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1785 placeholder_text: self.placeholder_text.clone(),
1786 is_focused: self.focus_handle.is_focused(window),
1787 current_line_highlight: self
1788 .current_line_highlight
1789 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1790 gutter_hovered: self.gutter_hovered,
1791 }
1792 }
1793
1794 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1795 self.buffer.read(cx).language_at(point, cx)
1796 }
1797
1798 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1799 self.buffer.read(cx).read(cx).file_at(point).cloned()
1800 }
1801
1802 pub fn active_excerpt(
1803 &self,
1804 cx: &App,
1805 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1806 self.buffer
1807 .read(cx)
1808 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1809 }
1810
1811 pub fn mode(&self) -> EditorMode {
1812 self.mode
1813 }
1814
1815 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1816 self.collaboration_hub.as_deref()
1817 }
1818
1819 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1820 self.collaboration_hub = Some(hub);
1821 }
1822
1823 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1824 self.in_project_search = in_project_search;
1825 }
1826
1827 pub fn set_custom_context_menu(
1828 &mut self,
1829 f: impl 'static
1830 + Fn(
1831 &mut Self,
1832 DisplayPoint,
1833 &mut Window,
1834 &mut Context<Self>,
1835 ) -> Option<Entity<ui::ContextMenu>>,
1836 ) {
1837 self.custom_context_menu = Some(Box::new(f))
1838 }
1839
1840 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1841 self.completion_provider = provider;
1842 }
1843
1844 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1845 self.semantics_provider.clone()
1846 }
1847
1848 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1849 self.semantics_provider = provider;
1850 }
1851
1852 pub fn set_edit_prediction_provider<T>(
1853 &mut self,
1854 provider: Option<Entity<T>>,
1855 window: &mut Window,
1856 cx: &mut Context<Self>,
1857 ) where
1858 T: EditPredictionProvider,
1859 {
1860 self.edit_prediction_provider =
1861 provider.map(|provider| RegisteredInlineCompletionProvider {
1862 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1863 if this.focus_handle.is_focused(window) {
1864 this.update_visible_inline_completion(window, cx);
1865 }
1866 }),
1867 provider: Arc::new(provider),
1868 });
1869 self.update_edit_prediction_settings(cx);
1870 self.refresh_inline_completion(false, false, window, cx);
1871 }
1872
1873 pub fn placeholder_text(&self) -> Option<&str> {
1874 self.placeholder_text.as_deref()
1875 }
1876
1877 pub fn set_placeholder_text(
1878 &mut self,
1879 placeholder_text: impl Into<Arc<str>>,
1880 cx: &mut Context<Self>,
1881 ) {
1882 let placeholder_text = Some(placeholder_text.into());
1883 if self.placeholder_text != placeholder_text {
1884 self.placeholder_text = placeholder_text;
1885 cx.notify();
1886 }
1887 }
1888
1889 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1890 self.cursor_shape = cursor_shape;
1891
1892 // Disrupt blink for immediate user feedback that the cursor shape has changed
1893 self.blink_manager.update(cx, BlinkManager::show_cursor);
1894
1895 cx.notify();
1896 }
1897
1898 pub fn set_current_line_highlight(
1899 &mut self,
1900 current_line_highlight: Option<CurrentLineHighlight>,
1901 ) {
1902 self.current_line_highlight = current_line_highlight;
1903 }
1904
1905 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1906 self.collapse_matches = collapse_matches;
1907 }
1908
1909 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1910 let buffers = self.buffer.read(cx).all_buffers();
1911 let Some(project) = self.project.as_ref() else {
1912 return;
1913 };
1914 project.update(cx, |project, cx| {
1915 for buffer in buffers {
1916 self.registered_buffers
1917 .entry(buffer.read(cx).remote_id())
1918 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1919 }
1920 })
1921 }
1922
1923 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1924 if self.collapse_matches {
1925 return range.start..range.start;
1926 }
1927 range.clone()
1928 }
1929
1930 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1931 if self.display_map.read(cx).clip_at_line_ends != clip {
1932 self.display_map
1933 .update(cx, |map, _| map.clip_at_line_ends = clip);
1934 }
1935 }
1936
1937 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1938 self.input_enabled = input_enabled;
1939 }
1940
1941 pub fn set_inline_completions_hidden_for_vim_mode(
1942 &mut self,
1943 hidden: bool,
1944 window: &mut Window,
1945 cx: &mut Context<Self>,
1946 ) {
1947 if hidden != self.inline_completions_hidden_for_vim_mode {
1948 self.inline_completions_hidden_for_vim_mode = hidden;
1949 if hidden {
1950 self.update_visible_inline_completion(window, cx);
1951 } else {
1952 self.refresh_inline_completion(true, false, window, cx);
1953 }
1954 }
1955 }
1956
1957 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1958 self.menu_inline_completions_policy = value;
1959 }
1960
1961 pub fn set_autoindent(&mut self, autoindent: bool) {
1962 if autoindent {
1963 self.autoindent_mode = Some(AutoindentMode::EachLine);
1964 } else {
1965 self.autoindent_mode = None;
1966 }
1967 }
1968
1969 pub fn read_only(&self, cx: &App) -> bool {
1970 self.read_only || self.buffer.read(cx).read_only()
1971 }
1972
1973 pub fn set_read_only(&mut self, read_only: bool) {
1974 self.read_only = read_only;
1975 }
1976
1977 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1978 self.use_autoclose = autoclose;
1979 }
1980
1981 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1982 self.use_auto_surround = auto_surround;
1983 }
1984
1985 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1986 self.auto_replace_emoji_shortcode = auto_replace;
1987 }
1988
1989 pub fn toggle_edit_predictions(
1990 &mut self,
1991 _: &ToggleEditPrediction,
1992 window: &mut Window,
1993 cx: &mut Context<Self>,
1994 ) {
1995 if self.show_inline_completions_override.is_some() {
1996 self.set_show_edit_predictions(None, window, cx);
1997 } else {
1998 let show_edit_predictions = !self.edit_predictions_enabled();
1999 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2000 }
2001 }
2002
2003 pub fn set_show_edit_predictions(
2004 &mut self,
2005 show_edit_predictions: Option<bool>,
2006 window: &mut Window,
2007 cx: &mut Context<Self>,
2008 ) {
2009 self.show_inline_completions_override = show_edit_predictions;
2010 self.update_edit_prediction_settings(cx);
2011
2012 if let Some(false) = show_edit_predictions {
2013 self.discard_inline_completion(false, cx);
2014 } else {
2015 self.refresh_inline_completion(false, true, window, cx);
2016 }
2017 }
2018
2019 fn inline_completions_disabled_in_scope(
2020 &self,
2021 buffer: &Entity<Buffer>,
2022 buffer_position: language::Anchor,
2023 cx: &App,
2024 ) -> bool {
2025 let snapshot = buffer.read(cx).snapshot();
2026 let settings = snapshot.settings_at(buffer_position, cx);
2027
2028 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2029 return false;
2030 };
2031
2032 scope.override_name().map_or(false, |scope_name| {
2033 settings
2034 .edit_predictions_disabled_in
2035 .iter()
2036 .any(|s| s == scope_name)
2037 })
2038 }
2039
2040 pub fn set_use_modal_editing(&mut self, to: bool) {
2041 self.use_modal_editing = to;
2042 }
2043
2044 pub fn use_modal_editing(&self) -> bool {
2045 self.use_modal_editing
2046 }
2047
2048 fn selections_did_change(
2049 &mut self,
2050 local: bool,
2051 old_cursor_position: &Anchor,
2052 show_completions: bool,
2053 window: &mut Window,
2054 cx: &mut Context<Self>,
2055 ) {
2056 window.invalidate_character_coordinates();
2057
2058 // Copy selections to primary selection buffer
2059 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2060 if local {
2061 let selections = self.selections.all::<usize>(cx);
2062 let buffer_handle = self.buffer.read(cx).read(cx);
2063
2064 let mut text = String::new();
2065 for (index, selection) in selections.iter().enumerate() {
2066 let text_for_selection = buffer_handle
2067 .text_for_range(selection.start..selection.end)
2068 .collect::<String>();
2069
2070 text.push_str(&text_for_selection);
2071 if index != selections.len() - 1 {
2072 text.push('\n');
2073 }
2074 }
2075
2076 if !text.is_empty() {
2077 cx.write_to_primary(ClipboardItem::new_string(text));
2078 }
2079 }
2080
2081 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2082 self.buffer.update(cx, |buffer, cx| {
2083 buffer.set_active_selections(
2084 &self.selections.disjoint_anchors(),
2085 self.selections.line_mode,
2086 self.cursor_shape,
2087 cx,
2088 )
2089 });
2090 }
2091 let display_map = self
2092 .display_map
2093 .update(cx, |display_map, cx| display_map.snapshot(cx));
2094 let buffer = &display_map.buffer_snapshot;
2095 self.add_selections_state = None;
2096 self.select_next_state = None;
2097 self.select_prev_state = None;
2098 self.select_larger_syntax_node_stack.clear();
2099 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2100 self.snippet_stack
2101 .invalidate(&self.selections.disjoint_anchors(), buffer);
2102 self.take_rename(false, window, cx);
2103
2104 let new_cursor_position = self.selections.newest_anchor().head();
2105
2106 self.push_to_nav_history(
2107 *old_cursor_position,
2108 Some(new_cursor_position.to_point(buffer)),
2109 cx,
2110 );
2111
2112 if local {
2113 let new_cursor_position = self.selections.newest_anchor().head();
2114 let mut context_menu = self.context_menu.borrow_mut();
2115 let completion_menu = match context_menu.as_ref() {
2116 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2117 _ => {
2118 *context_menu = None;
2119 None
2120 }
2121 };
2122 if let Some(buffer_id) = new_cursor_position.buffer_id {
2123 if !self.registered_buffers.contains_key(&buffer_id) {
2124 if let Some(project) = self.project.as_ref() {
2125 project.update(cx, |project, cx| {
2126 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2127 return;
2128 };
2129 self.registered_buffers.insert(
2130 buffer_id,
2131 project.register_buffer_with_language_servers(&buffer, cx),
2132 );
2133 })
2134 }
2135 }
2136 }
2137
2138 if let Some(completion_menu) = completion_menu {
2139 let cursor_position = new_cursor_position.to_offset(buffer);
2140 let (word_range, kind) =
2141 buffer.surrounding_word(completion_menu.initial_position, true);
2142 if kind == Some(CharKind::Word)
2143 && word_range.to_inclusive().contains(&cursor_position)
2144 {
2145 let mut completion_menu = completion_menu.clone();
2146 drop(context_menu);
2147
2148 let query = Self::completion_query(buffer, cursor_position);
2149 cx.spawn(move |this, mut cx| async move {
2150 completion_menu
2151 .filter(query.as_deref(), cx.background_executor().clone())
2152 .await;
2153
2154 this.update(&mut cx, |this, cx| {
2155 let mut context_menu = this.context_menu.borrow_mut();
2156 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2157 else {
2158 return;
2159 };
2160
2161 if menu.id > completion_menu.id {
2162 return;
2163 }
2164
2165 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2166 drop(context_menu);
2167 cx.notify();
2168 })
2169 })
2170 .detach();
2171
2172 if show_completions {
2173 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2174 }
2175 } else {
2176 drop(context_menu);
2177 self.hide_context_menu(window, cx);
2178 }
2179 } else {
2180 drop(context_menu);
2181 }
2182
2183 hide_hover(self, cx);
2184
2185 if old_cursor_position.to_display_point(&display_map).row()
2186 != new_cursor_position.to_display_point(&display_map).row()
2187 {
2188 self.available_code_actions.take();
2189 }
2190 self.refresh_code_actions(window, cx);
2191 self.refresh_document_highlights(cx);
2192 self.refresh_selected_text_highlights(window, cx);
2193 refresh_matching_bracket_highlights(self, window, cx);
2194 self.update_visible_inline_completion(window, cx);
2195 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2196 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2197 if self.git_blame_inline_enabled {
2198 self.start_inline_blame_timer(window, cx);
2199 }
2200 }
2201
2202 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2203 cx.emit(EditorEvent::SelectionsChanged { local });
2204
2205 let selections = &self.selections.disjoint;
2206 if selections.len() == 1 {
2207 cx.emit(SearchEvent::ActiveMatchChanged)
2208 }
2209 if local
2210 && self.is_singleton(cx)
2211 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2212 {
2213 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2214 let background_executor = cx.background_executor().clone();
2215 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2216 let snapshot = self.buffer().read(cx).snapshot(cx);
2217 let selections = selections.clone();
2218 self.serialize_selections = cx.background_spawn(async move {
2219 background_executor.timer(Duration::from_millis(100)).await;
2220 let selections = selections
2221 .iter()
2222 .map(|selection| {
2223 (
2224 selection.start.to_offset(&snapshot),
2225 selection.end.to_offset(&snapshot),
2226 )
2227 })
2228 .collect();
2229 DB.save_editor_selections(editor_id, workspace_id, selections)
2230 .await
2231 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2232 .log_err();
2233 });
2234 }
2235 }
2236
2237 cx.notify();
2238 }
2239
2240 pub fn sync_selections(
2241 &mut self,
2242 other: Entity<Editor>,
2243 cx: &mut Context<Self>,
2244 ) -> gpui::Subscription {
2245 let other_selections = other.read(cx).selections.disjoint.to_vec();
2246 self.selections.change_with(cx, |selections| {
2247 selections.select_anchors(other_selections);
2248 });
2249
2250 let other_subscription =
2251 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2252 EditorEvent::SelectionsChanged { local: true } => {
2253 let other_selections = other.read(cx).selections.disjoint.to_vec();
2254 if other_selections.is_empty() {
2255 return;
2256 }
2257 this.selections.change_with(cx, |selections| {
2258 selections.select_anchors(other_selections);
2259 });
2260 }
2261 _ => {}
2262 });
2263
2264 let this_subscription =
2265 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2266 EditorEvent::SelectionsChanged { local: true } => {
2267 let these_selections = this.selections.disjoint.to_vec();
2268 if these_selections.is_empty() {
2269 return;
2270 }
2271 other.update(cx, |other_editor, cx| {
2272 other_editor.selections.change_with(cx, |selections| {
2273 selections.select_anchors(these_selections);
2274 })
2275 });
2276 }
2277 _ => {}
2278 });
2279
2280 Subscription::join(other_subscription, this_subscription)
2281 }
2282
2283 pub fn change_selections<R>(
2284 &mut self,
2285 autoscroll: Option<Autoscroll>,
2286 window: &mut Window,
2287 cx: &mut Context<Self>,
2288 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2289 ) -> R {
2290 self.change_selections_inner(autoscroll, true, window, cx, change)
2291 }
2292
2293 fn change_selections_inner<R>(
2294 &mut self,
2295 autoscroll: Option<Autoscroll>,
2296 request_completions: bool,
2297 window: &mut Window,
2298 cx: &mut Context<Self>,
2299 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2300 ) -> R {
2301 let old_cursor_position = self.selections.newest_anchor().head();
2302 self.push_to_selection_history();
2303
2304 let (changed, result) = self.selections.change_with(cx, change);
2305
2306 if changed {
2307 if let Some(autoscroll) = autoscroll {
2308 self.request_autoscroll(autoscroll, cx);
2309 }
2310 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2311
2312 if self.should_open_signature_help_automatically(
2313 &old_cursor_position,
2314 self.signature_help_state.backspace_pressed(),
2315 cx,
2316 ) {
2317 self.show_signature_help(&ShowSignatureHelp, window, cx);
2318 }
2319 self.signature_help_state.set_backspace_pressed(false);
2320 }
2321
2322 result
2323 }
2324
2325 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2326 where
2327 I: IntoIterator<Item = (Range<S>, T)>,
2328 S: ToOffset,
2329 T: Into<Arc<str>>,
2330 {
2331 if self.read_only(cx) {
2332 return;
2333 }
2334
2335 self.buffer
2336 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2337 }
2338
2339 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2340 where
2341 I: IntoIterator<Item = (Range<S>, T)>,
2342 S: ToOffset,
2343 T: Into<Arc<str>>,
2344 {
2345 if self.read_only(cx) {
2346 return;
2347 }
2348
2349 self.buffer.update(cx, |buffer, cx| {
2350 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2351 });
2352 }
2353
2354 pub fn edit_with_block_indent<I, S, T>(
2355 &mut self,
2356 edits: I,
2357 original_indent_columns: Vec<Option<u32>>,
2358 cx: &mut Context<Self>,
2359 ) where
2360 I: IntoIterator<Item = (Range<S>, T)>,
2361 S: ToOffset,
2362 T: Into<Arc<str>>,
2363 {
2364 if self.read_only(cx) {
2365 return;
2366 }
2367
2368 self.buffer.update(cx, |buffer, cx| {
2369 buffer.edit(
2370 edits,
2371 Some(AutoindentMode::Block {
2372 original_indent_columns,
2373 }),
2374 cx,
2375 )
2376 });
2377 }
2378
2379 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2380 self.hide_context_menu(window, cx);
2381
2382 match phase {
2383 SelectPhase::Begin {
2384 position,
2385 add,
2386 click_count,
2387 } => self.begin_selection(position, add, click_count, window, cx),
2388 SelectPhase::BeginColumnar {
2389 position,
2390 goal_column,
2391 reset,
2392 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2393 SelectPhase::Extend {
2394 position,
2395 click_count,
2396 } => self.extend_selection(position, click_count, window, cx),
2397 SelectPhase::Update {
2398 position,
2399 goal_column,
2400 scroll_delta,
2401 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2402 SelectPhase::End => self.end_selection(window, cx),
2403 }
2404 }
2405
2406 fn extend_selection(
2407 &mut self,
2408 position: DisplayPoint,
2409 click_count: usize,
2410 window: &mut Window,
2411 cx: &mut Context<Self>,
2412 ) {
2413 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2414 let tail = self.selections.newest::<usize>(cx).tail();
2415 self.begin_selection(position, false, click_count, window, cx);
2416
2417 let position = position.to_offset(&display_map, Bias::Left);
2418 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2419
2420 let mut pending_selection = self
2421 .selections
2422 .pending_anchor()
2423 .expect("extend_selection not called with pending selection");
2424 if position >= tail {
2425 pending_selection.start = tail_anchor;
2426 } else {
2427 pending_selection.end = tail_anchor;
2428 pending_selection.reversed = true;
2429 }
2430
2431 let mut pending_mode = self.selections.pending_mode().unwrap();
2432 match &mut pending_mode {
2433 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2434 _ => {}
2435 }
2436
2437 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2438 s.set_pending(pending_selection, pending_mode)
2439 });
2440 }
2441
2442 fn begin_selection(
2443 &mut self,
2444 position: DisplayPoint,
2445 add: bool,
2446 click_count: usize,
2447 window: &mut Window,
2448 cx: &mut Context<Self>,
2449 ) {
2450 if !self.focus_handle.is_focused(window) {
2451 self.last_focused_descendant = None;
2452 window.focus(&self.focus_handle);
2453 }
2454
2455 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2456 let buffer = &display_map.buffer_snapshot;
2457 let newest_selection = self.selections.newest_anchor().clone();
2458 let position = display_map.clip_point(position, Bias::Left);
2459
2460 let start;
2461 let end;
2462 let mode;
2463 let mut auto_scroll;
2464 match click_count {
2465 1 => {
2466 start = buffer.anchor_before(position.to_point(&display_map));
2467 end = start;
2468 mode = SelectMode::Character;
2469 auto_scroll = true;
2470 }
2471 2 => {
2472 let range = movement::surrounding_word(&display_map, position);
2473 start = buffer.anchor_before(range.start.to_point(&display_map));
2474 end = buffer.anchor_before(range.end.to_point(&display_map));
2475 mode = SelectMode::Word(start..end);
2476 auto_scroll = true;
2477 }
2478 3 => {
2479 let position = display_map
2480 .clip_point(position, Bias::Left)
2481 .to_point(&display_map);
2482 let line_start = display_map.prev_line_boundary(position).0;
2483 let next_line_start = buffer.clip_point(
2484 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2485 Bias::Left,
2486 );
2487 start = buffer.anchor_before(line_start);
2488 end = buffer.anchor_before(next_line_start);
2489 mode = SelectMode::Line(start..end);
2490 auto_scroll = true;
2491 }
2492 _ => {
2493 start = buffer.anchor_before(0);
2494 end = buffer.anchor_before(buffer.len());
2495 mode = SelectMode::All;
2496 auto_scroll = false;
2497 }
2498 }
2499 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2500
2501 let point_to_delete: Option<usize> = {
2502 let selected_points: Vec<Selection<Point>> =
2503 self.selections.disjoint_in_range(start..end, cx);
2504
2505 if !add || click_count > 1 {
2506 None
2507 } else if !selected_points.is_empty() {
2508 Some(selected_points[0].id)
2509 } else {
2510 let clicked_point_already_selected =
2511 self.selections.disjoint.iter().find(|selection| {
2512 selection.start.to_point(buffer) == start.to_point(buffer)
2513 || selection.end.to_point(buffer) == end.to_point(buffer)
2514 });
2515
2516 clicked_point_already_selected.map(|selection| selection.id)
2517 }
2518 };
2519
2520 let selections_count = self.selections.count();
2521
2522 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2523 if let Some(point_to_delete) = point_to_delete {
2524 s.delete(point_to_delete);
2525
2526 if selections_count == 1 {
2527 s.set_pending_anchor_range(start..end, mode);
2528 }
2529 } else {
2530 if !add {
2531 s.clear_disjoint();
2532 } else if click_count > 1 {
2533 s.delete(newest_selection.id)
2534 }
2535
2536 s.set_pending_anchor_range(start..end, mode);
2537 }
2538 });
2539 }
2540
2541 fn begin_columnar_selection(
2542 &mut self,
2543 position: DisplayPoint,
2544 goal_column: u32,
2545 reset: bool,
2546 window: &mut Window,
2547 cx: &mut Context<Self>,
2548 ) {
2549 if !self.focus_handle.is_focused(window) {
2550 self.last_focused_descendant = None;
2551 window.focus(&self.focus_handle);
2552 }
2553
2554 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2555
2556 if reset {
2557 let pointer_position = display_map
2558 .buffer_snapshot
2559 .anchor_before(position.to_point(&display_map));
2560
2561 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2562 s.clear_disjoint();
2563 s.set_pending_anchor_range(
2564 pointer_position..pointer_position,
2565 SelectMode::Character,
2566 );
2567 });
2568 }
2569
2570 let tail = self.selections.newest::<Point>(cx).tail();
2571 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2572
2573 if !reset {
2574 self.select_columns(
2575 tail.to_display_point(&display_map),
2576 position,
2577 goal_column,
2578 &display_map,
2579 window,
2580 cx,
2581 );
2582 }
2583 }
2584
2585 fn update_selection(
2586 &mut self,
2587 position: DisplayPoint,
2588 goal_column: u32,
2589 scroll_delta: gpui::Point<f32>,
2590 window: &mut Window,
2591 cx: &mut Context<Self>,
2592 ) {
2593 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2594
2595 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2596 let tail = tail.to_display_point(&display_map);
2597 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2598 } else if let Some(mut pending) = self.selections.pending_anchor() {
2599 let buffer = self.buffer.read(cx).snapshot(cx);
2600 let head;
2601 let tail;
2602 let mode = self.selections.pending_mode().unwrap();
2603 match &mode {
2604 SelectMode::Character => {
2605 head = position.to_point(&display_map);
2606 tail = pending.tail().to_point(&buffer);
2607 }
2608 SelectMode::Word(original_range) => {
2609 let original_display_range = original_range.start.to_display_point(&display_map)
2610 ..original_range.end.to_display_point(&display_map);
2611 let original_buffer_range = original_display_range.start.to_point(&display_map)
2612 ..original_display_range.end.to_point(&display_map);
2613 if movement::is_inside_word(&display_map, position)
2614 || original_display_range.contains(&position)
2615 {
2616 let word_range = movement::surrounding_word(&display_map, position);
2617 if word_range.start < original_display_range.start {
2618 head = word_range.start.to_point(&display_map);
2619 } else {
2620 head = word_range.end.to_point(&display_map);
2621 }
2622 } else {
2623 head = position.to_point(&display_map);
2624 }
2625
2626 if head <= original_buffer_range.start {
2627 tail = original_buffer_range.end;
2628 } else {
2629 tail = original_buffer_range.start;
2630 }
2631 }
2632 SelectMode::Line(original_range) => {
2633 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2634
2635 let position = display_map
2636 .clip_point(position, Bias::Left)
2637 .to_point(&display_map);
2638 let line_start = display_map.prev_line_boundary(position).0;
2639 let next_line_start = buffer.clip_point(
2640 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2641 Bias::Left,
2642 );
2643
2644 if line_start < original_range.start {
2645 head = line_start
2646 } else {
2647 head = next_line_start
2648 }
2649
2650 if head <= original_range.start {
2651 tail = original_range.end;
2652 } else {
2653 tail = original_range.start;
2654 }
2655 }
2656 SelectMode::All => {
2657 return;
2658 }
2659 };
2660
2661 if head < tail {
2662 pending.start = buffer.anchor_before(head);
2663 pending.end = buffer.anchor_before(tail);
2664 pending.reversed = true;
2665 } else {
2666 pending.start = buffer.anchor_before(tail);
2667 pending.end = buffer.anchor_before(head);
2668 pending.reversed = false;
2669 }
2670
2671 self.change_selections(None, window, cx, |s| {
2672 s.set_pending(pending, mode);
2673 });
2674 } else {
2675 log::error!("update_selection dispatched with no pending selection");
2676 return;
2677 }
2678
2679 self.apply_scroll_delta(scroll_delta, window, cx);
2680 cx.notify();
2681 }
2682
2683 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2684 self.columnar_selection_tail.take();
2685 if self.selections.pending_anchor().is_some() {
2686 let selections = self.selections.all::<usize>(cx);
2687 self.change_selections(None, window, cx, |s| {
2688 s.select(selections);
2689 s.clear_pending();
2690 });
2691 }
2692 }
2693
2694 fn select_columns(
2695 &mut self,
2696 tail: DisplayPoint,
2697 head: DisplayPoint,
2698 goal_column: u32,
2699 display_map: &DisplaySnapshot,
2700 window: &mut Window,
2701 cx: &mut Context<Self>,
2702 ) {
2703 let start_row = cmp::min(tail.row(), head.row());
2704 let end_row = cmp::max(tail.row(), head.row());
2705 let start_column = cmp::min(tail.column(), goal_column);
2706 let end_column = cmp::max(tail.column(), goal_column);
2707 let reversed = start_column < tail.column();
2708
2709 let selection_ranges = (start_row.0..=end_row.0)
2710 .map(DisplayRow)
2711 .filter_map(|row| {
2712 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2713 let start = display_map
2714 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2715 .to_point(display_map);
2716 let end = display_map
2717 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2718 .to_point(display_map);
2719 if reversed {
2720 Some(end..start)
2721 } else {
2722 Some(start..end)
2723 }
2724 } else {
2725 None
2726 }
2727 })
2728 .collect::<Vec<_>>();
2729
2730 self.change_selections(None, window, cx, |s| {
2731 s.select_ranges(selection_ranges);
2732 });
2733 cx.notify();
2734 }
2735
2736 pub fn has_pending_nonempty_selection(&self) -> bool {
2737 let pending_nonempty_selection = match self.selections.pending_anchor() {
2738 Some(Selection { start, end, .. }) => start != end,
2739 None => false,
2740 };
2741
2742 pending_nonempty_selection
2743 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2744 }
2745
2746 pub fn has_pending_selection(&self) -> bool {
2747 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2748 }
2749
2750 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2751 self.selection_mark_mode = false;
2752
2753 if self.clear_expanded_diff_hunks(cx) {
2754 cx.notify();
2755 return;
2756 }
2757 if self.dismiss_menus_and_popups(true, window, cx) {
2758 return;
2759 }
2760
2761 if self.mode == EditorMode::Full
2762 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2763 {
2764 return;
2765 }
2766
2767 cx.propagate();
2768 }
2769
2770 pub fn dismiss_menus_and_popups(
2771 &mut self,
2772 is_user_requested: bool,
2773 window: &mut Window,
2774 cx: &mut Context<Self>,
2775 ) -> bool {
2776 if self.take_rename(false, window, cx).is_some() {
2777 return true;
2778 }
2779
2780 if hide_hover(self, cx) {
2781 return true;
2782 }
2783
2784 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2785 return true;
2786 }
2787
2788 if self.hide_context_menu(window, cx).is_some() {
2789 return true;
2790 }
2791
2792 if self.mouse_context_menu.take().is_some() {
2793 return true;
2794 }
2795
2796 if is_user_requested && self.discard_inline_completion(true, cx) {
2797 return true;
2798 }
2799
2800 if self.snippet_stack.pop().is_some() {
2801 return true;
2802 }
2803
2804 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2805 self.dismiss_diagnostics(cx);
2806 return true;
2807 }
2808
2809 false
2810 }
2811
2812 fn linked_editing_ranges_for(
2813 &self,
2814 selection: Range<text::Anchor>,
2815 cx: &App,
2816 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2817 if self.linked_edit_ranges.is_empty() {
2818 return None;
2819 }
2820 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2821 selection.end.buffer_id.and_then(|end_buffer_id| {
2822 if selection.start.buffer_id != Some(end_buffer_id) {
2823 return None;
2824 }
2825 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2826 let snapshot = buffer.read(cx).snapshot();
2827 self.linked_edit_ranges
2828 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2829 .map(|ranges| (ranges, snapshot, buffer))
2830 })?;
2831 use text::ToOffset as TO;
2832 // find offset from the start of current range to current cursor position
2833 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2834
2835 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2836 let start_difference = start_offset - start_byte_offset;
2837 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2838 let end_difference = end_offset - start_byte_offset;
2839 // Current range has associated linked ranges.
2840 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2841 for range in linked_ranges.iter() {
2842 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2843 let end_offset = start_offset + end_difference;
2844 let start_offset = start_offset + start_difference;
2845 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2846 continue;
2847 }
2848 if self.selections.disjoint_anchor_ranges().any(|s| {
2849 if s.start.buffer_id != selection.start.buffer_id
2850 || s.end.buffer_id != selection.end.buffer_id
2851 {
2852 return false;
2853 }
2854 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2855 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2856 }) {
2857 continue;
2858 }
2859 let start = buffer_snapshot.anchor_after(start_offset);
2860 let end = buffer_snapshot.anchor_after(end_offset);
2861 linked_edits
2862 .entry(buffer.clone())
2863 .or_default()
2864 .push(start..end);
2865 }
2866 Some(linked_edits)
2867 }
2868
2869 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2870 let text: Arc<str> = text.into();
2871
2872 if self.read_only(cx) {
2873 return;
2874 }
2875
2876 let selections = self.selections.all_adjusted(cx);
2877 let mut bracket_inserted = false;
2878 let mut edits = Vec::new();
2879 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2880 let mut new_selections = Vec::with_capacity(selections.len());
2881 let mut new_autoclose_regions = Vec::new();
2882 let snapshot = self.buffer.read(cx).read(cx);
2883
2884 for (selection, autoclose_region) in
2885 self.selections_with_autoclose_regions(selections, &snapshot)
2886 {
2887 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2888 // Determine if the inserted text matches the opening or closing
2889 // bracket of any of this language's bracket pairs.
2890 let mut bracket_pair = None;
2891 let mut is_bracket_pair_start = false;
2892 let mut is_bracket_pair_end = false;
2893 if !text.is_empty() {
2894 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2895 // and they are removing the character that triggered IME popup.
2896 for (pair, enabled) in scope.brackets() {
2897 if !pair.close && !pair.surround {
2898 continue;
2899 }
2900
2901 if enabled && pair.start.ends_with(text.as_ref()) {
2902 let prefix_len = pair.start.len() - text.len();
2903 let preceding_text_matches_prefix = prefix_len == 0
2904 || (selection.start.column >= (prefix_len as u32)
2905 && snapshot.contains_str_at(
2906 Point::new(
2907 selection.start.row,
2908 selection.start.column - (prefix_len as u32),
2909 ),
2910 &pair.start[..prefix_len],
2911 ));
2912 if preceding_text_matches_prefix {
2913 bracket_pair = Some(pair.clone());
2914 is_bracket_pair_start = true;
2915 break;
2916 }
2917 }
2918 if pair.end.as_str() == text.as_ref() {
2919 bracket_pair = Some(pair.clone());
2920 is_bracket_pair_end = true;
2921 break;
2922 }
2923 }
2924 }
2925
2926 if let Some(bracket_pair) = bracket_pair {
2927 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
2928 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2929 let auto_surround =
2930 self.use_auto_surround && snapshot_settings.use_auto_surround;
2931 if selection.is_empty() {
2932 if is_bracket_pair_start {
2933 // If the inserted text is a suffix of an opening bracket and the
2934 // selection is preceded by the rest of the opening bracket, then
2935 // insert the closing bracket.
2936 let following_text_allows_autoclose = snapshot
2937 .chars_at(selection.start)
2938 .next()
2939 .map_or(true, |c| scope.should_autoclose_before(c));
2940
2941 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2942 && bracket_pair.start.len() == 1
2943 {
2944 let target = bracket_pair.start.chars().next().unwrap();
2945 let current_line_count = snapshot
2946 .reversed_chars_at(selection.start)
2947 .take_while(|&c| c != '\n')
2948 .filter(|&c| c == target)
2949 .count();
2950 current_line_count % 2 == 1
2951 } else {
2952 false
2953 };
2954
2955 if autoclose
2956 && bracket_pair.close
2957 && following_text_allows_autoclose
2958 && !is_closing_quote
2959 {
2960 let anchor = snapshot.anchor_before(selection.end);
2961 new_selections.push((selection.map(|_| anchor), text.len()));
2962 new_autoclose_regions.push((
2963 anchor,
2964 text.len(),
2965 selection.id,
2966 bracket_pair.clone(),
2967 ));
2968 edits.push((
2969 selection.range(),
2970 format!("{}{}", text, bracket_pair.end).into(),
2971 ));
2972 bracket_inserted = true;
2973 continue;
2974 }
2975 }
2976
2977 if let Some(region) = autoclose_region {
2978 // If the selection is followed by an auto-inserted closing bracket,
2979 // then don't insert that closing bracket again; just move the selection
2980 // past the closing bracket.
2981 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2982 && text.as_ref() == region.pair.end.as_str();
2983 if should_skip {
2984 let anchor = snapshot.anchor_after(selection.end);
2985 new_selections
2986 .push((selection.map(|_| anchor), region.pair.end.len()));
2987 continue;
2988 }
2989 }
2990
2991 let always_treat_brackets_as_autoclosed = snapshot
2992 .language_settings_at(selection.start, cx)
2993 .always_treat_brackets_as_autoclosed;
2994 if always_treat_brackets_as_autoclosed
2995 && is_bracket_pair_end
2996 && snapshot.contains_str_at(selection.end, text.as_ref())
2997 {
2998 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2999 // and the inserted text is a closing bracket and the selection is followed
3000 // by the closing bracket then move the selection past the closing bracket.
3001 let anchor = snapshot.anchor_after(selection.end);
3002 new_selections.push((selection.map(|_| anchor), text.len()));
3003 continue;
3004 }
3005 }
3006 // If an opening bracket is 1 character long and is typed while
3007 // text is selected, then surround that text with the bracket pair.
3008 else if auto_surround
3009 && bracket_pair.surround
3010 && is_bracket_pair_start
3011 && bracket_pair.start.chars().count() == 1
3012 {
3013 edits.push((selection.start..selection.start, text.clone()));
3014 edits.push((
3015 selection.end..selection.end,
3016 bracket_pair.end.as_str().into(),
3017 ));
3018 bracket_inserted = true;
3019 new_selections.push((
3020 Selection {
3021 id: selection.id,
3022 start: snapshot.anchor_after(selection.start),
3023 end: snapshot.anchor_before(selection.end),
3024 reversed: selection.reversed,
3025 goal: selection.goal,
3026 },
3027 0,
3028 ));
3029 continue;
3030 }
3031 }
3032 }
3033
3034 if self.auto_replace_emoji_shortcode
3035 && selection.is_empty()
3036 && text.as_ref().ends_with(':')
3037 {
3038 if let Some(possible_emoji_short_code) =
3039 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3040 {
3041 if !possible_emoji_short_code.is_empty() {
3042 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3043 let emoji_shortcode_start = Point::new(
3044 selection.start.row,
3045 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3046 );
3047
3048 // Remove shortcode from buffer
3049 edits.push((
3050 emoji_shortcode_start..selection.start,
3051 "".to_string().into(),
3052 ));
3053 new_selections.push((
3054 Selection {
3055 id: selection.id,
3056 start: snapshot.anchor_after(emoji_shortcode_start),
3057 end: snapshot.anchor_before(selection.start),
3058 reversed: selection.reversed,
3059 goal: selection.goal,
3060 },
3061 0,
3062 ));
3063
3064 // Insert emoji
3065 let selection_start_anchor = snapshot.anchor_after(selection.start);
3066 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3067 edits.push((selection.start..selection.end, emoji.to_string().into()));
3068
3069 continue;
3070 }
3071 }
3072 }
3073 }
3074
3075 // If not handling any auto-close operation, then just replace the selected
3076 // text with the given input and move the selection to the end of the
3077 // newly inserted text.
3078 let anchor = snapshot.anchor_after(selection.end);
3079 if !self.linked_edit_ranges.is_empty() {
3080 let start_anchor = snapshot.anchor_before(selection.start);
3081
3082 let is_word_char = text.chars().next().map_or(true, |char| {
3083 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3084 classifier.is_word(char)
3085 });
3086
3087 if is_word_char {
3088 if let Some(ranges) = self
3089 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3090 {
3091 for (buffer, edits) in ranges {
3092 linked_edits
3093 .entry(buffer.clone())
3094 .or_default()
3095 .extend(edits.into_iter().map(|range| (range, text.clone())));
3096 }
3097 }
3098 }
3099 }
3100
3101 new_selections.push((selection.map(|_| anchor), 0));
3102 edits.push((selection.start..selection.end, text.clone()));
3103 }
3104
3105 drop(snapshot);
3106
3107 self.transact(window, cx, |this, window, cx| {
3108 let initial_buffer_versions =
3109 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3110
3111 this.buffer.update(cx, |buffer, cx| {
3112 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3113 });
3114 for (buffer, edits) in linked_edits {
3115 buffer.update(cx, |buffer, cx| {
3116 let snapshot = buffer.snapshot();
3117 let edits = edits
3118 .into_iter()
3119 .map(|(range, text)| {
3120 use text::ToPoint as TP;
3121 let end_point = TP::to_point(&range.end, &snapshot);
3122 let start_point = TP::to_point(&range.start, &snapshot);
3123 (start_point..end_point, text)
3124 })
3125 .sorted_by_key(|(range, _)| range.start)
3126 .collect::<Vec<_>>();
3127 buffer.edit(edits, None, cx);
3128 })
3129 }
3130 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3131 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3132 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3133 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3134 .zip(new_selection_deltas)
3135 .map(|(selection, delta)| Selection {
3136 id: selection.id,
3137 start: selection.start + delta,
3138 end: selection.end + delta,
3139 reversed: selection.reversed,
3140 goal: SelectionGoal::None,
3141 })
3142 .collect::<Vec<_>>();
3143
3144 let mut i = 0;
3145 for (position, delta, selection_id, pair) in new_autoclose_regions {
3146 let position = position.to_offset(&map.buffer_snapshot) + delta;
3147 let start = map.buffer_snapshot.anchor_before(position);
3148 let end = map.buffer_snapshot.anchor_after(position);
3149 while let Some(existing_state) = this.autoclose_regions.get(i) {
3150 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3151 Ordering::Less => i += 1,
3152 Ordering::Greater => break,
3153 Ordering::Equal => {
3154 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3155 Ordering::Less => i += 1,
3156 Ordering::Equal => break,
3157 Ordering::Greater => break,
3158 }
3159 }
3160 }
3161 }
3162 this.autoclose_regions.insert(
3163 i,
3164 AutocloseRegion {
3165 selection_id,
3166 range: start..end,
3167 pair,
3168 },
3169 );
3170 }
3171
3172 let had_active_inline_completion = this.has_active_inline_completion();
3173 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3174 s.select(new_selections)
3175 });
3176
3177 if !bracket_inserted {
3178 if let Some(on_type_format_task) =
3179 this.trigger_on_type_formatting(text.to_string(), window, cx)
3180 {
3181 on_type_format_task.detach_and_log_err(cx);
3182 }
3183 }
3184
3185 let editor_settings = EditorSettings::get_global(cx);
3186 if bracket_inserted
3187 && (editor_settings.auto_signature_help
3188 || editor_settings.show_signature_help_after_edits)
3189 {
3190 this.show_signature_help(&ShowSignatureHelp, window, cx);
3191 }
3192
3193 let trigger_in_words =
3194 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3195 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3196 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3197 this.refresh_inline_completion(true, false, window, cx);
3198 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3199 });
3200 }
3201
3202 fn find_possible_emoji_shortcode_at_position(
3203 snapshot: &MultiBufferSnapshot,
3204 position: Point,
3205 ) -> Option<String> {
3206 let mut chars = Vec::new();
3207 let mut found_colon = false;
3208 for char in snapshot.reversed_chars_at(position).take(100) {
3209 // Found a possible emoji shortcode in the middle of the buffer
3210 if found_colon {
3211 if char.is_whitespace() {
3212 chars.reverse();
3213 return Some(chars.iter().collect());
3214 }
3215 // If the previous character is not a whitespace, we are in the middle of a word
3216 // and we only want to complete the shortcode if the word is made up of other emojis
3217 let mut containing_word = String::new();
3218 for ch in snapshot
3219 .reversed_chars_at(position)
3220 .skip(chars.len() + 1)
3221 .take(100)
3222 {
3223 if ch.is_whitespace() {
3224 break;
3225 }
3226 containing_word.push(ch);
3227 }
3228 let containing_word = containing_word.chars().rev().collect::<String>();
3229 if util::word_consists_of_emojis(containing_word.as_str()) {
3230 chars.reverse();
3231 return Some(chars.iter().collect());
3232 }
3233 }
3234
3235 if char.is_whitespace() || !char.is_ascii() {
3236 return None;
3237 }
3238 if char == ':' {
3239 found_colon = true;
3240 } else {
3241 chars.push(char);
3242 }
3243 }
3244 // Found a possible emoji shortcode at the beginning of the buffer
3245 chars.reverse();
3246 Some(chars.iter().collect())
3247 }
3248
3249 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3250 self.transact(window, cx, |this, window, cx| {
3251 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3252 let selections = this.selections.all::<usize>(cx);
3253 let multi_buffer = this.buffer.read(cx);
3254 let buffer = multi_buffer.snapshot(cx);
3255 selections
3256 .iter()
3257 .map(|selection| {
3258 let start_point = selection.start.to_point(&buffer);
3259 let mut indent =
3260 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3261 indent.len = cmp::min(indent.len, start_point.column);
3262 let start = selection.start;
3263 let end = selection.end;
3264 let selection_is_empty = start == end;
3265 let language_scope = buffer.language_scope_at(start);
3266 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3267 &language_scope
3268 {
3269 let insert_extra_newline =
3270 insert_extra_newline_brackets(&buffer, start..end, language)
3271 || insert_extra_newline_tree_sitter(&buffer, start..end);
3272
3273 // Comment extension on newline is allowed only for cursor selections
3274 let comment_delimiter = maybe!({
3275 if !selection_is_empty {
3276 return None;
3277 }
3278
3279 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3280 return None;
3281 }
3282
3283 let delimiters = language.line_comment_prefixes();
3284 let max_len_of_delimiter =
3285 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3286 let (snapshot, range) =
3287 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3288
3289 let mut index_of_first_non_whitespace = 0;
3290 let comment_candidate = snapshot
3291 .chars_for_range(range)
3292 .skip_while(|c| {
3293 let should_skip = c.is_whitespace();
3294 if should_skip {
3295 index_of_first_non_whitespace += 1;
3296 }
3297 should_skip
3298 })
3299 .take(max_len_of_delimiter)
3300 .collect::<String>();
3301 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3302 comment_candidate.starts_with(comment_prefix.as_ref())
3303 })?;
3304 let cursor_is_placed_after_comment_marker =
3305 index_of_first_non_whitespace + comment_prefix.len()
3306 <= start_point.column as usize;
3307 if cursor_is_placed_after_comment_marker {
3308 Some(comment_prefix.clone())
3309 } else {
3310 None
3311 }
3312 });
3313 (comment_delimiter, insert_extra_newline)
3314 } else {
3315 (None, false)
3316 };
3317
3318 let capacity_for_delimiter = comment_delimiter
3319 .as_deref()
3320 .map(str::len)
3321 .unwrap_or_default();
3322 let mut new_text =
3323 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3324 new_text.push('\n');
3325 new_text.extend(indent.chars());
3326 if let Some(delimiter) = &comment_delimiter {
3327 new_text.push_str(delimiter);
3328 }
3329 if insert_extra_newline {
3330 new_text = new_text.repeat(2);
3331 }
3332
3333 let anchor = buffer.anchor_after(end);
3334 let new_selection = selection.map(|_| anchor);
3335 (
3336 (start..end, new_text),
3337 (insert_extra_newline, new_selection),
3338 )
3339 })
3340 .unzip()
3341 };
3342
3343 this.edit_with_autoindent(edits, cx);
3344 let buffer = this.buffer.read(cx).snapshot(cx);
3345 let new_selections = selection_fixup_info
3346 .into_iter()
3347 .map(|(extra_newline_inserted, new_selection)| {
3348 let mut cursor = new_selection.end.to_point(&buffer);
3349 if extra_newline_inserted {
3350 cursor.row -= 1;
3351 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3352 }
3353 new_selection.map(|_| cursor)
3354 })
3355 .collect();
3356
3357 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3358 s.select(new_selections)
3359 });
3360 this.refresh_inline_completion(true, false, window, cx);
3361 });
3362 }
3363
3364 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3365 let buffer = self.buffer.read(cx);
3366 let snapshot = buffer.snapshot(cx);
3367
3368 let mut edits = Vec::new();
3369 let mut rows = Vec::new();
3370
3371 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3372 let cursor = selection.head();
3373 let row = cursor.row;
3374
3375 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3376
3377 let newline = "\n".to_string();
3378 edits.push((start_of_line..start_of_line, newline));
3379
3380 rows.push(row + rows_inserted as u32);
3381 }
3382
3383 self.transact(window, cx, |editor, window, cx| {
3384 editor.edit(edits, cx);
3385
3386 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3387 let mut index = 0;
3388 s.move_cursors_with(|map, _, _| {
3389 let row = rows[index];
3390 index += 1;
3391
3392 let point = Point::new(row, 0);
3393 let boundary = map.next_line_boundary(point).1;
3394 let clipped = map.clip_point(boundary, Bias::Left);
3395
3396 (clipped, SelectionGoal::None)
3397 });
3398 });
3399
3400 let mut indent_edits = Vec::new();
3401 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3402 for row in rows {
3403 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3404 for (row, indent) in indents {
3405 if indent.len == 0 {
3406 continue;
3407 }
3408
3409 let text = match indent.kind {
3410 IndentKind::Space => " ".repeat(indent.len as usize),
3411 IndentKind::Tab => "\t".repeat(indent.len as usize),
3412 };
3413 let point = Point::new(row.0, 0);
3414 indent_edits.push((point..point, text));
3415 }
3416 }
3417 editor.edit(indent_edits, cx);
3418 });
3419 }
3420
3421 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3422 let buffer = self.buffer.read(cx);
3423 let snapshot = buffer.snapshot(cx);
3424
3425 let mut edits = Vec::new();
3426 let mut rows = Vec::new();
3427 let mut rows_inserted = 0;
3428
3429 for selection in self.selections.all_adjusted(cx) {
3430 let cursor = selection.head();
3431 let row = cursor.row;
3432
3433 let point = Point::new(row + 1, 0);
3434 let start_of_line = snapshot.clip_point(point, Bias::Left);
3435
3436 let newline = "\n".to_string();
3437 edits.push((start_of_line..start_of_line, newline));
3438
3439 rows_inserted += 1;
3440 rows.push(row + rows_inserted);
3441 }
3442
3443 self.transact(window, cx, |editor, window, cx| {
3444 editor.edit(edits, cx);
3445
3446 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3447 let mut index = 0;
3448 s.move_cursors_with(|map, _, _| {
3449 let row = rows[index];
3450 index += 1;
3451
3452 let point = Point::new(row, 0);
3453 let boundary = map.next_line_boundary(point).1;
3454 let clipped = map.clip_point(boundary, Bias::Left);
3455
3456 (clipped, SelectionGoal::None)
3457 });
3458 });
3459
3460 let mut indent_edits = Vec::new();
3461 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3462 for row in rows {
3463 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3464 for (row, indent) in indents {
3465 if indent.len == 0 {
3466 continue;
3467 }
3468
3469 let text = match indent.kind {
3470 IndentKind::Space => " ".repeat(indent.len as usize),
3471 IndentKind::Tab => "\t".repeat(indent.len as usize),
3472 };
3473 let point = Point::new(row.0, 0);
3474 indent_edits.push((point..point, text));
3475 }
3476 }
3477 editor.edit(indent_edits, cx);
3478 });
3479 }
3480
3481 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3482 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3483 original_indent_columns: Vec::new(),
3484 });
3485 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3486 }
3487
3488 fn insert_with_autoindent_mode(
3489 &mut self,
3490 text: &str,
3491 autoindent_mode: Option<AutoindentMode>,
3492 window: &mut Window,
3493 cx: &mut Context<Self>,
3494 ) {
3495 if self.read_only(cx) {
3496 return;
3497 }
3498
3499 let text: Arc<str> = text.into();
3500 self.transact(window, cx, |this, window, cx| {
3501 let old_selections = this.selections.all_adjusted(cx);
3502 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3503 let anchors = {
3504 let snapshot = buffer.read(cx);
3505 old_selections
3506 .iter()
3507 .map(|s| {
3508 let anchor = snapshot.anchor_after(s.head());
3509 s.map(|_| anchor)
3510 })
3511 .collect::<Vec<_>>()
3512 };
3513 buffer.edit(
3514 old_selections
3515 .iter()
3516 .map(|s| (s.start..s.end, text.clone())),
3517 autoindent_mode,
3518 cx,
3519 );
3520 anchors
3521 });
3522
3523 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3524 s.select_anchors(selection_anchors);
3525 });
3526
3527 cx.notify();
3528 });
3529 }
3530
3531 fn trigger_completion_on_input(
3532 &mut self,
3533 text: &str,
3534 trigger_in_words: bool,
3535 window: &mut Window,
3536 cx: &mut Context<Self>,
3537 ) {
3538 if self.is_completion_trigger(text, trigger_in_words, cx) {
3539 self.show_completions(
3540 &ShowCompletions {
3541 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3542 },
3543 window,
3544 cx,
3545 );
3546 } else {
3547 self.hide_context_menu(window, cx);
3548 }
3549 }
3550
3551 fn is_completion_trigger(
3552 &self,
3553 text: &str,
3554 trigger_in_words: bool,
3555 cx: &mut Context<Self>,
3556 ) -> bool {
3557 let position = self.selections.newest_anchor().head();
3558 let multibuffer = self.buffer.read(cx);
3559 let Some(buffer) = position
3560 .buffer_id
3561 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3562 else {
3563 return false;
3564 };
3565
3566 if let Some(completion_provider) = &self.completion_provider {
3567 completion_provider.is_completion_trigger(
3568 &buffer,
3569 position.text_anchor,
3570 text,
3571 trigger_in_words,
3572 cx,
3573 )
3574 } else {
3575 false
3576 }
3577 }
3578
3579 /// If any empty selections is touching the start of its innermost containing autoclose
3580 /// region, expand it to select the brackets.
3581 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3582 let selections = self.selections.all::<usize>(cx);
3583 let buffer = self.buffer.read(cx).read(cx);
3584 let new_selections = self
3585 .selections_with_autoclose_regions(selections, &buffer)
3586 .map(|(mut selection, region)| {
3587 if !selection.is_empty() {
3588 return selection;
3589 }
3590
3591 if let Some(region) = region {
3592 let mut range = region.range.to_offset(&buffer);
3593 if selection.start == range.start && range.start >= region.pair.start.len() {
3594 range.start -= region.pair.start.len();
3595 if buffer.contains_str_at(range.start, ®ion.pair.start)
3596 && buffer.contains_str_at(range.end, ®ion.pair.end)
3597 {
3598 range.end += region.pair.end.len();
3599 selection.start = range.start;
3600 selection.end = range.end;
3601
3602 return selection;
3603 }
3604 }
3605 }
3606
3607 let always_treat_brackets_as_autoclosed = buffer
3608 .language_settings_at(selection.start, cx)
3609 .always_treat_brackets_as_autoclosed;
3610
3611 if !always_treat_brackets_as_autoclosed {
3612 return selection;
3613 }
3614
3615 if let Some(scope) = buffer.language_scope_at(selection.start) {
3616 for (pair, enabled) in scope.brackets() {
3617 if !enabled || !pair.close {
3618 continue;
3619 }
3620
3621 if buffer.contains_str_at(selection.start, &pair.end) {
3622 let pair_start_len = pair.start.len();
3623 if buffer.contains_str_at(
3624 selection.start.saturating_sub(pair_start_len),
3625 &pair.start,
3626 ) {
3627 selection.start -= pair_start_len;
3628 selection.end += pair.end.len();
3629
3630 return selection;
3631 }
3632 }
3633 }
3634 }
3635
3636 selection
3637 })
3638 .collect();
3639
3640 drop(buffer);
3641 self.change_selections(None, window, cx, |selections| {
3642 selections.select(new_selections)
3643 });
3644 }
3645
3646 /// Iterate the given selections, and for each one, find the smallest surrounding
3647 /// autoclose region. This uses the ordering of the selections and the autoclose
3648 /// regions to avoid repeated comparisons.
3649 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3650 &'a self,
3651 selections: impl IntoIterator<Item = Selection<D>>,
3652 buffer: &'a MultiBufferSnapshot,
3653 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3654 let mut i = 0;
3655 let mut regions = self.autoclose_regions.as_slice();
3656 selections.into_iter().map(move |selection| {
3657 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3658
3659 let mut enclosing = None;
3660 while let Some(pair_state) = regions.get(i) {
3661 if pair_state.range.end.to_offset(buffer) < range.start {
3662 regions = ®ions[i + 1..];
3663 i = 0;
3664 } else if pair_state.range.start.to_offset(buffer) > range.end {
3665 break;
3666 } else {
3667 if pair_state.selection_id == selection.id {
3668 enclosing = Some(pair_state);
3669 }
3670 i += 1;
3671 }
3672 }
3673
3674 (selection, enclosing)
3675 })
3676 }
3677
3678 /// Remove any autoclose regions that no longer contain their selection.
3679 fn invalidate_autoclose_regions(
3680 &mut self,
3681 mut selections: &[Selection<Anchor>],
3682 buffer: &MultiBufferSnapshot,
3683 ) {
3684 self.autoclose_regions.retain(|state| {
3685 let mut i = 0;
3686 while let Some(selection) = selections.get(i) {
3687 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3688 selections = &selections[1..];
3689 continue;
3690 }
3691 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3692 break;
3693 }
3694 if selection.id == state.selection_id {
3695 return true;
3696 } else {
3697 i += 1;
3698 }
3699 }
3700 false
3701 });
3702 }
3703
3704 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3705 let offset = position.to_offset(buffer);
3706 let (word_range, kind) = buffer.surrounding_word(offset, true);
3707 if offset > word_range.start && kind == Some(CharKind::Word) {
3708 Some(
3709 buffer
3710 .text_for_range(word_range.start..offset)
3711 .collect::<String>(),
3712 )
3713 } else {
3714 None
3715 }
3716 }
3717
3718 pub fn toggle_inlay_hints(
3719 &mut self,
3720 _: &ToggleInlayHints,
3721 _: &mut Window,
3722 cx: &mut Context<Self>,
3723 ) {
3724 self.refresh_inlay_hints(
3725 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3726 cx,
3727 );
3728 }
3729
3730 pub fn inlay_hints_enabled(&self) -> bool {
3731 self.inlay_hint_cache.enabled
3732 }
3733
3734 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3735 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3736 return;
3737 }
3738
3739 let reason_description = reason.description();
3740 let ignore_debounce = matches!(
3741 reason,
3742 InlayHintRefreshReason::SettingsChange(_)
3743 | InlayHintRefreshReason::Toggle(_)
3744 | InlayHintRefreshReason::ExcerptsRemoved(_)
3745 | InlayHintRefreshReason::ModifiersChanged(_)
3746 );
3747 let (invalidate_cache, required_languages) = match reason {
3748 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3749 match self.inlay_hint_cache.modifiers_override(enabled) {
3750 Some(enabled) => {
3751 if enabled {
3752 (InvalidationStrategy::RefreshRequested, None)
3753 } else {
3754 self.splice_inlays(
3755 &self
3756 .visible_inlay_hints(cx)
3757 .iter()
3758 .map(|inlay| inlay.id)
3759 .collect::<Vec<InlayId>>(),
3760 Vec::new(),
3761 cx,
3762 );
3763 return;
3764 }
3765 }
3766 None => return,
3767 }
3768 }
3769 InlayHintRefreshReason::Toggle(enabled) => {
3770 if self.inlay_hint_cache.toggle(enabled) {
3771 if enabled {
3772 (InvalidationStrategy::RefreshRequested, None)
3773 } else {
3774 self.splice_inlays(
3775 &self
3776 .visible_inlay_hints(cx)
3777 .iter()
3778 .map(|inlay| inlay.id)
3779 .collect::<Vec<InlayId>>(),
3780 Vec::new(),
3781 cx,
3782 );
3783 return;
3784 }
3785 } else {
3786 return;
3787 }
3788 }
3789 InlayHintRefreshReason::SettingsChange(new_settings) => {
3790 match self.inlay_hint_cache.update_settings(
3791 &self.buffer,
3792 new_settings,
3793 self.visible_inlay_hints(cx),
3794 cx,
3795 ) {
3796 ControlFlow::Break(Some(InlaySplice {
3797 to_remove,
3798 to_insert,
3799 })) => {
3800 self.splice_inlays(&to_remove, to_insert, cx);
3801 return;
3802 }
3803 ControlFlow::Break(None) => return,
3804 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3805 }
3806 }
3807 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3808 if let Some(InlaySplice {
3809 to_remove,
3810 to_insert,
3811 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3812 {
3813 self.splice_inlays(&to_remove, to_insert, cx);
3814 }
3815 return;
3816 }
3817 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3818 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3819 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3820 }
3821 InlayHintRefreshReason::RefreshRequested => {
3822 (InvalidationStrategy::RefreshRequested, None)
3823 }
3824 };
3825
3826 if let Some(InlaySplice {
3827 to_remove,
3828 to_insert,
3829 }) = self.inlay_hint_cache.spawn_hint_refresh(
3830 reason_description,
3831 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3832 invalidate_cache,
3833 ignore_debounce,
3834 cx,
3835 ) {
3836 self.splice_inlays(&to_remove, to_insert, cx);
3837 }
3838 }
3839
3840 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3841 self.display_map
3842 .read(cx)
3843 .current_inlays()
3844 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3845 .cloned()
3846 .collect()
3847 }
3848
3849 pub fn excerpts_for_inlay_hints_query(
3850 &self,
3851 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3852 cx: &mut Context<Editor>,
3853 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3854 let Some(project) = self.project.as_ref() else {
3855 return HashMap::default();
3856 };
3857 let project = project.read(cx);
3858 let multi_buffer = self.buffer().read(cx);
3859 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3860 let multi_buffer_visible_start = self
3861 .scroll_manager
3862 .anchor()
3863 .anchor
3864 .to_point(&multi_buffer_snapshot);
3865 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3866 multi_buffer_visible_start
3867 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3868 Bias::Left,
3869 );
3870 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3871 multi_buffer_snapshot
3872 .range_to_buffer_ranges(multi_buffer_visible_range)
3873 .into_iter()
3874 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3875 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3876 let buffer_file = project::File::from_dyn(buffer.file())?;
3877 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3878 let worktree_entry = buffer_worktree
3879 .read(cx)
3880 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3881 if worktree_entry.is_ignored {
3882 return None;
3883 }
3884
3885 let language = buffer.language()?;
3886 if let Some(restrict_to_languages) = restrict_to_languages {
3887 if !restrict_to_languages.contains(language) {
3888 return None;
3889 }
3890 }
3891 Some((
3892 excerpt_id,
3893 (
3894 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3895 buffer.version().clone(),
3896 excerpt_visible_range,
3897 ),
3898 ))
3899 })
3900 .collect()
3901 }
3902
3903 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3904 TextLayoutDetails {
3905 text_system: window.text_system().clone(),
3906 editor_style: self.style.clone().unwrap(),
3907 rem_size: window.rem_size(),
3908 scroll_anchor: self.scroll_manager.anchor(),
3909 visible_rows: self.visible_line_count(),
3910 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3911 }
3912 }
3913
3914 pub fn splice_inlays(
3915 &self,
3916 to_remove: &[InlayId],
3917 to_insert: Vec<Inlay>,
3918 cx: &mut Context<Self>,
3919 ) {
3920 self.display_map.update(cx, |display_map, cx| {
3921 display_map.splice_inlays(to_remove, to_insert, cx)
3922 });
3923 cx.notify();
3924 }
3925
3926 fn trigger_on_type_formatting(
3927 &self,
3928 input: String,
3929 window: &mut Window,
3930 cx: &mut Context<Self>,
3931 ) -> Option<Task<Result<()>>> {
3932 if input.len() != 1 {
3933 return None;
3934 }
3935
3936 let project = self.project.as_ref()?;
3937 let position = self.selections.newest_anchor().head();
3938 let (buffer, buffer_position) = self
3939 .buffer
3940 .read(cx)
3941 .text_anchor_for_position(position, cx)?;
3942
3943 let settings = language_settings::language_settings(
3944 buffer
3945 .read(cx)
3946 .language_at(buffer_position)
3947 .map(|l| l.name()),
3948 buffer.read(cx).file(),
3949 cx,
3950 );
3951 if !settings.use_on_type_format {
3952 return None;
3953 }
3954
3955 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3956 // hence we do LSP request & edit on host side only — add formats to host's history.
3957 let push_to_lsp_host_history = true;
3958 // If this is not the host, append its history with new edits.
3959 let push_to_client_history = project.read(cx).is_via_collab();
3960
3961 let on_type_formatting = project.update(cx, |project, cx| {
3962 project.on_type_format(
3963 buffer.clone(),
3964 buffer_position,
3965 input,
3966 push_to_lsp_host_history,
3967 cx,
3968 )
3969 });
3970 Some(cx.spawn_in(window, |editor, mut cx| async move {
3971 if let Some(transaction) = on_type_formatting.await? {
3972 if push_to_client_history {
3973 buffer
3974 .update(&mut cx, |buffer, _| {
3975 buffer.push_transaction(transaction, Instant::now());
3976 })
3977 .ok();
3978 }
3979 editor.update(&mut cx, |editor, cx| {
3980 editor.refresh_document_highlights(cx);
3981 })?;
3982 }
3983 Ok(())
3984 }))
3985 }
3986
3987 pub fn show_completions(
3988 &mut self,
3989 options: &ShowCompletions,
3990 window: &mut Window,
3991 cx: &mut Context<Self>,
3992 ) {
3993 if self.pending_rename.is_some() {
3994 return;
3995 }
3996
3997 let Some(provider) = self.completion_provider.as_ref() else {
3998 return;
3999 };
4000
4001 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4002 return;
4003 }
4004
4005 let position = self.selections.newest_anchor().head();
4006 if position.diff_base_anchor.is_some() {
4007 return;
4008 }
4009 let (buffer, buffer_position) =
4010 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4011 output
4012 } else {
4013 return;
4014 };
4015 let show_completion_documentation = buffer
4016 .read(cx)
4017 .snapshot()
4018 .settings_at(buffer_position, cx)
4019 .show_completion_documentation;
4020
4021 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4022
4023 let trigger_kind = match &options.trigger {
4024 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4025 CompletionTriggerKind::TRIGGER_CHARACTER
4026 }
4027 _ => CompletionTriggerKind::INVOKED,
4028 };
4029 let completion_context = CompletionContext {
4030 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4031 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4032 Some(String::from(trigger))
4033 } else {
4034 None
4035 }
4036 }),
4037 trigger_kind,
4038 };
4039 let completions =
4040 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4041 let sort_completions = provider.sort_completions();
4042
4043 let id = post_inc(&mut self.next_completion_id);
4044 let task = cx.spawn_in(window, |editor, mut cx| {
4045 async move {
4046 editor.update(&mut cx, |this, _| {
4047 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4048 })?;
4049 let completions = completions.await.log_err();
4050 let menu = if let Some(completions) = completions {
4051 let mut menu = CompletionsMenu::new(
4052 id,
4053 sort_completions,
4054 show_completion_documentation,
4055 position,
4056 buffer.clone(),
4057 completions.into(),
4058 );
4059
4060 menu.filter(query.as_deref(), cx.background_executor().clone())
4061 .await;
4062
4063 menu.visible().then_some(menu)
4064 } else {
4065 None
4066 };
4067
4068 editor.update_in(&mut cx, |editor, window, cx| {
4069 match editor.context_menu.borrow().as_ref() {
4070 None => {}
4071 Some(CodeContextMenu::Completions(prev_menu)) => {
4072 if prev_menu.id > id {
4073 return;
4074 }
4075 }
4076 _ => return,
4077 }
4078
4079 if editor.focus_handle.is_focused(window) && menu.is_some() {
4080 let mut menu = menu.unwrap();
4081 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4082
4083 *editor.context_menu.borrow_mut() =
4084 Some(CodeContextMenu::Completions(menu));
4085
4086 if editor.show_edit_predictions_in_menu() {
4087 editor.update_visible_inline_completion(window, cx);
4088 } else {
4089 editor.discard_inline_completion(false, cx);
4090 }
4091
4092 cx.notify();
4093 } else if editor.completion_tasks.len() <= 1 {
4094 // If there are no more completion tasks and the last menu was
4095 // empty, we should hide it.
4096 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4097 // If it was already hidden and we don't show inline
4098 // completions in the menu, we should also show the
4099 // inline-completion when available.
4100 if was_hidden && editor.show_edit_predictions_in_menu() {
4101 editor.update_visible_inline_completion(window, cx);
4102 }
4103 }
4104 })?;
4105
4106 Ok::<_, anyhow::Error>(())
4107 }
4108 .log_err()
4109 });
4110
4111 self.completion_tasks.push((id, task));
4112 }
4113
4114 pub fn confirm_completion(
4115 &mut self,
4116 action: &ConfirmCompletion,
4117 window: &mut Window,
4118 cx: &mut Context<Self>,
4119 ) -> Option<Task<Result<()>>> {
4120 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4121 }
4122
4123 pub fn compose_completion(
4124 &mut self,
4125 action: &ComposeCompletion,
4126 window: &mut Window,
4127 cx: &mut Context<Self>,
4128 ) -> Option<Task<Result<()>>> {
4129 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4130 }
4131
4132 fn do_completion(
4133 &mut self,
4134 item_ix: Option<usize>,
4135 intent: CompletionIntent,
4136 window: &mut Window,
4137 cx: &mut Context<Editor>,
4138 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4139 use language::ToOffset as _;
4140
4141 let completions_menu =
4142 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4143 menu
4144 } else {
4145 return None;
4146 };
4147
4148 let entries = completions_menu.entries.borrow();
4149 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4150 if self.show_edit_predictions_in_menu() {
4151 self.discard_inline_completion(true, cx);
4152 }
4153 let candidate_id = mat.candidate_id;
4154 drop(entries);
4155
4156 let buffer_handle = completions_menu.buffer;
4157 let completion = completions_menu
4158 .completions
4159 .borrow()
4160 .get(candidate_id)?
4161 .clone();
4162 cx.stop_propagation();
4163
4164 let snippet;
4165 let text;
4166
4167 if completion.is_snippet() {
4168 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4169 text = snippet.as_ref().unwrap().text.clone();
4170 } else {
4171 snippet = None;
4172 text = completion.new_text.clone();
4173 };
4174 let selections = self.selections.all::<usize>(cx);
4175 let buffer = buffer_handle.read(cx);
4176 let old_range = completion.old_range.to_offset(buffer);
4177 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4178
4179 let newest_selection = self.selections.newest_anchor();
4180 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4181 return None;
4182 }
4183
4184 let lookbehind = newest_selection
4185 .start
4186 .text_anchor
4187 .to_offset(buffer)
4188 .saturating_sub(old_range.start);
4189 let lookahead = old_range
4190 .end
4191 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4192 let mut common_prefix_len = old_text
4193 .bytes()
4194 .zip(text.bytes())
4195 .take_while(|(a, b)| a == b)
4196 .count();
4197
4198 let snapshot = self.buffer.read(cx).snapshot(cx);
4199 let mut range_to_replace: Option<Range<isize>> = None;
4200 let mut ranges = Vec::new();
4201 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4202 for selection in &selections {
4203 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4204 let start = selection.start.saturating_sub(lookbehind);
4205 let end = selection.end + lookahead;
4206 if selection.id == newest_selection.id {
4207 range_to_replace = Some(
4208 ((start + common_prefix_len) as isize - selection.start as isize)
4209 ..(end as isize - selection.start as isize),
4210 );
4211 }
4212 ranges.push(start + common_prefix_len..end);
4213 } else {
4214 common_prefix_len = 0;
4215 ranges.clear();
4216 ranges.extend(selections.iter().map(|s| {
4217 if s.id == newest_selection.id {
4218 range_to_replace = Some(
4219 old_range.start.to_offset_utf16(&snapshot).0 as isize
4220 - selection.start as isize
4221 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4222 - selection.start as isize,
4223 );
4224 old_range.clone()
4225 } else {
4226 s.start..s.end
4227 }
4228 }));
4229 break;
4230 }
4231 if !self.linked_edit_ranges.is_empty() {
4232 let start_anchor = snapshot.anchor_before(selection.head());
4233 let end_anchor = snapshot.anchor_after(selection.tail());
4234 if let Some(ranges) = self
4235 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4236 {
4237 for (buffer, edits) in ranges {
4238 linked_edits.entry(buffer.clone()).or_default().extend(
4239 edits
4240 .into_iter()
4241 .map(|range| (range, text[common_prefix_len..].to_owned())),
4242 );
4243 }
4244 }
4245 }
4246 }
4247 let text = &text[common_prefix_len..];
4248
4249 cx.emit(EditorEvent::InputHandled {
4250 utf16_range_to_replace: range_to_replace,
4251 text: text.into(),
4252 });
4253
4254 self.transact(window, cx, |this, window, cx| {
4255 if let Some(mut snippet) = snippet {
4256 snippet.text = text.to_string();
4257 for tabstop in snippet
4258 .tabstops
4259 .iter_mut()
4260 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4261 {
4262 tabstop.start -= common_prefix_len as isize;
4263 tabstop.end -= common_prefix_len as isize;
4264 }
4265
4266 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4267 } else {
4268 this.buffer.update(cx, |buffer, cx| {
4269 buffer.edit(
4270 ranges.iter().map(|range| (range.clone(), text)),
4271 this.autoindent_mode.clone(),
4272 cx,
4273 );
4274 });
4275 }
4276 for (buffer, edits) in linked_edits {
4277 buffer.update(cx, |buffer, cx| {
4278 let snapshot = buffer.snapshot();
4279 let edits = edits
4280 .into_iter()
4281 .map(|(range, text)| {
4282 use text::ToPoint as TP;
4283 let end_point = TP::to_point(&range.end, &snapshot);
4284 let start_point = TP::to_point(&range.start, &snapshot);
4285 (start_point..end_point, text)
4286 })
4287 .sorted_by_key(|(range, _)| range.start)
4288 .collect::<Vec<_>>();
4289 buffer.edit(edits, None, cx);
4290 })
4291 }
4292
4293 this.refresh_inline_completion(true, false, window, cx);
4294 });
4295
4296 let show_new_completions_on_confirm = completion
4297 .confirm
4298 .as_ref()
4299 .map_or(false, |confirm| confirm(intent, window, cx));
4300 if show_new_completions_on_confirm {
4301 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4302 }
4303
4304 let provider = self.completion_provider.as_ref()?;
4305 drop(completion);
4306 let apply_edits = provider.apply_additional_edits_for_completion(
4307 buffer_handle,
4308 completions_menu.completions.clone(),
4309 candidate_id,
4310 true,
4311 cx,
4312 );
4313
4314 let editor_settings = EditorSettings::get_global(cx);
4315 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4316 // After the code completion is finished, users often want to know what signatures are needed.
4317 // so we should automatically call signature_help
4318 self.show_signature_help(&ShowSignatureHelp, window, cx);
4319 }
4320
4321 Some(cx.foreground_executor().spawn(async move {
4322 apply_edits.await?;
4323 Ok(())
4324 }))
4325 }
4326
4327 pub fn toggle_code_actions(
4328 &mut self,
4329 action: &ToggleCodeActions,
4330 window: &mut Window,
4331 cx: &mut Context<Self>,
4332 ) {
4333 let mut context_menu = self.context_menu.borrow_mut();
4334 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4335 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4336 // Toggle if we're selecting the same one
4337 *context_menu = None;
4338 cx.notify();
4339 return;
4340 } else {
4341 // Otherwise, clear it and start a new one
4342 *context_menu = None;
4343 cx.notify();
4344 }
4345 }
4346 drop(context_menu);
4347 let snapshot = self.snapshot(window, cx);
4348 let deployed_from_indicator = action.deployed_from_indicator;
4349 let mut task = self.code_actions_task.take();
4350 let action = action.clone();
4351 cx.spawn_in(window, |editor, mut cx| async move {
4352 while let Some(prev_task) = task {
4353 prev_task.await.log_err();
4354 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4355 }
4356
4357 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4358 if editor.focus_handle.is_focused(window) {
4359 let multibuffer_point = action
4360 .deployed_from_indicator
4361 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4362 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4363 let (buffer, buffer_row) = snapshot
4364 .buffer_snapshot
4365 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4366 .and_then(|(buffer_snapshot, range)| {
4367 editor
4368 .buffer
4369 .read(cx)
4370 .buffer(buffer_snapshot.remote_id())
4371 .map(|buffer| (buffer, range.start.row))
4372 })?;
4373 let (_, code_actions) = editor
4374 .available_code_actions
4375 .clone()
4376 .and_then(|(location, code_actions)| {
4377 let snapshot = location.buffer.read(cx).snapshot();
4378 let point_range = location.range.to_point(&snapshot);
4379 let point_range = point_range.start.row..=point_range.end.row;
4380 if point_range.contains(&buffer_row) {
4381 Some((location, code_actions))
4382 } else {
4383 None
4384 }
4385 })
4386 .unzip();
4387 let buffer_id = buffer.read(cx).remote_id();
4388 let tasks = editor
4389 .tasks
4390 .get(&(buffer_id, buffer_row))
4391 .map(|t| Arc::new(t.to_owned()));
4392 if tasks.is_none() && code_actions.is_none() {
4393 return None;
4394 }
4395
4396 editor.completion_tasks.clear();
4397 editor.discard_inline_completion(false, cx);
4398 let task_context =
4399 tasks
4400 .as_ref()
4401 .zip(editor.project.clone())
4402 .map(|(tasks, project)| {
4403 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4404 });
4405
4406 Some(cx.spawn_in(window, |editor, mut cx| async move {
4407 let task_context = match task_context {
4408 Some(task_context) => task_context.await,
4409 None => None,
4410 };
4411 let resolved_tasks =
4412 tasks.zip(task_context).map(|(tasks, task_context)| {
4413 Rc::new(ResolvedTasks {
4414 templates: tasks.resolve(&task_context).collect(),
4415 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4416 multibuffer_point.row,
4417 tasks.column,
4418 )),
4419 })
4420 });
4421 let spawn_straight_away = resolved_tasks
4422 .as_ref()
4423 .map_or(false, |tasks| tasks.templates.len() == 1)
4424 && code_actions
4425 .as_ref()
4426 .map_or(true, |actions| actions.is_empty());
4427 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4428 *editor.context_menu.borrow_mut() =
4429 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4430 buffer,
4431 actions: CodeActionContents {
4432 tasks: resolved_tasks,
4433 actions: code_actions,
4434 },
4435 selected_item: Default::default(),
4436 scroll_handle: UniformListScrollHandle::default(),
4437 deployed_from_indicator,
4438 }));
4439 if spawn_straight_away {
4440 if let Some(task) = editor.confirm_code_action(
4441 &ConfirmCodeAction { item_ix: Some(0) },
4442 window,
4443 cx,
4444 ) {
4445 cx.notify();
4446 return task;
4447 }
4448 }
4449 cx.notify();
4450 Task::ready(Ok(()))
4451 }) {
4452 task.await
4453 } else {
4454 Ok(())
4455 }
4456 }))
4457 } else {
4458 Some(Task::ready(Ok(())))
4459 }
4460 })?;
4461 if let Some(task) = spawned_test_task {
4462 task.await?;
4463 }
4464
4465 Ok::<_, anyhow::Error>(())
4466 })
4467 .detach_and_log_err(cx);
4468 }
4469
4470 pub fn confirm_code_action(
4471 &mut self,
4472 action: &ConfirmCodeAction,
4473 window: &mut Window,
4474 cx: &mut Context<Self>,
4475 ) -> Option<Task<Result<()>>> {
4476 let actions_menu =
4477 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4478 menu
4479 } else {
4480 return None;
4481 };
4482 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4483 let action = actions_menu.actions.get(action_ix)?;
4484 let title = action.label();
4485 let buffer = actions_menu.buffer;
4486 let workspace = self.workspace()?;
4487
4488 match action {
4489 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4490 workspace.update(cx, |workspace, cx| {
4491 workspace::tasks::schedule_resolved_task(
4492 workspace,
4493 task_source_kind,
4494 resolved_task,
4495 false,
4496 cx,
4497 );
4498
4499 Some(Task::ready(Ok(())))
4500 })
4501 }
4502 CodeActionsItem::CodeAction {
4503 excerpt_id,
4504 action,
4505 provider,
4506 } => {
4507 let apply_code_action =
4508 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4509 let workspace = workspace.downgrade();
4510 Some(cx.spawn_in(window, |editor, cx| async move {
4511 let project_transaction = apply_code_action.await?;
4512 Self::open_project_transaction(
4513 &editor,
4514 workspace,
4515 project_transaction,
4516 title,
4517 cx,
4518 )
4519 .await
4520 }))
4521 }
4522 }
4523 }
4524
4525 pub async fn open_project_transaction(
4526 this: &WeakEntity<Editor>,
4527 workspace: WeakEntity<Workspace>,
4528 transaction: ProjectTransaction,
4529 title: String,
4530 mut cx: AsyncWindowContext,
4531 ) -> Result<()> {
4532 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4533 cx.update(|_, cx| {
4534 entries.sort_unstable_by_key(|(buffer, _)| {
4535 buffer.read(cx).file().map(|f| f.path().clone())
4536 });
4537 })?;
4538
4539 // If the project transaction's edits are all contained within this editor, then
4540 // avoid opening a new editor to display them.
4541
4542 if let Some((buffer, transaction)) = entries.first() {
4543 if entries.len() == 1 {
4544 let excerpt = this.update(&mut cx, |editor, cx| {
4545 editor
4546 .buffer()
4547 .read(cx)
4548 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4549 })?;
4550 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4551 if excerpted_buffer == *buffer {
4552 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4553 let excerpt_range = excerpt_range.to_offset(buffer);
4554 buffer
4555 .edited_ranges_for_transaction::<usize>(transaction)
4556 .all(|range| {
4557 excerpt_range.start <= range.start
4558 && excerpt_range.end >= range.end
4559 })
4560 })?;
4561
4562 if all_edits_within_excerpt {
4563 return Ok(());
4564 }
4565 }
4566 }
4567 }
4568 } else {
4569 return Ok(());
4570 }
4571
4572 let mut ranges_to_highlight = Vec::new();
4573 let excerpt_buffer = cx.new(|cx| {
4574 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4575 for (buffer_handle, transaction) in &entries {
4576 let buffer = buffer_handle.read(cx);
4577 ranges_to_highlight.extend(
4578 multibuffer.push_excerpts_with_context_lines(
4579 buffer_handle.clone(),
4580 buffer
4581 .edited_ranges_for_transaction::<usize>(transaction)
4582 .collect(),
4583 DEFAULT_MULTIBUFFER_CONTEXT,
4584 cx,
4585 ),
4586 );
4587 }
4588 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4589 multibuffer
4590 })?;
4591
4592 workspace.update_in(&mut cx, |workspace, window, cx| {
4593 let project = workspace.project().clone();
4594 let editor = cx
4595 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4596 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4597 editor.update(cx, |editor, cx| {
4598 editor.highlight_background::<Self>(
4599 &ranges_to_highlight,
4600 |theme| theme.editor_highlighted_line_background,
4601 cx,
4602 );
4603 });
4604 })?;
4605
4606 Ok(())
4607 }
4608
4609 pub fn clear_code_action_providers(&mut self) {
4610 self.code_action_providers.clear();
4611 self.available_code_actions.take();
4612 }
4613
4614 pub fn add_code_action_provider(
4615 &mut self,
4616 provider: Rc<dyn CodeActionProvider>,
4617 window: &mut Window,
4618 cx: &mut Context<Self>,
4619 ) {
4620 if self
4621 .code_action_providers
4622 .iter()
4623 .any(|existing_provider| existing_provider.id() == provider.id())
4624 {
4625 return;
4626 }
4627
4628 self.code_action_providers.push(provider);
4629 self.refresh_code_actions(window, cx);
4630 }
4631
4632 pub fn remove_code_action_provider(
4633 &mut self,
4634 id: Arc<str>,
4635 window: &mut Window,
4636 cx: &mut Context<Self>,
4637 ) {
4638 self.code_action_providers
4639 .retain(|provider| provider.id() != id);
4640 self.refresh_code_actions(window, cx);
4641 }
4642
4643 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4644 let buffer = self.buffer.read(cx);
4645 let newest_selection = self.selections.newest_anchor().clone();
4646 if newest_selection.head().diff_base_anchor.is_some() {
4647 return None;
4648 }
4649 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4650 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4651 if start_buffer != end_buffer {
4652 return None;
4653 }
4654
4655 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4656 cx.background_executor()
4657 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4658 .await;
4659
4660 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4661 let providers = this.code_action_providers.clone();
4662 let tasks = this
4663 .code_action_providers
4664 .iter()
4665 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4666 .collect::<Vec<_>>();
4667 (providers, tasks)
4668 })?;
4669
4670 let mut actions = Vec::new();
4671 for (provider, provider_actions) in
4672 providers.into_iter().zip(future::join_all(tasks).await)
4673 {
4674 if let Some(provider_actions) = provider_actions.log_err() {
4675 actions.extend(provider_actions.into_iter().map(|action| {
4676 AvailableCodeAction {
4677 excerpt_id: newest_selection.start.excerpt_id,
4678 action,
4679 provider: provider.clone(),
4680 }
4681 }));
4682 }
4683 }
4684
4685 this.update(&mut cx, |this, cx| {
4686 this.available_code_actions = if actions.is_empty() {
4687 None
4688 } else {
4689 Some((
4690 Location {
4691 buffer: start_buffer,
4692 range: start..end,
4693 },
4694 actions.into(),
4695 ))
4696 };
4697 cx.notify();
4698 })
4699 }));
4700 None
4701 }
4702
4703 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4704 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4705 self.show_git_blame_inline = false;
4706
4707 self.show_git_blame_inline_delay_task =
4708 Some(cx.spawn_in(window, |this, mut cx| async move {
4709 cx.background_executor().timer(delay).await;
4710
4711 this.update(&mut cx, |this, cx| {
4712 this.show_git_blame_inline = true;
4713 cx.notify();
4714 })
4715 .log_err();
4716 }));
4717 }
4718 }
4719
4720 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4721 if self.pending_rename.is_some() {
4722 return None;
4723 }
4724
4725 let provider = self.semantics_provider.clone()?;
4726 let buffer = self.buffer.read(cx);
4727 let newest_selection = self.selections.newest_anchor().clone();
4728 let cursor_position = newest_selection.head();
4729 let (cursor_buffer, cursor_buffer_position) =
4730 buffer.text_anchor_for_position(cursor_position, cx)?;
4731 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4732 if cursor_buffer != tail_buffer {
4733 return None;
4734 }
4735 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4736 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4737 cx.background_executor()
4738 .timer(Duration::from_millis(debounce))
4739 .await;
4740
4741 let highlights = if let Some(highlights) = cx
4742 .update(|cx| {
4743 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4744 })
4745 .ok()
4746 .flatten()
4747 {
4748 highlights.await.log_err()
4749 } else {
4750 None
4751 };
4752
4753 if let Some(highlights) = highlights {
4754 this.update(&mut cx, |this, cx| {
4755 if this.pending_rename.is_some() {
4756 return;
4757 }
4758
4759 let buffer_id = cursor_position.buffer_id;
4760 let buffer = this.buffer.read(cx);
4761 if !buffer
4762 .text_anchor_for_position(cursor_position, cx)
4763 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4764 {
4765 return;
4766 }
4767
4768 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4769 let mut write_ranges = Vec::new();
4770 let mut read_ranges = Vec::new();
4771 for highlight in highlights {
4772 for (excerpt_id, excerpt_range) in
4773 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4774 {
4775 let start = highlight
4776 .range
4777 .start
4778 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4779 let end = highlight
4780 .range
4781 .end
4782 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4783 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4784 continue;
4785 }
4786
4787 let range = Anchor {
4788 buffer_id,
4789 excerpt_id,
4790 text_anchor: start,
4791 diff_base_anchor: None,
4792 }..Anchor {
4793 buffer_id,
4794 excerpt_id,
4795 text_anchor: end,
4796 diff_base_anchor: None,
4797 };
4798 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4799 write_ranges.push(range);
4800 } else {
4801 read_ranges.push(range);
4802 }
4803 }
4804 }
4805
4806 this.highlight_background::<DocumentHighlightRead>(
4807 &read_ranges,
4808 |theme| theme.editor_document_highlight_read_background,
4809 cx,
4810 );
4811 this.highlight_background::<DocumentHighlightWrite>(
4812 &write_ranges,
4813 |theme| theme.editor_document_highlight_write_background,
4814 cx,
4815 );
4816 cx.notify();
4817 })
4818 .log_err();
4819 }
4820 }));
4821 None
4822 }
4823
4824 pub fn refresh_selected_text_highlights(
4825 &mut self,
4826 window: &mut Window,
4827 cx: &mut Context<Editor>,
4828 ) {
4829 self.selection_highlight_task.take();
4830 if !EditorSettings::get_global(cx).selection_highlight {
4831 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4832 return;
4833 }
4834 if self.selections.count() != 1 || self.selections.line_mode {
4835 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4836 return;
4837 }
4838 let selection = self.selections.newest::<Point>(cx);
4839 if selection.is_empty() || selection.start.row != selection.end.row {
4840 self.clear_background_highlights::<SelectedTextHighlight>(cx);
4841 return;
4842 }
4843 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
4844 self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
4845 cx.background_executor()
4846 .timer(Duration::from_millis(debounce))
4847 .await;
4848 let Some(Some(matches_task)) = editor
4849 .update_in(&mut cx, |editor, _, cx| {
4850 if editor.selections.count() != 1 || editor.selections.line_mode {
4851 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4852 return None;
4853 }
4854 let selection = editor.selections.newest::<Point>(cx);
4855 if selection.is_empty() || selection.start.row != selection.end.row {
4856 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4857 return None;
4858 }
4859 let buffer = editor.buffer().read(cx).snapshot(cx);
4860 let query = buffer.text_for_range(selection.range()).collect::<String>();
4861 if query.trim().is_empty() {
4862 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4863 return None;
4864 }
4865 Some(cx.background_spawn(async move {
4866 let mut ranges = Vec::new();
4867 let selection_anchors = selection.range().to_anchors(&buffer);
4868 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
4869 for (search_buffer, search_range, excerpt_id) in
4870 buffer.range_to_buffer_ranges(range)
4871 {
4872 ranges.extend(
4873 project::search::SearchQuery::text(
4874 query.clone(),
4875 false,
4876 false,
4877 false,
4878 Default::default(),
4879 Default::default(),
4880 None,
4881 )
4882 .unwrap()
4883 .search(search_buffer, Some(search_range.clone()))
4884 .await
4885 .into_iter()
4886 .filter_map(
4887 |match_range| {
4888 let start = search_buffer.anchor_after(
4889 search_range.start + match_range.start,
4890 );
4891 let end = search_buffer.anchor_before(
4892 search_range.start + match_range.end,
4893 );
4894 let range = Anchor::range_in_buffer(
4895 excerpt_id,
4896 search_buffer.remote_id(),
4897 start..end,
4898 );
4899 (range != selection_anchors).then_some(range)
4900 },
4901 ),
4902 );
4903 }
4904 }
4905 ranges
4906 }))
4907 })
4908 .log_err()
4909 else {
4910 return;
4911 };
4912 let matches = matches_task.await;
4913 editor
4914 .update_in(&mut cx, |editor, _, cx| {
4915 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
4916 if !matches.is_empty() {
4917 editor.highlight_background::<SelectedTextHighlight>(
4918 &matches,
4919 |theme| theme.editor_document_highlight_bracket_background,
4920 cx,
4921 )
4922 }
4923 })
4924 .log_err();
4925 }));
4926 }
4927
4928 pub fn refresh_inline_completion(
4929 &mut self,
4930 debounce: bool,
4931 user_requested: bool,
4932 window: &mut Window,
4933 cx: &mut Context<Self>,
4934 ) -> Option<()> {
4935 let provider = self.edit_prediction_provider()?;
4936 let cursor = self.selections.newest_anchor().head();
4937 let (buffer, cursor_buffer_position) =
4938 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4939
4940 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4941 self.discard_inline_completion(false, cx);
4942 return None;
4943 }
4944
4945 if !user_requested
4946 && (!self.should_show_edit_predictions()
4947 || !self.is_focused(window)
4948 || buffer.read(cx).is_empty())
4949 {
4950 self.discard_inline_completion(false, cx);
4951 return None;
4952 }
4953
4954 self.update_visible_inline_completion(window, cx);
4955 provider.refresh(
4956 self.project.clone(),
4957 buffer,
4958 cursor_buffer_position,
4959 debounce,
4960 cx,
4961 );
4962 Some(())
4963 }
4964
4965 fn show_edit_predictions_in_menu(&self) -> bool {
4966 match self.edit_prediction_settings {
4967 EditPredictionSettings::Disabled => false,
4968 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
4969 }
4970 }
4971
4972 pub fn edit_predictions_enabled(&self) -> bool {
4973 match self.edit_prediction_settings {
4974 EditPredictionSettings::Disabled => false,
4975 EditPredictionSettings::Enabled { .. } => true,
4976 }
4977 }
4978
4979 fn edit_prediction_requires_modifier(&self) -> bool {
4980 match self.edit_prediction_settings {
4981 EditPredictionSettings::Disabled => false,
4982 EditPredictionSettings::Enabled {
4983 preview_requires_modifier,
4984 ..
4985 } => preview_requires_modifier,
4986 }
4987 }
4988
4989 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
4990 if self.edit_prediction_provider.is_none() {
4991 self.edit_prediction_settings = EditPredictionSettings::Disabled;
4992 } else {
4993 let selection = self.selections.newest_anchor();
4994 let cursor = selection.head();
4995
4996 if let Some((buffer, cursor_buffer_position)) =
4997 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4998 {
4999 self.edit_prediction_settings =
5000 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5001 }
5002 }
5003 }
5004
5005 fn edit_prediction_settings_at_position(
5006 &self,
5007 buffer: &Entity<Buffer>,
5008 buffer_position: language::Anchor,
5009 cx: &App,
5010 ) -> EditPredictionSettings {
5011 if self.mode != EditorMode::Full
5012 || !self.show_inline_completions_override.unwrap_or(true)
5013 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5014 {
5015 return EditPredictionSettings::Disabled;
5016 }
5017
5018 let buffer = buffer.read(cx);
5019
5020 let file = buffer.file();
5021
5022 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5023 return EditPredictionSettings::Disabled;
5024 };
5025
5026 let by_provider = matches!(
5027 self.menu_inline_completions_policy,
5028 MenuInlineCompletionsPolicy::ByProvider
5029 );
5030
5031 let show_in_menu = by_provider
5032 && self
5033 .edit_prediction_provider
5034 .as_ref()
5035 .map_or(false, |provider| {
5036 provider.provider.show_completions_in_menu()
5037 });
5038
5039 let preview_requires_modifier =
5040 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5041
5042 EditPredictionSettings::Enabled {
5043 show_in_menu,
5044 preview_requires_modifier,
5045 }
5046 }
5047
5048 fn should_show_edit_predictions(&self) -> bool {
5049 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5050 }
5051
5052 pub fn edit_prediction_preview_is_active(&self) -> bool {
5053 matches!(
5054 self.edit_prediction_preview,
5055 EditPredictionPreview::Active { .. }
5056 )
5057 }
5058
5059 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5060 let cursor = self.selections.newest_anchor().head();
5061 if let Some((buffer, cursor_position)) =
5062 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5063 {
5064 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5065 } else {
5066 false
5067 }
5068 }
5069
5070 fn edit_predictions_enabled_in_buffer(
5071 &self,
5072 buffer: &Entity<Buffer>,
5073 buffer_position: language::Anchor,
5074 cx: &App,
5075 ) -> bool {
5076 maybe!({
5077 let provider = self.edit_prediction_provider()?;
5078 if !provider.is_enabled(&buffer, buffer_position, cx) {
5079 return Some(false);
5080 }
5081 let buffer = buffer.read(cx);
5082 let Some(file) = buffer.file() else {
5083 return Some(true);
5084 };
5085 let settings = all_language_settings(Some(file), cx);
5086 Some(settings.edit_predictions_enabled_for_file(file, cx))
5087 })
5088 .unwrap_or(false)
5089 }
5090
5091 fn cycle_inline_completion(
5092 &mut self,
5093 direction: Direction,
5094 window: &mut Window,
5095 cx: &mut Context<Self>,
5096 ) -> Option<()> {
5097 let provider = self.edit_prediction_provider()?;
5098 let cursor = self.selections.newest_anchor().head();
5099 let (buffer, cursor_buffer_position) =
5100 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5101 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5102 return None;
5103 }
5104
5105 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5106 self.update_visible_inline_completion(window, cx);
5107
5108 Some(())
5109 }
5110
5111 pub fn show_inline_completion(
5112 &mut self,
5113 _: &ShowEditPrediction,
5114 window: &mut Window,
5115 cx: &mut Context<Self>,
5116 ) {
5117 if !self.has_active_inline_completion() {
5118 self.refresh_inline_completion(false, true, window, cx);
5119 return;
5120 }
5121
5122 self.update_visible_inline_completion(window, cx);
5123 }
5124
5125 pub fn display_cursor_names(
5126 &mut self,
5127 _: &DisplayCursorNames,
5128 window: &mut Window,
5129 cx: &mut Context<Self>,
5130 ) {
5131 self.show_cursor_names(window, cx);
5132 }
5133
5134 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5135 self.show_cursor_names = true;
5136 cx.notify();
5137 cx.spawn_in(window, |this, mut cx| async move {
5138 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5139 this.update(&mut cx, |this, cx| {
5140 this.show_cursor_names = false;
5141 cx.notify()
5142 })
5143 .ok()
5144 })
5145 .detach();
5146 }
5147
5148 pub fn next_edit_prediction(
5149 &mut self,
5150 _: &NextEditPrediction,
5151 window: &mut Window,
5152 cx: &mut Context<Self>,
5153 ) {
5154 if self.has_active_inline_completion() {
5155 self.cycle_inline_completion(Direction::Next, window, cx);
5156 } else {
5157 let is_copilot_disabled = self
5158 .refresh_inline_completion(false, true, window, cx)
5159 .is_none();
5160 if is_copilot_disabled {
5161 cx.propagate();
5162 }
5163 }
5164 }
5165
5166 pub fn previous_edit_prediction(
5167 &mut self,
5168 _: &PreviousEditPrediction,
5169 window: &mut Window,
5170 cx: &mut Context<Self>,
5171 ) {
5172 if self.has_active_inline_completion() {
5173 self.cycle_inline_completion(Direction::Prev, window, cx);
5174 } else {
5175 let is_copilot_disabled = self
5176 .refresh_inline_completion(false, true, window, cx)
5177 .is_none();
5178 if is_copilot_disabled {
5179 cx.propagate();
5180 }
5181 }
5182 }
5183
5184 pub fn accept_edit_prediction(
5185 &mut self,
5186 _: &AcceptEditPrediction,
5187 window: &mut Window,
5188 cx: &mut Context<Self>,
5189 ) {
5190 if self.show_edit_predictions_in_menu() {
5191 self.hide_context_menu(window, cx);
5192 }
5193
5194 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5195 return;
5196 };
5197
5198 self.report_inline_completion_event(
5199 active_inline_completion.completion_id.clone(),
5200 true,
5201 cx,
5202 );
5203
5204 match &active_inline_completion.completion {
5205 InlineCompletion::Move { target, .. } => {
5206 let target = *target;
5207
5208 if let Some(position_map) = &self.last_position_map {
5209 if position_map
5210 .visible_row_range
5211 .contains(&target.to_display_point(&position_map.snapshot).row())
5212 || !self.edit_prediction_requires_modifier()
5213 {
5214 self.unfold_ranges(&[target..target], true, false, cx);
5215 // Note that this is also done in vim's handler of the Tab action.
5216 self.change_selections(
5217 Some(Autoscroll::newest()),
5218 window,
5219 cx,
5220 |selections| {
5221 selections.select_anchor_ranges([target..target]);
5222 },
5223 );
5224 self.clear_row_highlights::<EditPredictionPreview>();
5225
5226 self.edit_prediction_preview
5227 .set_previous_scroll_position(None);
5228 } else {
5229 self.edit_prediction_preview
5230 .set_previous_scroll_position(Some(
5231 position_map.snapshot.scroll_anchor,
5232 ));
5233
5234 self.highlight_rows::<EditPredictionPreview>(
5235 target..target,
5236 cx.theme().colors().editor_highlighted_line_background,
5237 true,
5238 cx,
5239 );
5240 self.request_autoscroll(Autoscroll::fit(), cx);
5241 }
5242 }
5243 }
5244 InlineCompletion::Edit { edits, .. } => {
5245 if let Some(provider) = self.edit_prediction_provider() {
5246 provider.accept(cx);
5247 }
5248
5249 let snapshot = self.buffer.read(cx).snapshot(cx);
5250 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5251
5252 self.buffer.update(cx, |buffer, cx| {
5253 buffer.edit(edits.iter().cloned(), None, cx)
5254 });
5255
5256 self.change_selections(None, window, cx, |s| {
5257 s.select_anchor_ranges([last_edit_end..last_edit_end])
5258 });
5259
5260 self.update_visible_inline_completion(window, cx);
5261 if self.active_inline_completion.is_none() {
5262 self.refresh_inline_completion(true, true, window, cx);
5263 }
5264
5265 cx.notify();
5266 }
5267 }
5268
5269 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5270 }
5271
5272 pub fn accept_partial_inline_completion(
5273 &mut self,
5274 _: &AcceptPartialEditPrediction,
5275 window: &mut Window,
5276 cx: &mut Context<Self>,
5277 ) {
5278 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5279 return;
5280 };
5281 if self.selections.count() != 1 {
5282 return;
5283 }
5284
5285 self.report_inline_completion_event(
5286 active_inline_completion.completion_id.clone(),
5287 true,
5288 cx,
5289 );
5290
5291 match &active_inline_completion.completion {
5292 InlineCompletion::Move { target, .. } => {
5293 let target = *target;
5294 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5295 selections.select_anchor_ranges([target..target]);
5296 });
5297 }
5298 InlineCompletion::Edit { edits, .. } => {
5299 // Find an insertion that starts at the cursor position.
5300 let snapshot = self.buffer.read(cx).snapshot(cx);
5301 let cursor_offset = self.selections.newest::<usize>(cx).head();
5302 let insertion = edits.iter().find_map(|(range, text)| {
5303 let range = range.to_offset(&snapshot);
5304 if range.is_empty() && range.start == cursor_offset {
5305 Some(text)
5306 } else {
5307 None
5308 }
5309 });
5310
5311 if let Some(text) = insertion {
5312 let mut partial_completion = text
5313 .chars()
5314 .by_ref()
5315 .take_while(|c| c.is_alphabetic())
5316 .collect::<String>();
5317 if partial_completion.is_empty() {
5318 partial_completion = text
5319 .chars()
5320 .by_ref()
5321 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5322 .collect::<String>();
5323 }
5324
5325 cx.emit(EditorEvent::InputHandled {
5326 utf16_range_to_replace: None,
5327 text: partial_completion.clone().into(),
5328 });
5329
5330 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5331
5332 self.refresh_inline_completion(true, true, window, cx);
5333 cx.notify();
5334 } else {
5335 self.accept_edit_prediction(&Default::default(), window, cx);
5336 }
5337 }
5338 }
5339 }
5340
5341 fn discard_inline_completion(
5342 &mut self,
5343 should_report_inline_completion_event: bool,
5344 cx: &mut Context<Self>,
5345 ) -> bool {
5346 if should_report_inline_completion_event {
5347 let completion_id = self
5348 .active_inline_completion
5349 .as_ref()
5350 .and_then(|active_completion| active_completion.completion_id.clone());
5351
5352 self.report_inline_completion_event(completion_id, false, cx);
5353 }
5354
5355 if let Some(provider) = self.edit_prediction_provider() {
5356 provider.discard(cx);
5357 }
5358
5359 self.take_active_inline_completion(cx)
5360 }
5361
5362 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5363 let Some(provider) = self.edit_prediction_provider() else {
5364 return;
5365 };
5366
5367 let Some((_, buffer, _)) = self
5368 .buffer
5369 .read(cx)
5370 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5371 else {
5372 return;
5373 };
5374
5375 let extension = buffer
5376 .read(cx)
5377 .file()
5378 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5379
5380 let event_type = match accepted {
5381 true => "Edit Prediction Accepted",
5382 false => "Edit Prediction Discarded",
5383 };
5384 telemetry::event!(
5385 event_type,
5386 provider = provider.name(),
5387 prediction_id = id,
5388 suggestion_accepted = accepted,
5389 file_extension = extension,
5390 );
5391 }
5392
5393 pub fn has_active_inline_completion(&self) -> bool {
5394 self.active_inline_completion.is_some()
5395 }
5396
5397 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5398 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5399 return false;
5400 };
5401
5402 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5403 self.clear_highlights::<InlineCompletionHighlight>(cx);
5404 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5405 true
5406 }
5407
5408 /// Returns true when we're displaying the edit prediction popover below the cursor
5409 /// like we are not previewing and the LSP autocomplete menu is visible
5410 /// or we are in `when_holding_modifier` mode.
5411 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5412 if self.edit_prediction_preview_is_active()
5413 || !self.show_edit_predictions_in_menu()
5414 || !self.edit_predictions_enabled()
5415 {
5416 return false;
5417 }
5418
5419 if self.has_visible_completions_menu() {
5420 return true;
5421 }
5422
5423 has_completion && self.edit_prediction_requires_modifier()
5424 }
5425
5426 fn handle_modifiers_changed(
5427 &mut self,
5428 modifiers: Modifiers,
5429 position_map: &PositionMap,
5430 window: &mut Window,
5431 cx: &mut Context<Self>,
5432 ) {
5433 if self.show_edit_predictions_in_menu() {
5434 self.update_edit_prediction_preview(&modifiers, window, cx);
5435 }
5436
5437 self.update_selection_mode(&modifiers, position_map, window, cx);
5438
5439 let mouse_position = window.mouse_position();
5440 if !position_map.text_hitbox.is_hovered(window) {
5441 return;
5442 }
5443
5444 self.update_hovered_link(
5445 position_map.point_for_position(mouse_position),
5446 &position_map.snapshot,
5447 modifiers,
5448 window,
5449 cx,
5450 )
5451 }
5452
5453 fn update_selection_mode(
5454 &mut self,
5455 modifiers: &Modifiers,
5456 position_map: &PositionMap,
5457 window: &mut Window,
5458 cx: &mut Context<Self>,
5459 ) {
5460 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5461 return;
5462 }
5463
5464 let mouse_position = window.mouse_position();
5465 let point_for_position = position_map.point_for_position(mouse_position);
5466 let position = point_for_position.previous_valid;
5467
5468 self.select(
5469 SelectPhase::BeginColumnar {
5470 position,
5471 reset: false,
5472 goal_column: point_for_position.exact_unclipped.column(),
5473 },
5474 window,
5475 cx,
5476 );
5477 }
5478
5479 fn update_edit_prediction_preview(
5480 &mut self,
5481 modifiers: &Modifiers,
5482 window: &mut Window,
5483 cx: &mut Context<Self>,
5484 ) {
5485 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5486 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5487 return;
5488 };
5489
5490 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5491 if matches!(
5492 self.edit_prediction_preview,
5493 EditPredictionPreview::Inactive { .. }
5494 ) {
5495 self.edit_prediction_preview = EditPredictionPreview::Active {
5496 previous_scroll_position: None,
5497 since: Instant::now(),
5498 };
5499
5500 self.update_visible_inline_completion(window, cx);
5501 cx.notify();
5502 }
5503 } else if let EditPredictionPreview::Active {
5504 previous_scroll_position,
5505 since,
5506 } = self.edit_prediction_preview
5507 {
5508 if let (Some(previous_scroll_position), Some(position_map)) =
5509 (previous_scroll_position, self.last_position_map.as_ref())
5510 {
5511 self.set_scroll_position(
5512 previous_scroll_position
5513 .scroll_position(&position_map.snapshot.display_snapshot),
5514 window,
5515 cx,
5516 );
5517 }
5518
5519 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5520 released_too_fast: since.elapsed() < Duration::from_millis(200),
5521 };
5522 self.clear_row_highlights::<EditPredictionPreview>();
5523 self.update_visible_inline_completion(window, cx);
5524 cx.notify();
5525 }
5526 }
5527
5528 fn update_visible_inline_completion(
5529 &mut self,
5530 _window: &mut Window,
5531 cx: &mut Context<Self>,
5532 ) -> Option<()> {
5533 let selection = self.selections.newest_anchor();
5534 let cursor = selection.head();
5535 let multibuffer = self.buffer.read(cx).snapshot(cx);
5536 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5537 let excerpt_id = cursor.excerpt_id;
5538
5539 let show_in_menu = self.show_edit_predictions_in_menu();
5540 let completions_menu_has_precedence = !show_in_menu
5541 && (self.context_menu.borrow().is_some()
5542 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5543
5544 if completions_menu_has_precedence
5545 || !offset_selection.is_empty()
5546 || self
5547 .active_inline_completion
5548 .as_ref()
5549 .map_or(false, |completion| {
5550 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5551 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5552 !invalidation_range.contains(&offset_selection.head())
5553 })
5554 {
5555 self.discard_inline_completion(false, cx);
5556 return None;
5557 }
5558
5559 self.take_active_inline_completion(cx);
5560 let Some(provider) = self.edit_prediction_provider() else {
5561 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5562 return None;
5563 };
5564
5565 let (buffer, cursor_buffer_position) =
5566 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5567
5568 self.edit_prediction_settings =
5569 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5570
5571 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5572
5573 if self.edit_prediction_indent_conflict {
5574 let cursor_point = cursor.to_point(&multibuffer);
5575
5576 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5577
5578 if let Some((_, indent)) = indents.iter().next() {
5579 if indent.len == cursor_point.column {
5580 self.edit_prediction_indent_conflict = false;
5581 }
5582 }
5583 }
5584
5585 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5586 let edits = inline_completion
5587 .edits
5588 .into_iter()
5589 .flat_map(|(range, new_text)| {
5590 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5591 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5592 Some((start..end, new_text))
5593 })
5594 .collect::<Vec<_>>();
5595 if edits.is_empty() {
5596 return None;
5597 }
5598
5599 let first_edit_start = edits.first().unwrap().0.start;
5600 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5601 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5602
5603 let last_edit_end = edits.last().unwrap().0.end;
5604 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5605 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5606
5607 let cursor_row = cursor.to_point(&multibuffer).row;
5608
5609 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5610
5611 let mut inlay_ids = Vec::new();
5612 let invalidation_row_range;
5613 let move_invalidation_row_range = if cursor_row < edit_start_row {
5614 Some(cursor_row..edit_end_row)
5615 } else if cursor_row > edit_end_row {
5616 Some(edit_start_row..cursor_row)
5617 } else {
5618 None
5619 };
5620 let is_move =
5621 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5622 let completion = if is_move {
5623 invalidation_row_range =
5624 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5625 let target = first_edit_start;
5626 InlineCompletion::Move { target, snapshot }
5627 } else {
5628 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5629 && !self.inline_completions_hidden_for_vim_mode;
5630
5631 if show_completions_in_buffer {
5632 if edits
5633 .iter()
5634 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5635 {
5636 let mut inlays = Vec::new();
5637 for (range, new_text) in &edits {
5638 let inlay = Inlay::inline_completion(
5639 post_inc(&mut self.next_inlay_id),
5640 range.start,
5641 new_text.as_str(),
5642 );
5643 inlay_ids.push(inlay.id);
5644 inlays.push(inlay);
5645 }
5646
5647 self.splice_inlays(&[], inlays, cx);
5648 } else {
5649 let background_color = cx.theme().status().deleted_background;
5650 self.highlight_text::<InlineCompletionHighlight>(
5651 edits.iter().map(|(range, _)| range.clone()).collect(),
5652 HighlightStyle {
5653 background_color: Some(background_color),
5654 ..Default::default()
5655 },
5656 cx,
5657 );
5658 }
5659 }
5660
5661 invalidation_row_range = edit_start_row..edit_end_row;
5662
5663 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5664 if provider.show_tab_accept_marker() {
5665 EditDisplayMode::TabAccept
5666 } else {
5667 EditDisplayMode::Inline
5668 }
5669 } else {
5670 EditDisplayMode::DiffPopover
5671 };
5672
5673 InlineCompletion::Edit {
5674 edits,
5675 edit_preview: inline_completion.edit_preview,
5676 display_mode,
5677 snapshot,
5678 }
5679 };
5680
5681 let invalidation_range = multibuffer
5682 .anchor_before(Point::new(invalidation_row_range.start, 0))
5683 ..multibuffer.anchor_after(Point::new(
5684 invalidation_row_range.end,
5685 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5686 ));
5687
5688 self.stale_inline_completion_in_menu = None;
5689 self.active_inline_completion = Some(InlineCompletionState {
5690 inlay_ids,
5691 completion,
5692 completion_id: inline_completion.id,
5693 invalidation_range,
5694 });
5695
5696 cx.notify();
5697
5698 Some(())
5699 }
5700
5701 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5702 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5703 }
5704
5705 fn render_code_actions_indicator(
5706 &self,
5707 _style: &EditorStyle,
5708 row: DisplayRow,
5709 is_active: bool,
5710 cx: &mut Context<Self>,
5711 ) -> Option<IconButton> {
5712 if self.available_code_actions.is_some() {
5713 Some(
5714 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5715 .shape(ui::IconButtonShape::Square)
5716 .icon_size(IconSize::XSmall)
5717 .icon_color(Color::Muted)
5718 .toggle_state(is_active)
5719 .tooltip({
5720 let focus_handle = self.focus_handle.clone();
5721 move |window, cx| {
5722 Tooltip::for_action_in(
5723 "Toggle Code Actions",
5724 &ToggleCodeActions {
5725 deployed_from_indicator: None,
5726 },
5727 &focus_handle,
5728 window,
5729 cx,
5730 )
5731 }
5732 })
5733 .on_click(cx.listener(move |editor, _e, window, cx| {
5734 window.focus(&editor.focus_handle(cx));
5735 editor.toggle_code_actions(
5736 &ToggleCodeActions {
5737 deployed_from_indicator: Some(row),
5738 },
5739 window,
5740 cx,
5741 );
5742 })),
5743 )
5744 } else {
5745 None
5746 }
5747 }
5748
5749 fn clear_tasks(&mut self) {
5750 self.tasks.clear()
5751 }
5752
5753 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5754 if self.tasks.insert(key, value).is_some() {
5755 // This case should hopefully be rare, but just in case...
5756 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5757 }
5758 }
5759
5760 fn build_tasks_context(
5761 project: &Entity<Project>,
5762 buffer: &Entity<Buffer>,
5763 buffer_row: u32,
5764 tasks: &Arc<RunnableTasks>,
5765 cx: &mut Context<Self>,
5766 ) -> Task<Option<task::TaskContext>> {
5767 let position = Point::new(buffer_row, tasks.column);
5768 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5769 let location = Location {
5770 buffer: buffer.clone(),
5771 range: range_start..range_start,
5772 };
5773 // Fill in the environmental variables from the tree-sitter captures
5774 let mut captured_task_variables = TaskVariables::default();
5775 for (capture_name, value) in tasks.extra_variables.clone() {
5776 captured_task_variables.insert(
5777 task::VariableName::Custom(capture_name.into()),
5778 value.clone(),
5779 );
5780 }
5781 project.update(cx, |project, cx| {
5782 project.task_store().update(cx, |task_store, cx| {
5783 task_store.task_context_for_location(captured_task_variables, location, cx)
5784 })
5785 })
5786 }
5787
5788 pub fn spawn_nearest_task(
5789 &mut self,
5790 action: &SpawnNearestTask,
5791 window: &mut Window,
5792 cx: &mut Context<Self>,
5793 ) {
5794 let Some((workspace, _)) = self.workspace.clone() else {
5795 return;
5796 };
5797 let Some(project) = self.project.clone() else {
5798 return;
5799 };
5800
5801 // Try to find a closest, enclosing node using tree-sitter that has a
5802 // task
5803 let Some((buffer, buffer_row, tasks)) = self
5804 .find_enclosing_node_task(cx)
5805 // Or find the task that's closest in row-distance.
5806 .or_else(|| self.find_closest_task(cx))
5807 else {
5808 return;
5809 };
5810
5811 let reveal_strategy = action.reveal;
5812 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5813 cx.spawn_in(window, |_, mut cx| async move {
5814 let context = task_context.await?;
5815 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5816
5817 let resolved = resolved_task.resolved.as_mut()?;
5818 resolved.reveal = reveal_strategy;
5819
5820 workspace
5821 .update(&mut cx, |workspace, cx| {
5822 workspace::tasks::schedule_resolved_task(
5823 workspace,
5824 task_source_kind,
5825 resolved_task,
5826 false,
5827 cx,
5828 );
5829 })
5830 .ok()
5831 })
5832 .detach();
5833 }
5834
5835 fn find_closest_task(
5836 &mut self,
5837 cx: &mut Context<Self>,
5838 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5839 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5840
5841 let ((buffer_id, row), tasks) = self
5842 .tasks
5843 .iter()
5844 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5845
5846 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5847 let tasks = Arc::new(tasks.to_owned());
5848 Some((buffer, *row, tasks))
5849 }
5850
5851 fn find_enclosing_node_task(
5852 &mut self,
5853 cx: &mut Context<Self>,
5854 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5855 let snapshot = self.buffer.read(cx).snapshot(cx);
5856 let offset = self.selections.newest::<usize>(cx).head();
5857 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5858 let buffer_id = excerpt.buffer().remote_id();
5859
5860 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5861 let mut cursor = layer.node().walk();
5862
5863 while cursor.goto_first_child_for_byte(offset).is_some() {
5864 if cursor.node().end_byte() == offset {
5865 cursor.goto_next_sibling();
5866 }
5867 }
5868
5869 // Ascend to the smallest ancestor that contains the range and has a task.
5870 loop {
5871 let node = cursor.node();
5872 let node_range = node.byte_range();
5873 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5874
5875 // Check if this node contains our offset
5876 if node_range.start <= offset && node_range.end >= offset {
5877 // If it contains offset, check for task
5878 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5879 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5880 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5881 }
5882 }
5883
5884 if !cursor.goto_parent() {
5885 break;
5886 }
5887 }
5888 None
5889 }
5890
5891 fn render_run_indicator(
5892 &self,
5893 _style: &EditorStyle,
5894 is_active: bool,
5895 row: DisplayRow,
5896 cx: &mut Context<Self>,
5897 ) -> IconButton {
5898 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5899 .shape(ui::IconButtonShape::Square)
5900 .icon_size(IconSize::XSmall)
5901 .icon_color(Color::Muted)
5902 .toggle_state(is_active)
5903 .on_click(cx.listener(move |editor, _e, window, cx| {
5904 window.focus(&editor.focus_handle(cx));
5905 editor.toggle_code_actions(
5906 &ToggleCodeActions {
5907 deployed_from_indicator: Some(row),
5908 },
5909 window,
5910 cx,
5911 );
5912 }))
5913 }
5914
5915 pub fn context_menu_visible(&self) -> bool {
5916 !self.edit_prediction_preview_is_active()
5917 && self
5918 .context_menu
5919 .borrow()
5920 .as_ref()
5921 .map_or(false, |menu| menu.visible())
5922 }
5923
5924 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5925 self.context_menu
5926 .borrow()
5927 .as_ref()
5928 .map(|menu| menu.origin())
5929 }
5930
5931 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
5932 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
5933
5934 #[allow(clippy::too_many_arguments)]
5935 fn render_edit_prediction_popover(
5936 &mut self,
5937 text_bounds: &Bounds<Pixels>,
5938 content_origin: gpui::Point<Pixels>,
5939 editor_snapshot: &EditorSnapshot,
5940 visible_row_range: Range<DisplayRow>,
5941 scroll_top: f32,
5942 scroll_bottom: f32,
5943 line_layouts: &[LineWithInvisibles],
5944 line_height: Pixels,
5945 scroll_pixel_position: gpui::Point<Pixels>,
5946 newest_selection_head: Option<DisplayPoint>,
5947 editor_width: Pixels,
5948 style: &EditorStyle,
5949 window: &mut Window,
5950 cx: &mut App,
5951 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5952 let active_inline_completion = self.active_inline_completion.as_ref()?;
5953
5954 if self.edit_prediction_visible_in_cursor_popover(true) {
5955 return None;
5956 }
5957
5958 match &active_inline_completion.completion {
5959 InlineCompletion::Move { target, .. } => {
5960 let target_display_point = target.to_display_point(editor_snapshot);
5961
5962 if self.edit_prediction_requires_modifier() {
5963 if !self.edit_prediction_preview_is_active() {
5964 return None;
5965 }
5966
5967 self.render_edit_prediction_modifier_jump_popover(
5968 text_bounds,
5969 content_origin,
5970 visible_row_range,
5971 line_layouts,
5972 line_height,
5973 scroll_pixel_position,
5974 newest_selection_head,
5975 target_display_point,
5976 window,
5977 cx,
5978 )
5979 } else {
5980 self.render_edit_prediction_eager_jump_popover(
5981 text_bounds,
5982 content_origin,
5983 editor_snapshot,
5984 visible_row_range,
5985 scroll_top,
5986 scroll_bottom,
5987 line_height,
5988 scroll_pixel_position,
5989 target_display_point,
5990 editor_width,
5991 window,
5992 cx,
5993 )
5994 }
5995 }
5996 InlineCompletion::Edit {
5997 display_mode: EditDisplayMode::Inline,
5998 ..
5999 } => None,
6000 InlineCompletion::Edit {
6001 display_mode: EditDisplayMode::TabAccept,
6002 edits,
6003 ..
6004 } => {
6005 let range = &edits.first()?.0;
6006 let target_display_point = range.end.to_display_point(editor_snapshot);
6007
6008 self.render_edit_prediction_end_of_line_popover(
6009 "Accept",
6010 editor_snapshot,
6011 visible_row_range,
6012 target_display_point,
6013 line_height,
6014 scroll_pixel_position,
6015 content_origin,
6016 editor_width,
6017 window,
6018 cx,
6019 )
6020 }
6021 InlineCompletion::Edit {
6022 edits,
6023 edit_preview,
6024 display_mode: EditDisplayMode::DiffPopover,
6025 snapshot,
6026 } => self.render_edit_prediction_diff_popover(
6027 text_bounds,
6028 content_origin,
6029 editor_snapshot,
6030 visible_row_range,
6031 line_layouts,
6032 line_height,
6033 scroll_pixel_position,
6034 newest_selection_head,
6035 editor_width,
6036 style,
6037 edits,
6038 edit_preview,
6039 snapshot,
6040 window,
6041 cx,
6042 ),
6043 }
6044 }
6045
6046 #[allow(clippy::too_many_arguments)]
6047 fn render_edit_prediction_modifier_jump_popover(
6048 &mut self,
6049 text_bounds: &Bounds<Pixels>,
6050 content_origin: gpui::Point<Pixels>,
6051 visible_row_range: Range<DisplayRow>,
6052 line_layouts: &[LineWithInvisibles],
6053 line_height: Pixels,
6054 scroll_pixel_position: gpui::Point<Pixels>,
6055 newest_selection_head: Option<DisplayPoint>,
6056 target_display_point: DisplayPoint,
6057 window: &mut Window,
6058 cx: &mut App,
6059 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6060 let scrolled_content_origin =
6061 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6062
6063 const SCROLL_PADDING_Y: Pixels = px(12.);
6064
6065 if target_display_point.row() < visible_row_range.start {
6066 return self.render_edit_prediction_scroll_popover(
6067 |_| SCROLL_PADDING_Y,
6068 IconName::ArrowUp,
6069 visible_row_range,
6070 line_layouts,
6071 newest_selection_head,
6072 scrolled_content_origin,
6073 window,
6074 cx,
6075 );
6076 } else if target_display_point.row() >= visible_row_range.end {
6077 return self.render_edit_prediction_scroll_popover(
6078 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6079 IconName::ArrowDown,
6080 visible_row_range,
6081 line_layouts,
6082 newest_selection_head,
6083 scrolled_content_origin,
6084 window,
6085 cx,
6086 );
6087 }
6088
6089 const POLE_WIDTH: Pixels = px(2.);
6090
6091 let line_layout =
6092 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6093 let target_column = target_display_point.column() as usize;
6094
6095 let target_x = line_layout.x_for_index(target_column);
6096 let target_y =
6097 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6098
6099 let flag_on_right = target_x < text_bounds.size.width / 2.;
6100
6101 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6102 border_color.l += 0.001;
6103
6104 let mut element = v_flex()
6105 .items_end()
6106 .when(flag_on_right, |el| el.items_start())
6107 .child(if flag_on_right {
6108 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6109 .rounded_bl(px(0.))
6110 .rounded_tl(px(0.))
6111 .border_l_2()
6112 .border_color(border_color)
6113 } else {
6114 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6115 .rounded_br(px(0.))
6116 .rounded_tr(px(0.))
6117 .border_r_2()
6118 .border_color(border_color)
6119 })
6120 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6121 .into_any();
6122
6123 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6124
6125 let mut origin = scrolled_content_origin + point(target_x, target_y)
6126 - point(
6127 if flag_on_right {
6128 POLE_WIDTH
6129 } else {
6130 size.width - POLE_WIDTH
6131 },
6132 size.height - line_height,
6133 );
6134
6135 origin.x = origin.x.max(content_origin.x);
6136
6137 element.prepaint_at(origin, window, cx);
6138
6139 Some((element, origin))
6140 }
6141
6142 #[allow(clippy::too_many_arguments)]
6143 fn render_edit_prediction_scroll_popover(
6144 &mut self,
6145 to_y: impl Fn(Size<Pixels>) -> Pixels,
6146 scroll_icon: IconName,
6147 visible_row_range: Range<DisplayRow>,
6148 line_layouts: &[LineWithInvisibles],
6149 newest_selection_head: Option<DisplayPoint>,
6150 scrolled_content_origin: gpui::Point<Pixels>,
6151 window: &mut Window,
6152 cx: &mut App,
6153 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6154 let mut element = self
6155 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6156 .into_any();
6157
6158 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6159
6160 let cursor = newest_selection_head?;
6161 let cursor_row_layout =
6162 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6163 let cursor_column = cursor.column() as usize;
6164
6165 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6166
6167 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6168
6169 element.prepaint_at(origin, window, cx);
6170 Some((element, origin))
6171 }
6172
6173 #[allow(clippy::too_many_arguments)]
6174 fn render_edit_prediction_eager_jump_popover(
6175 &mut self,
6176 text_bounds: &Bounds<Pixels>,
6177 content_origin: gpui::Point<Pixels>,
6178 editor_snapshot: &EditorSnapshot,
6179 visible_row_range: Range<DisplayRow>,
6180 scroll_top: f32,
6181 scroll_bottom: f32,
6182 line_height: Pixels,
6183 scroll_pixel_position: gpui::Point<Pixels>,
6184 target_display_point: DisplayPoint,
6185 editor_width: Pixels,
6186 window: &mut Window,
6187 cx: &mut App,
6188 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6189 if target_display_point.row().as_f32() < scroll_top {
6190 let mut element = self
6191 .render_edit_prediction_line_popover(
6192 "Jump to Edit",
6193 Some(IconName::ArrowUp),
6194 window,
6195 cx,
6196 )?
6197 .into_any();
6198
6199 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6200 let offset = point(
6201 (text_bounds.size.width - size.width) / 2.,
6202 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6203 );
6204
6205 let origin = text_bounds.origin + offset;
6206 element.prepaint_at(origin, window, cx);
6207 Some((element, origin))
6208 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6209 let mut element = self
6210 .render_edit_prediction_line_popover(
6211 "Jump to Edit",
6212 Some(IconName::ArrowDown),
6213 window,
6214 cx,
6215 )?
6216 .into_any();
6217
6218 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6219 let offset = point(
6220 (text_bounds.size.width - size.width) / 2.,
6221 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6222 );
6223
6224 let origin = text_bounds.origin + offset;
6225 element.prepaint_at(origin, window, cx);
6226 Some((element, origin))
6227 } else {
6228 self.render_edit_prediction_end_of_line_popover(
6229 "Jump to Edit",
6230 editor_snapshot,
6231 visible_row_range,
6232 target_display_point,
6233 line_height,
6234 scroll_pixel_position,
6235 content_origin,
6236 editor_width,
6237 window,
6238 cx,
6239 )
6240 }
6241 }
6242
6243 #[allow(clippy::too_many_arguments)]
6244 fn render_edit_prediction_end_of_line_popover(
6245 self: &mut Editor,
6246 label: &'static str,
6247 editor_snapshot: &EditorSnapshot,
6248 visible_row_range: Range<DisplayRow>,
6249 target_display_point: DisplayPoint,
6250 line_height: Pixels,
6251 scroll_pixel_position: gpui::Point<Pixels>,
6252 content_origin: gpui::Point<Pixels>,
6253 editor_width: Pixels,
6254 window: &mut Window,
6255 cx: &mut App,
6256 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6257 let target_line_end = DisplayPoint::new(
6258 target_display_point.row(),
6259 editor_snapshot.line_len(target_display_point.row()),
6260 );
6261
6262 let mut element = self
6263 .render_edit_prediction_line_popover(label, None, window, cx)?
6264 .into_any();
6265
6266 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6267
6268 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6269
6270 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6271 let mut origin = start_point
6272 + line_origin
6273 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6274 origin.x = origin.x.max(content_origin.x);
6275
6276 let max_x = content_origin.x + editor_width - size.width;
6277
6278 if origin.x > max_x {
6279 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6280
6281 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6282 origin.y += offset;
6283 IconName::ArrowUp
6284 } else {
6285 origin.y -= offset;
6286 IconName::ArrowDown
6287 };
6288
6289 element = self
6290 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6291 .into_any();
6292
6293 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6294
6295 origin.x = content_origin.x + editor_width - size.width - px(2.);
6296 }
6297
6298 element.prepaint_at(origin, window, cx);
6299 Some((element, origin))
6300 }
6301
6302 #[allow(clippy::too_many_arguments)]
6303 fn render_edit_prediction_diff_popover(
6304 self: &Editor,
6305 text_bounds: &Bounds<Pixels>,
6306 content_origin: gpui::Point<Pixels>,
6307 editor_snapshot: &EditorSnapshot,
6308 visible_row_range: Range<DisplayRow>,
6309 line_layouts: &[LineWithInvisibles],
6310 line_height: Pixels,
6311 scroll_pixel_position: gpui::Point<Pixels>,
6312 newest_selection_head: Option<DisplayPoint>,
6313 editor_width: Pixels,
6314 style: &EditorStyle,
6315 edits: &Vec<(Range<Anchor>, String)>,
6316 edit_preview: &Option<language::EditPreview>,
6317 snapshot: &language::BufferSnapshot,
6318 window: &mut Window,
6319 cx: &mut App,
6320 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6321 let edit_start = edits
6322 .first()
6323 .unwrap()
6324 .0
6325 .start
6326 .to_display_point(editor_snapshot);
6327 let edit_end = edits
6328 .last()
6329 .unwrap()
6330 .0
6331 .end
6332 .to_display_point(editor_snapshot);
6333
6334 let is_visible = visible_row_range.contains(&edit_start.row())
6335 || visible_row_range.contains(&edit_end.row());
6336 if !is_visible {
6337 return None;
6338 }
6339
6340 let highlighted_edits =
6341 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6342
6343 let styled_text = highlighted_edits.to_styled_text(&style.text);
6344 let line_count = highlighted_edits.text.lines().count();
6345
6346 const BORDER_WIDTH: Pixels = px(1.);
6347
6348 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6349 let has_keybind = keybind.is_some();
6350
6351 let mut element = h_flex()
6352 .items_start()
6353 .child(
6354 h_flex()
6355 .bg(cx.theme().colors().editor_background)
6356 .border(BORDER_WIDTH)
6357 .shadow_sm()
6358 .border_color(cx.theme().colors().border)
6359 .rounded_l_lg()
6360 .when(line_count > 1, |el| el.rounded_br_lg())
6361 .pr_1()
6362 .child(styled_text),
6363 )
6364 .child(
6365 h_flex()
6366 .h(line_height + BORDER_WIDTH * px(2.))
6367 .px_1p5()
6368 .gap_1()
6369 // Workaround: For some reason, there's a gap if we don't do this
6370 .ml(-BORDER_WIDTH)
6371 .shadow(smallvec![gpui::BoxShadow {
6372 color: gpui::black().opacity(0.05),
6373 offset: point(px(1.), px(1.)),
6374 blur_radius: px(2.),
6375 spread_radius: px(0.),
6376 }])
6377 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6378 .border(BORDER_WIDTH)
6379 .border_color(cx.theme().colors().border)
6380 .rounded_r_lg()
6381 .id("edit_prediction_diff_popover_keybind")
6382 .when(!has_keybind, |el| {
6383 let status_colors = cx.theme().status();
6384
6385 el.bg(status_colors.error_background)
6386 .border_color(status_colors.error.opacity(0.6))
6387 .child(Icon::new(IconName::Info).color(Color::Error))
6388 .cursor_default()
6389 .hoverable_tooltip(move |_window, cx| {
6390 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6391 })
6392 })
6393 .children(keybind),
6394 )
6395 .into_any();
6396
6397 let longest_row =
6398 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6399 let longest_line_width = if visible_row_range.contains(&longest_row) {
6400 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6401 } else {
6402 layout_line(
6403 longest_row,
6404 editor_snapshot,
6405 style,
6406 editor_width,
6407 |_| false,
6408 window,
6409 cx,
6410 )
6411 .width
6412 };
6413
6414 let viewport_bounds =
6415 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6416 right: -EditorElement::SCROLLBAR_WIDTH,
6417 ..Default::default()
6418 });
6419
6420 let x_after_longest =
6421 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6422 - scroll_pixel_position.x;
6423
6424 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6425
6426 // Fully visible if it can be displayed within the window (allow overlapping other
6427 // panes). However, this is only allowed if the popover starts within text_bounds.
6428 let can_position_to_the_right = x_after_longest < text_bounds.right()
6429 && x_after_longest + element_bounds.width < viewport_bounds.right();
6430
6431 let mut origin = if can_position_to_the_right {
6432 point(
6433 x_after_longest,
6434 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6435 - scroll_pixel_position.y,
6436 )
6437 } else {
6438 let cursor_row = newest_selection_head.map(|head| head.row());
6439 let above_edit = edit_start
6440 .row()
6441 .0
6442 .checked_sub(line_count as u32)
6443 .map(DisplayRow);
6444 let below_edit = Some(edit_end.row() + 1);
6445 let above_cursor =
6446 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6447 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6448
6449 // Place the edit popover adjacent to the edit if there is a location
6450 // available that is onscreen and does not obscure the cursor. Otherwise,
6451 // place it adjacent to the cursor.
6452 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6453 .into_iter()
6454 .flatten()
6455 .find(|&start_row| {
6456 let end_row = start_row + line_count as u32;
6457 visible_row_range.contains(&start_row)
6458 && visible_row_range.contains(&end_row)
6459 && cursor_row.map_or(true, |cursor_row| {
6460 !((start_row..end_row).contains(&cursor_row))
6461 })
6462 })?;
6463
6464 content_origin
6465 + point(
6466 -scroll_pixel_position.x,
6467 row_target.as_f32() * line_height - scroll_pixel_position.y,
6468 )
6469 };
6470
6471 origin.x -= BORDER_WIDTH;
6472
6473 window.defer_draw(element, origin, 1);
6474
6475 // Do not return an element, since it will already be drawn due to defer_draw.
6476 None
6477 }
6478
6479 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6480 px(30.)
6481 }
6482
6483 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6484 if self.read_only(cx) {
6485 cx.theme().players().read_only()
6486 } else {
6487 self.style.as_ref().unwrap().local_player
6488 }
6489 }
6490
6491 fn render_edit_prediction_accept_keybind(
6492 &self,
6493 window: &mut Window,
6494 cx: &App,
6495 ) -> Option<AnyElement> {
6496 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6497 let accept_keystroke = accept_binding.keystroke()?;
6498
6499 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6500
6501 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6502 Color::Accent
6503 } else {
6504 Color::Muted
6505 };
6506
6507 h_flex()
6508 .px_0p5()
6509 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6510 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6511 .text_size(TextSize::XSmall.rems(cx))
6512 .child(h_flex().children(ui::render_modifiers(
6513 &accept_keystroke.modifiers,
6514 PlatformStyle::platform(),
6515 Some(modifiers_color),
6516 Some(IconSize::XSmall.rems().into()),
6517 true,
6518 )))
6519 .when(is_platform_style_mac, |parent| {
6520 parent.child(accept_keystroke.key.clone())
6521 })
6522 .when(!is_platform_style_mac, |parent| {
6523 parent.child(
6524 Key::new(
6525 util::capitalize(&accept_keystroke.key),
6526 Some(Color::Default),
6527 )
6528 .size(Some(IconSize::XSmall.rems().into())),
6529 )
6530 })
6531 .into_any()
6532 .into()
6533 }
6534
6535 fn render_edit_prediction_line_popover(
6536 &self,
6537 label: impl Into<SharedString>,
6538 icon: Option<IconName>,
6539 window: &mut Window,
6540 cx: &App,
6541 ) -> Option<Stateful<Div>> {
6542 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6543
6544 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6545 let has_keybind = keybind.is_some();
6546
6547 let result = h_flex()
6548 .id("ep-line-popover")
6549 .py_0p5()
6550 .pl_1()
6551 .pr(padding_right)
6552 .gap_1()
6553 .rounded_md()
6554 .border_1()
6555 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6556 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6557 .shadow_sm()
6558 .when(!has_keybind, |el| {
6559 let status_colors = cx.theme().status();
6560
6561 el.bg(status_colors.error_background)
6562 .border_color(status_colors.error.opacity(0.6))
6563 .pl_2()
6564 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
6565 .cursor_default()
6566 .hoverable_tooltip(move |_window, cx| {
6567 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6568 })
6569 })
6570 .children(keybind)
6571 .child(
6572 Label::new(label)
6573 .size(LabelSize::Small)
6574 .when(!has_keybind, |el| {
6575 el.color(cx.theme().status().error.into()).strikethrough()
6576 }),
6577 )
6578 .when(!has_keybind, |el| {
6579 el.child(
6580 h_flex().ml_1().child(
6581 Icon::new(IconName::Info)
6582 .size(IconSize::Small)
6583 .color(cx.theme().status().error.into()),
6584 ),
6585 )
6586 })
6587 .when_some(icon, |element, icon| {
6588 element.child(
6589 div()
6590 .mt(px(1.5))
6591 .child(Icon::new(icon).size(IconSize::Small)),
6592 )
6593 });
6594
6595 Some(result)
6596 }
6597
6598 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6599 let accent_color = cx.theme().colors().text_accent;
6600 let editor_bg_color = cx.theme().colors().editor_background;
6601 editor_bg_color.blend(accent_color.opacity(0.1))
6602 }
6603
6604 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
6605 let accent_color = cx.theme().colors().text_accent;
6606 let editor_bg_color = cx.theme().colors().editor_background;
6607 editor_bg_color.blend(accent_color.opacity(0.6))
6608 }
6609
6610 #[allow(clippy::too_many_arguments)]
6611 fn render_edit_prediction_cursor_popover(
6612 &self,
6613 min_width: Pixels,
6614 max_width: Pixels,
6615 cursor_point: Point,
6616 style: &EditorStyle,
6617 accept_keystroke: Option<&gpui::Keystroke>,
6618 _window: &Window,
6619 cx: &mut Context<Editor>,
6620 ) -> Option<AnyElement> {
6621 let provider = self.edit_prediction_provider.as_ref()?;
6622
6623 if provider.provider.needs_terms_acceptance(cx) {
6624 return Some(
6625 h_flex()
6626 .min_w(min_width)
6627 .flex_1()
6628 .px_2()
6629 .py_1()
6630 .gap_3()
6631 .elevation_2(cx)
6632 .hover(|style| style.bg(cx.theme().colors().element_hover))
6633 .id("accept-terms")
6634 .cursor_pointer()
6635 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6636 .on_click(cx.listener(|this, _event, window, cx| {
6637 cx.stop_propagation();
6638 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6639 window.dispatch_action(
6640 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6641 cx,
6642 );
6643 }))
6644 .child(
6645 h_flex()
6646 .flex_1()
6647 .gap_2()
6648 .child(Icon::new(IconName::ZedPredict))
6649 .child(Label::new("Accept Terms of Service"))
6650 .child(div().w_full())
6651 .child(
6652 Icon::new(IconName::ArrowUpRight)
6653 .color(Color::Muted)
6654 .size(IconSize::Small),
6655 )
6656 .into_any_element(),
6657 )
6658 .into_any(),
6659 );
6660 }
6661
6662 let is_refreshing = provider.provider.is_refreshing(cx);
6663
6664 fn pending_completion_container() -> Div {
6665 h_flex()
6666 .h_full()
6667 .flex_1()
6668 .gap_2()
6669 .child(Icon::new(IconName::ZedPredict))
6670 }
6671
6672 let completion = match &self.active_inline_completion {
6673 Some(prediction) => {
6674 if !self.has_visible_completions_menu() {
6675 const RADIUS: Pixels = px(6.);
6676 const BORDER_WIDTH: Pixels = px(1.);
6677
6678 return Some(
6679 h_flex()
6680 .elevation_2(cx)
6681 .border(BORDER_WIDTH)
6682 .border_color(cx.theme().colors().border)
6683 .when(accept_keystroke.is_none(), |el| {
6684 el.border_color(cx.theme().status().error)
6685 })
6686 .rounded(RADIUS)
6687 .rounded_tl(px(0.))
6688 .overflow_hidden()
6689 .child(div().px_1p5().child(match &prediction.completion {
6690 InlineCompletion::Move { target, snapshot } => {
6691 use text::ToPoint as _;
6692 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6693 {
6694 Icon::new(IconName::ZedPredictDown)
6695 } else {
6696 Icon::new(IconName::ZedPredictUp)
6697 }
6698 }
6699 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6700 }))
6701 .child(
6702 h_flex()
6703 .gap_1()
6704 .py_1()
6705 .px_2()
6706 .rounded_r(RADIUS - BORDER_WIDTH)
6707 .border_l_1()
6708 .border_color(cx.theme().colors().border)
6709 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6710 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6711 el.child(
6712 Label::new("Hold")
6713 .size(LabelSize::Small)
6714 .when(accept_keystroke.is_none(), |el| {
6715 el.strikethrough()
6716 })
6717 .line_height_style(LineHeightStyle::UiLabel),
6718 )
6719 })
6720 .id("edit_prediction_cursor_popover_keybind")
6721 .when(accept_keystroke.is_none(), |el| {
6722 let status_colors = cx.theme().status();
6723
6724 el.bg(status_colors.error_background)
6725 .border_color(status_colors.error.opacity(0.6))
6726 .child(Icon::new(IconName::Info).color(Color::Error))
6727 .cursor_default()
6728 .hoverable_tooltip(move |_window, cx| {
6729 cx.new(|_| MissingEditPredictionKeybindingTooltip)
6730 .into()
6731 })
6732 })
6733 .when_some(
6734 accept_keystroke.as_ref(),
6735 |el, accept_keystroke| {
6736 el.child(h_flex().children(ui::render_modifiers(
6737 &accept_keystroke.modifiers,
6738 PlatformStyle::platform(),
6739 Some(Color::Default),
6740 Some(IconSize::XSmall.rems().into()),
6741 false,
6742 )))
6743 },
6744 ),
6745 )
6746 .into_any(),
6747 );
6748 }
6749
6750 self.render_edit_prediction_cursor_popover_preview(
6751 prediction,
6752 cursor_point,
6753 style,
6754 cx,
6755 )?
6756 }
6757
6758 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6759 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6760 stale_completion,
6761 cursor_point,
6762 style,
6763 cx,
6764 )?,
6765
6766 None => {
6767 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6768 }
6769 },
6770
6771 None => pending_completion_container().child(Label::new("No Prediction")),
6772 };
6773
6774 let completion = if is_refreshing {
6775 completion
6776 .with_animation(
6777 "loading-completion",
6778 Animation::new(Duration::from_secs(2))
6779 .repeat()
6780 .with_easing(pulsating_between(0.4, 0.8)),
6781 |label, delta| label.opacity(delta),
6782 )
6783 .into_any_element()
6784 } else {
6785 completion.into_any_element()
6786 };
6787
6788 let has_completion = self.active_inline_completion.is_some();
6789
6790 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6791 Some(
6792 h_flex()
6793 .min_w(min_width)
6794 .max_w(max_width)
6795 .flex_1()
6796 .elevation_2(cx)
6797 .border_color(cx.theme().colors().border)
6798 .child(
6799 div()
6800 .flex_1()
6801 .py_1()
6802 .px_2()
6803 .overflow_hidden()
6804 .child(completion),
6805 )
6806 .when_some(accept_keystroke, |el, accept_keystroke| {
6807 if !accept_keystroke.modifiers.modified() {
6808 return el;
6809 }
6810
6811 el.child(
6812 h_flex()
6813 .h_full()
6814 .border_l_1()
6815 .rounded_r_lg()
6816 .border_color(cx.theme().colors().border)
6817 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6818 .gap_1()
6819 .py_1()
6820 .px_2()
6821 .child(
6822 h_flex()
6823 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6824 .when(is_platform_style_mac, |parent| parent.gap_1())
6825 .child(h_flex().children(ui::render_modifiers(
6826 &accept_keystroke.modifiers,
6827 PlatformStyle::platform(),
6828 Some(if !has_completion {
6829 Color::Muted
6830 } else {
6831 Color::Default
6832 }),
6833 None,
6834 false,
6835 ))),
6836 )
6837 .child(Label::new("Preview").into_any_element())
6838 .opacity(if has_completion { 1.0 } else { 0.4 }),
6839 )
6840 })
6841 .into_any(),
6842 )
6843 }
6844
6845 fn render_edit_prediction_cursor_popover_preview(
6846 &self,
6847 completion: &InlineCompletionState,
6848 cursor_point: Point,
6849 style: &EditorStyle,
6850 cx: &mut Context<Editor>,
6851 ) -> Option<Div> {
6852 use text::ToPoint as _;
6853
6854 fn render_relative_row_jump(
6855 prefix: impl Into<String>,
6856 current_row: u32,
6857 target_row: u32,
6858 ) -> Div {
6859 let (row_diff, arrow) = if target_row < current_row {
6860 (current_row - target_row, IconName::ArrowUp)
6861 } else {
6862 (target_row - current_row, IconName::ArrowDown)
6863 };
6864
6865 h_flex()
6866 .child(
6867 Label::new(format!("{}{}", prefix.into(), row_diff))
6868 .color(Color::Muted)
6869 .size(LabelSize::Small),
6870 )
6871 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6872 }
6873
6874 match &completion.completion {
6875 InlineCompletion::Move {
6876 target, snapshot, ..
6877 } => Some(
6878 h_flex()
6879 .px_2()
6880 .gap_2()
6881 .flex_1()
6882 .child(
6883 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6884 Icon::new(IconName::ZedPredictDown)
6885 } else {
6886 Icon::new(IconName::ZedPredictUp)
6887 },
6888 )
6889 .child(Label::new("Jump to Edit")),
6890 ),
6891
6892 InlineCompletion::Edit {
6893 edits,
6894 edit_preview,
6895 snapshot,
6896 display_mode: _,
6897 } => {
6898 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6899
6900 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6901 &snapshot,
6902 &edits,
6903 edit_preview.as_ref()?,
6904 true,
6905 cx,
6906 )
6907 .first_line_preview();
6908
6909 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6910 .with_default_highlights(&style.text, highlighted_edits.highlights);
6911
6912 let preview = h_flex()
6913 .gap_1()
6914 .min_w_16()
6915 .child(styled_text)
6916 .when(has_more_lines, |parent| parent.child("…"));
6917
6918 let left = if first_edit_row != cursor_point.row {
6919 render_relative_row_jump("", cursor_point.row, first_edit_row)
6920 .into_any_element()
6921 } else {
6922 Icon::new(IconName::ZedPredict).into_any_element()
6923 };
6924
6925 Some(
6926 h_flex()
6927 .h_full()
6928 .flex_1()
6929 .gap_2()
6930 .pr_1()
6931 .overflow_x_hidden()
6932 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6933 .child(left)
6934 .child(preview),
6935 )
6936 }
6937 }
6938 }
6939
6940 fn render_context_menu(
6941 &self,
6942 style: &EditorStyle,
6943 max_height_in_lines: u32,
6944 y_flipped: bool,
6945 window: &mut Window,
6946 cx: &mut Context<Editor>,
6947 ) -> Option<AnyElement> {
6948 let menu = self.context_menu.borrow();
6949 let menu = menu.as_ref()?;
6950 if !menu.visible() {
6951 return None;
6952 };
6953 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6954 }
6955
6956 fn render_context_menu_aside(
6957 &mut self,
6958 max_size: Size<Pixels>,
6959 window: &mut Window,
6960 cx: &mut Context<Editor>,
6961 ) -> Option<AnyElement> {
6962 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6963 if menu.visible() {
6964 menu.render_aside(self, max_size, window, cx)
6965 } else {
6966 None
6967 }
6968 })
6969 }
6970
6971 fn hide_context_menu(
6972 &mut self,
6973 window: &mut Window,
6974 cx: &mut Context<Self>,
6975 ) -> Option<CodeContextMenu> {
6976 cx.notify();
6977 self.completion_tasks.clear();
6978 let context_menu = self.context_menu.borrow_mut().take();
6979 self.stale_inline_completion_in_menu.take();
6980 self.update_visible_inline_completion(window, cx);
6981 context_menu
6982 }
6983
6984 fn show_snippet_choices(
6985 &mut self,
6986 choices: &Vec<String>,
6987 selection: Range<Anchor>,
6988 cx: &mut Context<Self>,
6989 ) {
6990 if selection.start.buffer_id.is_none() {
6991 return;
6992 }
6993 let buffer_id = selection.start.buffer_id.unwrap();
6994 let buffer = self.buffer().read(cx).buffer(buffer_id);
6995 let id = post_inc(&mut self.next_completion_id);
6996
6997 if let Some(buffer) = buffer {
6998 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6999 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7000 ));
7001 }
7002 }
7003
7004 pub fn insert_snippet(
7005 &mut self,
7006 insertion_ranges: &[Range<usize>],
7007 snippet: Snippet,
7008 window: &mut Window,
7009 cx: &mut Context<Self>,
7010 ) -> Result<()> {
7011 struct Tabstop<T> {
7012 is_end_tabstop: bool,
7013 ranges: Vec<Range<T>>,
7014 choices: Option<Vec<String>>,
7015 }
7016
7017 let tabstops = self.buffer.update(cx, |buffer, cx| {
7018 let snippet_text: Arc<str> = snippet.text.clone().into();
7019 buffer.edit(
7020 insertion_ranges
7021 .iter()
7022 .cloned()
7023 .map(|range| (range, snippet_text.clone())),
7024 Some(AutoindentMode::EachLine),
7025 cx,
7026 );
7027
7028 let snapshot = &*buffer.read(cx);
7029 let snippet = &snippet;
7030 snippet
7031 .tabstops
7032 .iter()
7033 .map(|tabstop| {
7034 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7035 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7036 });
7037 let mut tabstop_ranges = tabstop
7038 .ranges
7039 .iter()
7040 .flat_map(|tabstop_range| {
7041 let mut delta = 0_isize;
7042 insertion_ranges.iter().map(move |insertion_range| {
7043 let insertion_start = insertion_range.start as isize + delta;
7044 delta +=
7045 snippet.text.len() as isize - insertion_range.len() as isize;
7046
7047 let start = ((insertion_start + tabstop_range.start) as usize)
7048 .min(snapshot.len());
7049 let end = ((insertion_start + tabstop_range.end) as usize)
7050 .min(snapshot.len());
7051 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7052 })
7053 })
7054 .collect::<Vec<_>>();
7055 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7056
7057 Tabstop {
7058 is_end_tabstop,
7059 ranges: tabstop_ranges,
7060 choices: tabstop.choices.clone(),
7061 }
7062 })
7063 .collect::<Vec<_>>()
7064 });
7065 if let Some(tabstop) = tabstops.first() {
7066 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7067 s.select_ranges(tabstop.ranges.iter().cloned());
7068 });
7069
7070 if let Some(choices) = &tabstop.choices {
7071 if let Some(selection) = tabstop.ranges.first() {
7072 self.show_snippet_choices(choices, selection.clone(), cx)
7073 }
7074 }
7075
7076 // If we're already at the last tabstop and it's at the end of the snippet,
7077 // we're done, we don't need to keep the state around.
7078 if !tabstop.is_end_tabstop {
7079 let choices = tabstops
7080 .iter()
7081 .map(|tabstop| tabstop.choices.clone())
7082 .collect();
7083
7084 let ranges = tabstops
7085 .into_iter()
7086 .map(|tabstop| tabstop.ranges)
7087 .collect::<Vec<_>>();
7088
7089 self.snippet_stack.push(SnippetState {
7090 active_index: 0,
7091 ranges,
7092 choices,
7093 });
7094 }
7095
7096 // Check whether the just-entered snippet ends with an auto-closable bracket.
7097 if self.autoclose_regions.is_empty() {
7098 let snapshot = self.buffer.read(cx).snapshot(cx);
7099 for selection in &mut self.selections.all::<Point>(cx) {
7100 let selection_head = selection.head();
7101 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7102 continue;
7103 };
7104
7105 let mut bracket_pair = None;
7106 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7107 let prev_chars = snapshot
7108 .reversed_chars_at(selection_head)
7109 .collect::<String>();
7110 for (pair, enabled) in scope.brackets() {
7111 if enabled
7112 && pair.close
7113 && prev_chars.starts_with(pair.start.as_str())
7114 && next_chars.starts_with(pair.end.as_str())
7115 {
7116 bracket_pair = Some(pair.clone());
7117 break;
7118 }
7119 }
7120 if let Some(pair) = bracket_pair {
7121 let start = snapshot.anchor_after(selection_head);
7122 let end = snapshot.anchor_after(selection_head);
7123 self.autoclose_regions.push(AutocloseRegion {
7124 selection_id: selection.id,
7125 range: start..end,
7126 pair,
7127 });
7128 }
7129 }
7130 }
7131 }
7132 Ok(())
7133 }
7134
7135 pub fn move_to_next_snippet_tabstop(
7136 &mut self,
7137 window: &mut Window,
7138 cx: &mut Context<Self>,
7139 ) -> bool {
7140 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7141 }
7142
7143 pub fn move_to_prev_snippet_tabstop(
7144 &mut self,
7145 window: &mut Window,
7146 cx: &mut Context<Self>,
7147 ) -> bool {
7148 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7149 }
7150
7151 pub fn move_to_snippet_tabstop(
7152 &mut self,
7153 bias: Bias,
7154 window: &mut Window,
7155 cx: &mut Context<Self>,
7156 ) -> bool {
7157 if let Some(mut snippet) = self.snippet_stack.pop() {
7158 match bias {
7159 Bias::Left => {
7160 if snippet.active_index > 0 {
7161 snippet.active_index -= 1;
7162 } else {
7163 self.snippet_stack.push(snippet);
7164 return false;
7165 }
7166 }
7167 Bias::Right => {
7168 if snippet.active_index + 1 < snippet.ranges.len() {
7169 snippet.active_index += 1;
7170 } else {
7171 self.snippet_stack.push(snippet);
7172 return false;
7173 }
7174 }
7175 }
7176 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7177 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7178 s.select_anchor_ranges(current_ranges.iter().cloned())
7179 });
7180
7181 if let Some(choices) = &snippet.choices[snippet.active_index] {
7182 if let Some(selection) = current_ranges.first() {
7183 self.show_snippet_choices(&choices, selection.clone(), cx);
7184 }
7185 }
7186
7187 // If snippet state is not at the last tabstop, push it back on the stack
7188 if snippet.active_index + 1 < snippet.ranges.len() {
7189 self.snippet_stack.push(snippet);
7190 }
7191 return true;
7192 }
7193 }
7194
7195 false
7196 }
7197
7198 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7199 self.transact(window, cx, |this, window, cx| {
7200 this.select_all(&SelectAll, window, cx);
7201 this.insert("", window, cx);
7202 });
7203 }
7204
7205 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7206 self.transact(window, cx, |this, window, cx| {
7207 this.select_autoclose_pair(window, cx);
7208 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7209 if !this.linked_edit_ranges.is_empty() {
7210 let selections = this.selections.all::<MultiBufferPoint>(cx);
7211 let snapshot = this.buffer.read(cx).snapshot(cx);
7212
7213 for selection in selections.iter() {
7214 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7215 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7216 if selection_start.buffer_id != selection_end.buffer_id {
7217 continue;
7218 }
7219 if let Some(ranges) =
7220 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7221 {
7222 for (buffer, entries) in ranges {
7223 linked_ranges.entry(buffer).or_default().extend(entries);
7224 }
7225 }
7226 }
7227 }
7228
7229 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7230 if !this.selections.line_mode {
7231 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7232 for selection in &mut selections {
7233 if selection.is_empty() {
7234 let old_head = selection.head();
7235 let mut new_head =
7236 movement::left(&display_map, old_head.to_display_point(&display_map))
7237 .to_point(&display_map);
7238 if let Some((buffer, line_buffer_range)) = display_map
7239 .buffer_snapshot
7240 .buffer_line_for_row(MultiBufferRow(old_head.row))
7241 {
7242 let indent_size =
7243 buffer.indent_size_for_line(line_buffer_range.start.row);
7244 let indent_len = match indent_size.kind {
7245 IndentKind::Space => {
7246 buffer.settings_at(line_buffer_range.start, cx).tab_size
7247 }
7248 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7249 };
7250 if old_head.column <= indent_size.len && old_head.column > 0 {
7251 let indent_len = indent_len.get();
7252 new_head = cmp::min(
7253 new_head,
7254 MultiBufferPoint::new(
7255 old_head.row,
7256 ((old_head.column - 1) / indent_len) * indent_len,
7257 ),
7258 );
7259 }
7260 }
7261
7262 selection.set_head(new_head, SelectionGoal::None);
7263 }
7264 }
7265 }
7266
7267 this.signature_help_state.set_backspace_pressed(true);
7268 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7269 s.select(selections)
7270 });
7271 this.insert("", window, cx);
7272 let empty_str: Arc<str> = Arc::from("");
7273 for (buffer, edits) in linked_ranges {
7274 let snapshot = buffer.read(cx).snapshot();
7275 use text::ToPoint as TP;
7276
7277 let edits = edits
7278 .into_iter()
7279 .map(|range| {
7280 let end_point = TP::to_point(&range.end, &snapshot);
7281 let mut start_point = TP::to_point(&range.start, &snapshot);
7282
7283 if end_point == start_point {
7284 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7285 .saturating_sub(1);
7286 start_point =
7287 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7288 };
7289
7290 (start_point..end_point, empty_str.clone())
7291 })
7292 .sorted_by_key(|(range, _)| range.start)
7293 .collect::<Vec<_>>();
7294 buffer.update(cx, |this, cx| {
7295 this.edit(edits, None, cx);
7296 })
7297 }
7298 this.refresh_inline_completion(true, false, window, cx);
7299 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7300 });
7301 }
7302
7303 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7304 self.transact(window, cx, |this, window, cx| {
7305 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7306 let line_mode = s.line_mode;
7307 s.move_with(|map, selection| {
7308 if selection.is_empty() && !line_mode {
7309 let cursor = movement::right(map, selection.head());
7310 selection.end = cursor;
7311 selection.reversed = true;
7312 selection.goal = SelectionGoal::None;
7313 }
7314 })
7315 });
7316 this.insert("", window, cx);
7317 this.refresh_inline_completion(true, false, window, cx);
7318 });
7319 }
7320
7321 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7322 if self.move_to_prev_snippet_tabstop(window, cx) {
7323 return;
7324 }
7325
7326 self.outdent(&Outdent, window, cx);
7327 }
7328
7329 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7330 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7331 return;
7332 }
7333
7334 let mut selections = self.selections.all_adjusted(cx);
7335 let buffer = self.buffer.read(cx);
7336 let snapshot = buffer.snapshot(cx);
7337 let rows_iter = selections.iter().map(|s| s.head().row);
7338 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7339
7340 let mut edits = Vec::new();
7341 let mut prev_edited_row = 0;
7342 let mut row_delta = 0;
7343 for selection in &mut selections {
7344 if selection.start.row != prev_edited_row {
7345 row_delta = 0;
7346 }
7347 prev_edited_row = selection.end.row;
7348
7349 // If the selection is non-empty, then increase the indentation of the selected lines.
7350 if !selection.is_empty() {
7351 row_delta =
7352 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7353 continue;
7354 }
7355
7356 // If the selection is empty and the cursor is in the leading whitespace before the
7357 // suggested indentation, then auto-indent the line.
7358 let cursor = selection.head();
7359 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7360 if let Some(suggested_indent) =
7361 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7362 {
7363 if cursor.column < suggested_indent.len
7364 && cursor.column <= current_indent.len
7365 && current_indent.len <= suggested_indent.len
7366 {
7367 selection.start = Point::new(cursor.row, suggested_indent.len);
7368 selection.end = selection.start;
7369 if row_delta == 0 {
7370 edits.extend(Buffer::edit_for_indent_size_adjustment(
7371 cursor.row,
7372 current_indent,
7373 suggested_indent,
7374 ));
7375 row_delta = suggested_indent.len - current_indent.len;
7376 }
7377 continue;
7378 }
7379 }
7380
7381 // Otherwise, insert a hard or soft tab.
7382 let settings = buffer.language_settings_at(cursor, cx);
7383 let tab_size = if settings.hard_tabs {
7384 IndentSize::tab()
7385 } else {
7386 let tab_size = settings.tab_size.get();
7387 let char_column = snapshot
7388 .text_for_range(Point::new(cursor.row, 0)..cursor)
7389 .flat_map(str::chars)
7390 .count()
7391 + row_delta as usize;
7392 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7393 IndentSize::spaces(chars_to_next_tab_stop)
7394 };
7395 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7396 selection.end = selection.start;
7397 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7398 row_delta += tab_size.len;
7399 }
7400
7401 self.transact(window, cx, |this, window, cx| {
7402 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7403 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7404 s.select(selections)
7405 });
7406 this.refresh_inline_completion(true, false, window, cx);
7407 });
7408 }
7409
7410 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7411 if self.read_only(cx) {
7412 return;
7413 }
7414 let mut selections = self.selections.all::<Point>(cx);
7415 let mut prev_edited_row = 0;
7416 let mut row_delta = 0;
7417 let mut edits = Vec::new();
7418 let buffer = self.buffer.read(cx);
7419 let snapshot = buffer.snapshot(cx);
7420 for selection in &mut selections {
7421 if selection.start.row != prev_edited_row {
7422 row_delta = 0;
7423 }
7424 prev_edited_row = selection.end.row;
7425
7426 row_delta =
7427 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7428 }
7429
7430 self.transact(window, cx, |this, window, cx| {
7431 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7432 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7433 s.select(selections)
7434 });
7435 });
7436 }
7437
7438 fn indent_selection(
7439 buffer: &MultiBuffer,
7440 snapshot: &MultiBufferSnapshot,
7441 selection: &mut Selection<Point>,
7442 edits: &mut Vec<(Range<Point>, String)>,
7443 delta_for_start_row: u32,
7444 cx: &App,
7445 ) -> u32 {
7446 let settings = buffer.language_settings_at(selection.start, cx);
7447 let tab_size = settings.tab_size.get();
7448 let indent_kind = if settings.hard_tabs {
7449 IndentKind::Tab
7450 } else {
7451 IndentKind::Space
7452 };
7453 let mut start_row = selection.start.row;
7454 let mut end_row = selection.end.row + 1;
7455
7456 // If a selection ends at the beginning of a line, don't indent
7457 // that last line.
7458 if selection.end.column == 0 && selection.end.row > selection.start.row {
7459 end_row -= 1;
7460 }
7461
7462 // Avoid re-indenting a row that has already been indented by a
7463 // previous selection, but still update this selection's column
7464 // to reflect that indentation.
7465 if delta_for_start_row > 0 {
7466 start_row += 1;
7467 selection.start.column += delta_for_start_row;
7468 if selection.end.row == selection.start.row {
7469 selection.end.column += delta_for_start_row;
7470 }
7471 }
7472
7473 let mut delta_for_end_row = 0;
7474 let has_multiple_rows = start_row + 1 != end_row;
7475 for row in start_row..end_row {
7476 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7477 let indent_delta = match (current_indent.kind, indent_kind) {
7478 (IndentKind::Space, IndentKind::Space) => {
7479 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7480 IndentSize::spaces(columns_to_next_tab_stop)
7481 }
7482 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7483 (_, IndentKind::Tab) => IndentSize::tab(),
7484 };
7485
7486 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7487 0
7488 } else {
7489 selection.start.column
7490 };
7491 let row_start = Point::new(row, start);
7492 edits.push((
7493 row_start..row_start,
7494 indent_delta.chars().collect::<String>(),
7495 ));
7496
7497 // Update this selection's endpoints to reflect the indentation.
7498 if row == selection.start.row {
7499 selection.start.column += indent_delta.len;
7500 }
7501 if row == selection.end.row {
7502 selection.end.column += indent_delta.len;
7503 delta_for_end_row = indent_delta.len;
7504 }
7505 }
7506
7507 if selection.start.row == selection.end.row {
7508 delta_for_start_row + delta_for_end_row
7509 } else {
7510 delta_for_end_row
7511 }
7512 }
7513
7514 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7515 if self.read_only(cx) {
7516 return;
7517 }
7518 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7519 let selections = self.selections.all::<Point>(cx);
7520 let mut deletion_ranges = Vec::new();
7521 let mut last_outdent = None;
7522 {
7523 let buffer = self.buffer.read(cx);
7524 let snapshot = buffer.snapshot(cx);
7525 for selection in &selections {
7526 let settings = buffer.language_settings_at(selection.start, cx);
7527 let tab_size = settings.tab_size.get();
7528 let mut rows = selection.spanned_rows(false, &display_map);
7529
7530 // Avoid re-outdenting a row that has already been outdented by a
7531 // previous selection.
7532 if let Some(last_row) = last_outdent {
7533 if last_row == rows.start {
7534 rows.start = rows.start.next_row();
7535 }
7536 }
7537 let has_multiple_rows = rows.len() > 1;
7538 for row in rows.iter_rows() {
7539 let indent_size = snapshot.indent_size_for_line(row);
7540 if indent_size.len > 0 {
7541 let deletion_len = match indent_size.kind {
7542 IndentKind::Space => {
7543 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7544 if columns_to_prev_tab_stop == 0 {
7545 tab_size
7546 } else {
7547 columns_to_prev_tab_stop
7548 }
7549 }
7550 IndentKind::Tab => 1,
7551 };
7552 let start = if has_multiple_rows
7553 || deletion_len > selection.start.column
7554 || indent_size.len < selection.start.column
7555 {
7556 0
7557 } else {
7558 selection.start.column - deletion_len
7559 };
7560 deletion_ranges.push(
7561 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7562 );
7563 last_outdent = Some(row);
7564 }
7565 }
7566 }
7567 }
7568
7569 self.transact(window, cx, |this, window, cx| {
7570 this.buffer.update(cx, |buffer, cx| {
7571 let empty_str: Arc<str> = Arc::default();
7572 buffer.edit(
7573 deletion_ranges
7574 .into_iter()
7575 .map(|range| (range, empty_str.clone())),
7576 None,
7577 cx,
7578 );
7579 });
7580 let selections = this.selections.all::<usize>(cx);
7581 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7582 s.select(selections)
7583 });
7584 });
7585 }
7586
7587 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7588 if self.read_only(cx) {
7589 return;
7590 }
7591 let selections = self
7592 .selections
7593 .all::<usize>(cx)
7594 .into_iter()
7595 .map(|s| s.range());
7596
7597 self.transact(window, cx, |this, window, cx| {
7598 this.buffer.update(cx, |buffer, cx| {
7599 buffer.autoindent_ranges(selections, cx);
7600 });
7601 let selections = this.selections.all::<usize>(cx);
7602 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7603 s.select(selections)
7604 });
7605 });
7606 }
7607
7608 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7609 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7610 let selections = self.selections.all::<Point>(cx);
7611
7612 let mut new_cursors = Vec::new();
7613 let mut edit_ranges = Vec::new();
7614 let mut selections = selections.iter().peekable();
7615 while let Some(selection) = selections.next() {
7616 let mut rows = selection.spanned_rows(false, &display_map);
7617 let goal_display_column = selection.head().to_display_point(&display_map).column();
7618
7619 // Accumulate contiguous regions of rows that we want to delete.
7620 while let Some(next_selection) = selections.peek() {
7621 let next_rows = next_selection.spanned_rows(false, &display_map);
7622 if next_rows.start <= rows.end {
7623 rows.end = next_rows.end;
7624 selections.next().unwrap();
7625 } else {
7626 break;
7627 }
7628 }
7629
7630 let buffer = &display_map.buffer_snapshot;
7631 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7632 let edit_end;
7633 let cursor_buffer_row;
7634 if buffer.max_point().row >= rows.end.0 {
7635 // If there's a line after the range, delete the \n from the end of the row range
7636 // and position the cursor on the next line.
7637 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7638 cursor_buffer_row = rows.end;
7639 } else {
7640 // If there isn't a line after the range, delete the \n from the line before the
7641 // start of the row range and position the cursor there.
7642 edit_start = edit_start.saturating_sub(1);
7643 edit_end = buffer.len();
7644 cursor_buffer_row = rows.start.previous_row();
7645 }
7646
7647 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7648 *cursor.column_mut() =
7649 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7650
7651 new_cursors.push((
7652 selection.id,
7653 buffer.anchor_after(cursor.to_point(&display_map)),
7654 ));
7655 edit_ranges.push(edit_start..edit_end);
7656 }
7657
7658 self.transact(window, cx, |this, window, cx| {
7659 let buffer = this.buffer.update(cx, |buffer, cx| {
7660 let empty_str: Arc<str> = Arc::default();
7661 buffer.edit(
7662 edit_ranges
7663 .into_iter()
7664 .map(|range| (range, empty_str.clone())),
7665 None,
7666 cx,
7667 );
7668 buffer.snapshot(cx)
7669 });
7670 let new_selections = new_cursors
7671 .into_iter()
7672 .map(|(id, cursor)| {
7673 let cursor = cursor.to_point(&buffer);
7674 Selection {
7675 id,
7676 start: cursor,
7677 end: cursor,
7678 reversed: false,
7679 goal: SelectionGoal::None,
7680 }
7681 })
7682 .collect();
7683
7684 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7685 s.select(new_selections);
7686 });
7687 });
7688 }
7689
7690 pub fn join_lines_impl(
7691 &mut self,
7692 insert_whitespace: bool,
7693 window: &mut Window,
7694 cx: &mut Context<Self>,
7695 ) {
7696 if self.read_only(cx) {
7697 return;
7698 }
7699 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7700 for selection in self.selections.all::<Point>(cx) {
7701 let start = MultiBufferRow(selection.start.row);
7702 // Treat single line selections as if they include the next line. Otherwise this action
7703 // would do nothing for single line selections individual cursors.
7704 let end = if selection.start.row == selection.end.row {
7705 MultiBufferRow(selection.start.row + 1)
7706 } else {
7707 MultiBufferRow(selection.end.row)
7708 };
7709
7710 if let Some(last_row_range) = row_ranges.last_mut() {
7711 if start <= last_row_range.end {
7712 last_row_range.end = end;
7713 continue;
7714 }
7715 }
7716 row_ranges.push(start..end);
7717 }
7718
7719 let snapshot = self.buffer.read(cx).snapshot(cx);
7720 let mut cursor_positions = Vec::new();
7721 for row_range in &row_ranges {
7722 let anchor = snapshot.anchor_before(Point::new(
7723 row_range.end.previous_row().0,
7724 snapshot.line_len(row_range.end.previous_row()),
7725 ));
7726 cursor_positions.push(anchor..anchor);
7727 }
7728
7729 self.transact(window, cx, |this, window, cx| {
7730 for row_range in row_ranges.into_iter().rev() {
7731 for row in row_range.iter_rows().rev() {
7732 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7733 let next_line_row = row.next_row();
7734 let indent = snapshot.indent_size_for_line(next_line_row);
7735 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7736
7737 let replace =
7738 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7739 " "
7740 } else {
7741 ""
7742 };
7743
7744 this.buffer.update(cx, |buffer, cx| {
7745 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7746 });
7747 }
7748 }
7749
7750 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7751 s.select_anchor_ranges(cursor_positions)
7752 });
7753 });
7754 }
7755
7756 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7757 self.join_lines_impl(true, window, cx);
7758 }
7759
7760 pub fn sort_lines_case_sensitive(
7761 &mut self,
7762 _: &SortLinesCaseSensitive,
7763 window: &mut Window,
7764 cx: &mut Context<Self>,
7765 ) {
7766 self.manipulate_lines(window, cx, |lines| lines.sort())
7767 }
7768
7769 pub fn sort_lines_case_insensitive(
7770 &mut self,
7771 _: &SortLinesCaseInsensitive,
7772 window: &mut Window,
7773 cx: &mut Context<Self>,
7774 ) {
7775 self.manipulate_lines(window, cx, |lines| {
7776 lines.sort_by_key(|line| line.to_lowercase())
7777 })
7778 }
7779
7780 pub fn unique_lines_case_insensitive(
7781 &mut self,
7782 _: &UniqueLinesCaseInsensitive,
7783 window: &mut Window,
7784 cx: &mut Context<Self>,
7785 ) {
7786 self.manipulate_lines(window, cx, |lines| {
7787 let mut seen = HashSet::default();
7788 lines.retain(|line| seen.insert(line.to_lowercase()));
7789 })
7790 }
7791
7792 pub fn unique_lines_case_sensitive(
7793 &mut self,
7794 _: &UniqueLinesCaseSensitive,
7795 window: &mut Window,
7796 cx: &mut Context<Self>,
7797 ) {
7798 self.manipulate_lines(window, cx, |lines| {
7799 let mut seen = HashSet::default();
7800 lines.retain(|line| seen.insert(*line));
7801 })
7802 }
7803
7804 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7805 let Some(project) = self.project.clone() else {
7806 return;
7807 };
7808 self.reload(project, window, cx)
7809 .detach_and_notify_err(window, cx);
7810 }
7811
7812 pub fn restore_file(
7813 &mut self,
7814 _: &::git::RestoreFile,
7815 window: &mut Window,
7816 cx: &mut Context<Self>,
7817 ) {
7818 let mut buffer_ids = HashSet::default();
7819 let snapshot = self.buffer().read(cx).snapshot(cx);
7820 for selection in self.selections.all::<usize>(cx) {
7821 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7822 }
7823
7824 let buffer = self.buffer().read(cx);
7825 let ranges = buffer_ids
7826 .into_iter()
7827 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7828 .collect::<Vec<_>>();
7829
7830 self.restore_hunks_in_ranges(ranges, window, cx);
7831 }
7832
7833 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7834 let selections = self
7835 .selections
7836 .all(cx)
7837 .into_iter()
7838 .map(|s| s.range())
7839 .collect();
7840 self.restore_hunks_in_ranges(selections, window, cx);
7841 }
7842
7843 fn restore_hunks_in_ranges(
7844 &mut self,
7845 ranges: Vec<Range<Point>>,
7846 window: &mut Window,
7847 cx: &mut Context<Editor>,
7848 ) {
7849 let mut revert_changes = HashMap::default();
7850 let chunk_by = self
7851 .snapshot(window, cx)
7852 .hunks_for_ranges(ranges)
7853 .into_iter()
7854 .chunk_by(|hunk| hunk.buffer_id);
7855 for (buffer_id, hunks) in &chunk_by {
7856 let hunks = hunks.collect::<Vec<_>>();
7857 for hunk in &hunks {
7858 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7859 }
7860 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7861 }
7862 drop(chunk_by);
7863 if !revert_changes.is_empty() {
7864 self.transact(window, cx, |editor, window, cx| {
7865 editor.restore(revert_changes, window, cx);
7866 });
7867 }
7868 }
7869
7870 pub fn open_active_item_in_terminal(
7871 &mut self,
7872 _: &OpenInTerminal,
7873 window: &mut Window,
7874 cx: &mut Context<Self>,
7875 ) {
7876 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7877 let project_path = buffer.read(cx).project_path(cx)?;
7878 let project = self.project.as_ref()?.read(cx);
7879 let entry = project.entry_for_path(&project_path, cx)?;
7880 let parent = match &entry.canonical_path {
7881 Some(canonical_path) => canonical_path.to_path_buf(),
7882 None => project.absolute_path(&project_path, cx)?,
7883 }
7884 .parent()?
7885 .to_path_buf();
7886 Some(parent)
7887 }) {
7888 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7889 }
7890 }
7891
7892 pub fn prepare_restore_change(
7893 &self,
7894 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7895 hunk: &MultiBufferDiffHunk,
7896 cx: &mut App,
7897 ) -> Option<()> {
7898 if hunk.is_created_file() {
7899 return None;
7900 }
7901 let buffer = self.buffer.read(cx);
7902 let diff = buffer.diff_for(hunk.buffer_id)?;
7903 let buffer = buffer.buffer(hunk.buffer_id)?;
7904 let buffer = buffer.read(cx);
7905 let original_text = diff
7906 .read(cx)
7907 .base_text()
7908 .as_rope()
7909 .slice(hunk.diff_base_byte_range.clone());
7910 let buffer_snapshot = buffer.snapshot();
7911 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7912 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7913 probe
7914 .0
7915 .start
7916 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7917 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7918 }) {
7919 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7920 Some(())
7921 } else {
7922 None
7923 }
7924 }
7925
7926 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7927 self.manipulate_lines(window, cx, |lines| lines.reverse())
7928 }
7929
7930 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7931 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7932 }
7933
7934 fn manipulate_lines<Fn>(
7935 &mut self,
7936 window: &mut Window,
7937 cx: &mut Context<Self>,
7938 mut callback: Fn,
7939 ) where
7940 Fn: FnMut(&mut Vec<&str>),
7941 {
7942 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7943 let buffer = self.buffer.read(cx).snapshot(cx);
7944
7945 let mut edits = Vec::new();
7946
7947 let selections = self.selections.all::<Point>(cx);
7948 let mut selections = selections.iter().peekable();
7949 let mut contiguous_row_selections = Vec::new();
7950 let mut new_selections = Vec::new();
7951 let mut added_lines = 0;
7952 let mut removed_lines = 0;
7953
7954 while let Some(selection) = selections.next() {
7955 let (start_row, end_row) = consume_contiguous_rows(
7956 &mut contiguous_row_selections,
7957 selection,
7958 &display_map,
7959 &mut selections,
7960 );
7961
7962 let start_point = Point::new(start_row.0, 0);
7963 let end_point = Point::new(
7964 end_row.previous_row().0,
7965 buffer.line_len(end_row.previous_row()),
7966 );
7967 let text = buffer
7968 .text_for_range(start_point..end_point)
7969 .collect::<String>();
7970
7971 let mut lines = text.split('\n').collect_vec();
7972
7973 let lines_before = lines.len();
7974 callback(&mut lines);
7975 let lines_after = lines.len();
7976
7977 edits.push((start_point..end_point, lines.join("\n")));
7978
7979 // Selections must change based on added and removed line count
7980 let start_row =
7981 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7982 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7983 new_selections.push(Selection {
7984 id: selection.id,
7985 start: start_row,
7986 end: end_row,
7987 goal: SelectionGoal::None,
7988 reversed: selection.reversed,
7989 });
7990
7991 if lines_after > lines_before {
7992 added_lines += lines_after - lines_before;
7993 } else if lines_before > lines_after {
7994 removed_lines += lines_before - lines_after;
7995 }
7996 }
7997
7998 self.transact(window, cx, |this, window, cx| {
7999 let buffer = this.buffer.update(cx, |buffer, cx| {
8000 buffer.edit(edits, None, cx);
8001 buffer.snapshot(cx)
8002 });
8003
8004 // Recalculate offsets on newly edited buffer
8005 let new_selections = new_selections
8006 .iter()
8007 .map(|s| {
8008 let start_point = Point::new(s.start.0, 0);
8009 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8010 Selection {
8011 id: s.id,
8012 start: buffer.point_to_offset(start_point),
8013 end: buffer.point_to_offset(end_point),
8014 goal: s.goal,
8015 reversed: s.reversed,
8016 }
8017 })
8018 .collect();
8019
8020 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8021 s.select(new_selections);
8022 });
8023
8024 this.request_autoscroll(Autoscroll::fit(), cx);
8025 });
8026 }
8027
8028 pub fn convert_to_upper_case(
8029 &mut self,
8030 _: &ConvertToUpperCase,
8031 window: &mut Window,
8032 cx: &mut Context<Self>,
8033 ) {
8034 self.manipulate_text(window, cx, |text| text.to_uppercase())
8035 }
8036
8037 pub fn convert_to_lower_case(
8038 &mut self,
8039 _: &ConvertToLowerCase,
8040 window: &mut Window,
8041 cx: &mut Context<Self>,
8042 ) {
8043 self.manipulate_text(window, cx, |text| text.to_lowercase())
8044 }
8045
8046 pub fn convert_to_title_case(
8047 &mut self,
8048 _: &ConvertToTitleCase,
8049 window: &mut Window,
8050 cx: &mut Context<Self>,
8051 ) {
8052 self.manipulate_text(window, cx, |text| {
8053 text.split('\n')
8054 .map(|line| line.to_case(Case::Title))
8055 .join("\n")
8056 })
8057 }
8058
8059 pub fn convert_to_snake_case(
8060 &mut self,
8061 _: &ConvertToSnakeCase,
8062 window: &mut Window,
8063 cx: &mut Context<Self>,
8064 ) {
8065 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8066 }
8067
8068 pub fn convert_to_kebab_case(
8069 &mut self,
8070 _: &ConvertToKebabCase,
8071 window: &mut Window,
8072 cx: &mut Context<Self>,
8073 ) {
8074 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8075 }
8076
8077 pub fn convert_to_upper_camel_case(
8078 &mut self,
8079 _: &ConvertToUpperCamelCase,
8080 window: &mut Window,
8081 cx: &mut Context<Self>,
8082 ) {
8083 self.manipulate_text(window, cx, |text| {
8084 text.split('\n')
8085 .map(|line| line.to_case(Case::UpperCamel))
8086 .join("\n")
8087 })
8088 }
8089
8090 pub fn convert_to_lower_camel_case(
8091 &mut self,
8092 _: &ConvertToLowerCamelCase,
8093 window: &mut Window,
8094 cx: &mut Context<Self>,
8095 ) {
8096 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8097 }
8098
8099 pub fn convert_to_opposite_case(
8100 &mut self,
8101 _: &ConvertToOppositeCase,
8102 window: &mut Window,
8103 cx: &mut Context<Self>,
8104 ) {
8105 self.manipulate_text(window, cx, |text| {
8106 text.chars()
8107 .fold(String::with_capacity(text.len()), |mut t, c| {
8108 if c.is_uppercase() {
8109 t.extend(c.to_lowercase());
8110 } else {
8111 t.extend(c.to_uppercase());
8112 }
8113 t
8114 })
8115 })
8116 }
8117
8118 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8119 where
8120 Fn: FnMut(&str) -> String,
8121 {
8122 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8123 let buffer = self.buffer.read(cx).snapshot(cx);
8124
8125 let mut new_selections = Vec::new();
8126 let mut edits = Vec::new();
8127 let mut selection_adjustment = 0i32;
8128
8129 for selection in self.selections.all::<usize>(cx) {
8130 let selection_is_empty = selection.is_empty();
8131
8132 let (start, end) = if selection_is_empty {
8133 let word_range = movement::surrounding_word(
8134 &display_map,
8135 selection.start.to_display_point(&display_map),
8136 );
8137 let start = word_range.start.to_offset(&display_map, Bias::Left);
8138 let end = word_range.end.to_offset(&display_map, Bias::Left);
8139 (start, end)
8140 } else {
8141 (selection.start, selection.end)
8142 };
8143
8144 let text = buffer.text_for_range(start..end).collect::<String>();
8145 let old_length = text.len() as i32;
8146 let text = callback(&text);
8147
8148 new_selections.push(Selection {
8149 start: (start as i32 - selection_adjustment) as usize,
8150 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8151 goal: SelectionGoal::None,
8152 ..selection
8153 });
8154
8155 selection_adjustment += old_length - text.len() as i32;
8156
8157 edits.push((start..end, text));
8158 }
8159
8160 self.transact(window, cx, |this, window, cx| {
8161 this.buffer.update(cx, |buffer, cx| {
8162 buffer.edit(edits, None, cx);
8163 });
8164
8165 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8166 s.select(new_selections);
8167 });
8168
8169 this.request_autoscroll(Autoscroll::fit(), cx);
8170 });
8171 }
8172
8173 pub fn duplicate(
8174 &mut self,
8175 upwards: bool,
8176 whole_lines: bool,
8177 window: &mut Window,
8178 cx: &mut Context<Self>,
8179 ) {
8180 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8181 let buffer = &display_map.buffer_snapshot;
8182 let selections = self.selections.all::<Point>(cx);
8183
8184 let mut edits = Vec::new();
8185 let mut selections_iter = selections.iter().peekable();
8186 while let Some(selection) = selections_iter.next() {
8187 let mut rows = selection.spanned_rows(false, &display_map);
8188 // duplicate line-wise
8189 if whole_lines || selection.start == selection.end {
8190 // Avoid duplicating the same lines twice.
8191 while let Some(next_selection) = selections_iter.peek() {
8192 let next_rows = next_selection.spanned_rows(false, &display_map);
8193 if next_rows.start < rows.end {
8194 rows.end = next_rows.end;
8195 selections_iter.next().unwrap();
8196 } else {
8197 break;
8198 }
8199 }
8200
8201 // Copy the text from the selected row region and splice it either at the start
8202 // or end of the region.
8203 let start = Point::new(rows.start.0, 0);
8204 let end = Point::new(
8205 rows.end.previous_row().0,
8206 buffer.line_len(rows.end.previous_row()),
8207 );
8208 let text = buffer
8209 .text_for_range(start..end)
8210 .chain(Some("\n"))
8211 .collect::<String>();
8212 let insert_location = if upwards {
8213 Point::new(rows.end.0, 0)
8214 } else {
8215 start
8216 };
8217 edits.push((insert_location..insert_location, text));
8218 } else {
8219 // duplicate character-wise
8220 let start = selection.start;
8221 let end = selection.end;
8222 let text = buffer.text_for_range(start..end).collect::<String>();
8223 edits.push((selection.end..selection.end, text));
8224 }
8225 }
8226
8227 self.transact(window, cx, |this, _, cx| {
8228 this.buffer.update(cx, |buffer, cx| {
8229 buffer.edit(edits, None, cx);
8230 });
8231
8232 this.request_autoscroll(Autoscroll::fit(), cx);
8233 });
8234 }
8235
8236 pub fn duplicate_line_up(
8237 &mut self,
8238 _: &DuplicateLineUp,
8239 window: &mut Window,
8240 cx: &mut Context<Self>,
8241 ) {
8242 self.duplicate(true, true, window, cx);
8243 }
8244
8245 pub fn duplicate_line_down(
8246 &mut self,
8247 _: &DuplicateLineDown,
8248 window: &mut Window,
8249 cx: &mut Context<Self>,
8250 ) {
8251 self.duplicate(false, true, window, cx);
8252 }
8253
8254 pub fn duplicate_selection(
8255 &mut self,
8256 _: &DuplicateSelection,
8257 window: &mut Window,
8258 cx: &mut Context<Self>,
8259 ) {
8260 self.duplicate(false, false, window, cx);
8261 }
8262
8263 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8264 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8265 let buffer = self.buffer.read(cx).snapshot(cx);
8266
8267 let mut edits = Vec::new();
8268 let mut unfold_ranges = Vec::new();
8269 let mut refold_creases = Vec::new();
8270
8271 let selections = self.selections.all::<Point>(cx);
8272 let mut selections = selections.iter().peekable();
8273 let mut contiguous_row_selections = Vec::new();
8274 let mut new_selections = Vec::new();
8275
8276 while let Some(selection) = selections.next() {
8277 // Find all the selections that span a contiguous row range
8278 let (start_row, end_row) = consume_contiguous_rows(
8279 &mut contiguous_row_selections,
8280 selection,
8281 &display_map,
8282 &mut selections,
8283 );
8284
8285 // Move the text spanned by the row range to be before the line preceding the row range
8286 if start_row.0 > 0 {
8287 let range_to_move = Point::new(
8288 start_row.previous_row().0,
8289 buffer.line_len(start_row.previous_row()),
8290 )
8291 ..Point::new(
8292 end_row.previous_row().0,
8293 buffer.line_len(end_row.previous_row()),
8294 );
8295 let insertion_point = display_map
8296 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8297 .0;
8298
8299 // Don't move lines across excerpts
8300 if buffer
8301 .excerpt_containing(insertion_point..range_to_move.end)
8302 .is_some()
8303 {
8304 let text = buffer
8305 .text_for_range(range_to_move.clone())
8306 .flat_map(|s| s.chars())
8307 .skip(1)
8308 .chain(['\n'])
8309 .collect::<String>();
8310
8311 edits.push((
8312 buffer.anchor_after(range_to_move.start)
8313 ..buffer.anchor_before(range_to_move.end),
8314 String::new(),
8315 ));
8316 let insertion_anchor = buffer.anchor_after(insertion_point);
8317 edits.push((insertion_anchor..insertion_anchor, text));
8318
8319 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8320
8321 // Move selections up
8322 new_selections.extend(contiguous_row_selections.drain(..).map(
8323 |mut selection| {
8324 selection.start.row -= row_delta;
8325 selection.end.row -= row_delta;
8326 selection
8327 },
8328 ));
8329
8330 // Move folds up
8331 unfold_ranges.push(range_to_move.clone());
8332 for fold in display_map.folds_in_range(
8333 buffer.anchor_before(range_to_move.start)
8334 ..buffer.anchor_after(range_to_move.end),
8335 ) {
8336 let mut start = fold.range.start.to_point(&buffer);
8337 let mut end = fold.range.end.to_point(&buffer);
8338 start.row -= row_delta;
8339 end.row -= row_delta;
8340 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8341 }
8342 }
8343 }
8344
8345 // If we didn't move line(s), preserve the existing selections
8346 new_selections.append(&mut contiguous_row_selections);
8347 }
8348
8349 self.transact(window, cx, |this, window, cx| {
8350 this.unfold_ranges(&unfold_ranges, true, true, cx);
8351 this.buffer.update(cx, |buffer, cx| {
8352 for (range, text) in edits {
8353 buffer.edit([(range, text)], None, cx);
8354 }
8355 });
8356 this.fold_creases(refold_creases, true, window, cx);
8357 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8358 s.select(new_selections);
8359 })
8360 });
8361 }
8362
8363 pub fn move_line_down(
8364 &mut self,
8365 _: &MoveLineDown,
8366 window: &mut Window,
8367 cx: &mut Context<Self>,
8368 ) {
8369 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8370 let buffer = self.buffer.read(cx).snapshot(cx);
8371
8372 let mut edits = Vec::new();
8373 let mut unfold_ranges = Vec::new();
8374 let mut refold_creases = Vec::new();
8375
8376 let selections = self.selections.all::<Point>(cx);
8377 let mut selections = selections.iter().peekable();
8378 let mut contiguous_row_selections = Vec::new();
8379 let mut new_selections = Vec::new();
8380
8381 while let Some(selection) = selections.next() {
8382 // Find all the selections that span a contiguous row range
8383 let (start_row, end_row) = consume_contiguous_rows(
8384 &mut contiguous_row_selections,
8385 selection,
8386 &display_map,
8387 &mut selections,
8388 );
8389
8390 // Move the text spanned by the row range to be after the last line of the row range
8391 if end_row.0 <= buffer.max_point().row {
8392 let range_to_move =
8393 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8394 let insertion_point = display_map
8395 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8396 .0;
8397
8398 // Don't move lines across excerpt boundaries
8399 if buffer
8400 .excerpt_containing(range_to_move.start..insertion_point)
8401 .is_some()
8402 {
8403 let mut text = String::from("\n");
8404 text.extend(buffer.text_for_range(range_to_move.clone()));
8405 text.pop(); // Drop trailing newline
8406 edits.push((
8407 buffer.anchor_after(range_to_move.start)
8408 ..buffer.anchor_before(range_to_move.end),
8409 String::new(),
8410 ));
8411 let insertion_anchor = buffer.anchor_after(insertion_point);
8412 edits.push((insertion_anchor..insertion_anchor, text));
8413
8414 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8415
8416 // Move selections down
8417 new_selections.extend(contiguous_row_selections.drain(..).map(
8418 |mut selection| {
8419 selection.start.row += row_delta;
8420 selection.end.row += row_delta;
8421 selection
8422 },
8423 ));
8424
8425 // Move folds down
8426 unfold_ranges.push(range_to_move.clone());
8427 for fold in display_map.folds_in_range(
8428 buffer.anchor_before(range_to_move.start)
8429 ..buffer.anchor_after(range_to_move.end),
8430 ) {
8431 let mut start = fold.range.start.to_point(&buffer);
8432 let mut end = fold.range.end.to_point(&buffer);
8433 start.row += row_delta;
8434 end.row += row_delta;
8435 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8436 }
8437 }
8438 }
8439
8440 // If we didn't move line(s), preserve the existing selections
8441 new_selections.append(&mut contiguous_row_selections);
8442 }
8443
8444 self.transact(window, cx, |this, window, cx| {
8445 this.unfold_ranges(&unfold_ranges, true, true, cx);
8446 this.buffer.update(cx, |buffer, cx| {
8447 for (range, text) in edits {
8448 buffer.edit([(range, text)], None, cx);
8449 }
8450 });
8451 this.fold_creases(refold_creases, true, window, cx);
8452 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8453 s.select(new_selections)
8454 });
8455 });
8456 }
8457
8458 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8459 let text_layout_details = &self.text_layout_details(window);
8460 self.transact(window, cx, |this, window, cx| {
8461 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8462 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8463 let line_mode = s.line_mode;
8464 s.move_with(|display_map, selection| {
8465 if !selection.is_empty() || line_mode {
8466 return;
8467 }
8468
8469 let mut head = selection.head();
8470 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8471 if head.column() == display_map.line_len(head.row()) {
8472 transpose_offset = display_map
8473 .buffer_snapshot
8474 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8475 }
8476
8477 if transpose_offset == 0 {
8478 return;
8479 }
8480
8481 *head.column_mut() += 1;
8482 head = display_map.clip_point(head, Bias::Right);
8483 let goal = SelectionGoal::HorizontalPosition(
8484 display_map
8485 .x_for_display_point(head, text_layout_details)
8486 .into(),
8487 );
8488 selection.collapse_to(head, goal);
8489
8490 let transpose_start = display_map
8491 .buffer_snapshot
8492 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8493 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8494 let transpose_end = display_map
8495 .buffer_snapshot
8496 .clip_offset(transpose_offset + 1, Bias::Right);
8497 if let Some(ch) =
8498 display_map.buffer_snapshot.chars_at(transpose_start).next()
8499 {
8500 edits.push((transpose_start..transpose_offset, String::new()));
8501 edits.push((transpose_end..transpose_end, ch.to_string()));
8502 }
8503 }
8504 });
8505 edits
8506 });
8507 this.buffer
8508 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8509 let selections = this.selections.all::<usize>(cx);
8510 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8511 s.select(selections);
8512 });
8513 });
8514 }
8515
8516 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8517 self.rewrap_impl(IsVimMode::No, cx)
8518 }
8519
8520 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8521 let buffer = self.buffer.read(cx).snapshot(cx);
8522 let selections = self.selections.all::<Point>(cx);
8523 let mut selections = selections.iter().peekable();
8524
8525 let mut edits = Vec::new();
8526 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8527
8528 while let Some(selection) = selections.next() {
8529 let mut start_row = selection.start.row;
8530 let mut end_row = selection.end.row;
8531
8532 // Skip selections that overlap with a range that has already been rewrapped.
8533 let selection_range = start_row..end_row;
8534 if rewrapped_row_ranges
8535 .iter()
8536 .any(|range| range.overlaps(&selection_range))
8537 {
8538 continue;
8539 }
8540
8541 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
8542
8543 // Since not all lines in the selection may be at the same indent
8544 // level, choose the indent size that is the most common between all
8545 // of the lines.
8546 //
8547 // If there is a tie, we use the deepest indent.
8548 let (indent_size, indent_end) = {
8549 let mut indent_size_occurrences = HashMap::default();
8550 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8551
8552 for row in start_row..=end_row {
8553 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8554 rows_by_indent_size.entry(indent).or_default().push(row);
8555 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8556 }
8557
8558 let indent_size = indent_size_occurrences
8559 .into_iter()
8560 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8561 .map(|(indent, _)| indent)
8562 .unwrap_or_default();
8563 let row = rows_by_indent_size[&indent_size][0];
8564 let indent_end = Point::new(row, indent_size.len);
8565
8566 (indent_size, indent_end)
8567 };
8568
8569 let mut line_prefix = indent_size.chars().collect::<String>();
8570
8571 let mut inside_comment = false;
8572 if let Some(comment_prefix) =
8573 buffer
8574 .language_scope_at(selection.head())
8575 .and_then(|language| {
8576 language
8577 .line_comment_prefixes()
8578 .iter()
8579 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8580 .cloned()
8581 })
8582 {
8583 line_prefix.push_str(&comment_prefix);
8584 inside_comment = true;
8585 }
8586
8587 let language_settings = buffer.language_settings_at(selection.head(), cx);
8588 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8589 RewrapBehavior::InComments => inside_comment,
8590 RewrapBehavior::InSelections => !selection.is_empty(),
8591 RewrapBehavior::Anywhere => true,
8592 };
8593
8594 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8595 if !should_rewrap {
8596 continue;
8597 }
8598
8599 if selection.is_empty() {
8600 'expand_upwards: while start_row > 0 {
8601 let prev_row = start_row - 1;
8602 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8603 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8604 {
8605 start_row = prev_row;
8606 } else {
8607 break 'expand_upwards;
8608 }
8609 }
8610
8611 'expand_downwards: while end_row < buffer.max_point().row {
8612 let next_row = end_row + 1;
8613 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8614 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8615 {
8616 end_row = next_row;
8617 } else {
8618 break 'expand_downwards;
8619 }
8620 }
8621 }
8622
8623 let start = Point::new(start_row, 0);
8624 let start_offset = start.to_offset(&buffer);
8625 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8626 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8627 let Some(lines_without_prefixes) = selection_text
8628 .lines()
8629 .map(|line| {
8630 line.strip_prefix(&line_prefix)
8631 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8632 .ok_or_else(|| {
8633 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8634 })
8635 })
8636 .collect::<Result<Vec<_>, _>>()
8637 .log_err()
8638 else {
8639 continue;
8640 };
8641
8642 let wrap_column = buffer
8643 .language_settings_at(Point::new(start_row, 0), cx)
8644 .preferred_line_length as usize;
8645 let wrapped_text = wrap_with_prefix(
8646 line_prefix,
8647 lines_without_prefixes.join(" "),
8648 wrap_column,
8649 tab_size,
8650 );
8651
8652 // TODO: should always use char-based diff while still supporting cursor behavior that
8653 // matches vim.
8654 let mut diff_options = DiffOptions::default();
8655 if is_vim_mode == IsVimMode::Yes {
8656 diff_options.max_word_diff_len = 0;
8657 diff_options.max_word_diff_line_count = 0;
8658 } else {
8659 diff_options.max_word_diff_len = usize::MAX;
8660 diff_options.max_word_diff_line_count = usize::MAX;
8661 }
8662
8663 for (old_range, new_text) in
8664 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8665 {
8666 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8667 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8668 edits.push((edit_start..edit_end, new_text));
8669 }
8670
8671 rewrapped_row_ranges.push(start_row..=end_row);
8672 }
8673
8674 self.buffer
8675 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8676 }
8677
8678 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8679 let mut text = String::new();
8680 let buffer = self.buffer.read(cx).snapshot(cx);
8681 let mut selections = self.selections.all::<Point>(cx);
8682 let mut clipboard_selections = Vec::with_capacity(selections.len());
8683 {
8684 let max_point = buffer.max_point();
8685 let mut is_first = true;
8686 for selection in &mut selections {
8687 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8688 if is_entire_line {
8689 selection.start = Point::new(selection.start.row, 0);
8690 if !selection.is_empty() && selection.end.column == 0 {
8691 selection.end = cmp::min(max_point, selection.end);
8692 } else {
8693 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8694 }
8695 selection.goal = SelectionGoal::None;
8696 }
8697 if is_first {
8698 is_first = false;
8699 } else {
8700 text += "\n";
8701 }
8702 let mut len = 0;
8703 for chunk in buffer.text_for_range(selection.start..selection.end) {
8704 text.push_str(chunk);
8705 len += chunk.len();
8706 }
8707 clipboard_selections.push(ClipboardSelection {
8708 len,
8709 is_entire_line,
8710 first_line_indent: buffer
8711 .indent_size_for_line(MultiBufferRow(selection.start.row))
8712 .len,
8713 });
8714 }
8715 }
8716
8717 self.transact(window, cx, |this, window, cx| {
8718 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8719 s.select(selections);
8720 });
8721 this.insert("", window, cx);
8722 });
8723 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8724 }
8725
8726 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8727 let item = self.cut_common(window, cx);
8728 cx.write_to_clipboard(item);
8729 }
8730
8731 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8732 self.change_selections(None, window, cx, |s| {
8733 s.move_with(|snapshot, sel| {
8734 if sel.is_empty() {
8735 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8736 }
8737 });
8738 });
8739 let item = self.cut_common(window, cx);
8740 cx.set_global(KillRing(item))
8741 }
8742
8743 pub fn kill_ring_yank(
8744 &mut self,
8745 _: &KillRingYank,
8746 window: &mut Window,
8747 cx: &mut Context<Self>,
8748 ) {
8749 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8750 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8751 (kill_ring.text().to_string(), kill_ring.metadata_json())
8752 } else {
8753 return;
8754 }
8755 } else {
8756 return;
8757 };
8758 self.do_paste(&text, metadata, false, window, cx);
8759 }
8760
8761 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8762 let selections = self.selections.all::<Point>(cx);
8763 let buffer = self.buffer.read(cx).read(cx);
8764 let mut text = String::new();
8765
8766 let mut clipboard_selections = Vec::with_capacity(selections.len());
8767 {
8768 let max_point = buffer.max_point();
8769 let mut is_first = true;
8770 for selection in selections.iter() {
8771 let mut start = selection.start;
8772 let mut end = selection.end;
8773 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8774 if is_entire_line {
8775 start = Point::new(start.row, 0);
8776 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8777 }
8778 if is_first {
8779 is_first = false;
8780 } else {
8781 text += "\n";
8782 }
8783 let mut len = 0;
8784 for chunk in buffer.text_for_range(start..end) {
8785 text.push_str(chunk);
8786 len += chunk.len();
8787 }
8788 clipboard_selections.push(ClipboardSelection {
8789 len,
8790 is_entire_line,
8791 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8792 });
8793 }
8794 }
8795
8796 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8797 text,
8798 clipboard_selections,
8799 ));
8800 }
8801
8802 pub fn do_paste(
8803 &mut self,
8804 text: &String,
8805 clipboard_selections: Option<Vec<ClipboardSelection>>,
8806 handle_entire_lines: bool,
8807 window: &mut Window,
8808 cx: &mut Context<Self>,
8809 ) {
8810 if self.read_only(cx) {
8811 return;
8812 }
8813
8814 let clipboard_text = Cow::Borrowed(text);
8815
8816 self.transact(window, cx, |this, window, cx| {
8817 if let Some(mut clipboard_selections) = clipboard_selections {
8818 let old_selections = this.selections.all::<usize>(cx);
8819 let all_selections_were_entire_line =
8820 clipboard_selections.iter().all(|s| s.is_entire_line);
8821 let first_selection_indent_column =
8822 clipboard_selections.first().map(|s| s.first_line_indent);
8823 if clipboard_selections.len() != old_selections.len() {
8824 clipboard_selections.drain(..);
8825 }
8826 let cursor_offset = this.selections.last::<usize>(cx).head();
8827 let mut auto_indent_on_paste = true;
8828
8829 this.buffer.update(cx, |buffer, cx| {
8830 let snapshot = buffer.read(cx);
8831 auto_indent_on_paste = snapshot
8832 .language_settings_at(cursor_offset, cx)
8833 .auto_indent_on_paste;
8834
8835 let mut start_offset = 0;
8836 let mut edits = Vec::new();
8837 let mut original_indent_columns = Vec::new();
8838 for (ix, selection) in old_selections.iter().enumerate() {
8839 let to_insert;
8840 let entire_line;
8841 let original_indent_column;
8842 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8843 let end_offset = start_offset + clipboard_selection.len;
8844 to_insert = &clipboard_text[start_offset..end_offset];
8845 entire_line = clipboard_selection.is_entire_line;
8846 start_offset = end_offset + 1;
8847 original_indent_column = Some(clipboard_selection.first_line_indent);
8848 } else {
8849 to_insert = clipboard_text.as_str();
8850 entire_line = all_selections_were_entire_line;
8851 original_indent_column = first_selection_indent_column
8852 }
8853
8854 // If the corresponding selection was empty when this slice of the
8855 // clipboard text was written, then the entire line containing the
8856 // selection was copied. If this selection is also currently empty,
8857 // then paste the line before the current line of the buffer.
8858 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8859 let column = selection.start.to_point(&snapshot).column as usize;
8860 let line_start = selection.start - column;
8861 line_start..line_start
8862 } else {
8863 selection.range()
8864 };
8865
8866 edits.push((range, to_insert));
8867 original_indent_columns.push(original_indent_column);
8868 }
8869 drop(snapshot);
8870
8871 buffer.edit(
8872 edits,
8873 if auto_indent_on_paste {
8874 Some(AutoindentMode::Block {
8875 original_indent_columns,
8876 })
8877 } else {
8878 None
8879 },
8880 cx,
8881 );
8882 });
8883
8884 let selections = this.selections.all::<usize>(cx);
8885 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8886 s.select(selections)
8887 });
8888 } else {
8889 this.insert(&clipboard_text, window, cx);
8890 }
8891 });
8892 }
8893
8894 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8895 if let Some(item) = cx.read_from_clipboard() {
8896 let entries = item.entries();
8897
8898 match entries.first() {
8899 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8900 // of all the pasted entries.
8901 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8902 .do_paste(
8903 clipboard_string.text(),
8904 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8905 true,
8906 window,
8907 cx,
8908 ),
8909 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8910 }
8911 }
8912 }
8913
8914 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8915 if self.read_only(cx) {
8916 return;
8917 }
8918
8919 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8920 if let Some((selections, _)) =
8921 self.selection_history.transaction(transaction_id).cloned()
8922 {
8923 self.change_selections(None, window, cx, |s| {
8924 s.select_anchors(selections.to_vec());
8925 });
8926 } else {
8927 log::error!(
8928 "No entry in selection_history found for undo. \
8929 This may correspond to a bug where undo does not update the selection. \
8930 If this is occurring, please add details to \
8931 https://github.com/zed-industries/zed/issues/22692"
8932 );
8933 }
8934 self.request_autoscroll(Autoscroll::fit(), cx);
8935 self.unmark_text(window, cx);
8936 self.refresh_inline_completion(true, false, window, cx);
8937 cx.emit(EditorEvent::Edited { transaction_id });
8938 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8939 }
8940 }
8941
8942 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8943 if self.read_only(cx) {
8944 return;
8945 }
8946
8947 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8948 if let Some((_, Some(selections))) =
8949 self.selection_history.transaction(transaction_id).cloned()
8950 {
8951 self.change_selections(None, window, cx, |s| {
8952 s.select_anchors(selections.to_vec());
8953 });
8954 } else {
8955 log::error!(
8956 "No entry in selection_history found for redo. \
8957 This may correspond to a bug where undo does not update the selection. \
8958 If this is occurring, please add details to \
8959 https://github.com/zed-industries/zed/issues/22692"
8960 );
8961 }
8962 self.request_autoscroll(Autoscroll::fit(), cx);
8963 self.unmark_text(window, cx);
8964 self.refresh_inline_completion(true, false, window, cx);
8965 cx.emit(EditorEvent::Edited { transaction_id });
8966 }
8967 }
8968
8969 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8970 self.buffer
8971 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8972 }
8973
8974 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8975 self.buffer
8976 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8977 }
8978
8979 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8980 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8981 let line_mode = s.line_mode;
8982 s.move_with(|map, selection| {
8983 let cursor = if selection.is_empty() && !line_mode {
8984 movement::left(map, selection.start)
8985 } else {
8986 selection.start
8987 };
8988 selection.collapse_to(cursor, SelectionGoal::None);
8989 });
8990 })
8991 }
8992
8993 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8994 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8995 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8996 })
8997 }
8998
8999 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9000 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9001 let line_mode = s.line_mode;
9002 s.move_with(|map, selection| {
9003 let cursor = if selection.is_empty() && !line_mode {
9004 movement::right(map, selection.end)
9005 } else {
9006 selection.end
9007 };
9008 selection.collapse_to(cursor, SelectionGoal::None)
9009 });
9010 })
9011 }
9012
9013 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9014 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9015 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9016 })
9017 }
9018
9019 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9020 if self.take_rename(true, window, cx).is_some() {
9021 return;
9022 }
9023
9024 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9025 cx.propagate();
9026 return;
9027 }
9028
9029 let text_layout_details = &self.text_layout_details(window);
9030 let selection_count = self.selections.count();
9031 let first_selection = self.selections.first_anchor();
9032
9033 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9034 let line_mode = s.line_mode;
9035 s.move_with(|map, selection| {
9036 if !selection.is_empty() && !line_mode {
9037 selection.goal = SelectionGoal::None;
9038 }
9039 let (cursor, goal) = movement::up(
9040 map,
9041 selection.start,
9042 selection.goal,
9043 false,
9044 text_layout_details,
9045 );
9046 selection.collapse_to(cursor, goal);
9047 });
9048 });
9049
9050 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9051 {
9052 cx.propagate();
9053 }
9054 }
9055
9056 pub fn move_up_by_lines(
9057 &mut self,
9058 action: &MoveUpByLines,
9059 window: &mut Window,
9060 cx: &mut Context<Self>,
9061 ) {
9062 if self.take_rename(true, window, cx).is_some() {
9063 return;
9064 }
9065
9066 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9067 cx.propagate();
9068 return;
9069 }
9070
9071 let text_layout_details = &self.text_layout_details(window);
9072
9073 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9074 let line_mode = s.line_mode;
9075 s.move_with(|map, selection| {
9076 if !selection.is_empty() && !line_mode {
9077 selection.goal = SelectionGoal::None;
9078 }
9079 let (cursor, goal) = movement::up_by_rows(
9080 map,
9081 selection.start,
9082 action.lines,
9083 selection.goal,
9084 false,
9085 text_layout_details,
9086 );
9087 selection.collapse_to(cursor, goal);
9088 });
9089 })
9090 }
9091
9092 pub fn move_down_by_lines(
9093 &mut self,
9094 action: &MoveDownByLines,
9095 window: &mut Window,
9096 cx: &mut Context<Self>,
9097 ) {
9098 if self.take_rename(true, window, cx).is_some() {
9099 return;
9100 }
9101
9102 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9103 cx.propagate();
9104 return;
9105 }
9106
9107 let text_layout_details = &self.text_layout_details(window);
9108
9109 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9110 let line_mode = s.line_mode;
9111 s.move_with(|map, selection| {
9112 if !selection.is_empty() && !line_mode {
9113 selection.goal = SelectionGoal::None;
9114 }
9115 let (cursor, goal) = movement::down_by_rows(
9116 map,
9117 selection.start,
9118 action.lines,
9119 selection.goal,
9120 false,
9121 text_layout_details,
9122 );
9123 selection.collapse_to(cursor, goal);
9124 });
9125 })
9126 }
9127
9128 pub fn select_down_by_lines(
9129 &mut self,
9130 action: &SelectDownByLines,
9131 window: &mut Window,
9132 cx: &mut Context<Self>,
9133 ) {
9134 let text_layout_details = &self.text_layout_details(window);
9135 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9136 s.move_heads_with(|map, head, goal| {
9137 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9138 })
9139 })
9140 }
9141
9142 pub fn select_up_by_lines(
9143 &mut self,
9144 action: &SelectUpByLines,
9145 window: &mut Window,
9146 cx: &mut Context<Self>,
9147 ) {
9148 let text_layout_details = &self.text_layout_details(window);
9149 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9150 s.move_heads_with(|map, head, goal| {
9151 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9152 })
9153 })
9154 }
9155
9156 pub fn select_page_up(
9157 &mut self,
9158 _: &SelectPageUp,
9159 window: &mut Window,
9160 cx: &mut Context<Self>,
9161 ) {
9162 let Some(row_count) = self.visible_row_count() else {
9163 return;
9164 };
9165
9166 let text_layout_details = &self.text_layout_details(window);
9167
9168 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9169 s.move_heads_with(|map, head, goal| {
9170 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9171 })
9172 })
9173 }
9174
9175 pub fn move_page_up(
9176 &mut self,
9177 action: &MovePageUp,
9178 window: &mut Window,
9179 cx: &mut Context<Self>,
9180 ) {
9181 if self.take_rename(true, window, cx).is_some() {
9182 return;
9183 }
9184
9185 if self
9186 .context_menu
9187 .borrow_mut()
9188 .as_mut()
9189 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9190 .unwrap_or(false)
9191 {
9192 return;
9193 }
9194
9195 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9196 cx.propagate();
9197 return;
9198 }
9199
9200 let Some(row_count) = self.visible_row_count() else {
9201 return;
9202 };
9203
9204 let autoscroll = if action.center_cursor {
9205 Autoscroll::center()
9206 } else {
9207 Autoscroll::fit()
9208 };
9209
9210 let text_layout_details = &self.text_layout_details(window);
9211
9212 self.change_selections(Some(autoscroll), window, cx, |s| {
9213 let line_mode = s.line_mode;
9214 s.move_with(|map, selection| {
9215 if !selection.is_empty() && !line_mode {
9216 selection.goal = SelectionGoal::None;
9217 }
9218 let (cursor, goal) = movement::up_by_rows(
9219 map,
9220 selection.end,
9221 row_count,
9222 selection.goal,
9223 false,
9224 text_layout_details,
9225 );
9226 selection.collapse_to(cursor, goal);
9227 });
9228 });
9229 }
9230
9231 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9232 let text_layout_details = &self.text_layout_details(window);
9233 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9234 s.move_heads_with(|map, head, goal| {
9235 movement::up(map, head, goal, false, text_layout_details)
9236 })
9237 })
9238 }
9239
9240 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9241 self.take_rename(true, window, cx);
9242
9243 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9244 cx.propagate();
9245 return;
9246 }
9247
9248 let text_layout_details = &self.text_layout_details(window);
9249 let selection_count = self.selections.count();
9250 let first_selection = self.selections.first_anchor();
9251
9252 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9253 let line_mode = s.line_mode;
9254 s.move_with(|map, selection| {
9255 if !selection.is_empty() && !line_mode {
9256 selection.goal = SelectionGoal::None;
9257 }
9258 let (cursor, goal) = movement::down(
9259 map,
9260 selection.end,
9261 selection.goal,
9262 false,
9263 text_layout_details,
9264 );
9265 selection.collapse_to(cursor, goal);
9266 });
9267 });
9268
9269 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9270 {
9271 cx.propagate();
9272 }
9273 }
9274
9275 pub fn select_page_down(
9276 &mut self,
9277 _: &SelectPageDown,
9278 window: &mut Window,
9279 cx: &mut Context<Self>,
9280 ) {
9281 let Some(row_count) = self.visible_row_count() else {
9282 return;
9283 };
9284
9285 let text_layout_details = &self.text_layout_details(window);
9286
9287 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9288 s.move_heads_with(|map, head, goal| {
9289 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9290 })
9291 })
9292 }
9293
9294 pub fn move_page_down(
9295 &mut self,
9296 action: &MovePageDown,
9297 window: &mut Window,
9298 cx: &mut Context<Self>,
9299 ) {
9300 if self.take_rename(true, window, cx).is_some() {
9301 return;
9302 }
9303
9304 if self
9305 .context_menu
9306 .borrow_mut()
9307 .as_mut()
9308 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9309 .unwrap_or(false)
9310 {
9311 return;
9312 }
9313
9314 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9315 cx.propagate();
9316 return;
9317 }
9318
9319 let Some(row_count) = self.visible_row_count() else {
9320 return;
9321 };
9322
9323 let autoscroll = if action.center_cursor {
9324 Autoscroll::center()
9325 } else {
9326 Autoscroll::fit()
9327 };
9328
9329 let text_layout_details = &self.text_layout_details(window);
9330 self.change_selections(Some(autoscroll), window, cx, |s| {
9331 let line_mode = s.line_mode;
9332 s.move_with(|map, selection| {
9333 if !selection.is_empty() && !line_mode {
9334 selection.goal = SelectionGoal::None;
9335 }
9336 let (cursor, goal) = movement::down_by_rows(
9337 map,
9338 selection.end,
9339 row_count,
9340 selection.goal,
9341 false,
9342 text_layout_details,
9343 );
9344 selection.collapse_to(cursor, goal);
9345 });
9346 });
9347 }
9348
9349 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9350 let text_layout_details = &self.text_layout_details(window);
9351 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9352 s.move_heads_with(|map, head, goal| {
9353 movement::down(map, head, goal, false, text_layout_details)
9354 })
9355 });
9356 }
9357
9358 pub fn context_menu_first(
9359 &mut self,
9360 _: &ContextMenuFirst,
9361 _window: &mut Window,
9362 cx: &mut Context<Self>,
9363 ) {
9364 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9365 context_menu.select_first(self.completion_provider.as_deref(), cx);
9366 }
9367 }
9368
9369 pub fn context_menu_prev(
9370 &mut self,
9371 _: &ContextMenuPrevious,
9372 _window: &mut Window,
9373 cx: &mut Context<Self>,
9374 ) {
9375 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9376 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9377 }
9378 }
9379
9380 pub fn context_menu_next(
9381 &mut self,
9382 _: &ContextMenuNext,
9383 _window: &mut Window,
9384 cx: &mut Context<Self>,
9385 ) {
9386 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9387 context_menu.select_next(self.completion_provider.as_deref(), cx);
9388 }
9389 }
9390
9391 pub fn context_menu_last(
9392 &mut self,
9393 _: &ContextMenuLast,
9394 _window: &mut Window,
9395 cx: &mut Context<Self>,
9396 ) {
9397 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9398 context_menu.select_last(self.completion_provider.as_deref(), cx);
9399 }
9400 }
9401
9402 pub fn move_to_previous_word_start(
9403 &mut self,
9404 _: &MoveToPreviousWordStart,
9405 window: &mut Window,
9406 cx: &mut Context<Self>,
9407 ) {
9408 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9409 s.move_cursors_with(|map, head, _| {
9410 (
9411 movement::previous_word_start(map, head),
9412 SelectionGoal::None,
9413 )
9414 });
9415 })
9416 }
9417
9418 pub fn move_to_previous_subword_start(
9419 &mut self,
9420 _: &MoveToPreviousSubwordStart,
9421 window: &mut Window,
9422 cx: &mut Context<Self>,
9423 ) {
9424 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9425 s.move_cursors_with(|map, head, _| {
9426 (
9427 movement::previous_subword_start(map, head),
9428 SelectionGoal::None,
9429 )
9430 });
9431 })
9432 }
9433
9434 pub fn select_to_previous_word_start(
9435 &mut self,
9436 _: &SelectToPreviousWordStart,
9437 window: &mut Window,
9438 cx: &mut Context<Self>,
9439 ) {
9440 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9441 s.move_heads_with(|map, head, _| {
9442 (
9443 movement::previous_word_start(map, head),
9444 SelectionGoal::None,
9445 )
9446 });
9447 })
9448 }
9449
9450 pub fn select_to_previous_subword_start(
9451 &mut self,
9452 _: &SelectToPreviousSubwordStart,
9453 window: &mut Window,
9454 cx: &mut Context<Self>,
9455 ) {
9456 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9457 s.move_heads_with(|map, head, _| {
9458 (
9459 movement::previous_subword_start(map, head),
9460 SelectionGoal::None,
9461 )
9462 });
9463 })
9464 }
9465
9466 pub fn delete_to_previous_word_start(
9467 &mut self,
9468 action: &DeleteToPreviousWordStart,
9469 window: &mut Window,
9470 cx: &mut Context<Self>,
9471 ) {
9472 self.transact(window, cx, |this, window, cx| {
9473 this.select_autoclose_pair(window, cx);
9474 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9475 let line_mode = s.line_mode;
9476 s.move_with(|map, selection| {
9477 if selection.is_empty() && !line_mode {
9478 let cursor = if action.ignore_newlines {
9479 movement::previous_word_start(map, selection.head())
9480 } else {
9481 movement::previous_word_start_or_newline(map, selection.head())
9482 };
9483 selection.set_head(cursor, SelectionGoal::None);
9484 }
9485 });
9486 });
9487 this.insert("", window, cx);
9488 });
9489 }
9490
9491 pub fn delete_to_previous_subword_start(
9492 &mut self,
9493 _: &DeleteToPreviousSubwordStart,
9494 window: &mut Window,
9495 cx: &mut Context<Self>,
9496 ) {
9497 self.transact(window, cx, |this, window, cx| {
9498 this.select_autoclose_pair(window, cx);
9499 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9500 let line_mode = s.line_mode;
9501 s.move_with(|map, selection| {
9502 if selection.is_empty() && !line_mode {
9503 let cursor = movement::previous_subword_start(map, selection.head());
9504 selection.set_head(cursor, SelectionGoal::None);
9505 }
9506 });
9507 });
9508 this.insert("", window, cx);
9509 });
9510 }
9511
9512 pub fn move_to_next_word_end(
9513 &mut self,
9514 _: &MoveToNextWordEnd,
9515 window: &mut Window,
9516 cx: &mut Context<Self>,
9517 ) {
9518 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9519 s.move_cursors_with(|map, head, _| {
9520 (movement::next_word_end(map, head), SelectionGoal::None)
9521 });
9522 })
9523 }
9524
9525 pub fn move_to_next_subword_end(
9526 &mut self,
9527 _: &MoveToNextSubwordEnd,
9528 window: &mut Window,
9529 cx: &mut Context<Self>,
9530 ) {
9531 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9532 s.move_cursors_with(|map, head, _| {
9533 (movement::next_subword_end(map, head), SelectionGoal::None)
9534 });
9535 })
9536 }
9537
9538 pub fn select_to_next_word_end(
9539 &mut self,
9540 _: &SelectToNextWordEnd,
9541 window: &mut Window,
9542 cx: &mut Context<Self>,
9543 ) {
9544 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9545 s.move_heads_with(|map, head, _| {
9546 (movement::next_word_end(map, head), SelectionGoal::None)
9547 });
9548 })
9549 }
9550
9551 pub fn select_to_next_subword_end(
9552 &mut self,
9553 _: &SelectToNextSubwordEnd,
9554 window: &mut Window,
9555 cx: &mut Context<Self>,
9556 ) {
9557 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9558 s.move_heads_with(|map, head, _| {
9559 (movement::next_subword_end(map, head), SelectionGoal::None)
9560 });
9561 })
9562 }
9563
9564 pub fn delete_to_next_word_end(
9565 &mut self,
9566 action: &DeleteToNextWordEnd,
9567 window: &mut Window,
9568 cx: &mut Context<Self>,
9569 ) {
9570 self.transact(window, cx, |this, window, cx| {
9571 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9572 let line_mode = s.line_mode;
9573 s.move_with(|map, selection| {
9574 if selection.is_empty() && !line_mode {
9575 let cursor = if action.ignore_newlines {
9576 movement::next_word_end(map, selection.head())
9577 } else {
9578 movement::next_word_end_or_newline(map, selection.head())
9579 };
9580 selection.set_head(cursor, SelectionGoal::None);
9581 }
9582 });
9583 });
9584 this.insert("", window, cx);
9585 });
9586 }
9587
9588 pub fn delete_to_next_subword_end(
9589 &mut self,
9590 _: &DeleteToNextSubwordEnd,
9591 window: &mut Window,
9592 cx: &mut Context<Self>,
9593 ) {
9594 self.transact(window, cx, |this, window, cx| {
9595 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9596 s.move_with(|map, selection| {
9597 if selection.is_empty() {
9598 let cursor = movement::next_subword_end(map, selection.head());
9599 selection.set_head(cursor, SelectionGoal::None);
9600 }
9601 });
9602 });
9603 this.insert("", window, cx);
9604 });
9605 }
9606
9607 pub fn move_to_beginning_of_line(
9608 &mut self,
9609 action: &MoveToBeginningOfLine,
9610 window: &mut Window,
9611 cx: &mut Context<Self>,
9612 ) {
9613 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9614 s.move_cursors_with(|map, head, _| {
9615 (
9616 movement::indented_line_beginning(
9617 map,
9618 head,
9619 action.stop_at_soft_wraps,
9620 action.stop_at_indent,
9621 ),
9622 SelectionGoal::None,
9623 )
9624 });
9625 })
9626 }
9627
9628 pub fn select_to_beginning_of_line(
9629 &mut self,
9630 action: &SelectToBeginningOfLine,
9631 window: &mut Window,
9632 cx: &mut Context<Self>,
9633 ) {
9634 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9635 s.move_heads_with(|map, head, _| {
9636 (
9637 movement::indented_line_beginning(
9638 map,
9639 head,
9640 action.stop_at_soft_wraps,
9641 action.stop_at_indent,
9642 ),
9643 SelectionGoal::None,
9644 )
9645 });
9646 });
9647 }
9648
9649 pub fn delete_to_beginning_of_line(
9650 &mut self,
9651 action: &DeleteToBeginningOfLine,
9652 window: &mut Window,
9653 cx: &mut Context<Self>,
9654 ) {
9655 self.transact(window, cx, |this, window, cx| {
9656 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9657 s.move_with(|_, selection| {
9658 selection.reversed = true;
9659 });
9660 });
9661
9662 this.select_to_beginning_of_line(
9663 &SelectToBeginningOfLine {
9664 stop_at_soft_wraps: false,
9665 stop_at_indent: action.stop_at_indent,
9666 },
9667 window,
9668 cx,
9669 );
9670 this.backspace(&Backspace, window, cx);
9671 });
9672 }
9673
9674 pub fn move_to_end_of_line(
9675 &mut self,
9676 action: &MoveToEndOfLine,
9677 window: &mut Window,
9678 cx: &mut Context<Self>,
9679 ) {
9680 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9681 s.move_cursors_with(|map, head, _| {
9682 (
9683 movement::line_end(map, head, action.stop_at_soft_wraps),
9684 SelectionGoal::None,
9685 )
9686 });
9687 })
9688 }
9689
9690 pub fn select_to_end_of_line(
9691 &mut self,
9692 action: &SelectToEndOfLine,
9693 window: &mut Window,
9694 cx: &mut Context<Self>,
9695 ) {
9696 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9697 s.move_heads_with(|map, head, _| {
9698 (
9699 movement::line_end(map, head, action.stop_at_soft_wraps),
9700 SelectionGoal::None,
9701 )
9702 });
9703 })
9704 }
9705
9706 pub fn delete_to_end_of_line(
9707 &mut self,
9708 _: &DeleteToEndOfLine,
9709 window: &mut Window,
9710 cx: &mut Context<Self>,
9711 ) {
9712 self.transact(window, cx, |this, window, cx| {
9713 this.select_to_end_of_line(
9714 &SelectToEndOfLine {
9715 stop_at_soft_wraps: false,
9716 },
9717 window,
9718 cx,
9719 );
9720 this.delete(&Delete, window, cx);
9721 });
9722 }
9723
9724 pub fn cut_to_end_of_line(
9725 &mut self,
9726 _: &CutToEndOfLine,
9727 window: &mut Window,
9728 cx: &mut Context<Self>,
9729 ) {
9730 self.transact(window, cx, |this, window, cx| {
9731 this.select_to_end_of_line(
9732 &SelectToEndOfLine {
9733 stop_at_soft_wraps: false,
9734 },
9735 window,
9736 cx,
9737 );
9738 this.cut(&Cut, window, cx);
9739 });
9740 }
9741
9742 pub fn move_to_start_of_paragraph(
9743 &mut self,
9744 _: &MoveToStartOfParagraph,
9745 window: &mut Window,
9746 cx: &mut Context<Self>,
9747 ) {
9748 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9749 cx.propagate();
9750 return;
9751 }
9752
9753 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9754 s.move_with(|map, selection| {
9755 selection.collapse_to(
9756 movement::start_of_paragraph(map, selection.head(), 1),
9757 SelectionGoal::None,
9758 )
9759 });
9760 })
9761 }
9762
9763 pub fn move_to_end_of_paragraph(
9764 &mut self,
9765 _: &MoveToEndOfParagraph,
9766 window: &mut Window,
9767 cx: &mut Context<Self>,
9768 ) {
9769 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9770 cx.propagate();
9771 return;
9772 }
9773
9774 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9775 s.move_with(|map, selection| {
9776 selection.collapse_to(
9777 movement::end_of_paragraph(map, selection.head(), 1),
9778 SelectionGoal::None,
9779 )
9780 });
9781 })
9782 }
9783
9784 pub fn select_to_start_of_paragraph(
9785 &mut self,
9786 _: &SelectToStartOfParagraph,
9787 window: &mut Window,
9788 cx: &mut Context<Self>,
9789 ) {
9790 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9791 cx.propagate();
9792 return;
9793 }
9794
9795 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9796 s.move_heads_with(|map, head, _| {
9797 (
9798 movement::start_of_paragraph(map, head, 1),
9799 SelectionGoal::None,
9800 )
9801 });
9802 })
9803 }
9804
9805 pub fn select_to_end_of_paragraph(
9806 &mut self,
9807 _: &SelectToEndOfParagraph,
9808 window: &mut Window,
9809 cx: &mut Context<Self>,
9810 ) {
9811 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9812 cx.propagate();
9813 return;
9814 }
9815
9816 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9817 s.move_heads_with(|map, head, _| {
9818 (
9819 movement::end_of_paragraph(map, head, 1),
9820 SelectionGoal::None,
9821 )
9822 });
9823 })
9824 }
9825
9826 pub fn move_to_start_of_excerpt(
9827 &mut self,
9828 _: &MoveToStartOfExcerpt,
9829 window: &mut Window,
9830 cx: &mut Context<Self>,
9831 ) {
9832 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9833 cx.propagate();
9834 return;
9835 }
9836
9837 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9838 s.move_with(|map, selection| {
9839 selection.collapse_to(
9840 movement::start_of_excerpt(
9841 map,
9842 selection.head(),
9843 workspace::searchable::Direction::Prev,
9844 ),
9845 SelectionGoal::None,
9846 )
9847 });
9848 })
9849 }
9850
9851 pub fn move_to_start_of_next_excerpt(
9852 &mut self,
9853 _: &MoveToStartOfNextExcerpt,
9854 window: &mut Window,
9855 cx: &mut Context<Self>,
9856 ) {
9857 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9858 cx.propagate();
9859 return;
9860 }
9861
9862 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9863 s.move_with(|map, selection| {
9864 selection.collapse_to(
9865 movement::start_of_excerpt(
9866 map,
9867 selection.head(),
9868 workspace::searchable::Direction::Next,
9869 ),
9870 SelectionGoal::None,
9871 )
9872 });
9873 })
9874 }
9875
9876 pub fn move_to_end_of_excerpt(
9877 &mut self,
9878 _: &MoveToEndOfExcerpt,
9879 window: &mut Window,
9880 cx: &mut Context<Self>,
9881 ) {
9882 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9883 cx.propagate();
9884 return;
9885 }
9886
9887 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9888 s.move_with(|map, selection| {
9889 selection.collapse_to(
9890 movement::end_of_excerpt(
9891 map,
9892 selection.head(),
9893 workspace::searchable::Direction::Next,
9894 ),
9895 SelectionGoal::None,
9896 )
9897 });
9898 })
9899 }
9900
9901 pub fn move_to_end_of_previous_excerpt(
9902 &mut self,
9903 _: &MoveToEndOfPreviousExcerpt,
9904 window: &mut Window,
9905 cx: &mut Context<Self>,
9906 ) {
9907 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9908 cx.propagate();
9909 return;
9910 }
9911
9912 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9913 s.move_with(|map, selection| {
9914 selection.collapse_to(
9915 movement::end_of_excerpt(
9916 map,
9917 selection.head(),
9918 workspace::searchable::Direction::Prev,
9919 ),
9920 SelectionGoal::None,
9921 )
9922 });
9923 })
9924 }
9925
9926 pub fn select_to_start_of_excerpt(
9927 &mut self,
9928 _: &SelectToStartOfExcerpt,
9929 window: &mut Window,
9930 cx: &mut Context<Self>,
9931 ) {
9932 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9933 cx.propagate();
9934 return;
9935 }
9936
9937 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9938 s.move_heads_with(|map, head, _| {
9939 (
9940 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9941 SelectionGoal::None,
9942 )
9943 });
9944 })
9945 }
9946
9947 pub fn select_to_start_of_next_excerpt(
9948 &mut self,
9949 _: &SelectToStartOfNextExcerpt,
9950 window: &mut Window,
9951 cx: &mut Context<Self>,
9952 ) {
9953 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9954 cx.propagate();
9955 return;
9956 }
9957
9958 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9959 s.move_heads_with(|map, head, _| {
9960 (
9961 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
9962 SelectionGoal::None,
9963 )
9964 });
9965 })
9966 }
9967
9968 pub fn select_to_end_of_excerpt(
9969 &mut self,
9970 _: &SelectToEndOfExcerpt,
9971 window: &mut Window,
9972 cx: &mut Context<Self>,
9973 ) {
9974 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9975 cx.propagate();
9976 return;
9977 }
9978
9979 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9980 s.move_heads_with(|map, head, _| {
9981 (
9982 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9983 SelectionGoal::None,
9984 )
9985 });
9986 })
9987 }
9988
9989 pub fn select_to_end_of_previous_excerpt(
9990 &mut self,
9991 _: &SelectToEndOfPreviousExcerpt,
9992 window: &mut Window,
9993 cx: &mut Context<Self>,
9994 ) {
9995 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9996 cx.propagate();
9997 return;
9998 }
9999
10000 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10001 s.move_heads_with(|map, head, _| {
10002 (
10003 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10004 SelectionGoal::None,
10005 )
10006 });
10007 })
10008 }
10009
10010 pub fn move_to_beginning(
10011 &mut self,
10012 _: &MoveToBeginning,
10013 window: &mut Window,
10014 cx: &mut Context<Self>,
10015 ) {
10016 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10017 cx.propagate();
10018 return;
10019 }
10020
10021 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10022 s.select_ranges(vec![0..0]);
10023 });
10024 }
10025
10026 pub fn select_to_beginning(
10027 &mut self,
10028 _: &SelectToBeginning,
10029 window: &mut Window,
10030 cx: &mut Context<Self>,
10031 ) {
10032 let mut selection = self.selections.last::<Point>(cx);
10033 selection.set_head(Point::zero(), SelectionGoal::None);
10034
10035 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10036 s.select(vec![selection]);
10037 });
10038 }
10039
10040 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10041 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10042 cx.propagate();
10043 return;
10044 }
10045
10046 let cursor = self.buffer.read(cx).read(cx).len();
10047 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10048 s.select_ranges(vec![cursor..cursor])
10049 });
10050 }
10051
10052 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10053 self.nav_history = nav_history;
10054 }
10055
10056 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10057 self.nav_history.as_ref()
10058 }
10059
10060 fn push_to_nav_history(
10061 &mut self,
10062 cursor_anchor: Anchor,
10063 new_position: Option<Point>,
10064 cx: &mut Context<Self>,
10065 ) {
10066 if let Some(nav_history) = self.nav_history.as_mut() {
10067 let buffer = self.buffer.read(cx).read(cx);
10068 let cursor_position = cursor_anchor.to_point(&buffer);
10069 let scroll_state = self.scroll_manager.anchor();
10070 let scroll_top_row = scroll_state.top_row(&buffer);
10071 drop(buffer);
10072
10073 if let Some(new_position) = new_position {
10074 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10075 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10076 return;
10077 }
10078 }
10079
10080 nav_history.push(
10081 Some(NavigationData {
10082 cursor_anchor,
10083 cursor_position,
10084 scroll_anchor: scroll_state,
10085 scroll_top_row,
10086 }),
10087 cx,
10088 );
10089 }
10090 }
10091
10092 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10093 let buffer = self.buffer.read(cx).snapshot(cx);
10094 let mut selection = self.selections.first::<usize>(cx);
10095 selection.set_head(buffer.len(), SelectionGoal::None);
10096 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10097 s.select(vec![selection]);
10098 });
10099 }
10100
10101 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10102 let end = self.buffer.read(cx).read(cx).len();
10103 self.change_selections(None, window, cx, |s| {
10104 s.select_ranges(vec![0..end]);
10105 });
10106 }
10107
10108 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10109 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10110 let mut selections = self.selections.all::<Point>(cx);
10111 let max_point = display_map.buffer_snapshot.max_point();
10112 for selection in &mut selections {
10113 let rows = selection.spanned_rows(true, &display_map);
10114 selection.start = Point::new(rows.start.0, 0);
10115 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10116 selection.reversed = false;
10117 }
10118 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10119 s.select(selections);
10120 });
10121 }
10122
10123 pub fn split_selection_into_lines(
10124 &mut self,
10125 _: &SplitSelectionIntoLines,
10126 window: &mut Window,
10127 cx: &mut Context<Self>,
10128 ) {
10129 let selections = self
10130 .selections
10131 .all::<Point>(cx)
10132 .into_iter()
10133 .map(|selection| selection.start..selection.end)
10134 .collect::<Vec<_>>();
10135 self.unfold_ranges(&selections, true, true, cx);
10136
10137 let mut new_selection_ranges = Vec::new();
10138 {
10139 let buffer = self.buffer.read(cx).read(cx);
10140 for selection in selections {
10141 for row in selection.start.row..selection.end.row {
10142 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10143 new_selection_ranges.push(cursor..cursor);
10144 }
10145
10146 let is_multiline_selection = selection.start.row != selection.end.row;
10147 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10148 // so this action feels more ergonomic when paired with other selection operations
10149 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10150 if !should_skip_last {
10151 new_selection_ranges.push(selection.end..selection.end);
10152 }
10153 }
10154 }
10155 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10156 s.select_ranges(new_selection_ranges);
10157 });
10158 }
10159
10160 pub fn add_selection_above(
10161 &mut self,
10162 _: &AddSelectionAbove,
10163 window: &mut Window,
10164 cx: &mut Context<Self>,
10165 ) {
10166 self.add_selection(true, window, cx);
10167 }
10168
10169 pub fn add_selection_below(
10170 &mut self,
10171 _: &AddSelectionBelow,
10172 window: &mut Window,
10173 cx: &mut Context<Self>,
10174 ) {
10175 self.add_selection(false, window, cx);
10176 }
10177
10178 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10179 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10180 let mut selections = self.selections.all::<Point>(cx);
10181 let text_layout_details = self.text_layout_details(window);
10182 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10183 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10184 let range = oldest_selection.display_range(&display_map).sorted();
10185
10186 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10187 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10188 let positions = start_x.min(end_x)..start_x.max(end_x);
10189
10190 selections.clear();
10191 let mut stack = Vec::new();
10192 for row in range.start.row().0..=range.end.row().0 {
10193 if let Some(selection) = self.selections.build_columnar_selection(
10194 &display_map,
10195 DisplayRow(row),
10196 &positions,
10197 oldest_selection.reversed,
10198 &text_layout_details,
10199 ) {
10200 stack.push(selection.id);
10201 selections.push(selection);
10202 }
10203 }
10204
10205 if above {
10206 stack.reverse();
10207 }
10208
10209 AddSelectionsState { above, stack }
10210 });
10211
10212 let last_added_selection = *state.stack.last().unwrap();
10213 let mut new_selections = Vec::new();
10214 if above == state.above {
10215 let end_row = if above {
10216 DisplayRow(0)
10217 } else {
10218 display_map.max_point().row()
10219 };
10220
10221 'outer: for selection in selections {
10222 if selection.id == last_added_selection {
10223 let range = selection.display_range(&display_map).sorted();
10224 debug_assert_eq!(range.start.row(), range.end.row());
10225 let mut row = range.start.row();
10226 let positions =
10227 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10228 px(start)..px(end)
10229 } else {
10230 let start_x =
10231 display_map.x_for_display_point(range.start, &text_layout_details);
10232 let end_x =
10233 display_map.x_for_display_point(range.end, &text_layout_details);
10234 start_x.min(end_x)..start_x.max(end_x)
10235 };
10236
10237 while row != end_row {
10238 if above {
10239 row.0 -= 1;
10240 } else {
10241 row.0 += 1;
10242 }
10243
10244 if let Some(new_selection) = self.selections.build_columnar_selection(
10245 &display_map,
10246 row,
10247 &positions,
10248 selection.reversed,
10249 &text_layout_details,
10250 ) {
10251 state.stack.push(new_selection.id);
10252 if above {
10253 new_selections.push(new_selection);
10254 new_selections.push(selection);
10255 } else {
10256 new_selections.push(selection);
10257 new_selections.push(new_selection);
10258 }
10259
10260 continue 'outer;
10261 }
10262 }
10263 }
10264
10265 new_selections.push(selection);
10266 }
10267 } else {
10268 new_selections = selections;
10269 new_selections.retain(|s| s.id != last_added_selection);
10270 state.stack.pop();
10271 }
10272
10273 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10274 s.select(new_selections);
10275 });
10276 if state.stack.len() > 1 {
10277 self.add_selections_state = Some(state);
10278 }
10279 }
10280
10281 pub fn select_next_match_internal(
10282 &mut self,
10283 display_map: &DisplaySnapshot,
10284 replace_newest: bool,
10285 autoscroll: Option<Autoscroll>,
10286 window: &mut Window,
10287 cx: &mut Context<Self>,
10288 ) -> Result<()> {
10289 fn select_next_match_ranges(
10290 this: &mut Editor,
10291 range: Range<usize>,
10292 replace_newest: bool,
10293 auto_scroll: Option<Autoscroll>,
10294 window: &mut Window,
10295 cx: &mut Context<Editor>,
10296 ) {
10297 this.unfold_ranges(&[range.clone()], false, true, cx);
10298 this.change_selections(auto_scroll, window, cx, |s| {
10299 if replace_newest {
10300 s.delete(s.newest_anchor().id);
10301 }
10302 s.insert_range(range.clone());
10303 });
10304 }
10305
10306 let buffer = &display_map.buffer_snapshot;
10307 let mut selections = self.selections.all::<usize>(cx);
10308 if let Some(mut select_next_state) = self.select_next_state.take() {
10309 let query = &select_next_state.query;
10310 if !select_next_state.done {
10311 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10312 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10313 let mut next_selected_range = None;
10314
10315 let bytes_after_last_selection =
10316 buffer.bytes_in_range(last_selection.end..buffer.len());
10317 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10318 let query_matches = query
10319 .stream_find_iter(bytes_after_last_selection)
10320 .map(|result| (last_selection.end, result))
10321 .chain(
10322 query
10323 .stream_find_iter(bytes_before_first_selection)
10324 .map(|result| (0, result)),
10325 );
10326
10327 for (start_offset, query_match) in query_matches {
10328 let query_match = query_match.unwrap(); // can only fail due to I/O
10329 let offset_range =
10330 start_offset + query_match.start()..start_offset + query_match.end();
10331 let display_range = offset_range.start.to_display_point(display_map)
10332 ..offset_range.end.to_display_point(display_map);
10333
10334 if !select_next_state.wordwise
10335 || (!movement::is_inside_word(display_map, display_range.start)
10336 && !movement::is_inside_word(display_map, display_range.end))
10337 {
10338 // TODO: This is n^2, because we might check all the selections
10339 if !selections
10340 .iter()
10341 .any(|selection| selection.range().overlaps(&offset_range))
10342 {
10343 next_selected_range = Some(offset_range);
10344 break;
10345 }
10346 }
10347 }
10348
10349 if let Some(next_selected_range) = next_selected_range {
10350 select_next_match_ranges(
10351 self,
10352 next_selected_range,
10353 replace_newest,
10354 autoscroll,
10355 window,
10356 cx,
10357 );
10358 } else {
10359 select_next_state.done = true;
10360 }
10361 }
10362
10363 self.select_next_state = Some(select_next_state);
10364 } else {
10365 let mut only_carets = true;
10366 let mut same_text_selected = true;
10367 let mut selected_text = None;
10368
10369 let mut selections_iter = selections.iter().peekable();
10370 while let Some(selection) = selections_iter.next() {
10371 if selection.start != selection.end {
10372 only_carets = false;
10373 }
10374
10375 if same_text_selected {
10376 if selected_text.is_none() {
10377 selected_text =
10378 Some(buffer.text_for_range(selection.range()).collect::<String>());
10379 }
10380
10381 if let Some(next_selection) = selections_iter.peek() {
10382 if next_selection.range().len() == selection.range().len() {
10383 let next_selected_text = buffer
10384 .text_for_range(next_selection.range())
10385 .collect::<String>();
10386 if Some(next_selected_text) != selected_text {
10387 same_text_selected = false;
10388 selected_text = None;
10389 }
10390 } else {
10391 same_text_selected = false;
10392 selected_text = None;
10393 }
10394 }
10395 }
10396 }
10397
10398 if only_carets {
10399 for selection in &mut selections {
10400 let word_range = movement::surrounding_word(
10401 display_map,
10402 selection.start.to_display_point(display_map),
10403 );
10404 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10405 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10406 selection.goal = SelectionGoal::None;
10407 selection.reversed = false;
10408 select_next_match_ranges(
10409 self,
10410 selection.start..selection.end,
10411 replace_newest,
10412 autoscroll,
10413 window,
10414 cx,
10415 );
10416 }
10417
10418 if selections.len() == 1 {
10419 let selection = selections
10420 .last()
10421 .expect("ensured that there's only one selection");
10422 let query = buffer
10423 .text_for_range(selection.start..selection.end)
10424 .collect::<String>();
10425 let is_empty = query.is_empty();
10426 let select_state = SelectNextState {
10427 query: AhoCorasick::new(&[query])?,
10428 wordwise: true,
10429 done: is_empty,
10430 };
10431 self.select_next_state = Some(select_state);
10432 } else {
10433 self.select_next_state = None;
10434 }
10435 } else if let Some(selected_text) = selected_text {
10436 self.select_next_state = Some(SelectNextState {
10437 query: AhoCorasick::new(&[selected_text])?,
10438 wordwise: false,
10439 done: false,
10440 });
10441 self.select_next_match_internal(
10442 display_map,
10443 replace_newest,
10444 autoscroll,
10445 window,
10446 cx,
10447 )?;
10448 }
10449 }
10450 Ok(())
10451 }
10452
10453 pub fn select_all_matches(
10454 &mut self,
10455 _action: &SelectAllMatches,
10456 window: &mut Window,
10457 cx: &mut Context<Self>,
10458 ) -> Result<()> {
10459 self.push_to_selection_history();
10460 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10461
10462 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10463 let Some(select_next_state) = self.select_next_state.as_mut() else {
10464 return Ok(());
10465 };
10466 if select_next_state.done {
10467 return Ok(());
10468 }
10469
10470 let mut new_selections = self.selections.all::<usize>(cx);
10471
10472 let buffer = &display_map.buffer_snapshot;
10473 let query_matches = select_next_state
10474 .query
10475 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10476
10477 for query_match in query_matches {
10478 let query_match = query_match.unwrap(); // can only fail due to I/O
10479 let offset_range = query_match.start()..query_match.end();
10480 let display_range = offset_range.start.to_display_point(&display_map)
10481 ..offset_range.end.to_display_point(&display_map);
10482
10483 if !select_next_state.wordwise
10484 || (!movement::is_inside_word(&display_map, display_range.start)
10485 && !movement::is_inside_word(&display_map, display_range.end))
10486 {
10487 self.selections.change_with(cx, |selections| {
10488 new_selections.push(Selection {
10489 id: selections.new_selection_id(),
10490 start: offset_range.start,
10491 end: offset_range.end,
10492 reversed: false,
10493 goal: SelectionGoal::None,
10494 });
10495 });
10496 }
10497 }
10498
10499 new_selections.sort_by_key(|selection| selection.start);
10500 let mut ix = 0;
10501 while ix + 1 < new_selections.len() {
10502 let current_selection = &new_selections[ix];
10503 let next_selection = &new_selections[ix + 1];
10504 if current_selection.range().overlaps(&next_selection.range()) {
10505 if current_selection.id < next_selection.id {
10506 new_selections.remove(ix + 1);
10507 } else {
10508 new_selections.remove(ix);
10509 }
10510 } else {
10511 ix += 1;
10512 }
10513 }
10514
10515 let reversed = self.selections.oldest::<usize>(cx).reversed;
10516
10517 for selection in new_selections.iter_mut() {
10518 selection.reversed = reversed;
10519 }
10520
10521 select_next_state.done = true;
10522 self.unfold_ranges(
10523 &new_selections
10524 .iter()
10525 .map(|selection| selection.range())
10526 .collect::<Vec<_>>(),
10527 false,
10528 false,
10529 cx,
10530 );
10531 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10532 selections.select(new_selections)
10533 });
10534
10535 Ok(())
10536 }
10537
10538 pub fn select_next(
10539 &mut self,
10540 action: &SelectNext,
10541 window: &mut Window,
10542 cx: &mut Context<Self>,
10543 ) -> Result<()> {
10544 self.push_to_selection_history();
10545 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10546 self.select_next_match_internal(
10547 &display_map,
10548 action.replace_newest,
10549 Some(Autoscroll::newest()),
10550 window,
10551 cx,
10552 )?;
10553 Ok(())
10554 }
10555
10556 pub fn select_previous(
10557 &mut self,
10558 action: &SelectPrevious,
10559 window: &mut Window,
10560 cx: &mut Context<Self>,
10561 ) -> Result<()> {
10562 self.push_to_selection_history();
10563 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10564 let buffer = &display_map.buffer_snapshot;
10565 let mut selections = self.selections.all::<usize>(cx);
10566 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10567 let query = &select_prev_state.query;
10568 if !select_prev_state.done {
10569 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10570 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10571 let mut next_selected_range = None;
10572 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10573 let bytes_before_last_selection =
10574 buffer.reversed_bytes_in_range(0..last_selection.start);
10575 let bytes_after_first_selection =
10576 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10577 let query_matches = query
10578 .stream_find_iter(bytes_before_last_selection)
10579 .map(|result| (last_selection.start, result))
10580 .chain(
10581 query
10582 .stream_find_iter(bytes_after_first_selection)
10583 .map(|result| (buffer.len(), result)),
10584 );
10585 for (end_offset, query_match) in query_matches {
10586 let query_match = query_match.unwrap(); // can only fail due to I/O
10587 let offset_range =
10588 end_offset - query_match.end()..end_offset - query_match.start();
10589 let display_range = offset_range.start.to_display_point(&display_map)
10590 ..offset_range.end.to_display_point(&display_map);
10591
10592 if !select_prev_state.wordwise
10593 || (!movement::is_inside_word(&display_map, display_range.start)
10594 && !movement::is_inside_word(&display_map, display_range.end))
10595 {
10596 next_selected_range = Some(offset_range);
10597 break;
10598 }
10599 }
10600
10601 if let Some(next_selected_range) = next_selected_range {
10602 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10603 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10604 if action.replace_newest {
10605 s.delete(s.newest_anchor().id);
10606 }
10607 s.insert_range(next_selected_range);
10608 });
10609 } else {
10610 select_prev_state.done = true;
10611 }
10612 }
10613
10614 self.select_prev_state = Some(select_prev_state);
10615 } else {
10616 let mut only_carets = true;
10617 let mut same_text_selected = true;
10618 let mut selected_text = None;
10619
10620 let mut selections_iter = selections.iter().peekable();
10621 while let Some(selection) = selections_iter.next() {
10622 if selection.start != selection.end {
10623 only_carets = false;
10624 }
10625
10626 if same_text_selected {
10627 if selected_text.is_none() {
10628 selected_text =
10629 Some(buffer.text_for_range(selection.range()).collect::<String>());
10630 }
10631
10632 if let Some(next_selection) = selections_iter.peek() {
10633 if next_selection.range().len() == selection.range().len() {
10634 let next_selected_text = buffer
10635 .text_for_range(next_selection.range())
10636 .collect::<String>();
10637 if Some(next_selected_text) != selected_text {
10638 same_text_selected = false;
10639 selected_text = None;
10640 }
10641 } else {
10642 same_text_selected = false;
10643 selected_text = None;
10644 }
10645 }
10646 }
10647 }
10648
10649 if only_carets {
10650 for selection in &mut selections {
10651 let word_range = movement::surrounding_word(
10652 &display_map,
10653 selection.start.to_display_point(&display_map),
10654 );
10655 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10656 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10657 selection.goal = SelectionGoal::None;
10658 selection.reversed = false;
10659 }
10660 if selections.len() == 1 {
10661 let selection = selections
10662 .last()
10663 .expect("ensured that there's only one selection");
10664 let query = buffer
10665 .text_for_range(selection.start..selection.end)
10666 .collect::<String>();
10667 let is_empty = query.is_empty();
10668 let select_state = SelectNextState {
10669 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10670 wordwise: true,
10671 done: is_empty,
10672 };
10673 self.select_prev_state = Some(select_state);
10674 } else {
10675 self.select_prev_state = None;
10676 }
10677
10678 self.unfold_ranges(
10679 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10680 false,
10681 true,
10682 cx,
10683 );
10684 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10685 s.select(selections);
10686 });
10687 } else if let Some(selected_text) = selected_text {
10688 self.select_prev_state = Some(SelectNextState {
10689 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10690 wordwise: false,
10691 done: false,
10692 });
10693 self.select_previous(action, window, cx)?;
10694 }
10695 }
10696 Ok(())
10697 }
10698
10699 pub fn toggle_comments(
10700 &mut self,
10701 action: &ToggleComments,
10702 window: &mut Window,
10703 cx: &mut Context<Self>,
10704 ) {
10705 if self.read_only(cx) {
10706 return;
10707 }
10708 let text_layout_details = &self.text_layout_details(window);
10709 self.transact(window, cx, |this, window, cx| {
10710 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10711 let mut edits = Vec::new();
10712 let mut selection_edit_ranges = Vec::new();
10713 let mut last_toggled_row = None;
10714 let snapshot = this.buffer.read(cx).read(cx);
10715 let empty_str: Arc<str> = Arc::default();
10716 let mut suffixes_inserted = Vec::new();
10717 let ignore_indent = action.ignore_indent;
10718
10719 fn comment_prefix_range(
10720 snapshot: &MultiBufferSnapshot,
10721 row: MultiBufferRow,
10722 comment_prefix: &str,
10723 comment_prefix_whitespace: &str,
10724 ignore_indent: bool,
10725 ) -> Range<Point> {
10726 let indent_size = if ignore_indent {
10727 0
10728 } else {
10729 snapshot.indent_size_for_line(row).len
10730 };
10731
10732 let start = Point::new(row.0, indent_size);
10733
10734 let mut line_bytes = snapshot
10735 .bytes_in_range(start..snapshot.max_point())
10736 .flatten()
10737 .copied();
10738
10739 // If this line currently begins with the line comment prefix, then record
10740 // the range containing the prefix.
10741 if line_bytes
10742 .by_ref()
10743 .take(comment_prefix.len())
10744 .eq(comment_prefix.bytes())
10745 {
10746 // Include any whitespace that matches the comment prefix.
10747 let matching_whitespace_len = line_bytes
10748 .zip(comment_prefix_whitespace.bytes())
10749 .take_while(|(a, b)| a == b)
10750 .count() as u32;
10751 let end = Point::new(
10752 start.row,
10753 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10754 );
10755 start..end
10756 } else {
10757 start..start
10758 }
10759 }
10760
10761 fn comment_suffix_range(
10762 snapshot: &MultiBufferSnapshot,
10763 row: MultiBufferRow,
10764 comment_suffix: &str,
10765 comment_suffix_has_leading_space: bool,
10766 ) -> Range<Point> {
10767 let end = Point::new(row.0, snapshot.line_len(row));
10768 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10769
10770 let mut line_end_bytes = snapshot
10771 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10772 .flatten()
10773 .copied();
10774
10775 let leading_space_len = if suffix_start_column > 0
10776 && line_end_bytes.next() == Some(b' ')
10777 && comment_suffix_has_leading_space
10778 {
10779 1
10780 } else {
10781 0
10782 };
10783
10784 // If this line currently begins with the line comment prefix, then record
10785 // the range containing the prefix.
10786 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10787 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10788 start..end
10789 } else {
10790 end..end
10791 }
10792 }
10793
10794 // TODO: Handle selections that cross excerpts
10795 for selection in &mut selections {
10796 let start_column = snapshot
10797 .indent_size_for_line(MultiBufferRow(selection.start.row))
10798 .len;
10799 let language = if let Some(language) =
10800 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10801 {
10802 language
10803 } else {
10804 continue;
10805 };
10806
10807 selection_edit_ranges.clear();
10808
10809 // If multiple selections contain a given row, avoid processing that
10810 // row more than once.
10811 let mut start_row = MultiBufferRow(selection.start.row);
10812 if last_toggled_row == Some(start_row) {
10813 start_row = start_row.next_row();
10814 }
10815 let end_row =
10816 if selection.end.row > selection.start.row && selection.end.column == 0 {
10817 MultiBufferRow(selection.end.row - 1)
10818 } else {
10819 MultiBufferRow(selection.end.row)
10820 };
10821 last_toggled_row = Some(end_row);
10822
10823 if start_row > end_row {
10824 continue;
10825 }
10826
10827 // If the language has line comments, toggle those.
10828 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10829
10830 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10831 if ignore_indent {
10832 full_comment_prefixes = full_comment_prefixes
10833 .into_iter()
10834 .map(|s| Arc::from(s.trim_end()))
10835 .collect();
10836 }
10837
10838 if !full_comment_prefixes.is_empty() {
10839 let first_prefix = full_comment_prefixes
10840 .first()
10841 .expect("prefixes is non-empty");
10842 let prefix_trimmed_lengths = full_comment_prefixes
10843 .iter()
10844 .map(|p| p.trim_end_matches(' ').len())
10845 .collect::<SmallVec<[usize; 4]>>();
10846
10847 let mut all_selection_lines_are_comments = true;
10848
10849 for row in start_row.0..=end_row.0 {
10850 let row = MultiBufferRow(row);
10851 if start_row < end_row && snapshot.is_line_blank(row) {
10852 continue;
10853 }
10854
10855 let prefix_range = full_comment_prefixes
10856 .iter()
10857 .zip(prefix_trimmed_lengths.iter().copied())
10858 .map(|(prefix, trimmed_prefix_len)| {
10859 comment_prefix_range(
10860 snapshot.deref(),
10861 row,
10862 &prefix[..trimmed_prefix_len],
10863 &prefix[trimmed_prefix_len..],
10864 ignore_indent,
10865 )
10866 })
10867 .max_by_key(|range| range.end.column - range.start.column)
10868 .expect("prefixes is non-empty");
10869
10870 if prefix_range.is_empty() {
10871 all_selection_lines_are_comments = false;
10872 }
10873
10874 selection_edit_ranges.push(prefix_range);
10875 }
10876
10877 if all_selection_lines_are_comments {
10878 edits.extend(
10879 selection_edit_ranges
10880 .iter()
10881 .cloned()
10882 .map(|range| (range, empty_str.clone())),
10883 );
10884 } else {
10885 let min_column = selection_edit_ranges
10886 .iter()
10887 .map(|range| range.start.column)
10888 .min()
10889 .unwrap_or(0);
10890 edits.extend(selection_edit_ranges.iter().map(|range| {
10891 let position = Point::new(range.start.row, min_column);
10892 (position..position, first_prefix.clone())
10893 }));
10894 }
10895 } else if let Some((full_comment_prefix, comment_suffix)) =
10896 language.block_comment_delimiters()
10897 {
10898 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10899 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10900 let prefix_range = comment_prefix_range(
10901 snapshot.deref(),
10902 start_row,
10903 comment_prefix,
10904 comment_prefix_whitespace,
10905 ignore_indent,
10906 );
10907 let suffix_range = comment_suffix_range(
10908 snapshot.deref(),
10909 end_row,
10910 comment_suffix.trim_start_matches(' '),
10911 comment_suffix.starts_with(' '),
10912 );
10913
10914 if prefix_range.is_empty() || suffix_range.is_empty() {
10915 edits.push((
10916 prefix_range.start..prefix_range.start,
10917 full_comment_prefix.clone(),
10918 ));
10919 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10920 suffixes_inserted.push((end_row, comment_suffix.len()));
10921 } else {
10922 edits.push((prefix_range, empty_str.clone()));
10923 edits.push((suffix_range, empty_str.clone()));
10924 }
10925 } else {
10926 continue;
10927 }
10928 }
10929
10930 drop(snapshot);
10931 this.buffer.update(cx, |buffer, cx| {
10932 buffer.edit(edits, None, cx);
10933 });
10934
10935 // Adjust selections so that they end before any comment suffixes that
10936 // were inserted.
10937 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10938 let mut selections = this.selections.all::<Point>(cx);
10939 let snapshot = this.buffer.read(cx).read(cx);
10940 for selection in &mut selections {
10941 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10942 match row.cmp(&MultiBufferRow(selection.end.row)) {
10943 Ordering::Less => {
10944 suffixes_inserted.next();
10945 continue;
10946 }
10947 Ordering::Greater => break,
10948 Ordering::Equal => {
10949 if selection.end.column == snapshot.line_len(row) {
10950 if selection.is_empty() {
10951 selection.start.column -= suffix_len as u32;
10952 }
10953 selection.end.column -= suffix_len as u32;
10954 }
10955 break;
10956 }
10957 }
10958 }
10959 }
10960
10961 drop(snapshot);
10962 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10963 s.select(selections)
10964 });
10965
10966 let selections = this.selections.all::<Point>(cx);
10967 let selections_on_single_row = selections.windows(2).all(|selections| {
10968 selections[0].start.row == selections[1].start.row
10969 && selections[0].end.row == selections[1].end.row
10970 && selections[0].start.row == selections[0].end.row
10971 });
10972 let selections_selecting = selections
10973 .iter()
10974 .any(|selection| selection.start != selection.end);
10975 let advance_downwards = action.advance_downwards
10976 && selections_on_single_row
10977 && !selections_selecting
10978 && !matches!(this.mode, EditorMode::SingleLine { .. });
10979
10980 if advance_downwards {
10981 let snapshot = this.buffer.read(cx).snapshot(cx);
10982
10983 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10984 s.move_cursors_with(|display_snapshot, display_point, _| {
10985 let mut point = display_point.to_point(display_snapshot);
10986 point.row += 1;
10987 point = snapshot.clip_point(point, Bias::Left);
10988 let display_point = point.to_display_point(display_snapshot);
10989 let goal = SelectionGoal::HorizontalPosition(
10990 display_snapshot
10991 .x_for_display_point(display_point, text_layout_details)
10992 .into(),
10993 );
10994 (display_point, goal)
10995 })
10996 });
10997 }
10998 });
10999 }
11000
11001 pub fn select_enclosing_symbol(
11002 &mut self,
11003 _: &SelectEnclosingSymbol,
11004 window: &mut Window,
11005 cx: &mut Context<Self>,
11006 ) {
11007 let buffer = self.buffer.read(cx).snapshot(cx);
11008 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11009
11010 fn update_selection(
11011 selection: &Selection<usize>,
11012 buffer_snap: &MultiBufferSnapshot,
11013 ) -> Option<Selection<usize>> {
11014 let cursor = selection.head();
11015 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11016 for symbol in symbols.iter().rev() {
11017 let start = symbol.range.start.to_offset(buffer_snap);
11018 let end = symbol.range.end.to_offset(buffer_snap);
11019 let new_range = start..end;
11020 if start < selection.start || end > selection.end {
11021 return Some(Selection {
11022 id: selection.id,
11023 start: new_range.start,
11024 end: new_range.end,
11025 goal: SelectionGoal::None,
11026 reversed: selection.reversed,
11027 });
11028 }
11029 }
11030 None
11031 }
11032
11033 let mut selected_larger_symbol = false;
11034 let new_selections = old_selections
11035 .iter()
11036 .map(|selection| match update_selection(selection, &buffer) {
11037 Some(new_selection) => {
11038 if new_selection.range() != selection.range() {
11039 selected_larger_symbol = true;
11040 }
11041 new_selection
11042 }
11043 None => selection.clone(),
11044 })
11045 .collect::<Vec<_>>();
11046
11047 if selected_larger_symbol {
11048 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11049 s.select(new_selections);
11050 });
11051 }
11052 }
11053
11054 pub fn select_larger_syntax_node(
11055 &mut self,
11056 _: &SelectLargerSyntaxNode,
11057 window: &mut Window,
11058 cx: &mut Context<Self>,
11059 ) {
11060 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11061 let buffer = self.buffer.read(cx).snapshot(cx);
11062 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11063
11064 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11065 let mut selected_larger_node = false;
11066 let new_selections = old_selections
11067 .iter()
11068 .map(|selection| {
11069 let old_range = selection.start..selection.end;
11070 let mut new_range = old_range.clone();
11071 let mut new_node = None;
11072 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11073 {
11074 new_node = Some(node);
11075 new_range = match containing_range {
11076 MultiOrSingleBufferOffsetRange::Single(_) => break,
11077 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11078 };
11079 if !display_map.intersects_fold(new_range.start)
11080 && !display_map.intersects_fold(new_range.end)
11081 {
11082 break;
11083 }
11084 }
11085
11086 if let Some(node) = new_node {
11087 // Log the ancestor, to support using this action as a way to explore TreeSitter
11088 // nodes. Parent and grandparent are also logged because this operation will not
11089 // visit nodes that have the same range as their parent.
11090 log::info!("Node: {node:?}");
11091 let parent = node.parent();
11092 log::info!("Parent: {parent:?}");
11093 let grandparent = parent.and_then(|x| x.parent());
11094 log::info!("Grandparent: {grandparent:?}");
11095 }
11096
11097 selected_larger_node |= new_range != old_range;
11098 Selection {
11099 id: selection.id,
11100 start: new_range.start,
11101 end: new_range.end,
11102 goal: SelectionGoal::None,
11103 reversed: selection.reversed,
11104 }
11105 })
11106 .collect::<Vec<_>>();
11107
11108 if selected_larger_node {
11109 stack.push(old_selections);
11110 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11111 s.select(new_selections);
11112 });
11113 }
11114 self.select_larger_syntax_node_stack = stack;
11115 }
11116
11117 pub fn select_smaller_syntax_node(
11118 &mut self,
11119 _: &SelectSmallerSyntaxNode,
11120 window: &mut Window,
11121 cx: &mut Context<Self>,
11122 ) {
11123 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11124 if let Some(selections) = stack.pop() {
11125 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11126 s.select(selections.to_vec());
11127 });
11128 }
11129 self.select_larger_syntax_node_stack = stack;
11130 }
11131
11132 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11133 if !EditorSettings::get_global(cx).gutter.runnables {
11134 self.clear_tasks();
11135 return Task::ready(());
11136 }
11137 let project = self.project.as_ref().map(Entity::downgrade);
11138 cx.spawn_in(window, |this, mut cx| async move {
11139 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11140 let Some(project) = project.and_then(|p| p.upgrade()) else {
11141 return;
11142 };
11143 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11144 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11145 }) else {
11146 return;
11147 };
11148
11149 let hide_runnables = project
11150 .update(&mut cx, |project, cx| {
11151 // Do not display any test indicators in non-dev server remote projects.
11152 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11153 })
11154 .unwrap_or(true);
11155 if hide_runnables {
11156 return;
11157 }
11158 let new_rows =
11159 cx.background_spawn({
11160 let snapshot = display_snapshot.clone();
11161 async move {
11162 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11163 }
11164 })
11165 .await;
11166
11167 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11168 this.update(&mut cx, |this, _| {
11169 this.clear_tasks();
11170 for (key, value) in rows {
11171 this.insert_tasks(key, value);
11172 }
11173 })
11174 .ok();
11175 })
11176 }
11177 fn fetch_runnable_ranges(
11178 snapshot: &DisplaySnapshot,
11179 range: Range<Anchor>,
11180 ) -> Vec<language::RunnableRange> {
11181 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11182 }
11183
11184 fn runnable_rows(
11185 project: Entity<Project>,
11186 snapshot: DisplaySnapshot,
11187 runnable_ranges: Vec<RunnableRange>,
11188 mut cx: AsyncWindowContext,
11189 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11190 runnable_ranges
11191 .into_iter()
11192 .filter_map(|mut runnable| {
11193 let tasks = cx
11194 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11195 .ok()?;
11196 if tasks.is_empty() {
11197 return None;
11198 }
11199
11200 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11201
11202 let row = snapshot
11203 .buffer_snapshot
11204 .buffer_line_for_row(MultiBufferRow(point.row))?
11205 .1
11206 .start
11207 .row;
11208
11209 let context_range =
11210 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11211 Some((
11212 (runnable.buffer_id, row),
11213 RunnableTasks {
11214 templates: tasks,
11215 offset: snapshot
11216 .buffer_snapshot
11217 .anchor_before(runnable.run_range.start),
11218 context_range,
11219 column: point.column,
11220 extra_variables: runnable.extra_captures,
11221 },
11222 ))
11223 })
11224 .collect()
11225 }
11226
11227 fn templates_with_tags(
11228 project: &Entity<Project>,
11229 runnable: &mut Runnable,
11230 cx: &mut App,
11231 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11232 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11233 let (worktree_id, file) = project
11234 .buffer_for_id(runnable.buffer, cx)
11235 .and_then(|buffer| buffer.read(cx).file())
11236 .map(|file| (file.worktree_id(cx), file.clone()))
11237 .unzip();
11238
11239 (
11240 project.task_store().read(cx).task_inventory().cloned(),
11241 worktree_id,
11242 file,
11243 )
11244 });
11245
11246 let tags = mem::take(&mut runnable.tags);
11247 let mut tags: Vec<_> = tags
11248 .into_iter()
11249 .flat_map(|tag| {
11250 let tag = tag.0.clone();
11251 inventory
11252 .as_ref()
11253 .into_iter()
11254 .flat_map(|inventory| {
11255 inventory.read(cx).list_tasks(
11256 file.clone(),
11257 Some(runnable.language.clone()),
11258 worktree_id,
11259 cx,
11260 )
11261 })
11262 .filter(move |(_, template)| {
11263 template.tags.iter().any(|source_tag| source_tag == &tag)
11264 })
11265 })
11266 .sorted_by_key(|(kind, _)| kind.to_owned())
11267 .collect();
11268 if let Some((leading_tag_source, _)) = tags.first() {
11269 // Strongest source wins; if we have worktree tag binding, prefer that to
11270 // global and language bindings;
11271 // if we have a global binding, prefer that to language binding.
11272 let first_mismatch = tags
11273 .iter()
11274 .position(|(tag_source, _)| tag_source != leading_tag_source);
11275 if let Some(index) = first_mismatch {
11276 tags.truncate(index);
11277 }
11278 }
11279
11280 tags
11281 }
11282
11283 pub fn move_to_enclosing_bracket(
11284 &mut self,
11285 _: &MoveToEnclosingBracket,
11286 window: &mut Window,
11287 cx: &mut Context<Self>,
11288 ) {
11289 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11290 s.move_offsets_with(|snapshot, selection| {
11291 let Some(enclosing_bracket_ranges) =
11292 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11293 else {
11294 return;
11295 };
11296
11297 let mut best_length = usize::MAX;
11298 let mut best_inside = false;
11299 let mut best_in_bracket_range = false;
11300 let mut best_destination = None;
11301 for (open, close) in enclosing_bracket_ranges {
11302 let close = close.to_inclusive();
11303 let length = close.end() - open.start;
11304 let inside = selection.start >= open.end && selection.end <= *close.start();
11305 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11306 || close.contains(&selection.head());
11307
11308 // If best is next to a bracket and current isn't, skip
11309 if !in_bracket_range && best_in_bracket_range {
11310 continue;
11311 }
11312
11313 // Prefer smaller lengths unless best is inside and current isn't
11314 if length > best_length && (best_inside || !inside) {
11315 continue;
11316 }
11317
11318 best_length = length;
11319 best_inside = inside;
11320 best_in_bracket_range = in_bracket_range;
11321 best_destination = Some(
11322 if close.contains(&selection.start) && close.contains(&selection.end) {
11323 if inside {
11324 open.end
11325 } else {
11326 open.start
11327 }
11328 } else if inside {
11329 *close.start()
11330 } else {
11331 *close.end()
11332 },
11333 );
11334 }
11335
11336 if let Some(destination) = best_destination {
11337 selection.collapse_to(destination, SelectionGoal::None);
11338 }
11339 })
11340 });
11341 }
11342
11343 pub fn undo_selection(
11344 &mut self,
11345 _: &UndoSelection,
11346 window: &mut Window,
11347 cx: &mut Context<Self>,
11348 ) {
11349 self.end_selection(window, cx);
11350 self.selection_history.mode = SelectionHistoryMode::Undoing;
11351 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11352 self.change_selections(None, window, cx, |s| {
11353 s.select_anchors(entry.selections.to_vec())
11354 });
11355 self.select_next_state = entry.select_next_state;
11356 self.select_prev_state = entry.select_prev_state;
11357 self.add_selections_state = entry.add_selections_state;
11358 self.request_autoscroll(Autoscroll::newest(), cx);
11359 }
11360 self.selection_history.mode = SelectionHistoryMode::Normal;
11361 }
11362
11363 pub fn redo_selection(
11364 &mut self,
11365 _: &RedoSelection,
11366 window: &mut Window,
11367 cx: &mut Context<Self>,
11368 ) {
11369 self.end_selection(window, cx);
11370 self.selection_history.mode = SelectionHistoryMode::Redoing;
11371 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11372 self.change_selections(None, window, cx, |s| {
11373 s.select_anchors(entry.selections.to_vec())
11374 });
11375 self.select_next_state = entry.select_next_state;
11376 self.select_prev_state = entry.select_prev_state;
11377 self.add_selections_state = entry.add_selections_state;
11378 self.request_autoscroll(Autoscroll::newest(), cx);
11379 }
11380 self.selection_history.mode = SelectionHistoryMode::Normal;
11381 }
11382
11383 pub fn expand_excerpts(
11384 &mut self,
11385 action: &ExpandExcerpts,
11386 _: &mut Window,
11387 cx: &mut Context<Self>,
11388 ) {
11389 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11390 }
11391
11392 pub fn expand_excerpts_down(
11393 &mut self,
11394 action: &ExpandExcerptsDown,
11395 _: &mut Window,
11396 cx: &mut Context<Self>,
11397 ) {
11398 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11399 }
11400
11401 pub fn expand_excerpts_up(
11402 &mut self,
11403 action: &ExpandExcerptsUp,
11404 _: &mut Window,
11405 cx: &mut Context<Self>,
11406 ) {
11407 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11408 }
11409
11410 pub fn expand_excerpts_for_direction(
11411 &mut self,
11412 lines: u32,
11413 direction: ExpandExcerptDirection,
11414
11415 cx: &mut Context<Self>,
11416 ) {
11417 let selections = self.selections.disjoint_anchors();
11418
11419 let lines = if lines == 0 {
11420 EditorSettings::get_global(cx).expand_excerpt_lines
11421 } else {
11422 lines
11423 };
11424
11425 self.buffer.update(cx, |buffer, cx| {
11426 let snapshot = buffer.snapshot(cx);
11427 let mut excerpt_ids = selections
11428 .iter()
11429 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11430 .collect::<Vec<_>>();
11431 excerpt_ids.sort();
11432 excerpt_ids.dedup();
11433 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11434 })
11435 }
11436
11437 pub fn expand_excerpt(
11438 &mut self,
11439 excerpt: ExcerptId,
11440 direction: ExpandExcerptDirection,
11441 cx: &mut Context<Self>,
11442 ) {
11443 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11444 self.buffer.update(cx, |buffer, cx| {
11445 buffer.expand_excerpts([excerpt], lines, direction, cx)
11446 })
11447 }
11448
11449 pub fn go_to_singleton_buffer_point(
11450 &mut self,
11451 point: Point,
11452 window: &mut Window,
11453 cx: &mut Context<Self>,
11454 ) {
11455 self.go_to_singleton_buffer_range(point..point, window, cx);
11456 }
11457
11458 pub fn go_to_singleton_buffer_range(
11459 &mut self,
11460 range: Range<Point>,
11461 window: &mut Window,
11462 cx: &mut Context<Self>,
11463 ) {
11464 let multibuffer = self.buffer().read(cx);
11465 let Some(buffer) = multibuffer.as_singleton() else {
11466 return;
11467 };
11468 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11469 return;
11470 };
11471 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11472 return;
11473 };
11474 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11475 s.select_anchor_ranges([start..end])
11476 });
11477 }
11478
11479 fn go_to_diagnostic(
11480 &mut self,
11481 _: &GoToDiagnostic,
11482 window: &mut Window,
11483 cx: &mut Context<Self>,
11484 ) {
11485 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11486 }
11487
11488 fn go_to_prev_diagnostic(
11489 &mut self,
11490 _: &GoToPreviousDiagnostic,
11491 window: &mut Window,
11492 cx: &mut Context<Self>,
11493 ) {
11494 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11495 }
11496
11497 pub fn go_to_diagnostic_impl(
11498 &mut self,
11499 direction: Direction,
11500 window: &mut Window,
11501 cx: &mut Context<Self>,
11502 ) {
11503 let buffer = self.buffer.read(cx).snapshot(cx);
11504 let selection = self.selections.newest::<usize>(cx);
11505
11506 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11507 if direction == Direction::Next {
11508 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11509 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11510 return;
11511 };
11512 self.activate_diagnostics(
11513 buffer_id,
11514 popover.local_diagnostic.diagnostic.group_id,
11515 window,
11516 cx,
11517 );
11518 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11519 let primary_range_start = active_diagnostics.primary_range.start;
11520 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11521 let mut new_selection = s.newest_anchor().clone();
11522 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11523 s.select_anchors(vec![new_selection.clone()]);
11524 });
11525 self.refresh_inline_completion(false, true, window, cx);
11526 }
11527 return;
11528 }
11529 }
11530
11531 let active_group_id = self
11532 .active_diagnostics
11533 .as_ref()
11534 .map(|active_group| active_group.group_id);
11535 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11536 active_diagnostics
11537 .primary_range
11538 .to_offset(&buffer)
11539 .to_inclusive()
11540 });
11541 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11542 if active_primary_range.contains(&selection.head()) {
11543 *active_primary_range.start()
11544 } else {
11545 selection.head()
11546 }
11547 } else {
11548 selection.head()
11549 };
11550
11551 let snapshot = self.snapshot(window, cx);
11552 let primary_diagnostics_before = buffer
11553 .diagnostics_in_range::<usize>(0..search_start)
11554 .filter(|entry| entry.diagnostic.is_primary)
11555 .filter(|entry| entry.range.start != entry.range.end)
11556 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11557 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11558 .collect::<Vec<_>>();
11559 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11560 primary_diagnostics_before
11561 .iter()
11562 .position(|entry| entry.diagnostic.group_id == active_group_id)
11563 });
11564
11565 let primary_diagnostics_after = buffer
11566 .diagnostics_in_range::<usize>(search_start..buffer.len())
11567 .filter(|entry| entry.diagnostic.is_primary)
11568 .filter(|entry| entry.range.start != entry.range.end)
11569 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11570 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11571 .collect::<Vec<_>>();
11572 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11573 primary_diagnostics_after
11574 .iter()
11575 .enumerate()
11576 .rev()
11577 .find_map(|(i, entry)| {
11578 if entry.diagnostic.group_id == active_group_id {
11579 Some(i)
11580 } else {
11581 None
11582 }
11583 })
11584 });
11585
11586 let next_primary_diagnostic = match direction {
11587 Direction::Prev => primary_diagnostics_before
11588 .iter()
11589 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11590 .rev()
11591 .next(),
11592 Direction::Next => primary_diagnostics_after
11593 .iter()
11594 .skip(
11595 last_same_group_diagnostic_after
11596 .map(|index| index + 1)
11597 .unwrap_or(0),
11598 )
11599 .next(),
11600 };
11601
11602 // Cycle around to the start of the buffer, potentially moving back to the start of
11603 // the currently active diagnostic.
11604 let cycle_around = || match direction {
11605 Direction::Prev => primary_diagnostics_after
11606 .iter()
11607 .rev()
11608 .chain(primary_diagnostics_before.iter().rev())
11609 .next(),
11610 Direction::Next => primary_diagnostics_before
11611 .iter()
11612 .chain(primary_diagnostics_after.iter())
11613 .next(),
11614 };
11615
11616 if let Some((primary_range, group_id)) = next_primary_diagnostic
11617 .or_else(cycle_around)
11618 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11619 {
11620 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11621 return;
11622 };
11623 self.activate_diagnostics(buffer_id, group_id, window, cx);
11624 if self.active_diagnostics.is_some() {
11625 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11626 s.select(vec![Selection {
11627 id: selection.id,
11628 start: primary_range.start,
11629 end: primary_range.start,
11630 reversed: false,
11631 goal: SelectionGoal::None,
11632 }]);
11633 });
11634 self.refresh_inline_completion(false, true, window, cx);
11635 }
11636 }
11637 }
11638
11639 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11640 let snapshot = self.snapshot(window, cx);
11641 let selection = self.selections.newest::<Point>(cx);
11642 self.go_to_hunk_after_or_before_position(
11643 &snapshot,
11644 selection.head(),
11645 Direction::Next,
11646 window,
11647 cx,
11648 );
11649 }
11650
11651 fn go_to_hunk_after_or_before_position(
11652 &mut self,
11653 snapshot: &EditorSnapshot,
11654 position: Point,
11655 direction: Direction,
11656 window: &mut Window,
11657 cx: &mut Context<Editor>,
11658 ) {
11659 let row = if direction == Direction::Next {
11660 self.hunk_after_position(snapshot, position)
11661 .map(|hunk| hunk.row_range.start)
11662 } else {
11663 self.hunk_before_position(snapshot, position)
11664 };
11665
11666 if let Some(row) = row {
11667 let destination = Point::new(row.0, 0);
11668 let autoscroll = Autoscroll::center();
11669
11670 self.unfold_ranges(&[destination..destination], false, false, cx);
11671 self.change_selections(Some(autoscroll), window, cx, |s| {
11672 s.select_ranges([destination..destination]);
11673 });
11674 }
11675 }
11676
11677 fn hunk_after_position(
11678 &mut self,
11679 snapshot: &EditorSnapshot,
11680 position: Point,
11681 ) -> Option<MultiBufferDiffHunk> {
11682 snapshot
11683 .buffer_snapshot
11684 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11685 .find(|hunk| hunk.row_range.start.0 > position.row)
11686 .or_else(|| {
11687 snapshot
11688 .buffer_snapshot
11689 .diff_hunks_in_range(Point::zero()..position)
11690 .find(|hunk| hunk.row_range.end.0 < position.row)
11691 })
11692 }
11693
11694 fn go_to_prev_hunk(
11695 &mut self,
11696 _: &GoToPreviousHunk,
11697 window: &mut Window,
11698 cx: &mut Context<Self>,
11699 ) {
11700 let snapshot = self.snapshot(window, cx);
11701 let selection = self.selections.newest::<Point>(cx);
11702 self.go_to_hunk_after_or_before_position(
11703 &snapshot,
11704 selection.head(),
11705 Direction::Prev,
11706 window,
11707 cx,
11708 );
11709 }
11710
11711 fn hunk_before_position(
11712 &mut self,
11713 snapshot: &EditorSnapshot,
11714 position: Point,
11715 ) -> Option<MultiBufferRow> {
11716 snapshot
11717 .buffer_snapshot
11718 .diff_hunk_before(position)
11719 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11720 }
11721
11722 pub fn go_to_definition(
11723 &mut self,
11724 _: &GoToDefinition,
11725 window: &mut Window,
11726 cx: &mut Context<Self>,
11727 ) -> Task<Result<Navigated>> {
11728 let definition =
11729 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11730 cx.spawn_in(window, |editor, mut cx| async move {
11731 if definition.await? == Navigated::Yes {
11732 return Ok(Navigated::Yes);
11733 }
11734 match editor.update_in(&mut cx, |editor, window, cx| {
11735 editor.find_all_references(&FindAllReferences, window, cx)
11736 })? {
11737 Some(references) => references.await,
11738 None => Ok(Navigated::No),
11739 }
11740 })
11741 }
11742
11743 pub fn go_to_declaration(
11744 &mut self,
11745 _: &GoToDeclaration,
11746 window: &mut Window,
11747 cx: &mut Context<Self>,
11748 ) -> Task<Result<Navigated>> {
11749 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11750 }
11751
11752 pub fn go_to_declaration_split(
11753 &mut self,
11754 _: &GoToDeclaration,
11755 window: &mut Window,
11756 cx: &mut Context<Self>,
11757 ) -> Task<Result<Navigated>> {
11758 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11759 }
11760
11761 pub fn go_to_implementation(
11762 &mut self,
11763 _: &GoToImplementation,
11764 window: &mut Window,
11765 cx: &mut Context<Self>,
11766 ) -> Task<Result<Navigated>> {
11767 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11768 }
11769
11770 pub fn go_to_implementation_split(
11771 &mut self,
11772 _: &GoToImplementationSplit,
11773 window: &mut Window,
11774 cx: &mut Context<Self>,
11775 ) -> Task<Result<Navigated>> {
11776 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11777 }
11778
11779 pub fn go_to_type_definition(
11780 &mut self,
11781 _: &GoToTypeDefinition,
11782 window: &mut Window,
11783 cx: &mut Context<Self>,
11784 ) -> Task<Result<Navigated>> {
11785 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11786 }
11787
11788 pub fn go_to_definition_split(
11789 &mut self,
11790 _: &GoToDefinitionSplit,
11791 window: &mut Window,
11792 cx: &mut Context<Self>,
11793 ) -> Task<Result<Navigated>> {
11794 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11795 }
11796
11797 pub fn go_to_type_definition_split(
11798 &mut self,
11799 _: &GoToTypeDefinitionSplit,
11800 window: &mut Window,
11801 cx: &mut Context<Self>,
11802 ) -> Task<Result<Navigated>> {
11803 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11804 }
11805
11806 fn go_to_definition_of_kind(
11807 &mut self,
11808 kind: GotoDefinitionKind,
11809 split: bool,
11810 window: &mut Window,
11811 cx: &mut Context<Self>,
11812 ) -> Task<Result<Navigated>> {
11813 let Some(provider) = self.semantics_provider.clone() else {
11814 return Task::ready(Ok(Navigated::No));
11815 };
11816 let head = self.selections.newest::<usize>(cx).head();
11817 let buffer = self.buffer.read(cx);
11818 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11819 text_anchor
11820 } else {
11821 return Task::ready(Ok(Navigated::No));
11822 };
11823
11824 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11825 return Task::ready(Ok(Navigated::No));
11826 };
11827
11828 cx.spawn_in(window, |editor, mut cx| async move {
11829 let definitions = definitions.await?;
11830 let navigated = editor
11831 .update_in(&mut cx, |editor, window, cx| {
11832 editor.navigate_to_hover_links(
11833 Some(kind),
11834 definitions
11835 .into_iter()
11836 .filter(|location| {
11837 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11838 })
11839 .map(HoverLink::Text)
11840 .collect::<Vec<_>>(),
11841 split,
11842 window,
11843 cx,
11844 )
11845 })?
11846 .await?;
11847 anyhow::Ok(navigated)
11848 })
11849 }
11850
11851 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11852 let selection = self.selections.newest_anchor();
11853 let head = selection.head();
11854 let tail = selection.tail();
11855
11856 let Some((buffer, start_position)) =
11857 self.buffer.read(cx).text_anchor_for_position(head, cx)
11858 else {
11859 return;
11860 };
11861
11862 let end_position = if head != tail {
11863 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11864 return;
11865 };
11866 Some(pos)
11867 } else {
11868 None
11869 };
11870
11871 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11872 let url = if let Some(end_pos) = end_position {
11873 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11874 } else {
11875 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11876 };
11877
11878 if let Some(url) = url {
11879 editor.update(&mut cx, |_, cx| {
11880 cx.open_url(&url);
11881 })
11882 } else {
11883 Ok(())
11884 }
11885 });
11886
11887 url_finder.detach();
11888 }
11889
11890 pub fn open_selected_filename(
11891 &mut self,
11892 _: &OpenSelectedFilename,
11893 window: &mut Window,
11894 cx: &mut Context<Self>,
11895 ) {
11896 let Some(workspace) = self.workspace() else {
11897 return;
11898 };
11899
11900 let position = self.selections.newest_anchor().head();
11901
11902 let Some((buffer, buffer_position)) =
11903 self.buffer.read(cx).text_anchor_for_position(position, cx)
11904 else {
11905 return;
11906 };
11907
11908 let project = self.project.clone();
11909
11910 cx.spawn_in(window, |_, mut cx| async move {
11911 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11912
11913 if let Some((_, path)) = result {
11914 workspace
11915 .update_in(&mut cx, |workspace, window, cx| {
11916 workspace.open_resolved_path(path, window, cx)
11917 })?
11918 .await?;
11919 }
11920 anyhow::Ok(())
11921 })
11922 .detach();
11923 }
11924
11925 pub(crate) fn navigate_to_hover_links(
11926 &mut self,
11927 kind: Option<GotoDefinitionKind>,
11928 mut definitions: Vec<HoverLink>,
11929 split: bool,
11930 window: &mut Window,
11931 cx: &mut Context<Editor>,
11932 ) -> Task<Result<Navigated>> {
11933 // If there is one definition, just open it directly
11934 if definitions.len() == 1 {
11935 let definition = definitions.pop().unwrap();
11936
11937 enum TargetTaskResult {
11938 Location(Option<Location>),
11939 AlreadyNavigated,
11940 }
11941
11942 let target_task = match definition {
11943 HoverLink::Text(link) => {
11944 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11945 }
11946 HoverLink::InlayHint(lsp_location, server_id) => {
11947 let computation =
11948 self.compute_target_location(lsp_location, server_id, window, cx);
11949 cx.background_spawn(async move {
11950 let location = computation.await?;
11951 Ok(TargetTaskResult::Location(location))
11952 })
11953 }
11954 HoverLink::Url(url) => {
11955 cx.open_url(&url);
11956 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11957 }
11958 HoverLink::File(path) => {
11959 if let Some(workspace) = self.workspace() {
11960 cx.spawn_in(window, |_, mut cx| async move {
11961 workspace
11962 .update_in(&mut cx, |workspace, window, cx| {
11963 workspace.open_resolved_path(path, window, cx)
11964 })?
11965 .await
11966 .map(|_| TargetTaskResult::AlreadyNavigated)
11967 })
11968 } else {
11969 Task::ready(Ok(TargetTaskResult::Location(None)))
11970 }
11971 }
11972 };
11973 cx.spawn_in(window, |editor, mut cx| async move {
11974 let target = match target_task.await.context("target resolution task")? {
11975 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11976 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11977 TargetTaskResult::Location(Some(target)) => target,
11978 };
11979
11980 editor.update_in(&mut cx, |editor, window, cx| {
11981 let Some(workspace) = editor.workspace() else {
11982 return Navigated::No;
11983 };
11984 let pane = workspace.read(cx).active_pane().clone();
11985
11986 let range = target.range.to_point(target.buffer.read(cx));
11987 let range = editor.range_for_match(&range);
11988 let range = collapse_multiline_range(range);
11989
11990 if !split
11991 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11992 {
11993 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11994 } else {
11995 window.defer(cx, move |window, cx| {
11996 let target_editor: Entity<Self> =
11997 workspace.update(cx, |workspace, cx| {
11998 let pane = if split {
11999 workspace.adjacent_pane(window, cx)
12000 } else {
12001 workspace.active_pane().clone()
12002 };
12003
12004 workspace.open_project_item(
12005 pane,
12006 target.buffer.clone(),
12007 true,
12008 true,
12009 window,
12010 cx,
12011 )
12012 });
12013 target_editor.update(cx, |target_editor, cx| {
12014 // When selecting a definition in a different buffer, disable the nav history
12015 // to avoid creating a history entry at the previous cursor location.
12016 pane.update(cx, |pane, _| pane.disable_history());
12017 target_editor.go_to_singleton_buffer_range(range, window, cx);
12018 pane.update(cx, |pane, _| pane.enable_history());
12019 });
12020 });
12021 }
12022 Navigated::Yes
12023 })
12024 })
12025 } else if !definitions.is_empty() {
12026 cx.spawn_in(window, |editor, mut cx| async move {
12027 let (title, location_tasks, workspace) = editor
12028 .update_in(&mut cx, |editor, window, cx| {
12029 let tab_kind = match kind {
12030 Some(GotoDefinitionKind::Implementation) => "Implementations",
12031 _ => "Definitions",
12032 };
12033 let title = definitions
12034 .iter()
12035 .find_map(|definition| match definition {
12036 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12037 let buffer = origin.buffer.read(cx);
12038 format!(
12039 "{} for {}",
12040 tab_kind,
12041 buffer
12042 .text_for_range(origin.range.clone())
12043 .collect::<String>()
12044 )
12045 }),
12046 HoverLink::InlayHint(_, _) => None,
12047 HoverLink::Url(_) => None,
12048 HoverLink::File(_) => None,
12049 })
12050 .unwrap_or(tab_kind.to_string());
12051 let location_tasks = definitions
12052 .into_iter()
12053 .map(|definition| match definition {
12054 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12055 HoverLink::InlayHint(lsp_location, server_id) => editor
12056 .compute_target_location(lsp_location, server_id, window, cx),
12057 HoverLink::Url(_) => Task::ready(Ok(None)),
12058 HoverLink::File(_) => Task::ready(Ok(None)),
12059 })
12060 .collect::<Vec<_>>();
12061 (title, location_tasks, editor.workspace().clone())
12062 })
12063 .context("location tasks preparation")?;
12064
12065 let locations = future::join_all(location_tasks)
12066 .await
12067 .into_iter()
12068 .filter_map(|location| location.transpose())
12069 .collect::<Result<_>>()
12070 .context("location tasks")?;
12071
12072 let Some(workspace) = workspace else {
12073 return Ok(Navigated::No);
12074 };
12075 let opened = workspace
12076 .update_in(&mut cx, |workspace, window, cx| {
12077 Self::open_locations_in_multibuffer(
12078 workspace,
12079 locations,
12080 title,
12081 split,
12082 MultibufferSelectionMode::First,
12083 window,
12084 cx,
12085 )
12086 })
12087 .ok();
12088
12089 anyhow::Ok(Navigated::from_bool(opened.is_some()))
12090 })
12091 } else {
12092 Task::ready(Ok(Navigated::No))
12093 }
12094 }
12095
12096 fn compute_target_location(
12097 &self,
12098 lsp_location: lsp::Location,
12099 server_id: LanguageServerId,
12100 window: &mut Window,
12101 cx: &mut Context<Self>,
12102 ) -> Task<anyhow::Result<Option<Location>>> {
12103 let Some(project) = self.project.clone() else {
12104 return Task::ready(Ok(None));
12105 };
12106
12107 cx.spawn_in(window, move |editor, mut cx| async move {
12108 let location_task = editor.update(&mut cx, |_, cx| {
12109 project.update(cx, |project, cx| {
12110 let language_server_name = project
12111 .language_server_statuses(cx)
12112 .find(|(id, _)| server_id == *id)
12113 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12114 language_server_name.map(|language_server_name| {
12115 project.open_local_buffer_via_lsp(
12116 lsp_location.uri.clone(),
12117 server_id,
12118 language_server_name,
12119 cx,
12120 )
12121 })
12122 })
12123 })?;
12124 let location = match location_task {
12125 Some(task) => Some({
12126 let target_buffer_handle = task.await.context("open local buffer")?;
12127 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12128 let target_start = target_buffer
12129 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12130 let target_end = target_buffer
12131 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12132 target_buffer.anchor_after(target_start)
12133 ..target_buffer.anchor_before(target_end)
12134 })?;
12135 Location {
12136 buffer: target_buffer_handle,
12137 range,
12138 }
12139 }),
12140 None => None,
12141 };
12142 Ok(location)
12143 })
12144 }
12145
12146 pub fn find_all_references(
12147 &mut self,
12148 _: &FindAllReferences,
12149 window: &mut Window,
12150 cx: &mut Context<Self>,
12151 ) -> Option<Task<Result<Navigated>>> {
12152 let selection = self.selections.newest::<usize>(cx);
12153 let multi_buffer = self.buffer.read(cx);
12154 let head = selection.head();
12155
12156 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12157 let head_anchor = multi_buffer_snapshot.anchor_at(
12158 head,
12159 if head < selection.tail() {
12160 Bias::Right
12161 } else {
12162 Bias::Left
12163 },
12164 );
12165
12166 match self
12167 .find_all_references_task_sources
12168 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12169 {
12170 Ok(_) => {
12171 log::info!(
12172 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12173 );
12174 return None;
12175 }
12176 Err(i) => {
12177 self.find_all_references_task_sources.insert(i, head_anchor);
12178 }
12179 }
12180
12181 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12182 let workspace = self.workspace()?;
12183 let project = workspace.read(cx).project().clone();
12184 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12185 Some(cx.spawn_in(window, |editor, mut cx| async move {
12186 let _cleanup = defer({
12187 let mut cx = cx.clone();
12188 move || {
12189 let _ = editor.update(&mut cx, |editor, _| {
12190 if let Ok(i) =
12191 editor
12192 .find_all_references_task_sources
12193 .binary_search_by(|anchor| {
12194 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12195 })
12196 {
12197 editor.find_all_references_task_sources.remove(i);
12198 }
12199 });
12200 }
12201 });
12202
12203 let locations = references.await?;
12204 if locations.is_empty() {
12205 return anyhow::Ok(Navigated::No);
12206 }
12207
12208 workspace.update_in(&mut cx, |workspace, window, cx| {
12209 let title = locations
12210 .first()
12211 .as_ref()
12212 .map(|location| {
12213 let buffer = location.buffer.read(cx);
12214 format!(
12215 "References to `{}`",
12216 buffer
12217 .text_for_range(location.range.clone())
12218 .collect::<String>()
12219 )
12220 })
12221 .unwrap();
12222 Self::open_locations_in_multibuffer(
12223 workspace,
12224 locations,
12225 title,
12226 false,
12227 MultibufferSelectionMode::First,
12228 window,
12229 cx,
12230 );
12231 Navigated::Yes
12232 })
12233 }))
12234 }
12235
12236 /// Opens a multibuffer with the given project locations in it
12237 pub fn open_locations_in_multibuffer(
12238 workspace: &mut Workspace,
12239 mut locations: Vec<Location>,
12240 title: String,
12241 split: bool,
12242 multibuffer_selection_mode: MultibufferSelectionMode,
12243 window: &mut Window,
12244 cx: &mut Context<Workspace>,
12245 ) {
12246 // If there are multiple definitions, open them in a multibuffer
12247 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12248 let mut locations = locations.into_iter().peekable();
12249 let mut ranges = Vec::new();
12250 let capability = workspace.project().read(cx).capability();
12251
12252 let excerpt_buffer = cx.new(|cx| {
12253 let mut multibuffer = MultiBuffer::new(capability);
12254 while let Some(location) = locations.next() {
12255 let buffer = location.buffer.read(cx);
12256 let mut ranges_for_buffer = Vec::new();
12257 let range = location.range.to_offset(buffer);
12258 ranges_for_buffer.push(range.clone());
12259
12260 while let Some(next_location) = locations.peek() {
12261 if next_location.buffer == location.buffer {
12262 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12263 locations.next();
12264 } else {
12265 break;
12266 }
12267 }
12268
12269 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12270 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12271 location.buffer.clone(),
12272 ranges_for_buffer,
12273 DEFAULT_MULTIBUFFER_CONTEXT,
12274 cx,
12275 ))
12276 }
12277
12278 multibuffer.with_title(title)
12279 });
12280
12281 let editor = cx.new(|cx| {
12282 Editor::for_multibuffer(
12283 excerpt_buffer,
12284 Some(workspace.project().clone()),
12285 true,
12286 window,
12287 cx,
12288 )
12289 });
12290 editor.update(cx, |editor, cx| {
12291 match multibuffer_selection_mode {
12292 MultibufferSelectionMode::First => {
12293 if let Some(first_range) = ranges.first() {
12294 editor.change_selections(None, window, cx, |selections| {
12295 selections.clear_disjoint();
12296 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12297 });
12298 }
12299 editor.highlight_background::<Self>(
12300 &ranges,
12301 |theme| theme.editor_highlighted_line_background,
12302 cx,
12303 );
12304 }
12305 MultibufferSelectionMode::All => {
12306 editor.change_selections(None, window, cx, |selections| {
12307 selections.clear_disjoint();
12308 selections.select_anchor_ranges(ranges);
12309 });
12310 }
12311 }
12312 editor.register_buffers_with_language_servers(cx);
12313 });
12314
12315 let item = Box::new(editor);
12316 let item_id = item.item_id();
12317
12318 if split {
12319 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12320 } else {
12321 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12322 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12323 pane.close_current_preview_item(window, cx)
12324 } else {
12325 None
12326 }
12327 });
12328 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12329 }
12330 workspace.active_pane().update(cx, |pane, cx| {
12331 pane.set_preview_item_id(Some(item_id), cx);
12332 });
12333 }
12334
12335 pub fn rename(
12336 &mut self,
12337 _: &Rename,
12338 window: &mut Window,
12339 cx: &mut Context<Self>,
12340 ) -> Option<Task<Result<()>>> {
12341 use language::ToOffset as _;
12342
12343 let provider = self.semantics_provider.clone()?;
12344 let selection = self.selections.newest_anchor().clone();
12345 let (cursor_buffer, cursor_buffer_position) = self
12346 .buffer
12347 .read(cx)
12348 .text_anchor_for_position(selection.head(), cx)?;
12349 let (tail_buffer, cursor_buffer_position_end) = self
12350 .buffer
12351 .read(cx)
12352 .text_anchor_for_position(selection.tail(), cx)?;
12353 if tail_buffer != cursor_buffer {
12354 return None;
12355 }
12356
12357 let snapshot = cursor_buffer.read(cx).snapshot();
12358 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12359 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12360 let prepare_rename = provider
12361 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12362 .unwrap_or_else(|| Task::ready(Ok(None)));
12363 drop(snapshot);
12364
12365 Some(cx.spawn_in(window, |this, mut cx| async move {
12366 let rename_range = if let Some(range) = prepare_rename.await? {
12367 Some(range)
12368 } else {
12369 this.update(&mut cx, |this, cx| {
12370 let buffer = this.buffer.read(cx).snapshot(cx);
12371 let mut buffer_highlights = this
12372 .document_highlights_for_position(selection.head(), &buffer)
12373 .filter(|highlight| {
12374 highlight.start.excerpt_id == selection.head().excerpt_id
12375 && highlight.end.excerpt_id == selection.head().excerpt_id
12376 });
12377 buffer_highlights
12378 .next()
12379 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12380 })?
12381 };
12382 if let Some(rename_range) = rename_range {
12383 this.update_in(&mut cx, |this, window, cx| {
12384 let snapshot = cursor_buffer.read(cx).snapshot();
12385 let rename_buffer_range = rename_range.to_offset(&snapshot);
12386 let cursor_offset_in_rename_range =
12387 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12388 let cursor_offset_in_rename_range_end =
12389 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12390
12391 this.take_rename(false, window, cx);
12392 let buffer = this.buffer.read(cx).read(cx);
12393 let cursor_offset = selection.head().to_offset(&buffer);
12394 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12395 let rename_end = rename_start + rename_buffer_range.len();
12396 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12397 let mut old_highlight_id = None;
12398 let old_name: Arc<str> = buffer
12399 .chunks(rename_start..rename_end, true)
12400 .map(|chunk| {
12401 if old_highlight_id.is_none() {
12402 old_highlight_id = chunk.syntax_highlight_id;
12403 }
12404 chunk.text
12405 })
12406 .collect::<String>()
12407 .into();
12408
12409 drop(buffer);
12410
12411 // Position the selection in the rename editor so that it matches the current selection.
12412 this.show_local_selections = false;
12413 let rename_editor = cx.new(|cx| {
12414 let mut editor = Editor::single_line(window, cx);
12415 editor.buffer.update(cx, |buffer, cx| {
12416 buffer.edit([(0..0, old_name.clone())], None, cx)
12417 });
12418 let rename_selection_range = match cursor_offset_in_rename_range
12419 .cmp(&cursor_offset_in_rename_range_end)
12420 {
12421 Ordering::Equal => {
12422 editor.select_all(&SelectAll, window, cx);
12423 return editor;
12424 }
12425 Ordering::Less => {
12426 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12427 }
12428 Ordering::Greater => {
12429 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12430 }
12431 };
12432 if rename_selection_range.end > old_name.len() {
12433 editor.select_all(&SelectAll, window, cx);
12434 } else {
12435 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12436 s.select_ranges([rename_selection_range]);
12437 });
12438 }
12439 editor
12440 });
12441 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12442 if e == &EditorEvent::Focused {
12443 cx.emit(EditorEvent::FocusedIn)
12444 }
12445 })
12446 .detach();
12447
12448 let write_highlights =
12449 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12450 let read_highlights =
12451 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12452 let ranges = write_highlights
12453 .iter()
12454 .flat_map(|(_, ranges)| ranges.iter())
12455 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12456 .cloned()
12457 .collect();
12458
12459 this.highlight_text::<Rename>(
12460 ranges,
12461 HighlightStyle {
12462 fade_out: Some(0.6),
12463 ..Default::default()
12464 },
12465 cx,
12466 );
12467 let rename_focus_handle = rename_editor.focus_handle(cx);
12468 window.focus(&rename_focus_handle);
12469 let block_id = this.insert_blocks(
12470 [BlockProperties {
12471 style: BlockStyle::Flex,
12472 placement: BlockPlacement::Below(range.start),
12473 height: 1,
12474 render: Arc::new({
12475 let rename_editor = rename_editor.clone();
12476 move |cx: &mut BlockContext| {
12477 let mut text_style = cx.editor_style.text.clone();
12478 if let Some(highlight_style) = old_highlight_id
12479 .and_then(|h| h.style(&cx.editor_style.syntax))
12480 {
12481 text_style = text_style.highlight(highlight_style);
12482 }
12483 div()
12484 .block_mouse_down()
12485 .pl(cx.anchor_x)
12486 .child(EditorElement::new(
12487 &rename_editor,
12488 EditorStyle {
12489 background: cx.theme().system().transparent,
12490 local_player: cx.editor_style.local_player,
12491 text: text_style,
12492 scrollbar_width: cx.editor_style.scrollbar_width,
12493 syntax: cx.editor_style.syntax.clone(),
12494 status: cx.editor_style.status.clone(),
12495 inlay_hints_style: HighlightStyle {
12496 font_weight: Some(FontWeight::BOLD),
12497 ..make_inlay_hints_style(cx.app)
12498 },
12499 inline_completion_styles: make_suggestion_styles(
12500 cx.app,
12501 ),
12502 ..EditorStyle::default()
12503 },
12504 ))
12505 .into_any_element()
12506 }
12507 }),
12508 priority: 0,
12509 }],
12510 Some(Autoscroll::fit()),
12511 cx,
12512 )[0];
12513 this.pending_rename = Some(RenameState {
12514 range,
12515 old_name,
12516 editor: rename_editor,
12517 block_id,
12518 });
12519 })?;
12520 }
12521
12522 Ok(())
12523 }))
12524 }
12525
12526 pub fn confirm_rename(
12527 &mut self,
12528 _: &ConfirmRename,
12529 window: &mut Window,
12530 cx: &mut Context<Self>,
12531 ) -> Option<Task<Result<()>>> {
12532 let rename = self.take_rename(false, window, cx)?;
12533 let workspace = self.workspace()?.downgrade();
12534 let (buffer, start) = self
12535 .buffer
12536 .read(cx)
12537 .text_anchor_for_position(rename.range.start, cx)?;
12538 let (end_buffer, _) = self
12539 .buffer
12540 .read(cx)
12541 .text_anchor_for_position(rename.range.end, cx)?;
12542 if buffer != end_buffer {
12543 return None;
12544 }
12545
12546 let old_name = rename.old_name;
12547 let new_name = rename.editor.read(cx).text(cx);
12548
12549 let rename = self.semantics_provider.as_ref()?.perform_rename(
12550 &buffer,
12551 start,
12552 new_name.clone(),
12553 cx,
12554 )?;
12555
12556 Some(cx.spawn_in(window, |editor, mut cx| async move {
12557 let project_transaction = rename.await?;
12558 Self::open_project_transaction(
12559 &editor,
12560 workspace,
12561 project_transaction,
12562 format!("Rename: {} → {}", old_name, new_name),
12563 cx.clone(),
12564 )
12565 .await?;
12566
12567 editor.update(&mut cx, |editor, cx| {
12568 editor.refresh_document_highlights(cx);
12569 })?;
12570 Ok(())
12571 }))
12572 }
12573
12574 fn take_rename(
12575 &mut self,
12576 moving_cursor: bool,
12577 window: &mut Window,
12578 cx: &mut Context<Self>,
12579 ) -> Option<RenameState> {
12580 let rename = self.pending_rename.take()?;
12581 if rename.editor.focus_handle(cx).is_focused(window) {
12582 window.focus(&self.focus_handle);
12583 }
12584
12585 self.remove_blocks(
12586 [rename.block_id].into_iter().collect(),
12587 Some(Autoscroll::fit()),
12588 cx,
12589 );
12590 self.clear_highlights::<Rename>(cx);
12591 self.show_local_selections = true;
12592
12593 if moving_cursor {
12594 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12595 editor.selections.newest::<usize>(cx).head()
12596 });
12597
12598 // Update the selection to match the position of the selection inside
12599 // the rename editor.
12600 let snapshot = self.buffer.read(cx).read(cx);
12601 let rename_range = rename.range.to_offset(&snapshot);
12602 let cursor_in_editor = snapshot
12603 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12604 .min(rename_range.end);
12605 drop(snapshot);
12606
12607 self.change_selections(None, window, cx, |s| {
12608 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12609 });
12610 } else {
12611 self.refresh_document_highlights(cx);
12612 }
12613
12614 Some(rename)
12615 }
12616
12617 pub fn pending_rename(&self) -> Option<&RenameState> {
12618 self.pending_rename.as_ref()
12619 }
12620
12621 fn format(
12622 &mut self,
12623 _: &Format,
12624 window: &mut Window,
12625 cx: &mut Context<Self>,
12626 ) -> Option<Task<Result<()>>> {
12627 let project = match &self.project {
12628 Some(project) => project.clone(),
12629 None => return None,
12630 };
12631
12632 Some(self.perform_format(
12633 project,
12634 FormatTrigger::Manual,
12635 FormatTarget::Buffers,
12636 window,
12637 cx,
12638 ))
12639 }
12640
12641 fn format_selections(
12642 &mut self,
12643 _: &FormatSelections,
12644 window: &mut Window,
12645 cx: &mut Context<Self>,
12646 ) -> Option<Task<Result<()>>> {
12647 let project = match &self.project {
12648 Some(project) => project.clone(),
12649 None => return None,
12650 };
12651
12652 let ranges = self
12653 .selections
12654 .all_adjusted(cx)
12655 .into_iter()
12656 .map(|selection| selection.range())
12657 .collect_vec();
12658
12659 Some(self.perform_format(
12660 project,
12661 FormatTrigger::Manual,
12662 FormatTarget::Ranges(ranges),
12663 window,
12664 cx,
12665 ))
12666 }
12667
12668 fn perform_format(
12669 &mut self,
12670 project: Entity<Project>,
12671 trigger: FormatTrigger,
12672 target: FormatTarget,
12673 window: &mut Window,
12674 cx: &mut Context<Self>,
12675 ) -> Task<Result<()>> {
12676 let buffer = self.buffer.clone();
12677 let (buffers, target) = match target {
12678 FormatTarget::Buffers => {
12679 let mut buffers = buffer.read(cx).all_buffers();
12680 if trigger == FormatTrigger::Save {
12681 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12682 }
12683 (buffers, LspFormatTarget::Buffers)
12684 }
12685 FormatTarget::Ranges(selection_ranges) => {
12686 let multi_buffer = buffer.read(cx);
12687 let snapshot = multi_buffer.read(cx);
12688 let mut buffers = HashSet::default();
12689 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12690 BTreeMap::new();
12691 for selection_range in selection_ranges {
12692 for (buffer, buffer_range, _) in
12693 snapshot.range_to_buffer_ranges(selection_range)
12694 {
12695 let buffer_id = buffer.remote_id();
12696 let start = buffer.anchor_before(buffer_range.start);
12697 let end = buffer.anchor_after(buffer_range.end);
12698 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12699 buffer_id_to_ranges
12700 .entry(buffer_id)
12701 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12702 .or_insert_with(|| vec![start..end]);
12703 }
12704 }
12705 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12706 }
12707 };
12708
12709 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12710 let format = project.update(cx, |project, cx| {
12711 project.format(buffers, target, true, trigger, cx)
12712 });
12713
12714 cx.spawn_in(window, |_, mut cx| async move {
12715 let transaction = futures::select_biased! {
12716 () = timeout => {
12717 log::warn!("timed out waiting for formatting");
12718 None
12719 }
12720 transaction = format.log_err().fuse() => transaction,
12721 };
12722
12723 buffer
12724 .update(&mut cx, |buffer, cx| {
12725 if let Some(transaction) = transaction {
12726 if !buffer.is_singleton() {
12727 buffer.push_transaction(&transaction.0, cx);
12728 }
12729 }
12730 cx.notify();
12731 })
12732 .ok();
12733
12734 Ok(())
12735 })
12736 }
12737
12738 fn organize_imports(
12739 &mut self,
12740 _: &OrganizeImports,
12741 window: &mut Window,
12742 cx: &mut Context<Self>,
12743 ) -> Option<Task<Result<()>>> {
12744 let project = match &self.project {
12745 Some(project) => project.clone(),
12746 None => return None,
12747 };
12748 Some(self.perform_code_action_kind(
12749 project,
12750 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12751 window,
12752 cx,
12753 ))
12754 }
12755
12756 fn perform_code_action_kind(
12757 &mut self,
12758 project: Entity<Project>,
12759 kind: CodeActionKind,
12760 window: &mut Window,
12761 cx: &mut Context<Self>,
12762 ) -> Task<Result<()>> {
12763 let buffer = self.buffer.clone();
12764 let buffers = buffer.read(cx).all_buffers();
12765 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12766 let apply_action = project.update(cx, |project, cx| {
12767 project.apply_code_action_kind(buffers, kind, true, cx)
12768 });
12769 cx.spawn_in(window, |_, mut cx| async move {
12770 let transaction = futures::select_biased! {
12771 () = timeout => {
12772 log::warn!("timed out waiting for executing code action");
12773 None
12774 }
12775 transaction = apply_action.log_err().fuse() => transaction,
12776 };
12777 buffer
12778 .update(&mut cx, |buffer, cx| {
12779 // check if we need this
12780 if let Some(transaction) = transaction {
12781 if !buffer.is_singleton() {
12782 buffer.push_transaction(&transaction.0, cx);
12783 }
12784 }
12785 cx.notify();
12786 })
12787 .ok();
12788 Ok(())
12789 })
12790 }
12791
12792 fn restart_language_server(
12793 &mut self,
12794 _: &RestartLanguageServer,
12795 _: &mut Window,
12796 cx: &mut Context<Self>,
12797 ) {
12798 if let Some(project) = self.project.clone() {
12799 self.buffer.update(cx, |multi_buffer, cx| {
12800 project.update(cx, |project, cx| {
12801 project.restart_language_servers_for_buffers(
12802 multi_buffer.all_buffers().into_iter().collect(),
12803 cx,
12804 );
12805 });
12806 })
12807 }
12808 }
12809
12810 fn cancel_language_server_work(
12811 workspace: &mut Workspace,
12812 _: &actions::CancelLanguageServerWork,
12813 _: &mut Window,
12814 cx: &mut Context<Workspace>,
12815 ) {
12816 let project = workspace.project();
12817 let buffers = workspace
12818 .active_item(cx)
12819 .and_then(|item| item.act_as::<Editor>(cx))
12820 .map_or(HashSet::default(), |editor| {
12821 editor.read(cx).buffer.read(cx).all_buffers()
12822 });
12823 project.update(cx, |project, cx| {
12824 project.cancel_language_server_work_for_buffers(buffers, cx);
12825 });
12826 }
12827
12828 fn show_character_palette(
12829 &mut self,
12830 _: &ShowCharacterPalette,
12831 window: &mut Window,
12832 _: &mut Context<Self>,
12833 ) {
12834 window.show_character_palette();
12835 }
12836
12837 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12838 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12839 let buffer = self.buffer.read(cx).snapshot(cx);
12840 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12841 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12842 let is_valid = buffer
12843 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12844 .any(|entry| {
12845 entry.diagnostic.is_primary
12846 && !entry.range.is_empty()
12847 && entry.range.start == primary_range_start
12848 && entry.diagnostic.message == active_diagnostics.primary_message
12849 });
12850
12851 if is_valid != active_diagnostics.is_valid {
12852 active_diagnostics.is_valid = is_valid;
12853 if is_valid {
12854 let mut new_styles = HashMap::default();
12855 for (block_id, diagnostic) in &active_diagnostics.blocks {
12856 new_styles.insert(
12857 *block_id,
12858 diagnostic_block_renderer(diagnostic.clone(), None, true),
12859 );
12860 }
12861 self.display_map.update(cx, |display_map, _cx| {
12862 display_map.replace_blocks(new_styles);
12863 });
12864 } else {
12865 self.dismiss_diagnostics(cx);
12866 }
12867 }
12868 }
12869 }
12870
12871 fn activate_diagnostics(
12872 &mut self,
12873 buffer_id: BufferId,
12874 group_id: usize,
12875 window: &mut Window,
12876 cx: &mut Context<Self>,
12877 ) {
12878 self.dismiss_diagnostics(cx);
12879 let snapshot = self.snapshot(window, cx);
12880 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12881 let buffer = self.buffer.read(cx).snapshot(cx);
12882
12883 let mut primary_range = None;
12884 let mut primary_message = None;
12885 let diagnostic_group = buffer
12886 .diagnostic_group(buffer_id, group_id)
12887 .filter_map(|entry| {
12888 let start = entry.range.start;
12889 let end = entry.range.end;
12890 if snapshot.is_line_folded(MultiBufferRow(start.row))
12891 && (start.row == end.row
12892 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12893 {
12894 return None;
12895 }
12896 if entry.diagnostic.is_primary {
12897 primary_range = Some(entry.range.clone());
12898 primary_message = Some(entry.diagnostic.message.clone());
12899 }
12900 Some(entry)
12901 })
12902 .collect::<Vec<_>>();
12903 let primary_range = primary_range?;
12904 let primary_message = primary_message?;
12905
12906 let blocks = display_map
12907 .insert_blocks(
12908 diagnostic_group.iter().map(|entry| {
12909 let diagnostic = entry.diagnostic.clone();
12910 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12911 BlockProperties {
12912 style: BlockStyle::Fixed,
12913 placement: BlockPlacement::Below(
12914 buffer.anchor_after(entry.range.start),
12915 ),
12916 height: message_height,
12917 render: diagnostic_block_renderer(diagnostic, None, true),
12918 priority: 0,
12919 }
12920 }),
12921 cx,
12922 )
12923 .into_iter()
12924 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12925 .collect();
12926
12927 Some(ActiveDiagnosticGroup {
12928 primary_range: buffer.anchor_before(primary_range.start)
12929 ..buffer.anchor_after(primary_range.end),
12930 primary_message,
12931 group_id,
12932 blocks,
12933 is_valid: true,
12934 })
12935 });
12936 }
12937
12938 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12939 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12940 self.display_map.update(cx, |display_map, cx| {
12941 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12942 });
12943 cx.notify();
12944 }
12945 }
12946
12947 /// Disable inline diagnostics rendering for this editor.
12948 pub fn disable_inline_diagnostics(&mut self) {
12949 self.inline_diagnostics_enabled = false;
12950 self.inline_diagnostics_update = Task::ready(());
12951 self.inline_diagnostics.clear();
12952 }
12953
12954 pub fn inline_diagnostics_enabled(&self) -> bool {
12955 self.inline_diagnostics_enabled
12956 }
12957
12958 pub fn show_inline_diagnostics(&self) -> bool {
12959 self.show_inline_diagnostics
12960 }
12961
12962 pub fn toggle_inline_diagnostics(
12963 &mut self,
12964 _: &ToggleInlineDiagnostics,
12965 window: &mut Window,
12966 cx: &mut Context<'_, Editor>,
12967 ) {
12968 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12969 self.refresh_inline_diagnostics(false, window, cx);
12970 }
12971
12972 fn refresh_inline_diagnostics(
12973 &mut self,
12974 debounce: bool,
12975 window: &mut Window,
12976 cx: &mut Context<Self>,
12977 ) {
12978 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12979 self.inline_diagnostics_update = Task::ready(());
12980 self.inline_diagnostics.clear();
12981 return;
12982 }
12983
12984 let debounce_ms = ProjectSettings::get_global(cx)
12985 .diagnostics
12986 .inline
12987 .update_debounce_ms;
12988 let debounce = if debounce && debounce_ms > 0 {
12989 Some(Duration::from_millis(debounce_ms))
12990 } else {
12991 None
12992 };
12993 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12994 if let Some(debounce) = debounce {
12995 cx.background_executor().timer(debounce).await;
12996 }
12997 let Some(snapshot) = editor
12998 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12999 .ok()
13000 else {
13001 return;
13002 };
13003
13004 let new_inline_diagnostics = cx
13005 .background_spawn(async move {
13006 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13007 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13008 let message = diagnostic_entry
13009 .diagnostic
13010 .message
13011 .split_once('\n')
13012 .map(|(line, _)| line)
13013 .map(SharedString::new)
13014 .unwrap_or_else(|| {
13015 SharedString::from(diagnostic_entry.diagnostic.message)
13016 });
13017 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13018 let (Ok(i) | Err(i)) = inline_diagnostics
13019 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13020 inline_diagnostics.insert(
13021 i,
13022 (
13023 start_anchor,
13024 InlineDiagnostic {
13025 message,
13026 group_id: diagnostic_entry.diagnostic.group_id,
13027 start: diagnostic_entry.range.start.to_point(&snapshot),
13028 is_primary: diagnostic_entry.diagnostic.is_primary,
13029 severity: diagnostic_entry.diagnostic.severity,
13030 },
13031 ),
13032 );
13033 }
13034 inline_diagnostics
13035 })
13036 .await;
13037
13038 editor
13039 .update(&mut cx, |editor, cx| {
13040 editor.inline_diagnostics = new_inline_diagnostics;
13041 cx.notify();
13042 })
13043 .ok();
13044 });
13045 }
13046
13047 pub fn set_selections_from_remote(
13048 &mut self,
13049 selections: Vec<Selection<Anchor>>,
13050 pending_selection: Option<Selection<Anchor>>,
13051 window: &mut Window,
13052 cx: &mut Context<Self>,
13053 ) {
13054 let old_cursor_position = self.selections.newest_anchor().head();
13055 self.selections.change_with(cx, |s| {
13056 s.select_anchors(selections);
13057 if let Some(pending_selection) = pending_selection {
13058 s.set_pending(pending_selection, SelectMode::Character);
13059 } else {
13060 s.clear_pending();
13061 }
13062 });
13063 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13064 }
13065
13066 fn push_to_selection_history(&mut self) {
13067 self.selection_history.push(SelectionHistoryEntry {
13068 selections: self.selections.disjoint_anchors(),
13069 select_next_state: self.select_next_state.clone(),
13070 select_prev_state: self.select_prev_state.clone(),
13071 add_selections_state: self.add_selections_state.clone(),
13072 });
13073 }
13074
13075 pub fn transact(
13076 &mut self,
13077 window: &mut Window,
13078 cx: &mut Context<Self>,
13079 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13080 ) -> Option<TransactionId> {
13081 self.start_transaction_at(Instant::now(), window, cx);
13082 update(self, window, cx);
13083 self.end_transaction_at(Instant::now(), cx)
13084 }
13085
13086 pub fn start_transaction_at(
13087 &mut self,
13088 now: Instant,
13089 window: &mut Window,
13090 cx: &mut Context<Self>,
13091 ) {
13092 self.end_selection(window, cx);
13093 if let Some(tx_id) = self
13094 .buffer
13095 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13096 {
13097 self.selection_history
13098 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13099 cx.emit(EditorEvent::TransactionBegun {
13100 transaction_id: tx_id,
13101 })
13102 }
13103 }
13104
13105 pub fn end_transaction_at(
13106 &mut self,
13107 now: Instant,
13108 cx: &mut Context<Self>,
13109 ) -> Option<TransactionId> {
13110 if let Some(transaction_id) = self
13111 .buffer
13112 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13113 {
13114 if let Some((_, end_selections)) =
13115 self.selection_history.transaction_mut(transaction_id)
13116 {
13117 *end_selections = Some(self.selections.disjoint_anchors());
13118 } else {
13119 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13120 }
13121
13122 cx.emit(EditorEvent::Edited { transaction_id });
13123 Some(transaction_id)
13124 } else {
13125 None
13126 }
13127 }
13128
13129 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13130 if self.selection_mark_mode {
13131 self.change_selections(None, window, cx, |s| {
13132 s.move_with(|_, sel| {
13133 sel.collapse_to(sel.head(), SelectionGoal::None);
13134 });
13135 })
13136 }
13137 self.selection_mark_mode = true;
13138 cx.notify();
13139 }
13140
13141 pub fn swap_selection_ends(
13142 &mut self,
13143 _: &actions::SwapSelectionEnds,
13144 window: &mut Window,
13145 cx: &mut Context<Self>,
13146 ) {
13147 self.change_selections(None, window, cx, |s| {
13148 s.move_with(|_, sel| {
13149 if sel.start != sel.end {
13150 sel.reversed = !sel.reversed
13151 }
13152 });
13153 });
13154 self.request_autoscroll(Autoscroll::newest(), cx);
13155 cx.notify();
13156 }
13157
13158 pub fn toggle_fold(
13159 &mut self,
13160 _: &actions::ToggleFold,
13161 window: &mut Window,
13162 cx: &mut Context<Self>,
13163 ) {
13164 if self.is_singleton(cx) {
13165 let selection = self.selections.newest::<Point>(cx);
13166
13167 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13168 let range = if selection.is_empty() {
13169 let point = selection.head().to_display_point(&display_map);
13170 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13171 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13172 .to_point(&display_map);
13173 start..end
13174 } else {
13175 selection.range()
13176 };
13177 if display_map.folds_in_range(range).next().is_some() {
13178 self.unfold_lines(&Default::default(), window, cx)
13179 } else {
13180 self.fold(&Default::default(), window, cx)
13181 }
13182 } else {
13183 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13184 let buffer_ids: HashSet<_> = self
13185 .selections
13186 .disjoint_anchor_ranges()
13187 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13188 .collect();
13189
13190 let should_unfold = buffer_ids
13191 .iter()
13192 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13193
13194 for buffer_id in buffer_ids {
13195 if should_unfold {
13196 self.unfold_buffer(buffer_id, cx);
13197 } else {
13198 self.fold_buffer(buffer_id, cx);
13199 }
13200 }
13201 }
13202 }
13203
13204 pub fn toggle_fold_recursive(
13205 &mut self,
13206 _: &actions::ToggleFoldRecursive,
13207 window: &mut Window,
13208 cx: &mut Context<Self>,
13209 ) {
13210 let selection = self.selections.newest::<Point>(cx);
13211
13212 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13213 let range = if selection.is_empty() {
13214 let point = selection.head().to_display_point(&display_map);
13215 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13216 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13217 .to_point(&display_map);
13218 start..end
13219 } else {
13220 selection.range()
13221 };
13222 if display_map.folds_in_range(range).next().is_some() {
13223 self.unfold_recursive(&Default::default(), window, cx)
13224 } else {
13225 self.fold_recursive(&Default::default(), window, cx)
13226 }
13227 }
13228
13229 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13230 if self.is_singleton(cx) {
13231 let mut to_fold = Vec::new();
13232 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13233 let selections = self.selections.all_adjusted(cx);
13234
13235 for selection in selections {
13236 let range = selection.range().sorted();
13237 let buffer_start_row = range.start.row;
13238
13239 if range.start.row != range.end.row {
13240 let mut found = false;
13241 let mut row = range.start.row;
13242 while row <= range.end.row {
13243 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13244 {
13245 found = true;
13246 row = crease.range().end.row + 1;
13247 to_fold.push(crease);
13248 } else {
13249 row += 1
13250 }
13251 }
13252 if found {
13253 continue;
13254 }
13255 }
13256
13257 for row in (0..=range.start.row).rev() {
13258 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13259 if crease.range().end.row >= buffer_start_row {
13260 to_fold.push(crease);
13261 if row <= range.start.row {
13262 break;
13263 }
13264 }
13265 }
13266 }
13267 }
13268
13269 self.fold_creases(to_fold, true, window, cx);
13270 } else {
13271 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13272 let buffer_ids = self
13273 .selections
13274 .disjoint_anchor_ranges()
13275 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13276 .collect::<HashSet<_>>();
13277 for buffer_id in buffer_ids {
13278 self.fold_buffer(buffer_id, cx);
13279 }
13280 }
13281 }
13282
13283 fn fold_at_level(
13284 &mut self,
13285 fold_at: &FoldAtLevel,
13286 window: &mut Window,
13287 cx: &mut Context<Self>,
13288 ) {
13289 if !self.buffer.read(cx).is_singleton() {
13290 return;
13291 }
13292
13293 let fold_at_level = fold_at.0;
13294 let snapshot = self.buffer.read(cx).snapshot(cx);
13295 let mut to_fold = Vec::new();
13296 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13297
13298 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13299 while start_row < end_row {
13300 match self
13301 .snapshot(window, cx)
13302 .crease_for_buffer_row(MultiBufferRow(start_row))
13303 {
13304 Some(crease) => {
13305 let nested_start_row = crease.range().start.row + 1;
13306 let nested_end_row = crease.range().end.row;
13307
13308 if current_level < fold_at_level {
13309 stack.push((nested_start_row, nested_end_row, current_level + 1));
13310 } else if current_level == fold_at_level {
13311 to_fold.push(crease);
13312 }
13313
13314 start_row = nested_end_row + 1;
13315 }
13316 None => start_row += 1,
13317 }
13318 }
13319 }
13320
13321 self.fold_creases(to_fold, true, window, cx);
13322 }
13323
13324 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13325 if self.buffer.read(cx).is_singleton() {
13326 let mut fold_ranges = Vec::new();
13327 let snapshot = self.buffer.read(cx).snapshot(cx);
13328
13329 for row in 0..snapshot.max_row().0 {
13330 if let Some(foldable_range) = self
13331 .snapshot(window, cx)
13332 .crease_for_buffer_row(MultiBufferRow(row))
13333 {
13334 fold_ranges.push(foldable_range);
13335 }
13336 }
13337
13338 self.fold_creases(fold_ranges, true, window, cx);
13339 } else {
13340 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13341 editor
13342 .update_in(&mut cx, |editor, _, cx| {
13343 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13344 editor.fold_buffer(buffer_id, cx);
13345 }
13346 })
13347 .ok();
13348 });
13349 }
13350 }
13351
13352 pub fn fold_function_bodies(
13353 &mut self,
13354 _: &actions::FoldFunctionBodies,
13355 window: &mut Window,
13356 cx: &mut Context<Self>,
13357 ) {
13358 let snapshot = self.buffer.read(cx).snapshot(cx);
13359
13360 let ranges = snapshot
13361 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13362 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13363 .collect::<Vec<_>>();
13364
13365 let creases = ranges
13366 .into_iter()
13367 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13368 .collect();
13369
13370 self.fold_creases(creases, true, window, cx);
13371 }
13372
13373 pub fn fold_recursive(
13374 &mut self,
13375 _: &actions::FoldRecursive,
13376 window: &mut Window,
13377 cx: &mut Context<Self>,
13378 ) {
13379 let mut to_fold = Vec::new();
13380 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13381 let selections = self.selections.all_adjusted(cx);
13382
13383 for selection in selections {
13384 let range = selection.range().sorted();
13385 let buffer_start_row = range.start.row;
13386
13387 if range.start.row != range.end.row {
13388 let mut found = false;
13389 for row in range.start.row..=range.end.row {
13390 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13391 found = true;
13392 to_fold.push(crease);
13393 }
13394 }
13395 if found {
13396 continue;
13397 }
13398 }
13399
13400 for row in (0..=range.start.row).rev() {
13401 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13402 if crease.range().end.row >= buffer_start_row {
13403 to_fold.push(crease);
13404 } else {
13405 break;
13406 }
13407 }
13408 }
13409 }
13410
13411 self.fold_creases(to_fold, true, window, cx);
13412 }
13413
13414 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13415 let buffer_row = fold_at.buffer_row;
13416 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13417
13418 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13419 let autoscroll = self
13420 .selections
13421 .all::<Point>(cx)
13422 .iter()
13423 .any(|selection| crease.range().overlaps(&selection.range()));
13424
13425 self.fold_creases(vec![crease], autoscroll, window, cx);
13426 }
13427 }
13428
13429 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13430 if self.is_singleton(cx) {
13431 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13432 let buffer = &display_map.buffer_snapshot;
13433 let selections = self.selections.all::<Point>(cx);
13434 let ranges = selections
13435 .iter()
13436 .map(|s| {
13437 let range = s.display_range(&display_map).sorted();
13438 let mut start = range.start.to_point(&display_map);
13439 let mut end = range.end.to_point(&display_map);
13440 start.column = 0;
13441 end.column = buffer.line_len(MultiBufferRow(end.row));
13442 start..end
13443 })
13444 .collect::<Vec<_>>();
13445
13446 self.unfold_ranges(&ranges, true, true, cx);
13447 } else {
13448 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13449 let buffer_ids = self
13450 .selections
13451 .disjoint_anchor_ranges()
13452 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13453 .collect::<HashSet<_>>();
13454 for buffer_id in buffer_ids {
13455 self.unfold_buffer(buffer_id, cx);
13456 }
13457 }
13458 }
13459
13460 pub fn unfold_recursive(
13461 &mut self,
13462 _: &UnfoldRecursive,
13463 _window: &mut Window,
13464 cx: &mut Context<Self>,
13465 ) {
13466 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13467 let selections = self.selections.all::<Point>(cx);
13468 let ranges = selections
13469 .iter()
13470 .map(|s| {
13471 let mut range = s.display_range(&display_map).sorted();
13472 *range.start.column_mut() = 0;
13473 *range.end.column_mut() = display_map.line_len(range.end.row());
13474 let start = range.start.to_point(&display_map);
13475 let end = range.end.to_point(&display_map);
13476 start..end
13477 })
13478 .collect::<Vec<_>>();
13479
13480 self.unfold_ranges(&ranges, true, true, cx);
13481 }
13482
13483 pub fn unfold_at(
13484 &mut self,
13485 unfold_at: &UnfoldAt,
13486 _window: &mut Window,
13487 cx: &mut Context<Self>,
13488 ) {
13489 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13490
13491 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13492 ..Point::new(
13493 unfold_at.buffer_row.0,
13494 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13495 );
13496
13497 let autoscroll = self
13498 .selections
13499 .all::<Point>(cx)
13500 .iter()
13501 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13502
13503 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13504 }
13505
13506 pub fn unfold_all(
13507 &mut self,
13508 _: &actions::UnfoldAll,
13509 _window: &mut Window,
13510 cx: &mut Context<Self>,
13511 ) {
13512 if self.buffer.read(cx).is_singleton() {
13513 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13514 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13515 } else {
13516 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13517 editor
13518 .update(&mut cx, |editor, cx| {
13519 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13520 editor.unfold_buffer(buffer_id, cx);
13521 }
13522 })
13523 .ok();
13524 });
13525 }
13526 }
13527
13528 pub fn fold_selected_ranges(
13529 &mut self,
13530 _: &FoldSelectedRanges,
13531 window: &mut Window,
13532 cx: &mut Context<Self>,
13533 ) {
13534 let selections = self.selections.all::<Point>(cx);
13535 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13536 let line_mode = self.selections.line_mode;
13537 let ranges = selections
13538 .into_iter()
13539 .map(|s| {
13540 if line_mode {
13541 let start = Point::new(s.start.row, 0);
13542 let end = Point::new(
13543 s.end.row,
13544 display_map
13545 .buffer_snapshot
13546 .line_len(MultiBufferRow(s.end.row)),
13547 );
13548 Crease::simple(start..end, display_map.fold_placeholder.clone())
13549 } else {
13550 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13551 }
13552 })
13553 .collect::<Vec<_>>();
13554 self.fold_creases(ranges, true, window, cx);
13555 }
13556
13557 pub fn fold_ranges<T: ToOffset + Clone>(
13558 &mut self,
13559 ranges: Vec<Range<T>>,
13560 auto_scroll: bool,
13561 window: &mut Window,
13562 cx: &mut Context<Self>,
13563 ) {
13564 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13565 let ranges = ranges
13566 .into_iter()
13567 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13568 .collect::<Vec<_>>();
13569 self.fold_creases(ranges, auto_scroll, window, cx);
13570 }
13571
13572 pub fn fold_creases<T: ToOffset + Clone>(
13573 &mut self,
13574 creases: Vec<Crease<T>>,
13575 auto_scroll: bool,
13576 window: &mut Window,
13577 cx: &mut Context<Self>,
13578 ) {
13579 if creases.is_empty() {
13580 return;
13581 }
13582
13583 let mut buffers_affected = HashSet::default();
13584 let multi_buffer = self.buffer().read(cx);
13585 for crease in &creases {
13586 if let Some((_, buffer, _)) =
13587 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13588 {
13589 buffers_affected.insert(buffer.read(cx).remote_id());
13590 };
13591 }
13592
13593 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13594
13595 if auto_scroll {
13596 self.request_autoscroll(Autoscroll::fit(), cx);
13597 }
13598
13599 cx.notify();
13600
13601 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13602 // Clear diagnostics block when folding a range that contains it.
13603 let snapshot = self.snapshot(window, cx);
13604 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13605 drop(snapshot);
13606 self.active_diagnostics = Some(active_diagnostics);
13607 self.dismiss_diagnostics(cx);
13608 } else {
13609 self.active_diagnostics = Some(active_diagnostics);
13610 }
13611 }
13612
13613 self.scrollbar_marker_state.dirty = true;
13614 }
13615
13616 /// Removes any folds whose ranges intersect any of the given ranges.
13617 pub fn unfold_ranges<T: ToOffset + Clone>(
13618 &mut self,
13619 ranges: &[Range<T>],
13620 inclusive: bool,
13621 auto_scroll: bool,
13622 cx: &mut Context<Self>,
13623 ) {
13624 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13625 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13626 });
13627 }
13628
13629 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13630 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13631 return;
13632 }
13633 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13634 self.display_map.update(cx, |display_map, cx| {
13635 display_map.fold_buffers([buffer_id], cx)
13636 });
13637 cx.emit(EditorEvent::BufferFoldToggled {
13638 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13639 folded: true,
13640 });
13641 cx.notify();
13642 }
13643
13644 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13645 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13646 return;
13647 }
13648 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13649 self.display_map.update(cx, |display_map, cx| {
13650 display_map.unfold_buffers([buffer_id], cx);
13651 });
13652 cx.emit(EditorEvent::BufferFoldToggled {
13653 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13654 folded: false,
13655 });
13656 cx.notify();
13657 }
13658
13659 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13660 self.display_map.read(cx).is_buffer_folded(buffer)
13661 }
13662
13663 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13664 self.display_map.read(cx).folded_buffers()
13665 }
13666
13667 /// Removes any folds with the given ranges.
13668 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13669 &mut self,
13670 ranges: &[Range<T>],
13671 type_id: TypeId,
13672 auto_scroll: bool,
13673 cx: &mut Context<Self>,
13674 ) {
13675 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13676 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13677 });
13678 }
13679
13680 fn remove_folds_with<T: ToOffset + Clone>(
13681 &mut self,
13682 ranges: &[Range<T>],
13683 auto_scroll: bool,
13684 cx: &mut Context<Self>,
13685 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13686 ) {
13687 if ranges.is_empty() {
13688 return;
13689 }
13690
13691 let mut buffers_affected = HashSet::default();
13692 let multi_buffer = self.buffer().read(cx);
13693 for range in ranges {
13694 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13695 buffers_affected.insert(buffer.read(cx).remote_id());
13696 };
13697 }
13698
13699 self.display_map.update(cx, update);
13700
13701 if auto_scroll {
13702 self.request_autoscroll(Autoscroll::fit(), cx);
13703 }
13704
13705 cx.notify();
13706 self.scrollbar_marker_state.dirty = true;
13707 self.active_indent_guides_state.dirty = true;
13708 }
13709
13710 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13711 self.display_map.read(cx).fold_placeholder.clone()
13712 }
13713
13714 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13715 self.buffer.update(cx, |buffer, cx| {
13716 buffer.set_all_diff_hunks_expanded(cx);
13717 });
13718 }
13719
13720 pub fn expand_all_diff_hunks(
13721 &mut self,
13722 _: &ExpandAllDiffHunks,
13723 _window: &mut Window,
13724 cx: &mut Context<Self>,
13725 ) {
13726 self.buffer.update(cx, |buffer, cx| {
13727 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13728 });
13729 }
13730
13731 pub fn toggle_selected_diff_hunks(
13732 &mut self,
13733 _: &ToggleSelectedDiffHunks,
13734 _window: &mut Window,
13735 cx: &mut Context<Self>,
13736 ) {
13737 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13738 self.toggle_diff_hunks_in_ranges(ranges, cx);
13739 }
13740
13741 pub fn diff_hunks_in_ranges<'a>(
13742 &'a self,
13743 ranges: &'a [Range<Anchor>],
13744 buffer: &'a MultiBufferSnapshot,
13745 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13746 ranges.iter().flat_map(move |range| {
13747 let end_excerpt_id = range.end.excerpt_id;
13748 let range = range.to_point(buffer);
13749 let mut peek_end = range.end;
13750 if range.end.row < buffer.max_row().0 {
13751 peek_end = Point::new(range.end.row + 1, 0);
13752 }
13753 buffer
13754 .diff_hunks_in_range(range.start..peek_end)
13755 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13756 })
13757 }
13758
13759 pub fn has_stageable_diff_hunks_in_ranges(
13760 &self,
13761 ranges: &[Range<Anchor>],
13762 snapshot: &MultiBufferSnapshot,
13763 ) -> bool {
13764 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13765 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13766 }
13767
13768 pub fn toggle_staged_selected_diff_hunks(
13769 &mut self,
13770 _: &::git::ToggleStaged,
13771 _: &mut Window,
13772 cx: &mut Context<Self>,
13773 ) {
13774 let snapshot = self.buffer.read(cx).snapshot(cx);
13775 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13776 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13777 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13778 }
13779
13780 pub fn stage_and_next(
13781 &mut self,
13782 _: &::git::StageAndNext,
13783 window: &mut Window,
13784 cx: &mut Context<Self>,
13785 ) {
13786 self.do_stage_or_unstage_and_next(true, window, cx);
13787 }
13788
13789 pub fn unstage_and_next(
13790 &mut self,
13791 _: &::git::UnstageAndNext,
13792 window: &mut Window,
13793 cx: &mut Context<Self>,
13794 ) {
13795 self.do_stage_or_unstage_and_next(false, window, cx);
13796 }
13797
13798 pub fn stage_or_unstage_diff_hunks(
13799 &mut self,
13800 stage: bool,
13801 ranges: Vec<Range<Anchor>>,
13802 cx: &mut Context<Self>,
13803 ) {
13804 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13805 cx.spawn(|this, mut cx| async move {
13806 task.await?;
13807 this.update(&mut cx, |this, cx| {
13808 let snapshot = this.buffer.read(cx).snapshot(cx);
13809 let chunk_by = this
13810 .diff_hunks_in_ranges(&ranges, &snapshot)
13811 .chunk_by(|hunk| hunk.buffer_id);
13812 for (buffer_id, hunks) in &chunk_by {
13813 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13814 }
13815 })
13816 })
13817 .detach_and_log_err(cx);
13818 }
13819
13820 fn save_buffers_for_ranges_if_needed(
13821 &mut self,
13822 ranges: &[Range<Anchor>],
13823 cx: &mut Context<'_, Editor>,
13824 ) -> Task<Result<()>> {
13825 let multibuffer = self.buffer.read(cx);
13826 let snapshot = multibuffer.read(cx);
13827 let buffer_ids: HashSet<_> = ranges
13828 .iter()
13829 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13830 .collect();
13831 drop(snapshot);
13832
13833 let mut buffers = HashSet::default();
13834 for buffer_id in buffer_ids {
13835 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13836 let buffer = buffer_entity.read(cx);
13837 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13838 {
13839 buffers.insert(buffer_entity);
13840 }
13841 }
13842 }
13843
13844 if let Some(project) = &self.project {
13845 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13846 } else {
13847 Task::ready(Ok(()))
13848 }
13849 }
13850
13851 fn do_stage_or_unstage_and_next(
13852 &mut self,
13853 stage: bool,
13854 window: &mut Window,
13855 cx: &mut Context<Self>,
13856 ) {
13857 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13858
13859 if ranges.iter().any(|range| range.start != range.end) {
13860 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13861 return;
13862 }
13863
13864 let snapshot = self.snapshot(window, cx);
13865 let newest_range = self.selections.newest::<Point>(cx).range();
13866
13867 let run_twice = snapshot
13868 .hunks_for_ranges([newest_range])
13869 .first()
13870 .is_some_and(|hunk| {
13871 let next_line = Point::new(hunk.row_range.end.0 + 1, 0);
13872 self.hunk_after_position(&snapshot, next_line)
13873 .is_some_and(|other| other.row_range == hunk.row_range)
13874 });
13875
13876 if run_twice {
13877 self.go_to_next_hunk(&GoToHunk, window, cx);
13878 }
13879 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13880 self.go_to_next_hunk(&GoToHunk, window, cx);
13881 }
13882
13883 fn do_stage_or_unstage(
13884 &self,
13885 stage: bool,
13886 buffer_id: BufferId,
13887 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13888 cx: &mut App,
13889 ) -> Option<()> {
13890 let project = self.project.as_ref()?;
13891 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13892 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13893 let buffer_snapshot = buffer.read(cx).snapshot();
13894 let file_exists = buffer_snapshot
13895 .file()
13896 .is_some_and(|file| file.disk_state().exists());
13897 diff.update(cx, |diff, cx| {
13898 diff.stage_or_unstage_hunks(
13899 stage,
13900 &hunks
13901 .map(|hunk| buffer_diff::DiffHunk {
13902 buffer_range: hunk.buffer_range,
13903 diff_base_byte_range: hunk.diff_base_byte_range,
13904 secondary_status: hunk.secondary_status,
13905 range: Point::zero()..Point::zero(), // unused
13906 })
13907 .collect::<Vec<_>>(),
13908 &buffer_snapshot,
13909 file_exists,
13910 cx,
13911 )
13912 });
13913 None
13914 }
13915
13916 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13917 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13918 self.buffer
13919 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13920 }
13921
13922 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13923 self.buffer.update(cx, |buffer, cx| {
13924 let ranges = vec![Anchor::min()..Anchor::max()];
13925 if !buffer.all_diff_hunks_expanded()
13926 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13927 {
13928 buffer.collapse_diff_hunks(ranges, cx);
13929 true
13930 } else {
13931 false
13932 }
13933 })
13934 }
13935
13936 fn toggle_diff_hunks_in_ranges(
13937 &mut self,
13938 ranges: Vec<Range<Anchor>>,
13939 cx: &mut Context<'_, Editor>,
13940 ) {
13941 self.buffer.update(cx, |buffer, cx| {
13942 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13943 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13944 })
13945 }
13946
13947 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13948 self.buffer.update(cx, |buffer, cx| {
13949 let snapshot = buffer.snapshot(cx);
13950 let excerpt_id = range.end.excerpt_id;
13951 let point_range = range.to_point(&snapshot);
13952 let expand = !buffer.single_hunk_is_expanded(range, cx);
13953 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13954 })
13955 }
13956
13957 pub(crate) fn apply_all_diff_hunks(
13958 &mut self,
13959 _: &ApplyAllDiffHunks,
13960 window: &mut Window,
13961 cx: &mut Context<Self>,
13962 ) {
13963 let buffers = self.buffer.read(cx).all_buffers();
13964 for branch_buffer in buffers {
13965 branch_buffer.update(cx, |branch_buffer, cx| {
13966 branch_buffer.merge_into_base(Vec::new(), cx);
13967 });
13968 }
13969
13970 if let Some(project) = self.project.clone() {
13971 self.save(true, project, window, cx).detach_and_log_err(cx);
13972 }
13973 }
13974
13975 pub(crate) fn apply_selected_diff_hunks(
13976 &mut self,
13977 _: &ApplyDiffHunk,
13978 window: &mut Window,
13979 cx: &mut Context<Self>,
13980 ) {
13981 let snapshot = self.snapshot(window, cx);
13982 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13983 let mut ranges_by_buffer = HashMap::default();
13984 self.transact(window, cx, |editor, _window, cx| {
13985 for hunk in hunks {
13986 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13987 ranges_by_buffer
13988 .entry(buffer.clone())
13989 .or_insert_with(Vec::new)
13990 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13991 }
13992 }
13993
13994 for (buffer, ranges) in ranges_by_buffer {
13995 buffer.update(cx, |buffer, cx| {
13996 buffer.merge_into_base(ranges, cx);
13997 });
13998 }
13999 });
14000
14001 if let Some(project) = self.project.clone() {
14002 self.save(true, project, window, cx).detach_and_log_err(cx);
14003 }
14004 }
14005
14006 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14007 if hovered != self.gutter_hovered {
14008 self.gutter_hovered = hovered;
14009 cx.notify();
14010 }
14011 }
14012
14013 pub fn insert_blocks(
14014 &mut self,
14015 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14016 autoscroll: Option<Autoscroll>,
14017 cx: &mut Context<Self>,
14018 ) -> Vec<CustomBlockId> {
14019 let blocks = self
14020 .display_map
14021 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14022 if let Some(autoscroll) = autoscroll {
14023 self.request_autoscroll(autoscroll, cx);
14024 }
14025 cx.notify();
14026 blocks
14027 }
14028
14029 pub fn resize_blocks(
14030 &mut self,
14031 heights: HashMap<CustomBlockId, u32>,
14032 autoscroll: Option<Autoscroll>,
14033 cx: &mut Context<Self>,
14034 ) {
14035 self.display_map
14036 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14037 if let Some(autoscroll) = autoscroll {
14038 self.request_autoscroll(autoscroll, cx);
14039 }
14040 cx.notify();
14041 }
14042
14043 pub fn replace_blocks(
14044 &mut self,
14045 renderers: HashMap<CustomBlockId, RenderBlock>,
14046 autoscroll: Option<Autoscroll>,
14047 cx: &mut Context<Self>,
14048 ) {
14049 self.display_map
14050 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14051 if let Some(autoscroll) = autoscroll {
14052 self.request_autoscroll(autoscroll, cx);
14053 }
14054 cx.notify();
14055 }
14056
14057 pub fn remove_blocks(
14058 &mut self,
14059 block_ids: HashSet<CustomBlockId>,
14060 autoscroll: Option<Autoscroll>,
14061 cx: &mut Context<Self>,
14062 ) {
14063 self.display_map.update(cx, |display_map, cx| {
14064 display_map.remove_blocks(block_ids, cx)
14065 });
14066 if let Some(autoscroll) = autoscroll {
14067 self.request_autoscroll(autoscroll, cx);
14068 }
14069 cx.notify();
14070 }
14071
14072 pub fn row_for_block(
14073 &self,
14074 block_id: CustomBlockId,
14075 cx: &mut Context<Self>,
14076 ) -> Option<DisplayRow> {
14077 self.display_map
14078 .update(cx, |map, cx| map.row_for_block(block_id, cx))
14079 }
14080
14081 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14082 self.focused_block = Some(focused_block);
14083 }
14084
14085 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14086 self.focused_block.take()
14087 }
14088
14089 pub fn insert_creases(
14090 &mut self,
14091 creases: impl IntoIterator<Item = Crease<Anchor>>,
14092 cx: &mut Context<Self>,
14093 ) -> Vec<CreaseId> {
14094 self.display_map
14095 .update(cx, |map, cx| map.insert_creases(creases, cx))
14096 }
14097
14098 pub fn remove_creases(
14099 &mut self,
14100 ids: impl IntoIterator<Item = CreaseId>,
14101 cx: &mut Context<Self>,
14102 ) {
14103 self.display_map
14104 .update(cx, |map, cx| map.remove_creases(ids, cx));
14105 }
14106
14107 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14108 self.display_map
14109 .update(cx, |map, cx| map.snapshot(cx))
14110 .longest_row()
14111 }
14112
14113 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14114 self.display_map
14115 .update(cx, |map, cx| map.snapshot(cx))
14116 .max_point()
14117 }
14118
14119 pub fn text(&self, cx: &App) -> String {
14120 self.buffer.read(cx).read(cx).text()
14121 }
14122
14123 pub fn is_empty(&self, cx: &App) -> bool {
14124 self.buffer.read(cx).read(cx).is_empty()
14125 }
14126
14127 pub fn text_option(&self, cx: &App) -> Option<String> {
14128 let text = self.text(cx);
14129 let text = text.trim();
14130
14131 if text.is_empty() {
14132 return None;
14133 }
14134
14135 Some(text.to_string())
14136 }
14137
14138 pub fn set_text(
14139 &mut self,
14140 text: impl Into<Arc<str>>,
14141 window: &mut Window,
14142 cx: &mut Context<Self>,
14143 ) {
14144 self.transact(window, cx, |this, _, cx| {
14145 this.buffer
14146 .read(cx)
14147 .as_singleton()
14148 .expect("you can only call set_text on editors for singleton buffers")
14149 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14150 });
14151 }
14152
14153 pub fn display_text(&self, cx: &mut App) -> String {
14154 self.display_map
14155 .update(cx, |map, cx| map.snapshot(cx))
14156 .text()
14157 }
14158
14159 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14160 let mut wrap_guides = smallvec::smallvec![];
14161
14162 if self.show_wrap_guides == Some(false) {
14163 return wrap_guides;
14164 }
14165
14166 let settings = self.buffer.read(cx).language_settings(cx);
14167 if settings.show_wrap_guides {
14168 match self.soft_wrap_mode(cx) {
14169 SoftWrap::Column(soft_wrap) => {
14170 wrap_guides.push((soft_wrap as usize, true));
14171 }
14172 SoftWrap::Bounded(soft_wrap) => {
14173 wrap_guides.push((soft_wrap as usize, true));
14174 }
14175 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14176 }
14177 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14178 }
14179
14180 wrap_guides
14181 }
14182
14183 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14184 let settings = self.buffer.read(cx).language_settings(cx);
14185 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14186 match mode {
14187 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14188 SoftWrap::None
14189 }
14190 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14191 language_settings::SoftWrap::PreferredLineLength => {
14192 SoftWrap::Column(settings.preferred_line_length)
14193 }
14194 language_settings::SoftWrap::Bounded => {
14195 SoftWrap::Bounded(settings.preferred_line_length)
14196 }
14197 }
14198 }
14199
14200 pub fn set_soft_wrap_mode(
14201 &mut self,
14202 mode: language_settings::SoftWrap,
14203
14204 cx: &mut Context<Self>,
14205 ) {
14206 self.soft_wrap_mode_override = Some(mode);
14207 cx.notify();
14208 }
14209
14210 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14211 self.text_style_refinement = Some(style);
14212 }
14213
14214 /// called by the Element so we know what style we were most recently rendered with.
14215 pub(crate) fn set_style(
14216 &mut self,
14217 style: EditorStyle,
14218 window: &mut Window,
14219 cx: &mut Context<Self>,
14220 ) {
14221 let rem_size = window.rem_size();
14222 self.display_map.update(cx, |map, cx| {
14223 map.set_font(
14224 style.text.font(),
14225 style.text.font_size.to_pixels(rem_size),
14226 cx,
14227 )
14228 });
14229 self.style = Some(style);
14230 }
14231
14232 pub fn style(&self) -> Option<&EditorStyle> {
14233 self.style.as_ref()
14234 }
14235
14236 // Called by the element. This method is not designed to be called outside of the editor
14237 // element's layout code because it does not notify when rewrapping is computed synchronously.
14238 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14239 self.display_map
14240 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14241 }
14242
14243 pub fn set_soft_wrap(&mut self) {
14244 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14245 }
14246
14247 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14248 if self.soft_wrap_mode_override.is_some() {
14249 self.soft_wrap_mode_override.take();
14250 } else {
14251 let soft_wrap = match self.soft_wrap_mode(cx) {
14252 SoftWrap::GitDiff => return,
14253 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14254 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14255 language_settings::SoftWrap::None
14256 }
14257 };
14258 self.soft_wrap_mode_override = Some(soft_wrap);
14259 }
14260 cx.notify();
14261 }
14262
14263 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14264 let Some(workspace) = self.workspace() else {
14265 return;
14266 };
14267 let fs = workspace.read(cx).app_state().fs.clone();
14268 let current_show = TabBarSettings::get_global(cx).show;
14269 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14270 setting.show = Some(!current_show);
14271 });
14272 }
14273
14274 pub fn toggle_indent_guides(
14275 &mut self,
14276 _: &ToggleIndentGuides,
14277 _: &mut Window,
14278 cx: &mut Context<Self>,
14279 ) {
14280 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14281 self.buffer
14282 .read(cx)
14283 .language_settings(cx)
14284 .indent_guides
14285 .enabled
14286 });
14287 self.show_indent_guides = Some(!currently_enabled);
14288 cx.notify();
14289 }
14290
14291 fn should_show_indent_guides(&self) -> Option<bool> {
14292 self.show_indent_guides
14293 }
14294
14295 pub fn toggle_line_numbers(
14296 &mut self,
14297 _: &ToggleLineNumbers,
14298 _: &mut Window,
14299 cx: &mut Context<Self>,
14300 ) {
14301 let mut editor_settings = EditorSettings::get_global(cx).clone();
14302 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14303 EditorSettings::override_global(editor_settings, cx);
14304 }
14305
14306 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14307 self.use_relative_line_numbers
14308 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14309 }
14310
14311 pub fn toggle_relative_line_numbers(
14312 &mut self,
14313 _: &ToggleRelativeLineNumbers,
14314 _: &mut Window,
14315 cx: &mut Context<Self>,
14316 ) {
14317 let is_relative = self.should_use_relative_line_numbers(cx);
14318 self.set_relative_line_number(Some(!is_relative), cx)
14319 }
14320
14321 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14322 self.use_relative_line_numbers = is_relative;
14323 cx.notify();
14324 }
14325
14326 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14327 self.show_gutter = show_gutter;
14328 cx.notify();
14329 }
14330
14331 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14332 self.show_scrollbars = show_scrollbars;
14333 cx.notify();
14334 }
14335
14336 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14337 self.show_line_numbers = Some(show_line_numbers);
14338 cx.notify();
14339 }
14340
14341 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14342 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14343 cx.notify();
14344 }
14345
14346 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14347 self.show_code_actions = Some(show_code_actions);
14348 cx.notify();
14349 }
14350
14351 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14352 self.show_runnables = Some(show_runnables);
14353 cx.notify();
14354 }
14355
14356 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14357 if self.display_map.read(cx).masked != masked {
14358 self.display_map.update(cx, |map, _| map.masked = masked);
14359 }
14360 cx.notify()
14361 }
14362
14363 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14364 self.show_wrap_guides = Some(show_wrap_guides);
14365 cx.notify();
14366 }
14367
14368 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14369 self.show_indent_guides = Some(show_indent_guides);
14370 cx.notify();
14371 }
14372
14373 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14374 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14375 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14376 if let Some(dir) = file.abs_path(cx).parent() {
14377 return Some(dir.to_owned());
14378 }
14379 }
14380
14381 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14382 return Some(project_path.path.to_path_buf());
14383 }
14384 }
14385
14386 None
14387 }
14388
14389 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14390 self.active_excerpt(cx)?
14391 .1
14392 .read(cx)
14393 .file()
14394 .and_then(|f| f.as_local())
14395 }
14396
14397 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14398 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14399 let buffer = buffer.read(cx);
14400 if let Some(project_path) = buffer.project_path(cx) {
14401 let project = self.project.as_ref()?.read(cx);
14402 project.absolute_path(&project_path, cx)
14403 } else {
14404 buffer
14405 .file()
14406 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14407 }
14408 })
14409 }
14410
14411 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14412 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14413 let project_path = buffer.read(cx).project_path(cx)?;
14414 let project = self.project.as_ref()?.read(cx);
14415 let entry = project.entry_for_path(&project_path, cx)?;
14416 let path = entry.path.to_path_buf();
14417 Some(path)
14418 })
14419 }
14420
14421 pub fn reveal_in_finder(
14422 &mut self,
14423 _: &RevealInFileManager,
14424 _window: &mut Window,
14425 cx: &mut Context<Self>,
14426 ) {
14427 if let Some(target) = self.target_file(cx) {
14428 cx.reveal_path(&target.abs_path(cx));
14429 }
14430 }
14431
14432 pub fn copy_path(
14433 &mut self,
14434 _: &zed_actions::workspace::CopyPath,
14435 _window: &mut Window,
14436 cx: &mut Context<Self>,
14437 ) {
14438 if let Some(path) = self.target_file_abs_path(cx) {
14439 if let Some(path) = path.to_str() {
14440 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14441 }
14442 }
14443 }
14444
14445 pub fn copy_relative_path(
14446 &mut self,
14447 _: &zed_actions::workspace::CopyRelativePath,
14448 _window: &mut Window,
14449 cx: &mut Context<Self>,
14450 ) {
14451 if let Some(path) = self.target_file_path(cx) {
14452 if let Some(path) = path.to_str() {
14453 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14454 }
14455 }
14456 }
14457
14458 pub fn copy_file_name_without_extension(
14459 &mut self,
14460 _: &CopyFileNameWithoutExtension,
14461 _: &mut Window,
14462 cx: &mut Context<Self>,
14463 ) {
14464 if let Some(file) = self.target_file(cx) {
14465 if let Some(file_stem) = file.path().file_stem() {
14466 if let Some(name) = file_stem.to_str() {
14467 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14468 }
14469 }
14470 }
14471 }
14472
14473 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14474 if let Some(file) = self.target_file(cx) {
14475 if let Some(file_name) = file.path().file_name() {
14476 if let Some(name) = file_name.to_str() {
14477 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14478 }
14479 }
14480 }
14481 }
14482
14483 pub fn toggle_git_blame(
14484 &mut self,
14485 _: &ToggleGitBlame,
14486 window: &mut Window,
14487 cx: &mut Context<Self>,
14488 ) {
14489 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14490
14491 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14492 self.start_git_blame(true, window, cx);
14493 }
14494
14495 cx.notify();
14496 }
14497
14498 pub fn toggle_git_blame_inline(
14499 &mut self,
14500 _: &ToggleGitBlameInline,
14501 window: &mut Window,
14502 cx: &mut Context<Self>,
14503 ) {
14504 self.toggle_git_blame_inline_internal(true, window, cx);
14505 cx.notify();
14506 }
14507
14508 pub fn git_blame_inline_enabled(&self) -> bool {
14509 self.git_blame_inline_enabled
14510 }
14511
14512 pub fn toggle_selection_menu(
14513 &mut self,
14514 _: &ToggleSelectionMenu,
14515 _: &mut Window,
14516 cx: &mut Context<Self>,
14517 ) {
14518 self.show_selection_menu = self
14519 .show_selection_menu
14520 .map(|show_selections_menu| !show_selections_menu)
14521 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14522
14523 cx.notify();
14524 }
14525
14526 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14527 self.show_selection_menu
14528 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14529 }
14530
14531 fn start_git_blame(
14532 &mut self,
14533 user_triggered: bool,
14534 window: &mut Window,
14535 cx: &mut Context<Self>,
14536 ) {
14537 if let Some(project) = self.project.as_ref() {
14538 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14539 return;
14540 };
14541
14542 if buffer.read(cx).file().is_none() {
14543 return;
14544 }
14545
14546 let focused = self.focus_handle(cx).contains_focused(window, cx);
14547
14548 let project = project.clone();
14549 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14550 self.blame_subscription =
14551 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14552 self.blame = Some(blame);
14553 }
14554 }
14555
14556 fn toggle_git_blame_inline_internal(
14557 &mut self,
14558 user_triggered: bool,
14559 window: &mut Window,
14560 cx: &mut Context<Self>,
14561 ) {
14562 if self.git_blame_inline_enabled {
14563 self.git_blame_inline_enabled = false;
14564 self.show_git_blame_inline = false;
14565 self.show_git_blame_inline_delay_task.take();
14566 } else {
14567 self.git_blame_inline_enabled = true;
14568 self.start_git_blame_inline(user_triggered, window, cx);
14569 }
14570
14571 cx.notify();
14572 }
14573
14574 fn start_git_blame_inline(
14575 &mut self,
14576 user_triggered: bool,
14577 window: &mut Window,
14578 cx: &mut Context<Self>,
14579 ) {
14580 self.start_git_blame(user_triggered, window, cx);
14581
14582 if ProjectSettings::get_global(cx)
14583 .git
14584 .inline_blame_delay()
14585 .is_some()
14586 {
14587 self.start_inline_blame_timer(window, cx);
14588 } else {
14589 self.show_git_blame_inline = true
14590 }
14591 }
14592
14593 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14594 self.blame.as_ref()
14595 }
14596
14597 pub fn show_git_blame_gutter(&self) -> bool {
14598 self.show_git_blame_gutter
14599 }
14600
14601 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14602 self.show_git_blame_gutter && self.has_blame_entries(cx)
14603 }
14604
14605 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14606 self.show_git_blame_inline
14607 && (self.focus_handle.is_focused(window)
14608 || self
14609 .git_blame_inline_tooltip
14610 .as_ref()
14611 .and_then(|t| t.upgrade())
14612 .is_some())
14613 && !self.newest_selection_head_on_empty_line(cx)
14614 && self.has_blame_entries(cx)
14615 }
14616
14617 fn has_blame_entries(&self, cx: &App) -> bool {
14618 self.blame()
14619 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14620 }
14621
14622 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14623 let cursor_anchor = self.selections.newest_anchor().head();
14624
14625 let snapshot = self.buffer.read(cx).snapshot(cx);
14626 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14627
14628 snapshot.line_len(buffer_row) == 0
14629 }
14630
14631 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14632 let buffer_and_selection = maybe!({
14633 let selection = self.selections.newest::<Point>(cx);
14634 let selection_range = selection.range();
14635
14636 let multi_buffer = self.buffer().read(cx);
14637 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14638 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14639
14640 let (buffer, range, _) = if selection.reversed {
14641 buffer_ranges.first()
14642 } else {
14643 buffer_ranges.last()
14644 }?;
14645
14646 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14647 ..text::ToPoint::to_point(&range.end, &buffer).row;
14648 Some((
14649 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14650 selection,
14651 ))
14652 });
14653
14654 let Some((buffer, selection)) = buffer_and_selection else {
14655 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14656 };
14657
14658 let Some(project) = self.project.as_ref() else {
14659 return Task::ready(Err(anyhow!("editor does not have project")));
14660 };
14661
14662 project.update(cx, |project, cx| {
14663 project.get_permalink_to_line(&buffer, selection, cx)
14664 })
14665 }
14666
14667 pub fn copy_permalink_to_line(
14668 &mut self,
14669 _: &CopyPermalinkToLine,
14670 window: &mut Window,
14671 cx: &mut Context<Self>,
14672 ) {
14673 let permalink_task = self.get_permalink_to_line(cx);
14674 let workspace = self.workspace();
14675
14676 cx.spawn_in(window, |_, mut cx| async move {
14677 match permalink_task.await {
14678 Ok(permalink) => {
14679 cx.update(|_, cx| {
14680 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14681 })
14682 .ok();
14683 }
14684 Err(err) => {
14685 let message = format!("Failed to copy permalink: {err}");
14686
14687 Err::<(), anyhow::Error>(err).log_err();
14688
14689 if let Some(workspace) = workspace {
14690 workspace
14691 .update_in(&mut cx, |workspace, _, cx| {
14692 struct CopyPermalinkToLine;
14693
14694 workspace.show_toast(
14695 Toast::new(
14696 NotificationId::unique::<CopyPermalinkToLine>(),
14697 message,
14698 ),
14699 cx,
14700 )
14701 })
14702 .ok();
14703 }
14704 }
14705 }
14706 })
14707 .detach();
14708 }
14709
14710 pub fn copy_file_location(
14711 &mut self,
14712 _: &CopyFileLocation,
14713 _: &mut Window,
14714 cx: &mut Context<Self>,
14715 ) {
14716 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14717 if let Some(file) = self.target_file(cx) {
14718 if let Some(path) = file.path().to_str() {
14719 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14720 }
14721 }
14722 }
14723
14724 pub fn open_permalink_to_line(
14725 &mut self,
14726 _: &OpenPermalinkToLine,
14727 window: &mut Window,
14728 cx: &mut Context<Self>,
14729 ) {
14730 let permalink_task = self.get_permalink_to_line(cx);
14731 let workspace = self.workspace();
14732
14733 cx.spawn_in(window, |_, mut cx| async move {
14734 match permalink_task.await {
14735 Ok(permalink) => {
14736 cx.update(|_, cx| {
14737 cx.open_url(permalink.as_ref());
14738 })
14739 .ok();
14740 }
14741 Err(err) => {
14742 let message = format!("Failed to open permalink: {err}");
14743
14744 Err::<(), anyhow::Error>(err).log_err();
14745
14746 if let Some(workspace) = workspace {
14747 workspace
14748 .update(&mut cx, |workspace, cx| {
14749 struct OpenPermalinkToLine;
14750
14751 workspace.show_toast(
14752 Toast::new(
14753 NotificationId::unique::<OpenPermalinkToLine>(),
14754 message,
14755 ),
14756 cx,
14757 )
14758 })
14759 .ok();
14760 }
14761 }
14762 }
14763 })
14764 .detach();
14765 }
14766
14767 pub fn insert_uuid_v4(
14768 &mut self,
14769 _: &InsertUuidV4,
14770 window: &mut Window,
14771 cx: &mut Context<Self>,
14772 ) {
14773 self.insert_uuid(UuidVersion::V4, window, cx);
14774 }
14775
14776 pub fn insert_uuid_v7(
14777 &mut self,
14778 _: &InsertUuidV7,
14779 window: &mut Window,
14780 cx: &mut Context<Self>,
14781 ) {
14782 self.insert_uuid(UuidVersion::V7, window, cx);
14783 }
14784
14785 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14786 self.transact(window, cx, |this, window, cx| {
14787 let edits = this
14788 .selections
14789 .all::<Point>(cx)
14790 .into_iter()
14791 .map(|selection| {
14792 let uuid = match version {
14793 UuidVersion::V4 => uuid::Uuid::new_v4(),
14794 UuidVersion::V7 => uuid::Uuid::now_v7(),
14795 };
14796
14797 (selection.range(), uuid.to_string())
14798 });
14799 this.edit(edits, cx);
14800 this.refresh_inline_completion(true, false, window, cx);
14801 });
14802 }
14803
14804 pub fn open_selections_in_multibuffer(
14805 &mut self,
14806 _: &OpenSelectionsInMultibuffer,
14807 window: &mut Window,
14808 cx: &mut Context<Self>,
14809 ) {
14810 let multibuffer = self.buffer.read(cx);
14811
14812 let Some(buffer) = multibuffer.as_singleton() else {
14813 return;
14814 };
14815
14816 let Some(workspace) = self.workspace() else {
14817 return;
14818 };
14819
14820 let locations = self
14821 .selections
14822 .disjoint_anchors()
14823 .iter()
14824 .map(|range| Location {
14825 buffer: buffer.clone(),
14826 range: range.start.text_anchor..range.end.text_anchor,
14827 })
14828 .collect::<Vec<_>>();
14829
14830 let title = multibuffer.title(cx).to_string();
14831
14832 cx.spawn_in(window, |_, mut cx| async move {
14833 workspace.update_in(&mut cx, |workspace, window, cx| {
14834 Self::open_locations_in_multibuffer(
14835 workspace,
14836 locations,
14837 format!("Selections for '{title}'"),
14838 false,
14839 MultibufferSelectionMode::All,
14840 window,
14841 cx,
14842 );
14843 })
14844 })
14845 .detach();
14846 }
14847
14848 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14849 /// last highlight added will be used.
14850 ///
14851 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14852 pub fn highlight_rows<T: 'static>(
14853 &mut self,
14854 range: Range<Anchor>,
14855 color: Hsla,
14856 should_autoscroll: bool,
14857 cx: &mut Context<Self>,
14858 ) {
14859 let snapshot = self.buffer().read(cx).snapshot(cx);
14860 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14861 let ix = row_highlights.binary_search_by(|highlight| {
14862 Ordering::Equal
14863 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14864 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14865 });
14866
14867 if let Err(mut ix) = ix {
14868 let index = post_inc(&mut self.highlight_order);
14869
14870 // If this range intersects with the preceding highlight, then merge it with
14871 // the preceding highlight. Otherwise insert a new highlight.
14872 let mut merged = false;
14873 if ix > 0 {
14874 let prev_highlight = &mut row_highlights[ix - 1];
14875 if prev_highlight
14876 .range
14877 .end
14878 .cmp(&range.start, &snapshot)
14879 .is_ge()
14880 {
14881 ix -= 1;
14882 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14883 prev_highlight.range.end = range.end;
14884 }
14885 merged = true;
14886 prev_highlight.index = index;
14887 prev_highlight.color = color;
14888 prev_highlight.should_autoscroll = should_autoscroll;
14889 }
14890 }
14891
14892 if !merged {
14893 row_highlights.insert(
14894 ix,
14895 RowHighlight {
14896 range: range.clone(),
14897 index,
14898 color,
14899 should_autoscroll,
14900 },
14901 );
14902 }
14903
14904 // If any of the following highlights intersect with this one, merge them.
14905 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14906 let highlight = &row_highlights[ix];
14907 if next_highlight
14908 .range
14909 .start
14910 .cmp(&highlight.range.end, &snapshot)
14911 .is_le()
14912 {
14913 if next_highlight
14914 .range
14915 .end
14916 .cmp(&highlight.range.end, &snapshot)
14917 .is_gt()
14918 {
14919 row_highlights[ix].range.end = next_highlight.range.end;
14920 }
14921 row_highlights.remove(ix + 1);
14922 } else {
14923 break;
14924 }
14925 }
14926 }
14927 }
14928
14929 /// Remove any highlighted row ranges of the given type that intersect the
14930 /// given ranges.
14931 pub fn remove_highlighted_rows<T: 'static>(
14932 &mut self,
14933 ranges_to_remove: Vec<Range<Anchor>>,
14934 cx: &mut Context<Self>,
14935 ) {
14936 let snapshot = self.buffer().read(cx).snapshot(cx);
14937 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14938 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14939 row_highlights.retain(|highlight| {
14940 while let Some(range_to_remove) = ranges_to_remove.peek() {
14941 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14942 Ordering::Less | Ordering::Equal => {
14943 ranges_to_remove.next();
14944 }
14945 Ordering::Greater => {
14946 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14947 Ordering::Less | Ordering::Equal => {
14948 return false;
14949 }
14950 Ordering::Greater => break,
14951 }
14952 }
14953 }
14954 }
14955
14956 true
14957 })
14958 }
14959
14960 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14961 pub fn clear_row_highlights<T: 'static>(&mut self) {
14962 self.highlighted_rows.remove(&TypeId::of::<T>());
14963 }
14964
14965 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14966 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14967 self.highlighted_rows
14968 .get(&TypeId::of::<T>())
14969 .map_or(&[] as &[_], |vec| vec.as_slice())
14970 .iter()
14971 .map(|highlight| (highlight.range.clone(), highlight.color))
14972 }
14973
14974 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14975 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14976 /// Allows to ignore certain kinds of highlights.
14977 pub fn highlighted_display_rows(
14978 &self,
14979 window: &mut Window,
14980 cx: &mut App,
14981 ) -> BTreeMap<DisplayRow, LineHighlight> {
14982 let snapshot = self.snapshot(window, cx);
14983 let mut used_highlight_orders = HashMap::default();
14984 self.highlighted_rows
14985 .iter()
14986 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14987 .fold(
14988 BTreeMap::<DisplayRow, LineHighlight>::new(),
14989 |mut unique_rows, highlight| {
14990 let start = highlight.range.start.to_display_point(&snapshot);
14991 let end = highlight.range.end.to_display_point(&snapshot);
14992 let start_row = start.row().0;
14993 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14994 && end.column() == 0
14995 {
14996 end.row().0.saturating_sub(1)
14997 } else {
14998 end.row().0
14999 };
15000 for row in start_row..=end_row {
15001 let used_index =
15002 used_highlight_orders.entry(row).or_insert(highlight.index);
15003 if highlight.index >= *used_index {
15004 *used_index = highlight.index;
15005 unique_rows.insert(DisplayRow(row), highlight.color.into());
15006 }
15007 }
15008 unique_rows
15009 },
15010 )
15011 }
15012
15013 pub fn highlighted_display_row_for_autoscroll(
15014 &self,
15015 snapshot: &DisplaySnapshot,
15016 ) -> Option<DisplayRow> {
15017 self.highlighted_rows
15018 .values()
15019 .flat_map(|highlighted_rows| highlighted_rows.iter())
15020 .filter_map(|highlight| {
15021 if highlight.should_autoscroll {
15022 Some(highlight.range.start.to_display_point(snapshot).row())
15023 } else {
15024 None
15025 }
15026 })
15027 .min()
15028 }
15029
15030 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15031 self.highlight_background::<SearchWithinRange>(
15032 ranges,
15033 |colors| colors.editor_document_highlight_read_background,
15034 cx,
15035 )
15036 }
15037
15038 pub fn set_breadcrumb_header(&mut self, new_header: String) {
15039 self.breadcrumb_header = Some(new_header);
15040 }
15041
15042 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15043 self.clear_background_highlights::<SearchWithinRange>(cx);
15044 }
15045
15046 pub fn highlight_background<T: 'static>(
15047 &mut self,
15048 ranges: &[Range<Anchor>],
15049 color_fetcher: fn(&ThemeColors) -> Hsla,
15050 cx: &mut Context<Self>,
15051 ) {
15052 self.background_highlights
15053 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15054 self.scrollbar_marker_state.dirty = true;
15055 cx.notify();
15056 }
15057
15058 pub fn clear_background_highlights<T: 'static>(
15059 &mut self,
15060 cx: &mut Context<Self>,
15061 ) -> Option<BackgroundHighlight> {
15062 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15063 if !text_highlights.1.is_empty() {
15064 self.scrollbar_marker_state.dirty = true;
15065 cx.notify();
15066 }
15067 Some(text_highlights)
15068 }
15069
15070 pub fn highlight_gutter<T: 'static>(
15071 &mut self,
15072 ranges: &[Range<Anchor>],
15073 color_fetcher: fn(&App) -> Hsla,
15074 cx: &mut Context<Self>,
15075 ) {
15076 self.gutter_highlights
15077 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15078 cx.notify();
15079 }
15080
15081 pub fn clear_gutter_highlights<T: 'static>(
15082 &mut self,
15083 cx: &mut Context<Self>,
15084 ) -> Option<GutterHighlight> {
15085 cx.notify();
15086 self.gutter_highlights.remove(&TypeId::of::<T>())
15087 }
15088
15089 #[cfg(feature = "test-support")]
15090 pub fn all_text_background_highlights(
15091 &self,
15092 window: &mut Window,
15093 cx: &mut Context<Self>,
15094 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15095 let snapshot = self.snapshot(window, cx);
15096 let buffer = &snapshot.buffer_snapshot;
15097 let start = buffer.anchor_before(0);
15098 let end = buffer.anchor_after(buffer.len());
15099 let theme = cx.theme().colors();
15100 self.background_highlights_in_range(start..end, &snapshot, theme)
15101 }
15102
15103 #[cfg(feature = "test-support")]
15104 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15105 let snapshot = self.buffer().read(cx).snapshot(cx);
15106
15107 let highlights = self
15108 .background_highlights
15109 .get(&TypeId::of::<items::BufferSearchHighlights>());
15110
15111 if let Some((_color, ranges)) = highlights {
15112 ranges
15113 .iter()
15114 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15115 .collect_vec()
15116 } else {
15117 vec![]
15118 }
15119 }
15120
15121 fn document_highlights_for_position<'a>(
15122 &'a self,
15123 position: Anchor,
15124 buffer: &'a MultiBufferSnapshot,
15125 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15126 let read_highlights = self
15127 .background_highlights
15128 .get(&TypeId::of::<DocumentHighlightRead>())
15129 .map(|h| &h.1);
15130 let write_highlights = self
15131 .background_highlights
15132 .get(&TypeId::of::<DocumentHighlightWrite>())
15133 .map(|h| &h.1);
15134 let left_position = position.bias_left(buffer);
15135 let right_position = position.bias_right(buffer);
15136 read_highlights
15137 .into_iter()
15138 .chain(write_highlights)
15139 .flat_map(move |ranges| {
15140 let start_ix = match ranges.binary_search_by(|probe| {
15141 let cmp = probe.end.cmp(&left_position, buffer);
15142 if cmp.is_ge() {
15143 Ordering::Greater
15144 } else {
15145 Ordering::Less
15146 }
15147 }) {
15148 Ok(i) | Err(i) => i,
15149 };
15150
15151 ranges[start_ix..]
15152 .iter()
15153 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15154 })
15155 }
15156
15157 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15158 self.background_highlights
15159 .get(&TypeId::of::<T>())
15160 .map_or(false, |(_, highlights)| !highlights.is_empty())
15161 }
15162
15163 pub fn background_highlights_in_range(
15164 &self,
15165 search_range: Range<Anchor>,
15166 display_snapshot: &DisplaySnapshot,
15167 theme: &ThemeColors,
15168 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15169 let mut results = Vec::new();
15170 for (color_fetcher, ranges) in self.background_highlights.values() {
15171 let color = color_fetcher(theme);
15172 let start_ix = match ranges.binary_search_by(|probe| {
15173 let cmp = probe
15174 .end
15175 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15176 if cmp.is_gt() {
15177 Ordering::Greater
15178 } else {
15179 Ordering::Less
15180 }
15181 }) {
15182 Ok(i) | Err(i) => i,
15183 };
15184 for range in &ranges[start_ix..] {
15185 if range
15186 .start
15187 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15188 .is_ge()
15189 {
15190 break;
15191 }
15192
15193 let start = range.start.to_display_point(display_snapshot);
15194 let end = range.end.to_display_point(display_snapshot);
15195 results.push((start..end, color))
15196 }
15197 }
15198 results
15199 }
15200
15201 pub fn background_highlight_row_ranges<T: 'static>(
15202 &self,
15203 search_range: Range<Anchor>,
15204 display_snapshot: &DisplaySnapshot,
15205 count: usize,
15206 ) -> Vec<RangeInclusive<DisplayPoint>> {
15207 let mut results = Vec::new();
15208 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15209 return vec![];
15210 };
15211
15212 let start_ix = match ranges.binary_search_by(|probe| {
15213 let cmp = probe
15214 .end
15215 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15216 if cmp.is_gt() {
15217 Ordering::Greater
15218 } else {
15219 Ordering::Less
15220 }
15221 }) {
15222 Ok(i) | Err(i) => i,
15223 };
15224 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15225 if let (Some(start_display), Some(end_display)) = (start, end) {
15226 results.push(
15227 start_display.to_display_point(display_snapshot)
15228 ..=end_display.to_display_point(display_snapshot),
15229 );
15230 }
15231 };
15232 let mut start_row: Option<Point> = None;
15233 let mut end_row: Option<Point> = None;
15234 if ranges.len() > count {
15235 return Vec::new();
15236 }
15237 for range in &ranges[start_ix..] {
15238 if range
15239 .start
15240 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15241 .is_ge()
15242 {
15243 break;
15244 }
15245 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15246 if let Some(current_row) = &end_row {
15247 if end.row == current_row.row {
15248 continue;
15249 }
15250 }
15251 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15252 if start_row.is_none() {
15253 assert_eq!(end_row, None);
15254 start_row = Some(start);
15255 end_row = Some(end);
15256 continue;
15257 }
15258 if let Some(current_end) = end_row.as_mut() {
15259 if start.row > current_end.row + 1 {
15260 push_region(start_row, end_row);
15261 start_row = Some(start);
15262 end_row = Some(end);
15263 } else {
15264 // Merge two hunks.
15265 *current_end = end;
15266 }
15267 } else {
15268 unreachable!();
15269 }
15270 }
15271 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15272 push_region(start_row, end_row);
15273 results
15274 }
15275
15276 pub fn gutter_highlights_in_range(
15277 &self,
15278 search_range: Range<Anchor>,
15279 display_snapshot: &DisplaySnapshot,
15280 cx: &App,
15281 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15282 let mut results = Vec::new();
15283 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15284 let color = color_fetcher(cx);
15285 let start_ix = match ranges.binary_search_by(|probe| {
15286 let cmp = probe
15287 .end
15288 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15289 if cmp.is_gt() {
15290 Ordering::Greater
15291 } else {
15292 Ordering::Less
15293 }
15294 }) {
15295 Ok(i) | Err(i) => i,
15296 };
15297 for range in &ranges[start_ix..] {
15298 if range
15299 .start
15300 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15301 .is_ge()
15302 {
15303 break;
15304 }
15305
15306 let start = range.start.to_display_point(display_snapshot);
15307 let end = range.end.to_display_point(display_snapshot);
15308 results.push((start..end, color))
15309 }
15310 }
15311 results
15312 }
15313
15314 /// Get the text ranges corresponding to the redaction query
15315 pub fn redacted_ranges(
15316 &self,
15317 search_range: Range<Anchor>,
15318 display_snapshot: &DisplaySnapshot,
15319 cx: &App,
15320 ) -> Vec<Range<DisplayPoint>> {
15321 display_snapshot
15322 .buffer_snapshot
15323 .redacted_ranges(search_range, |file| {
15324 if let Some(file) = file {
15325 file.is_private()
15326 && EditorSettings::get(
15327 Some(SettingsLocation {
15328 worktree_id: file.worktree_id(cx),
15329 path: file.path().as_ref(),
15330 }),
15331 cx,
15332 )
15333 .redact_private_values
15334 } else {
15335 false
15336 }
15337 })
15338 .map(|range| {
15339 range.start.to_display_point(display_snapshot)
15340 ..range.end.to_display_point(display_snapshot)
15341 })
15342 .collect()
15343 }
15344
15345 pub fn highlight_text<T: 'static>(
15346 &mut self,
15347 ranges: Vec<Range<Anchor>>,
15348 style: HighlightStyle,
15349 cx: &mut Context<Self>,
15350 ) {
15351 self.display_map.update(cx, |map, _| {
15352 map.highlight_text(TypeId::of::<T>(), ranges, style)
15353 });
15354 cx.notify();
15355 }
15356
15357 pub(crate) fn highlight_inlays<T: 'static>(
15358 &mut self,
15359 highlights: Vec<InlayHighlight>,
15360 style: HighlightStyle,
15361 cx: &mut Context<Self>,
15362 ) {
15363 self.display_map.update(cx, |map, _| {
15364 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15365 });
15366 cx.notify();
15367 }
15368
15369 pub fn text_highlights<'a, T: 'static>(
15370 &'a self,
15371 cx: &'a App,
15372 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15373 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15374 }
15375
15376 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15377 let cleared = self
15378 .display_map
15379 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15380 if cleared {
15381 cx.notify();
15382 }
15383 }
15384
15385 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15386 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15387 && self.focus_handle.is_focused(window)
15388 }
15389
15390 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15391 self.show_cursor_when_unfocused = is_enabled;
15392 cx.notify();
15393 }
15394
15395 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15396 cx.notify();
15397 }
15398
15399 fn on_buffer_event(
15400 &mut self,
15401 multibuffer: &Entity<MultiBuffer>,
15402 event: &multi_buffer::Event,
15403 window: &mut Window,
15404 cx: &mut Context<Self>,
15405 ) {
15406 match event {
15407 multi_buffer::Event::Edited {
15408 singleton_buffer_edited,
15409 edited_buffer: buffer_edited,
15410 } => {
15411 self.scrollbar_marker_state.dirty = true;
15412 self.active_indent_guides_state.dirty = true;
15413 self.refresh_active_diagnostics(cx);
15414 self.refresh_code_actions(window, cx);
15415 if self.has_active_inline_completion() {
15416 self.update_visible_inline_completion(window, cx);
15417 }
15418 if let Some(buffer) = buffer_edited {
15419 let buffer_id = buffer.read(cx).remote_id();
15420 if !self.registered_buffers.contains_key(&buffer_id) {
15421 if let Some(project) = self.project.as_ref() {
15422 project.update(cx, |project, cx| {
15423 self.registered_buffers.insert(
15424 buffer_id,
15425 project.register_buffer_with_language_servers(&buffer, cx),
15426 );
15427 })
15428 }
15429 }
15430 }
15431 cx.emit(EditorEvent::BufferEdited);
15432 cx.emit(SearchEvent::MatchesInvalidated);
15433 if *singleton_buffer_edited {
15434 if let Some(project) = &self.project {
15435 #[allow(clippy::mutable_key_type)]
15436 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15437 multibuffer
15438 .all_buffers()
15439 .into_iter()
15440 .filter_map(|buffer| {
15441 buffer.update(cx, |buffer, cx| {
15442 let language = buffer.language()?;
15443 let should_discard = project.update(cx, |project, cx| {
15444 project.is_local()
15445 && !project.has_language_servers_for(buffer, cx)
15446 });
15447 should_discard.not().then_some(language.clone())
15448 })
15449 })
15450 .collect::<HashSet<_>>()
15451 });
15452 if !languages_affected.is_empty() {
15453 self.refresh_inlay_hints(
15454 InlayHintRefreshReason::BufferEdited(languages_affected),
15455 cx,
15456 );
15457 }
15458 }
15459 }
15460
15461 let Some(project) = &self.project else { return };
15462 let (telemetry, is_via_ssh) = {
15463 let project = project.read(cx);
15464 let telemetry = project.client().telemetry().clone();
15465 let is_via_ssh = project.is_via_ssh();
15466 (telemetry, is_via_ssh)
15467 };
15468 refresh_linked_ranges(self, window, cx);
15469 telemetry.log_edit_event("editor", is_via_ssh);
15470 }
15471 multi_buffer::Event::ExcerptsAdded {
15472 buffer,
15473 predecessor,
15474 excerpts,
15475 } => {
15476 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15477 let buffer_id = buffer.read(cx).remote_id();
15478 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15479 if let Some(project) = &self.project {
15480 get_uncommitted_diff_for_buffer(
15481 project,
15482 [buffer.clone()],
15483 self.buffer.clone(),
15484 cx,
15485 )
15486 .detach();
15487 }
15488 }
15489 cx.emit(EditorEvent::ExcerptsAdded {
15490 buffer: buffer.clone(),
15491 predecessor: *predecessor,
15492 excerpts: excerpts.clone(),
15493 });
15494 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15495 }
15496 multi_buffer::Event::ExcerptsRemoved { ids } => {
15497 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15498 let buffer = self.buffer.read(cx);
15499 self.registered_buffers
15500 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15501 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15502 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15503 }
15504 multi_buffer::Event::ExcerptsEdited {
15505 excerpt_ids,
15506 buffer_ids,
15507 } => {
15508 self.display_map.update(cx, |map, cx| {
15509 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15510 });
15511 cx.emit(EditorEvent::ExcerptsEdited {
15512 ids: excerpt_ids.clone(),
15513 })
15514 }
15515 multi_buffer::Event::ExcerptsExpanded { ids } => {
15516 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15517 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15518 }
15519 multi_buffer::Event::Reparsed(buffer_id) => {
15520 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15521 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15522
15523 cx.emit(EditorEvent::Reparsed(*buffer_id));
15524 }
15525 multi_buffer::Event::DiffHunksToggled => {
15526 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15527 }
15528 multi_buffer::Event::LanguageChanged(buffer_id) => {
15529 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15530 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15531 cx.emit(EditorEvent::Reparsed(*buffer_id));
15532 cx.notify();
15533 }
15534 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15535 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15536 multi_buffer::Event::FileHandleChanged
15537 | multi_buffer::Event::Reloaded
15538 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15539 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15540 multi_buffer::Event::DiagnosticsUpdated => {
15541 self.refresh_active_diagnostics(cx);
15542 self.refresh_inline_diagnostics(true, window, cx);
15543 self.scrollbar_marker_state.dirty = true;
15544 cx.notify();
15545 }
15546 _ => {}
15547 };
15548 }
15549
15550 fn on_display_map_changed(
15551 &mut self,
15552 _: Entity<DisplayMap>,
15553 _: &mut Window,
15554 cx: &mut Context<Self>,
15555 ) {
15556 cx.notify();
15557 }
15558
15559 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15560 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15561 self.update_edit_prediction_settings(cx);
15562 self.refresh_inline_completion(true, false, window, cx);
15563 self.refresh_inlay_hints(
15564 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15565 self.selections.newest_anchor().head(),
15566 &self.buffer.read(cx).snapshot(cx),
15567 cx,
15568 )),
15569 cx,
15570 );
15571
15572 let old_cursor_shape = self.cursor_shape;
15573
15574 {
15575 let editor_settings = EditorSettings::get_global(cx);
15576 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15577 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15578 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15579 }
15580
15581 if old_cursor_shape != self.cursor_shape {
15582 cx.emit(EditorEvent::CursorShapeChanged);
15583 }
15584
15585 let project_settings = ProjectSettings::get_global(cx);
15586 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15587
15588 if self.mode == EditorMode::Full {
15589 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15590 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15591 if self.show_inline_diagnostics != show_inline_diagnostics {
15592 self.show_inline_diagnostics = show_inline_diagnostics;
15593 self.refresh_inline_diagnostics(false, window, cx);
15594 }
15595
15596 if self.git_blame_inline_enabled != inline_blame_enabled {
15597 self.toggle_git_blame_inline_internal(false, window, cx);
15598 }
15599 }
15600
15601 cx.notify();
15602 }
15603
15604 pub fn set_searchable(&mut self, searchable: bool) {
15605 self.searchable = searchable;
15606 }
15607
15608 pub fn searchable(&self) -> bool {
15609 self.searchable
15610 }
15611
15612 fn open_proposed_changes_editor(
15613 &mut self,
15614 _: &OpenProposedChangesEditor,
15615 window: &mut Window,
15616 cx: &mut Context<Self>,
15617 ) {
15618 let Some(workspace) = self.workspace() else {
15619 cx.propagate();
15620 return;
15621 };
15622
15623 let selections = self.selections.all::<usize>(cx);
15624 let multi_buffer = self.buffer.read(cx);
15625 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15626 let mut new_selections_by_buffer = HashMap::default();
15627 for selection in selections {
15628 for (buffer, range, _) in
15629 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15630 {
15631 let mut range = range.to_point(buffer);
15632 range.start.column = 0;
15633 range.end.column = buffer.line_len(range.end.row);
15634 new_selections_by_buffer
15635 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15636 .or_insert(Vec::new())
15637 .push(range)
15638 }
15639 }
15640
15641 let proposed_changes_buffers = new_selections_by_buffer
15642 .into_iter()
15643 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15644 .collect::<Vec<_>>();
15645 let proposed_changes_editor = cx.new(|cx| {
15646 ProposedChangesEditor::new(
15647 "Proposed changes",
15648 proposed_changes_buffers,
15649 self.project.clone(),
15650 window,
15651 cx,
15652 )
15653 });
15654
15655 window.defer(cx, move |window, cx| {
15656 workspace.update(cx, |workspace, cx| {
15657 workspace.active_pane().update(cx, |pane, cx| {
15658 pane.add_item(
15659 Box::new(proposed_changes_editor),
15660 true,
15661 true,
15662 None,
15663 window,
15664 cx,
15665 );
15666 });
15667 });
15668 });
15669 }
15670
15671 pub fn open_excerpts_in_split(
15672 &mut self,
15673 _: &OpenExcerptsSplit,
15674 window: &mut Window,
15675 cx: &mut Context<Self>,
15676 ) {
15677 self.open_excerpts_common(None, true, window, cx)
15678 }
15679
15680 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15681 self.open_excerpts_common(None, false, window, cx)
15682 }
15683
15684 fn open_excerpts_common(
15685 &mut self,
15686 jump_data: Option<JumpData>,
15687 split: bool,
15688 window: &mut Window,
15689 cx: &mut Context<Self>,
15690 ) {
15691 let Some(workspace) = self.workspace() else {
15692 cx.propagate();
15693 return;
15694 };
15695
15696 if self.buffer.read(cx).is_singleton() {
15697 cx.propagate();
15698 return;
15699 }
15700
15701 let mut new_selections_by_buffer = HashMap::default();
15702 match &jump_data {
15703 Some(JumpData::MultiBufferPoint {
15704 excerpt_id,
15705 position,
15706 anchor,
15707 line_offset_from_top,
15708 }) => {
15709 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15710 if let Some(buffer) = multi_buffer_snapshot
15711 .buffer_id_for_excerpt(*excerpt_id)
15712 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15713 {
15714 let buffer_snapshot = buffer.read(cx).snapshot();
15715 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15716 language::ToPoint::to_point(anchor, &buffer_snapshot)
15717 } else {
15718 buffer_snapshot.clip_point(*position, Bias::Left)
15719 };
15720 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15721 new_selections_by_buffer.insert(
15722 buffer,
15723 (
15724 vec![jump_to_offset..jump_to_offset],
15725 Some(*line_offset_from_top),
15726 ),
15727 );
15728 }
15729 }
15730 Some(JumpData::MultiBufferRow {
15731 row,
15732 line_offset_from_top,
15733 }) => {
15734 let point = MultiBufferPoint::new(row.0, 0);
15735 if let Some((buffer, buffer_point, _)) =
15736 self.buffer.read(cx).point_to_buffer_point(point, cx)
15737 {
15738 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15739 new_selections_by_buffer
15740 .entry(buffer)
15741 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15742 .0
15743 .push(buffer_offset..buffer_offset)
15744 }
15745 }
15746 None => {
15747 let selections = self.selections.all::<usize>(cx);
15748 let multi_buffer = self.buffer.read(cx);
15749 for selection in selections {
15750 for (snapshot, range, _, anchor) in multi_buffer
15751 .snapshot(cx)
15752 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15753 {
15754 if let Some(anchor) = anchor {
15755 // selection is in a deleted hunk
15756 let Some(buffer_id) = anchor.buffer_id else {
15757 continue;
15758 };
15759 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15760 continue;
15761 };
15762 let offset = text::ToOffset::to_offset(
15763 &anchor.text_anchor,
15764 &buffer_handle.read(cx).snapshot(),
15765 );
15766 let range = offset..offset;
15767 new_selections_by_buffer
15768 .entry(buffer_handle)
15769 .or_insert((Vec::new(), None))
15770 .0
15771 .push(range)
15772 } else {
15773 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15774 else {
15775 continue;
15776 };
15777 new_selections_by_buffer
15778 .entry(buffer_handle)
15779 .or_insert((Vec::new(), None))
15780 .0
15781 .push(range)
15782 }
15783 }
15784 }
15785 }
15786 }
15787
15788 if new_selections_by_buffer.is_empty() {
15789 return;
15790 }
15791
15792 // We defer the pane interaction because we ourselves are a workspace item
15793 // and activating a new item causes the pane to call a method on us reentrantly,
15794 // which panics if we're on the stack.
15795 window.defer(cx, move |window, cx| {
15796 workspace.update(cx, |workspace, cx| {
15797 let pane = if split {
15798 workspace.adjacent_pane(window, cx)
15799 } else {
15800 workspace.active_pane().clone()
15801 };
15802
15803 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15804 let editor = buffer
15805 .read(cx)
15806 .file()
15807 .is_none()
15808 .then(|| {
15809 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15810 // so `workspace.open_project_item` will never find them, always opening a new editor.
15811 // Instead, we try to activate the existing editor in the pane first.
15812 let (editor, pane_item_index) =
15813 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15814 let editor = item.downcast::<Editor>()?;
15815 let singleton_buffer =
15816 editor.read(cx).buffer().read(cx).as_singleton()?;
15817 if singleton_buffer == buffer {
15818 Some((editor, i))
15819 } else {
15820 None
15821 }
15822 })?;
15823 pane.update(cx, |pane, cx| {
15824 pane.activate_item(pane_item_index, true, true, window, cx)
15825 });
15826 Some(editor)
15827 })
15828 .flatten()
15829 .unwrap_or_else(|| {
15830 workspace.open_project_item::<Self>(
15831 pane.clone(),
15832 buffer,
15833 true,
15834 true,
15835 window,
15836 cx,
15837 )
15838 });
15839
15840 editor.update(cx, |editor, cx| {
15841 let autoscroll = match scroll_offset {
15842 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15843 None => Autoscroll::newest(),
15844 };
15845 let nav_history = editor.nav_history.take();
15846 editor.change_selections(Some(autoscroll), window, cx, |s| {
15847 s.select_ranges(ranges);
15848 });
15849 editor.nav_history = nav_history;
15850 });
15851 }
15852 })
15853 });
15854 }
15855
15856 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15857 let snapshot = self.buffer.read(cx).read(cx);
15858 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15859 Some(
15860 ranges
15861 .iter()
15862 .map(move |range| {
15863 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15864 })
15865 .collect(),
15866 )
15867 }
15868
15869 fn selection_replacement_ranges(
15870 &self,
15871 range: Range<OffsetUtf16>,
15872 cx: &mut App,
15873 ) -> Vec<Range<OffsetUtf16>> {
15874 let selections = self.selections.all::<OffsetUtf16>(cx);
15875 let newest_selection = selections
15876 .iter()
15877 .max_by_key(|selection| selection.id)
15878 .unwrap();
15879 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15880 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15881 let snapshot = self.buffer.read(cx).read(cx);
15882 selections
15883 .into_iter()
15884 .map(|mut selection| {
15885 selection.start.0 =
15886 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15887 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15888 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15889 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15890 })
15891 .collect()
15892 }
15893
15894 fn report_editor_event(
15895 &self,
15896 event_type: &'static str,
15897 file_extension: Option<String>,
15898 cx: &App,
15899 ) {
15900 if cfg!(any(test, feature = "test-support")) {
15901 return;
15902 }
15903
15904 let Some(project) = &self.project else { return };
15905
15906 // If None, we are in a file without an extension
15907 let file = self
15908 .buffer
15909 .read(cx)
15910 .as_singleton()
15911 .and_then(|b| b.read(cx).file());
15912 let file_extension = file_extension.or(file
15913 .as_ref()
15914 .and_then(|file| Path::new(file.file_name(cx)).extension())
15915 .and_then(|e| e.to_str())
15916 .map(|a| a.to_string()));
15917
15918 let vim_mode = cx
15919 .global::<SettingsStore>()
15920 .raw_user_settings()
15921 .get("vim_mode")
15922 == Some(&serde_json::Value::Bool(true));
15923
15924 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15925 let copilot_enabled = edit_predictions_provider
15926 == language::language_settings::EditPredictionProvider::Copilot;
15927 let copilot_enabled_for_language = self
15928 .buffer
15929 .read(cx)
15930 .language_settings(cx)
15931 .show_edit_predictions;
15932
15933 let project = project.read(cx);
15934 telemetry::event!(
15935 event_type,
15936 file_extension,
15937 vim_mode,
15938 copilot_enabled,
15939 copilot_enabled_for_language,
15940 edit_predictions_provider,
15941 is_via_ssh = project.is_via_ssh(),
15942 );
15943 }
15944
15945 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15946 /// with each line being an array of {text, highlight} objects.
15947 fn copy_highlight_json(
15948 &mut self,
15949 _: &CopyHighlightJson,
15950 window: &mut Window,
15951 cx: &mut Context<Self>,
15952 ) {
15953 #[derive(Serialize)]
15954 struct Chunk<'a> {
15955 text: String,
15956 highlight: Option<&'a str>,
15957 }
15958
15959 let snapshot = self.buffer.read(cx).snapshot(cx);
15960 let range = self
15961 .selected_text_range(false, window, cx)
15962 .and_then(|selection| {
15963 if selection.range.is_empty() {
15964 None
15965 } else {
15966 Some(selection.range)
15967 }
15968 })
15969 .unwrap_or_else(|| 0..snapshot.len());
15970
15971 let chunks = snapshot.chunks(range, true);
15972 let mut lines = Vec::new();
15973 let mut line: VecDeque<Chunk> = VecDeque::new();
15974
15975 let Some(style) = self.style.as_ref() else {
15976 return;
15977 };
15978
15979 for chunk in chunks {
15980 let highlight = chunk
15981 .syntax_highlight_id
15982 .and_then(|id| id.name(&style.syntax));
15983 let mut chunk_lines = chunk.text.split('\n').peekable();
15984 while let Some(text) = chunk_lines.next() {
15985 let mut merged_with_last_token = false;
15986 if let Some(last_token) = line.back_mut() {
15987 if last_token.highlight == highlight {
15988 last_token.text.push_str(text);
15989 merged_with_last_token = true;
15990 }
15991 }
15992
15993 if !merged_with_last_token {
15994 line.push_back(Chunk {
15995 text: text.into(),
15996 highlight,
15997 });
15998 }
15999
16000 if chunk_lines.peek().is_some() {
16001 if line.len() > 1 && line.front().unwrap().text.is_empty() {
16002 line.pop_front();
16003 }
16004 if line.len() > 1 && line.back().unwrap().text.is_empty() {
16005 line.pop_back();
16006 }
16007
16008 lines.push(mem::take(&mut line));
16009 }
16010 }
16011 }
16012
16013 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16014 return;
16015 };
16016 cx.write_to_clipboard(ClipboardItem::new_string(lines));
16017 }
16018
16019 pub fn open_context_menu(
16020 &mut self,
16021 _: &OpenContextMenu,
16022 window: &mut Window,
16023 cx: &mut Context<Self>,
16024 ) {
16025 self.request_autoscroll(Autoscroll::newest(), cx);
16026 let position = self.selections.newest_display(cx).start;
16027 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16028 }
16029
16030 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16031 &self.inlay_hint_cache
16032 }
16033
16034 pub fn replay_insert_event(
16035 &mut self,
16036 text: &str,
16037 relative_utf16_range: Option<Range<isize>>,
16038 window: &mut Window,
16039 cx: &mut Context<Self>,
16040 ) {
16041 if !self.input_enabled {
16042 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16043 return;
16044 }
16045 if let Some(relative_utf16_range) = relative_utf16_range {
16046 let selections = self.selections.all::<OffsetUtf16>(cx);
16047 self.change_selections(None, window, cx, |s| {
16048 let new_ranges = selections.into_iter().map(|range| {
16049 let start = OffsetUtf16(
16050 range
16051 .head()
16052 .0
16053 .saturating_add_signed(relative_utf16_range.start),
16054 );
16055 let end = OffsetUtf16(
16056 range
16057 .head()
16058 .0
16059 .saturating_add_signed(relative_utf16_range.end),
16060 );
16061 start..end
16062 });
16063 s.select_ranges(new_ranges);
16064 });
16065 }
16066
16067 self.handle_input(text, window, cx);
16068 }
16069
16070 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16071 let Some(provider) = self.semantics_provider.as_ref() else {
16072 return false;
16073 };
16074
16075 let mut supports = false;
16076 self.buffer().update(cx, |this, cx| {
16077 this.for_each_buffer(|buffer| {
16078 supports |= provider.supports_inlay_hints(buffer, cx);
16079 });
16080 });
16081
16082 supports
16083 }
16084
16085 pub fn is_focused(&self, window: &Window) -> bool {
16086 self.focus_handle.is_focused(window)
16087 }
16088
16089 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16090 cx.emit(EditorEvent::Focused);
16091
16092 if let Some(descendant) = self
16093 .last_focused_descendant
16094 .take()
16095 .and_then(|descendant| descendant.upgrade())
16096 {
16097 window.focus(&descendant);
16098 } else {
16099 if let Some(blame) = self.blame.as_ref() {
16100 blame.update(cx, GitBlame::focus)
16101 }
16102
16103 self.blink_manager.update(cx, BlinkManager::enable);
16104 self.show_cursor_names(window, cx);
16105 self.buffer.update(cx, |buffer, cx| {
16106 buffer.finalize_last_transaction(cx);
16107 if self.leader_peer_id.is_none() {
16108 buffer.set_active_selections(
16109 &self.selections.disjoint_anchors(),
16110 self.selections.line_mode,
16111 self.cursor_shape,
16112 cx,
16113 );
16114 }
16115 });
16116 }
16117 }
16118
16119 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16120 cx.emit(EditorEvent::FocusedIn)
16121 }
16122
16123 fn handle_focus_out(
16124 &mut self,
16125 event: FocusOutEvent,
16126 _window: &mut Window,
16127 cx: &mut Context<Self>,
16128 ) {
16129 if event.blurred != self.focus_handle {
16130 self.last_focused_descendant = Some(event.blurred);
16131 }
16132 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16133 }
16134
16135 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16136 self.blink_manager.update(cx, BlinkManager::disable);
16137 self.buffer
16138 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16139
16140 if let Some(blame) = self.blame.as_ref() {
16141 blame.update(cx, GitBlame::blur)
16142 }
16143 if !self.hover_state.focused(window, cx) {
16144 hide_hover(self, cx);
16145 }
16146 if !self
16147 .context_menu
16148 .borrow()
16149 .as_ref()
16150 .is_some_and(|context_menu| context_menu.focused(window, cx))
16151 {
16152 self.hide_context_menu(window, cx);
16153 }
16154 self.discard_inline_completion(false, cx);
16155 cx.emit(EditorEvent::Blurred);
16156 cx.notify();
16157 }
16158
16159 pub fn register_action<A: Action>(
16160 &mut self,
16161 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16162 ) -> Subscription {
16163 let id = self.next_editor_action_id.post_inc();
16164 let listener = Arc::new(listener);
16165 self.editor_actions.borrow_mut().insert(
16166 id,
16167 Box::new(move |window, _| {
16168 let listener = listener.clone();
16169 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16170 let action = action.downcast_ref().unwrap();
16171 if phase == DispatchPhase::Bubble {
16172 listener(action, window, cx)
16173 }
16174 })
16175 }),
16176 );
16177
16178 let editor_actions = self.editor_actions.clone();
16179 Subscription::new(move || {
16180 editor_actions.borrow_mut().remove(&id);
16181 })
16182 }
16183
16184 pub fn file_header_size(&self) -> u32 {
16185 FILE_HEADER_HEIGHT
16186 }
16187
16188 pub fn restore(
16189 &mut self,
16190 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16191 window: &mut Window,
16192 cx: &mut Context<Self>,
16193 ) {
16194 let workspace = self.workspace();
16195 let project = self.project.as_ref();
16196 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16197 let mut tasks = Vec::new();
16198 for (buffer_id, changes) in revert_changes {
16199 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16200 buffer.update(cx, |buffer, cx| {
16201 buffer.edit(
16202 changes
16203 .into_iter()
16204 .map(|(range, text)| (range, text.to_string())),
16205 None,
16206 cx,
16207 );
16208 });
16209
16210 if let Some(project) =
16211 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16212 {
16213 project.update(cx, |project, cx| {
16214 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16215 })
16216 }
16217 }
16218 }
16219 tasks
16220 });
16221 cx.spawn_in(window, |_, mut cx| async move {
16222 for (buffer, task) in save_tasks {
16223 let result = task.await;
16224 if result.is_err() {
16225 let Some(path) = buffer
16226 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16227 .ok()
16228 else {
16229 continue;
16230 };
16231 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16232 let Some(task) = cx
16233 .update_window_entity(&workspace, |workspace, window, cx| {
16234 workspace
16235 .open_path_preview(path, None, false, false, false, window, cx)
16236 })
16237 .ok()
16238 else {
16239 continue;
16240 };
16241 task.await.log_err();
16242 }
16243 }
16244 }
16245 })
16246 .detach();
16247 self.change_selections(None, window, cx, |selections| selections.refresh());
16248 }
16249
16250 pub fn to_pixel_point(
16251 &self,
16252 source: multi_buffer::Anchor,
16253 editor_snapshot: &EditorSnapshot,
16254 window: &mut Window,
16255 ) -> Option<gpui::Point<Pixels>> {
16256 let source_point = source.to_display_point(editor_snapshot);
16257 self.display_to_pixel_point(source_point, editor_snapshot, window)
16258 }
16259
16260 pub fn display_to_pixel_point(
16261 &self,
16262 source: DisplayPoint,
16263 editor_snapshot: &EditorSnapshot,
16264 window: &mut Window,
16265 ) -> Option<gpui::Point<Pixels>> {
16266 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16267 let text_layout_details = self.text_layout_details(window);
16268 let scroll_top = text_layout_details
16269 .scroll_anchor
16270 .scroll_position(editor_snapshot)
16271 .y;
16272
16273 if source.row().as_f32() < scroll_top.floor() {
16274 return None;
16275 }
16276 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16277 let source_y = line_height * (source.row().as_f32() - scroll_top);
16278 Some(gpui::Point::new(source_x, source_y))
16279 }
16280
16281 pub fn has_visible_completions_menu(&self) -> bool {
16282 !self.edit_prediction_preview_is_active()
16283 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16284 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16285 })
16286 }
16287
16288 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16289 self.addons
16290 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16291 }
16292
16293 pub fn unregister_addon<T: Addon>(&mut self) {
16294 self.addons.remove(&std::any::TypeId::of::<T>());
16295 }
16296
16297 pub fn addon<T: Addon>(&self) -> Option<&T> {
16298 let type_id = std::any::TypeId::of::<T>();
16299 self.addons
16300 .get(&type_id)
16301 .and_then(|item| item.to_any().downcast_ref::<T>())
16302 }
16303
16304 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16305 let text_layout_details = self.text_layout_details(window);
16306 let style = &text_layout_details.editor_style;
16307 let font_id = window.text_system().resolve_font(&style.text.font());
16308 let font_size = style.text.font_size.to_pixels(window.rem_size());
16309 let line_height = style.text.line_height_in_pixels(window.rem_size());
16310 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16311
16312 gpui::Size::new(em_width, line_height)
16313 }
16314
16315 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16316 self.load_diff_task.clone()
16317 }
16318
16319 fn read_selections_from_db(
16320 &mut self,
16321 item_id: u64,
16322 workspace_id: WorkspaceId,
16323 window: &mut Window,
16324 cx: &mut Context<Editor>,
16325 ) {
16326 if !self.is_singleton(cx)
16327 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16328 {
16329 return;
16330 }
16331 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16332 return;
16333 };
16334 if selections.is_empty() {
16335 return;
16336 }
16337
16338 let snapshot = self.buffer.read(cx).snapshot(cx);
16339 self.change_selections(None, window, cx, |s| {
16340 s.select_ranges(selections.into_iter().map(|(start, end)| {
16341 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16342 }));
16343 });
16344 }
16345}
16346
16347fn insert_extra_newline_brackets(
16348 buffer: &MultiBufferSnapshot,
16349 range: Range<usize>,
16350 language: &language::LanguageScope,
16351) -> bool {
16352 let leading_whitespace_len = buffer
16353 .reversed_chars_at(range.start)
16354 .take_while(|c| c.is_whitespace() && *c != '\n')
16355 .map(|c| c.len_utf8())
16356 .sum::<usize>();
16357 let trailing_whitespace_len = buffer
16358 .chars_at(range.end)
16359 .take_while(|c| c.is_whitespace() && *c != '\n')
16360 .map(|c| c.len_utf8())
16361 .sum::<usize>();
16362 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16363
16364 language.brackets().any(|(pair, enabled)| {
16365 let pair_start = pair.start.trim_end();
16366 let pair_end = pair.end.trim_start();
16367
16368 enabled
16369 && pair.newline
16370 && buffer.contains_str_at(range.end, pair_end)
16371 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16372 })
16373}
16374
16375fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16376 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16377 [(buffer, range, _)] => (*buffer, range.clone()),
16378 _ => return false,
16379 };
16380 let pair = {
16381 let mut result: Option<BracketMatch> = None;
16382
16383 for pair in buffer
16384 .all_bracket_ranges(range.clone())
16385 .filter(move |pair| {
16386 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16387 })
16388 {
16389 let len = pair.close_range.end - pair.open_range.start;
16390
16391 if let Some(existing) = &result {
16392 let existing_len = existing.close_range.end - existing.open_range.start;
16393 if len > existing_len {
16394 continue;
16395 }
16396 }
16397
16398 result = Some(pair);
16399 }
16400
16401 result
16402 };
16403 let Some(pair) = pair else {
16404 return false;
16405 };
16406 pair.newline_only
16407 && buffer
16408 .chars_for_range(pair.open_range.end..range.start)
16409 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16410 .all(|c| c.is_whitespace() && c != '\n')
16411}
16412
16413fn get_uncommitted_diff_for_buffer(
16414 project: &Entity<Project>,
16415 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16416 buffer: Entity<MultiBuffer>,
16417 cx: &mut App,
16418) -> Task<()> {
16419 let mut tasks = Vec::new();
16420 project.update(cx, |project, cx| {
16421 for buffer in buffers {
16422 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16423 }
16424 });
16425 cx.spawn(|mut cx| async move {
16426 let diffs = future::join_all(tasks).await;
16427 buffer
16428 .update(&mut cx, |buffer, cx| {
16429 for diff in diffs.into_iter().flatten() {
16430 buffer.add_diff(diff, cx);
16431 }
16432 })
16433 .ok();
16434 })
16435}
16436
16437fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16438 let tab_size = tab_size.get() as usize;
16439 let mut width = offset;
16440
16441 for ch in text.chars() {
16442 width += if ch == '\t' {
16443 tab_size - (width % tab_size)
16444 } else {
16445 1
16446 };
16447 }
16448
16449 width - offset
16450}
16451
16452#[cfg(test)]
16453mod tests {
16454 use super::*;
16455
16456 #[test]
16457 fn test_string_size_with_expanded_tabs() {
16458 let nz = |val| NonZeroU32::new(val).unwrap();
16459 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16460 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16461 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16462 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16463 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16464 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16465 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16466 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16467 }
16468}
16469
16470/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16471struct WordBreakingTokenizer<'a> {
16472 input: &'a str,
16473}
16474
16475impl<'a> WordBreakingTokenizer<'a> {
16476 fn new(input: &'a str) -> Self {
16477 Self { input }
16478 }
16479}
16480
16481fn is_char_ideographic(ch: char) -> bool {
16482 use unicode_script::Script::*;
16483 use unicode_script::UnicodeScript;
16484 matches!(ch.script(), Han | Tangut | Yi)
16485}
16486
16487fn is_grapheme_ideographic(text: &str) -> bool {
16488 text.chars().any(is_char_ideographic)
16489}
16490
16491fn is_grapheme_whitespace(text: &str) -> bool {
16492 text.chars().any(|x| x.is_whitespace())
16493}
16494
16495fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16496 text.chars().next().map_or(false, |ch| {
16497 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16498 })
16499}
16500
16501#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16502struct WordBreakToken<'a> {
16503 token: &'a str,
16504 grapheme_len: usize,
16505 is_whitespace: bool,
16506}
16507
16508impl<'a> Iterator for WordBreakingTokenizer<'a> {
16509 /// Yields a span, the count of graphemes in the token, and whether it was
16510 /// whitespace. Note that it also breaks at word boundaries.
16511 type Item = WordBreakToken<'a>;
16512
16513 fn next(&mut self) -> Option<Self::Item> {
16514 use unicode_segmentation::UnicodeSegmentation;
16515 if self.input.is_empty() {
16516 return None;
16517 }
16518
16519 let mut iter = self.input.graphemes(true).peekable();
16520 let mut offset = 0;
16521 let mut graphemes = 0;
16522 if let Some(first_grapheme) = iter.next() {
16523 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16524 offset += first_grapheme.len();
16525 graphemes += 1;
16526 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16527 if let Some(grapheme) = iter.peek().copied() {
16528 if should_stay_with_preceding_ideograph(grapheme) {
16529 offset += grapheme.len();
16530 graphemes += 1;
16531 }
16532 }
16533 } else {
16534 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16535 let mut next_word_bound = words.peek().copied();
16536 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16537 next_word_bound = words.next();
16538 }
16539 while let Some(grapheme) = iter.peek().copied() {
16540 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16541 break;
16542 };
16543 if is_grapheme_whitespace(grapheme) != is_whitespace {
16544 break;
16545 };
16546 offset += grapheme.len();
16547 graphemes += 1;
16548 iter.next();
16549 }
16550 }
16551 let token = &self.input[..offset];
16552 self.input = &self.input[offset..];
16553 if is_whitespace {
16554 Some(WordBreakToken {
16555 token: " ",
16556 grapheme_len: 1,
16557 is_whitespace: true,
16558 })
16559 } else {
16560 Some(WordBreakToken {
16561 token,
16562 grapheme_len: graphemes,
16563 is_whitespace: false,
16564 })
16565 }
16566 } else {
16567 None
16568 }
16569 }
16570}
16571
16572#[test]
16573fn test_word_breaking_tokenizer() {
16574 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16575 ("", &[]),
16576 (" ", &[(" ", 1, true)]),
16577 ("Ʒ", &[("Ʒ", 1, false)]),
16578 ("Ǽ", &[("Ǽ", 1, false)]),
16579 ("⋑", &[("⋑", 1, false)]),
16580 ("⋑⋑", &[("⋑⋑", 2, false)]),
16581 (
16582 "原理,进而",
16583 &[
16584 ("原", 1, false),
16585 ("理,", 2, false),
16586 ("进", 1, false),
16587 ("而", 1, false),
16588 ],
16589 ),
16590 (
16591 "hello world",
16592 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16593 ),
16594 (
16595 "hello, world",
16596 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16597 ),
16598 (
16599 " hello world",
16600 &[
16601 (" ", 1, true),
16602 ("hello", 5, false),
16603 (" ", 1, true),
16604 ("world", 5, false),
16605 ],
16606 ),
16607 (
16608 "这是什么 \n 钢笔",
16609 &[
16610 ("这", 1, false),
16611 ("是", 1, false),
16612 ("什", 1, false),
16613 ("么", 1, false),
16614 (" ", 1, true),
16615 ("钢", 1, false),
16616 ("笔", 1, false),
16617 ],
16618 ),
16619 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16620 ];
16621
16622 for (input, result) in tests {
16623 assert_eq!(
16624 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16625 result
16626 .iter()
16627 .copied()
16628 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16629 token,
16630 grapheme_len,
16631 is_whitespace,
16632 })
16633 .collect::<Vec<_>>()
16634 );
16635 }
16636}
16637
16638fn wrap_with_prefix(
16639 line_prefix: String,
16640 unwrapped_text: String,
16641 wrap_column: usize,
16642 tab_size: NonZeroU32,
16643) -> String {
16644 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16645 let mut wrapped_text = String::new();
16646 let mut current_line = line_prefix.clone();
16647
16648 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16649 let mut current_line_len = line_prefix_len;
16650 for WordBreakToken {
16651 token,
16652 grapheme_len,
16653 is_whitespace,
16654 } in tokenizer
16655 {
16656 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16657 wrapped_text.push_str(current_line.trim_end());
16658 wrapped_text.push('\n');
16659 current_line.truncate(line_prefix.len());
16660 current_line_len = line_prefix_len;
16661 if !is_whitespace {
16662 current_line.push_str(token);
16663 current_line_len += grapheme_len;
16664 }
16665 } else if !is_whitespace {
16666 current_line.push_str(token);
16667 current_line_len += grapheme_len;
16668 } else if current_line_len != line_prefix_len {
16669 current_line.push(' ');
16670 current_line_len += 1;
16671 }
16672 }
16673
16674 if !current_line.is_empty() {
16675 wrapped_text.push_str(¤t_line);
16676 }
16677 wrapped_text
16678}
16679
16680#[test]
16681fn test_wrap_with_prefix() {
16682 assert_eq!(
16683 wrap_with_prefix(
16684 "# ".to_string(),
16685 "abcdefg".to_string(),
16686 4,
16687 NonZeroU32::new(4).unwrap()
16688 ),
16689 "# abcdefg"
16690 );
16691 assert_eq!(
16692 wrap_with_prefix(
16693 "".to_string(),
16694 "\thello world".to_string(),
16695 8,
16696 NonZeroU32::new(4).unwrap()
16697 ),
16698 "hello\nworld"
16699 );
16700 assert_eq!(
16701 wrap_with_prefix(
16702 "// ".to_string(),
16703 "xx \nyy zz aa bb cc".to_string(),
16704 12,
16705 NonZeroU32::new(4).unwrap()
16706 ),
16707 "// xx yy zz\n// aa bb cc"
16708 );
16709 assert_eq!(
16710 wrap_with_prefix(
16711 String::new(),
16712 "这是什么 \n 钢笔".to_string(),
16713 3,
16714 NonZeroU32::new(4).unwrap()
16715 ),
16716 "这是什\n么 钢\n笔"
16717 );
16718}
16719
16720pub trait CollaborationHub {
16721 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16722 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16723 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16724}
16725
16726impl CollaborationHub for Entity<Project> {
16727 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16728 self.read(cx).collaborators()
16729 }
16730
16731 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16732 self.read(cx).user_store().read(cx).participant_indices()
16733 }
16734
16735 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16736 let this = self.read(cx);
16737 let user_ids = this.collaborators().values().map(|c| c.user_id);
16738 this.user_store().read_with(cx, |user_store, cx| {
16739 user_store.participant_names(user_ids, cx)
16740 })
16741 }
16742}
16743
16744pub trait SemanticsProvider {
16745 fn hover(
16746 &self,
16747 buffer: &Entity<Buffer>,
16748 position: text::Anchor,
16749 cx: &mut App,
16750 ) -> Option<Task<Vec<project::Hover>>>;
16751
16752 fn inlay_hints(
16753 &self,
16754 buffer_handle: Entity<Buffer>,
16755 range: Range<text::Anchor>,
16756 cx: &mut App,
16757 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16758
16759 fn resolve_inlay_hint(
16760 &self,
16761 hint: InlayHint,
16762 buffer_handle: Entity<Buffer>,
16763 server_id: LanguageServerId,
16764 cx: &mut App,
16765 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16766
16767 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16768
16769 fn document_highlights(
16770 &self,
16771 buffer: &Entity<Buffer>,
16772 position: text::Anchor,
16773 cx: &mut App,
16774 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16775
16776 fn definitions(
16777 &self,
16778 buffer: &Entity<Buffer>,
16779 position: text::Anchor,
16780 kind: GotoDefinitionKind,
16781 cx: &mut App,
16782 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16783
16784 fn range_for_rename(
16785 &self,
16786 buffer: &Entity<Buffer>,
16787 position: text::Anchor,
16788 cx: &mut App,
16789 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16790
16791 fn perform_rename(
16792 &self,
16793 buffer: &Entity<Buffer>,
16794 position: text::Anchor,
16795 new_name: String,
16796 cx: &mut App,
16797 ) -> Option<Task<Result<ProjectTransaction>>>;
16798}
16799
16800pub trait CompletionProvider {
16801 fn completions(
16802 &self,
16803 buffer: &Entity<Buffer>,
16804 buffer_position: text::Anchor,
16805 trigger: CompletionContext,
16806 window: &mut Window,
16807 cx: &mut Context<Editor>,
16808 ) -> Task<Result<Vec<Completion>>>;
16809
16810 fn resolve_completions(
16811 &self,
16812 buffer: Entity<Buffer>,
16813 completion_indices: Vec<usize>,
16814 completions: Rc<RefCell<Box<[Completion]>>>,
16815 cx: &mut Context<Editor>,
16816 ) -> Task<Result<bool>>;
16817
16818 fn apply_additional_edits_for_completion(
16819 &self,
16820 _buffer: Entity<Buffer>,
16821 _completions: Rc<RefCell<Box<[Completion]>>>,
16822 _completion_index: usize,
16823 _push_to_history: bool,
16824 _cx: &mut Context<Editor>,
16825 ) -> Task<Result<Option<language::Transaction>>> {
16826 Task::ready(Ok(None))
16827 }
16828
16829 fn is_completion_trigger(
16830 &self,
16831 buffer: &Entity<Buffer>,
16832 position: language::Anchor,
16833 text: &str,
16834 trigger_in_words: bool,
16835 cx: &mut Context<Editor>,
16836 ) -> bool;
16837
16838 fn sort_completions(&self) -> bool {
16839 true
16840 }
16841}
16842
16843pub trait CodeActionProvider {
16844 fn id(&self) -> Arc<str>;
16845
16846 fn code_actions(
16847 &self,
16848 buffer: &Entity<Buffer>,
16849 range: Range<text::Anchor>,
16850 window: &mut Window,
16851 cx: &mut App,
16852 ) -> Task<Result<Vec<CodeAction>>>;
16853
16854 fn apply_code_action(
16855 &self,
16856 buffer_handle: Entity<Buffer>,
16857 action: CodeAction,
16858 excerpt_id: ExcerptId,
16859 push_to_history: bool,
16860 window: &mut Window,
16861 cx: &mut App,
16862 ) -> Task<Result<ProjectTransaction>>;
16863}
16864
16865impl CodeActionProvider for Entity<Project> {
16866 fn id(&self) -> Arc<str> {
16867 "project".into()
16868 }
16869
16870 fn code_actions(
16871 &self,
16872 buffer: &Entity<Buffer>,
16873 range: Range<text::Anchor>,
16874 _window: &mut Window,
16875 cx: &mut App,
16876 ) -> Task<Result<Vec<CodeAction>>> {
16877 self.update(cx, |project, cx| {
16878 project.code_actions(buffer, range, None, cx)
16879 })
16880 }
16881
16882 fn apply_code_action(
16883 &self,
16884 buffer_handle: Entity<Buffer>,
16885 action: CodeAction,
16886 _excerpt_id: ExcerptId,
16887 push_to_history: bool,
16888 _window: &mut Window,
16889 cx: &mut App,
16890 ) -> Task<Result<ProjectTransaction>> {
16891 self.update(cx, |project, cx| {
16892 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16893 })
16894 }
16895}
16896
16897fn snippet_completions(
16898 project: &Project,
16899 buffer: &Entity<Buffer>,
16900 buffer_position: text::Anchor,
16901 cx: &mut App,
16902) -> Task<Result<Vec<Completion>>> {
16903 let language = buffer.read(cx).language_at(buffer_position);
16904 let language_name = language.as_ref().map(|language| language.lsp_id());
16905 let snippet_store = project.snippets().read(cx);
16906 let snippets = snippet_store.snippets_for(language_name, cx);
16907
16908 if snippets.is_empty() {
16909 return Task::ready(Ok(vec![]));
16910 }
16911 let snapshot = buffer.read(cx).text_snapshot();
16912 let chars: String = snapshot
16913 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16914 .collect();
16915
16916 let scope = language.map(|language| language.default_scope());
16917 let executor = cx.background_executor().clone();
16918
16919 cx.background_spawn(async move {
16920 let classifier = CharClassifier::new(scope).for_completion(true);
16921 let mut last_word = chars
16922 .chars()
16923 .take_while(|c| classifier.is_word(*c))
16924 .collect::<String>();
16925 last_word = last_word.chars().rev().collect();
16926
16927 if last_word.is_empty() {
16928 return Ok(vec![]);
16929 }
16930
16931 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16932 let to_lsp = |point: &text::Anchor| {
16933 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16934 point_to_lsp(end)
16935 };
16936 let lsp_end = to_lsp(&buffer_position);
16937
16938 let candidates = snippets
16939 .iter()
16940 .enumerate()
16941 .flat_map(|(ix, snippet)| {
16942 snippet
16943 .prefix
16944 .iter()
16945 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16946 })
16947 .collect::<Vec<StringMatchCandidate>>();
16948
16949 let mut matches = fuzzy::match_strings(
16950 &candidates,
16951 &last_word,
16952 last_word.chars().any(|c| c.is_uppercase()),
16953 100,
16954 &Default::default(),
16955 executor,
16956 )
16957 .await;
16958
16959 // Remove all candidates where the query's start does not match the start of any word in the candidate
16960 if let Some(query_start) = last_word.chars().next() {
16961 matches.retain(|string_match| {
16962 split_words(&string_match.string).any(|word| {
16963 // Check that the first codepoint of the word as lowercase matches the first
16964 // codepoint of the query as lowercase
16965 word.chars()
16966 .flat_map(|codepoint| codepoint.to_lowercase())
16967 .zip(query_start.to_lowercase())
16968 .all(|(word_cp, query_cp)| word_cp == query_cp)
16969 })
16970 });
16971 }
16972
16973 let matched_strings = matches
16974 .into_iter()
16975 .map(|m| m.string)
16976 .collect::<HashSet<_>>();
16977
16978 let result: Vec<Completion> = snippets
16979 .into_iter()
16980 .filter_map(|snippet| {
16981 let matching_prefix = snippet
16982 .prefix
16983 .iter()
16984 .find(|prefix| matched_strings.contains(*prefix))?;
16985 let start = as_offset - last_word.len();
16986 let start = snapshot.anchor_before(start);
16987 let range = start..buffer_position;
16988 let lsp_start = to_lsp(&start);
16989 let lsp_range = lsp::Range {
16990 start: lsp_start,
16991 end: lsp_end,
16992 };
16993 Some(Completion {
16994 old_range: range,
16995 new_text: snippet.body.clone(),
16996 source: CompletionSource::Lsp {
16997 server_id: LanguageServerId(usize::MAX),
16998 resolved: true,
16999 lsp_completion: Box::new(lsp::CompletionItem {
17000 label: snippet.prefix.first().unwrap().clone(),
17001 kind: Some(CompletionItemKind::SNIPPET),
17002 label_details: snippet.description.as_ref().map(|description| {
17003 lsp::CompletionItemLabelDetails {
17004 detail: Some(description.clone()),
17005 description: None,
17006 }
17007 }),
17008 insert_text_format: Some(InsertTextFormat::SNIPPET),
17009 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17010 lsp::InsertReplaceEdit {
17011 new_text: snippet.body.clone(),
17012 insert: lsp_range,
17013 replace: lsp_range,
17014 },
17015 )),
17016 filter_text: Some(snippet.body.clone()),
17017 sort_text: Some(char::MAX.to_string()),
17018 ..lsp::CompletionItem::default()
17019 }),
17020 },
17021 label: CodeLabel {
17022 text: matching_prefix.clone(),
17023 runs: Vec::new(),
17024 filter_range: 0..matching_prefix.len(),
17025 },
17026 documentation: snippet
17027 .description
17028 .clone()
17029 .map(|description| CompletionDocumentation::SingleLine(description.into())),
17030 confirm: None,
17031 })
17032 })
17033 .collect();
17034
17035 Ok(result)
17036 })
17037}
17038
17039impl CompletionProvider for Entity<Project> {
17040 fn completions(
17041 &self,
17042 buffer: &Entity<Buffer>,
17043 buffer_position: text::Anchor,
17044 options: CompletionContext,
17045 _window: &mut Window,
17046 cx: &mut Context<Editor>,
17047 ) -> Task<Result<Vec<Completion>>> {
17048 self.update(cx, |project, cx| {
17049 let snippets = snippet_completions(project, buffer, buffer_position, cx);
17050 let project_completions = project.completions(buffer, buffer_position, options, cx);
17051 cx.background_spawn(async move {
17052 let mut completions = project_completions.await?;
17053 let snippets_completions = snippets.await?;
17054 completions.extend(snippets_completions);
17055 Ok(completions)
17056 })
17057 })
17058 }
17059
17060 fn resolve_completions(
17061 &self,
17062 buffer: Entity<Buffer>,
17063 completion_indices: Vec<usize>,
17064 completions: Rc<RefCell<Box<[Completion]>>>,
17065 cx: &mut Context<Editor>,
17066 ) -> Task<Result<bool>> {
17067 self.update(cx, |project, cx| {
17068 project.lsp_store().update(cx, |lsp_store, cx| {
17069 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17070 })
17071 })
17072 }
17073
17074 fn apply_additional_edits_for_completion(
17075 &self,
17076 buffer: Entity<Buffer>,
17077 completions: Rc<RefCell<Box<[Completion]>>>,
17078 completion_index: usize,
17079 push_to_history: bool,
17080 cx: &mut Context<Editor>,
17081 ) -> Task<Result<Option<language::Transaction>>> {
17082 self.update(cx, |project, cx| {
17083 project.lsp_store().update(cx, |lsp_store, cx| {
17084 lsp_store.apply_additional_edits_for_completion(
17085 buffer,
17086 completions,
17087 completion_index,
17088 push_to_history,
17089 cx,
17090 )
17091 })
17092 })
17093 }
17094
17095 fn is_completion_trigger(
17096 &self,
17097 buffer: &Entity<Buffer>,
17098 position: language::Anchor,
17099 text: &str,
17100 trigger_in_words: bool,
17101 cx: &mut Context<Editor>,
17102 ) -> bool {
17103 let mut chars = text.chars();
17104 let char = if let Some(char) = chars.next() {
17105 char
17106 } else {
17107 return false;
17108 };
17109 if chars.next().is_some() {
17110 return false;
17111 }
17112
17113 let buffer = buffer.read(cx);
17114 let snapshot = buffer.snapshot();
17115 if !snapshot.settings_at(position, cx).show_completions_on_input {
17116 return false;
17117 }
17118 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17119 if trigger_in_words && classifier.is_word(char) {
17120 return true;
17121 }
17122
17123 buffer.completion_triggers().contains(text)
17124 }
17125}
17126
17127impl SemanticsProvider for Entity<Project> {
17128 fn hover(
17129 &self,
17130 buffer: &Entity<Buffer>,
17131 position: text::Anchor,
17132 cx: &mut App,
17133 ) -> Option<Task<Vec<project::Hover>>> {
17134 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17135 }
17136
17137 fn document_highlights(
17138 &self,
17139 buffer: &Entity<Buffer>,
17140 position: text::Anchor,
17141 cx: &mut App,
17142 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17143 Some(self.update(cx, |project, cx| {
17144 project.document_highlights(buffer, position, cx)
17145 }))
17146 }
17147
17148 fn definitions(
17149 &self,
17150 buffer: &Entity<Buffer>,
17151 position: text::Anchor,
17152 kind: GotoDefinitionKind,
17153 cx: &mut App,
17154 ) -> Option<Task<Result<Vec<LocationLink>>>> {
17155 Some(self.update(cx, |project, cx| match kind {
17156 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17157 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17158 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17159 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17160 }))
17161 }
17162
17163 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17164 // TODO: make this work for remote projects
17165 self.update(cx, |this, cx| {
17166 buffer.update(cx, |buffer, cx| {
17167 this.any_language_server_supports_inlay_hints(buffer, cx)
17168 })
17169 })
17170 }
17171
17172 fn inlay_hints(
17173 &self,
17174 buffer_handle: Entity<Buffer>,
17175 range: Range<text::Anchor>,
17176 cx: &mut App,
17177 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17178 Some(self.update(cx, |project, cx| {
17179 project.inlay_hints(buffer_handle, range, cx)
17180 }))
17181 }
17182
17183 fn resolve_inlay_hint(
17184 &self,
17185 hint: InlayHint,
17186 buffer_handle: Entity<Buffer>,
17187 server_id: LanguageServerId,
17188 cx: &mut App,
17189 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17190 Some(self.update(cx, |project, cx| {
17191 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17192 }))
17193 }
17194
17195 fn range_for_rename(
17196 &self,
17197 buffer: &Entity<Buffer>,
17198 position: text::Anchor,
17199 cx: &mut App,
17200 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17201 Some(self.update(cx, |project, cx| {
17202 let buffer = buffer.clone();
17203 let task = project.prepare_rename(buffer.clone(), position, cx);
17204 cx.spawn(|_, mut cx| async move {
17205 Ok(match task.await? {
17206 PrepareRenameResponse::Success(range) => Some(range),
17207 PrepareRenameResponse::InvalidPosition => None,
17208 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17209 // Fallback on using TreeSitter info to determine identifier range
17210 buffer.update(&mut cx, |buffer, _| {
17211 let snapshot = buffer.snapshot();
17212 let (range, kind) = snapshot.surrounding_word(position);
17213 if kind != Some(CharKind::Word) {
17214 return None;
17215 }
17216 Some(
17217 snapshot.anchor_before(range.start)
17218 ..snapshot.anchor_after(range.end),
17219 )
17220 })?
17221 }
17222 })
17223 })
17224 }))
17225 }
17226
17227 fn perform_rename(
17228 &self,
17229 buffer: &Entity<Buffer>,
17230 position: text::Anchor,
17231 new_name: String,
17232 cx: &mut App,
17233 ) -> Option<Task<Result<ProjectTransaction>>> {
17234 Some(self.update(cx, |project, cx| {
17235 project.perform_rename(buffer.clone(), position, new_name, cx)
17236 }))
17237 }
17238}
17239
17240fn inlay_hint_settings(
17241 location: Anchor,
17242 snapshot: &MultiBufferSnapshot,
17243 cx: &mut Context<Editor>,
17244) -> InlayHintSettings {
17245 let file = snapshot.file_at(location);
17246 let language = snapshot.language_at(location).map(|l| l.name());
17247 language_settings(language, file, cx).inlay_hints
17248}
17249
17250fn consume_contiguous_rows(
17251 contiguous_row_selections: &mut Vec<Selection<Point>>,
17252 selection: &Selection<Point>,
17253 display_map: &DisplaySnapshot,
17254 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17255) -> (MultiBufferRow, MultiBufferRow) {
17256 contiguous_row_selections.push(selection.clone());
17257 let start_row = MultiBufferRow(selection.start.row);
17258 let mut end_row = ending_row(selection, display_map);
17259
17260 while let Some(next_selection) = selections.peek() {
17261 if next_selection.start.row <= end_row.0 {
17262 end_row = ending_row(next_selection, display_map);
17263 contiguous_row_selections.push(selections.next().unwrap().clone());
17264 } else {
17265 break;
17266 }
17267 }
17268 (start_row, end_row)
17269}
17270
17271fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17272 if next_selection.end.column > 0 || next_selection.is_empty() {
17273 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17274 } else {
17275 MultiBufferRow(next_selection.end.row)
17276 }
17277}
17278
17279impl EditorSnapshot {
17280 pub fn remote_selections_in_range<'a>(
17281 &'a self,
17282 range: &'a Range<Anchor>,
17283 collaboration_hub: &dyn CollaborationHub,
17284 cx: &'a App,
17285 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17286 let participant_names = collaboration_hub.user_names(cx);
17287 let participant_indices = collaboration_hub.user_participant_indices(cx);
17288 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17289 let collaborators_by_replica_id = collaborators_by_peer_id
17290 .iter()
17291 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17292 .collect::<HashMap<_, _>>();
17293 self.buffer_snapshot
17294 .selections_in_range(range, false)
17295 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17296 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17297 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17298 let user_name = participant_names.get(&collaborator.user_id).cloned();
17299 Some(RemoteSelection {
17300 replica_id,
17301 selection,
17302 cursor_shape,
17303 line_mode,
17304 participant_index,
17305 peer_id: collaborator.peer_id,
17306 user_name,
17307 })
17308 })
17309 }
17310
17311 pub fn hunks_for_ranges(
17312 &self,
17313 ranges: impl IntoIterator<Item = Range<Point>>,
17314 ) -> Vec<MultiBufferDiffHunk> {
17315 let mut hunks = Vec::new();
17316 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17317 HashMap::default();
17318 for query_range in ranges {
17319 let query_rows =
17320 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17321 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17322 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17323 ) {
17324 // Include deleted hunks that are adjacent to the query range, because
17325 // otherwise they would be missed.
17326 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17327 if hunk.status().is_deleted() {
17328 intersects_range |= hunk.row_range.start == query_rows.end;
17329 intersects_range |= hunk.row_range.end == query_rows.start;
17330 }
17331 if intersects_range {
17332 if !processed_buffer_rows
17333 .entry(hunk.buffer_id)
17334 .or_default()
17335 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17336 {
17337 continue;
17338 }
17339 hunks.push(hunk);
17340 }
17341 }
17342 }
17343
17344 hunks
17345 }
17346
17347 fn display_diff_hunks_for_rows<'a>(
17348 &'a self,
17349 display_rows: Range<DisplayRow>,
17350 folded_buffers: &'a HashSet<BufferId>,
17351 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17352 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17353 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17354
17355 self.buffer_snapshot
17356 .diff_hunks_in_range(buffer_start..buffer_end)
17357 .filter_map(|hunk| {
17358 if folded_buffers.contains(&hunk.buffer_id) {
17359 return None;
17360 }
17361
17362 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17363 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17364
17365 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17366 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17367
17368 let display_hunk = if hunk_display_start.column() != 0 {
17369 DisplayDiffHunk::Folded {
17370 display_row: hunk_display_start.row(),
17371 }
17372 } else {
17373 let mut end_row = hunk_display_end.row();
17374 if hunk_display_end.column() > 0 {
17375 end_row.0 += 1;
17376 }
17377 let is_created_file = hunk.is_created_file();
17378 DisplayDiffHunk::Unfolded {
17379 status: hunk.status(),
17380 diff_base_byte_range: hunk.diff_base_byte_range,
17381 display_row_range: hunk_display_start.row()..end_row,
17382 multi_buffer_range: Anchor::range_in_buffer(
17383 hunk.excerpt_id,
17384 hunk.buffer_id,
17385 hunk.buffer_range,
17386 ),
17387 is_created_file,
17388 }
17389 };
17390
17391 Some(display_hunk)
17392 })
17393 }
17394
17395 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17396 self.display_snapshot.buffer_snapshot.language_at(position)
17397 }
17398
17399 pub fn is_focused(&self) -> bool {
17400 self.is_focused
17401 }
17402
17403 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17404 self.placeholder_text.as_ref()
17405 }
17406
17407 pub fn scroll_position(&self) -> gpui::Point<f32> {
17408 self.scroll_anchor.scroll_position(&self.display_snapshot)
17409 }
17410
17411 fn gutter_dimensions(
17412 &self,
17413 font_id: FontId,
17414 font_size: Pixels,
17415 max_line_number_width: Pixels,
17416 cx: &App,
17417 ) -> Option<GutterDimensions> {
17418 if !self.show_gutter {
17419 return None;
17420 }
17421
17422 let descent = cx.text_system().descent(font_id, font_size);
17423 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17424 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17425
17426 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17427 matches!(
17428 ProjectSettings::get_global(cx).git.git_gutter,
17429 Some(GitGutterSetting::TrackedFiles)
17430 )
17431 });
17432 let gutter_settings = EditorSettings::get_global(cx).gutter;
17433 let show_line_numbers = self
17434 .show_line_numbers
17435 .unwrap_or(gutter_settings.line_numbers);
17436 let line_gutter_width = if show_line_numbers {
17437 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17438 let min_width_for_number_on_gutter = em_advance * 4.0;
17439 max_line_number_width.max(min_width_for_number_on_gutter)
17440 } else {
17441 0.0.into()
17442 };
17443
17444 let show_code_actions = self
17445 .show_code_actions
17446 .unwrap_or(gutter_settings.code_actions);
17447
17448 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17449
17450 let git_blame_entries_width =
17451 self.git_blame_gutter_max_author_length
17452 .map(|max_author_length| {
17453 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17454
17455 /// The number of characters to dedicate to gaps and margins.
17456 const SPACING_WIDTH: usize = 4;
17457
17458 let max_char_count = max_author_length
17459 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17460 + ::git::SHORT_SHA_LENGTH
17461 + MAX_RELATIVE_TIMESTAMP.len()
17462 + SPACING_WIDTH;
17463
17464 em_advance * max_char_count
17465 });
17466
17467 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17468 left_padding += if show_code_actions || show_runnables {
17469 em_width * 3.0
17470 } else if show_git_gutter && show_line_numbers {
17471 em_width * 2.0
17472 } else if show_git_gutter || show_line_numbers {
17473 em_width
17474 } else {
17475 px(0.)
17476 };
17477
17478 let right_padding = if gutter_settings.folds && show_line_numbers {
17479 em_width * 4.0
17480 } else if gutter_settings.folds {
17481 em_width * 3.0
17482 } else if show_line_numbers {
17483 em_width
17484 } else {
17485 px(0.)
17486 };
17487
17488 Some(GutterDimensions {
17489 left_padding,
17490 right_padding,
17491 width: line_gutter_width + left_padding + right_padding,
17492 margin: -descent,
17493 git_blame_entries_width,
17494 })
17495 }
17496
17497 pub fn render_crease_toggle(
17498 &self,
17499 buffer_row: MultiBufferRow,
17500 row_contains_cursor: bool,
17501 editor: Entity<Editor>,
17502 window: &mut Window,
17503 cx: &mut App,
17504 ) -> Option<AnyElement> {
17505 let folded = self.is_line_folded(buffer_row);
17506 let mut is_foldable = false;
17507
17508 if let Some(crease) = self
17509 .crease_snapshot
17510 .query_row(buffer_row, &self.buffer_snapshot)
17511 {
17512 is_foldable = true;
17513 match crease {
17514 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17515 if let Some(render_toggle) = render_toggle {
17516 let toggle_callback =
17517 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17518 if folded {
17519 editor.update(cx, |editor, cx| {
17520 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17521 });
17522 } else {
17523 editor.update(cx, |editor, cx| {
17524 editor.unfold_at(
17525 &crate::UnfoldAt { buffer_row },
17526 window,
17527 cx,
17528 )
17529 });
17530 }
17531 });
17532 return Some((render_toggle)(
17533 buffer_row,
17534 folded,
17535 toggle_callback,
17536 window,
17537 cx,
17538 ));
17539 }
17540 }
17541 }
17542 }
17543
17544 is_foldable |= self.starts_indent(buffer_row);
17545
17546 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17547 Some(
17548 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17549 .toggle_state(folded)
17550 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17551 if folded {
17552 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17553 } else {
17554 this.fold_at(&FoldAt { buffer_row }, window, cx);
17555 }
17556 }))
17557 .into_any_element(),
17558 )
17559 } else {
17560 None
17561 }
17562 }
17563
17564 pub fn render_crease_trailer(
17565 &self,
17566 buffer_row: MultiBufferRow,
17567 window: &mut Window,
17568 cx: &mut App,
17569 ) -> Option<AnyElement> {
17570 let folded = self.is_line_folded(buffer_row);
17571 if let Crease::Inline { render_trailer, .. } = self
17572 .crease_snapshot
17573 .query_row(buffer_row, &self.buffer_snapshot)?
17574 {
17575 let render_trailer = render_trailer.as_ref()?;
17576 Some(render_trailer(buffer_row, folded, window, cx))
17577 } else {
17578 None
17579 }
17580 }
17581}
17582
17583impl Deref for EditorSnapshot {
17584 type Target = DisplaySnapshot;
17585
17586 fn deref(&self) -> &Self::Target {
17587 &self.display_snapshot
17588 }
17589}
17590
17591#[derive(Clone, Debug, PartialEq, Eq)]
17592pub enum EditorEvent {
17593 InputIgnored {
17594 text: Arc<str>,
17595 },
17596 InputHandled {
17597 utf16_range_to_replace: Option<Range<isize>>,
17598 text: Arc<str>,
17599 },
17600 ExcerptsAdded {
17601 buffer: Entity<Buffer>,
17602 predecessor: ExcerptId,
17603 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17604 },
17605 ExcerptsRemoved {
17606 ids: Vec<ExcerptId>,
17607 },
17608 BufferFoldToggled {
17609 ids: Vec<ExcerptId>,
17610 folded: bool,
17611 },
17612 ExcerptsEdited {
17613 ids: Vec<ExcerptId>,
17614 },
17615 ExcerptsExpanded {
17616 ids: Vec<ExcerptId>,
17617 },
17618 BufferEdited,
17619 Edited {
17620 transaction_id: clock::Lamport,
17621 },
17622 Reparsed(BufferId),
17623 Focused,
17624 FocusedIn,
17625 Blurred,
17626 DirtyChanged,
17627 Saved,
17628 TitleChanged,
17629 DiffBaseChanged,
17630 SelectionsChanged {
17631 local: bool,
17632 },
17633 ScrollPositionChanged {
17634 local: bool,
17635 autoscroll: bool,
17636 },
17637 Closed,
17638 TransactionUndone {
17639 transaction_id: clock::Lamport,
17640 },
17641 TransactionBegun {
17642 transaction_id: clock::Lamport,
17643 },
17644 Reloaded,
17645 CursorShapeChanged,
17646}
17647
17648impl EventEmitter<EditorEvent> for Editor {}
17649
17650impl Focusable for Editor {
17651 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17652 self.focus_handle.clone()
17653 }
17654}
17655
17656impl Render for Editor {
17657 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17658 let settings = ThemeSettings::get_global(cx);
17659
17660 let mut text_style = match self.mode {
17661 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17662 color: cx.theme().colors().editor_foreground,
17663 font_family: settings.ui_font.family.clone(),
17664 font_features: settings.ui_font.features.clone(),
17665 font_fallbacks: settings.ui_font.fallbacks.clone(),
17666 font_size: rems(0.875).into(),
17667 font_weight: settings.ui_font.weight,
17668 line_height: relative(settings.buffer_line_height.value()),
17669 ..Default::default()
17670 },
17671 EditorMode::Full => TextStyle {
17672 color: cx.theme().colors().editor_foreground,
17673 font_family: settings.buffer_font.family.clone(),
17674 font_features: settings.buffer_font.features.clone(),
17675 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17676 font_size: settings.buffer_font_size(cx).into(),
17677 font_weight: settings.buffer_font.weight,
17678 line_height: relative(settings.buffer_line_height.value()),
17679 ..Default::default()
17680 },
17681 };
17682 if let Some(text_style_refinement) = &self.text_style_refinement {
17683 text_style.refine(text_style_refinement)
17684 }
17685
17686 let background = match self.mode {
17687 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17688 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17689 EditorMode::Full => cx.theme().colors().editor_background,
17690 };
17691
17692 EditorElement::new(
17693 &cx.entity(),
17694 EditorStyle {
17695 background,
17696 local_player: cx.theme().players().local(),
17697 text: text_style,
17698 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17699 syntax: cx.theme().syntax().clone(),
17700 status: cx.theme().status().clone(),
17701 inlay_hints_style: make_inlay_hints_style(cx),
17702 inline_completion_styles: make_suggestion_styles(cx),
17703 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17704 },
17705 )
17706 }
17707}
17708
17709impl EntityInputHandler for Editor {
17710 fn text_for_range(
17711 &mut self,
17712 range_utf16: Range<usize>,
17713 adjusted_range: &mut Option<Range<usize>>,
17714 _: &mut Window,
17715 cx: &mut Context<Self>,
17716 ) -> Option<String> {
17717 let snapshot = self.buffer.read(cx).read(cx);
17718 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17719 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17720 if (start.0..end.0) != range_utf16 {
17721 adjusted_range.replace(start.0..end.0);
17722 }
17723 Some(snapshot.text_for_range(start..end).collect())
17724 }
17725
17726 fn selected_text_range(
17727 &mut self,
17728 ignore_disabled_input: bool,
17729 _: &mut Window,
17730 cx: &mut Context<Self>,
17731 ) -> Option<UTF16Selection> {
17732 // Prevent the IME menu from appearing when holding down an alphabetic key
17733 // while input is disabled.
17734 if !ignore_disabled_input && !self.input_enabled {
17735 return None;
17736 }
17737
17738 let selection = self.selections.newest::<OffsetUtf16>(cx);
17739 let range = selection.range();
17740
17741 Some(UTF16Selection {
17742 range: range.start.0..range.end.0,
17743 reversed: selection.reversed,
17744 })
17745 }
17746
17747 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17748 let snapshot = self.buffer.read(cx).read(cx);
17749 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17750 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17751 }
17752
17753 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17754 self.clear_highlights::<InputComposition>(cx);
17755 self.ime_transaction.take();
17756 }
17757
17758 fn replace_text_in_range(
17759 &mut self,
17760 range_utf16: Option<Range<usize>>,
17761 text: &str,
17762 window: &mut Window,
17763 cx: &mut Context<Self>,
17764 ) {
17765 if !self.input_enabled {
17766 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17767 return;
17768 }
17769
17770 self.transact(window, cx, |this, window, cx| {
17771 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17772 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17773 Some(this.selection_replacement_ranges(range_utf16, cx))
17774 } else {
17775 this.marked_text_ranges(cx)
17776 };
17777
17778 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17779 let newest_selection_id = this.selections.newest_anchor().id;
17780 this.selections
17781 .all::<OffsetUtf16>(cx)
17782 .iter()
17783 .zip(ranges_to_replace.iter())
17784 .find_map(|(selection, range)| {
17785 if selection.id == newest_selection_id {
17786 Some(
17787 (range.start.0 as isize - selection.head().0 as isize)
17788 ..(range.end.0 as isize - selection.head().0 as isize),
17789 )
17790 } else {
17791 None
17792 }
17793 })
17794 });
17795
17796 cx.emit(EditorEvent::InputHandled {
17797 utf16_range_to_replace: range_to_replace,
17798 text: text.into(),
17799 });
17800
17801 if let Some(new_selected_ranges) = new_selected_ranges {
17802 this.change_selections(None, window, cx, |selections| {
17803 selections.select_ranges(new_selected_ranges)
17804 });
17805 this.backspace(&Default::default(), window, cx);
17806 }
17807
17808 this.handle_input(text, window, cx);
17809 });
17810
17811 if let Some(transaction) = self.ime_transaction {
17812 self.buffer.update(cx, |buffer, cx| {
17813 buffer.group_until_transaction(transaction, cx);
17814 });
17815 }
17816
17817 self.unmark_text(window, cx);
17818 }
17819
17820 fn replace_and_mark_text_in_range(
17821 &mut self,
17822 range_utf16: Option<Range<usize>>,
17823 text: &str,
17824 new_selected_range_utf16: Option<Range<usize>>,
17825 window: &mut Window,
17826 cx: &mut Context<Self>,
17827 ) {
17828 if !self.input_enabled {
17829 return;
17830 }
17831
17832 let transaction = self.transact(window, cx, |this, window, cx| {
17833 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17834 let snapshot = this.buffer.read(cx).read(cx);
17835 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17836 for marked_range in &mut marked_ranges {
17837 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17838 marked_range.start.0 += relative_range_utf16.start;
17839 marked_range.start =
17840 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17841 marked_range.end =
17842 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17843 }
17844 }
17845 Some(marked_ranges)
17846 } else if let Some(range_utf16) = range_utf16 {
17847 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17848 Some(this.selection_replacement_ranges(range_utf16, cx))
17849 } else {
17850 None
17851 };
17852
17853 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17854 let newest_selection_id = this.selections.newest_anchor().id;
17855 this.selections
17856 .all::<OffsetUtf16>(cx)
17857 .iter()
17858 .zip(ranges_to_replace.iter())
17859 .find_map(|(selection, range)| {
17860 if selection.id == newest_selection_id {
17861 Some(
17862 (range.start.0 as isize - selection.head().0 as isize)
17863 ..(range.end.0 as isize - selection.head().0 as isize),
17864 )
17865 } else {
17866 None
17867 }
17868 })
17869 });
17870
17871 cx.emit(EditorEvent::InputHandled {
17872 utf16_range_to_replace: range_to_replace,
17873 text: text.into(),
17874 });
17875
17876 if let Some(ranges) = ranges_to_replace {
17877 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17878 }
17879
17880 let marked_ranges = {
17881 let snapshot = this.buffer.read(cx).read(cx);
17882 this.selections
17883 .disjoint_anchors()
17884 .iter()
17885 .map(|selection| {
17886 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17887 })
17888 .collect::<Vec<_>>()
17889 };
17890
17891 if text.is_empty() {
17892 this.unmark_text(window, cx);
17893 } else {
17894 this.highlight_text::<InputComposition>(
17895 marked_ranges.clone(),
17896 HighlightStyle {
17897 underline: Some(UnderlineStyle {
17898 thickness: px(1.),
17899 color: None,
17900 wavy: false,
17901 }),
17902 ..Default::default()
17903 },
17904 cx,
17905 );
17906 }
17907
17908 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17909 let use_autoclose = this.use_autoclose;
17910 let use_auto_surround = this.use_auto_surround;
17911 this.set_use_autoclose(false);
17912 this.set_use_auto_surround(false);
17913 this.handle_input(text, window, cx);
17914 this.set_use_autoclose(use_autoclose);
17915 this.set_use_auto_surround(use_auto_surround);
17916
17917 if let Some(new_selected_range) = new_selected_range_utf16 {
17918 let snapshot = this.buffer.read(cx).read(cx);
17919 let new_selected_ranges = marked_ranges
17920 .into_iter()
17921 .map(|marked_range| {
17922 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17923 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17924 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17925 snapshot.clip_offset_utf16(new_start, Bias::Left)
17926 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17927 })
17928 .collect::<Vec<_>>();
17929
17930 drop(snapshot);
17931 this.change_selections(None, window, cx, |selections| {
17932 selections.select_ranges(new_selected_ranges)
17933 });
17934 }
17935 });
17936
17937 self.ime_transaction = self.ime_transaction.or(transaction);
17938 if let Some(transaction) = self.ime_transaction {
17939 self.buffer.update(cx, |buffer, cx| {
17940 buffer.group_until_transaction(transaction, cx);
17941 });
17942 }
17943
17944 if self.text_highlights::<InputComposition>(cx).is_none() {
17945 self.ime_transaction.take();
17946 }
17947 }
17948
17949 fn bounds_for_range(
17950 &mut self,
17951 range_utf16: Range<usize>,
17952 element_bounds: gpui::Bounds<Pixels>,
17953 window: &mut Window,
17954 cx: &mut Context<Self>,
17955 ) -> Option<gpui::Bounds<Pixels>> {
17956 let text_layout_details = self.text_layout_details(window);
17957 let gpui::Size {
17958 width: em_width,
17959 height: line_height,
17960 } = self.character_size(window);
17961
17962 let snapshot = self.snapshot(window, cx);
17963 let scroll_position = snapshot.scroll_position();
17964 let scroll_left = scroll_position.x * em_width;
17965
17966 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17967 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17968 + self.gutter_dimensions.width
17969 + self.gutter_dimensions.margin;
17970 let y = line_height * (start.row().as_f32() - scroll_position.y);
17971
17972 Some(Bounds {
17973 origin: element_bounds.origin + point(x, y),
17974 size: size(em_width, line_height),
17975 })
17976 }
17977
17978 fn character_index_for_point(
17979 &mut self,
17980 point: gpui::Point<Pixels>,
17981 _window: &mut Window,
17982 _cx: &mut Context<Self>,
17983 ) -> Option<usize> {
17984 let position_map = self.last_position_map.as_ref()?;
17985 if !position_map.text_hitbox.contains(&point) {
17986 return None;
17987 }
17988 let display_point = position_map.point_for_position(point).previous_valid;
17989 let anchor = position_map
17990 .snapshot
17991 .display_point_to_anchor(display_point, Bias::Left);
17992 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17993 Some(utf16_offset.0)
17994 }
17995}
17996
17997trait SelectionExt {
17998 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17999 fn spanned_rows(
18000 &self,
18001 include_end_if_at_line_start: bool,
18002 map: &DisplaySnapshot,
18003 ) -> Range<MultiBufferRow>;
18004}
18005
18006impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18007 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18008 let start = self
18009 .start
18010 .to_point(&map.buffer_snapshot)
18011 .to_display_point(map);
18012 let end = self
18013 .end
18014 .to_point(&map.buffer_snapshot)
18015 .to_display_point(map);
18016 if self.reversed {
18017 end..start
18018 } else {
18019 start..end
18020 }
18021 }
18022
18023 fn spanned_rows(
18024 &self,
18025 include_end_if_at_line_start: bool,
18026 map: &DisplaySnapshot,
18027 ) -> Range<MultiBufferRow> {
18028 let start = self.start.to_point(&map.buffer_snapshot);
18029 let mut end = self.end.to_point(&map.buffer_snapshot);
18030 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18031 end.row -= 1;
18032 }
18033
18034 let buffer_start = map.prev_line_boundary(start).0;
18035 let buffer_end = map.next_line_boundary(end).0;
18036 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18037 }
18038}
18039
18040impl<T: InvalidationRegion> InvalidationStack<T> {
18041 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18042 where
18043 S: Clone + ToOffset,
18044 {
18045 while let Some(region) = self.last() {
18046 let all_selections_inside_invalidation_ranges =
18047 if selections.len() == region.ranges().len() {
18048 selections
18049 .iter()
18050 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18051 .all(|(selection, invalidation_range)| {
18052 let head = selection.head().to_offset(buffer);
18053 invalidation_range.start <= head && invalidation_range.end >= head
18054 })
18055 } else {
18056 false
18057 };
18058
18059 if all_selections_inside_invalidation_ranges {
18060 break;
18061 } else {
18062 self.pop();
18063 }
18064 }
18065 }
18066}
18067
18068impl<T> Default for InvalidationStack<T> {
18069 fn default() -> Self {
18070 Self(Default::default())
18071 }
18072}
18073
18074impl<T> Deref for InvalidationStack<T> {
18075 type Target = Vec<T>;
18076
18077 fn deref(&self) -> &Self::Target {
18078 &self.0
18079 }
18080}
18081
18082impl<T> DerefMut for InvalidationStack<T> {
18083 fn deref_mut(&mut self) -> &mut Self::Target {
18084 &mut self.0
18085 }
18086}
18087
18088impl InvalidationRegion for SnippetState {
18089 fn ranges(&self) -> &[Range<Anchor>] {
18090 &self.ranges[self.active_index]
18091 }
18092}
18093
18094pub fn diagnostic_block_renderer(
18095 diagnostic: Diagnostic,
18096 max_message_rows: Option<u8>,
18097 allow_closing: bool,
18098) -> RenderBlock {
18099 let (text_without_backticks, code_ranges) =
18100 highlight_diagnostic_message(&diagnostic, max_message_rows);
18101
18102 Arc::new(move |cx: &mut BlockContext| {
18103 let group_id: SharedString = cx.block_id.to_string().into();
18104
18105 let mut text_style = cx.window.text_style().clone();
18106 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18107 let theme_settings = ThemeSettings::get_global(cx);
18108 text_style.font_family = theme_settings.buffer_font.family.clone();
18109 text_style.font_style = theme_settings.buffer_font.style;
18110 text_style.font_features = theme_settings.buffer_font.features.clone();
18111 text_style.font_weight = theme_settings.buffer_font.weight;
18112
18113 let multi_line_diagnostic = diagnostic.message.contains('\n');
18114
18115 let buttons = |diagnostic: &Diagnostic| {
18116 if multi_line_diagnostic {
18117 v_flex()
18118 } else {
18119 h_flex()
18120 }
18121 .when(allow_closing, |div| {
18122 div.children(diagnostic.is_primary.then(|| {
18123 IconButton::new("close-block", IconName::XCircle)
18124 .icon_color(Color::Muted)
18125 .size(ButtonSize::Compact)
18126 .style(ButtonStyle::Transparent)
18127 .visible_on_hover(group_id.clone())
18128 .on_click(move |_click, window, cx| {
18129 window.dispatch_action(Box::new(Cancel), cx)
18130 })
18131 .tooltip(|window, cx| {
18132 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18133 })
18134 }))
18135 })
18136 .child(
18137 IconButton::new("copy-block", IconName::Copy)
18138 .icon_color(Color::Muted)
18139 .size(ButtonSize::Compact)
18140 .style(ButtonStyle::Transparent)
18141 .visible_on_hover(group_id.clone())
18142 .on_click({
18143 let message = diagnostic.message.clone();
18144 move |_click, _, cx| {
18145 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18146 }
18147 })
18148 .tooltip(Tooltip::text("Copy diagnostic message")),
18149 )
18150 };
18151
18152 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18153 AvailableSpace::min_size(),
18154 cx.window,
18155 cx.app,
18156 );
18157
18158 h_flex()
18159 .id(cx.block_id)
18160 .group(group_id.clone())
18161 .relative()
18162 .size_full()
18163 .block_mouse_down()
18164 .pl(cx.gutter_dimensions.width)
18165 .w(cx.max_width - cx.gutter_dimensions.full_width())
18166 .child(
18167 div()
18168 .flex()
18169 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18170 .flex_shrink(),
18171 )
18172 .child(buttons(&diagnostic))
18173 .child(div().flex().flex_shrink_0().child(
18174 StyledText::new(text_without_backticks.clone()).with_default_highlights(
18175 &text_style,
18176 code_ranges.iter().map(|range| {
18177 (
18178 range.clone(),
18179 HighlightStyle {
18180 font_weight: Some(FontWeight::BOLD),
18181 ..Default::default()
18182 },
18183 )
18184 }),
18185 ),
18186 ))
18187 .into_any_element()
18188 })
18189}
18190
18191fn inline_completion_edit_text(
18192 current_snapshot: &BufferSnapshot,
18193 edits: &[(Range<Anchor>, String)],
18194 edit_preview: &EditPreview,
18195 include_deletions: bool,
18196 cx: &App,
18197) -> HighlightedText {
18198 let edits = edits
18199 .iter()
18200 .map(|(anchor, text)| {
18201 (
18202 anchor.start.text_anchor..anchor.end.text_anchor,
18203 text.clone(),
18204 )
18205 })
18206 .collect::<Vec<_>>();
18207
18208 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18209}
18210
18211pub fn highlight_diagnostic_message(
18212 diagnostic: &Diagnostic,
18213 mut max_message_rows: Option<u8>,
18214) -> (SharedString, Vec<Range<usize>>) {
18215 let mut text_without_backticks = String::new();
18216 let mut code_ranges = Vec::new();
18217
18218 if let Some(source) = &diagnostic.source {
18219 text_without_backticks.push_str(source);
18220 code_ranges.push(0..source.len());
18221 text_without_backticks.push_str(": ");
18222 }
18223
18224 let mut prev_offset = 0;
18225 let mut in_code_block = false;
18226 let has_row_limit = max_message_rows.is_some();
18227 let mut newline_indices = diagnostic
18228 .message
18229 .match_indices('\n')
18230 .filter(|_| has_row_limit)
18231 .map(|(ix, _)| ix)
18232 .fuse()
18233 .peekable();
18234
18235 for (quote_ix, _) in diagnostic
18236 .message
18237 .match_indices('`')
18238 .chain([(diagnostic.message.len(), "")])
18239 {
18240 let mut first_newline_ix = None;
18241 let mut last_newline_ix = None;
18242 while let Some(newline_ix) = newline_indices.peek() {
18243 if *newline_ix < quote_ix {
18244 if first_newline_ix.is_none() {
18245 first_newline_ix = Some(*newline_ix);
18246 }
18247 last_newline_ix = Some(*newline_ix);
18248
18249 if let Some(rows_left) = &mut max_message_rows {
18250 if *rows_left == 0 {
18251 break;
18252 } else {
18253 *rows_left -= 1;
18254 }
18255 }
18256 let _ = newline_indices.next();
18257 } else {
18258 break;
18259 }
18260 }
18261 let prev_len = text_without_backticks.len();
18262 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18263 text_without_backticks.push_str(new_text);
18264 if in_code_block {
18265 code_ranges.push(prev_len..text_without_backticks.len());
18266 }
18267 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18268 in_code_block = !in_code_block;
18269 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18270 text_without_backticks.push_str("...");
18271 break;
18272 }
18273 }
18274
18275 (text_without_backticks.into(), code_ranges)
18276}
18277
18278fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18279 match severity {
18280 DiagnosticSeverity::ERROR => colors.error,
18281 DiagnosticSeverity::WARNING => colors.warning,
18282 DiagnosticSeverity::INFORMATION => colors.info,
18283 DiagnosticSeverity::HINT => colors.info,
18284 _ => colors.ignored,
18285 }
18286}
18287
18288pub fn styled_runs_for_code_label<'a>(
18289 label: &'a CodeLabel,
18290 syntax_theme: &'a theme::SyntaxTheme,
18291) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18292 let fade_out = HighlightStyle {
18293 fade_out: Some(0.35),
18294 ..Default::default()
18295 };
18296
18297 let mut prev_end = label.filter_range.end;
18298 label
18299 .runs
18300 .iter()
18301 .enumerate()
18302 .flat_map(move |(ix, (range, highlight_id))| {
18303 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18304 style
18305 } else {
18306 return Default::default();
18307 };
18308 let mut muted_style = style;
18309 muted_style.highlight(fade_out);
18310
18311 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18312 if range.start >= label.filter_range.end {
18313 if range.start > prev_end {
18314 runs.push((prev_end..range.start, fade_out));
18315 }
18316 runs.push((range.clone(), muted_style));
18317 } else if range.end <= label.filter_range.end {
18318 runs.push((range.clone(), style));
18319 } else {
18320 runs.push((range.start..label.filter_range.end, style));
18321 runs.push((label.filter_range.end..range.end, muted_style));
18322 }
18323 prev_end = cmp::max(prev_end, range.end);
18324
18325 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18326 runs.push((prev_end..label.text.len(), fade_out));
18327 }
18328
18329 runs
18330 })
18331}
18332
18333pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18334 let mut prev_index = 0;
18335 let mut prev_codepoint: Option<char> = None;
18336 text.char_indices()
18337 .chain([(text.len(), '\0')])
18338 .filter_map(move |(index, codepoint)| {
18339 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18340 let is_boundary = index == text.len()
18341 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18342 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18343 if is_boundary {
18344 let chunk = &text[prev_index..index];
18345 prev_index = index;
18346 Some(chunk)
18347 } else {
18348 None
18349 }
18350 })
18351}
18352
18353pub trait RangeToAnchorExt: Sized {
18354 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18355
18356 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18357 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18358 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18359 }
18360}
18361
18362impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18363 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18364 let start_offset = self.start.to_offset(snapshot);
18365 let end_offset = self.end.to_offset(snapshot);
18366 if start_offset == end_offset {
18367 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18368 } else {
18369 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18370 }
18371 }
18372}
18373
18374pub trait RowExt {
18375 fn as_f32(&self) -> f32;
18376
18377 fn next_row(&self) -> Self;
18378
18379 fn previous_row(&self) -> Self;
18380
18381 fn minus(&self, other: Self) -> u32;
18382}
18383
18384impl RowExt for DisplayRow {
18385 fn as_f32(&self) -> f32 {
18386 self.0 as f32
18387 }
18388
18389 fn next_row(&self) -> Self {
18390 Self(self.0 + 1)
18391 }
18392
18393 fn previous_row(&self) -> Self {
18394 Self(self.0.saturating_sub(1))
18395 }
18396
18397 fn minus(&self, other: Self) -> u32 {
18398 self.0 - other.0
18399 }
18400}
18401
18402impl RowExt for MultiBufferRow {
18403 fn as_f32(&self) -> f32 {
18404 self.0 as f32
18405 }
18406
18407 fn next_row(&self) -> Self {
18408 Self(self.0 + 1)
18409 }
18410
18411 fn previous_row(&self) -> Self {
18412 Self(self.0.saturating_sub(1))
18413 }
18414
18415 fn minus(&self, other: Self) -> u32 {
18416 self.0 - other.0
18417 }
18418}
18419
18420trait RowRangeExt {
18421 type Row;
18422
18423 fn len(&self) -> usize;
18424
18425 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18426}
18427
18428impl RowRangeExt for Range<MultiBufferRow> {
18429 type Row = MultiBufferRow;
18430
18431 fn len(&self) -> usize {
18432 (self.end.0 - self.start.0) as usize
18433 }
18434
18435 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18436 (self.start.0..self.end.0).map(MultiBufferRow)
18437 }
18438}
18439
18440impl RowRangeExt for Range<DisplayRow> {
18441 type Row = DisplayRow;
18442
18443 fn len(&self) -> usize {
18444 (self.end.0 - self.start.0) as usize
18445 }
18446
18447 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18448 (self.start.0..self.end.0).map(DisplayRow)
18449 }
18450}
18451
18452/// If select range has more than one line, we
18453/// just point the cursor to range.start.
18454fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18455 if range.start.row == range.end.row {
18456 range
18457 } else {
18458 range.start..range.start
18459 }
18460}
18461pub struct KillRing(ClipboardItem);
18462impl Global for KillRing {}
18463
18464const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18465
18466fn all_edits_insertions_or_deletions(
18467 edits: &Vec<(Range<Anchor>, String)>,
18468 snapshot: &MultiBufferSnapshot,
18469) -> bool {
18470 let mut all_insertions = true;
18471 let mut all_deletions = true;
18472
18473 for (range, new_text) in edits.iter() {
18474 let range_is_empty = range.to_offset(&snapshot).is_empty();
18475 let text_is_empty = new_text.is_empty();
18476
18477 if range_is_empty != text_is_empty {
18478 if range_is_empty {
18479 all_deletions = false;
18480 } else {
18481 all_insertions = false;
18482 }
18483 } else {
18484 return false;
18485 }
18486
18487 if !all_insertions && !all_deletions {
18488 return false;
18489 }
18490 }
18491 all_insertions || all_deletions
18492}
18493
18494struct MissingEditPredictionKeybindingTooltip;
18495
18496impl Render for MissingEditPredictionKeybindingTooltip {
18497 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18498 ui::tooltip_container(window, cx, |container, _, cx| {
18499 container
18500 .flex_shrink_0()
18501 .max_w_80()
18502 .min_h(rems_from_px(124.))
18503 .justify_between()
18504 .child(
18505 v_flex()
18506 .flex_1()
18507 .text_ui_sm(cx)
18508 .child(Label::new("Conflict with Accept Keybinding"))
18509 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18510 )
18511 .child(
18512 h_flex()
18513 .pb_1()
18514 .gap_1()
18515 .items_end()
18516 .w_full()
18517 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18518 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18519 }))
18520 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18521 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18522 })),
18523 )
18524 })
18525 }
18526}
18527
18528#[derive(Debug, Clone, Copy, PartialEq)]
18529pub struct LineHighlight {
18530 pub background: Background,
18531 pub border: Option<gpui::Hsla>,
18532}
18533
18534impl From<Hsla> for LineHighlight {
18535 fn from(hsla: Hsla) -> Self {
18536 Self {
18537 background: hsla.into(),
18538 border: None,
18539 }
18540 }
18541}
18542
18543impl From<Background> for LineHighlight {
18544 fn from(background: Background) -> Self {
18545 Self {
18546 background,
18547 border: None,
18548 }
18549 }
18550}