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 fn render_edit_prediction_popover(
5935 &mut self,
5936 text_bounds: &Bounds<Pixels>,
5937 content_origin: gpui::Point<Pixels>,
5938 editor_snapshot: &EditorSnapshot,
5939 visible_row_range: Range<DisplayRow>,
5940 scroll_top: f32,
5941 scroll_bottom: f32,
5942 line_layouts: &[LineWithInvisibles],
5943 line_height: Pixels,
5944 scroll_pixel_position: gpui::Point<Pixels>,
5945 newest_selection_head: Option<DisplayPoint>,
5946 editor_width: Pixels,
5947 style: &EditorStyle,
5948 window: &mut Window,
5949 cx: &mut App,
5950 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
5951 let active_inline_completion = self.active_inline_completion.as_ref()?;
5952
5953 if self.edit_prediction_visible_in_cursor_popover(true) {
5954 return None;
5955 }
5956
5957 match &active_inline_completion.completion {
5958 InlineCompletion::Move { target, .. } => {
5959 let target_display_point = target.to_display_point(editor_snapshot);
5960
5961 if self.edit_prediction_requires_modifier() {
5962 if !self.edit_prediction_preview_is_active() {
5963 return None;
5964 }
5965
5966 self.render_edit_prediction_modifier_jump_popover(
5967 text_bounds,
5968 content_origin,
5969 visible_row_range,
5970 line_layouts,
5971 line_height,
5972 scroll_pixel_position,
5973 newest_selection_head,
5974 target_display_point,
5975 window,
5976 cx,
5977 )
5978 } else {
5979 self.render_edit_prediction_eager_jump_popover(
5980 text_bounds,
5981 content_origin,
5982 editor_snapshot,
5983 visible_row_range,
5984 scroll_top,
5985 scroll_bottom,
5986 line_height,
5987 scroll_pixel_position,
5988 target_display_point,
5989 editor_width,
5990 window,
5991 cx,
5992 )
5993 }
5994 }
5995 InlineCompletion::Edit {
5996 display_mode: EditDisplayMode::Inline,
5997 ..
5998 } => None,
5999 InlineCompletion::Edit {
6000 display_mode: EditDisplayMode::TabAccept,
6001 edits,
6002 ..
6003 } => {
6004 let range = &edits.first()?.0;
6005 let target_display_point = range.end.to_display_point(editor_snapshot);
6006
6007 self.render_edit_prediction_end_of_line_popover(
6008 "Accept",
6009 editor_snapshot,
6010 visible_row_range,
6011 target_display_point,
6012 line_height,
6013 scroll_pixel_position,
6014 content_origin,
6015 editor_width,
6016 window,
6017 cx,
6018 )
6019 }
6020 InlineCompletion::Edit {
6021 edits,
6022 edit_preview,
6023 display_mode: EditDisplayMode::DiffPopover,
6024 snapshot,
6025 } => self.render_edit_prediction_diff_popover(
6026 text_bounds,
6027 content_origin,
6028 editor_snapshot,
6029 visible_row_range,
6030 line_layouts,
6031 line_height,
6032 scroll_pixel_position,
6033 newest_selection_head,
6034 editor_width,
6035 style,
6036 edits,
6037 edit_preview,
6038 snapshot,
6039 window,
6040 cx,
6041 ),
6042 }
6043 }
6044
6045 fn render_edit_prediction_modifier_jump_popover(
6046 &mut self,
6047 text_bounds: &Bounds<Pixels>,
6048 content_origin: gpui::Point<Pixels>,
6049 visible_row_range: Range<DisplayRow>,
6050 line_layouts: &[LineWithInvisibles],
6051 line_height: Pixels,
6052 scroll_pixel_position: gpui::Point<Pixels>,
6053 newest_selection_head: Option<DisplayPoint>,
6054 target_display_point: DisplayPoint,
6055 window: &mut Window,
6056 cx: &mut App,
6057 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6058 let scrolled_content_origin =
6059 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6060
6061 const SCROLL_PADDING_Y: Pixels = px(12.);
6062
6063 if target_display_point.row() < visible_row_range.start {
6064 return self.render_edit_prediction_scroll_popover(
6065 |_| SCROLL_PADDING_Y,
6066 IconName::ArrowUp,
6067 visible_row_range,
6068 line_layouts,
6069 newest_selection_head,
6070 scrolled_content_origin,
6071 window,
6072 cx,
6073 );
6074 } else if target_display_point.row() >= visible_row_range.end {
6075 return self.render_edit_prediction_scroll_popover(
6076 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6077 IconName::ArrowDown,
6078 visible_row_range,
6079 line_layouts,
6080 newest_selection_head,
6081 scrolled_content_origin,
6082 window,
6083 cx,
6084 );
6085 }
6086
6087 const POLE_WIDTH: Pixels = px(2.);
6088
6089 let line_layout =
6090 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6091 let target_column = target_display_point.column() as usize;
6092
6093 let target_x = line_layout.x_for_index(target_column);
6094 let target_y =
6095 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6096
6097 let flag_on_right = target_x < text_bounds.size.width / 2.;
6098
6099 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6100 border_color.l += 0.001;
6101
6102 let mut element = v_flex()
6103 .items_end()
6104 .when(flag_on_right, |el| el.items_start())
6105 .child(if flag_on_right {
6106 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6107 .rounded_bl(px(0.))
6108 .rounded_tl(px(0.))
6109 .border_l_2()
6110 .border_color(border_color)
6111 } else {
6112 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6113 .rounded_br(px(0.))
6114 .rounded_tr(px(0.))
6115 .border_r_2()
6116 .border_color(border_color)
6117 })
6118 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6119 .into_any();
6120
6121 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6122
6123 let mut origin = scrolled_content_origin + point(target_x, target_y)
6124 - point(
6125 if flag_on_right {
6126 POLE_WIDTH
6127 } else {
6128 size.width - POLE_WIDTH
6129 },
6130 size.height - line_height,
6131 );
6132
6133 origin.x = origin.x.max(content_origin.x);
6134
6135 element.prepaint_at(origin, window, cx);
6136
6137 Some((element, origin))
6138 }
6139
6140 fn render_edit_prediction_scroll_popover(
6141 &mut self,
6142 to_y: impl Fn(Size<Pixels>) -> Pixels,
6143 scroll_icon: IconName,
6144 visible_row_range: Range<DisplayRow>,
6145 line_layouts: &[LineWithInvisibles],
6146 newest_selection_head: Option<DisplayPoint>,
6147 scrolled_content_origin: gpui::Point<Pixels>,
6148 window: &mut Window,
6149 cx: &mut App,
6150 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6151 let mut element = self
6152 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6153 .into_any();
6154
6155 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6156
6157 let cursor = newest_selection_head?;
6158 let cursor_row_layout =
6159 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6160 let cursor_column = cursor.column() as usize;
6161
6162 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6163
6164 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6165
6166 element.prepaint_at(origin, window, cx);
6167 Some((element, origin))
6168 }
6169
6170 fn render_edit_prediction_eager_jump_popover(
6171 &mut self,
6172 text_bounds: &Bounds<Pixels>,
6173 content_origin: gpui::Point<Pixels>,
6174 editor_snapshot: &EditorSnapshot,
6175 visible_row_range: Range<DisplayRow>,
6176 scroll_top: f32,
6177 scroll_bottom: f32,
6178 line_height: Pixels,
6179 scroll_pixel_position: gpui::Point<Pixels>,
6180 target_display_point: DisplayPoint,
6181 editor_width: Pixels,
6182 window: &mut Window,
6183 cx: &mut App,
6184 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6185 if target_display_point.row().as_f32() < scroll_top {
6186 let mut element = self
6187 .render_edit_prediction_line_popover(
6188 "Jump to Edit",
6189 Some(IconName::ArrowUp),
6190 window,
6191 cx,
6192 )?
6193 .into_any();
6194
6195 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6196 let offset = point(
6197 (text_bounds.size.width - size.width) / 2.,
6198 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6199 );
6200
6201 let origin = text_bounds.origin + offset;
6202 element.prepaint_at(origin, window, cx);
6203 Some((element, origin))
6204 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6205 let mut element = self
6206 .render_edit_prediction_line_popover(
6207 "Jump to Edit",
6208 Some(IconName::ArrowDown),
6209 window,
6210 cx,
6211 )?
6212 .into_any();
6213
6214 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6215 let offset = point(
6216 (text_bounds.size.width - size.width) / 2.,
6217 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6218 );
6219
6220 let origin = text_bounds.origin + offset;
6221 element.prepaint_at(origin, window, cx);
6222 Some((element, origin))
6223 } else {
6224 self.render_edit_prediction_end_of_line_popover(
6225 "Jump to Edit",
6226 editor_snapshot,
6227 visible_row_range,
6228 target_display_point,
6229 line_height,
6230 scroll_pixel_position,
6231 content_origin,
6232 editor_width,
6233 window,
6234 cx,
6235 )
6236 }
6237 }
6238
6239 fn render_edit_prediction_end_of_line_popover(
6240 self: &mut Editor,
6241 label: &'static str,
6242 editor_snapshot: &EditorSnapshot,
6243 visible_row_range: Range<DisplayRow>,
6244 target_display_point: DisplayPoint,
6245 line_height: Pixels,
6246 scroll_pixel_position: gpui::Point<Pixels>,
6247 content_origin: gpui::Point<Pixels>,
6248 editor_width: Pixels,
6249 window: &mut Window,
6250 cx: &mut App,
6251 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6252 let target_line_end = DisplayPoint::new(
6253 target_display_point.row(),
6254 editor_snapshot.line_len(target_display_point.row()),
6255 );
6256
6257 let mut element = self
6258 .render_edit_prediction_line_popover(label, None, window, cx)?
6259 .into_any();
6260
6261 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6262
6263 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6264
6265 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6266 let mut origin = start_point
6267 + line_origin
6268 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6269 origin.x = origin.x.max(content_origin.x);
6270
6271 let max_x = content_origin.x + editor_width - size.width;
6272
6273 if origin.x > max_x {
6274 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6275
6276 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6277 origin.y += offset;
6278 IconName::ArrowUp
6279 } else {
6280 origin.y -= offset;
6281 IconName::ArrowDown
6282 };
6283
6284 element = self
6285 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6286 .into_any();
6287
6288 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6289
6290 origin.x = content_origin.x + editor_width - size.width - px(2.);
6291 }
6292
6293 element.prepaint_at(origin, window, cx);
6294 Some((element, origin))
6295 }
6296
6297 fn render_edit_prediction_diff_popover(
6298 self: &Editor,
6299 text_bounds: &Bounds<Pixels>,
6300 content_origin: gpui::Point<Pixels>,
6301 editor_snapshot: &EditorSnapshot,
6302 visible_row_range: Range<DisplayRow>,
6303 line_layouts: &[LineWithInvisibles],
6304 line_height: Pixels,
6305 scroll_pixel_position: gpui::Point<Pixels>,
6306 newest_selection_head: Option<DisplayPoint>,
6307 editor_width: Pixels,
6308 style: &EditorStyle,
6309 edits: &Vec<(Range<Anchor>, String)>,
6310 edit_preview: &Option<language::EditPreview>,
6311 snapshot: &language::BufferSnapshot,
6312 window: &mut Window,
6313 cx: &mut App,
6314 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6315 let edit_start = edits
6316 .first()
6317 .unwrap()
6318 .0
6319 .start
6320 .to_display_point(editor_snapshot);
6321 let edit_end = edits
6322 .last()
6323 .unwrap()
6324 .0
6325 .end
6326 .to_display_point(editor_snapshot);
6327
6328 let is_visible = visible_row_range.contains(&edit_start.row())
6329 || visible_row_range.contains(&edit_end.row());
6330 if !is_visible {
6331 return None;
6332 }
6333
6334 let highlighted_edits =
6335 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6336
6337 let styled_text = highlighted_edits.to_styled_text(&style.text);
6338 let line_count = highlighted_edits.text.lines().count();
6339
6340 const BORDER_WIDTH: Pixels = px(1.);
6341
6342 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6343 let has_keybind = keybind.is_some();
6344
6345 let mut element = h_flex()
6346 .items_start()
6347 .child(
6348 h_flex()
6349 .bg(cx.theme().colors().editor_background)
6350 .border(BORDER_WIDTH)
6351 .shadow_sm()
6352 .border_color(cx.theme().colors().border)
6353 .rounded_l_lg()
6354 .when(line_count > 1, |el| el.rounded_br_lg())
6355 .pr_1()
6356 .child(styled_text),
6357 )
6358 .child(
6359 h_flex()
6360 .h(line_height + BORDER_WIDTH * px(2.))
6361 .px_1p5()
6362 .gap_1()
6363 // Workaround: For some reason, there's a gap if we don't do this
6364 .ml(-BORDER_WIDTH)
6365 .shadow(smallvec![gpui::BoxShadow {
6366 color: gpui::black().opacity(0.05),
6367 offset: point(px(1.), px(1.)),
6368 blur_radius: px(2.),
6369 spread_radius: px(0.),
6370 }])
6371 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6372 .border(BORDER_WIDTH)
6373 .border_color(cx.theme().colors().border)
6374 .rounded_r_lg()
6375 .id("edit_prediction_diff_popover_keybind")
6376 .when(!has_keybind, |el| {
6377 let status_colors = cx.theme().status();
6378
6379 el.bg(status_colors.error_background)
6380 .border_color(status_colors.error.opacity(0.6))
6381 .child(Icon::new(IconName::Info).color(Color::Error))
6382 .cursor_default()
6383 .hoverable_tooltip(move |_window, cx| {
6384 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6385 })
6386 })
6387 .children(keybind),
6388 )
6389 .into_any();
6390
6391 let longest_row =
6392 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6393 let longest_line_width = if visible_row_range.contains(&longest_row) {
6394 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6395 } else {
6396 layout_line(
6397 longest_row,
6398 editor_snapshot,
6399 style,
6400 editor_width,
6401 |_| false,
6402 window,
6403 cx,
6404 )
6405 .width
6406 };
6407
6408 let viewport_bounds =
6409 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6410 right: -EditorElement::SCROLLBAR_WIDTH,
6411 ..Default::default()
6412 });
6413
6414 let x_after_longest =
6415 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6416 - scroll_pixel_position.x;
6417
6418 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6419
6420 // Fully visible if it can be displayed within the window (allow overlapping other
6421 // panes). However, this is only allowed if the popover starts within text_bounds.
6422 let can_position_to_the_right = x_after_longest < text_bounds.right()
6423 && x_after_longest + element_bounds.width < viewport_bounds.right();
6424
6425 let mut origin = if can_position_to_the_right {
6426 point(
6427 x_after_longest,
6428 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6429 - scroll_pixel_position.y,
6430 )
6431 } else {
6432 let cursor_row = newest_selection_head.map(|head| head.row());
6433 let above_edit = edit_start
6434 .row()
6435 .0
6436 .checked_sub(line_count as u32)
6437 .map(DisplayRow);
6438 let below_edit = Some(edit_end.row() + 1);
6439 let above_cursor =
6440 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6441 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6442
6443 // Place the edit popover adjacent to the edit if there is a location
6444 // available that is onscreen and does not obscure the cursor. Otherwise,
6445 // place it adjacent to the cursor.
6446 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6447 .into_iter()
6448 .flatten()
6449 .find(|&start_row| {
6450 let end_row = start_row + line_count as u32;
6451 visible_row_range.contains(&start_row)
6452 && visible_row_range.contains(&end_row)
6453 && cursor_row.map_or(true, |cursor_row| {
6454 !((start_row..end_row).contains(&cursor_row))
6455 })
6456 })?;
6457
6458 content_origin
6459 + point(
6460 -scroll_pixel_position.x,
6461 row_target.as_f32() * line_height - scroll_pixel_position.y,
6462 )
6463 };
6464
6465 origin.x -= BORDER_WIDTH;
6466
6467 window.defer_draw(element, origin, 1);
6468
6469 // Do not return an element, since it will already be drawn due to defer_draw.
6470 None
6471 }
6472
6473 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6474 px(30.)
6475 }
6476
6477 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6478 if self.read_only(cx) {
6479 cx.theme().players().read_only()
6480 } else {
6481 self.style.as_ref().unwrap().local_player
6482 }
6483 }
6484
6485 fn render_edit_prediction_accept_keybind(
6486 &self,
6487 window: &mut Window,
6488 cx: &App,
6489 ) -> Option<AnyElement> {
6490 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6491 let accept_keystroke = accept_binding.keystroke()?;
6492
6493 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6494
6495 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6496 Color::Accent
6497 } else {
6498 Color::Muted
6499 };
6500
6501 h_flex()
6502 .px_0p5()
6503 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6504 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6505 .text_size(TextSize::XSmall.rems(cx))
6506 .child(h_flex().children(ui::render_modifiers(
6507 &accept_keystroke.modifiers,
6508 PlatformStyle::platform(),
6509 Some(modifiers_color),
6510 Some(IconSize::XSmall.rems().into()),
6511 true,
6512 )))
6513 .when(is_platform_style_mac, |parent| {
6514 parent.child(accept_keystroke.key.clone())
6515 })
6516 .when(!is_platform_style_mac, |parent| {
6517 parent.child(
6518 Key::new(
6519 util::capitalize(&accept_keystroke.key),
6520 Some(Color::Default),
6521 )
6522 .size(Some(IconSize::XSmall.rems().into())),
6523 )
6524 })
6525 .into_any()
6526 .into()
6527 }
6528
6529 fn render_edit_prediction_line_popover(
6530 &self,
6531 label: impl Into<SharedString>,
6532 icon: Option<IconName>,
6533 window: &mut Window,
6534 cx: &App,
6535 ) -> Option<Stateful<Div>> {
6536 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6537
6538 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6539 let has_keybind = keybind.is_some();
6540
6541 let result = h_flex()
6542 .id("ep-line-popover")
6543 .py_0p5()
6544 .pl_1()
6545 .pr(padding_right)
6546 .gap_1()
6547 .rounded_md()
6548 .border_1()
6549 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6550 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6551 .shadow_sm()
6552 .when(!has_keybind, |el| {
6553 let status_colors = cx.theme().status();
6554
6555 el.bg(status_colors.error_background)
6556 .border_color(status_colors.error.opacity(0.6))
6557 .pl_2()
6558 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
6559 .cursor_default()
6560 .hoverable_tooltip(move |_window, cx| {
6561 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6562 })
6563 })
6564 .children(keybind)
6565 .child(
6566 Label::new(label)
6567 .size(LabelSize::Small)
6568 .when(!has_keybind, |el| {
6569 el.color(cx.theme().status().error.into()).strikethrough()
6570 }),
6571 )
6572 .when(!has_keybind, |el| {
6573 el.child(
6574 h_flex().ml_1().child(
6575 Icon::new(IconName::Info)
6576 .size(IconSize::Small)
6577 .color(cx.theme().status().error.into()),
6578 ),
6579 )
6580 })
6581 .when_some(icon, |element, icon| {
6582 element.child(
6583 div()
6584 .mt(px(1.5))
6585 .child(Icon::new(icon).size(IconSize::Small)),
6586 )
6587 });
6588
6589 Some(result)
6590 }
6591
6592 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
6593 let accent_color = cx.theme().colors().text_accent;
6594 let editor_bg_color = cx.theme().colors().editor_background;
6595 editor_bg_color.blend(accent_color.opacity(0.1))
6596 }
6597
6598 fn edit_prediction_callout_popover_border_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.6))
6602 }
6603
6604 fn render_edit_prediction_cursor_popover(
6605 &self,
6606 min_width: Pixels,
6607 max_width: Pixels,
6608 cursor_point: Point,
6609 style: &EditorStyle,
6610 accept_keystroke: Option<&gpui::Keystroke>,
6611 _window: &Window,
6612 cx: &mut Context<Editor>,
6613 ) -> Option<AnyElement> {
6614 let provider = self.edit_prediction_provider.as_ref()?;
6615
6616 if provider.provider.needs_terms_acceptance(cx) {
6617 return Some(
6618 h_flex()
6619 .min_w(min_width)
6620 .flex_1()
6621 .px_2()
6622 .py_1()
6623 .gap_3()
6624 .elevation_2(cx)
6625 .hover(|style| style.bg(cx.theme().colors().element_hover))
6626 .id("accept-terms")
6627 .cursor_pointer()
6628 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
6629 .on_click(cx.listener(|this, _event, window, cx| {
6630 cx.stop_propagation();
6631 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
6632 window.dispatch_action(
6633 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
6634 cx,
6635 );
6636 }))
6637 .child(
6638 h_flex()
6639 .flex_1()
6640 .gap_2()
6641 .child(Icon::new(IconName::ZedPredict))
6642 .child(Label::new("Accept Terms of Service"))
6643 .child(div().w_full())
6644 .child(
6645 Icon::new(IconName::ArrowUpRight)
6646 .color(Color::Muted)
6647 .size(IconSize::Small),
6648 )
6649 .into_any_element(),
6650 )
6651 .into_any(),
6652 );
6653 }
6654
6655 let is_refreshing = provider.provider.is_refreshing(cx);
6656
6657 fn pending_completion_container() -> Div {
6658 h_flex()
6659 .h_full()
6660 .flex_1()
6661 .gap_2()
6662 .child(Icon::new(IconName::ZedPredict))
6663 }
6664
6665 let completion = match &self.active_inline_completion {
6666 Some(prediction) => {
6667 if !self.has_visible_completions_menu() {
6668 const RADIUS: Pixels = px(6.);
6669 const BORDER_WIDTH: Pixels = px(1.);
6670
6671 return Some(
6672 h_flex()
6673 .elevation_2(cx)
6674 .border(BORDER_WIDTH)
6675 .border_color(cx.theme().colors().border)
6676 .when(accept_keystroke.is_none(), |el| {
6677 el.border_color(cx.theme().status().error)
6678 })
6679 .rounded(RADIUS)
6680 .rounded_tl(px(0.))
6681 .overflow_hidden()
6682 .child(div().px_1p5().child(match &prediction.completion {
6683 InlineCompletion::Move { target, snapshot } => {
6684 use text::ToPoint as _;
6685 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
6686 {
6687 Icon::new(IconName::ZedPredictDown)
6688 } else {
6689 Icon::new(IconName::ZedPredictUp)
6690 }
6691 }
6692 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
6693 }))
6694 .child(
6695 h_flex()
6696 .gap_1()
6697 .py_1()
6698 .px_2()
6699 .rounded_r(RADIUS - BORDER_WIDTH)
6700 .border_l_1()
6701 .border_color(cx.theme().colors().border)
6702 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6703 .when(self.edit_prediction_preview.released_too_fast(), |el| {
6704 el.child(
6705 Label::new("Hold")
6706 .size(LabelSize::Small)
6707 .when(accept_keystroke.is_none(), |el| {
6708 el.strikethrough()
6709 })
6710 .line_height_style(LineHeightStyle::UiLabel),
6711 )
6712 })
6713 .id("edit_prediction_cursor_popover_keybind")
6714 .when(accept_keystroke.is_none(), |el| {
6715 let status_colors = cx.theme().status();
6716
6717 el.bg(status_colors.error_background)
6718 .border_color(status_colors.error.opacity(0.6))
6719 .child(Icon::new(IconName::Info).color(Color::Error))
6720 .cursor_default()
6721 .hoverable_tooltip(move |_window, cx| {
6722 cx.new(|_| MissingEditPredictionKeybindingTooltip)
6723 .into()
6724 })
6725 })
6726 .when_some(
6727 accept_keystroke.as_ref(),
6728 |el, accept_keystroke| {
6729 el.child(h_flex().children(ui::render_modifiers(
6730 &accept_keystroke.modifiers,
6731 PlatformStyle::platform(),
6732 Some(Color::Default),
6733 Some(IconSize::XSmall.rems().into()),
6734 false,
6735 )))
6736 },
6737 ),
6738 )
6739 .into_any(),
6740 );
6741 }
6742
6743 self.render_edit_prediction_cursor_popover_preview(
6744 prediction,
6745 cursor_point,
6746 style,
6747 cx,
6748 )?
6749 }
6750
6751 None if is_refreshing => match &self.stale_inline_completion_in_menu {
6752 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
6753 stale_completion,
6754 cursor_point,
6755 style,
6756 cx,
6757 )?,
6758
6759 None => {
6760 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
6761 }
6762 },
6763
6764 None => pending_completion_container().child(Label::new("No Prediction")),
6765 };
6766
6767 let completion = if is_refreshing {
6768 completion
6769 .with_animation(
6770 "loading-completion",
6771 Animation::new(Duration::from_secs(2))
6772 .repeat()
6773 .with_easing(pulsating_between(0.4, 0.8)),
6774 |label, delta| label.opacity(delta),
6775 )
6776 .into_any_element()
6777 } else {
6778 completion.into_any_element()
6779 };
6780
6781 let has_completion = self.active_inline_completion.is_some();
6782
6783 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6784 Some(
6785 h_flex()
6786 .min_w(min_width)
6787 .max_w(max_width)
6788 .flex_1()
6789 .elevation_2(cx)
6790 .border_color(cx.theme().colors().border)
6791 .child(
6792 div()
6793 .flex_1()
6794 .py_1()
6795 .px_2()
6796 .overflow_hidden()
6797 .child(completion),
6798 )
6799 .when_some(accept_keystroke, |el, accept_keystroke| {
6800 if !accept_keystroke.modifiers.modified() {
6801 return el;
6802 }
6803
6804 el.child(
6805 h_flex()
6806 .h_full()
6807 .border_l_1()
6808 .rounded_r_lg()
6809 .border_color(cx.theme().colors().border)
6810 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6811 .gap_1()
6812 .py_1()
6813 .px_2()
6814 .child(
6815 h_flex()
6816 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6817 .when(is_platform_style_mac, |parent| parent.gap_1())
6818 .child(h_flex().children(ui::render_modifiers(
6819 &accept_keystroke.modifiers,
6820 PlatformStyle::platform(),
6821 Some(if !has_completion {
6822 Color::Muted
6823 } else {
6824 Color::Default
6825 }),
6826 None,
6827 false,
6828 ))),
6829 )
6830 .child(Label::new("Preview").into_any_element())
6831 .opacity(if has_completion { 1.0 } else { 0.4 }),
6832 )
6833 })
6834 .into_any(),
6835 )
6836 }
6837
6838 fn render_edit_prediction_cursor_popover_preview(
6839 &self,
6840 completion: &InlineCompletionState,
6841 cursor_point: Point,
6842 style: &EditorStyle,
6843 cx: &mut Context<Editor>,
6844 ) -> Option<Div> {
6845 use text::ToPoint as _;
6846
6847 fn render_relative_row_jump(
6848 prefix: impl Into<String>,
6849 current_row: u32,
6850 target_row: u32,
6851 ) -> Div {
6852 let (row_diff, arrow) = if target_row < current_row {
6853 (current_row - target_row, IconName::ArrowUp)
6854 } else {
6855 (target_row - current_row, IconName::ArrowDown)
6856 };
6857
6858 h_flex()
6859 .child(
6860 Label::new(format!("{}{}", prefix.into(), row_diff))
6861 .color(Color::Muted)
6862 .size(LabelSize::Small),
6863 )
6864 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
6865 }
6866
6867 match &completion.completion {
6868 InlineCompletion::Move {
6869 target, snapshot, ..
6870 } => Some(
6871 h_flex()
6872 .px_2()
6873 .gap_2()
6874 .flex_1()
6875 .child(
6876 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
6877 Icon::new(IconName::ZedPredictDown)
6878 } else {
6879 Icon::new(IconName::ZedPredictUp)
6880 },
6881 )
6882 .child(Label::new("Jump to Edit")),
6883 ),
6884
6885 InlineCompletion::Edit {
6886 edits,
6887 edit_preview,
6888 snapshot,
6889 display_mode: _,
6890 } => {
6891 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
6892
6893 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
6894 &snapshot,
6895 &edits,
6896 edit_preview.as_ref()?,
6897 true,
6898 cx,
6899 )
6900 .first_line_preview();
6901
6902 let styled_text = gpui::StyledText::new(highlighted_edits.text)
6903 .with_default_highlights(&style.text, highlighted_edits.highlights);
6904
6905 let preview = h_flex()
6906 .gap_1()
6907 .min_w_16()
6908 .child(styled_text)
6909 .when(has_more_lines, |parent| parent.child("…"));
6910
6911 let left = if first_edit_row != cursor_point.row {
6912 render_relative_row_jump("", cursor_point.row, first_edit_row)
6913 .into_any_element()
6914 } else {
6915 Icon::new(IconName::ZedPredict).into_any_element()
6916 };
6917
6918 Some(
6919 h_flex()
6920 .h_full()
6921 .flex_1()
6922 .gap_2()
6923 .pr_1()
6924 .overflow_x_hidden()
6925 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6926 .child(left)
6927 .child(preview),
6928 )
6929 }
6930 }
6931 }
6932
6933 fn render_context_menu(
6934 &self,
6935 style: &EditorStyle,
6936 max_height_in_lines: u32,
6937 y_flipped: bool,
6938 window: &mut Window,
6939 cx: &mut Context<Editor>,
6940 ) -> Option<AnyElement> {
6941 let menu = self.context_menu.borrow();
6942 let menu = menu.as_ref()?;
6943 if !menu.visible() {
6944 return None;
6945 };
6946 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
6947 }
6948
6949 fn render_context_menu_aside(
6950 &mut self,
6951 max_size: Size<Pixels>,
6952 window: &mut Window,
6953 cx: &mut Context<Editor>,
6954 ) -> Option<AnyElement> {
6955 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
6956 if menu.visible() {
6957 menu.render_aside(self, max_size, window, cx)
6958 } else {
6959 None
6960 }
6961 })
6962 }
6963
6964 fn hide_context_menu(
6965 &mut self,
6966 window: &mut Window,
6967 cx: &mut Context<Self>,
6968 ) -> Option<CodeContextMenu> {
6969 cx.notify();
6970 self.completion_tasks.clear();
6971 let context_menu = self.context_menu.borrow_mut().take();
6972 self.stale_inline_completion_in_menu.take();
6973 self.update_visible_inline_completion(window, cx);
6974 context_menu
6975 }
6976
6977 fn show_snippet_choices(
6978 &mut self,
6979 choices: &Vec<String>,
6980 selection: Range<Anchor>,
6981 cx: &mut Context<Self>,
6982 ) {
6983 if selection.start.buffer_id.is_none() {
6984 return;
6985 }
6986 let buffer_id = selection.start.buffer_id.unwrap();
6987 let buffer = self.buffer().read(cx).buffer(buffer_id);
6988 let id = post_inc(&mut self.next_completion_id);
6989
6990 if let Some(buffer) = buffer {
6991 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
6992 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
6993 ));
6994 }
6995 }
6996
6997 pub fn insert_snippet(
6998 &mut self,
6999 insertion_ranges: &[Range<usize>],
7000 snippet: Snippet,
7001 window: &mut Window,
7002 cx: &mut Context<Self>,
7003 ) -> Result<()> {
7004 struct Tabstop<T> {
7005 is_end_tabstop: bool,
7006 ranges: Vec<Range<T>>,
7007 choices: Option<Vec<String>>,
7008 }
7009
7010 let tabstops = self.buffer.update(cx, |buffer, cx| {
7011 let snippet_text: Arc<str> = snippet.text.clone().into();
7012 buffer.edit(
7013 insertion_ranges
7014 .iter()
7015 .cloned()
7016 .map(|range| (range, snippet_text.clone())),
7017 Some(AutoindentMode::EachLine),
7018 cx,
7019 );
7020
7021 let snapshot = &*buffer.read(cx);
7022 let snippet = &snippet;
7023 snippet
7024 .tabstops
7025 .iter()
7026 .map(|tabstop| {
7027 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7028 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7029 });
7030 let mut tabstop_ranges = tabstop
7031 .ranges
7032 .iter()
7033 .flat_map(|tabstop_range| {
7034 let mut delta = 0_isize;
7035 insertion_ranges.iter().map(move |insertion_range| {
7036 let insertion_start = insertion_range.start as isize + delta;
7037 delta +=
7038 snippet.text.len() as isize - insertion_range.len() as isize;
7039
7040 let start = ((insertion_start + tabstop_range.start) as usize)
7041 .min(snapshot.len());
7042 let end = ((insertion_start + tabstop_range.end) as usize)
7043 .min(snapshot.len());
7044 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7045 })
7046 })
7047 .collect::<Vec<_>>();
7048 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7049
7050 Tabstop {
7051 is_end_tabstop,
7052 ranges: tabstop_ranges,
7053 choices: tabstop.choices.clone(),
7054 }
7055 })
7056 .collect::<Vec<_>>()
7057 });
7058 if let Some(tabstop) = tabstops.first() {
7059 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7060 s.select_ranges(tabstop.ranges.iter().cloned());
7061 });
7062
7063 if let Some(choices) = &tabstop.choices {
7064 if let Some(selection) = tabstop.ranges.first() {
7065 self.show_snippet_choices(choices, selection.clone(), cx)
7066 }
7067 }
7068
7069 // If we're already at the last tabstop and it's at the end of the snippet,
7070 // we're done, we don't need to keep the state around.
7071 if !tabstop.is_end_tabstop {
7072 let choices = tabstops
7073 .iter()
7074 .map(|tabstop| tabstop.choices.clone())
7075 .collect();
7076
7077 let ranges = tabstops
7078 .into_iter()
7079 .map(|tabstop| tabstop.ranges)
7080 .collect::<Vec<_>>();
7081
7082 self.snippet_stack.push(SnippetState {
7083 active_index: 0,
7084 ranges,
7085 choices,
7086 });
7087 }
7088
7089 // Check whether the just-entered snippet ends with an auto-closable bracket.
7090 if self.autoclose_regions.is_empty() {
7091 let snapshot = self.buffer.read(cx).snapshot(cx);
7092 for selection in &mut self.selections.all::<Point>(cx) {
7093 let selection_head = selection.head();
7094 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7095 continue;
7096 };
7097
7098 let mut bracket_pair = None;
7099 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7100 let prev_chars = snapshot
7101 .reversed_chars_at(selection_head)
7102 .collect::<String>();
7103 for (pair, enabled) in scope.brackets() {
7104 if enabled
7105 && pair.close
7106 && prev_chars.starts_with(pair.start.as_str())
7107 && next_chars.starts_with(pair.end.as_str())
7108 {
7109 bracket_pair = Some(pair.clone());
7110 break;
7111 }
7112 }
7113 if let Some(pair) = bracket_pair {
7114 let start = snapshot.anchor_after(selection_head);
7115 let end = snapshot.anchor_after(selection_head);
7116 self.autoclose_regions.push(AutocloseRegion {
7117 selection_id: selection.id,
7118 range: start..end,
7119 pair,
7120 });
7121 }
7122 }
7123 }
7124 }
7125 Ok(())
7126 }
7127
7128 pub fn move_to_next_snippet_tabstop(
7129 &mut self,
7130 window: &mut Window,
7131 cx: &mut Context<Self>,
7132 ) -> bool {
7133 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7134 }
7135
7136 pub fn move_to_prev_snippet_tabstop(
7137 &mut self,
7138 window: &mut Window,
7139 cx: &mut Context<Self>,
7140 ) -> bool {
7141 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7142 }
7143
7144 pub fn move_to_snippet_tabstop(
7145 &mut self,
7146 bias: Bias,
7147 window: &mut Window,
7148 cx: &mut Context<Self>,
7149 ) -> bool {
7150 if let Some(mut snippet) = self.snippet_stack.pop() {
7151 match bias {
7152 Bias::Left => {
7153 if snippet.active_index > 0 {
7154 snippet.active_index -= 1;
7155 } else {
7156 self.snippet_stack.push(snippet);
7157 return false;
7158 }
7159 }
7160 Bias::Right => {
7161 if snippet.active_index + 1 < snippet.ranges.len() {
7162 snippet.active_index += 1;
7163 } else {
7164 self.snippet_stack.push(snippet);
7165 return false;
7166 }
7167 }
7168 }
7169 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7170 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7171 s.select_anchor_ranges(current_ranges.iter().cloned())
7172 });
7173
7174 if let Some(choices) = &snippet.choices[snippet.active_index] {
7175 if let Some(selection) = current_ranges.first() {
7176 self.show_snippet_choices(&choices, selection.clone(), cx);
7177 }
7178 }
7179
7180 // If snippet state is not at the last tabstop, push it back on the stack
7181 if snippet.active_index + 1 < snippet.ranges.len() {
7182 self.snippet_stack.push(snippet);
7183 }
7184 return true;
7185 }
7186 }
7187
7188 false
7189 }
7190
7191 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7192 self.transact(window, cx, |this, window, cx| {
7193 this.select_all(&SelectAll, window, cx);
7194 this.insert("", window, cx);
7195 });
7196 }
7197
7198 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7199 self.transact(window, cx, |this, window, cx| {
7200 this.select_autoclose_pair(window, cx);
7201 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7202 if !this.linked_edit_ranges.is_empty() {
7203 let selections = this.selections.all::<MultiBufferPoint>(cx);
7204 let snapshot = this.buffer.read(cx).snapshot(cx);
7205
7206 for selection in selections.iter() {
7207 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7208 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7209 if selection_start.buffer_id != selection_end.buffer_id {
7210 continue;
7211 }
7212 if let Some(ranges) =
7213 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7214 {
7215 for (buffer, entries) in ranges {
7216 linked_ranges.entry(buffer).or_default().extend(entries);
7217 }
7218 }
7219 }
7220 }
7221
7222 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7223 if !this.selections.line_mode {
7224 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7225 for selection in &mut selections {
7226 if selection.is_empty() {
7227 let old_head = selection.head();
7228 let mut new_head =
7229 movement::left(&display_map, old_head.to_display_point(&display_map))
7230 .to_point(&display_map);
7231 if let Some((buffer, line_buffer_range)) = display_map
7232 .buffer_snapshot
7233 .buffer_line_for_row(MultiBufferRow(old_head.row))
7234 {
7235 let indent_size =
7236 buffer.indent_size_for_line(line_buffer_range.start.row);
7237 let indent_len = match indent_size.kind {
7238 IndentKind::Space => {
7239 buffer.settings_at(line_buffer_range.start, cx).tab_size
7240 }
7241 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7242 };
7243 if old_head.column <= indent_size.len && old_head.column > 0 {
7244 let indent_len = indent_len.get();
7245 new_head = cmp::min(
7246 new_head,
7247 MultiBufferPoint::new(
7248 old_head.row,
7249 ((old_head.column - 1) / indent_len) * indent_len,
7250 ),
7251 );
7252 }
7253 }
7254
7255 selection.set_head(new_head, SelectionGoal::None);
7256 }
7257 }
7258 }
7259
7260 this.signature_help_state.set_backspace_pressed(true);
7261 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7262 s.select(selections)
7263 });
7264 this.insert("", window, cx);
7265 let empty_str: Arc<str> = Arc::from("");
7266 for (buffer, edits) in linked_ranges {
7267 let snapshot = buffer.read(cx).snapshot();
7268 use text::ToPoint as TP;
7269
7270 let edits = edits
7271 .into_iter()
7272 .map(|range| {
7273 let end_point = TP::to_point(&range.end, &snapshot);
7274 let mut start_point = TP::to_point(&range.start, &snapshot);
7275
7276 if end_point == start_point {
7277 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7278 .saturating_sub(1);
7279 start_point =
7280 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7281 };
7282
7283 (start_point..end_point, empty_str.clone())
7284 })
7285 .sorted_by_key(|(range, _)| range.start)
7286 .collect::<Vec<_>>();
7287 buffer.update(cx, |this, cx| {
7288 this.edit(edits, None, cx);
7289 })
7290 }
7291 this.refresh_inline_completion(true, false, window, cx);
7292 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7293 });
7294 }
7295
7296 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7297 self.transact(window, cx, |this, window, cx| {
7298 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7299 let line_mode = s.line_mode;
7300 s.move_with(|map, selection| {
7301 if selection.is_empty() && !line_mode {
7302 let cursor = movement::right(map, selection.head());
7303 selection.end = cursor;
7304 selection.reversed = true;
7305 selection.goal = SelectionGoal::None;
7306 }
7307 })
7308 });
7309 this.insert("", window, cx);
7310 this.refresh_inline_completion(true, false, window, cx);
7311 });
7312 }
7313
7314 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7315 if self.move_to_prev_snippet_tabstop(window, cx) {
7316 return;
7317 }
7318
7319 self.outdent(&Outdent, window, cx);
7320 }
7321
7322 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7323 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7324 return;
7325 }
7326
7327 let mut selections = self.selections.all_adjusted(cx);
7328 let buffer = self.buffer.read(cx);
7329 let snapshot = buffer.snapshot(cx);
7330 let rows_iter = selections.iter().map(|s| s.head().row);
7331 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7332
7333 let mut edits = Vec::new();
7334 let mut prev_edited_row = 0;
7335 let mut row_delta = 0;
7336 for selection in &mut selections {
7337 if selection.start.row != prev_edited_row {
7338 row_delta = 0;
7339 }
7340 prev_edited_row = selection.end.row;
7341
7342 // If the selection is non-empty, then increase the indentation of the selected lines.
7343 if !selection.is_empty() {
7344 row_delta =
7345 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7346 continue;
7347 }
7348
7349 // If the selection is empty and the cursor is in the leading whitespace before the
7350 // suggested indentation, then auto-indent the line.
7351 let cursor = selection.head();
7352 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7353 if let Some(suggested_indent) =
7354 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7355 {
7356 if cursor.column < suggested_indent.len
7357 && cursor.column <= current_indent.len
7358 && current_indent.len <= suggested_indent.len
7359 {
7360 selection.start = Point::new(cursor.row, suggested_indent.len);
7361 selection.end = selection.start;
7362 if row_delta == 0 {
7363 edits.extend(Buffer::edit_for_indent_size_adjustment(
7364 cursor.row,
7365 current_indent,
7366 suggested_indent,
7367 ));
7368 row_delta = suggested_indent.len - current_indent.len;
7369 }
7370 continue;
7371 }
7372 }
7373
7374 // Otherwise, insert a hard or soft tab.
7375 let settings = buffer.language_settings_at(cursor, cx);
7376 let tab_size = if settings.hard_tabs {
7377 IndentSize::tab()
7378 } else {
7379 let tab_size = settings.tab_size.get();
7380 let char_column = snapshot
7381 .text_for_range(Point::new(cursor.row, 0)..cursor)
7382 .flat_map(str::chars)
7383 .count()
7384 + row_delta as usize;
7385 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7386 IndentSize::spaces(chars_to_next_tab_stop)
7387 };
7388 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7389 selection.end = selection.start;
7390 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7391 row_delta += tab_size.len;
7392 }
7393
7394 self.transact(window, cx, |this, window, cx| {
7395 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7396 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7397 s.select(selections)
7398 });
7399 this.refresh_inline_completion(true, false, window, cx);
7400 });
7401 }
7402
7403 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7404 if self.read_only(cx) {
7405 return;
7406 }
7407 let mut selections = self.selections.all::<Point>(cx);
7408 let mut prev_edited_row = 0;
7409 let mut row_delta = 0;
7410 let mut edits = Vec::new();
7411 let buffer = self.buffer.read(cx);
7412 let snapshot = buffer.snapshot(cx);
7413 for selection in &mut selections {
7414 if selection.start.row != prev_edited_row {
7415 row_delta = 0;
7416 }
7417 prev_edited_row = selection.end.row;
7418
7419 row_delta =
7420 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7421 }
7422
7423 self.transact(window, cx, |this, window, cx| {
7424 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7425 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7426 s.select(selections)
7427 });
7428 });
7429 }
7430
7431 fn indent_selection(
7432 buffer: &MultiBuffer,
7433 snapshot: &MultiBufferSnapshot,
7434 selection: &mut Selection<Point>,
7435 edits: &mut Vec<(Range<Point>, String)>,
7436 delta_for_start_row: u32,
7437 cx: &App,
7438 ) -> u32 {
7439 let settings = buffer.language_settings_at(selection.start, cx);
7440 let tab_size = settings.tab_size.get();
7441 let indent_kind = if settings.hard_tabs {
7442 IndentKind::Tab
7443 } else {
7444 IndentKind::Space
7445 };
7446 let mut start_row = selection.start.row;
7447 let mut end_row = selection.end.row + 1;
7448
7449 // If a selection ends at the beginning of a line, don't indent
7450 // that last line.
7451 if selection.end.column == 0 && selection.end.row > selection.start.row {
7452 end_row -= 1;
7453 }
7454
7455 // Avoid re-indenting a row that has already been indented by a
7456 // previous selection, but still update this selection's column
7457 // to reflect that indentation.
7458 if delta_for_start_row > 0 {
7459 start_row += 1;
7460 selection.start.column += delta_for_start_row;
7461 if selection.end.row == selection.start.row {
7462 selection.end.column += delta_for_start_row;
7463 }
7464 }
7465
7466 let mut delta_for_end_row = 0;
7467 let has_multiple_rows = start_row + 1 != end_row;
7468 for row in start_row..end_row {
7469 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7470 let indent_delta = match (current_indent.kind, indent_kind) {
7471 (IndentKind::Space, IndentKind::Space) => {
7472 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7473 IndentSize::spaces(columns_to_next_tab_stop)
7474 }
7475 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7476 (_, IndentKind::Tab) => IndentSize::tab(),
7477 };
7478
7479 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7480 0
7481 } else {
7482 selection.start.column
7483 };
7484 let row_start = Point::new(row, start);
7485 edits.push((
7486 row_start..row_start,
7487 indent_delta.chars().collect::<String>(),
7488 ));
7489
7490 // Update this selection's endpoints to reflect the indentation.
7491 if row == selection.start.row {
7492 selection.start.column += indent_delta.len;
7493 }
7494 if row == selection.end.row {
7495 selection.end.column += indent_delta.len;
7496 delta_for_end_row = indent_delta.len;
7497 }
7498 }
7499
7500 if selection.start.row == selection.end.row {
7501 delta_for_start_row + delta_for_end_row
7502 } else {
7503 delta_for_end_row
7504 }
7505 }
7506
7507 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7508 if self.read_only(cx) {
7509 return;
7510 }
7511 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7512 let selections = self.selections.all::<Point>(cx);
7513 let mut deletion_ranges = Vec::new();
7514 let mut last_outdent = None;
7515 {
7516 let buffer = self.buffer.read(cx);
7517 let snapshot = buffer.snapshot(cx);
7518 for selection in &selections {
7519 let settings = buffer.language_settings_at(selection.start, cx);
7520 let tab_size = settings.tab_size.get();
7521 let mut rows = selection.spanned_rows(false, &display_map);
7522
7523 // Avoid re-outdenting a row that has already been outdented by a
7524 // previous selection.
7525 if let Some(last_row) = last_outdent {
7526 if last_row == rows.start {
7527 rows.start = rows.start.next_row();
7528 }
7529 }
7530 let has_multiple_rows = rows.len() > 1;
7531 for row in rows.iter_rows() {
7532 let indent_size = snapshot.indent_size_for_line(row);
7533 if indent_size.len > 0 {
7534 let deletion_len = match indent_size.kind {
7535 IndentKind::Space => {
7536 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7537 if columns_to_prev_tab_stop == 0 {
7538 tab_size
7539 } else {
7540 columns_to_prev_tab_stop
7541 }
7542 }
7543 IndentKind::Tab => 1,
7544 };
7545 let start = if has_multiple_rows
7546 || deletion_len > selection.start.column
7547 || indent_size.len < selection.start.column
7548 {
7549 0
7550 } else {
7551 selection.start.column - deletion_len
7552 };
7553 deletion_ranges.push(
7554 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7555 );
7556 last_outdent = Some(row);
7557 }
7558 }
7559 }
7560 }
7561
7562 self.transact(window, cx, |this, window, cx| {
7563 this.buffer.update(cx, |buffer, cx| {
7564 let empty_str: Arc<str> = Arc::default();
7565 buffer.edit(
7566 deletion_ranges
7567 .into_iter()
7568 .map(|range| (range, empty_str.clone())),
7569 None,
7570 cx,
7571 );
7572 });
7573 let selections = this.selections.all::<usize>(cx);
7574 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7575 s.select(selections)
7576 });
7577 });
7578 }
7579
7580 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
7581 if self.read_only(cx) {
7582 return;
7583 }
7584 let selections = self
7585 .selections
7586 .all::<usize>(cx)
7587 .into_iter()
7588 .map(|s| s.range());
7589
7590 self.transact(window, cx, |this, window, cx| {
7591 this.buffer.update(cx, |buffer, cx| {
7592 buffer.autoindent_ranges(selections, cx);
7593 });
7594 let selections = this.selections.all::<usize>(cx);
7595 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7596 s.select(selections)
7597 });
7598 });
7599 }
7600
7601 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
7602 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7603 let selections = self.selections.all::<Point>(cx);
7604
7605 let mut new_cursors = Vec::new();
7606 let mut edit_ranges = Vec::new();
7607 let mut selections = selections.iter().peekable();
7608 while let Some(selection) = selections.next() {
7609 let mut rows = selection.spanned_rows(false, &display_map);
7610 let goal_display_column = selection.head().to_display_point(&display_map).column();
7611
7612 // Accumulate contiguous regions of rows that we want to delete.
7613 while let Some(next_selection) = selections.peek() {
7614 let next_rows = next_selection.spanned_rows(false, &display_map);
7615 if next_rows.start <= rows.end {
7616 rows.end = next_rows.end;
7617 selections.next().unwrap();
7618 } else {
7619 break;
7620 }
7621 }
7622
7623 let buffer = &display_map.buffer_snapshot;
7624 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
7625 let edit_end;
7626 let cursor_buffer_row;
7627 if buffer.max_point().row >= rows.end.0 {
7628 // If there's a line after the range, delete the \n from the end of the row range
7629 // and position the cursor on the next line.
7630 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
7631 cursor_buffer_row = rows.end;
7632 } else {
7633 // If there isn't a line after the range, delete the \n from the line before the
7634 // start of the row range and position the cursor there.
7635 edit_start = edit_start.saturating_sub(1);
7636 edit_end = buffer.len();
7637 cursor_buffer_row = rows.start.previous_row();
7638 }
7639
7640 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
7641 *cursor.column_mut() =
7642 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
7643
7644 new_cursors.push((
7645 selection.id,
7646 buffer.anchor_after(cursor.to_point(&display_map)),
7647 ));
7648 edit_ranges.push(edit_start..edit_end);
7649 }
7650
7651 self.transact(window, cx, |this, window, cx| {
7652 let buffer = this.buffer.update(cx, |buffer, cx| {
7653 let empty_str: Arc<str> = Arc::default();
7654 buffer.edit(
7655 edit_ranges
7656 .into_iter()
7657 .map(|range| (range, empty_str.clone())),
7658 None,
7659 cx,
7660 );
7661 buffer.snapshot(cx)
7662 });
7663 let new_selections = new_cursors
7664 .into_iter()
7665 .map(|(id, cursor)| {
7666 let cursor = cursor.to_point(&buffer);
7667 Selection {
7668 id,
7669 start: cursor,
7670 end: cursor,
7671 reversed: false,
7672 goal: SelectionGoal::None,
7673 }
7674 })
7675 .collect();
7676
7677 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7678 s.select(new_selections);
7679 });
7680 });
7681 }
7682
7683 pub fn join_lines_impl(
7684 &mut self,
7685 insert_whitespace: bool,
7686 window: &mut Window,
7687 cx: &mut Context<Self>,
7688 ) {
7689 if self.read_only(cx) {
7690 return;
7691 }
7692 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
7693 for selection in self.selections.all::<Point>(cx) {
7694 let start = MultiBufferRow(selection.start.row);
7695 // Treat single line selections as if they include the next line. Otherwise this action
7696 // would do nothing for single line selections individual cursors.
7697 let end = if selection.start.row == selection.end.row {
7698 MultiBufferRow(selection.start.row + 1)
7699 } else {
7700 MultiBufferRow(selection.end.row)
7701 };
7702
7703 if let Some(last_row_range) = row_ranges.last_mut() {
7704 if start <= last_row_range.end {
7705 last_row_range.end = end;
7706 continue;
7707 }
7708 }
7709 row_ranges.push(start..end);
7710 }
7711
7712 let snapshot = self.buffer.read(cx).snapshot(cx);
7713 let mut cursor_positions = Vec::new();
7714 for row_range in &row_ranges {
7715 let anchor = snapshot.anchor_before(Point::new(
7716 row_range.end.previous_row().0,
7717 snapshot.line_len(row_range.end.previous_row()),
7718 ));
7719 cursor_positions.push(anchor..anchor);
7720 }
7721
7722 self.transact(window, cx, |this, window, cx| {
7723 for row_range in row_ranges.into_iter().rev() {
7724 for row in row_range.iter_rows().rev() {
7725 let end_of_line = Point::new(row.0, snapshot.line_len(row));
7726 let next_line_row = row.next_row();
7727 let indent = snapshot.indent_size_for_line(next_line_row);
7728 let start_of_next_line = Point::new(next_line_row.0, indent.len);
7729
7730 let replace =
7731 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
7732 " "
7733 } else {
7734 ""
7735 };
7736
7737 this.buffer.update(cx, |buffer, cx| {
7738 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
7739 });
7740 }
7741 }
7742
7743 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7744 s.select_anchor_ranges(cursor_positions)
7745 });
7746 });
7747 }
7748
7749 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
7750 self.join_lines_impl(true, window, cx);
7751 }
7752
7753 pub fn sort_lines_case_sensitive(
7754 &mut self,
7755 _: &SortLinesCaseSensitive,
7756 window: &mut Window,
7757 cx: &mut Context<Self>,
7758 ) {
7759 self.manipulate_lines(window, cx, |lines| lines.sort())
7760 }
7761
7762 pub fn sort_lines_case_insensitive(
7763 &mut self,
7764 _: &SortLinesCaseInsensitive,
7765 window: &mut Window,
7766 cx: &mut Context<Self>,
7767 ) {
7768 self.manipulate_lines(window, cx, |lines| {
7769 lines.sort_by_key(|line| line.to_lowercase())
7770 })
7771 }
7772
7773 pub fn unique_lines_case_insensitive(
7774 &mut self,
7775 _: &UniqueLinesCaseInsensitive,
7776 window: &mut Window,
7777 cx: &mut Context<Self>,
7778 ) {
7779 self.manipulate_lines(window, cx, |lines| {
7780 let mut seen = HashSet::default();
7781 lines.retain(|line| seen.insert(line.to_lowercase()));
7782 })
7783 }
7784
7785 pub fn unique_lines_case_sensitive(
7786 &mut self,
7787 _: &UniqueLinesCaseSensitive,
7788 window: &mut Window,
7789 cx: &mut Context<Self>,
7790 ) {
7791 self.manipulate_lines(window, cx, |lines| {
7792 let mut seen = HashSet::default();
7793 lines.retain(|line| seen.insert(*line));
7794 })
7795 }
7796
7797 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
7798 let Some(project) = self.project.clone() else {
7799 return;
7800 };
7801 self.reload(project, window, cx)
7802 .detach_and_notify_err(window, cx);
7803 }
7804
7805 pub fn restore_file(
7806 &mut self,
7807 _: &::git::RestoreFile,
7808 window: &mut Window,
7809 cx: &mut Context<Self>,
7810 ) {
7811 let mut buffer_ids = HashSet::default();
7812 let snapshot = self.buffer().read(cx).snapshot(cx);
7813 for selection in self.selections.all::<usize>(cx) {
7814 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
7815 }
7816
7817 let buffer = self.buffer().read(cx);
7818 let ranges = buffer_ids
7819 .into_iter()
7820 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
7821 .collect::<Vec<_>>();
7822
7823 self.restore_hunks_in_ranges(ranges, window, cx);
7824 }
7825
7826 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
7827 let selections = self
7828 .selections
7829 .all(cx)
7830 .into_iter()
7831 .map(|s| s.range())
7832 .collect();
7833 self.restore_hunks_in_ranges(selections, window, cx);
7834 }
7835
7836 fn restore_hunks_in_ranges(
7837 &mut self,
7838 ranges: Vec<Range<Point>>,
7839 window: &mut Window,
7840 cx: &mut Context<Editor>,
7841 ) {
7842 let mut revert_changes = HashMap::default();
7843 let chunk_by = self
7844 .snapshot(window, cx)
7845 .hunks_for_ranges(ranges)
7846 .into_iter()
7847 .chunk_by(|hunk| hunk.buffer_id);
7848 for (buffer_id, hunks) in &chunk_by {
7849 let hunks = hunks.collect::<Vec<_>>();
7850 for hunk in &hunks {
7851 self.prepare_restore_change(&mut revert_changes, hunk, cx);
7852 }
7853 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
7854 }
7855 drop(chunk_by);
7856 if !revert_changes.is_empty() {
7857 self.transact(window, cx, |editor, window, cx| {
7858 editor.restore(revert_changes, window, cx);
7859 });
7860 }
7861 }
7862
7863 pub fn open_active_item_in_terminal(
7864 &mut self,
7865 _: &OpenInTerminal,
7866 window: &mut Window,
7867 cx: &mut Context<Self>,
7868 ) {
7869 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
7870 let project_path = buffer.read(cx).project_path(cx)?;
7871 let project = self.project.as_ref()?.read(cx);
7872 let entry = project.entry_for_path(&project_path, cx)?;
7873 let parent = match &entry.canonical_path {
7874 Some(canonical_path) => canonical_path.to_path_buf(),
7875 None => project.absolute_path(&project_path, cx)?,
7876 }
7877 .parent()?
7878 .to_path_buf();
7879 Some(parent)
7880 }) {
7881 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
7882 }
7883 }
7884
7885 pub fn prepare_restore_change(
7886 &self,
7887 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
7888 hunk: &MultiBufferDiffHunk,
7889 cx: &mut App,
7890 ) -> Option<()> {
7891 if hunk.is_created_file() {
7892 return None;
7893 }
7894 let buffer = self.buffer.read(cx);
7895 let diff = buffer.diff_for(hunk.buffer_id)?;
7896 let buffer = buffer.buffer(hunk.buffer_id)?;
7897 let buffer = buffer.read(cx);
7898 let original_text = diff
7899 .read(cx)
7900 .base_text()
7901 .as_rope()
7902 .slice(hunk.diff_base_byte_range.clone());
7903 let buffer_snapshot = buffer.snapshot();
7904 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
7905 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
7906 probe
7907 .0
7908 .start
7909 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
7910 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
7911 }) {
7912 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
7913 Some(())
7914 } else {
7915 None
7916 }
7917 }
7918
7919 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
7920 self.manipulate_lines(window, cx, |lines| lines.reverse())
7921 }
7922
7923 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
7924 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
7925 }
7926
7927 fn manipulate_lines<Fn>(
7928 &mut self,
7929 window: &mut Window,
7930 cx: &mut Context<Self>,
7931 mut callback: Fn,
7932 ) where
7933 Fn: FnMut(&mut Vec<&str>),
7934 {
7935 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7936 let buffer = self.buffer.read(cx).snapshot(cx);
7937
7938 let mut edits = Vec::new();
7939
7940 let selections = self.selections.all::<Point>(cx);
7941 let mut selections = selections.iter().peekable();
7942 let mut contiguous_row_selections = Vec::new();
7943 let mut new_selections = Vec::new();
7944 let mut added_lines = 0;
7945 let mut removed_lines = 0;
7946
7947 while let Some(selection) = selections.next() {
7948 let (start_row, end_row) = consume_contiguous_rows(
7949 &mut contiguous_row_selections,
7950 selection,
7951 &display_map,
7952 &mut selections,
7953 );
7954
7955 let start_point = Point::new(start_row.0, 0);
7956 let end_point = Point::new(
7957 end_row.previous_row().0,
7958 buffer.line_len(end_row.previous_row()),
7959 );
7960 let text = buffer
7961 .text_for_range(start_point..end_point)
7962 .collect::<String>();
7963
7964 let mut lines = text.split('\n').collect_vec();
7965
7966 let lines_before = lines.len();
7967 callback(&mut lines);
7968 let lines_after = lines.len();
7969
7970 edits.push((start_point..end_point, lines.join("\n")));
7971
7972 // Selections must change based on added and removed line count
7973 let start_row =
7974 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
7975 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
7976 new_selections.push(Selection {
7977 id: selection.id,
7978 start: start_row,
7979 end: end_row,
7980 goal: SelectionGoal::None,
7981 reversed: selection.reversed,
7982 });
7983
7984 if lines_after > lines_before {
7985 added_lines += lines_after - lines_before;
7986 } else if lines_before > lines_after {
7987 removed_lines += lines_before - lines_after;
7988 }
7989 }
7990
7991 self.transact(window, cx, |this, window, cx| {
7992 let buffer = this.buffer.update(cx, |buffer, cx| {
7993 buffer.edit(edits, None, cx);
7994 buffer.snapshot(cx)
7995 });
7996
7997 // Recalculate offsets on newly edited buffer
7998 let new_selections = new_selections
7999 .iter()
8000 .map(|s| {
8001 let start_point = Point::new(s.start.0, 0);
8002 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8003 Selection {
8004 id: s.id,
8005 start: buffer.point_to_offset(start_point),
8006 end: buffer.point_to_offset(end_point),
8007 goal: s.goal,
8008 reversed: s.reversed,
8009 }
8010 })
8011 .collect();
8012
8013 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8014 s.select(new_selections);
8015 });
8016
8017 this.request_autoscroll(Autoscroll::fit(), cx);
8018 });
8019 }
8020
8021 pub fn convert_to_upper_case(
8022 &mut self,
8023 _: &ConvertToUpperCase,
8024 window: &mut Window,
8025 cx: &mut Context<Self>,
8026 ) {
8027 self.manipulate_text(window, cx, |text| text.to_uppercase())
8028 }
8029
8030 pub fn convert_to_lower_case(
8031 &mut self,
8032 _: &ConvertToLowerCase,
8033 window: &mut Window,
8034 cx: &mut Context<Self>,
8035 ) {
8036 self.manipulate_text(window, cx, |text| text.to_lowercase())
8037 }
8038
8039 pub fn convert_to_title_case(
8040 &mut self,
8041 _: &ConvertToTitleCase,
8042 window: &mut Window,
8043 cx: &mut Context<Self>,
8044 ) {
8045 self.manipulate_text(window, cx, |text| {
8046 text.split('\n')
8047 .map(|line| line.to_case(Case::Title))
8048 .join("\n")
8049 })
8050 }
8051
8052 pub fn convert_to_snake_case(
8053 &mut self,
8054 _: &ConvertToSnakeCase,
8055 window: &mut Window,
8056 cx: &mut Context<Self>,
8057 ) {
8058 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8059 }
8060
8061 pub fn convert_to_kebab_case(
8062 &mut self,
8063 _: &ConvertToKebabCase,
8064 window: &mut Window,
8065 cx: &mut Context<Self>,
8066 ) {
8067 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8068 }
8069
8070 pub fn convert_to_upper_camel_case(
8071 &mut self,
8072 _: &ConvertToUpperCamelCase,
8073 window: &mut Window,
8074 cx: &mut Context<Self>,
8075 ) {
8076 self.manipulate_text(window, cx, |text| {
8077 text.split('\n')
8078 .map(|line| line.to_case(Case::UpperCamel))
8079 .join("\n")
8080 })
8081 }
8082
8083 pub fn convert_to_lower_camel_case(
8084 &mut self,
8085 _: &ConvertToLowerCamelCase,
8086 window: &mut Window,
8087 cx: &mut Context<Self>,
8088 ) {
8089 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8090 }
8091
8092 pub fn convert_to_opposite_case(
8093 &mut self,
8094 _: &ConvertToOppositeCase,
8095 window: &mut Window,
8096 cx: &mut Context<Self>,
8097 ) {
8098 self.manipulate_text(window, cx, |text| {
8099 text.chars()
8100 .fold(String::with_capacity(text.len()), |mut t, c| {
8101 if c.is_uppercase() {
8102 t.extend(c.to_lowercase());
8103 } else {
8104 t.extend(c.to_uppercase());
8105 }
8106 t
8107 })
8108 })
8109 }
8110
8111 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8112 where
8113 Fn: FnMut(&str) -> String,
8114 {
8115 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8116 let buffer = self.buffer.read(cx).snapshot(cx);
8117
8118 let mut new_selections = Vec::new();
8119 let mut edits = Vec::new();
8120 let mut selection_adjustment = 0i32;
8121
8122 for selection in self.selections.all::<usize>(cx) {
8123 let selection_is_empty = selection.is_empty();
8124
8125 let (start, end) = if selection_is_empty {
8126 let word_range = movement::surrounding_word(
8127 &display_map,
8128 selection.start.to_display_point(&display_map),
8129 );
8130 let start = word_range.start.to_offset(&display_map, Bias::Left);
8131 let end = word_range.end.to_offset(&display_map, Bias::Left);
8132 (start, end)
8133 } else {
8134 (selection.start, selection.end)
8135 };
8136
8137 let text = buffer.text_for_range(start..end).collect::<String>();
8138 let old_length = text.len() as i32;
8139 let text = callback(&text);
8140
8141 new_selections.push(Selection {
8142 start: (start as i32 - selection_adjustment) as usize,
8143 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8144 goal: SelectionGoal::None,
8145 ..selection
8146 });
8147
8148 selection_adjustment += old_length - text.len() as i32;
8149
8150 edits.push((start..end, text));
8151 }
8152
8153 self.transact(window, cx, |this, window, cx| {
8154 this.buffer.update(cx, |buffer, cx| {
8155 buffer.edit(edits, None, cx);
8156 });
8157
8158 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8159 s.select(new_selections);
8160 });
8161
8162 this.request_autoscroll(Autoscroll::fit(), cx);
8163 });
8164 }
8165
8166 pub fn duplicate(
8167 &mut self,
8168 upwards: bool,
8169 whole_lines: bool,
8170 window: &mut Window,
8171 cx: &mut Context<Self>,
8172 ) {
8173 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8174 let buffer = &display_map.buffer_snapshot;
8175 let selections = self.selections.all::<Point>(cx);
8176
8177 let mut edits = Vec::new();
8178 let mut selections_iter = selections.iter().peekable();
8179 while let Some(selection) = selections_iter.next() {
8180 let mut rows = selection.spanned_rows(false, &display_map);
8181 // duplicate line-wise
8182 if whole_lines || selection.start == selection.end {
8183 // Avoid duplicating the same lines twice.
8184 while let Some(next_selection) = selections_iter.peek() {
8185 let next_rows = next_selection.spanned_rows(false, &display_map);
8186 if next_rows.start < rows.end {
8187 rows.end = next_rows.end;
8188 selections_iter.next().unwrap();
8189 } else {
8190 break;
8191 }
8192 }
8193
8194 // Copy the text from the selected row region and splice it either at the start
8195 // or end of the region.
8196 let start = Point::new(rows.start.0, 0);
8197 let end = Point::new(
8198 rows.end.previous_row().0,
8199 buffer.line_len(rows.end.previous_row()),
8200 );
8201 let text = buffer
8202 .text_for_range(start..end)
8203 .chain(Some("\n"))
8204 .collect::<String>();
8205 let insert_location = if upwards {
8206 Point::new(rows.end.0, 0)
8207 } else {
8208 start
8209 };
8210 edits.push((insert_location..insert_location, text));
8211 } else {
8212 // duplicate character-wise
8213 let start = selection.start;
8214 let end = selection.end;
8215 let text = buffer.text_for_range(start..end).collect::<String>();
8216 edits.push((selection.end..selection.end, text));
8217 }
8218 }
8219
8220 self.transact(window, cx, |this, _, cx| {
8221 this.buffer.update(cx, |buffer, cx| {
8222 buffer.edit(edits, None, cx);
8223 });
8224
8225 this.request_autoscroll(Autoscroll::fit(), cx);
8226 });
8227 }
8228
8229 pub fn duplicate_line_up(
8230 &mut self,
8231 _: &DuplicateLineUp,
8232 window: &mut Window,
8233 cx: &mut Context<Self>,
8234 ) {
8235 self.duplicate(true, true, window, cx);
8236 }
8237
8238 pub fn duplicate_line_down(
8239 &mut self,
8240 _: &DuplicateLineDown,
8241 window: &mut Window,
8242 cx: &mut Context<Self>,
8243 ) {
8244 self.duplicate(false, true, window, cx);
8245 }
8246
8247 pub fn duplicate_selection(
8248 &mut self,
8249 _: &DuplicateSelection,
8250 window: &mut Window,
8251 cx: &mut Context<Self>,
8252 ) {
8253 self.duplicate(false, false, window, cx);
8254 }
8255
8256 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8257 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8258 let buffer = self.buffer.read(cx).snapshot(cx);
8259
8260 let mut edits = Vec::new();
8261 let mut unfold_ranges = Vec::new();
8262 let mut refold_creases = Vec::new();
8263
8264 let selections = self.selections.all::<Point>(cx);
8265 let mut selections = selections.iter().peekable();
8266 let mut contiguous_row_selections = Vec::new();
8267 let mut new_selections = Vec::new();
8268
8269 while let Some(selection) = selections.next() {
8270 // Find all the selections that span a contiguous row range
8271 let (start_row, end_row) = consume_contiguous_rows(
8272 &mut contiguous_row_selections,
8273 selection,
8274 &display_map,
8275 &mut selections,
8276 );
8277
8278 // Move the text spanned by the row range to be before the line preceding the row range
8279 if start_row.0 > 0 {
8280 let range_to_move = Point::new(
8281 start_row.previous_row().0,
8282 buffer.line_len(start_row.previous_row()),
8283 )
8284 ..Point::new(
8285 end_row.previous_row().0,
8286 buffer.line_len(end_row.previous_row()),
8287 );
8288 let insertion_point = display_map
8289 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8290 .0;
8291
8292 // Don't move lines across excerpts
8293 if buffer
8294 .excerpt_containing(insertion_point..range_to_move.end)
8295 .is_some()
8296 {
8297 let text = buffer
8298 .text_for_range(range_to_move.clone())
8299 .flat_map(|s| s.chars())
8300 .skip(1)
8301 .chain(['\n'])
8302 .collect::<String>();
8303
8304 edits.push((
8305 buffer.anchor_after(range_to_move.start)
8306 ..buffer.anchor_before(range_to_move.end),
8307 String::new(),
8308 ));
8309 let insertion_anchor = buffer.anchor_after(insertion_point);
8310 edits.push((insertion_anchor..insertion_anchor, text));
8311
8312 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8313
8314 // Move selections up
8315 new_selections.extend(contiguous_row_selections.drain(..).map(
8316 |mut selection| {
8317 selection.start.row -= row_delta;
8318 selection.end.row -= row_delta;
8319 selection
8320 },
8321 ));
8322
8323 // Move folds up
8324 unfold_ranges.push(range_to_move.clone());
8325 for fold in display_map.folds_in_range(
8326 buffer.anchor_before(range_to_move.start)
8327 ..buffer.anchor_after(range_to_move.end),
8328 ) {
8329 let mut start = fold.range.start.to_point(&buffer);
8330 let mut end = fold.range.end.to_point(&buffer);
8331 start.row -= row_delta;
8332 end.row -= row_delta;
8333 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8334 }
8335 }
8336 }
8337
8338 // If we didn't move line(s), preserve the existing selections
8339 new_selections.append(&mut contiguous_row_selections);
8340 }
8341
8342 self.transact(window, cx, |this, window, cx| {
8343 this.unfold_ranges(&unfold_ranges, true, true, cx);
8344 this.buffer.update(cx, |buffer, cx| {
8345 for (range, text) in edits {
8346 buffer.edit([(range, text)], None, cx);
8347 }
8348 });
8349 this.fold_creases(refold_creases, true, window, cx);
8350 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8351 s.select(new_selections);
8352 })
8353 });
8354 }
8355
8356 pub fn move_line_down(
8357 &mut self,
8358 _: &MoveLineDown,
8359 window: &mut Window,
8360 cx: &mut Context<Self>,
8361 ) {
8362 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8363 let buffer = self.buffer.read(cx).snapshot(cx);
8364
8365 let mut edits = Vec::new();
8366 let mut unfold_ranges = Vec::new();
8367 let mut refold_creases = Vec::new();
8368
8369 let selections = self.selections.all::<Point>(cx);
8370 let mut selections = selections.iter().peekable();
8371 let mut contiguous_row_selections = Vec::new();
8372 let mut new_selections = Vec::new();
8373
8374 while let Some(selection) = selections.next() {
8375 // Find all the selections that span a contiguous row range
8376 let (start_row, end_row) = consume_contiguous_rows(
8377 &mut contiguous_row_selections,
8378 selection,
8379 &display_map,
8380 &mut selections,
8381 );
8382
8383 // Move the text spanned by the row range to be after the last line of the row range
8384 if end_row.0 <= buffer.max_point().row {
8385 let range_to_move =
8386 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
8387 let insertion_point = display_map
8388 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
8389 .0;
8390
8391 // Don't move lines across excerpt boundaries
8392 if buffer
8393 .excerpt_containing(range_to_move.start..insertion_point)
8394 .is_some()
8395 {
8396 let mut text = String::from("\n");
8397 text.extend(buffer.text_for_range(range_to_move.clone()));
8398 text.pop(); // Drop trailing newline
8399 edits.push((
8400 buffer.anchor_after(range_to_move.start)
8401 ..buffer.anchor_before(range_to_move.end),
8402 String::new(),
8403 ));
8404 let insertion_anchor = buffer.anchor_after(insertion_point);
8405 edits.push((insertion_anchor..insertion_anchor, text));
8406
8407 let row_delta = insertion_point.row - range_to_move.end.row + 1;
8408
8409 // Move selections down
8410 new_selections.extend(contiguous_row_selections.drain(..).map(
8411 |mut selection| {
8412 selection.start.row += row_delta;
8413 selection.end.row += row_delta;
8414 selection
8415 },
8416 ));
8417
8418 // Move folds down
8419 unfold_ranges.push(range_to_move.clone());
8420 for fold in display_map.folds_in_range(
8421 buffer.anchor_before(range_to_move.start)
8422 ..buffer.anchor_after(range_to_move.end),
8423 ) {
8424 let mut start = fold.range.start.to_point(&buffer);
8425 let mut end = fold.range.end.to_point(&buffer);
8426 start.row += row_delta;
8427 end.row += row_delta;
8428 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
8429 }
8430 }
8431 }
8432
8433 // If we didn't move line(s), preserve the existing selections
8434 new_selections.append(&mut contiguous_row_selections);
8435 }
8436
8437 self.transact(window, cx, |this, window, cx| {
8438 this.unfold_ranges(&unfold_ranges, true, true, cx);
8439 this.buffer.update(cx, |buffer, cx| {
8440 for (range, text) in edits {
8441 buffer.edit([(range, text)], None, cx);
8442 }
8443 });
8444 this.fold_creases(refold_creases, true, window, cx);
8445 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8446 s.select(new_selections)
8447 });
8448 });
8449 }
8450
8451 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
8452 let text_layout_details = &self.text_layout_details(window);
8453 self.transact(window, cx, |this, window, cx| {
8454 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8455 let mut edits: Vec<(Range<usize>, String)> = Default::default();
8456 let line_mode = s.line_mode;
8457 s.move_with(|display_map, selection| {
8458 if !selection.is_empty() || line_mode {
8459 return;
8460 }
8461
8462 let mut head = selection.head();
8463 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
8464 if head.column() == display_map.line_len(head.row()) {
8465 transpose_offset = display_map
8466 .buffer_snapshot
8467 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8468 }
8469
8470 if transpose_offset == 0 {
8471 return;
8472 }
8473
8474 *head.column_mut() += 1;
8475 head = display_map.clip_point(head, Bias::Right);
8476 let goal = SelectionGoal::HorizontalPosition(
8477 display_map
8478 .x_for_display_point(head, text_layout_details)
8479 .into(),
8480 );
8481 selection.collapse_to(head, goal);
8482
8483 let transpose_start = display_map
8484 .buffer_snapshot
8485 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
8486 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
8487 let transpose_end = display_map
8488 .buffer_snapshot
8489 .clip_offset(transpose_offset + 1, Bias::Right);
8490 if let Some(ch) =
8491 display_map.buffer_snapshot.chars_at(transpose_start).next()
8492 {
8493 edits.push((transpose_start..transpose_offset, String::new()));
8494 edits.push((transpose_end..transpose_end, ch.to_string()));
8495 }
8496 }
8497 });
8498 edits
8499 });
8500 this.buffer
8501 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8502 let selections = this.selections.all::<usize>(cx);
8503 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8504 s.select(selections);
8505 });
8506 });
8507 }
8508
8509 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
8510 self.rewrap_impl(IsVimMode::No, cx)
8511 }
8512
8513 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
8514 let buffer = self.buffer.read(cx).snapshot(cx);
8515 let selections = self.selections.all::<Point>(cx);
8516 let mut selections = selections.iter().peekable();
8517
8518 let mut edits = Vec::new();
8519 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
8520
8521 while let Some(selection) = selections.next() {
8522 let mut start_row = selection.start.row;
8523 let mut end_row = selection.end.row;
8524
8525 // Skip selections that overlap with a range that has already been rewrapped.
8526 let selection_range = start_row..end_row;
8527 if rewrapped_row_ranges
8528 .iter()
8529 .any(|range| range.overlaps(&selection_range))
8530 {
8531 continue;
8532 }
8533
8534 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
8535
8536 // Since not all lines in the selection may be at the same indent
8537 // level, choose the indent size that is the most common between all
8538 // of the lines.
8539 //
8540 // If there is a tie, we use the deepest indent.
8541 let (indent_size, indent_end) = {
8542 let mut indent_size_occurrences = HashMap::default();
8543 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
8544
8545 for row in start_row..=end_row {
8546 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
8547 rows_by_indent_size.entry(indent).or_default().push(row);
8548 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
8549 }
8550
8551 let indent_size = indent_size_occurrences
8552 .into_iter()
8553 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
8554 .map(|(indent, _)| indent)
8555 .unwrap_or_default();
8556 let row = rows_by_indent_size[&indent_size][0];
8557 let indent_end = Point::new(row, indent_size.len);
8558
8559 (indent_size, indent_end)
8560 };
8561
8562 let mut line_prefix = indent_size.chars().collect::<String>();
8563
8564 let mut inside_comment = false;
8565 if let Some(comment_prefix) =
8566 buffer
8567 .language_scope_at(selection.head())
8568 .and_then(|language| {
8569 language
8570 .line_comment_prefixes()
8571 .iter()
8572 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
8573 .cloned()
8574 })
8575 {
8576 line_prefix.push_str(&comment_prefix);
8577 inside_comment = true;
8578 }
8579
8580 let language_settings = buffer.language_settings_at(selection.head(), cx);
8581 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
8582 RewrapBehavior::InComments => inside_comment,
8583 RewrapBehavior::InSelections => !selection.is_empty(),
8584 RewrapBehavior::Anywhere => true,
8585 };
8586
8587 let should_rewrap = is_vim_mode == IsVimMode::Yes || allow_rewrap_based_on_language;
8588 if !should_rewrap {
8589 continue;
8590 }
8591
8592 if selection.is_empty() {
8593 'expand_upwards: while start_row > 0 {
8594 let prev_row = start_row - 1;
8595 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
8596 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
8597 {
8598 start_row = prev_row;
8599 } else {
8600 break 'expand_upwards;
8601 }
8602 }
8603
8604 'expand_downwards: while end_row < buffer.max_point().row {
8605 let next_row = end_row + 1;
8606 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
8607 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
8608 {
8609 end_row = next_row;
8610 } else {
8611 break 'expand_downwards;
8612 }
8613 }
8614 }
8615
8616 let start = Point::new(start_row, 0);
8617 let start_offset = start.to_offset(&buffer);
8618 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
8619 let selection_text = buffer.text_for_range(start..end).collect::<String>();
8620 let Some(lines_without_prefixes) = selection_text
8621 .lines()
8622 .map(|line| {
8623 line.strip_prefix(&line_prefix)
8624 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
8625 .ok_or_else(|| {
8626 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
8627 })
8628 })
8629 .collect::<Result<Vec<_>, _>>()
8630 .log_err()
8631 else {
8632 continue;
8633 };
8634
8635 let wrap_column = buffer
8636 .language_settings_at(Point::new(start_row, 0), cx)
8637 .preferred_line_length as usize;
8638 let wrapped_text = wrap_with_prefix(
8639 line_prefix,
8640 lines_without_prefixes.join(" "),
8641 wrap_column,
8642 tab_size,
8643 );
8644
8645 // TODO: should always use char-based diff while still supporting cursor behavior that
8646 // matches vim.
8647 let mut diff_options = DiffOptions::default();
8648 if is_vim_mode == IsVimMode::Yes {
8649 diff_options.max_word_diff_len = 0;
8650 diff_options.max_word_diff_line_count = 0;
8651 } else {
8652 diff_options.max_word_diff_len = usize::MAX;
8653 diff_options.max_word_diff_line_count = usize::MAX;
8654 }
8655
8656 for (old_range, new_text) in
8657 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
8658 {
8659 let edit_start = buffer.anchor_after(start_offset + old_range.start);
8660 let edit_end = buffer.anchor_after(start_offset + old_range.end);
8661 edits.push((edit_start..edit_end, new_text));
8662 }
8663
8664 rewrapped_row_ranges.push(start_row..=end_row);
8665 }
8666
8667 self.buffer
8668 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
8669 }
8670
8671 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
8672 let mut text = String::new();
8673 let buffer = self.buffer.read(cx).snapshot(cx);
8674 let mut selections = self.selections.all::<Point>(cx);
8675 let mut clipboard_selections = Vec::with_capacity(selections.len());
8676 {
8677 let max_point = buffer.max_point();
8678 let mut is_first = true;
8679 for selection in &mut selections {
8680 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8681 if is_entire_line {
8682 selection.start = Point::new(selection.start.row, 0);
8683 if !selection.is_empty() && selection.end.column == 0 {
8684 selection.end = cmp::min(max_point, selection.end);
8685 } else {
8686 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
8687 }
8688 selection.goal = SelectionGoal::None;
8689 }
8690 if is_first {
8691 is_first = false;
8692 } else {
8693 text += "\n";
8694 }
8695 let mut len = 0;
8696 for chunk in buffer.text_for_range(selection.start..selection.end) {
8697 text.push_str(chunk);
8698 len += chunk.len();
8699 }
8700 clipboard_selections.push(ClipboardSelection {
8701 len,
8702 is_entire_line,
8703 first_line_indent: buffer
8704 .indent_size_for_line(MultiBufferRow(selection.start.row))
8705 .len,
8706 });
8707 }
8708 }
8709
8710 self.transact(window, cx, |this, window, cx| {
8711 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8712 s.select(selections);
8713 });
8714 this.insert("", window, cx);
8715 });
8716 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
8717 }
8718
8719 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
8720 let item = self.cut_common(window, cx);
8721 cx.write_to_clipboard(item);
8722 }
8723
8724 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
8725 self.change_selections(None, window, cx, |s| {
8726 s.move_with(|snapshot, sel| {
8727 if sel.is_empty() {
8728 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
8729 }
8730 });
8731 });
8732 let item = self.cut_common(window, cx);
8733 cx.set_global(KillRing(item))
8734 }
8735
8736 pub fn kill_ring_yank(
8737 &mut self,
8738 _: &KillRingYank,
8739 window: &mut Window,
8740 cx: &mut Context<Self>,
8741 ) {
8742 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
8743 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
8744 (kill_ring.text().to_string(), kill_ring.metadata_json())
8745 } else {
8746 return;
8747 }
8748 } else {
8749 return;
8750 };
8751 self.do_paste(&text, metadata, false, window, cx);
8752 }
8753
8754 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
8755 let selections = self.selections.all::<Point>(cx);
8756 let buffer = self.buffer.read(cx).read(cx);
8757 let mut text = String::new();
8758
8759 let mut clipboard_selections = Vec::with_capacity(selections.len());
8760 {
8761 let max_point = buffer.max_point();
8762 let mut is_first = true;
8763 for selection in selections.iter() {
8764 let mut start = selection.start;
8765 let mut end = selection.end;
8766 let is_entire_line = selection.is_empty() || self.selections.line_mode;
8767 if is_entire_line {
8768 start = Point::new(start.row, 0);
8769 end = cmp::min(max_point, Point::new(end.row + 1, 0));
8770 }
8771 if is_first {
8772 is_first = false;
8773 } else {
8774 text += "\n";
8775 }
8776 let mut len = 0;
8777 for chunk in buffer.text_for_range(start..end) {
8778 text.push_str(chunk);
8779 len += chunk.len();
8780 }
8781 clipboard_selections.push(ClipboardSelection {
8782 len,
8783 is_entire_line,
8784 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
8785 });
8786 }
8787 }
8788
8789 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
8790 text,
8791 clipboard_selections,
8792 ));
8793 }
8794
8795 pub fn do_paste(
8796 &mut self,
8797 text: &String,
8798 clipboard_selections: Option<Vec<ClipboardSelection>>,
8799 handle_entire_lines: bool,
8800 window: &mut Window,
8801 cx: &mut Context<Self>,
8802 ) {
8803 if self.read_only(cx) {
8804 return;
8805 }
8806
8807 let clipboard_text = Cow::Borrowed(text);
8808
8809 self.transact(window, cx, |this, window, cx| {
8810 if let Some(mut clipboard_selections) = clipboard_selections {
8811 let old_selections = this.selections.all::<usize>(cx);
8812 let all_selections_were_entire_line =
8813 clipboard_selections.iter().all(|s| s.is_entire_line);
8814 let first_selection_indent_column =
8815 clipboard_selections.first().map(|s| s.first_line_indent);
8816 if clipboard_selections.len() != old_selections.len() {
8817 clipboard_selections.drain(..);
8818 }
8819 let cursor_offset = this.selections.last::<usize>(cx).head();
8820 let mut auto_indent_on_paste = true;
8821
8822 this.buffer.update(cx, |buffer, cx| {
8823 let snapshot = buffer.read(cx);
8824 auto_indent_on_paste = snapshot
8825 .language_settings_at(cursor_offset, cx)
8826 .auto_indent_on_paste;
8827
8828 let mut start_offset = 0;
8829 let mut edits = Vec::new();
8830 let mut original_indent_columns = Vec::new();
8831 for (ix, selection) in old_selections.iter().enumerate() {
8832 let to_insert;
8833 let entire_line;
8834 let original_indent_column;
8835 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
8836 let end_offset = start_offset + clipboard_selection.len;
8837 to_insert = &clipboard_text[start_offset..end_offset];
8838 entire_line = clipboard_selection.is_entire_line;
8839 start_offset = end_offset + 1;
8840 original_indent_column = Some(clipboard_selection.first_line_indent);
8841 } else {
8842 to_insert = clipboard_text.as_str();
8843 entire_line = all_selections_were_entire_line;
8844 original_indent_column = first_selection_indent_column
8845 }
8846
8847 // If the corresponding selection was empty when this slice of the
8848 // clipboard text was written, then the entire line containing the
8849 // selection was copied. If this selection is also currently empty,
8850 // then paste the line before the current line of the buffer.
8851 let range = if selection.is_empty() && handle_entire_lines && entire_line {
8852 let column = selection.start.to_point(&snapshot).column as usize;
8853 let line_start = selection.start - column;
8854 line_start..line_start
8855 } else {
8856 selection.range()
8857 };
8858
8859 edits.push((range, to_insert));
8860 original_indent_columns.push(original_indent_column);
8861 }
8862 drop(snapshot);
8863
8864 buffer.edit(
8865 edits,
8866 if auto_indent_on_paste {
8867 Some(AutoindentMode::Block {
8868 original_indent_columns,
8869 })
8870 } else {
8871 None
8872 },
8873 cx,
8874 );
8875 });
8876
8877 let selections = this.selections.all::<usize>(cx);
8878 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8879 s.select(selections)
8880 });
8881 } else {
8882 this.insert(&clipboard_text, window, cx);
8883 }
8884 });
8885 }
8886
8887 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
8888 if let Some(item) = cx.read_from_clipboard() {
8889 let entries = item.entries();
8890
8891 match entries.first() {
8892 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
8893 // of all the pasted entries.
8894 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
8895 .do_paste(
8896 clipboard_string.text(),
8897 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
8898 true,
8899 window,
8900 cx,
8901 ),
8902 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
8903 }
8904 }
8905 }
8906
8907 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
8908 if self.read_only(cx) {
8909 return;
8910 }
8911
8912 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
8913 if let Some((selections, _)) =
8914 self.selection_history.transaction(transaction_id).cloned()
8915 {
8916 self.change_selections(None, window, cx, |s| {
8917 s.select_anchors(selections.to_vec());
8918 });
8919 } else {
8920 log::error!(
8921 "No entry in selection_history found for undo. \
8922 This may correspond to a bug where undo does not update the selection. \
8923 If this is occurring, please add details to \
8924 https://github.com/zed-industries/zed/issues/22692"
8925 );
8926 }
8927 self.request_autoscroll(Autoscroll::fit(), cx);
8928 self.unmark_text(window, cx);
8929 self.refresh_inline_completion(true, false, window, cx);
8930 cx.emit(EditorEvent::Edited { transaction_id });
8931 cx.emit(EditorEvent::TransactionUndone { transaction_id });
8932 }
8933 }
8934
8935 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
8936 if self.read_only(cx) {
8937 return;
8938 }
8939
8940 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
8941 if let Some((_, Some(selections))) =
8942 self.selection_history.transaction(transaction_id).cloned()
8943 {
8944 self.change_selections(None, window, cx, |s| {
8945 s.select_anchors(selections.to_vec());
8946 });
8947 } else {
8948 log::error!(
8949 "No entry in selection_history found for redo. \
8950 This may correspond to a bug where undo does not update the selection. \
8951 If this is occurring, please add details to \
8952 https://github.com/zed-industries/zed/issues/22692"
8953 );
8954 }
8955 self.request_autoscroll(Autoscroll::fit(), cx);
8956 self.unmark_text(window, cx);
8957 self.refresh_inline_completion(true, false, window, cx);
8958 cx.emit(EditorEvent::Edited { transaction_id });
8959 }
8960 }
8961
8962 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
8963 self.buffer
8964 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
8965 }
8966
8967 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
8968 self.buffer
8969 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
8970 }
8971
8972 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
8973 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8974 let line_mode = s.line_mode;
8975 s.move_with(|map, selection| {
8976 let cursor = if selection.is_empty() && !line_mode {
8977 movement::left(map, selection.start)
8978 } else {
8979 selection.start
8980 };
8981 selection.collapse_to(cursor, SelectionGoal::None);
8982 });
8983 })
8984 }
8985
8986 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
8987 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8988 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
8989 })
8990 }
8991
8992 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
8993 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8994 let line_mode = s.line_mode;
8995 s.move_with(|map, selection| {
8996 let cursor = if selection.is_empty() && !line_mode {
8997 movement::right(map, selection.end)
8998 } else {
8999 selection.end
9000 };
9001 selection.collapse_to(cursor, SelectionGoal::None)
9002 });
9003 })
9004 }
9005
9006 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9007 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9008 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9009 })
9010 }
9011
9012 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9013 if self.take_rename(true, window, cx).is_some() {
9014 return;
9015 }
9016
9017 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9018 cx.propagate();
9019 return;
9020 }
9021
9022 let text_layout_details = &self.text_layout_details(window);
9023 let selection_count = self.selections.count();
9024 let first_selection = self.selections.first_anchor();
9025
9026 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9027 let line_mode = s.line_mode;
9028 s.move_with(|map, selection| {
9029 if !selection.is_empty() && !line_mode {
9030 selection.goal = SelectionGoal::None;
9031 }
9032 let (cursor, goal) = movement::up(
9033 map,
9034 selection.start,
9035 selection.goal,
9036 false,
9037 text_layout_details,
9038 );
9039 selection.collapse_to(cursor, goal);
9040 });
9041 });
9042
9043 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9044 {
9045 cx.propagate();
9046 }
9047 }
9048
9049 pub fn move_up_by_lines(
9050 &mut self,
9051 action: &MoveUpByLines,
9052 window: &mut Window,
9053 cx: &mut Context<Self>,
9054 ) {
9055 if self.take_rename(true, window, cx).is_some() {
9056 return;
9057 }
9058
9059 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9060 cx.propagate();
9061 return;
9062 }
9063
9064 let text_layout_details = &self.text_layout_details(window);
9065
9066 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9067 let line_mode = s.line_mode;
9068 s.move_with(|map, selection| {
9069 if !selection.is_empty() && !line_mode {
9070 selection.goal = SelectionGoal::None;
9071 }
9072 let (cursor, goal) = movement::up_by_rows(
9073 map,
9074 selection.start,
9075 action.lines,
9076 selection.goal,
9077 false,
9078 text_layout_details,
9079 );
9080 selection.collapse_to(cursor, goal);
9081 });
9082 })
9083 }
9084
9085 pub fn move_down_by_lines(
9086 &mut self,
9087 action: &MoveDownByLines,
9088 window: &mut Window,
9089 cx: &mut Context<Self>,
9090 ) {
9091 if self.take_rename(true, window, cx).is_some() {
9092 return;
9093 }
9094
9095 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9096 cx.propagate();
9097 return;
9098 }
9099
9100 let text_layout_details = &self.text_layout_details(window);
9101
9102 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9103 let line_mode = s.line_mode;
9104 s.move_with(|map, selection| {
9105 if !selection.is_empty() && !line_mode {
9106 selection.goal = SelectionGoal::None;
9107 }
9108 let (cursor, goal) = movement::down_by_rows(
9109 map,
9110 selection.start,
9111 action.lines,
9112 selection.goal,
9113 false,
9114 text_layout_details,
9115 );
9116 selection.collapse_to(cursor, goal);
9117 });
9118 })
9119 }
9120
9121 pub fn select_down_by_lines(
9122 &mut self,
9123 action: &SelectDownByLines,
9124 window: &mut Window,
9125 cx: &mut Context<Self>,
9126 ) {
9127 let text_layout_details = &self.text_layout_details(window);
9128 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9129 s.move_heads_with(|map, head, goal| {
9130 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9131 })
9132 })
9133 }
9134
9135 pub fn select_up_by_lines(
9136 &mut self,
9137 action: &SelectUpByLines,
9138 window: &mut Window,
9139 cx: &mut Context<Self>,
9140 ) {
9141 let text_layout_details = &self.text_layout_details(window);
9142 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9143 s.move_heads_with(|map, head, goal| {
9144 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9145 })
9146 })
9147 }
9148
9149 pub fn select_page_up(
9150 &mut self,
9151 _: &SelectPageUp,
9152 window: &mut Window,
9153 cx: &mut Context<Self>,
9154 ) {
9155 let Some(row_count) = self.visible_row_count() else {
9156 return;
9157 };
9158
9159 let text_layout_details = &self.text_layout_details(window);
9160
9161 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9162 s.move_heads_with(|map, head, goal| {
9163 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9164 })
9165 })
9166 }
9167
9168 pub fn move_page_up(
9169 &mut self,
9170 action: &MovePageUp,
9171 window: &mut Window,
9172 cx: &mut Context<Self>,
9173 ) {
9174 if self.take_rename(true, window, cx).is_some() {
9175 return;
9176 }
9177
9178 if self
9179 .context_menu
9180 .borrow_mut()
9181 .as_mut()
9182 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9183 .unwrap_or(false)
9184 {
9185 return;
9186 }
9187
9188 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9189 cx.propagate();
9190 return;
9191 }
9192
9193 let Some(row_count) = self.visible_row_count() else {
9194 return;
9195 };
9196
9197 let autoscroll = if action.center_cursor {
9198 Autoscroll::center()
9199 } else {
9200 Autoscroll::fit()
9201 };
9202
9203 let text_layout_details = &self.text_layout_details(window);
9204
9205 self.change_selections(Some(autoscroll), window, cx, |s| {
9206 let line_mode = s.line_mode;
9207 s.move_with(|map, selection| {
9208 if !selection.is_empty() && !line_mode {
9209 selection.goal = SelectionGoal::None;
9210 }
9211 let (cursor, goal) = movement::up_by_rows(
9212 map,
9213 selection.end,
9214 row_count,
9215 selection.goal,
9216 false,
9217 text_layout_details,
9218 );
9219 selection.collapse_to(cursor, goal);
9220 });
9221 });
9222 }
9223
9224 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9225 let text_layout_details = &self.text_layout_details(window);
9226 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9227 s.move_heads_with(|map, head, goal| {
9228 movement::up(map, head, goal, false, text_layout_details)
9229 })
9230 })
9231 }
9232
9233 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9234 self.take_rename(true, window, cx);
9235
9236 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9237 cx.propagate();
9238 return;
9239 }
9240
9241 let text_layout_details = &self.text_layout_details(window);
9242 let selection_count = self.selections.count();
9243 let first_selection = self.selections.first_anchor();
9244
9245 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9246 let line_mode = s.line_mode;
9247 s.move_with(|map, selection| {
9248 if !selection.is_empty() && !line_mode {
9249 selection.goal = SelectionGoal::None;
9250 }
9251 let (cursor, goal) = movement::down(
9252 map,
9253 selection.end,
9254 selection.goal,
9255 false,
9256 text_layout_details,
9257 );
9258 selection.collapse_to(cursor, goal);
9259 });
9260 });
9261
9262 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9263 {
9264 cx.propagate();
9265 }
9266 }
9267
9268 pub fn select_page_down(
9269 &mut self,
9270 _: &SelectPageDown,
9271 window: &mut Window,
9272 cx: &mut Context<Self>,
9273 ) {
9274 let Some(row_count) = self.visible_row_count() else {
9275 return;
9276 };
9277
9278 let text_layout_details = &self.text_layout_details(window);
9279
9280 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9281 s.move_heads_with(|map, head, goal| {
9282 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9283 })
9284 })
9285 }
9286
9287 pub fn move_page_down(
9288 &mut self,
9289 action: &MovePageDown,
9290 window: &mut Window,
9291 cx: &mut Context<Self>,
9292 ) {
9293 if self.take_rename(true, window, cx).is_some() {
9294 return;
9295 }
9296
9297 if self
9298 .context_menu
9299 .borrow_mut()
9300 .as_mut()
9301 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9302 .unwrap_or(false)
9303 {
9304 return;
9305 }
9306
9307 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9308 cx.propagate();
9309 return;
9310 }
9311
9312 let Some(row_count) = self.visible_row_count() else {
9313 return;
9314 };
9315
9316 let autoscroll = if action.center_cursor {
9317 Autoscroll::center()
9318 } else {
9319 Autoscroll::fit()
9320 };
9321
9322 let text_layout_details = &self.text_layout_details(window);
9323 self.change_selections(Some(autoscroll), window, cx, |s| {
9324 let line_mode = s.line_mode;
9325 s.move_with(|map, selection| {
9326 if !selection.is_empty() && !line_mode {
9327 selection.goal = SelectionGoal::None;
9328 }
9329 let (cursor, goal) = movement::down_by_rows(
9330 map,
9331 selection.end,
9332 row_count,
9333 selection.goal,
9334 false,
9335 text_layout_details,
9336 );
9337 selection.collapse_to(cursor, goal);
9338 });
9339 });
9340 }
9341
9342 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
9343 let text_layout_details = &self.text_layout_details(window);
9344 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9345 s.move_heads_with(|map, head, goal| {
9346 movement::down(map, head, goal, false, text_layout_details)
9347 })
9348 });
9349 }
9350
9351 pub fn context_menu_first(
9352 &mut self,
9353 _: &ContextMenuFirst,
9354 _window: &mut Window,
9355 cx: &mut Context<Self>,
9356 ) {
9357 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9358 context_menu.select_first(self.completion_provider.as_deref(), cx);
9359 }
9360 }
9361
9362 pub fn context_menu_prev(
9363 &mut self,
9364 _: &ContextMenuPrevious,
9365 _window: &mut Window,
9366 cx: &mut Context<Self>,
9367 ) {
9368 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9369 context_menu.select_prev(self.completion_provider.as_deref(), cx);
9370 }
9371 }
9372
9373 pub fn context_menu_next(
9374 &mut self,
9375 _: &ContextMenuNext,
9376 _window: &mut Window,
9377 cx: &mut Context<Self>,
9378 ) {
9379 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9380 context_menu.select_next(self.completion_provider.as_deref(), cx);
9381 }
9382 }
9383
9384 pub fn context_menu_last(
9385 &mut self,
9386 _: &ContextMenuLast,
9387 _window: &mut Window,
9388 cx: &mut Context<Self>,
9389 ) {
9390 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
9391 context_menu.select_last(self.completion_provider.as_deref(), cx);
9392 }
9393 }
9394
9395 pub fn move_to_previous_word_start(
9396 &mut self,
9397 _: &MoveToPreviousWordStart,
9398 window: &mut Window,
9399 cx: &mut Context<Self>,
9400 ) {
9401 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9402 s.move_cursors_with(|map, head, _| {
9403 (
9404 movement::previous_word_start(map, head),
9405 SelectionGoal::None,
9406 )
9407 });
9408 })
9409 }
9410
9411 pub fn move_to_previous_subword_start(
9412 &mut self,
9413 _: &MoveToPreviousSubwordStart,
9414 window: &mut Window,
9415 cx: &mut Context<Self>,
9416 ) {
9417 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9418 s.move_cursors_with(|map, head, _| {
9419 (
9420 movement::previous_subword_start(map, head),
9421 SelectionGoal::None,
9422 )
9423 });
9424 })
9425 }
9426
9427 pub fn select_to_previous_word_start(
9428 &mut self,
9429 _: &SelectToPreviousWordStart,
9430 window: &mut Window,
9431 cx: &mut Context<Self>,
9432 ) {
9433 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9434 s.move_heads_with(|map, head, _| {
9435 (
9436 movement::previous_word_start(map, head),
9437 SelectionGoal::None,
9438 )
9439 });
9440 })
9441 }
9442
9443 pub fn select_to_previous_subword_start(
9444 &mut self,
9445 _: &SelectToPreviousSubwordStart,
9446 window: &mut Window,
9447 cx: &mut Context<Self>,
9448 ) {
9449 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9450 s.move_heads_with(|map, head, _| {
9451 (
9452 movement::previous_subword_start(map, head),
9453 SelectionGoal::None,
9454 )
9455 });
9456 })
9457 }
9458
9459 pub fn delete_to_previous_word_start(
9460 &mut self,
9461 action: &DeleteToPreviousWordStart,
9462 window: &mut Window,
9463 cx: &mut Context<Self>,
9464 ) {
9465 self.transact(window, cx, |this, window, cx| {
9466 this.select_autoclose_pair(window, cx);
9467 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9468 let line_mode = s.line_mode;
9469 s.move_with(|map, selection| {
9470 if selection.is_empty() && !line_mode {
9471 let cursor = if action.ignore_newlines {
9472 movement::previous_word_start(map, selection.head())
9473 } else {
9474 movement::previous_word_start_or_newline(map, selection.head())
9475 };
9476 selection.set_head(cursor, SelectionGoal::None);
9477 }
9478 });
9479 });
9480 this.insert("", window, cx);
9481 });
9482 }
9483
9484 pub fn delete_to_previous_subword_start(
9485 &mut self,
9486 _: &DeleteToPreviousSubwordStart,
9487 window: &mut Window,
9488 cx: &mut Context<Self>,
9489 ) {
9490 self.transact(window, cx, |this, window, cx| {
9491 this.select_autoclose_pair(window, cx);
9492 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9493 let line_mode = s.line_mode;
9494 s.move_with(|map, selection| {
9495 if selection.is_empty() && !line_mode {
9496 let cursor = movement::previous_subword_start(map, selection.head());
9497 selection.set_head(cursor, SelectionGoal::None);
9498 }
9499 });
9500 });
9501 this.insert("", window, cx);
9502 });
9503 }
9504
9505 pub fn move_to_next_word_end(
9506 &mut self,
9507 _: &MoveToNextWordEnd,
9508 window: &mut Window,
9509 cx: &mut Context<Self>,
9510 ) {
9511 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9512 s.move_cursors_with(|map, head, _| {
9513 (movement::next_word_end(map, head), SelectionGoal::None)
9514 });
9515 })
9516 }
9517
9518 pub fn move_to_next_subword_end(
9519 &mut self,
9520 _: &MoveToNextSubwordEnd,
9521 window: &mut Window,
9522 cx: &mut Context<Self>,
9523 ) {
9524 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9525 s.move_cursors_with(|map, head, _| {
9526 (movement::next_subword_end(map, head), SelectionGoal::None)
9527 });
9528 })
9529 }
9530
9531 pub fn select_to_next_word_end(
9532 &mut self,
9533 _: &SelectToNextWordEnd,
9534 window: &mut Window,
9535 cx: &mut Context<Self>,
9536 ) {
9537 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9538 s.move_heads_with(|map, head, _| {
9539 (movement::next_word_end(map, head), SelectionGoal::None)
9540 });
9541 })
9542 }
9543
9544 pub fn select_to_next_subword_end(
9545 &mut self,
9546 _: &SelectToNextSubwordEnd,
9547 window: &mut Window,
9548 cx: &mut Context<Self>,
9549 ) {
9550 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9551 s.move_heads_with(|map, head, _| {
9552 (movement::next_subword_end(map, head), SelectionGoal::None)
9553 });
9554 })
9555 }
9556
9557 pub fn delete_to_next_word_end(
9558 &mut self,
9559 action: &DeleteToNextWordEnd,
9560 window: &mut Window,
9561 cx: &mut Context<Self>,
9562 ) {
9563 self.transact(window, cx, |this, window, cx| {
9564 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9565 let line_mode = s.line_mode;
9566 s.move_with(|map, selection| {
9567 if selection.is_empty() && !line_mode {
9568 let cursor = if action.ignore_newlines {
9569 movement::next_word_end(map, selection.head())
9570 } else {
9571 movement::next_word_end_or_newline(map, selection.head())
9572 };
9573 selection.set_head(cursor, SelectionGoal::None);
9574 }
9575 });
9576 });
9577 this.insert("", window, cx);
9578 });
9579 }
9580
9581 pub fn delete_to_next_subword_end(
9582 &mut self,
9583 _: &DeleteToNextSubwordEnd,
9584 window: &mut Window,
9585 cx: &mut Context<Self>,
9586 ) {
9587 self.transact(window, cx, |this, window, cx| {
9588 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9589 s.move_with(|map, selection| {
9590 if selection.is_empty() {
9591 let cursor = movement::next_subword_end(map, selection.head());
9592 selection.set_head(cursor, SelectionGoal::None);
9593 }
9594 });
9595 });
9596 this.insert("", window, cx);
9597 });
9598 }
9599
9600 pub fn move_to_beginning_of_line(
9601 &mut self,
9602 action: &MoveToBeginningOfLine,
9603 window: &mut Window,
9604 cx: &mut Context<Self>,
9605 ) {
9606 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9607 s.move_cursors_with(|map, head, _| {
9608 (
9609 movement::indented_line_beginning(
9610 map,
9611 head,
9612 action.stop_at_soft_wraps,
9613 action.stop_at_indent,
9614 ),
9615 SelectionGoal::None,
9616 )
9617 });
9618 })
9619 }
9620
9621 pub fn select_to_beginning_of_line(
9622 &mut self,
9623 action: &SelectToBeginningOfLine,
9624 window: &mut Window,
9625 cx: &mut Context<Self>,
9626 ) {
9627 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9628 s.move_heads_with(|map, head, _| {
9629 (
9630 movement::indented_line_beginning(
9631 map,
9632 head,
9633 action.stop_at_soft_wraps,
9634 action.stop_at_indent,
9635 ),
9636 SelectionGoal::None,
9637 )
9638 });
9639 });
9640 }
9641
9642 pub fn delete_to_beginning_of_line(
9643 &mut self,
9644 action: &DeleteToBeginningOfLine,
9645 window: &mut Window,
9646 cx: &mut Context<Self>,
9647 ) {
9648 self.transact(window, cx, |this, window, cx| {
9649 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9650 s.move_with(|_, selection| {
9651 selection.reversed = true;
9652 });
9653 });
9654
9655 this.select_to_beginning_of_line(
9656 &SelectToBeginningOfLine {
9657 stop_at_soft_wraps: false,
9658 stop_at_indent: action.stop_at_indent,
9659 },
9660 window,
9661 cx,
9662 );
9663 this.backspace(&Backspace, window, cx);
9664 });
9665 }
9666
9667 pub fn move_to_end_of_line(
9668 &mut self,
9669 action: &MoveToEndOfLine,
9670 window: &mut Window,
9671 cx: &mut Context<Self>,
9672 ) {
9673 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9674 s.move_cursors_with(|map, head, _| {
9675 (
9676 movement::line_end(map, head, action.stop_at_soft_wraps),
9677 SelectionGoal::None,
9678 )
9679 });
9680 })
9681 }
9682
9683 pub fn select_to_end_of_line(
9684 &mut self,
9685 action: &SelectToEndOfLine,
9686 window: &mut Window,
9687 cx: &mut Context<Self>,
9688 ) {
9689 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9690 s.move_heads_with(|map, head, _| {
9691 (
9692 movement::line_end(map, head, action.stop_at_soft_wraps),
9693 SelectionGoal::None,
9694 )
9695 });
9696 })
9697 }
9698
9699 pub fn delete_to_end_of_line(
9700 &mut self,
9701 _: &DeleteToEndOfLine,
9702 window: &mut Window,
9703 cx: &mut Context<Self>,
9704 ) {
9705 self.transact(window, cx, |this, window, cx| {
9706 this.select_to_end_of_line(
9707 &SelectToEndOfLine {
9708 stop_at_soft_wraps: false,
9709 },
9710 window,
9711 cx,
9712 );
9713 this.delete(&Delete, window, cx);
9714 });
9715 }
9716
9717 pub fn cut_to_end_of_line(
9718 &mut self,
9719 _: &CutToEndOfLine,
9720 window: &mut Window,
9721 cx: &mut Context<Self>,
9722 ) {
9723 self.transact(window, cx, |this, window, cx| {
9724 this.select_to_end_of_line(
9725 &SelectToEndOfLine {
9726 stop_at_soft_wraps: false,
9727 },
9728 window,
9729 cx,
9730 );
9731 this.cut(&Cut, window, cx);
9732 });
9733 }
9734
9735 pub fn move_to_start_of_paragraph(
9736 &mut self,
9737 _: &MoveToStartOfParagraph,
9738 window: &mut Window,
9739 cx: &mut Context<Self>,
9740 ) {
9741 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9742 cx.propagate();
9743 return;
9744 }
9745
9746 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9747 s.move_with(|map, selection| {
9748 selection.collapse_to(
9749 movement::start_of_paragraph(map, selection.head(), 1),
9750 SelectionGoal::None,
9751 )
9752 });
9753 })
9754 }
9755
9756 pub fn move_to_end_of_paragraph(
9757 &mut self,
9758 _: &MoveToEndOfParagraph,
9759 window: &mut Window,
9760 cx: &mut Context<Self>,
9761 ) {
9762 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9763 cx.propagate();
9764 return;
9765 }
9766
9767 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9768 s.move_with(|map, selection| {
9769 selection.collapse_to(
9770 movement::end_of_paragraph(map, selection.head(), 1),
9771 SelectionGoal::None,
9772 )
9773 });
9774 })
9775 }
9776
9777 pub fn select_to_start_of_paragraph(
9778 &mut self,
9779 _: &SelectToStartOfParagraph,
9780 window: &mut Window,
9781 cx: &mut Context<Self>,
9782 ) {
9783 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9784 cx.propagate();
9785 return;
9786 }
9787
9788 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9789 s.move_heads_with(|map, head, _| {
9790 (
9791 movement::start_of_paragraph(map, head, 1),
9792 SelectionGoal::None,
9793 )
9794 });
9795 })
9796 }
9797
9798 pub fn select_to_end_of_paragraph(
9799 &mut self,
9800 _: &SelectToEndOfParagraph,
9801 window: &mut Window,
9802 cx: &mut Context<Self>,
9803 ) {
9804 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9805 cx.propagate();
9806 return;
9807 }
9808
9809 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9810 s.move_heads_with(|map, head, _| {
9811 (
9812 movement::end_of_paragraph(map, head, 1),
9813 SelectionGoal::None,
9814 )
9815 });
9816 })
9817 }
9818
9819 pub fn move_to_start_of_excerpt(
9820 &mut self,
9821 _: &MoveToStartOfExcerpt,
9822 window: &mut Window,
9823 cx: &mut Context<Self>,
9824 ) {
9825 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9826 cx.propagate();
9827 return;
9828 }
9829
9830 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9831 s.move_with(|map, selection| {
9832 selection.collapse_to(
9833 movement::start_of_excerpt(
9834 map,
9835 selection.head(),
9836 workspace::searchable::Direction::Prev,
9837 ),
9838 SelectionGoal::None,
9839 )
9840 });
9841 })
9842 }
9843
9844 pub fn move_to_start_of_next_excerpt(
9845 &mut self,
9846 _: &MoveToStartOfNextExcerpt,
9847 window: &mut Window,
9848 cx: &mut Context<Self>,
9849 ) {
9850 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9851 cx.propagate();
9852 return;
9853 }
9854
9855 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9856 s.move_with(|map, selection| {
9857 selection.collapse_to(
9858 movement::start_of_excerpt(
9859 map,
9860 selection.head(),
9861 workspace::searchable::Direction::Next,
9862 ),
9863 SelectionGoal::None,
9864 )
9865 });
9866 })
9867 }
9868
9869 pub fn move_to_end_of_excerpt(
9870 &mut self,
9871 _: &MoveToEndOfExcerpt,
9872 window: &mut Window,
9873 cx: &mut Context<Self>,
9874 ) {
9875 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9876 cx.propagate();
9877 return;
9878 }
9879
9880 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9881 s.move_with(|map, selection| {
9882 selection.collapse_to(
9883 movement::end_of_excerpt(
9884 map,
9885 selection.head(),
9886 workspace::searchable::Direction::Next,
9887 ),
9888 SelectionGoal::None,
9889 )
9890 });
9891 })
9892 }
9893
9894 pub fn move_to_end_of_previous_excerpt(
9895 &mut self,
9896 _: &MoveToEndOfPreviousExcerpt,
9897 window: &mut Window,
9898 cx: &mut Context<Self>,
9899 ) {
9900 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9901 cx.propagate();
9902 return;
9903 }
9904
9905 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9906 s.move_with(|map, selection| {
9907 selection.collapse_to(
9908 movement::end_of_excerpt(
9909 map,
9910 selection.head(),
9911 workspace::searchable::Direction::Prev,
9912 ),
9913 SelectionGoal::None,
9914 )
9915 });
9916 })
9917 }
9918
9919 pub fn select_to_start_of_excerpt(
9920 &mut self,
9921 _: &SelectToStartOfExcerpt,
9922 window: &mut Window,
9923 cx: &mut Context<Self>,
9924 ) {
9925 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9926 cx.propagate();
9927 return;
9928 }
9929
9930 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9931 s.move_heads_with(|map, head, _| {
9932 (
9933 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9934 SelectionGoal::None,
9935 )
9936 });
9937 })
9938 }
9939
9940 pub fn select_to_start_of_next_excerpt(
9941 &mut self,
9942 _: &SelectToStartOfNextExcerpt,
9943 window: &mut Window,
9944 cx: &mut Context<Self>,
9945 ) {
9946 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9947 cx.propagate();
9948 return;
9949 }
9950
9951 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9952 s.move_heads_with(|map, head, _| {
9953 (
9954 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
9955 SelectionGoal::None,
9956 )
9957 });
9958 })
9959 }
9960
9961 pub fn select_to_end_of_excerpt(
9962 &mut self,
9963 _: &SelectToEndOfExcerpt,
9964 window: &mut Window,
9965 cx: &mut Context<Self>,
9966 ) {
9967 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9968 cx.propagate();
9969 return;
9970 }
9971
9972 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9973 s.move_heads_with(|map, head, _| {
9974 (
9975 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
9976 SelectionGoal::None,
9977 )
9978 });
9979 })
9980 }
9981
9982 pub fn select_to_end_of_previous_excerpt(
9983 &mut self,
9984 _: &SelectToEndOfPreviousExcerpt,
9985 window: &mut Window,
9986 cx: &mut Context<Self>,
9987 ) {
9988 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9989 cx.propagate();
9990 return;
9991 }
9992
9993 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9994 s.move_heads_with(|map, head, _| {
9995 (
9996 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
9997 SelectionGoal::None,
9998 )
9999 });
10000 })
10001 }
10002
10003 pub fn move_to_beginning(
10004 &mut self,
10005 _: &MoveToBeginning,
10006 window: &mut Window,
10007 cx: &mut Context<Self>,
10008 ) {
10009 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10010 cx.propagate();
10011 return;
10012 }
10013
10014 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10015 s.select_ranges(vec![0..0]);
10016 });
10017 }
10018
10019 pub fn select_to_beginning(
10020 &mut self,
10021 _: &SelectToBeginning,
10022 window: &mut Window,
10023 cx: &mut Context<Self>,
10024 ) {
10025 let mut selection = self.selections.last::<Point>(cx);
10026 selection.set_head(Point::zero(), SelectionGoal::None);
10027
10028 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10029 s.select(vec![selection]);
10030 });
10031 }
10032
10033 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10034 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10035 cx.propagate();
10036 return;
10037 }
10038
10039 let cursor = self.buffer.read(cx).read(cx).len();
10040 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10041 s.select_ranges(vec![cursor..cursor])
10042 });
10043 }
10044
10045 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10046 self.nav_history = nav_history;
10047 }
10048
10049 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10050 self.nav_history.as_ref()
10051 }
10052
10053 fn push_to_nav_history(
10054 &mut self,
10055 cursor_anchor: Anchor,
10056 new_position: Option<Point>,
10057 cx: &mut Context<Self>,
10058 ) {
10059 if let Some(nav_history) = self.nav_history.as_mut() {
10060 let buffer = self.buffer.read(cx).read(cx);
10061 let cursor_position = cursor_anchor.to_point(&buffer);
10062 let scroll_state = self.scroll_manager.anchor();
10063 let scroll_top_row = scroll_state.top_row(&buffer);
10064 drop(buffer);
10065
10066 if let Some(new_position) = new_position {
10067 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10068 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10069 return;
10070 }
10071 }
10072
10073 nav_history.push(
10074 Some(NavigationData {
10075 cursor_anchor,
10076 cursor_position,
10077 scroll_anchor: scroll_state,
10078 scroll_top_row,
10079 }),
10080 cx,
10081 );
10082 }
10083 }
10084
10085 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10086 let buffer = self.buffer.read(cx).snapshot(cx);
10087 let mut selection = self.selections.first::<usize>(cx);
10088 selection.set_head(buffer.len(), SelectionGoal::None);
10089 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10090 s.select(vec![selection]);
10091 });
10092 }
10093
10094 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10095 let end = self.buffer.read(cx).read(cx).len();
10096 self.change_selections(None, window, cx, |s| {
10097 s.select_ranges(vec![0..end]);
10098 });
10099 }
10100
10101 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10102 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10103 let mut selections = self.selections.all::<Point>(cx);
10104 let max_point = display_map.buffer_snapshot.max_point();
10105 for selection in &mut selections {
10106 let rows = selection.spanned_rows(true, &display_map);
10107 selection.start = Point::new(rows.start.0, 0);
10108 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10109 selection.reversed = false;
10110 }
10111 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10112 s.select(selections);
10113 });
10114 }
10115
10116 pub fn split_selection_into_lines(
10117 &mut self,
10118 _: &SplitSelectionIntoLines,
10119 window: &mut Window,
10120 cx: &mut Context<Self>,
10121 ) {
10122 let selections = self
10123 .selections
10124 .all::<Point>(cx)
10125 .into_iter()
10126 .map(|selection| selection.start..selection.end)
10127 .collect::<Vec<_>>();
10128 self.unfold_ranges(&selections, true, true, cx);
10129
10130 let mut new_selection_ranges = Vec::new();
10131 {
10132 let buffer = self.buffer.read(cx).read(cx);
10133 for selection in selections {
10134 for row in selection.start.row..selection.end.row {
10135 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10136 new_selection_ranges.push(cursor..cursor);
10137 }
10138
10139 let is_multiline_selection = selection.start.row != selection.end.row;
10140 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10141 // so this action feels more ergonomic when paired with other selection operations
10142 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10143 if !should_skip_last {
10144 new_selection_ranges.push(selection.end..selection.end);
10145 }
10146 }
10147 }
10148 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10149 s.select_ranges(new_selection_ranges);
10150 });
10151 }
10152
10153 pub fn add_selection_above(
10154 &mut self,
10155 _: &AddSelectionAbove,
10156 window: &mut Window,
10157 cx: &mut Context<Self>,
10158 ) {
10159 self.add_selection(true, window, cx);
10160 }
10161
10162 pub fn add_selection_below(
10163 &mut self,
10164 _: &AddSelectionBelow,
10165 window: &mut Window,
10166 cx: &mut Context<Self>,
10167 ) {
10168 self.add_selection(false, window, cx);
10169 }
10170
10171 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10172 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10173 let mut selections = self.selections.all::<Point>(cx);
10174 let text_layout_details = self.text_layout_details(window);
10175 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10176 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10177 let range = oldest_selection.display_range(&display_map).sorted();
10178
10179 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10180 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10181 let positions = start_x.min(end_x)..start_x.max(end_x);
10182
10183 selections.clear();
10184 let mut stack = Vec::new();
10185 for row in range.start.row().0..=range.end.row().0 {
10186 if let Some(selection) = self.selections.build_columnar_selection(
10187 &display_map,
10188 DisplayRow(row),
10189 &positions,
10190 oldest_selection.reversed,
10191 &text_layout_details,
10192 ) {
10193 stack.push(selection.id);
10194 selections.push(selection);
10195 }
10196 }
10197
10198 if above {
10199 stack.reverse();
10200 }
10201
10202 AddSelectionsState { above, stack }
10203 });
10204
10205 let last_added_selection = *state.stack.last().unwrap();
10206 let mut new_selections = Vec::new();
10207 if above == state.above {
10208 let end_row = if above {
10209 DisplayRow(0)
10210 } else {
10211 display_map.max_point().row()
10212 };
10213
10214 'outer: for selection in selections {
10215 if selection.id == last_added_selection {
10216 let range = selection.display_range(&display_map).sorted();
10217 debug_assert_eq!(range.start.row(), range.end.row());
10218 let mut row = range.start.row();
10219 let positions =
10220 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10221 px(start)..px(end)
10222 } else {
10223 let start_x =
10224 display_map.x_for_display_point(range.start, &text_layout_details);
10225 let end_x =
10226 display_map.x_for_display_point(range.end, &text_layout_details);
10227 start_x.min(end_x)..start_x.max(end_x)
10228 };
10229
10230 while row != end_row {
10231 if above {
10232 row.0 -= 1;
10233 } else {
10234 row.0 += 1;
10235 }
10236
10237 if let Some(new_selection) = self.selections.build_columnar_selection(
10238 &display_map,
10239 row,
10240 &positions,
10241 selection.reversed,
10242 &text_layout_details,
10243 ) {
10244 state.stack.push(new_selection.id);
10245 if above {
10246 new_selections.push(new_selection);
10247 new_selections.push(selection);
10248 } else {
10249 new_selections.push(selection);
10250 new_selections.push(new_selection);
10251 }
10252
10253 continue 'outer;
10254 }
10255 }
10256 }
10257
10258 new_selections.push(selection);
10259 }
10260 } else {
10261 new_selections = selections;
10262 new_selections.retain(|s| s.id != last_added_selection);
10263 state.stack.pop();
10264 }
10265
10266 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10267 s.select(new_selections);
10268 });
10269 if state.stack.len() > 1 {
10270 self.add_selections_state = Some(state);
10271 }
10272 }
10273
10274 pub fn select_next_match_internal(
10275 &mut self,
10276 display_map: &DisplaySnapshot,
10277 replace_newest: bool,
10278 autoscroll: Option<Autoscroll>,
10279 window: &mut Window,
10280 cx: &mut Context<Self>,
10281 ) -> Result<()> {
10282 fn select_next_match_ranges(
10283 this: &mut Editor,
10284 range: Range<usize>,
10285 replace_newest: bool,
10286 auto_scroll: Option<Autoscroll>,
10287 window: &mut Window,
10288 cx: &mut Context<Editor>,
10289 ) {
10290 this.unfold_ranges(&[range.clone()], false, true, cx);
10291 this.change_selections(auto_scroll, window, cx, |s| {
10292 if replace_newest {
10293 s.delete(s.newest_anchor().id);
10294 }
10295 s.insert_range(range.clone());
10296 });
10297 }
10298
10299 let buffer = &display_map.buffer_snapshot;
10300 let mut selections = self.selections.all::<usize>(cx);
10301 if let Some(mut select_next_state) = self.select_next_state.take() {
10302 let query = &select_next_state.query;
10303 if !select_next_state.done {
10304 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10305 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10306 let mut next_selected_range = None;
10307
10308 let bytes_after_last_selection =
10309 buffer.bytes_in_range(last_selection.end..buffer.len());
10310 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10311 let query_matches = query
10312 .stream_find_iter(bytes_after_last_selection)
10313 .map(|result| (last_selection.end, result))
10314 .chain(
10315 query
10316 .stream_find_iter(bytes_before_first_selection)
10317 .map(|result| (0, result)),
10318 );
10319
10320 for (start_offset, query_match) in query_matches {
10321 let query_match = query_match.unwrap(); // can only fail due to I/O
10322 let offset_range =
10323 start_offset + query_match.start()..start_offset + query_match.end();
10324 let display_range = offset_range.start.to_display_point(display_map)
10325 ..offset_range.end.to_display_point(display_map);
10326
10327 if !select_next_state.wordwise
10328 || (!movement::is_inside_word(display_map, display_range.start)
10329 && !movement::is_inside_word(display_map, display_range.end))
10330 {
10331 // TODO: This is n^2, because we might check all the selections
10332 if !selections
10333 .iter()
10334 .any(|selection| selection.range().overlaps(&offset_range))
10335 {
10336 next_selected_range = Some(offset_range);
10337 break;
10338 }
10339 }
10340 }
10341
10342 if let Some(next_selected_range) = next_selected_range {
10343 select_next_match_ranges(
10344 self,
10345 next_selected_range,
10346 replace_newest,
10347 autoscroll,
10348 window,
10349 cx,
10350 );
10351 } else {
10352 select_next_state.done = true;
10353 }
10354 }
10355
10356 self.select_next_state = Some(select_next_state);
10357 } else {
10358 let mut only_carets = true;
10359 let mut same_text_selected = true;
10360 let mut selected_text = None;
10361
10362 let mut selections_iter = selections.iter().peekable();
10363 while let Some(selection) = selections_iter.next() {
10364 if selection.start != selection.end {
10365 only_carets = false;
10366 }
10367
10368 if same_text_selected {
10369 if selected_text.is_none() {
10370 selected_text =
10371 Some(buffer.text_for_range(selection.range()).collect::<String>());
10372 }
10373
10374 if let Some(next_selection) = selections_iter.peek() {
10375 if next_selection.range().len() == selection.range().len() {
10376 let next_selected_text = buffer
10377 .text_for_range(next_selection.range())
10378 .collect::<String>();
10379 if Some(next_selected_text) != selected_text {
10380 same_text_selected = false;
10381 selected_text = None;
10382 }
10383 } else {
10384 same_text_selected = false;
10385 selected_text = None;
10386 }
10387 }
10388 }
10389 }
10390
10391 if only_carets {
10392 for selection in &mut selections {
10393 let word_range = movement::surrounding_word(
10394 display_map,
10395 selection.start.to_display_point(display_map),
10396 );
10397 selection.start = word_range.start.to_offset(display_map, Bias::Left);
10398 selection.end = word_range.end.to_offset(display_map, Bias::Left);
10399 selection.goal = SelectionGoal::None;
10400 selection.reversed = false;
10401 select_next_match_ranges(
10402 self,
10403 selection.start..selection.end,
10404 replace_newest,
10405 autoscroll,
10406 window,
10407 cx,
10408 );
10409 }
10410
10411 if selections.len() == 1 {
10412 let selection = selections
10413 .last()
10414 .expect("ensured that there's only one selection");
10415 let query = buffer
10416 .text_for_range(selection.start..selection.end)
10417 .collect::<String>();
10418 let is_empty = query.is_empty();
10419 let select_state = SelectNextState {
10420 query: AhoCorasick::new(&[query])?,
10421 wordwise: true,
10422 done: is_empty,
10423 };
10424 self.select_next_state = Some(select_state);
10425 } else {
10426 self.select_next_state = None;
10427 }
10428 } else if let Some(selected_text) = selected_text {
10429 self.select_next_state = Some(SelectNextState {
10430 query: AhoCorasick::new(&[selected_text])?,
10431 wordwise: false,
10432 done: false,
10433 });
10434 self.select_next_match_internal(
10435 display_map,
10436 replace_newest,
10437 autoscroll,
10438 window,
10439 cx,
10440 )?;
10441 }
10442 }
10443 Ok(())
10444 }
10445
10446 pub fn select_all_matches(
10447 &mut self,
10448 _action: &SelectAllMatches,
10449 window: &mut Window,
10450 cx: &mut Context<Self>,
10451 ) -> Result<()> {
10452 self.push_to_selection_history();
10453 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10454
10455 self.select_next_match_internal(&display_map, false, None, window, cx)?;
10456 let Some(select_next_state) = self.select_next_state.as_mut() else {
10457 return Ok(());
10458 };
10459 if select_next_state.done {
10460 return Ok(());
10461 }
10462
10463 let mut new_selections = self.selections.all::<usize>(cx);
10464
10465 let buffer = &display_map.buffer_snapshot;
10466 let query_matches = select_next_state
10467 .query
10468 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
10469
10470 for query_match in query_matches {
10471 let query_match = query_match.unwrap(); // can only fail due to I/O
10472 let offset_range = query_match.start()..query_match.end();
10473 let display_range = offset_range.start.to_display_point(&display_map)
10474 ..offset_range.end.to_display_point(&display_map);
10475
10476 if !select_next_state.wordwise
10477 || (!movement::is_inside_word(&display_map, display_range.start)
10478 && !movement::is_inside_word(&display_map, display_range.end))
10479 {
10480 self.selections.change_with(cx, |selections| {
10481 new_selections.push(Selection {
10482 id: selections.new_selection_id(),
10483 start: offset_range.start,
10484 end: offset_range.end,
10485 reversed: false,
10486 goal: SelectionGoal::None,
10487 });
10488 });
10489 }
10490 }
10491
10492 new_selections.sort_by_key(|selection| selection.start);
10493 let mut ix = 0;
10494 while ix + 1 < new_selections.len() {
10495 let current_selection = &new_selections[ix];
10496 let next_selection = &new_selections[ix + 1];
10497 if current_selection.range().overlaps(&next_selection.range()) {
10498 if current_selection.id < next_selection.id {
10499 new_selections.remove(ix + 1);
10500 } else {
10501 new_selections.remove(ix);
10502 }
10503 } else {
10504 ix += 1;
10505 }
10506 }
10507
10508 let reversed = self.selections.oldest::<usize>(cx).reversed;
10509
10510 for selection in new_selections.iter_mut() {
10511 selection.reversed = reversed;
10512 }
10513
10514 select_next_state.done = true;
10515 self.unfold_ranges(
10516 &new_selections
10517 .iter()
10518 .map(|selection| selection.range())
10519 .collect::<Vec<_>>(),
10520 false,
10521 false,
10522 cx,
10523 );
10524 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
10525 selections.select(new_selections)
10526 });
10527
10528 Ok(())
10529 }
10530
10531 pub fn select_next(
10532 &mut self,
10533 action: &SelectNext,
10534 window: &mut Window,
10535 cx: &mut Context<Self>,
10536 ) -> Result<()> {
10537 self.push_to_selection_history();
10538 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10539 self.select_next_match_internal(
10540 &display_map,
10541 action.replace_newest,
10542 Some(Autoscroll::newest()),
10543 window,
10544 cx,
10545 )?;
10546 Ok(())
10547 }
10548
10549 pub fn select_previous(
10550 &mut self,
10551 action: &SelectPrevious,
10552 window: &mut Window,
10553 cx: &mut Context<Self>,
10554 ) -> Result<()> {
10555 self.push_to_selection_history();
10556 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10557 let buffer = &display_map.buffer_snapshot;
10558 let mut selections = self.selections.all::<usize>(cx);
10559 if let Some(mut select_prev_state) = self.select_prev_state.take() {
10560 let query = &select_prev_state.query;
10561 if !select_prev_state.done {
10562 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10563 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10564 let mut next_selected_range = None;
10565 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
10566 let bytes_before_last_selection =
10567 buffer.reversed_bytes_in_range(0..last_selection.start);
10568 let bytes_after_first_selection =
10569 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
10570 let query_matches = query
10571 .stream_find_iter(bytes_before_last_selection)
10572 .map(|result| (last_selection.start, result))
10573 .chain(
10574 query
10575 .stream_find_iter(bytes_after_first_selection)
10576 .map(|result| (buffer.len(), result)),
10577 );
10578 for (end_offset, query_match) in query_matches {
10579 let query_match = query_match.unwrap(); // can only fail due to I/O
10580 let offset_range =
10581 end_offset - query_match.end()..end_offset - query_match.start();
10582 let display_range = offset_range.start.to_display_point(&display_map)
10583 ..offset_range.end.to_display_point(&display_map);
10584
10585 if !select_prev_state.wordwise
10586 || (!movement::is_inside_word(&display_map, display_range.start)
10587 && !movement::is_inside_word(&display_map, display_range.end))
10588 {
10589 next_selected_range = Some(offset_range);
10590 break;
10591 }
10592 }
10593
10594 if let Some(next_selected_range) = next_selected_range {
10595 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
10596 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10597 if action.replace_newest {
10598 s.delete(s.newest_anchor().id);
10599 }
10600 s.insert_range(next_selected_range);
10601 });
10602 } else {
10603 select_prev_state.done = true;
10604 }
10605 }
10606
10607 self.select_prev_state = Some(select_prev_state);
10608 } else {
10609 let mut only_carets = true;
10610 let mut same_text_selected = true;
10611 let mut selected_text = None;
10612
10613 let mut selections_iter = selections.iter().peekable();
10614 while let Some(selection) = selections_iter.next() {
10615 if selection.start != selection.end {
10616 only_carets = false;
10617 }
10618
10619 if same_text_selected {
10620 if selected_text.is_none() {
10621 selected_text =
10622 Some(buffer.text_for_range(selection.range()).collect::<String>());
10623 }
10624
10625 if let Some(next_selection) = selections_iter.peek() {
10626 if next_selection.range().len() == selection.range().len() {
10627 let next_selected_text = buffer
10628 .text_for_range(next_selection.range())
10629 .collect::<String>();
10630 if Some(next_selected_text) != selected_text {
10631 same_text_selected = false;
10632 selected_text = None;
10633 }
10634 } else {
10635 same_text_selected = false;
10636 selected_text = None;
10637 }
10638 }
10639 }
10640 }
10641
10642 if only_carets {
10643 for selection in &mut selections {
10644 let word_range = movement::surrounding_word(
10645 &display_map,
10646 selection.start.to_display_point(&display_map),
10647 );
10648 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
10649 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
10650 selection.goal = SelectionGoal::None;
10651 selection.reversed = false;
10652 }
10653 if selections.len() == 1 {
10654 let selection = selections
10655 .last()
10656 .expect("ensured that there's only one selection");
10657 let query = buffer
10658 .text_for_range(selection.start..selection.end)
10659 .collect::<String>();
10660 let is_empty = query.is_empty();
10661 let select_state = SelectNextState {
10662 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
10663 wordwise: true,
10664 done: is_empty,
10665 };
10666 self.select_prev_state = Some(select_state);
10667 } else {
10668 self.select_prev_state = None;
10669 }
10670
10671 self.unfold_ranges(
10672 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
10673 false,
10674 true,
10675 cx,
10676 );
10677 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
10678 s.select(selections);
10679 });
10680 } else if let Some(selected_text) = selected_text {
10681 self.select_prev_state = Some(SelectNextState {
10682 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
10683 wordwise: false,
10684 done: false,
10685 });
10686 self.select_previous(action, window, cx)?;
10687 }
10688 }
10689 Ok(())
10690 }
10691
10692 pub fn toggle_comments(
10693 &mut self,
10694 action: &ToggleComments,
10695 window: &mut Window,
10696 cx: &mut Context<Self>,
10697 ) {
10698 if self.read_only(cx) {
10699 return;
10700 }
10701 let text_layout_details = &self.text_layout_details(window);
10702 self.transact(window, cx, |this, window, cx| {
10703 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
10704 let mut edits = Vec::new();
10705 let mut selection_edit_ranges = Vec::new();
10706 let mut last_toggled_row = None;
10707 let snapshot = this.buffer.read(cx).read(cx);
10708 let empty_str: Arc<str> = Arc::default();
10709 let mut suffixes_inserted = Vec::new();
10710 let ignore_indent = action.ignore_indent;
10711
10712 fn comment_prefix_range(
10713 snapshot: &MultiBufferSnapshot,
10714 row: MultiBufferRow,
10715 comment_prefix: &str,
10716 comment_prefix_whitespace: &str,
10717 ignore_indent: bool,
10718 ) -> Range<Point> {
10719 let indent_size = if ignore_indent {
10720 0
10721 } else {
10722 snapshot.indent_size_for_line(row).len
10723 };
10724
10725 let start = Point::new(row.0, indent_size);
10726
10727 let mut line_bytes = snapshot
10728 .bytes_in_range(start..snapshot.max_point())
10729 .flatten()
10730 .copied();
10731
10732 // If this line currently begins with the line comment prefix, then record
10733 // the range containing the prefix.
10734 if line_bytes
10735 .by_ref()
10736 .take(comment_prefix.len())
10737 .eq(comment_prefix.bytes())
10738 {
10739 // Include any whitespace that matches the comment prefix.
10740 let matching_whitespace_len = line_bytes
10741 .zip(comment_prefix_whitespace.bytes())
10742 .take_while(|(a, b)| a == b)
10743 .count() as u32;
10744 let end = Point::new(
10745 start.row,
10746 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
10747 );
10748 start..end
10749 } else {
10750 start..start
10751 }
10752 }
10753
10754 fn comment_suffix_range(
10755 snapshot: &MultiBufferSnapshot,
10756 row: MultiBufferRow,
10757 comment_suffix: &str,
10758 comment_suffix_has_leading_space: bool,
10759 ) -> Range<Point> {
10760 let end = Point::new(row.0, snapshot.line_len(row));
10761 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
10762
10763 let mut line_end_bytes = snapshot
10764 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
10765 .flatten()
10766 .copied();
10767
10768 let leading_space_len = if suffix_start_column > 0
10769 && line_end_bytes.next() == Some(b' ')
10770 && comment_suffix_has_leading_space
10771 {
10772 1
10773 } else {
10774 0
10775 };
10776
10777 // If this line currently begins with the line comment prefix, then record
10778 // the range containing the prefix.
10779 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
10780 let start = Point::new(end.row, suffix_start_column - leading_space_len);
10781 start..end
10782 } else {
10783 end..end
10784 }
10785 }
10786
10787 // TODO: Handle selections that cross excerpts
10788 for selection in &mut selections {
10789 let start_column = snapshot
10790 .indent_size_for_line(MultiBufferRow(selection.start.row))
10791 .len;
10792 let language = if let Some(language) =
10793 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
10794 {
10795 language
10796 } else {
10797 continue;
10798 };
10799
10800 selection_edit_ranges.clear();
10801
10802 // If multiple selections contain a given row, avoid processing that
10803 // row more than once.
10804 let mut start_row = MultiBufferRow(selection.start.row);
10805 if last_toggled_row == Some(start_row) {
10806 start_row = start_row.next_row();
10807 }
10808 let end_row =
10809 if selection.end.row > selection.start.row && selection.end.column == 0 {
10810 MultiBufferRow(selection.end.row - 1)
10811 } else {
10812 MultiBufferRow(selection.end.row)
10813 };
10814 last_toggled_row = Some(end_row);
10815
10816 if start_row > end_row {
10817 continue;
10818 }
10819
10820 // If the language has line comments, toggle those.
10821 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
10822
10823 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
10824 if ignore_indent {
10825 full_comment_prefixes = full_comment_prefixes
10826 .into_iter()
10827 .map(|s| Arc::from(s.trim_end()))
10828 .collect();
10829 }
10830
10831 if !full_comment_prefixes.is_empty() {
10832 let first_prefix = full_comment_prefixes
10833 .first()
10834 .expect("prefixes is non-empty");
10835 let prefix_trimmed_lengths = full_comment_prefixes
10836 .iter()
10837 .map(|p| p.trim_end_matches(' ').len())
10838 .collect::<SmallVec<[usize; 4]>>();
10839
10840 let mut all_selection_lines_are_comments = true;
10841
10842 for row in start_row.0..=end_row.0 {
10843 let row = MultiBufferRow(row);
10844 if start_row < end_row && snapshot.is_line_blank(row) {
10845 continue;
10846 }
10847
10848 let prefix_range = full_comment_prefixes
10849 .iter()
10850 .zip(prefix_trimmed_lengths.iter().copied())
10851 .map(|(prefix, trimmed_prefix_len)| {
10852 comment_prefix_range(
10853 snapshot.deref(),
10854 row,
10855 &prefix[..trimmed_prefix_len],
10856 &prefix[trimmed_prefix_len..],
10857 ignore_indent,
10858 )
10859 })
10860 .max_by_key(|range| range.end.column - range.start.column)
10861 .expect("prefixes is non-empty");
10862
10863 if prefix_range.is_empty() {
10864 all_selection_lines_are_comments = false;
10865 }
10866
10867 selection_edit_ranges.push(prefix_range);
10868 }
10869
10870 if all_selection_lines_are_comments {
10871 edits.extend(
10872 selection_edit_ranges
10873 .iter()
10874 .cloned()
10875 .map(|range| (range, empty_str.clone())),
10876 );
10877 } else {
10878 let min_column = selection_edit_ranges
10879 .iter()
10880 .map(|range| range.start.column)
10881 .min()
10882 .unwrap_or(0);
10883 edits.extend(selection_edit_ranges.iter().map(|range| {
10884 let position = Point::new(range.start.row, min_column);
10885 (position..position, first_prefix.clone())
10886 }));
10887 }
10888 } else if let Some((full_comment_prefix, comment_suffix)) =
10889 language.block_comment_delimiters()
10890 {
10891 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
10892 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
10893 let prefix_range = comment_prefix_range(
10894 snapshot.deref(),
10895 start_row,
10896 comment_prefix,
10897 comment_prefix_whitespace,
10898 ignore_indent,
10899 );
10900 let suffix_range = comment_suffix_range(
10901 snapshot.deref(),
10902 end_row,
10903 comment_suffix.trim_start_matches(' '),
10904 comment_suffix.starts_with(' '),
10905 );
10906
10907 if prefix_range.is_empty() || suffix_range.is_empty() {
10908 edits.push((
10909 prefix_range.start..prefix_range.start,
10910 full_comment_prefix.clone(),
10911 ));
10912 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
10913 suffixes_inserted.push((end_row, comment_suffix.len()));
10914 } else {
10915 edits.push((prefix_range, empty_str.clone()));
10916 edits.push((suffix_range, empty_str.clone()));
10917 }
10918 } else {
10919 continue;
10920 }
10921 }
10922
10923 drop(snapshot);
10924 this.buffer.update(cx, |buffer, cx| {
10925 buffer.edit(edits, None, cx);
10926 });
10927
10928 // Adjust selections so that they end before any comment suffixes that
10929 // were inserted.
10930 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10931 let mut selections = this.selections.all::<Point>(cx);
10932 let snapshot = this.buffer.read(cx).read(cx);
10933 for selection in &mut selections {
10934 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10935 match row.cmp(&MultiBufferRow(selection.end.row)) {
10936 Ordering::Less => {
10937 suffixes_inserted.next();
10938 continue;
10939 }
10940 Ordering::Greater => break,
10941 Ordering::Equal => {
10942 if selection.end.column == snapshot.line_len(row) {
10943 if selection.is_empty() {
10944 selection.start.column -= suffix_len as u32;
10945 }
10946 selection.end.column -= suffix_len as u32;
10947 }
10948 break;
10949 }
10950 }
10951 }
10952 }
10953
10954 drop(snapshot);
10955 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10956 s.select(selections)
10957 });
10958
10959 let selections = this.selections.all::<Point>(cx);
10960 let selections_on_single_row = selections.windows(2).all(|selections| {
10961 selections[0].start.row == selections[1].start.row
10962 && selections[0].end.row == selections[1].end.row
10963 && selections[0].start.row == selections[0].end.row
10964 });
10965 let selections_selecting = selections
10966 .iter()
10967 .any(|selection| selection.start != selection.end);
10968 let advance_downwards = action.advance_downwards
10969 && selections_on_single_row
10970 && !selections_selecting
10971 && !matches!(this.mode, EditorMode::SingleLine { .. });
10972
10973 if advance_downwards {
10974 let snapshot = this.buffer.read(cx).snapshot(cx);
10975
10976 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10977 s.move_cursors_with(|display_snapshot, display_point, _| {
10978 let mut point = display_point.to_point(display_snapshot);
10979 point.row += 1;
10980 point = snapshot.clip_point(point, Bias::Left);
10981 let display_point = point.to_display_point(display_snapshot);
10982 let goal = SelectionGoal::HorizontalPosition(
10983 display_snapshot
10984 .x_for_display_point(display_point, text_layout_details)
10985 .into(),
10986 );
10987 (display_point, goal)
10988 })
10989 });
10990 }
10991 });
10992 }
10993
10994 pub fn select_enclosing_symbol(
10995 &mut self,
10996 _: &SelectEnclosingSymbol,
10997 window: &mut Window,
10998 cx: &mut Context<Self>,
10999 ) {
11000 let buffer = self.buffer.read(cx).snapshot(cx);
11001 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11002
11003 fn update_selection(
11004 selection: &Selection<usize>,
11005 buffer_snap: &MultiBufferSnapshot,
11006 ) -> Option<Selection<usize>> {
11007 let cursor = selection.head();
11008 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11009 for symbol in symbols.iter().rev() {
11010 let start = symbol.range.start.to_offset(buffer_snap);
11011 let end = symbol.range.end.to_offset(buffer_snap);
11012 let new_range = start..end;
11013 if start < selection.start || end > selection.end {
11014 return Some(Selection {
11015 id: selection.id,
11016 start: new_range.start,
11017 end: new_range.end,
11018 goal: SelectionGoal::None,
11019 reversed: selection.reversed,
11020 });
11021 }
11022 }
11023 None
11024 }
11025
11026 let mut selected_larger_symbol = false;
11027 let new_selections = old_selections
11028 .iter()
11029 .map(|selection| match update_selection(selection, &buffer) {
11030 Some(new_selection) => {
11031 if new_selection.range() != selection.range() {
11032 selected_larger_symbol = true;
11033 }
11034 new_selection
11035 }
11036 None => selection.clone(),
11037 })
11038 .collect::<Vec<_>>();
11039
11040 if selected_larger_symbol {
11041 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11042 s.select(new_selections);
11043 });
11044 }
11045 }
11046
11047 pub fn select_larger_syntax_node(
11048 &mut self,
11049 _: &SelectLargerSyntaxNode,
11050 window: &mut Window,
11051 cx: &mut Context<Self>,
11052 ) {
11053 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11054 let buffer = self.buffer.read(cx).snapshot(cx);
11055 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11056
11057 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11058 let mut selected_larger_node = false;
11059 let new_selections = old_selections
11060 .iter()
11061 .map(|selection| {
11062 let old_range = selection.start..selection.end;
11063 let mut new_range = old_range.clone();
11064 let mut new_node = None;
11065 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11066 {
11067 new_node = Some(node);
11068 new_range = match containing_range {
11069 MultiOrSingleBufferOffsetRange::Single(_) => break,
11070 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11071 };
11072 if !display_map.intersects_fold(new_range.start)
11073 && !display_map.intersects_fold(new_range.end)
11074 {
11075 break;
11076 }
11077 }
11078
11079 if let Some(node) = new_node {
11080 // Log the ancestor, to support using this action as a way to explore TreeSitter
11081 // nodes. Parent and grandparent are also logged because this operation will not
11082 // visit nodes that have the same range as their parent.
11083 log::info!("Node: {node:?}");
11084 let parent = node.parent();
11085 log::info!("Parent: {parent:?}");
11086 let grandparent = parent.and_then(|x| x.parent());
11087 log::info!("Grandparent: {grandparent:?}");
11088 }
11089
11090 selected_larger_node |= new_range != old_range;
11091 Selection {
11092 id: selection.id,
11093 start: new_range.start,
11094 end: new_range.end,
11095 goal: SelectionGoal::None,
11096 reversed: selection.reversed,
11097 }
11098 })
11099 .collect::<Vec<_>>();
11100
11101 if selected_larger_node {
11102 stack.push(old_selections);
11103 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11104 s.select(new_selections);
11105 });
11106 }
11107 self.select_larger_syntax_node_stack = stack;
11108 }
11109
11110 pub fn select_smaller_syntax_node(
11111 &mut self,
11112 _: &SelectSmallerSyntaxNode,
11113 window: &mut Window,
11114 cx: &mut Context<Self>,
11115 ) {
11116 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11117 if let Some(selections) = stack.pop() {
11118 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11119 s.select(selections.to_vec());
11120 });
11121 }
11122 self.select_larger_syntax_node_stack = stack;
11123 }
11124
11125 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11126 if !EditorSettings::get_global(cx).gutter.runnables {
11127 self.clear_tasks();
11128 return Task::ready(());
11129 }
11130 let project = self.project.as_ref().map(Entity::downgrade);
11131 cx.spawn_in(window, |this, mut cx| async move {
11132 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11133 let Some(project) = project.and_then(|p| p.upgrade()) else {
11134 return;
11135 };
11136 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
11137 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11138 }) else {
11139 return;
11140 };
11141
11142 let hide_runnables = project
11143 .update(&mut cx, |project, cx| {
11144 // Do not display any test indicators in non-dev server remote projects.
11145 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11146 })
11147 .unwrap_or(true);
11148 if hide_runnables {
11149 return;
11150 }
11151 let new_rows =
11152 cx.background_spawn({
11153 let snapshot = display_snapshot.clone();
11154 async move {
11155 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11156 }
11157 })
11158 .await;
11159
11160 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11161 this.update(&mut cx, |this, _| {
11162 this.clear_tasks();
11163 for (key, value) in rows {
11164 this.insert_tasks(key, value);
11165 }
11166 })
11167 .ok();
11168 })
11169 }
11170 fn fetch_runnable_ranges(
11171 snapshot: &DisplaySnapshot,
11172 range: Range<Anchor>,
11173 ) -> Vec<language::RunnableRange> {
11174 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11175 }
11176
11177 fn runnable_rows(
11178 project: Entity<Project>,
11179 snapshot: DisplaySnapshot,
11180 runnable_ranges: Vec<RunnableRange>,
11181 mut cx: AsyncWindowContext,
11182 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11183 runnable_ranges
11184 .into_iter()
11185 .filter_map(|mut runnable| {
11186 let tasks = cx
11187 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11188 .ok()?;
11189 if tasks.is_empty() {
11190 return None;
11191 }
11192
11193 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11194
11195 let row = snapshot
11196 .buffer_snapshot
11197 .buffer_line_for_row(MultiBufferRow(point.row))?
11198 .1
11199 .start
11200 .row;
11201
11202 let context_range =
11203 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11204 Some((
11205 (runnable.buffer_id, row),
11206 RunnableTasks {
11207 templates: tasks,
11208 offset: snapshot
11209 .buffer_snapshot
11210 .anchor_before(runnable.run_range.start),
11211 context_range,
11212 column: point.column,
11213 extra_variables: runnable.extra_captures,
11214 },
11215 ))
11216 })
11217 .collect()
11218 }
11219
11220 fn templates_with_tags(
11221 project: &Entity<Project>,
11222 runnable: &mut Runnable,
11223 cx: &mut App,
11224 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11225 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11226 let (worktree_id, file) = project
11227 .buffer_for_id(runnable.buffer, cx)
11228 .and_then(|buffer| buffer.read(cx).file())
11229 .map(|file| (file.worktree_id(cx), file.clone()))
11230 .unzip();
11231
11232 (
11233 project.task_store().read(cx).task_inventory().cloned(),
11234 worktree_id,
11235 file,
11236 )
11237 });
11238
11239 let tags = mem::take(&mut runnable.tags);
11240 let mut tags: Vec<_> = tags
11241 .into_iter()
11242 .flat_map(|tag| {
11243 let tag = tag.0.clone();
11244 inventory
11245 .as_ref()
11246 .into_iter()
11247 .flat_map(|inventory| {
11248 inventory.read(cx).list_tasks(
11249 file.clone(),
11250 Some(runnable.language.clone()),
11251 worktree_id,
11252 cx,
11253 )
11254 })
11255 .filter(move |(_, template)| {
11256 template.tags.iter().any(|source_tag| source_tag == &tag)
11257 })
11258 })
11259 .sorted_by_key(|(kind, _)| kind.to_owned())
11260 .collect();
11261 if let Some((leading_tag_source, _)) = tags.first() {
11262 // Strongest source wins; if we have worktree tag binding, prefer that to
11263 // global and language bindings;
11264 // if we have a global binding, prefer that to language binding.
11265 let first_mismatch = tags
11266 .iter()
11267 .position(|(tag_source, _)| tag_source != leading_tag_source);
11268 if let Some(index) = first_mismatch {
11269 tags.truncate(index);
11270 }
11271 }
11272
11273 tags
11274 }
11275
11276 pub fn move_to_enclosing_bracket(
11277 &mut self,
11278 _: &MoveToEnclosingBracket,
11279 window: &mut Window,
11280 cx: &mut Context<Self>,
11281 ) {
11282 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11283 s.move_offsets_with(|snapshot, selection| {
11284 let Some(enclosing_bracket_ranges) =
11285 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11286 else {
11287 return;
11288 };
11289
11290 let mut best_length = usize::MAX;
11291 let mut best_inside = false;
11292 let mut best_in_bracket_range = false;
11293 let mut best_destination = None;
11294 for (open, close) in enclosing_bracket_ranges {
11295 let close = close.to_inclusive();
11296 let length = close.end() - open.start;
11297 let inside = selection.start >= open.end && selection.end <= *close.start();
11298 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11299 || close.contains(&selection.head());
11300
11301 // If best is next to a bracket and current isn't, skip
11302 if !in_bracket_range && best_in_bracket_range {
11303 continue;
11304 }
11305
11306 // Prefer smaller lengths unless best is inside and current isn't
11307 if length > best_length && (best_inside || !inside) {
11308 continue;
11309 }
11310
11311 best_length = length;
11312 best_inside = inside;
11313 best_in_bracket_range = in_bracket_range;
11314 best_destination = Some(
11315 if close.contains(&selection.start) && close.contains(&selection.end) {
11316 if inside {
11317 open.end
11318 } else {
11319 open.start
11320 }
11321 } else if inside {
11322 *close.start()
11323 } else {
11324 *close.end()
11325 },
11326 );
11327 }
11328
11329 if let Some(destination) = best_destination {
11330 selection.collapse_to(destination, SelectionGoal::None);
11331 }
11332 })
11333 });
11334 }
11335
11336 pub fn undo_selection(
11337 &mut self,
11338 _: &UndoSelection,
11339 window: &mut Window,
11340 cx: &mut Context<Self>,
11341 ) {
11342 self.end_selection(window, cx);
11343 self.selection_history.mode = SelectionHistoryMode::Undoing;
11344 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
11345 self.change_selections(None, window, cx, |s| {
11346 s.select_anchors(entry.selections.to_vec())
11347 });
11348 self.select_next_state = entry.select_next_state;
11349 self.select_prev_state = entry.select_prev_state;
11350 self.add_selections_state = entry.add_selections_state;
11351 self.request_autoscroll(Autoscroll::newest(), cx);
11352 }
11353 self.selection_history.mode = SelectionHistoryMode::Normal;
11354 }
11355
11356 pub fn redo_selection(
11357 &mut self,
11358 _: &RedoSelection,
11359 window: &mut Window,
11360 cx: &mut Context<Self>,
11361 ) {
11362 self.end_selection(window, cx);
11363 self.selection_history.mode = SelectionHistoryMode::Redoing;
11364 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
11365 self.change_selections(None, window, cx, |s| {
11366 s.select_anchors(entry.selections.to_vec())
11367 });
11368 self.select_next_state = entry.select_next_state;
11369 self.select_prev_state = entry.select_prev_state;
11370 self.add_selections_state = entry.add_selections_state;
11371 self.request_autoscroll(Autoscroll::newest(), cx);
11372 }
11373 self.selection_history.mode = SelectionHistoryMode::Normal;
11374 }
11375
11376 pub fn expand_excerpts(
11377 &mut self,
11378 action: &ExpandExcerpts,
11379 _: &mut Window,
11380 cx: &mut Context<Self>,
11381 ) {
11382 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
11383 }
11384
11385 pub fn expand_excerpts_down(
11386 &mut self,
11387 action: &ExpandExcerptsDown,
11388 _: &mut Window,
11389 cx: &mut Context<Self>,
11390 ) {
11391 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
11392 }
11393
11394 pub fn expand_excerpts_up(
11395 &mut self,
11396 action: &ExpandExcerptsUp,
11397 _: &mut Window,
11398 cx: &mut Context<Self>,
11399 ) {
11400 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
11401 }
11402
11403 pub fn expand_excerpts_for_direction(
11404 &mut self,
11405 lines: u32,
11406 direction: ExpandExcerptDirection,
11407
11408 cx: &mut Context<Self>,
11409 ) {
11410 let selections = self.selections.disjoint_anchors();
11411
11412 let lines = if lines == 0 {
11413 EditorSettings::get_global(cx).expand_excerpt_lines
11414 } else {
11415 lines
11416 };
11417
11418 self.buffer.update(cx, |buffer, cx| {
11419 let snapshot = buffer.snapshot(cx);
11420 let mut excerpt_ids = selections
11421 .iter()
11422 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
11423 .collect::<Vec<_>>();
11424 excerpt_ids.sort();
11425 excerpt_ids.dedup();
11426 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
11427 })
11428 }
11429
11430 pub fn expand_excerpt(
11431 &mut self,
11432 excerpt: ExcerptId,
11433 direction: ExpandExcerptDirection,
11434 cx: &mut Context<Self>,
11435 ) {
11436 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
11437 self.buffer.update(cx, |buffer, cx| {
11438 buffer.expand_excerpts([excerpt], lines, direction, cx)
11439 })
11440 }
11441
11442 pub fn go_to_singleton_buffer_point(
11443 &mut self,
11444 point: Point,
11445 window: &mut Window,
11446 cx: &mut Context<Self>,
11447 ) {
11448 self.go_to_singleton_buffer_range(point..point, window, cx);
11449 }
11450
11451 pub fn go_to_singleton_buffer_range(
11452 &mut self,
11453 range: Range<Point>,
11454 window: &mut Window,
11455 cx: &mut Context<Self>,
11456 ) {
11457 let multibuffer = self.buffer().read(cx);
11458 let Some(buffer) = multibuffer.as_singleton() else {
11459 return;
11460 };
11461 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
11462 return;
11463 };
11464 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
11465 return;
11466 };
11467 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
11468 s.select_anchor_ranges([start..end])
11469 });
11470 }
11471
11472 fn go_to_diagnostic(
11473 &mut self,
11474 _: &GoToDiagnostic,
11475 window: &mut Window,
11476 cx: &mut Context<Self>,
11477 ) {
11478 self.go_to_diagnostic_impl(Direction::Next, window, cx)
11479 }
11480
11481 fn go_to_prev_diagnostic(
11482 &mut self,
11483 _: &GoToPreviousDiagnostic,
11484 window: &mut Window,
11485 cx: &mut Context<Self>,
11486 ) {
11487 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
11488 }
11489
11490 pub fn go_to_diagnostic_impl(
11491 &mut self,
11492 direction: Direction,
11493 window: &mut Window,
11494 cx: &mut Context<Self>,
11495 ) {
11496 let buffer = self.buffer.read(cx).snapshot(cx);
11497 let selection = self.selections.newest::<usize>(cx);
11498
11499 // If there is an active Diagnostic Popover jump to its diagnostic instead.
11500 if direction == Direction::Next {
11501 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
11502 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
11503 return;
11504 };
11505 self.activate_diagnostics(
11506 buffer_id,
11507 popover.local_diagnostic.diagnostic.group_id,
11508 window,
11509 cx,
11510 );
11511 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
11512 let primary_range_start = active_diagnostics.primary_range.start;
11513 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11514 let mut new_selection = s.newest_anchor().clone();
11515 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
11516 s.select_anchors(vec![new_selection.clone()]);
11517 });
11518 self.refresh_inline_completion(false, true, window, cx);
11519 }
11520 return;
11521 }
11522 }
11523
11524 let active_group_id = self
11525 .active_diagnostics
11526 .as_ref()
11527 .map(|active_group| active_group.group_id);
11528 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
11529 active_diagnostics
11530 .primary_range
11531 .to_offset(&buffer)
11532 .to_inclusive()
11533 });
11534 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
11535 if active_primary_range.contains(&selection.head()) {
11536 *active_primary_range.start()
11537 } else {
11538 selection.head()
11539 }
11540 } else {
11541 selection.head()
11542 };
11543
11544 let snapshot = self.snapshot(window, cx);
11545 let primary_diagnostics_before = buffer
11546 .diagnostics_in_range::<usize>(0..search_start)
11547 .filter(|entry| entry.diagnostic.is_primary)
11548 .filter(|entry| entry.range.start != entry.range.end)
11549 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11550 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
11551 .collect::<Vec<_>>();
11552 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
11553 primary_diagnostics_before
11554 .iter()
11555 .position(|entry| entry.diagnostic.group_id == active_group_id)
11556 });
11557
11558 let primary_diagnostics_after = buffer
11559 .diagnostics_in_range::<usize>(search_start..buffer.len())
11560 .filter(|entry| entry.diagnostic.is_primary)
11561 .filter(|entry| entry.range.start != entry.range.end)
11562 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
11563 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
11564 .collect::<Vec<_>>();
11565 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
11566 primary_diagnostics_after
11567 .iter()
11568 .enumerate()
11569 .rev()
11570 .find_map(|(i, entry)| {
11571 if entry.diagnostic.group_id == active_group_id {
11572 Some(i)
11573 } else {
11574 None
11575 }
11576 })
11577 });
11578
11579 let next_primary_diagnostic = match direction {
11580 Direction::Prev => primary_diagnostics_before
11581 .iter()
11582 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
11583 .rev()
11584 .next(),
11585 Direction::Next => primary_diagnostics_after
11586 .iter()
11587 .skip(
11588 last_same_group_diagnostic_after
11589 .map(|index| index + 1)
11590 .unwrap_or(0),
11591 )
11592 .next(),
11593 };
11594
11595 // Cycle around to the start of the buffer, potentially moving back to the start of
11596 // the currently active diagnostic.
11597 let cycle_around = || match direction {
11598 Direction::Prev => primary_diagnostics_after
11599 .iter()
11600 .rev()
11601 .chain(primary_diagnostics_before.iter().rev())
11602 .next(),
11603 Direction::Next => primary_diagnostics_before
11604 .iter()
11605 .chain(primary_diagnostics_after.iter())
11606 .next(),
11607 };
11608
11609 if let Some((primary_range, group_id)) = next_primary_diagnostic
11610 .or_else(cycle_around)
11611 .map(|entry| (&entry.range, entry.diagnostic.group_id))
11612 {
11613 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
11614 return;
11615 };
11616 self.activate_diagnostics(buffer_id, group_id, window, cx);
11617 if self.active_diagnostics.is_some() {
11618 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11619 s.select(vec![Selection {
11620 id: selection.id,
11621 start: primary_range.start,
11622 end: primary_range.start,
11623 reversed: false,
11624 goal: SelectionGoal::None,
11625 }]);
11626 });
11627 self.refresh_inline_completion(false, true, window, cx);
11628 }
11629 }
11630 }
11631
11632 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
11633 let snapshot = self.snapshot(window, cx);
11634 let selection = self.selections.newest::<Point>(cx);
11635 self.go_to_hunk_before_or_after_position(
11636 &snapshot,
11637 selection.head(),
11638 Direction::Next,
11639 window,
11640 cx,
11641 );
11642 }
11643
11644 fn go_to_hunk_before_or_after_position(
11645 &mut self,
11646 snapshot: &EditorSnapshot,
11647 position: Point,
11648 direction: Direction,
11649 window: &mut Window,
11650 cx: &mut Context<Editor>,
11651 ) {
11652 let row = if direction == Direction::Next {
11653 self.hunk_after_position(snapshot, position)
11654 .map(|hunk| hunk.row_range.start)
11655 } else {
11656 self.hunk_before_position(snapshot, position)
11657 };
11658
11659 if let Some(row) = row {
11660 let destination = Point::new(row.0, 0);
11661 let autoscroll = Autoscroll::center();
11662
11663 self.unfold_ranges(&[destination..destination], false, false, cx);
11664 self.change_selections(Some(autoscroll), window, cx, |s| {
11665 s.select_ranges([destination..destination]);
11666 });
11667 }
11668 }
11669
11670 fn hunk_after_position(
11671 &mut self,
11672 snapshot: &EditorSnapshot,
11673 position: Point,
11674 ) -> Option<MultiBufferDiffHunk> {
11675 snapshot
11676 .buffer_snapshot
11677 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
11678 .find(|hunk| hunk.row_range.start.0 > position.row)
11679 .or_else(|| {
11680 snapshot
11681 .buffer_snapshot
11682 .diff_hunks_in_range(Point::zero()..position)
11683 .find(|hunk| hunk.row_range.end.0 < position.row)
11684 })
11685 }
11686
11687 fn go_to_prev_hunk(
11688 &mut self,
11689 _: &GoToPreviousHunk,
11690 window: &mut Window,
11691 cx: &mut Context<Self>,
11692 ) {
11693 let snapshot = self.snapshot(window, cx);
11694 let selection = self.selections.newest::<Point>(cx);
11695 self.go_to_hunk_before_or_after_position(
11696 &snapshot,
11697 selection.head(),
11698 Direction::Prev,
11699 window,
11700 cx,
11701 );
11702 }
11703
11704 fn hunk_before_position(
11705 &mut self,
11706 snapshot: &EditorSnapshot,
11707 position: Point,
11708 ) -> Option<MultiBufferRow> {
11709 snapshot
11710 .buffer_snapshot
11711 .diff_hunk_before(position)
11712 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
11713 }
11714
11715 pub fn go_to_definition(
11716 &mut self,
11717 _: &GoToDefinition,
11718 window: &mut Window,
11719 cx: &mut Context<Self>,
11720 ) -> Task<Result<Navigated>> {
11721 let definition =
11722 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
11723 cx.spawn_in(window, |editor, mut cx| async move {
11724 if definition.await? == Navigated::Yes {
11725 return Ok(Navigated::Yes);
11726 }
11727 match editor.update_in(&mut cx, |editor, window, cx| {
11728 editor.find_all_references(&FindAllReferences, window, cx)
11729 })? {
11730 Some(references) => references.await,
11731 None => Ok(Navigated::No),
11732 }
11733 })
11734 }
11735
11736 pub fn go_to_declaration(
11737 &mut self,
11738 _: &GoToDeclaration,
11739 window: &mut Window,
11740 cx: &mut Context<Self>,
11741 ) -> Task<Result<Navigated>> {
11742 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
11743 }
11744
11745 pub fn go_to_declaration_split(
11746 &mut self,
11747 _: &GoToDeclaration,
11748 window: &mut Window,
11749 cx: &mut Context<Self>,
11750 ) -> Task<Result<Navigated>> {
11751 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
11752 }
11753
11754 pub fn go_to_implementation(
11755 &mut self,
11756 _: &GoToImplementation,
11757 window: &mut Window,
11758 cx: &mut Context<Self>,
11759 ) -> Task<Result<Navigated>> {
11760 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
11761 }
11762
11763 pub fn go_to_implementation_split(
11764 &mut self,
11765 _: &GoToImplementationSplit,
11766 window: &mut Window,
11767 cx: &mut Context<Self>,
11768 ) -> Task<Result<Navigated>> {
11769 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
11770 }
11771
11772 pub fn go_to_type_definition(
11773 &mut self,
11774 _: &GoToTypeDefinition,
11775 window: &mut Window,
11776 cx: &mut Context<Self>,
11777 ) -> Task<Result<Navigated>> {
11778 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
11779 }
11780
11781 pub fn go_to_definition_split(
11782 &mut self,
11783 _: &GoToDefinitionSplit,
11784 window: &mut Window,
11785 cx: &mut Context<Self>,
11786 ) -> Task<Result<Navigated>> {
11787 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
11788 }
11789
11790 pub fn go_to_type_definition_split(
11791 &mut self,
11792 _: &GoToTypeDefinitionSplit,
11793 window: &mut Window,
11794 cx: &mut Context<Self>,
11795 ) -> Task<Result<Navigated>> {
11796 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
11797 }
11798
11799 fn go_to_definition_of_kind(
11800 &mut self,
11801 kind: GotoDefinitionKind,
11802 split: bool,
11803 window: &mut Window,
11804 cx: &mut Context<Self>,
11805 ) -> Task<Result<Navigated>> {
11806 let Some(provider) = self.semantics_provider.clone() else {
11807 return Task::ready(Ok(Navigated::No));
11808 };
11809 let head = self.selections.newest::<usize>(cx).head();
11810 let buffer = self.buffer.read(cx);
11811 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
11812 text_anchor
11813 } else {
11814 return Task::ready(Ok(Navigated::No));
11815 };
11816
11817 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
11818 return Task::ready(Ok(Navigated::No));
11819 };
11820
11821 cx.spawn_in(window, |editor, mut cx| async move {
11822 let definitions = definitions.await?;
11823 let navigated = editor
11824 .update_in(&mut cx, |editor, window, cx| {
11825 editor.navigate_to_hover_links(
11826 Some(kind),
11827 definitions
11828 .into_iter()
11829 .filter(|location| {
11830 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
11831 })
11832 .map(HoverLink::Text)
11833 .collect::<Vec<_>>(),
11834 split,
11835 window,
11836 cx,
11837 )
11838 })?
11839 .await?;
11840 anyhow::Ok(navigated)
11841 })
11842 }
11843
11844 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
11845 let selection = self.selections.newest_anchor();
11846 let head = selection.head();
11847 let tail = selection.tail();
11848
11849 let Some((buffer, start_position)) =
11850 self.buffer.read(cx).text_anchor_for_position(head, cx)
11851 else {
11852 return;
11853 };
11854
11855 let end_position = if head != tail {
11856 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
11857 return;
11858 };
11859 Some(pos)
11860 } else {
11861 None
11862 };
11863
11864 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
11865 let url = if let Some(end_pos) = end_position {
11866 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
11867 } else {
11868 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
11869 };
11870
11871 if let Some(url) = url {
11872 editor.update(&mut cx, |_, cx| {
11873 cx.open_url(&url);
11874 })
11875 } else {
11876 Ok(())
11877 }
11878 });
11879
11880 url_finder.detach();
11881 }
11882
11883 pub fn open_selected_filename(
11884 &mut self,
11885 _: &OpenSelectedFilename,
11886 window: &mut Window,
11887 cx: &mut Context<Self>,
11888 ) {
11889 let Some(workspace) = self.workspace() else {
11890 return;
11891 };
11892
11893 let position = self.selections.newest_anchor().head();
11894
11895 let Some((buffer, buffer_position)) =
11896 self.buffer.read(cx).text_anchor_for_position(position, cx)
11897 else {
11898 return;
11899 };
11900
11901 let project = self.project.clone();
11902
11903 cx.spawn_in(window, |_, mut cx| async move {
11904 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
11905
11906 if let Some((_, path)) = result {
11907 workspace
11908 .update_in(&mut cx, |workspace, window, cx| {
11909 workspace.open_resolved_path(path, window, cx)
11910 })?
11911 .await?;
11912 }
11913 anyhow::Ok(())
11914 })
11915 .detach();
11916 }
11917
11918 pub(crate) fn navigate_to_hover_links(
11919 &mut self,
11920 kind: Option<GotoDefinitionKind>,
11921 mut definitions: Vec<HoverLink>,
11922 split: bool,
11923 window: &mut Window,
11924 cx: &mut Context<Editor>,
11925 ) -> Task<Result<Navigated>> {
11926 // If there is one definition, just open it directly
11927 if definitions.len() == 1 {
11928 let definition = definitions.pop().unwrap();
11929
11930 enum TargetTaskResult {
11931 Location(Option<Location>),
11932 AlreadyNavigated,
11933 }
11934
11935 let target_task = match definition {
11936 HoverLink::Text(link) => {
11937 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
11938 }
11939 HoverLink::InlayHint(lsp_location, server_id) => {
11940 let computation =
11941 self.compute_target_location(lsp_location, server_id, window, cx);
11942 cx.background_spawn(async move {
11943 let location = computation.await?;
11944 Ok(TargetTaskResult::Location(location))
11945 })
11946 }
11947 HoverLink::Url(url) => {
11948 cx.open_url(&url);
11949 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11950 }
11951 HoverLink::File(path) => {
11952 if let Some(workspace) = self.workspace() {
11953 cx.spawn_in(window, |_, mut cx| async move {
11954 workspace
11955 .update_in(&mut cx, |workspace, window, cx| {
11956 workspace.open_resolved_path(path, window, cx)
11957 })?
11958 .await
11959 .map(|_| TargetTaskResult::AlreadyNavigated)
11960 })
11961 } else {
11962 Task::ready(Ok(TargetTaskResult::Location(None)))
11963 }
11964 }
11965 };
11966 cx.spawn_in(window, |editor, mut cx| async move {
11967 let target = match target_task.await.context("target resolution task")? {
11968 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11969 TargetTaskResult::Location(None) => return Ok(Navigated::No),
11970 TargetTaskResult::Location(Some(target)) => target,
11971 };
11972
11973 editor.update_in(&mut cx, |editor, window, cx| {
11974 let Some(workspace) = editor.workspace() else {
11975 return Navigated::No;
11976 };
11977 let pane = workspace.read(cx).active_pane().clone();
11978
11979 let range = target.range.to_point(target.buffer.read(cx));
11980 let range = editor.range_for_match(&range);
11981 let range = collapse_multiline_range(range);
11982
11983 if !split
11984 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
11985 {
11986 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11987 } else {
11988 window.defer(cx, move |window, cx| {
11989 let target_editor: Entity<Self> =
11990 workspace.update(cx, |workspace, cx| {
11991 let pane = if split {
11992 workspace.adjacent_pane(window, cx)
11993 } else {
11994 workspace.active_pane().clone()
11995 };
11996
11997 workspace.open_project_item(
11998 pane,
11999 target.buffer.clone(),
12000 true,
12001 true,
12002 window,
12003 cx,
12004 )
12005 });
12006 target_editor.update(cx, |target_editor, cx| {
12007 // When selecting a definition in a different buffer, disable the nav history
12008 // to avoid creating a history entry at the previous cursor location.
12009 pane.update(cx, |pane, _| pane.disable_history());
12010 target_editor.go_to_singleton_buffer_range(range, window, cx);
12011 pane.update(cx, |pane, _| pane.enable_history());
12012 });
12013 });
12014 }
12015 Navigated::Yes
12016 })
12017 })
12018 } else if !definitions.is_empty() {
12019 cx.spawn_in(window, |editor, mut cx| async move {
12020 let (title, location_tasks, workspace) = editor
12021 .update_in(&mut cx, |editor, window, cx| {
12022 let tab_kind = match kind {
12023 Some(GotoDefinitionKind::Implementation) => "Implementations",
12024 _ => "Definitions",
12025 };
12026 let title = definitions
12027 .iter()
12028 .find_map(|definition| match definition {
12029 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12030 let buffer = origin.buffer.read(cx);
12031 format!(
12032 "{} for {}",
12033 tab_kind,
12034 buffer
12035 .text_for_range(origin.range.clone())
12036 .collect::<String>()
12037 )
12038 }),
12039 HoverLink::InlayHint(_, _) => None,
12040 HoverLink::Url(_) => None,
12041 HoverLink::File(_) => None,
12042 })
12043 .unwrap_or(tab_kind.to_string());
12044 let location_tasks = definitions
12045 .into_iter()
12046 .map(|definition| match definition {
12047 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12048 HoverLink::InlayHint(lsp_location, server_id) => editor
12049 .compute_target_location(lsp_location, server_id, window, cx),
12050 HoverLink::Url(_) => Task::ready(Ok(None)),
12051 HoverLink::File(_) => Task::ready(Ok(None)),
12052 })
12053 .collect::<Vec<_>>();
12054 (title, location_tasks, editor.workspace().clone())
12055 })
12056 .context("location tasks preparation")?;
12057
12058 let locations = future::join_all(location_tasks)
12059 .await
12060 .into_iter()
12061 .filter_map(|location| location.transpose())
12062 .collect::<Result<_>>()
12063 .context("location tasks")?;
12064
12065 let Some(workspace) = workspace else {
12066 return Ok(Navigated::No);
12067 };
12068 let opened = workspace
12069 .update_in(&mut cx, |workspace, window, cx| {
12070 Self::open_locations_in_multibuffer(
12071 workspace,
12072 locations,
12073 title,
12074 split,
12075 MultibufferSelectionMode::First,
12076 window,
12077 cx,
12078 )
12079 })
12080 .ok();
12081
12082 anyhow::Ok(Navigated::from_bool(opened.is_some()))
12083 })
12084 } else {
12085 Task::ready(Ok(Navigated::No))
12086 }
12087 }
12088
12089 fn compute_target_location(
12090 &self,
12091 lsp_location: lsp::Location,
12092 server_id: LanguageServerId,
12093 window: &mut Window,
12094 cx: &mut Context<Self>,
12095 ) -> Task<anyhow::Result<Option<Location>>> {
12096 let Some(project) = self.project.clone() else {
12097 return Task::ready(Ok(None));
12098 };
12099
12100 cx.spawn_in(window, move |editor, mut cx| async move {
12101 let location_task = editor.update(&mut cx, |_, cx| {
12102 project.update(cx, |project, cx| {
12103 let language_server_name = project
12104 .language_server_statuses(cx)
12105 .find(|(id, _)| server_id == *id)
12106 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12107 language_server_name.map(|language_server_name| {
12108 project.open_local_buffer_via_lsp(
12109 lsp_location.uri.clone(),
12110 server_id,
12111 language_server_name,
12112 cx,
12113 )
12114 })
12115 })
12116 })?;
12117 let location = match location_task {
12118 Some(task) => Some({
12119 let target_buffer_handle = task.await.context("open local buffer")?;
12120 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
12121 let target_start = target_buffer
12122 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12123 let target_end = target_buffer
12124 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12125 target_buffer.anchor_after(target_start)
12126 ..target_buffer.anchor_before(target_end)
12127 })?;
12128 Location {
12129 buffer: target_buffer_handle,
12130 range,
12131 }
12132 }),
12133 None => None,
12134 };
12135 Ok(location)
12136 })
12137 }
12138
12139 pub fn find_all_references(
12140 &mut self,
12141 _: &FindAllReferences,
12142 window: &mut Window,
12143 cx: &mut Context<Self>,
12144 ) -> Option<Task<Result<Navigated>>> {
12145 let selection = self.selections.newest::<usize>(cx);
12146 let multi_buffer = self.buffer.read(cx);
12147 let head = selection.head();
12148
12149 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12150 let head_anchor = multi_buffer_snapshot.anchor_at(
12151 head,
12152 if head < selection.tail() {
12153 Bias::Right
12154 } else {
12155 Bias::Left
12156 },
12157 );
12158
12159 match self
12160 .find_all_references_task_sources
12161 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12162 {
12163 Ok(_) => {
12164 log::info!(
12165 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12166 );
12167 return None;
12168 }
12169 Err(i) => {
12170 self.find_all_references_task_sources.insert(i, head_anchor);
12171 }
12172 }
12173
12174 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12175 let workspace = self.workspace()?;
12176 let project = workspace.read(cx).project().clone();
12177 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12178 Some(cx.spawn_in(window, |editor, mut cx| async move {
12179 let _cleanup = defer({
12180 let mut cx = cx.clone();
12181 move || {
12182 let _ = editor.update(&mut cx, |editor, _| {
12183 if let Ok(i) =
12184 editor
12185 .find_all_references_task_sources
12186 .binary_search_by(|anchor| {
12187 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
12188 })
12189 {
12190 editor.find_all_references_task_sources.remove(i);
12191 }
12192 });
12193 }
12194 });
12195
12196 let locations = references.await?;
12197 if locations.is_empty() {
12198 return anyhow::Ok(Navigated::No);
12199 }
12200
12201 workspace.update_in(&mut cx, |workspace, window, cx| {
12202 let title = locations
12203 .first()
12204 .as_ref()
12205 .map(|location| {
12206 let buffer = location.buffer.read(cx);
12207 format!(
12208 "References to `{}`",
12209 buffer
12210 .text_for_range(location.range.clone())
12211 .collect::<String>()
12212 )
12213 })
12214 .unwrap();
12215 Self::open_locations_in_multibuffer(
12216 workspace,
12217 locations,
12218 title,
12219 false,
12220 MultibufferSelectionMode::First,
12221 window,
12222 cx,
12223 );
12224 Navigated::Yes
12225 })
12226 }))
12227 }
12228
12229 /// Opens a multibuffer with the given project locations in it
12230 pub fn open_locations_in_multibuffer(
12231 workspace: &mut Workspace,
12232 mut locations: Vec<Location>,
12233 title: String,
12234 split: bool,
12235 multibuffer_selection_mode: MultibufferSelectionMode,
12236 window: &mut Window,
12237 cx: &mut Context<Workspace>,
12238 ) {
12239 // If there are multiple definitions, open them in a multibuffer
12240 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12241 let mut locations = locations.into_iter().peekable();
12242 let mut ranges = Vec::new();
12243 let capability = workspace.project().read(cx).capability();
12244
12245 let excerpt_buffer = cx.new(|cx| {
12246 let mut multibuffer = MultiBuffer::new(capability);
12247 while let Some(location) = locations.next() {
12248 let buffer = location.buffer.read(cx);
12249 let mut ranges_for_buffer = Vec::new();
12250 let range = location.range.to_offset(buffer);
12251 ranges_for_buffer.push(range.clone());
12252
12253 while let Some(next_location) = locations.peek() {
12254 if next_location.buffer == location.buffer {
12255 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12256 locations.next();
12257 } else {
12258 break;
12259 }
12260 }
12261
12262 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12263 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12264 location.buffer.clone(),
12265 ranges_for_buffer,
12266 DEFAULT_MULTIBUFFER_CONTEXT,
12267 cx,
12268 ))
12269 }
12270
12271 multibuffer.with_title(title)
12272 });
12273
12274 let editor = cx.new(|cx| {
12275 Editor::for_multibuffer(
12276 excerpt_buffer,
12277 Some(workspace.project().clone()),
12278 true,
12279 window,
12280 cx,
12281 )
12282 });
12283 editor.update(cx, |editor, cx| {
12284 match multibuffer_selection_mode {
12285 MultibufferSelectionMode::First => {
12286 if let Some(first_range) = ranges.first() {
12287 editor.change_selections(None, window, cx, |selections| {
12288 selections.clear_disjoint();
12289 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12290 });
12291 }
12292 editor.highlight_background::<Self>(
12293 &ranges,
12294 |theme| theme.editor_highlighted_line_background,
12295 cx,
12296 );
12297 }
12298 MultibufferSelectionMode::All => {
12299 editor.change_selections(None, window, cx, |selections| {
12300 selections.clear_disjoint();
12301 selections.select_anchor_ranges(ranges);
12302 });
12303 }
12304 }
12305 editor.register_buffers_with_language_servers(cx);
12306 });
12307
12308 let item = Box::new(editor);
12309 let item_id = item.item_id();
12310
12311 if split {
12312 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
12313 } else {
12314 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
12315 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
12316 pane.close_current_preview_item(window, cx)
12317 } else {
12318 None
12319 }
12320 });
12321 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
12322 }
12323 workspace.active_pane().update(cx, |pane, cx| {
12324 pane.set_preview_item_id(Some(item_id), cx);
12325 });
12326 }
12327
12328 pub fn rename(
12329 &mut self,
12330 _: &Rename,
12331 window: &mut Window,
12332 cx: &mut Context<Self>,
12333 ) -> Option<Task<Result<()>>> {
12334 use language::ToOffset as _;
12335
12336 let provider = self.semantics_provider.clone()?;
12337 let selection = self.selections.newest_anchor().clone();
12338 let (cursor_buffer, cursor_buffer_position) = self
12339 .buffer
12340 .read(cx)
12341 .text_anchor_for_position(selection.head(), cx)?;
12342 let (tail_buffer, cursor_buffer_position_end) = self
12343 .buffer
12344 .read(cx)
12345 .text_anchor_for_position(selection.tail(), cx)?;
12346 if tail_buffer != cursor_buffer {
12347 return None;
12348 }
12349
12350 let snapshot = cursor_buffer.read(cx).snapshot();
12351 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
12352 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
12353 let prepare_rename = provider
12354 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
12355 .unwrap_or_else(|| Task::ready(Ok(None)));
12356 drop(snapshot);
12357
12358 Some(cx.spawn_in(window, |this, mut cx| async move {
12359 let rename_range = if let Some(range) = prepare_rename.await? {
12360 Some(range)
12361 } else {
12362 this.update(&mut cx, |this, cx| {
12363 let buffer = this.buffer.read(cx).snapshot(cx);
12364 let mut buffer_highlights = this
12365 .document_highlights_for_position(selection.head(), &buffer)
12366 .filter(|highlight| {
12367 highlight.start.excerpt_id == selection.head().excerpt_id
12368 && highlight.end.excerpt_id == selection.head().excerpt_id
12369 });
12370 buffer_highlights
12371 .next()
12372 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
12373 })?
12374 };
12375 if let Some(rename_range) = rename_range {
12376 this.update_in(&mut cx, |this, window, cx| {
12377 let snapshot = cursor_buffer.read(cx).snapshot();
12378 let rename_buffer_range = rename_range.to_offset(&snapshot);
12379 let cursor_offset_in_rename_range =
12380 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
12381 let cursor_offset_in_rename_range_end =
12382 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
12383
12384 this.take_rename(false, window, cx);
12385 let buffer = this.buffer.read(cx).read(cx);
12386 let cursor_offset = selection.head().to_offset(&buffer);
12387 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
12388 let rename_end = rename_start + rename_buffer_range.len();
12389 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
12390 let mut old_highlight_id = None;
12391 let old_name: Arc<str> = buffer
12392 .chunks(rename_start..rename_end, true)
12393 .map(|chunk| {
12394 if old_highlight_id.is_none() {
12395 old_highlight_id = chunk.syntax_highlight_id;
12396 }
12397 chunk.text
12398 })
12399 .collect::<String>()
12400 .into();
12401
12402 drop(buffer);
12403
12404 // Position the selection in the rename editor so that it matches the current selection.
12405 this.show_local_selections = false;
12406 let rename_editor = cx.new(|cx| {
12407 let mut editor = Editor::single_line(window, cx);
12408 editor.buffer.update(cx, |buffer, cx| {
12409 buffer.edit([(0..0, old_name.clone())], None, cx)
12410 });
12411 let rename_selection_range = match cursor_offset_in_rename_range
12412 .cmp(&cursor_offset_in_rename_range_end)
12413 {
12414 Ordering::Equal => {
12415 editor.select_all(&SelectAll, window, cx);
12416 return editor;
12417 }
12418 Ordering::Less => {
12419 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
12420 }
12421 Ordering::Greater => {
12422 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
12423 }
12424 };
12425 if rename_selection_range.end > old_name.len() {
12426 editor.select_all(&SelectAll, window, cx);
12427 } else {
12428 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12429 s.select_ranges([rename_selection_range]);
12430 });
12431 }
12432 editor
12433 });
12434 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
12435 if e == &EditorEvent::Focused {
12436 cx.emit(EditorEvent::FocusedIn)
12437 }
12438 })
12439 .detach();
12440
12441 let write_highlights =
12442 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
12443 let read_highlights =
12444 this.clear_background_highlights::<DocumentHighlightRead>(cx);
12445 let ranges = write_highlights
12446 .iter()
12447 .flat_map(|(_, ranges)| ranges.iter())
12448 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
12449 .cloned()
12450 .collect();
12451
12452 this.highlight_text::<Rename>(
12453 ranges,
12454 HighlightStyle {
12455 fade_out: Some(0.6),
12456 ..Default::default()
12457 },
12458 cx,
12459 );
12460 let rename_focus_handle = rename_editor.focus_handle(cx);
12461 window.focus(&rename_focus_handle);
12462 let block_id = this.insert_blocks(
12463 [BlockProperties {
12464 style: BlockStyle::Flex,
12465 placement: BlockPlacement::Below(range.start),
12466 height: 1,
12467 render: Arc::new({
12468 let rename_editor = rename_editor.clone();
12469 move |cx: &mut BlockContext| {
12470 let mut text_style = cx.editor_style.text.clone();
12471 if let Some(highlight_style) = old_highlight_id
12472 .and_then(|h| h.style(&cx.editor_style.syntax))
12473 {
12474 text_style = text_style.highlight(highlight_style);
12475 }
12476 div()
12477 .block_mouse_down()
12478 .pl(cx.anchor_x)
12479 .child(EditorElement::new(
12480 &rename_editor,
12481 EditorStyle {
12482 background: cx.theme().system().transparent,
12483 local_player: cx.editor_style.local_player,
12484 text: text_style,
12485 scrollbar_width: cx.editor_style.scrollbar_width,
12486 syntax: cx.editor_style.syntax.clone(),
12487 status: cx.editor_style.status.clone(),
12488 inlay_hints_style: HighlightStyle {
12489 font_weight: Some(FontWeight::BOLD),
12490 ..make_inlay_hints_style(cx.app)
12491 },
12492 inline_completion_styles: make_suggestion_styles(
12493 cx.app,
12494 ),
12495 ..EditorStyle::default()
12496 },
12497 ))
12498 .into_any_element()
12499 }
12500 }),
12501 priority: 0,
12502 }],
12503 Some(Autoscroll::fit()),
12504 cx,
12505 )[0];
12506 this.pending_rename = Some(RenameState {
12507 range,
12508 old_name,
12509 editor: rename_editor,
12510 block_id,
12511 });
12512 })?;
12513 }
12514
12515 Ok(())
12516 }))
12517 }
12518
12519 pub fn confirm_rename(
12520 &mut self,
12521 _: &ConfirmRename,
12522 window: &mut Window,
12523 cx: &mut Context<Self>,
12524 ) -> Option<Task<Result<()>>> {
12525 let rename = self.take_rename(false, window, cx)?;
12526 let workspace = self.workspace()?.downgrade();
12527 let (buffer, start) = self
12528 .buffer
12529 .read(cx)
12530 .text_anchor_for_position(rename.range.start, cx)?;
12531 let (end_buffer, _) = self
12532 .buffer
12533 .read(cx)
12534 .text_anchor_for_position(rename.range.end, cx)?;
12535 if buffer != end_buffer {
12536 return None;
12537 }
12538
12539 let old_name = rename.old_name;
12540 let new_name = rename.editor.read(cx).text(cx);
12541
12542 let rename = self.semantics_provider.as_ref()?.perform_rename(
12543 &buffer,
12544 start,
12545 new_name.clone(),
12546 cx,
12547 )?;
12548
12549 Some(cx.spawn_in(window, |editor, mut cx| async move {
12550 let project_transaction = rename.await?;
12551 Self::open_project_transaction(
12552 &editor,
12553 workspace,
12554 project_transaction,
12555 format!("Rename: {} → {}", old_name, new_name),
12556 cx.clone(),
12557 )
12558 .await?;
12559
12560 editor.update(&mut cx, |editor, cx| {
12561 editor.refresh_document_highlights(cx);
12562 })?;
12563 Ok(())
12564 }))
12565 }
12566
12567 fn take_rename(
12568 &mut self,
12569 moving_cursor: bool,
12570 window: &mut Window,
12571 cx: &mut Context<Self>,
12572 ) -> Option<RenameState> {
12573 let rename = self.pending_rename.take()?;
12574 if rename.editor.focus_handle(cx).is_focused(window) {
12575 window.focus(&self.focus_handle);
12576 }
12577
12578 self.remove_blocks(
12579 [rename.block_id].into_iter().collect(),
12580 Some(Autoscroll::fit()),
12581 cx,
12582 );
12583 self.clear_highlights::<Rename>(cx);
12584 self.show_local_selections = true;
12585
12586 if moving_cursor {
12587 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
12588 editor.selections.newest::<usize>(cx).head()
12589 });
12590
12591 // Update the selection to match the position of the selection inside
12592 // the rename editor.
12593 let snapshot = self.buffer.read(cx).read(cx);
12594 let rename_range = rename.range.to_offset(&snapshot);
12595 let cursor_in_editor = snapshot
12596 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
12597 .min(rename_range.end);
12598 drop(snapshot);
12599
12600 self.change_selections(None, window, cx, |s| {
12601 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
12602 });
12603 } else {
12604 self.refresh_document_highlights(cx);
12605 }
12606
12607 Some(rename)
12608 }
12609
12610 pub fn pending_rename(&self) -> Option<&RenameState> {
12611 self.pending_rename.as_ref()
12612 }
12613
12614 fn format(
12615 &mut self,
12616 _: &Format,
12617 window: &mut Window,
12618 cx: &mut Context<Self>,
12619 ) -> Option<Task<Result<()>>> {
12620 let project = match &self.project {
12621 Some(project) => project.clone(),
12622 None => return None,
12623 };
12624
12625 Some(self.perform_format(
12626 project,
12627 FormatTrigger::Manual,
12628 FormatTarget::Buffers,
12629 window,
12630 cx,
12631 ))
12632 }
12633
12634 fn format_selections(
12635 &mut self,
12636 _: &FormatSelections,
12637 window: &mut Window,
12638 cx: &mut Context<Self>,
12639 ) -> Option<Task<Result<()>>> {
12640 let project = match &self.project {
12641 Some(project) => project.clone(),
12642 None => return None,
12643 };
12644
12645 let ranges = self
12646 .selections
12647 .all_adjusted(cx)
12648 .into_iter()
12649 .map(|selection| selection.range())
12650 .collect_vec();
12651
12652 Some(self.perform_format(
12653 project,
12654 FormatTrigger::Manual,
12655 FormatTarget::Ranges(ranges),
12656 window,
12657 cx,
12658 ))
12659 }
12660
12661 fn perform_format(
12662 &mut self,
12663 project: Entity<Project>,
12664 trigger: FormatTrigger,
12665 target: FormatTarget,
12666 window: &mut Window,
12667 cx: &mut Context<Self>,
12668 ) -> Task<Result<()>> {
12669 let buffer = self.buffer.clone();
12670 let (buffers, target) = match target {
12671 FormatTarget::Buffers => {
12672 let mut buffers = buffer.read(cx).all_buffers();
12673 if trigger == FormatTrigger::Save {
12674 buffers.retain(|buffer| buffer.read(cx).is_dirty());
12675 }
12676 (buffers, LspFormatTarget::Buffers)
12677 }
12678 FormatTarget::Ranges(selection_ranges) => {
12679 let multi_buffer = buffer.read(cx);
12680 let snapshot = multi_buffer.read(cx);
12681 let mut buffers = HashSet::default();
12682 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
12683 BTreeMap::new();
12684 for selection_range in selection_ranges {
12685 for (buffer, buffer_range, _) in
12686 snapshot.range_to_buffer_ranges(selection_range)
12687 {
12688 let buffer_id = buffer.remote_id();
12689 let start = buffer.anchor_before(buffer_range.start);
12690 let end = buffer.anchor_after(buffer_range.end);
12691 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
12692 buffer_id_to_ranges
12693 .entry(buffer_id)
12694 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
12695 .or_insert_with(|| vec![start..end]);
12696 }
12697 }
12698 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
12699 }
12700 };
12701
12702 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
12703 let format = project.update(cx, |project, cx| {
12704 project.format(buffers, target, true, trigger, cx)
12705 });
12706
12707 cx.spawn_in(window, |_, mut cx| async move {
12708 let transaction = futures::select_biased! {
12709 () = timeout => {
12710 log::warn!("timed out waiting for formatting");
12711 None
12712 }
12713 transaction = format.log_err().fuse() => transaction,
12714 };
12715
12716 buffer
12717 .update(&mut cx, |buffer, cx| {
12718 if let Some(transaction) = transaction {
12719 if !buffer.is_singleton() {
12720 buffer.push_transaction(&transaction.0, cx);
12721 }
12722 }
12723 cx.notify();
12724 })
12725 .ok();
12726
12727 Ok(())
12728 })
12729 }
12730
12731 fn organize_imports(
12732 &mut self,
12733 _: &OrganizeImports,
12734 window: &mut Window,
12735 cx: &mut Context<Self>,
12736 ) -> Option<Task<Result<()>>> {
12737 let project = match &self.project {
12738 Some(project) => project.clone(),
12739 None => return None,
12740 };
12741 Some(self.perform_code_action_kind(
12742 project,
12743 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
12744 window,
12745 cx,
12746 ))
12747 }
12748
12749 fn perform_code_action_kind(
12750 &mut self,
12751 project: Entity<Project>,
12752 kind: CodeActionKind,
12753 window: &mut Window,
12754 cx: &mut Context<Self>,
12755 ) -> Task<Result<()>> {
12756 let buffer = self.buffer.clone();
12757 let buffers = buffer.read(cx).all_buffers();
12758 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
12759 let apply_action = project.update(cx, |project, cx| {
12760 project.apply_code_action_kind(buffers, kind, true, cx)
12761 });
12762 cx.spawn_in(window, |_, mut cx| async move {
12763 let transaction = futures::select_biased! {
12764 () = timeout => {
12765 log::warn!("timed out waiting for executing code action");
12766 None
12767 }
12768 transaction = apply_action.log_err().fuse() => transaction,
12769 };
12770 buffer
12771 .update(&mut cx, |buffer, cx| {
12772 // check if we need this
12773 if let Some(transaction) = transaction {
12774 if !buffer.is_singleton() {
12775 buffer.push_transaction(&transaction.0, cx);
12776 }
12777 }
12778 cx.notify();
12779 })
12780 .ok();
12781 Ok(())
12782 })
12783 }
12784
12785 fn restart_language_server(
12786 &mut self,
12787 _: &RestartLanguageServer,
12788 _: &mut Window,
12789 cx: &mut Context<Self>,
12790 ) {
12791 if let Some(project) = self.project.clone() {
12792 self.buffer.update(cx, |multi_buffer, cx| {
12793 project.update(cx, |project, cx| {
12794 project.restart_language_servers_for_buffers(
12795 multi_buffer.all_buffers().into_iter().collect(),
12796 cx,
12797 );
12798 });
12799 })
12800 }
12801 }
12802
12803 fn cancel_language_server_work(
12804 workspace: &mut Workspace,
12805 _: &actions::CancelLanguageServerWork,
12806 _: &mut Window,
12807 cx: &mut Context<Workspace>,
12808 ) {
12809 let project = workspace.project();
12810 let buffers = workspace
12811 .active_item(cx)
12812 .and_then(|item| item.act_as::<Editor>(cx))
12813 .map_or(HashSet::default(), |editor| {
12814 editor.read(cx).buffer.read(cx).all_buffers()
12815 });
12816 project.update(cx, |project, cx| {
12817 project.cancel_language_server_work_for_buffers(buffers, cx);
12818 });
12819 }
12820
12821 fn show_character_palette(
12822 &mut self,
12823 _: &ShowCharacterPalette,
12824 window: &mut Window,
12825 _: &mut Context<Self>,
12826 ) {
12827 window.show_character_palette();
12828 }
12829
12830 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
12831 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
12832 let buffer = self.buffer.read(cx).snapshot(cx);
12833 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
12834 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
12835 let is_valid = buffer
12836 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
12837 .any(|entry| {
12838 entry.diagnostic.is_primary
12839 && !entry.range.is_empty()
12840 && entry.range.start == primary_range_start
12841 && entry.diagnostic.message == active_diagnostics.primary_message
12842 });
12843
12844 if is_valid != active_diagnostics.is_valid {
12845 active_diagnostics.is_valid = is_valid;
12846 if is_valid {
12847 let mut new_styles = HashMap::default();
12848 for (block_id, diagnostic) in &active_diagnostics.blocks {
12849 new_styles.insert(
12850 *block_id,
12851 diagnostic_block_renderer(diagnostic.clone(), None, true),
12852 );
12853 }
12854 self.display_map.update(cx, |display_map, _cx| {
12855 display_map.replace_blocks(new_styles);
12856 });
12857 } else {
12858 self.dismiss_diagnostics(cx);
12859 }
12860 }
12861 }
12862 }
12863
12864 fn activate_diagnostics(
12865 &mut self,
12866 buffer_id: BufferId,
12867 group_id: usize,
12868 window: &mut Window,
12869 cx: &mut Context<Self>,
12870 ) {
12871 self.dismiss_diagnostics(cx);
12872 let snapshot = self.snapshot(window, cx);
12873 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
12874 let buffer = self.buffer.read(cx).snapshot(cx);
12875
12876 let mut primary_range = None;
12877 let mut primary_message = None;
12878 let diagnostic_group = buffer
12879 .diagnostic_group(buffer_id, group_id)
12880 .filter_map(|entry| {
12881 let start = entry.range.start;
12882 let end = entry.range.end;
12883 if snapshot.is_line_folded(MultiBufferRow(start.row))
12884 && (start.row == end.row
12885 || snapshot.is_line_folded(MultiBufferRow(end.row)))
12886 {
12887 return None;
12888 }
12889 if entry.diagnostic.is_primary {
12890 primary_range = Some(entry.range.clone());
12891 primary_message = Some(entry.diagnostic.message.clone());
12892 }
12893 Some(entry)
12894 })
12895 .collect::<Vec<_>>();
12896 let primary_range = primary_range?;
12897 let primary_message = primary_message?;
12898
12899 let blocks = display_map
12900 .insert_blocks(
12901 diagnostic_group.iter().map(|entry| {
12902 let diagnostic = entry.diagnostic.clone();
12903 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
12904 BlockProperties {
12905 style: BlockStyle::Fixed,
12906 placement: BlockPlacement::Below(
12907 buffer.anchor_after(entry.range.start),
12908 ),
12909 height: message_height,
12910 render: diagnostic_block_renderer(diagnostic, None, true),
12911 priority: 0,
12912 }
12913 }),
12914 cx,
12915 )
12916 .into_iter()
12917 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
12918 .collect();
12919
12920 Some(ActiveDiagnosticGroup {
12921 primary_range: buffer.anchor_before(primary_range.start)
12922 ..buffer.anchor_after(primary_range.end),
12923 primary_message,
12924 group_id,
12925 blocks,
12926 is_valid: true,
12927 })
12928 });
12929 }
12930
12931 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
12932 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
12933 self.display_map.update(cx, |display_map, cx| {
12934 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
12935 });
12936 cx.notify();
12937 }
12938 }
12939
12940 /// Disable inline diagnostics rendering for this editor.
12941 pub fn disable_inline_diagnostics(&mut self) {
12942 self.inline_diagnostics_enabled = false;
12943 self.inline_diagnostics_update = Task::ready(());
12944 self.inline_diagnostics.clear();
12945 }
12946
12947 pub fn inline_diagnostics_enabled(&self) -> bool {
12948 self.inline_diagnostics_enabled
12949 }
12950
12951 pub fn show_inline_diagnostics(&self) -> bool {
12952 self.show_inline_diagnostics
12953 }
12954
12955 pub fn toggle_inline_diagnostics(
12956 &mut self,
12957 _: &ToggleInlineDiagnostics,
12958 window: &mut Window,
12959 cx: &mut Context<'_, Editor>,
12960 ) {
12961 self.show_inline_diagnostics = !self.show_inline_diagnostics;
12962 self.refresh_inline_diagnostics(false, window, cx);
12963 }
12964
12965 fn refresh_inline_diagnostics(
12966 &mut self,
12967 debounce: bool,
12968 window: &mut Window,
12969 cx: &mut Context<Self>,
12970 ) {
12971 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
12972 self.inline_diagnostics_update = Task::ready(());
12973 self.inline_diagnostics.clear();
12974 return;
12975 }
12976
12977 let debounce_ms = ProjectSettings::get_global(cx)
12978 .diagnostics
12979 .inline
12980 .update_debounce_ms;
12981 let debounce = if debounce && debounce_ms > 0 {
12982 Some(Duration::from_millis(debounce_ms))
12983 } else {
12984 None
12985 };
12986 self.inline_diagnostics_update = cx.spawn_in(window, |editor, mut cx| async move {
12987 if let Some(debounce) = debounce {
12988 cx.background_executor().timer(debounce).await;
12989 }
12990 let Some(snapshot) = editor
12991 .update(&mut cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
12992 .ok()
12993 else {
12994 return;
12995 };
12996
12997 let new_inline_diagnostics = cx
12998 .background_spawn(async move {
12999 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13000 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13001 let message = diagnostic_entry
13002 .diagnostic
13003 .message
13004 .split_once('\n')
13005 .map(|(line, _)| line)
13006 .map(SharedString::new)
13007 .unwrap_or_else(|| {
13008 SharedString::from(diagnostic_entry.diagnostic.message)
13009 });
13010 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13011 let (Ok(i) | Err(i)) = inline_diagnostics
13012 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13013 inline_diagnostics.insert(
13014 i,
13015 (
13016 start_anchor,
13017 InlineDiagnostic {
13018 message,
13019 group_id: diagnostic_entry.diagnostic.group_id,
13020 start: diagnostic_entry.range.start.to_point(&snapshot),
13021 is_primary: diagnostic_entry.diagnostic.is_primary,
13022 severity: diagnostic_entry.diagnostic.severity,
13023 },
13024 ),
13025 );
13026 }
13027 inline_diagnostics
13028 })
13029 .await;
13030
13031 editor
13032 .update(&mut cx, |editor, cx| {
13033 editor.inline_diagnostics = new_inline_diagnostics;
13034 cx.notify();
13035 })
13036 .ok();
13037 });
13038 }
13039
13040 pub fn set_selections_from_remote(
13041 &mut self,
13042 selections: Vec<Selection<Anchor>>,
13043 pending_selection: Option<Selection<Anchor>>,
13044 window: &mut Window,
13045 cx: &mut Context<Self>,
13046 ) {
13047 let old_cursor_position = self.selections.newest_anchor().head();
13048 self.selections.change_with(cx, |s| {
13049 s.select_anchors(selections);
13050 if let Some(pending_selection) = pending_selection {
13051 s.set_pending(pending_selection, SelectMode::Character);
13052 } else {
13053 s.clear_pending();
13054 }
13055 });
13056 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13057 }
13058
13059 fn push_to_selection_history(&mut self) {
13060 self.selection_history.push(SelectionHistoryEntry {
13061 selections: self.selections.disjoint_anchors(),
13062 select_next_state: self.select_next_state.clone(),
13063 select_prev_state: self.select_prev_state.clone(),
13064 add_selections_state: self.add_selections_state.clone(),
13065 });
13066 }
13067
13068 pub fn transact(
13069 &mut self,
13070 window: &mut Window,
13071 cx: &mut Context<Self>,
13072 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13073 ) -> Option<TransactionId> {
13074 self.start_transaction_at(Instant::now(), window, cx);
13075 update(self, window, cx);
13076 self.end_transaction_at(Instant::now(), cx)
13077 }
13078
13079 pub fn start_transaction_at(
13080 &mut self,
13081 now: Instant,
13082 window: &mut Window,
13083 cx: &mut Context<Self>,
13084 ) {
13085 self.end_selection(window, cx);
13086 if let Some(tx_id) = self
13087 .buffer
13088 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13089 {
13090 self.selection_history
13091 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13092 cx.emit(EditorEvent::TransactionBegun {
13093 transaction_id: tx_id,
13094 })
13095 }
13096 }
13097
13098 pub fn end_transaction_at(
13099 &mut self,
13100 now: Instant,
13101 cx: &mut Context<Self>,
13102 ) -> Option<TransactionId> {
13103 if let Some(transaction_id) = self
13104 .buffer
13105 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13106 {
13107 if let Some((_, end_selections)) =
13108 self.selection_history.transaction_mut(transaction_id)
13109 {
13110 *end_selections = Some(self.selections.disjoint_anchors());
13111 } else {
13112 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13113 }
13114
13115 cx.emit(EditorEvent::Edited { transaction_id });
13116 Some(transaction_id)
13117 } else {
13118 None
13119 }
13120 }
13121
13122 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13123 if self.selection_mark_mode {
13124 self.change_selections(None, window, cx, |s| {
13125 s.move_with(|_, sel| {
13126 sel.collapse_to(sel.head(), SelectionGoal::None);
13127 });
13128 })
13129 }
13130 self.selection_mark_mode = true;
13131 cx.notify();
13132 }
13133
13134 pub fn swap_selection_ends(
13135 &mut self,
13136 _: &actions::SwapSelectionEnds,
13137 window: &mut Window,
13138 cx: &mut Context<Self>,
13139 ) {
13140 self.change_selections(None, window, cx, |s| {
13141 s.move_with(|_, sel| {
13142 if sel.start != sel.end {
13143 sel.reversed = !sel.reversed
13144 }
13145 });
13146 });
13147 self.request_autoscroll(Autoscroll::newest(), cx);
13148 cx.notify();
13149 }
13150
13151 pub fn toggle_fold(
13152 &mut self,
13153 _: &actions::ToggleFold,
13154 window: &mut Window,
13155 cx: &mut Context<Self>,
13156 ) {
13157 if self.is_singleton(cx) {
13158 let selection = self.selections.newest::<Point>(cx);
13159
13160 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13161 let range = if selection.is_empty() {
13162 let point = selection.head().to_display_point(&display_map);
13163 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13164 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13165 .to_point(&display_map);
13166 start..end
13167 } else {
13168 selection.range()
13169 };
13170 if display_map.folds_in_range(range).next().is_some() {
13171 self.unfold_lines(&Default::default(), window, cx)
13172 } else {
13173 self.fold(&Default::default(), window, cx)
13174 }
13175 } else {
13176 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13177 let buffer_ids: HashSet<_> = self
13178 .selections
13179 .disjoint_anchor_ranges()
13180 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13181 .collect();
13182
13183 let should_unfold = buffer_ids
13184 .iter()
13185 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13186
13187 for buffer_id in buffer_ids {
13188 if should_unfold {
13189 self.unfold_buffer(buffer_id, cx);
13190 } else {
13191 self.fold_buffer(buffer_id, cx);
13192 }
13193 }
13194 }
13195 }
13196
13197 pub fn toggle_fold_recursive(
13198 &mut self,
13199 _: &actions::ToggleFoldRecursive,
13200 window: &mut Window,
13201 cx: &mut Context<Self>,
13202 ) {
13203 let selection = self.selections.newest::<Point>(cx);
13204
13205 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13206 let range = if selection.is_empty() {
13207 let point = selection.head().to_display_point(&display_map);
13208 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13209 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13210 .to_point(&display_map);
13211 start..end
13212 } else {
13213 selection.range()
13214 };
13215 if display_map.folds_in_range(range).next().is_some() {
13216 self.unfold_recursive(&Default::default(), window, cx)
13217 } else {
13218 self.fold_recursive(&Default::default(), window, cx)
13219 }
13220 }
13221
13222 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13223 if self.is_singleton(cx) {
13224 let mut to_fold = Vec::new();
13225 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13226 let selections = self.selections.all_adjusted(cx);
13227
13228 for selection in selections {
13229 let range = selection.range().sorted();
13230 let buffer_start_row = range.start.row;
13231
13232 if range.start.row != range.end.row {
13233 let mut found = false;
13234 let mut row = range.start.row;
13235 while row <= range.end.row {
13236 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13237 {
13238 found = true;
13239 row = crease.range().end.row + 1;
13240 to_fold.push(crease);
13241 } else {
13242 row += 1
13243 }
13244 }
13245 if found {
13246 continue;
13247 }
13248 }
13249
13250 for row in (0..=range.start.row).rev() {
13251 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13252 if crease.range().end.row >= buffer_start_row {
13253 to_fold.push(crease);
13254 if row <= range.start.row {
13255 break;
13256 }
13257 }
13258 }
13259 }
13260 }
13261
13262 self.fold_creases(to_fold, true, window, cx);
13263 } else {
13264 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13265 let buffer_ids = self
13266 .selections
13267 .disjoint_anchor_ranges()
13268 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13269 .collect::<HashSet<_>>();
13270 for buffer_id in buffer_ids {
13271 self.fold_buffer(buffer_id, cx);
13272 }
13273 }
13274 }
13275
13276 fn fold_at_level(
13277 &mut self,
13278 fold_at: &FoldAtLevel,
13279 window: &mut Window,
13280 cx: &mut Context<Self>,
13281 ) {
13282 if !self.buffer.read(cx).is_singleton() {
13283 return;
13284 }
13285
13286 let fold_at_level = fold_at.0;
13287 let snapshot = self.buffer.read(cx).snapshot(cx);
13288 let mut to_fold = Vec::new();
13289 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13290
13291 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13292 while start_row < end_row {
13293 match self
13294 .snapshot(window, cx)
13295 .crease_for_buffer_row(MultiBufferRow(start_row))
13296 {
13297 Some(crease) => {
13298 let nested_start_row = crease.range().start.row + 1;
13299 let nested_end_row = crease.range().end.row;
13300
13301 if current_level < fold_at_level {
13302 stack.push((nested_start_row, nested_end_row, current_level + 1));
13303 } else if current_level == fold_at_level {
13304 to_fold.push(crease);
13305 }
13306
13307 start_row = nested_end_row + 1;
13308 }
13309 None => start_row += 1,
13310 }
13311 }
13312 }
13313
13314 self.fold_creases(to_fold, true, window, cx);
13315 }
13316
13317 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
13318 if self.buffer.read(cx).is_singleton() {
13319 let mut fold_ranges = Vec::new();
13320 let snapshot = self.buffer.read(cx).snapshot(cx);
13321
13322 for row in 0..snapshot.max_row().0 {
13323 if let Some(foldable_range) = self
13324 .snapshot(window, cx)
13325 .crease_for_buffer_row(MultiBufferRow(row))
13326 {
13327 fold_ranges.push(foldable_range);
13328 }
13329 }
13330
13331 self.fold_creases(fold_ranges, true, window, cx);
13332 } else {
13333 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
13334 editor
13335 .update_in(&mut cx, |editor, _, cx| {
13336 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13337 editor.fold_buffer(buffer_id, cx);
13338 }
13339 })
13340 .ok();
13341 });
13342 }
13343 }
13344
13345 pub fn fold_function_bodies(
13346 &mut self,
13347 _: &actions::FoldFunctionBodies,
13348 window: &mut Window,
13349 cx: &mut Context<Self>,
13350 ) {
13351 let snapshot = self.buffer.read(cx).snapshot(cx);
13352
13353 let ranges = snapshot
13354 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
13355 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
13356 .collect::<Vec<_>>();
13357
13358 let creases = ranges
13359 .into_iter()
13360 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
13361 .collect();
13362
13363 self.fold_creases(creases, true, window, cx);
13364 }
13365
13366 pub fn fold_recursive(
13367 &mut self,
13368 _: &actions::FoldRecursive,
13369 window: &mut Window,
13370 cx: &mut Context<Self>,
13371 ) {
13372 let mut to_fold = Vec::new();
13373 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13374 let selections = self.selections.all_adjusted(cx);
13375
13376 for selection in selections {
13377 let range = selection.range().sorted();
13378 let buffer_start_row = range.start.row;
13379
13380 if range.start.row != range.end.row {
13381 let mut found = false;
13382 for row in range.start.row..=range.end.row {
13383 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13384 found = true;
13385 to_fold.push(crease);
13386 }
13387 }
13388 if found {
13389 continue;
13390 }
13391 }
13392
13393 for row in (0..=range.start.row).rev() {
13394 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13395 if crease.range().end.row >= buffer_start_row {
13396 to_fold.push(crease);
13397 } else {
13398 break;
13399 }
13400 }
13401 }
13402 }
13403
13404 self.fold_creases(to_fold, true, window, cx);
13405 }
13406
13407 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
13408 let buffer_row = fold_at.buffer_row;
13409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13410
13411 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
13412 let autoscroll = self
13413 .selections
13414 .all::<Point>(cx)
13415 .iter()
13416 .any(|selection| crease.range().overlaps(&selection.range()));
13417
13418 self.fold_creases(vec![crease], autoscroll, window, cx);
13419 }
13420 }
13421
13422 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
13423 if self.is_singleton(cx) {
13424 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13425 let buffer = &display_map.buffer_snapshot;
13426 let selections = self.selections.all::<Point>(cx);
13427 let ranges = selections
13428 .iter()
13429 .map(|s| {
13430 let range = s.display_range(&display_map).sorted();
13431 let mut start = range.start.to_point(&display_map);
13432 let mut end = range.end.to_point(&display_map);
13433 start.column = 0;
13434 end.column = buffer.line_len(MultiBufferRow(end.row));
13435 start..end
13436 })
13437 .collect::<Vec<_>>();
13438
13439 self.unfold_ranges(&ranges, true, true, cx);
13440 } else {
13441 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13442 let buffer_ids = self
13443 .selections
13444 .disjoint_anchor_ranges()
13445 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13446 .collect::<HashSet<_>>();
13447 for buffer_id in buffer_ids {
13448 self.unfold_buffer(buffer_id, cx);
13449 }
13450 }
13451 }
13452
13453 pub fn unfold_recursive(
13454 &mut self,
13455 _: &UnfoldRecursive,
13456 _window: &mut Window,
13457 cx: &mut Context<Self>,
13458 ) {
13459 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13460 let selections = self.selections.all::<Point>(cx);
13461 let ranges = selections
13462 .iter()
13463 .map(|s| {
13464 let mut range = s.display_range(&display_map).sorted();
13465 *range.start.column_mut() = 0;
13466 *range.end.column_mut() = display_map.line_len(range.end.row());
13467 let start = range.start.to_point(&display_map);
13468 let end = range.end.to_point(&display_map);
13469 start..end
13470 })
13471 .collect::<Vec<_>>();
13472
13473 self.unfold_ranges(&ranges, true, true, cx);
13474 }
13475
13476 pub fn unfold_at(
13477 &mut self,
13478 unfold_at: &UnfoldAt,
13479 _window: &mut Window,
13480 cx: &mut Context<Self>,
13481 ) {
13482 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13483
13484 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
13485 ..Point::new(
13486 unfold_at.buffer_row.0,
13487 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
13488 );
13489
13490 let autoscroll = self
13491 .selections
13492 .all::<Point>(cx)
13493 .iter()
13494 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
13495
13496 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
13497 }
13498
13499 pub fn unfold_all(
13500 &mut self,
13501 _: &actions::UnfoldAll,
13502 _window: &mut Window,
13503 cx: &mut Context<Self>,
13504 ) {
13505 if self.buffer.read(cx).is_singleton() {
13506 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13507 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
13508 } else {
13509 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
13510 editor
13511 .update(&mut cx, |editor, cx| {
13512 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
13513 editor.unfold_buffer(buffer_id, cx);
13514 }
13515 })
13516 .ok();
13517 });
13518 }
13519 }
13520
13521 pub fn fold_selected_ranges(
13522 &mut self,
13523 _: &FoldSelectedRanges,
13524 window: &mut Window,
13525 cx: &mut Context<Self>,
13526 ) {
13527 let selections = self.selections.all::<Point>(cx);
13528 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13529 let line_mode = self.selections.line_mode;
13530 let ranges = selections
13531 .into_iter()
13532 .map(|s| {
13533 if line_mode {
13534 let start = Point::new(s.start.row, 0);
13535 let end = Point::new(
13536 s.end.row,
13537 display_map
13538 .buffer_snapshot
13539 .line_len(MultiBufferRow(s.end.row)),
13540 );
13541 Crease::simple(start..end, display_map.fold_placeholder.clone())
13542 } else {
13543 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
13544 }
13545 })
13546 .collect::<Vec<_>>();
13547 self.fold_creases(ranges, true, window, cx);
13548 }
13549
13550 pub fn fold_ranges<T: ToOffset + Clone>(
13551 &mut self,
13552 ranges: Vec<Range<T>>,
13553 auto_scroll: bool,
13554 window: &mut Window,
13555 cx: &mut Context<Self>,
13556 ) {
13557 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13558 let ranges = ranges
13559 .into_iter()
13560 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
13561 .collect::<Vec<_>>();
13562 self.fold_creases(ranges, auto_scroll, window, cx);
13563 }
13564
13565 pub fn fold_creases<T: ToOffset + Clone>(
13566 &mut self,
13567 creases: Vec<Crease<T>>,
13568 auto_scroll: bool,
13569 window: &mut Window,
13570 cx: &mut Context<Self>,
13571 ) {
13572 if creases.is_empty() {
13573 return;
13574 }
13575
13576 let mut buffers_affected = HashSet::default();
13577 let multi_buffer = self.buffer().read(cx);
13578 for crease in &creases {
13579 if let Some((_, buffer, _)) =
13580 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
13581 {
13582 buffers_affected.insert(buffer.read(cx).remote_id());
13583 };
13584 }
13585
13586 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
13587
13588 if auto_scroll {
13589 self.request_autoscroll(Autoscroll::fit(), cx);
13590 }
13591
13592 cx.notify();
13593
13594 if let Some(active_diagnostics) = self.active_diagnostics.take() {
13595 // Clear diagnostics block when folding a range that contains it.
13596 let snapshot = self.snapshot(window, cx);
13597 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
13598 drop(snapshot);
13599 self.active_diagnostics = Some(active_diagnostics);
13600 self.dismiss_diagnostics(cx);
13601 } else {
13602 self.active_diagnostics = Some(active_diagnostics);
13603 }
13604 }
13605
13606 self.scrollbar_marker_state.dirty = true;
13607 }
13608
13609 /// Removes any folds whose ranges intersect any of the given ranges.
13610 pub fn unfold_ranges<T: ToOffset + Clone>(
13611 &mut self,
13612 ranges: &[Range<T>],
13613 inclusive: bool,
13614 auto_scroll: bool,
13615 cx: &mut Context<Self>,
13616 ) {
13617 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13618 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
13619 });
13620 }
13621
13622 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13623 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
13624 return;
13625 }
13626 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13627 self.display_map.update(cx, |display_map, cx| {
13628 display_map.fold_buffers([buffer_id], cx)
13629 });
13630 cx.emit(EditorEvent::BufferFoldToggled {
13631 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
13632 folded: true,
13633 });
13634 cx.notify();
13635 }
13636
13637 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
13638 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
13639 return;
13640 }
13641 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
13642 self.display_map.update(cx, |display_map, cx| {
13643 display_map.unfold_buffers([buffer_id], cx);
13644 });
13645 cx.emit(EditorEvent::BufferFoldToggled {
13646 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
13647 folded: false,
13648 });
13649 cx.notify();
13650 }
13651
13652 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
13653 self.display_map.read(cx).is_buffer_folded(buffer)
13654 }
13655
13656 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
13657 self.display_map.read(cx).folded_buffers()
13658 }
13659
13660 /// Removes any folds with the given ranges.
13661 pub fn remove_folds_with_type<T: ToOffset + Clone>(
13662 &mut self,
13663 ranges: &[Range<T>],
13664 type_id: TypeId,
13665 auto_scroll: bool,
13666 cx: &mut Context<Self>,
13667 ) {
13668 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
13669 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
13670 });
13671 }
13672
13673 fn remove_folds_with<T: ToOffset + Clone>(
13674 &mut self,
13675 ranges: &[Range<T>],
13676 auto_scroll: bool,
13677 cx: &mut Context<Self>,
13678 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
13679 ) {
13680 if ranges.is_empty() {
13681 return;
13682 }
13683
13684 let mut buffers_affected = HashSet::default();
13685 let multi_buffer = self.buffer().read(cx);
13686 for range in ranges {
13687 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
13688 buffers_affected.insert(buffer.read(cx).remote_id());
13689 };
13690 }
13691
13692 self.display_map.update(cx, update);
13693
13694 if auto_scroll {
13695 self.request_autoscroll(Autoscroll::fit(), cx);
13696 }
13697
13698 cx.notify();
13699 self.scrollbar_marker_state.dirty = true;
13700 self.active_indent_guides_state.dirty = true;
13701 }
13702
13703 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
13704 self.display_map.read(cx).fold_placeholder.clone()
13705 }
13706
13707 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
13708 self.buffer.update(cx, |buffer, cx| {
13709 buffer.set_all_diff_hunks_expanded(cx);
13710 });
13711 }
13712
13713 pub fn expand_all_diff_hunks(
13714 &mut self,
13715 _: &ExpandAllDiffHunks,
13716 _window: &mut Window,
13717 cx: &mut Context<Self>,
13718 ) {
13719 self.buffer.update(cx, |buffer, cx| {
13720 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
13721 });
13722 }
13723
13724 pub fn toggle_selected_diff_hunks(
13725 &mut self,
13726 _: &ToggleSelectedDiffHunks,
13727 _window: &mut Window,
13728 cx: &mut Context<Self>,
13729 ) {
13730 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13731 self.toggle_diff_hunks_in_ranges(ranges, cx);
13732 }
13733
13734 pub fn diff_hunks_in_ranges<'a>(
13735 &'a self,
13736 ranges: &'a [Range<Anchor>],
13737 buffer: &'a MultiBufferSnapshot,
13738 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
13739 ranges.iter().flat_map(move |range| {
13740 let end_excerpt_id = range.end.excerpt_id;
13741 let range = range.to_point(buffer);
13742 let mut peek_end = range.end;
13743 if range.end.row < buffer.max_row().0 {
13744 peek_end = Point::new(range.end.row + 1, 0);
13745 }
13746 buffer
13747 .diff_hunks_in_range(range.start..peek_end)
13748 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
13749 })
13750 }
13751
13752 pub fn has_stageable_diff_hunks_in_ranges(
13753 &self,
13754 ranges: &[Range<Anchor>],
13755 snapshot: &MultiBufferSnapshot,
13756 ) -> bool {
13757 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
13758 hunks.any(|hunk| hunk.status().has_secondary_hunk())
13759 }
13760
13761 pub fn toggle_staged_selected_diff_hunks(
13762 &mut self,
13763 _: &::git::ToggleStaged,
13764 _: &mut Window,
13765 cx: &mut Context<Self>,
13766 ) {
13767 let snapshot = self.buffer.read(cx).snapshot(cx);
13768 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13769 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
13770 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13771 }
13772
13773 pub fn stage_and_next(
13774 &mut self,
13775 _: &::git::StageAndNext,
13776 window: &mut Window,
13777 cx: &mut Context<Self>,
13778 ) {
13779 self.do_stage_or_unstage_and_next(true, window, cx);
13780 }
13781
13782 pub fn unstage_and_next(
13783 &mut self,
13784 _: &::git::UnstageAndNext,
13785 window: &mut Window,
13786 cx: &mut Context<Self>,
13787 ) {
13788 self.do_stage_or_unstage_and_next(false, window, cx);
13789 }
13790
13791 pub fn stage_or_unstage_diff_hunks(
13792 &mut self,
13793 stage: bool,
13794 ranges: Vec<Range<Anchor>>,
13795 cx: &mut Context<Self>,
13796 ) {
13797 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
13798 cx.spawn(|this, mut cx| async move {
13799 task.await?;
13800 this.update(&mut cx, |this, cx| {
13801 let snapshot = this.buffer.read(cx).snapshot(cx);
13802 let chunk_by = this
13803 .diff_hunks_in_ranges(&ranges, &snapshot)
13804 .chunk_by(|hunk| hunk.buffer_id);
13805 for (buffer_id, hunks) in &chunk_by {
13806 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
13807 }
13808 })
13809 })
13810 .detach_and_log_err(cx);
13811 }
13812
13813 fn save_buffers_for_ranges_if_needed(
13814 &mut self,
13815 ranges: &[Range<Anchor>],
13816 cx: &mut Context<'_, Editor>,
13817 ) -> Task<Result<()>> {
13818 let multibuffer = self.buffer.read(cx);
13819 let snapshot = multibuffer.read(cx);
13820 let buffer_ids: HashSet<_> = ranges
13821 .iter()
13822 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
13823 .collect();
13824 drop(snapshot);
13825
13826 let mut buffers = HashSet::default();
13827 for buffer_id in buffer_ids {
13828 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
13829 let buffer = buffer_entity.read(cx);
13830 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
13831 {
13832 buffers.insert(buffer_entity);
13833 }
13834 }
13835 }
13836
13837 if let Some(project) = &self.project {
13838 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
13839 } else {
13840 Task::ready(Ok(()))
13841 }
13842 }
13843
13844 fn do_stage_or_unstage_and_next(
13845 &mut self,
13846 stage: bool,
13847 window: &mut Window,
13848 cx: &mut Context<Self>,
13849 ) {
13850 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
13851
13852 if ranges.iter().any(|range| range.start != range.end) {
13853 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13854 return;
13855 }
13856
13857 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
13858 self.go_to_next_hunk(&GoToHunk, window, cx);
13859 }
13860
13861 fn do_stage_or_unstage(
13862 &self,
13863 stage: bool,
13864 buffer_id: BufferId,
13865 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
13866 cx: &mut App,
13867 ) -> Option<()> {
13868 let project = self.project.as_ref()?;
13869 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
13870 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
13871 let buffer_snapshot = buffer.read(cx).snapshot();
13872 let file_exists = buffer_snapshot
13873 .file()
13874 .is_some_and(|file| file.disk_state().exists());
13875 diff.update(cx, |diff, cx| {
13876 diff.stage_or_unstage_hunks(
13877 stage,
13878 &hunks
13879 .map(|hunk| buffer_diff::DiffHunk {
13880 buffer_range: hunk.buffer_range,
13881 diff_base_byte_range: hunk.diff_base_byte_range,
13882 secondary_status: hunk.secondary_status,
13883 range: Point::zero()..Point::zero(), // unused
13884 })
13885 .collect::<Vec<_>>(),
13886 &buffer_snapshot,
13887 file_exists,
13888 cx,
13889 )
13890 });
13891 None
13892 }
13893
13894 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
13895 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
13896 self.buffer
13897 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
13898 }
13899
13900 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
13901 self.buffer.update(cx, |buffer, cx| {
13902 let ranges = vec![Anchor::min()..Anchor::max()];
13903 if !buffer.all_diff_hunks_expanded()
13904 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
13905 {
13906 buffer.collapse_diff_hunks(ranges, cx);
13907 true
13908 } else {
13909 false
13910 }
13911 })
13912 }
13913
13914 fn toggle_diff_hunks_in_ranges(
13915 &mut self,
13916 ranges: Vec<Range<Anchor>>,
13917 cx: &mut Context<'_, Editor>,
13918 ) {
13919 self.buffer.update(cx, |buffer, cx| {
13920 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
13921 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
13922 })
13923 }
13924
13925 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
13926 self.buffer.update(cx, |buffer, cx| {
13927 let snapshot = buffer.snapshot(cx);
13928 let excerpt_id = range.end.excerpt_id;
13929 let point_range = range.to_point(&snapshot);
13930 let expand = !buffer.single_hunk_is_expanded(range, cx);
13931 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
13932 })
13933 }
13934
13935 pub(crate) fn apply_all_diff_hunks(
13936 &mut self,
13937 _: &ApplyAllDiffHunks,
13938 window: &mut Window,
13939 cx: &mut Context<Self>,
13940 ) {
13941 let buffers = self.buffer.read(cx).all_buffers();
13942 for branch_buffer in buffers {
13943 branch_buffer.update(cx, |branch_buffer, cx| {
13944 branch_buffer.merge_into_base(Vec::new(), cx);
13945 });
13946 }
13947
13948 if let Some(project) = self.project.clone() {
13949 self.save(true, project, window, cx).detach_and_log_err(cx);
13950 }
13951 }
13952
13953 pub(crate) fn apply_selected_diff_hunks(
13954 &mut self,
13955 _: &ApplyDiffHunk,
13956 window: &mut Window,
13957 cx: &mut Context<Self>,
13958 ) {
13959 let snapshot = self.snapshot(window, cx);
13960 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
13961 let mut ranges_by_buffer = HashMap::default();
13962 self.transact(window, cx, |editor, _window, cx| {
13963 for hunk in hunks {
13964 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
13965 ranges_by_buffer
13966 .entry(buffer.clone())
13967 .or_insert_with(Vec::new)
13968 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
13969 }
13970 }
13971
13972 for (buffer, ranges) in ranges_by_buffer {
13973 buffer.update(cx, |buffer, cx| {
13974 buffer.merge_into_base(ranges, cx);
13975 });
13976 }
13977 });
13978
13979 if let Some(project) = self.project.clone() {
13980 self.save(true, project, window, cx).detach_and_log_err(cx);
13981 }
13982 }
13983
13984 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
13985 if hovered != self.gutter_hovered {
13986 self.gutter_hovered = hovered;
13987 cx.notify();
13988 }
13989 }
13990
13991 pub fn insert_blocks(
13992 &mut self,
13993 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
13994 autoscroll: Option<Autoscroll>,
13995 cx: &mut Context<Self>,
13996 ) -> Vec<CustomBlockId> {
13997 let blocks = self
13998 .display_map
13999 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14000 if let Some(autoscroll) = autoscroll {
14001 self.request_autoscroll(autoscroll, cx);
14002 }
14003 cx.notify();
14004 blocks
14005 }
14006
14007 pub fn resize_blocks(
14008 &mut self,
14009 heights: HashMap<CustomBlockId, u32>,
14010 autoscroll: Option<Autoscroll>,
14011 cx: &mut Context<Self>,
14012 ) {
14013 self.display_map
14014 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14015 if let Some(autoscroll) = autoscroll {
14016 self.request_autoscroll(autoscroll, cx);
14017 }
14018 cx.notify();
14019 }
14020
14021 pub fn replace_blocks(
14022 &mut self,
14023 renderers: HashMap<CustomBlockId, RenderBlock>,
14024 autoscroll: Option<Autoscroll>,
14025 cx: &mut Context<Self>,
14026 ) {
14027 self.display_map
14028 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14029 if let Some(autoscroll) = autoscroll {
14030 self.request_autoscroll(autoscroll, cx);
14031 }
14032 cx.notify();
14033 }
14034
14035 pub fn remove_blocks(
14036 &mut self,
14037 block_ids: HashSet<CustomBlockId>,
14038 autoscroll: Option<Autoscroll>,
14039 cx: &mut Context<Self>,
14040 ) {
14041 self.display_map.update(cx, |display_map, cx| {
14042 display_map.remove_blocks(block_ids, cx)
14043 });
14044 if let Some(autoscroll) = autoscroll {
14045 self.request_autoscroll(autoscroll, cx);
14046 }
14047 cx.notify();
14048 }
14049
14050 pub fn row_for_block(
14051 &self,
14052 block_id: CustomBlockId,
14053 cx: &mut Context<Self>,
14054 ) -> Option<DisplayRow> {
14055 self.display_map
14056 .update(cx, |map, cx| map.row_for_block(block_id, cx))
14057 }
14058
14059 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14060 self.focused_block = Some(focused_block);
14061 }
14062
14063 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14064 self.focused_block.take()
14065 }
14066
14067 pub fn insert_creases(
14068 &mut self,
14069 creases: impl IntoIterator<Item = Crease<Anchor>>,
14070 cx: &mut Context<Self>,
14071 ) -> Vec<CreaseId> {
14072 self.display_map
14073 .update(cx, |map, cx| map.insert_creases(creases, cx))
14074 }
14075
14076 pub fn remove_creases(
14077 &mut self,
14078 ids: impl IntoIterator<Item = CreaseId>,
14079 cx: &mut Context<Self>,
14080 ) {
14081 self.display_map
14082 .update(cx, |map, cx| map.remove_creases(ids, cx));
14083 }
14084
14085 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14086 self.display_map
14087 .update(cx, |map, cx| map.snapshot(cx))
14088 .longest_row()
14089 }
14090
14091 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14092 self.display_map
14093 .update(cx, |map, cx| map.snapshot(cx))
14094 .max_point()
14095 }
14096
14097 pub fn text(&self, cx: &App) -> String {
14098 self.buffer.read(cx).read(cx).text()
14099 }
14100
14101 pub fn is_empty(&self, cx: &App) -> bool {
14102 self.buffer.read(cx).read(cx).is_empty()
14103 }
14104
14105 pub fn text_option(&self, cx: &App) -> Option<String> {
14106 let text = self.text(cx);
14107 let text = text.trim();
14108
14109 if text.is_empty() {
14110 return None;
14111 }
14112
14113 Some(text.to_string())
14114 }
14115
14116 pub fn set_text(
14117 &mut self,
14118 text: impl Into<Arc<str>>,
14119 window: &mut Window,
14120 cx: &mut Context<Self>,
14121 ) {
14122 self.transact(window, cx, |this, _, cx| {
14123 this.buffer
14124 .read(cx)
14125 .as_singleton()
14126 .expect("you can only call set_text on editors for singleton buffers")
14127 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14128 });
14129 }
14130
14131 pub fn display_text(&self, cx: &mut App) -> String {
14132 self.display_map
14133 .update(cx, |map, cx| map.snapshot(cx))
14134 .text()
14135 }
14136
14137 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14138 let mut wrap_guides = smallvec::smallvec![];
14139
14140 if self.show_wrap_guides == Some(false) {
14141 return wrap_guides;
14142 }
14143
14144 let settings = self.buffer.read(cx).language_settings(cx);
14145 if settings.show_wrap_guides {
14146 match self.soft_wrap_mode(cx) {
14147 SoftWrap::Column(soft_wrap) => {
14148 wrap_guides.push((soft_wrap as usize, true));
14149 }
14150 SoftWrap::Bounded(soft_wrap) => {
14151 wrap_guides.push((soft_wrap as usize, true));
14152 }
14153 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14154 }
14155 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14156 }
14157
14158 wrap_guides
14159 }
14160
14161 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14162 let settings = self.buffer.read(cx).language_settings(cx);
14163 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14164 match mode {
14165 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14166 SoftWrap::None
14167 }
14168 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14169 language_settings::SoftWrap::PreferredLineLength => {
14170 SoftWrap::Column(settings.preferred_line_length)
14171 }
14172 language_settings::SoftWrap::Bounded => {
14173 SoftWrap::Bounded(settings.preferred_line_length)
14174 }
14175 }
14176 }
14177
14178 pub fn set_soft_wrap_mode(
14179 &mut self,
14180 mode: language_settings::SoftWrap,
14181
14182 cx: &mut Context<Self>,
14183 ) {
14184 self.soft_wrap_mode_override = Some(mode);
14185 cx.notify();
14186 }
14187
14188 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14189 self.text_style_refinement = Some(style);
14190 }
14191
14192 /// called by the Element so we know what style we were most recently rendered with.
14193 pub(crate) fn set_style(
14194 &mut self,
14195 style: EditorStyle,
14196 window: &mut Window,
14197 cx: &mut Context<Self>,
14198 ) {
14199 let rem_size = window.rem_size();
14200 self.display_map.update(cx, |map, cx| {
14201 map.set_font(
14202 style.text.font(),
14203 style.text.font_size.to_pixels(rem_size),
14204 cx,
14205 )
14206 });
14207 self.style = Some(style);
14208 }
14209
14210 pub fn style(&self) -> Option<&EditorStyle> {
14211 self.style.as_ref()
14212 }
14213
14214 // Called by the element. This method is not designed to be called outside of the editor
14215 // element's layout code because it does not notify when rewrapping is computed synchronously.
14216 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14217 self.display_map
14218 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14219 }
14220
14221 pub fn set_soft_wrap(&mut self) {
14222 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14223 }
14224
14225 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14226 if self.soft_wrap_mode_override.is_some() {
14227 self.soft_wrap_mode_override.take();
14228 } else {
14229 let soft_wrap = match self.soft_wrap_mode(cx) {
14230 SoftWrap::GitDiff => return,
14231 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14232 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14233 language_settings::SoftWrap::None
14234 }
14235 };
14236 self.soft_wrap_mode_override = Some(soft_wrap);
14237 }
14238 cx.notify();
14239 }
14240
14241 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14242 let Some(workspace) = self.workspace() else {
14243 return;
14244 };
14245 let fs = workspace.read(cx).app_state().fs.clone();
14246 let current_show = TabBarSettings::get_global(cx).show;
14247 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14248 setting.show = Some(!current_show);
14249 });
14250 }
14251
14252 pub fn toggle_indent_guides(
14253 &mut self,
14254 _: &ToggleIndentGuides,
14255 _: &mut Window,
14256 cx: &mut Context<Self>,
14257 ) {
14258 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14259 self.buffer
14260 .read(cx)
14261 .language_settings(cx)
14262 .indent_guides
14263 .enabled
14264 });
14265 self.show_indent_guides = Some(!currently_enabled);
14266 cx.notify();
14267 }
14268
14269 fn should_show_indent_guides(&self) -> Option<bool> {
14270 self.show_indent_guides
14271 }
14272
14273 pub fn toggle_line_numbers(
14274 &mut self,
14275 _: &ToggleLineNumbers,
14276 _: &mut Window,
14277 cx: &mut Context<Self>,
14278 ) {
14279 let mut editor_settings = EditorSettings::get_global(cx).clone();
14280 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
14281 EditorSettings::override_global(editor_settings, cx);
14282 }
14283
14284 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
14285 if let Some(show_line_numbers) = self.show_line_numbers {
14286 return show_line_numbers;
14287 }
14288 EditorSettings::get_global(cx).gutter.line_numbers
14289 }
14290
14291 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
14292 self.use_relative_line_numbers
14293 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
14294 }
14295
14296 pub fn toggle_relative_line_numbers(
14297 &mut self,
14298 _: &ToggleRelativeLineNumbers,
14299 _: &mut Window,
14300 cx: &mut Context<Self>,
14301 ) {
14302 let is_relative = self.should_use_relative_line_numbers(cx);
14303 self.set_relative_line_number(Some(!is_relative), cx)
14304 }
14305
14306 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
14307 self.use_relative_line_numbers = is_relative;
14308 cx.notify();
14309 }
14310
14311 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
14312 self.show_gutter = show_gutter;
14313 cx.notify();
14314 }
14315
14316 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
14317 self.show_scrollbars = show_scrollbars;
14318 cx.notify();
14319 }
14320
14321 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
14322 self.show_line_numbers = Some(show_line_numbers);
14323 cx.notify();
14324 }
14325
14326 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
14327 self.show_git_diff_gutter = Some(show_git_diff_gutter);
14328 cx.notify();
14329 }
14330
14331 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
14332 self.show_code_actions = Some(show_code_actions);
14333 cx.notify();
14334 }
14335
14336 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
14337 self.show_runnables = Some(show_runnables);
14338 cx.notify();
14339 }
14340
14341 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
14342 if self.display_map.read(cx).masked != masked {
14343 self.display_map.update(cx, |map, _| map.masked = masked);
14344 }
14345 cx.notify()
14346 }
14347
14348 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
14349 self.show_wrap_guides = Some(show_wrap_guides);
14350 cx.notify();
14351 }
14352
14353 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
14354 self.show_indent_guides = Some(show_indent_guides);
14355 cx.notify();
14356 }
14357
14358 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
14359 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
14360 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
14361 if let Some(dir) = file.abs_path(cx).parent() {
14362 return Some(dir.to_owned());
14363 }
14364 }
14365
14366 if let Some(project_path) = buffer.read(cx).project_path(cx) {
14367 return Some(project_path.path.to_path_buf());
14368 }
14369 }
14370
14371 None
14372 }
14373
14374 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
14375 self.active_excerpt(cx)?
14376 .1
14377 .read(cx)
14378 .file()
14379 .and_then(|f| f.as_local())
14380 }
14381
14382 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14383 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14384 let buffer = buffer.read(cx);
14385 if let Some(project_path) = buffer.project_path(cx) {
14386 let project = self.project.as_ref()?.read(cx);
14387 project.absolute_path(&project_path, cx)
14388 } else {
14389 buffer
14390 .file()
14391 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
14392 }
14393 })
14394 }
14395
14396 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
14397 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
14398 let project_path = buffer.read(cx).project_path(cx)?;
14399 let project = self.project.as_ref()?.read(cx);
14400 let entry = project.entry_for_path(&project_path, cx)?;
14401 let path = entry.path.to_path_buf();
14402 Some(path)
14403 })
14404 }
14405
14406 pub fn reveal_in_finder(
14407 &mut self,
14408 _: &RevealInFileManager,
14409 _window: &mut Window,
14410 cx: &mut Context<Self>,
14411 ) {
14412 if let Some(target) = self.target_file(cx) {
14413 cx.reveal_path(&target.abs_path(cx));
14414 }
14415 }
14416
14417 pub fn copy_path(
14418 &mut self,
14419 _: &zed_actions::workspace::CopyPath,
14420 _window: &mut Window,
14421 cx: &mut Context<Self>,
14422 ) {
14423 if let Some(path) = self.target_file_abs_path(cx) {
14424 if let Some(path) = path.to_str() {
14425 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14426 }
14427 }
14428 }
14429
14430 pub fn copy_relative_path(
14431 &mut self,
14432 _: &zed_actions::workspace::CopyRelativePath,
14433 _window: &mut Window,
14434 cx: &mut Context<Self>,
14435 ) {
14436 if let Some(path) = self.target_file_path(cx) {
14437 if let Some(path) = path.to_str() {
14438 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
14439 }
14440 }
14441 }
14442
14443 pub fn copy_file_name_without_extension(
14444 &mut self,
14445 _: &CopyFileNameWithoutExtension,
14446 _: &mut Window,
14447 cx: &mut Context<Self>,
14448 ) {
14449 if let Some(file) = self.target_file(cx) {
14450 if let Some(file_stem) = file.path().file_stem() {
14451 if let Some(name) = file_stem.to_str() {
14452 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14453 }
14454 }
14455 }
14456 }
14457
14458 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
14459 if let Some(file) = self.target_file(cx) {
14460 if let Some(file_name) = file.path().file_name() {
14461 if let Some(name) = file_name.to_str() {
14462 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
14463 }
14464 }
14465 }
14466 }
14467
14468 pub fn toggle_git_blame(
14469 &mut self,
14470 _: &ToggleGitBlame,
14471 window: &mut Window,
14472 cx: &mut Context<Self>,
14473 ) {
14474 self.show_git_blame_gutter = !self.show_git_blame_gutter;
14475
14476 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
14477 self.start_git_blame(true, window, cx);
14478 }
14479
14480 cx.notify();
14481 }
14482
14483 pub fn toggle_git_blame_inline(
14484 &mut self,
14485 _: &ToggleGitBlameInline,
14486 window: &mut Window,
14487 cx: &mut Context<Self>,
14488 ) {
14489 self.toggle_git_blame_inline_internal(true, window, cx);
14490 cx.notify();
14491 }
14492
14493 pub fn git_blame_inline_enabled(&self) -> bool {
14494 self.git_blame_inline_enabled
14495 }
14496
14497 pub fn toggle_selection_menu(
14498 &mut self,
14499 _: &ToggleSelectionMenu,
14500 _: &mut Window,
14501 cx: &mut Context<Self>,
14502 ) {
14503 self.show_selection_menu = self
14504 .show_selection_menu
14505 .map(|show_selections_menu| !show_selections_menu)
14506 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
14507
14508 cx.notify();
14509 }
14510
14511 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
14512 self.show_selection_menu
14513 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
14514 }
14515
14516 fn start_git_blame(
14517 &mut self,
14518 user_triggered: bool,
14519 window: &mut Window,
14520 cx: &mut Context<Self>,
14521 ) {
14522 if let Some(project) = self.project.as_ref() {
14523 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
14524 return;
14525 };
14526
14527 if buffer.read(cx).file().is_none() {
14528 return;
14529 }
14530
14531 let focused = self.focus_handle(cx).contains_focused(window, cx);
14532
14533 let project = project.clone();
14534 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
14535 self.blame_subscription =
14536 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
14537 self.blame = Some(blame);
14538 }
14539 }
14540
14541 fn toggle_git_blame_inline_internal(
14542 &mut self,
14543 user_triggered: bool,
14544 window: &mut Window,
14545 cx: &mut Context<Self>,
14546 ) {
14547 if self.git_blame_inline_enabled {
14548 self.git_blame_inline_enabled = false;
14549 self.show_git_blame_inline = false;
14550 self.show_git_blame_inline_delay_task.take();
14551 } else {
14552 self.git_blame_inline_enabled = true;
14553 self.start_git_blame_inline(user_triggered, window, cx);
14554 }
14555
14556 cx.notify();
14557 }
14558
14559 fn start_git_blame_inline(
14560 &mut self,
14561 user_triggered: bool,
14562 window: &mut Window,
14563 cx: &mut Context<Self>,
14564 ) {
14565 self.start_git_blame(user_triggered, window, cx);
14566
14567 if ProjectSettings::get_global(cx)
14568 .git
14569 .inline_blame_delay()
14570 .is_some()
14571 {
14572 self.start_inline_blame_timer(window, cx);
14573 } else {
14574 self.show_git_blame_inline = true
14575 }
14576 }
14577
14578 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
14579 self.blame.as_ref()
14580 }
14581
14582 pub fn show_git_blame_gutter(&self) -> bool {
14583 self.show_git_blame_gutter
14584 }
14585
14586 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
14587 self.show_git_blame_gutter && self.has_blame_entries(cx)
14588 }
14589
14590 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
14591 self.show_git_blame_inline
14592 && (self.focus_handle.is_focused(window)
14593 || self
14594 .git_blame_inline_tooltip
14595 .as_ref()
14596 .and_then(|t| t.upgrade())
14597 .is_some())
14598 && !self.newest_selection_head_on_empty_line(cx)
14599 && self.has_blame_entries(cx)
14600 }
14601
14602 fn has_blame_entries(&self, cx: &App) -> bool {
14603 self.blame()
14604 .map_or(false, |blame| blame.read(cx).has_generated_entries())
14605 }
14606
14607 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
14608 let cursor_anchor = self.selections.newest_anchor().head();
14609
14610 let snapshot = self.buffer.read(cx).snapshot(cx);
14611 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
14612
14613 snapshot.line_len(buffer_row) == 0
14614 }
14615
14616 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
14617 let buffer_and_selection = maybe!({
14618 let selection = self.selections.newest::<Point>(cx);
14619 let selection_range = selection.range();
14620
14621 let multi_buffer = self.buffer().read(cx);
14622 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14623 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
14624
14625 let (buffer, range, _) = if selection.reversed {
14626 buffer_ranges.first()
14627 } else {
14628 buffer_ranges.last()
14629 }?;
14630
14631 let selection = text::ToPoint::to_point(&range.start, &buffer).row
14632 ..text::ToPoint::to_point(&range.end, &buffer).row;
14633 Some((
14634 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
14635 selection,
14636 ))
14637 });
14638
14639 let Some((buffer, selection)) = buffer_and_selection else {
14640 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
14641 };
14642
14643 let Some(project) = self.project.as_ref() else {
14644 return Task::ready(Err(anyhow!("editor does not have project")));
14645 };
14646
14647 project.update(cx, |project, cx| {
14648 project.get_permalink_to_line(&buffer, selection, cx)
14649 })
14650 }
14651
14652 pub fn copy_permalink_to_line(
14653 &mut self,
14654 _: &CopyPermalinkToLine,
14655 window: &mut Window,
14656 cx: &mut Context<Self>,
14657 ) {
14658 let permalink_task = self.get_permalink_to_line(cx);
14659 let workspace = self.workspace();
14660
14661 cx.spawn_in(window, |_, mut cx| async move {
14662 match permalink_task.await {
14663 Ok(permalink) => {
14664 cx.update(|_, cx| {
14665 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
14666 })
14667 .ok();
14668 }
14669 Err(err) => {
14670 let message = format!("Failed to copy permalink: {err}");
14671
14672 Err::<(), anyhow::Error>(err).log_err();
14673
14674 if let Some(workspace) = workspace {
14675 workspace
14676 .update_in(&mut cx, |workspace, _, cx| {
14677 struct CopyPermalinkToLine;
14678
14679 workspace.show_toast(
14680 Toast::new(
14681 NotificationId::unique::<CopyPermalinkToLine>(),
14682 message,
14683 ),
14684 cx,
14685 )
14686 })
14687 .ok();
14688 }
14689 }
14690 }
14691 })
14692 .detach();
14693 }
14694
14695 pub fn copy_file_location(
14696 &mut self,
14697 _: &CopyFileLocation,
14698 _: &mut Window,
14699 cx: &mut Context<Self>,
14700 ) {
14701 let selection = self.selections.newest::<Point>(cx).start.row + 1;
14702 if let Some(file) = self.target_file(cx) {
14703 if let Some(path) = file.path().to_str() {
14704 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
14705 }
14706 }
14707 }
14708
14709 pub fn open_permalink_to_line(
14710 &mut self,
14711 _: &OpenPermalinkToLine,
14712 window: &mut Window,
14713 cx: &mut Context<Self>,
14714 ) {
14715 let permalink_task = self.get_permalink_to_line(cx);
14716 let workspace = self.workspace();
14717
14718 cx.spawn_in(window, |_, mut cx| async move {
14719 match permalink_task.await {
14720 Ok(permalink) => {
14721 cx.update(|_, cx| {
14722 cx.open_url(permalink.as_ref());
14723 })
14724 .ok();
14725 }
14726 Err(err) => {
14727 let message = format!("Failed to open permalink: {err}");
14728
14729 Err::<(), anyhow::Error>(err).log_err();
14730
14731 if let Some(workspace) = workspace {
14732 workspace
14733 .update(&mut cx, |workspace, cx| {
14734 struct OpenPermalinkToLine;
14735
14736 workspace.show_toast(
14737 Toast::new(
14738 NotificationId::unique::<OpenPermalinkToLine>(),
14739 message,
14740 ),
14741 cx,
14742 )
14743 })
14744 .ok();
14745 }
14746 }
14747 }
14748 })
14749 .detach();
14750 }
14751
14752 pub fn insert_uuid_v4(
14753 &mut self,
14754 _: &InsertUuidV4,
14755 window: &mut Window,
14756 cx: &mut Context<Self>,
14757 ) {
14758 self.insert_uuid(UuidVersion::V4, window, cx);
14759 }
14760
14761 pub fn insert_uuid_v7(
14762 &mut self,
14763 _: &InsertUuidV7,
14764 window: &mut Window,
14765 cx: &mut Context<Self>,
14766 ) {
14767 self.insert_uuid(UuidVersion::V7, window, cx);
14768 }
14769
14770 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
14771 self.transact(window, cx, |this, window, cx| {
14772 let edits = this
14773 .selections
14774 .all::<Point>(cx)
14775 .into_iter()
14776 .map(|selection| {
14777 let uuid = match version {
14778 UuidVersion::V4 => uuid::Uuid::new_v4(),
14779 UuidVersion::V7 => uuid::Uuid::now_v7(),
14780 };
14781
14782 (selection.range(), uuid.to_string())
14783 });
14784 this.edit(edits, cx);
14785 this.refresh_inline_completion(true, false, window, cx);
14786 });
14787 }
14788
14789 pub fn open_selections_in_multibuffer(
14790 &mut self,
14791 _: &OpenSelectionsInMultibuffer,
14792 window: &mut Window,
14793 cx: &mut Context<Self>,
14794 ) {
14795 let multibuffer = self.buffer.read(cx);
14796
14797 let Some(buffer) = multibuffer.as_singleton() else {
14798 return;
14799 };
14800
14801 let Some(workspace) = self.workspace() else {
14802 return;
14803 };
14804
14805 let locations = self
14806 .selections
14807 .disjoint_anchors()
14808 .iter()
14809 .map(|range| Location {
14810 buffer: buffer.clone(),
14811 range: range.start.text_anchor..range.end.text_anchor,
14812 })
14813 .collect::<Vec<_>>();
14814
14815 let title = multibuffer.title(cx).to_string();
14816
14817 cx.spawn_in(window, |_, mut cx| async move {
14818 workspace.update_in(&mut cx, |workspace, window, cx| {
14819 Self::open_locations_in_multibuffer(
14820 workspace,
14821 locations,
14822 format!("Selections for '{title}'"),
14823 false,
14824 MultibufferSelectionMode::All,
14825 window,
14826 cx,
14827 );
14828 })
14829 })
14830 .detach();
14831 }
14832
14833 /// Adds a row highlight for the given range. If a row has multiple highlights, the
14834 /// last highlight added will be used.
14835 ///
14836 /// If the range ends at the beginning of a line, then that line will not be highlighted.
14837 pub fn highlight_rows<T: 'static>(
14838 &mut self,
14839 range: Range<Anchor>,
14840 color: Hsla,
14841 should_autoscroll: bool,
14842 cx: &mut Context<Self>,
14843 ) {
14844 let snapshot = self.buffer().read(cx).snapshot(cx);
14845 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14846 let ix = row_highlights.binary_search_by(|highlight| {
14847 Ordering::Equal
14848 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
14849 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
14850 });
14851
14852 if let Err(mut ix) = ix {
14853 let index = post_inc(&mut self.highlight_order);
14854
14855 // If this range intersects with the preceding highlight, then merge it with
14856 // the preceding highlight. Otherwise insert a new highlight.
14857 let mut merged = false;
14858 if ix > 0 {
14859 let prev_highlight = &mut row_highlights[ix - 1];
14860 if prev_highlight
14861 .range
14862 .end
14863 .cmp(&range.start, &snapshot)
14864 .is_ge()
14865 {
14866 ix -= 1;
14867 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
14868 prev_highlight.range.end = range.end;
14869 }
14870 merged = true;
14871 prev_highlight.index = index;
14872 prev_highlight.color = color;
14873 prev_highlight.should_autoscroll = should_autoscroll;
14874 }
14875 }
14876
14877 if !merged {
14878 row_highlights.insert(
14879 ix,
14880 RowHighlight {
14881 range: range.clone(),
14882 index,
14883 color,
14884 should_autoscroll,
14885 },
14886 );
14887 }
14888
14889 // If any of the following highlights intersect with this one, merge them.
14890 while let Some(next_highlight) = row_highlights.get(ix + 1) {
14891 let highlight = &row_highlights[ix];
14892 if next_highlight
14893 .range
14894 .start
14895 .cmp(&highlight.range.end, &snapshot)
14896 .is_le()
14897 {
14898 if next_highlight
14899 .range
14900 .end
14901 .cmp(&highlight.range.end, &snapshot)
14902 .is_gt()
14903 {
14904 row_highlights[ix].range.end = next_highlight.range.end;
14905 }
14906 row_highlights.remove(ix + 1);
14907 } else {
14908 break;
14909 }
14910 }
14911 }
14912 }
14913
14914 /// Remove any highlighted row ranges of the given type that intersect the
14915 /// given ranges.
14916 pub fn remove_highlighted_rows<T: 'static>(
14917 &mut self,
14918 ranges_to_remove: Vec<Range<Anchor>>,
14919 cx: &mut Context<Self>,
14920 ) {
14921 let snapshot = self.buffer().read(cx).snapshot(cx);
14922 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
14923 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
14924 row_highlights.retain(|highlight| {
14925 while let Some(range_to_remove) = ranges_to_remove.peek() {
14926 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
14927 Ordering::Less | Ordering::Equal => {
14928 ranges_to_remove.next();
14929 }
14930 Ordering::Greater => {
14931 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
14932 Ordering::Less | Ordering::Equal => {
14933 return false;
14934 }
14935 Ordering::Greater => break,
14936 }
14937 }
14938 }
14939 }
14940
14941 true
14942 })
14943 }
14944
14945 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
14946 pub fn clear_row_highlights<T: 'static>(&mut self) {
14947 self.highlighted_rows.remove(&TypeId::of::<T>());
14948 }
14949
14950 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
14951 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
14952 self.highlighted_rows
14953 .get(&TypeId::of::<T>())
14954 .map_or(&[] as &[_], |vec| vec.as_slice())
14955 .iter()
14956 .map(|highlight| (highlight.range.clone(), highlight.color))
14957 }
14958
14959 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
14960 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
14961 /// Allows to ignore certain kinds of highlights.
14962 pub fn highlighted_display_rows(
14963 &self,
14964 window: &mut Window,
14965 cx: &mut App,
14966 ) -> BTreeMap<DisplayRow, LineHighlight> {
14967 let snapshot = self.snapshot(window, cx);
14968 let mut used_highlight_orders = HashMap::default();
14969 self.highlighted_rows
14970 .iter()
14971 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
14972 .fold(
14973 BTreeMap::<DisplayRow, LineHighlight>::new(),
14974 |mut unique_rows, highlight| {
14975 let start = highlight.range.start.to_display_point(&snapshot);
14976 let end = highlight.range.end.to_display_point(&snapshot);
14977 let start_row = start.row().0;
14978 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
14979 && end.column() == 0
14980 {
14981 end.row().0.saturating_sub(1)
14982 } else {
14983 end.row().0
14984 };
14985 for row in start_row..=end_row {
14986 let used_index =
14987 used_highlight_orders.entry(row).or_insert(highlight.index);
14988 if highlight.index >= *used_index {
14989 *used_index = highlight.index;
14990 unique_rows.insert(DisplayRow(row), highlight.color.into());
14991 }
14992 }
14993 unique_rows
14994 },
14995 )
14996 }
14997
14998 pub fn highlighted_display_row_for_autoscroll(
14999 &self,
15000 snapshot: &DisplaySnapshot,
15001 ) -> Option<DisplayRow> {
15002 self.highlighted_rows
15003 .values()
15004 .flat_map(|highlighted_rows| highlighted_rows.iter())
15005 .filter_map(|highlight| {
15006 if highlight.should_autoscroll {
15007 Some(highlight.range.start.to_display_point(snapshot).row())
15008 } else {
15009 None
15010 }
15011 })
15012 .min()
15013 }
15014
15015 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15016 self.highlight_background::<SearchWithinRange>(
15017 ranges,
15018 |colors| colors.editor_document_highlight_read_background,
15019 cx,
15020 )
15021 }
15022
15023 pub fn set_breadcrumb_header(&mut self, new_header: String) {
15024 self.breadcrumb_header = Some(new_header);
15025 }
15026
15027 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15028 self.clear_background_highlights::<SearchWithinRange>(cx);
15029 }
15030
15031 pub fn highlight_background<T: 'static>(
15032 &mut self,
15033 ranges: &[Range<Anchor>],
15034 color_fetcher: fn(&ThemeColors) -> Hsla,
15035 cx: &mut Context<Self>,
15036 ) {
15037 self.background_highlights
15038 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15039 self.scrollbar_marker_state.dirty = true;
15040 cx.notify();
15041 }
15042
15043 pub fn clear_background_highlights<T: 'static>(
15044 &mut self,
15045 cx: &mut Context<Self>,
15046 ) -> Option<BackgroundHighlight> {
15047 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15048 if !text_highlights.1.is_empty() {
15049 self.scrollbar_marker_state.dirty = true;
15050 cx.notify();
15051 }
15052 Some(text_highlights)
15053 }
15054
15055 pub fn highlight_gutter<T: 'static>(
15056 &mut self,
15057 ranges: &[Range<Anchor>],
15058 color_fetcher: fn(&App) -> Hsla,
15059 cx: &mut Context<Self>,
15060 ) {
15061 self.gutter_highlights
15062 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15063 cx.notify();
15064 }
15065
15066 pub fn clear_gutter_highlights<T: 'static>(
15067 &mut self,
15068 cx: &mut Context<Self>,
15069 ) -> Option<GutterHighlight> {
15070 cx.notify();
15071 self.gutter_highlights.remove(&TypeId::of::<T>())
15072 }
15073
15074 #[cfg(feature = "test-support")]
15075 pub fn all_text_background_highlights(
15076 &self,
15077 window: &mut Window,
15078 cx: &mut Context<Self>,
15079 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15080 let snapshot = self.snapshot(window, cx);
15081 let buffer = &snapshot.buffer_snapshot;
15082 let start = buffer.anchor_before(0);
15083 let end = buffer.anchor_after(buffer.len());
15084 let theme = cx.theme().colors();
15085 self.background_highlights_in_range(start..end, &snapshot, theme)
15086 }
15087
15088 #[cfg(feature = "test-support")]
15089 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15090 let snapshot = self.buffer().read(cx).snapshot(cx);
15091
15092 let highlights = self
15093 .background_highlights
15094 .get(&TypeId::of::<items::BufferSearchHighlights>());
15095
15096 if let Some((_color, ranges)) = highlights {
15097 ranges
15098 .iter()
15099 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15100 .collect_vec()
15101 } else {
15102 vec![]
15103 }
15104 }
15105
15106 fn document_highlights_for_position<'a>(
15107 &'a self,
15108 position: Anchor,
15109 buffer: &'a MultiBufferSnapshot,
15110 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15111 let read_highlights = self
15112 .background_highlights
15113 .get(&TypeId::of::<DocumentHighlightRead>())
15114 .map(|h| &h.1);
15115 let write_highlights = self
15116 .background_highlights
15117 .get(&TypeId::of::<DocumentHighlightWrite>())
15118 .map(|h| &h.1);
15119 let left_position = position.bias_left(buffer);
15120 let right_position = position.bias_right(buffer);
15121 read_highlights
15122 .into_iter()
15123 .chain(write_highlights)
15124 .flat_map(move |ranges| {
15125 let start_ix = match ranges.binary_search_by(|probe| {
15126 let cmp = probe.end.cmp(&left_position, buffer);
15127 if cmp.is_ge() {
15128 Ordering::Greater
15129 } else {
15130 Ordering::Less
15131 }
15132 }) {
15133 Ok(i) | Err(i) => i,
15134 };
15135
15136 ranges[start_ix..]
15137 .iter()
15138 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15139 })
15140 }
15141
15142 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15143 self.background_highlights
15144 .get(&TypeId::of::<T>())
15145 .map_or(false, |(_, highlights)| !highlights.is_empty())
15146 }
15147
15148 pub fn background_highlights_in_range(
15149 &self,
15150 search_range: Range<Anchor>,
15151 display_snapshot: &DisplaySnapshot,
15152 theme: &ThemeColors,
15153 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15154 let mut results = Vec::new();
15155 for (color_fetcher, ranges) in self.background_highlights.values() {
15156 let color = color_fetcher(theme);
15157 let start_ix = match ranges.binary_search_by(|probe| {
15158 let cmp = probe
15159 .end
15160 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15161 if cmp.is_gt() {
15162 Ordering::Greater
15163 } else {
15164 Ordering::Less
15165 }
15166 }) {
15167 Ok(i) | Err(i) => i,
15168 };
15169 for range in &ranges[start_ix..] {
15170 if range
15171 .start
15172 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15173 .is_ge()
15174 {
15175 break;
15176 }
15177
15178 let start = range.start.to_display_point(display_snapshot);
15179 let end = range.end.to_display_point(display_snapshot);
15180 results.push((start..end, color))
15181 }
15182 }
15183 results
15184 }
15185
15186 pub fn background_highlight_row_ranges<T: 'static>(
15187 &self,
15188 search_range: Range<Anchor>,
15189 display_snapshot: &DisplaySnapshot,
15190 count: usize,
15191 ) -> Vec<RangeInclusive<DisplayPoint>> {
15192 let mut results = Vec::new();
15193 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15194 return vec![];
15195 };
15196
15197 let start_ix = match ranges.binary_search_by(|probe| {
15198 let cmp = probe
15199 .end
15200 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15201 if cmp.is_gt() {
15202 Ordering::Greater
15203 } else {
15204 Ordering::Less
15205 }
15206 }) {
15207 Ok(i) | Err(i) => i,
15208 };
15209 let mut push_region = |start: Option<Point>, end: Option<Point>| {
15210 if let (Some(start_display), Some(end_display)) = (start, end) {
15211 results.push(
15212 start_display.to_display_point(display_snapshot)
15213 ..=end_display.to_display_point(display_snapshot),
15214 );
15215 }
15216 };
15217 let mut start_row: Option<Point> = None;
15218 let mut end_row: Option<Point> = None;
15219 if ranges.len() > count {
15220 return Vec::new();
15221 }
15222 for range in &ranges[start_ix..] {
15223 if range
15224 .start
15225 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15226 .is_ge()
15227 {
15228 break;
15229 }
15230 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
15231 if let Some(current_row) = &end_row {
15232 if end.row == current_row.row {
15233 continue;
15234 }
15235 }
15236 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
15237 if start_row.is_none() {
15238 assert_eq!(end_row, None);
15239 start_row = Some(start);
15240 end_row = Some(end);
15241 continue;
15242 }
15243 if let Some(current_end) = end_row.as_mut() {
15244 if start.row > current_end.row + 1 {
15245 push_region(start_row, end_row);
15246 start_row = Some(start);
15247 end_row = Some(end);
15248 } else {
15249 // Merge two hunks.
15250 *current_end = end;
15251 }
15252 } else {
15253 unreachable!();
15254 }
15255 }
15256 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
15257 push_region(start_row, end_row);
15258 results
15259 }
15260
15261 pub fn gutter_highlights_in_range(
15262 &self,
15263 search_range: Range<Anchor>,
15264 display_snapshot: &DisplaySnapshot,
15265 cx: &App,
15266 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15267 let mut results = Vec::new();
15268 for (color_fetcher, ranges) in self.gutter_highlights.values() {
15269 let color = color_fetcher(cx);
15270 let start_ix = match ranges.binary_search_by(|probe| {
15271 let cmp = probe
15272 .end
15273 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15274 if cmp.is_gt() {
15275 Ordering::Greater
15276 } else {
15277 Ordering::Less
15278 }
15279 }) {
15280 Ok(i) | Err(i) => i,
15281 };
15282 for range in &ranges[start_ix..] {
15283 if range
15284 .start
15285 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15286 .is_ge()
15287 {
15288 break;
15289 }
15290
15291 let start = range.start.to_display_point(display_snapshot);
15292 let end = range.end.to_display_point(display_snapshot);
15293 results.push((start..end, color))
15294 }
15295 }
15296 results
15297 }
15298
15299 /// Get the text ranges corresponding to the redaction query
15300 pub fn redacted_ranges(
15301 &self,
15302 search_range: Range<Anchor>,
15303 display_snapshot: &DisplaySnapshot,
15304 cx: &App,
15305 ) -> Vec<Range<DisplayPoint>> {
15306 display_snapshot
15307 .buffer_snapshot
15308 .redacted_ranges(search_range, |file| {
15309 if let Some(file) = file {
15310 file.is_private()
15311 && EditorSettings::get(
15312 Some(SettingsLocation {
15313 worktree_id: file.worktree_id(cx),
15314 path: file.path().as_ref(),
15315 }),
15316 cx,
15317 )
15318 .redact_private_values
15319 } else {
15320 false
15321 }
15322 })
15323 .map(|range| {
15324 range.start.to_display_point(display_snapshot)
15325 ..range.end.to_display_point(display_snapshot)
15326 })
15327 .collect()
15328 }
15329
15330 pub fn highlight_text<T: 'static>(
15331 &mut self,
15332 ranges: Vec<Range<Anchor>>,
15333 style: HighlightStyle,
15334 cx: &mut Context<Self>,
15335 ) {
15336 self.display_map.update(cx, |map, _| {
15337 map.highlight_text(TypeId::of::<T>(), ranges, style)
15338 });
15339 cx.notify();
15340 }
15341
15342 pub(crate) fn highlight_inlays<T: 'static>(
15343 &mut self,
15344 highlights: Vec<InlayHighlight>,
15345 style: HighlightStyle,
15346 cx: &mut Context<Self>,
15347 ) {
15348 self.display_map.update(cx, |map, _| {
15349 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
15350 });
15351 cx.notify();
15352 }
15353
15354 pub fn text_highlights<'a, T: 'static>(
15355 &'a self,
15356 cx: &'a App,
15357 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
15358 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
15359 }
15360
15361 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
15362 let cleared = self
15363 .display_map
15364 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
15365 if cleared {
15366 cx.notify();
15367 }
15368 }
15369
15370 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
15371 (self.read_only(cx) || self.blink_manager.read(cx).visible())
15372 && self.focus_handle.is_focused(window)
15373 }
15374
15375 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
15376 self.show_cursor_when_unfocused = is_enabled;
15377 cx.notify();
15378 }
15379
15380 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
15381 cx.notify();
15382 }
15383
15384 fn on_buffer_event(
15385 &mut self,
15386 multibuffer: &Entity<MultiBuffer>,
15387 event: &multi_buffer::Event,
15388 window: &mut Window,
15389 cx: &mut Context<Self>,
15390 ) {
15391 match event {
15392 multi_buffer::Event::Edited {
15393 singleton_buffer_edited,
15394 edited_buffer: buffer_edited,
15395 } => {
15396 self.scrollbar_marker_state.dirty = true;
15397 self.active_indent_guides_state.dirty = true;
15398 self.refresh_active_diagnostics(cx);
15399 self.refresh_code_actions(window, cx);
15400 if self.has_active_inline_completion() {
15401 self.update_visible_inline_completion(window, cx);
15402 }
15403 if let Some(buffer) = buffer_edited {
15404 let buffer_id = buffer.read(cx).remote_id();
15405 if !self.registered_buffers.contains_key(&buffer_id) {
15406 if let Some(project) = self.project.as_ref() {
15407 project.update(cx, |project, cx| {
15408 self.registered_buffers.insert(
15409 buffer_id,
15410 project.register_buffer_with_language_servers(&buffer, cx),
15411 );
15412 })
15413 }
15414 }
15415 }
15416 cx.emit(EditorEvent::BufferEdited);
15417 cx.emit(SearchEvent::MatchesInvalidated);
15418 if *singleton_buffer_edited {
15419 if let Some(project) = &self.project {
15420 #[allow(clippy::mutable_key_type)]
15421 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
15422 multibuffer
15423 .all_buffers()
15424 .into_iter()
15425 .filter_map(|buffer| {
15426 buffer.update(cx, |buffer, cx| {
15427 let language = buffer.language()?;
15428 let should_discard = project.update(cx, |project, cx| {
15429 project.is_local()
15430 && !project.has_language_servers_for(buffer, cx)
15431 });
15432 should_discard.not().then_some(language.clone())
15433 })
15434 })
15435 .collect::<HashSet<_>>()
15436 });
15437 if !languages_affected.is_empty() {
15438 self.refresh_inlay_hints(
15439 InlayHintRefreshReason::BufferEdited(languages_affected),
15440 cx,
15441 );
15442 }
15443 }
15444 }
15445
15446 let Some(project) = &self.project else { return };
15447 let (telemetry, is_via_ssh) = {
15448 let project = project.read(cx);
15449 let telemetry = project.client().telemetry().clone();
15450 let is_via_ssh = project.is_via_ssh();
15451 (telemetry, is_via_ssh)
15452 };
15453 refresh_linked_ranges(self, window, cx);
15454 telemetry.log_edit_event("editor", is_via_ssh);
15455 }
15456 multi_buffer::Event::ExcerptsAdded {
15457 buffer,
15458 predecessor,
15459 excerpts,
15460 } => {
15461 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15462 let buffer_id = buffer.read(cx).remote_id();
15463 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
15464 if let Some(project) = &self.project {
15465 get_uncommitted_diff_for_buffer(
15466 project,
15467 [buffer.clone()],
15468 self.buffer.clone(),
15469 cx,
15470 )
15471 .detach();
15472 }
15473 }
15474 cx.emit(EditorEvent::ExcerptsAdded {
15475 buffer: buffer.clone(),
15476 predecessor: *predecessor,
15477 excerpts: excerpts.clone(),
15478 });
15479 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15480 }
15481 multi_buffer::Event::ExcerptsRemoved { ids } => {
15482 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
15483 let buffer = self.buffer.read(cx);
15484 self.registered_buffers
15485 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
15486 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15487 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
15488 }
15489 multi_buffer::Event::ExcerptsEdited {
15490 excerpt_ids,
15491 buffer_ids,
15492 } => {
15493 self.display_map.update(cx, |map, cx| {
15494 map.unfold_buffers(buffer_ids.iter().copied(), cx)
15495 });
15496 cx.emit(EditorEvent::ExcerptsEdited {
15497 ids: excerpt_ids.clone(),
15498 })
15499 }
15500 multi_buffer::Event::ExcerptsExpanded { ids } => {
15501 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
15502 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
15503 }
15504 multi_buffer::Event::Reparsed(buffer_id) => {
15505 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15506 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15507
15508 cx.emit(EditorEvent::Reparsed(*buffer_id));
15509 }
15510 multi_buffer::Event::DiffHunksToggled => {
15511 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15512 }
15513 multi_buffer::Event::LanguageChanged(buffer_id) => {
15514 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
15515 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
15516 cx.emit(EditorEvent::Reparsed(*buffer_id));
15517 cx.notify();
15518 }
15519 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
15520 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
15521 multi_buffer::Event::FileHandleChanged
15522 | multi_buffer::Event::Reloaded
15523 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
15524 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
15525 multi_buffer::Event::DiagnosticsUpdated => {
15526 self.refresh_active_diagnostics(cx);
15527 self.refresh_inline_diagnostics(true, window, cx);
15528 self.scrollbar_marker_state.dirty = true;
15529 cx.notify();
15530 }
15531 _ => {}
15532 };
15533 }
15534
15535 fn on_display_map_changed(
15536 &mut self,
15537 _: Entity<DisplayMap>,
15538 _: &mut Window,
15539 cx: &mut Context<Self>,
15540 ) {
15541 cx.notify();
15542 }
15543
15544 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15545 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
15546 self.update_edit_prediction_settings(cx);
15547 self.refresh_inline_completion(true, false, window, cx);
15548 self.refresh_inlay_hints(
15549 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
15550 self.selections.newest_anchor().head(),
15551 &self.buffer.read(cx).snapshot(cx),
15552 cx,
15553 )),
15554 cx,
15555 );
15556
15557 let old_cursor_shape = self.cursor_shape;
15558
15559 {
15560 let editor_settings = EditorSettings::get_global(cx);
15561 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
15562 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
15563 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
15564 }
15565
15566 if old_cursor_shape != self.cursor_shape {
15567 cx.emit(EditorEvent::CursorShapeChanged);
15568 }
15569
15570 let project_settings = ProjectSettings::get_global(cx);
15571 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
15572
15573 if self.mode == EditorMode::Full {
15574 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
15575 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
15576 if self.show_inline_diagnostics != show_inline_diagnostics {
15577 self.show_inline_diagnostics = show_inline_diagnostics;
15578 self.refresh_inline_diagnostics(false, window, cx);
15579 }
15580
15581 if self.git_blame_inline_enabled != inline_blame_enabled {
15582 self.toggle_git_blame_inline_internal(false, window, cx);
15583 }
15584 }
15585
15586 cx.notify();
15587 }
15588
15589 pub fn set_searchable(&mut self, searchable: bool) {
15590 self.searchable = searchable;
15591 }
15592
15593 pub fn searchable(&self) -> bool {
15594 self.searchable
15595 }
15596
15597 fn open_proposed_changes_editor(
15598 &mut self,
15599 _: &OpenProposedChangesEditor,
15600 window: &mut Window,
15601 cx: &mut Context<Self>,
15602 ) {
15603 let Some(workspace) = self.workspace() else {
15604 cx.propagate();
15605 return;
15606 };
15607
15608 let selections = self.selections.all::<usize>(cx);
15609 let multi_buffer = self.buffer.read(cx);
15610 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15611 let mut new_selections_by_buffer = HashMap::default();
15612 for selection in selections {
15613 for (buffer, range, _) in
15614 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
15615 {
15616 let mut range = range.to_point(buffer);
15617 range.start.column = 0;
15618 range.end.column = buffer.line_len(range.end.row);
15619 new_selections_by_buffer
15620 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
15621 .or_insert(Vec::new())
15622 .push(range)
15623 }
15624 }
15625
15626 let proposed_changes_buffers = new_selections_by_buffer
15627 .into_iter()
15628 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
15629 .collect::<Vec<_>>();
15630 let proposed_changes_editor = cx.new(|cx| {
15631 ProposedChangesEditor::new(
15632 "Proposed changes",
15633 proposed_changes_buffers,
15634 self.project.clone(),
15635 window,
15636 cx,
15637 )
15638 });
15639
15640 window.defer(cx, move |window, cx| {
15641 workspace.update(cx, |workspace, cx| {
15642 workspace.active_pane().update(cx, |pane, cx| {
15643 pane.add_item(
15644 Box::new(proposed_changes_editor),
15645 true,
15646 true,
15647 None,
15648 window,
15649 cx,
15650 );
15651 });
15652 });
15653 });
15654 }
15655
15656 pub fn open_excerpts_in_split(
15657 &mut self,
15658 _: &OpenExcerptsSplit,
15659 window: &mut Window,
15660 cx: &mut Context<Self>,
15661 ) {
15662 self.open_excerpts_common(None, true, window, cx)
15663 }
15664
15665 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
15666 self.open_excerpts_common(None, false, window, cx)
15667 }
15668
15669 fn open_excerpts_common(
15670 &mut self,
15671 jump_data: Option<JumpData>,
15672 split: bool,
15673 window: &mut Window,
15674 cx: &mut Context<Self>,
15675 ) {
15676 let Some(workspace) = self.workspace() else {
15677 cx.propagate();
15678 return;
15679 };
15680
15681 if self.buffer.read(cx).is_singleton() {
15682 cx.propagate();
15683 return;
15684 }
15685
15686 let mut new_selections_by_buffer = HashMap::default();
15687 match &jump_data {
15688 Some(JumpData::MultiBufferPoint {
15689 excerpt_id,
15690 position,
15691 anchor,
15692 line_offset_from_top,
15693 }) => {
15694 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15695 if let Some(buffer) = multi_buffer_snapshot
15696 .buffer_id_for_excerpt(*excerpt_id)
15697 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
15698 {
15699 let buffer_snapshot = buffer.read(cx).snapshot();
15700 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
15701 language::ToPoint::to_point(anchor, &buffer_snapshot)
15702 } else {
15703 buffer_snapshot.clip_point(*position, Bias::Left)
15704 };
15705 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
15706 new_selections_by_buffer.insert(
15707 buffer,
15708 (
15709 vec![jump_to_offset..jump_to_offset],
15710 Some(*line_offset_from_top),
15711 ),
15712 );
15713 }
15714 }
15715 Some(JumpData::MultiBufferRow {
15716 row,
15717 line_offset_from_top,
15718 }) => {
15719 let point = MultiBufferPoint::new(row.0, 0);
15720 if let Some((buffer, buffer_point, _)) =
15721 self.buffer.read(cx).point_to_buffer_point(point, cx)
15722 {
15723 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
15724 new_selections_by_buffer
15725 .entry(buffer)
15726 .or_insert((Vec::new(), Some(*line_offset_from_top)))
15727 .0
15728 .push(buffer_offset..buffer_offset)
15729 }
15730 }
15731 None => {
15732 let selections = self.selections.all::<usize>(cx);
15733 let multi_buffer = self.buffer.read(cx);
15734 for selection in selections {
15735 for (snapshot, range, _, anchor) in multi_buffer
15736 .snapshot(cx)
15737 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
15738 {
15739 if let Some(anchor) = anchor {
15740 // selection is in a deleted hunk
15741 let Some(buffer_id) = anchor.buffer_id else {
15742 continue;
15743 };
15744 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
15745 continue;
15746 };
15747 let offset = text::ToOffset::to_offset(
15748 &anchor.text_anchor,
15749 &buffer_handle.read(cx).snapshot(),
15750 );
15751 let range = offset..offset;
15752 new_selections_by_buffer
15753 .entry(buffer_handle)
15754 .or_insert((Vec::new(), None))
15755 .0
15756 .push(range)
15757 } else {
15758 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
15759 else {
15760 continue;
15761 };
15762 new_selections_by_buffer
15763 .entry(buffer_handle)
15764 .or_insert((Vec::new(), None))
15765 .0
15766 .push(range)
15767 }
15768 }
15769 }
15770 }
15771 }
15772
15773 if new_selections_by_buffer.is_empty() {
15774 return;
15775 }
15776
15777 // We defer the pane interaction because we ourselves are a workspace item
15778 // and activating a new item causes the pane to call a method on us reentrantly,
15779 // which panics if we're on the stack.
15780 window.defer(cx, move |window, cx| {
15781 workspace.update(cx, |workspace, cx| {
15782 let pane = if split {
15783 workspace.adjacent_pane(window, cx)
15784 } else {
15785 workspace.active_pane().clone()
15786 };
15787
15788 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
15789 let editor = buffer
15790 .read(cx)
15791 .file()
15792 .is_none()
15793 .then(|| {
15794 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
15795 // so `workspace.open_project_item` will never find them, always opening a new editor.
15796 // Instead, we try to activate the existing editor in the pane first.
15797 let (editor, pane_item_index) =
15798 pane.read(cx).items().enumerate().find_map(|(i, item)| {
15799 let editor = item.downcast::<Editor>()?;
15800 let singleton_buffer =
15801 editor.read(cx).buffer().read(cx).as_singleton()?;
15802 if singleton_buffer == buffer {
15803 Some((editor, i))
15804 } else {
15805 None
15806 }
15807 })?;
15808 pane.update(cx, |pane, cx| {
15809 pane.activate_item(pane_item_index, true, true, window, cx)
15810 });
15811 Some(editor)
15812 })
15813 .flatten()
15814 .unwrap_or_else(|| {
15815 workspace.open_project_item::<Self>(
15816 pane.clone(),
15817 buffer,
15818 true,
15819 true,
15820 window,
15821 cx,
15822 )
15823 });
15824
15825 editor.update(cx, |editor, cx| {
15826 let autoscroll = match scroll_offset {
15827 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
15828 None => Autoscroll::newest(),
15829 };
15830 let nav_history = editor.nav_history.take();
15831 editor.change_selections(Some(autoscroll), window, cx, |s| {
15832 s.select_ranges(ranges);
15833 });
15834 editor.nav_history = nav_history;
15835 });
15836 }
15837 })
15838 });
15839 }
15840
15841 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
15842 let snapshot = self.buffer.read(cx).read(cx);
15843 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
15844 Some(
15845 ranges
15846 .iter()
15847 .map(move |range| {
15848 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
15849 })
15850 .collect(),
15851 )
15852 }
15853
15854 fn selection_replacement_ranges(
15855 &self,
15856 range: Range<OffsetUtf16>,
15857 cx: &mut App,
15858 ) -> Vec<Range<OffsetUtf16>> {
15859 let selections = self.selections.all::<OffsetUtf16>(cx);
15860 let newest_selection = selections
15861 .iter()
15862 .max_by_key(|selection| selection.id)
15863 .unwrap();
15864 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
15865 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
15866 let snapshot = self.buffer.read(cx).read(cx);
15867 selections
15868 .into_iter()
15869 .map(|mut selection| {
15870 selection.start.0 =
15871 (selection.start.0 as isize).saturating_add(start_delta) as usize;
15872 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
15873 snapshot.clip_offset_utf16(selection.start, Bias::Left)
15874 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
15875 })
15876 .collect()
15877 }
15878
15879 fn report_editor_event(
15880 &self,
15881 event_type: &'static str,
15882 file_extension: Option<String>,
15883 cx: &App,
15884 ) {
15885 if cfg!(any(test, feature = "test-support")) {
15886 return;
15887 }
15888
15889 let Some(project) = &self.project else { return };
15890
15891 // If None, we are in a file without an extension
15892 let file = self
15893 .buffer
15894 .read(cx)
15895 .as_singleton()
15896 .and_then(|b| b.read(cx).file());
15897 let file_extension = file_extension.or(file
15898 .as_ref()
15899 .and_then(|file| Path::new(file.file_name(cx)).extension())
15900 .and_then(|e| e.to_str())
15901 .map(|a| a.to_string()));
15902
15903 let vim_mode = cx
15904 .global::<SettingsStore>()
15905 .raw_user_settings()
15906 .get("vim_mode")
15907 == Some(&serde_json::Value::Bool(true));
15908
15909 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
15910 let copilot_enabled = edit_predictions_provider
15911 == language::language_settings::EditPredictionProvider::Copilot;
15912 let copilot_enabled_for_language = self
15913 .buffer
15914 .read(cx)
15915 .language_settings(cx)
15916 .show_edit_predictions;
15917
15918 let project = project.read(cx);
15919 telemetry::event!(
15920 event_type,
15921 file_extension,
15922 vim_mode,
15923 copilot_enabled,
15924 copilot_enabled_for_language,
15925 edit_predictions_provider,
15926 is_via_ssh = project.is_via_ssh(),
15927 );
15928 }
15929
15930 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
15931 /// with each line being an array of {text, highlight} objects.
15932 fn copy_highlight_json(
15933 &mut self,
15934 _: &CopyHighlightJson,
15935 window: &mut Window,
15936 cx: &mut Context<Self>,
15937 ) {
15938 #[derive(Serialize)]
15939 struct Chunk<'a> {
15940 text: String,
15941 highlight: Option<&'a str>,
15942 }
15943
15944 let snapshot = self.buffer.read(cx).snapshot(cx);
15945 let range = self
15946 .selected_text_range(false, window, cx)
15947 .and_then(|selection| {
15948 if selection.range.is_empty() {
15949 None
15950 } else {
15951 Some(selection.range)
15952 }
15953 })
15954 .unwrap_or_else(|| 0..snapshot.len());
15955
15956 let chunks = snapshot.chunks(range, true);
15957 let mut lines = Vec::new();
15958 let mut line: VecDeque<Chunk> = VecDeque::new();
15959
15960 let Some(style) = self.style.as_ref() else {
15961 return;
15962 };
15963
15964 for chunk in chunks {
15965 let highlight = chunk
15966 .syntax_highlight_id
15967 .and_then(|id| id.name(&style.syntax));
15968 let mut chunk_lines = chunk.text.split('\n').peekable();
15969 while let Some(text) = chunk_lines.next() {
15970 let mut merged_with_last_token = false;
15971 if let Some(last_token) = line.back_mut() {
15972 if last_token.highlight == highlight {
15973 last_token.text.push_str(text);
15974 merged_with_last_token = true;
15975 }
15976 }
15977
15978 if !merged_with_last_token {
15979 line.push_back(Chunk {
15980 text: text.into(),
15981 highlight,
15982 });
15983 }
15984
15985 if chunk_lines.peek().is_some() {
15986 if line.len() > 1 && line.front().unwrap().text.is_empty() {
15987 line.pop_front();
15988 }
15989 if line.len() > 1 && line.back().unwrap().text.is_empty() {
15990 line.pop_back();
15991 }
15992
15993 lines.push(mem::take(&mut line));
15994 }
15995 }
15996 }
15997
15998 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
15999 return;
16000 };
16001 cx.write_to_clipboard(ClipboardItem::new_string(lines));
16002 }
16003
16004 pub fn open_context_menu(
16005 &mut self,
16006 _: &OpenContextMenu,
16007 window: &mut Window,
16008 cx: &mut Context<Self>,
16009 ) {
16010 self.request_autoscroll(Autoscroll::newest(), cx);
16011 let position = self.selections.newest_display(cx).start;
16012 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16013 }
16014
16015 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16016 &self.inlay_hint_cache
16017 }
16018
16019 pub fn replay_insert_event(
16020 &mut self,
16021 text: &str,
16022 relative_utf16_range: Option<Range<isize>>,
16023 window: &mut Window,
16024 cx: &mut Context<Self>,
16025 ) {
16026 if !self.input_enabled {
16027 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16028 return;
16029 }
16030 if let Some(relative_utf16_range) = relative_utf16_range {
16031 let selections = self.selections.all::<OffsetUtf16>(cx);
16032 self.change_selections(None, window, cx, |s| {
16033 let new_ranges = selections.into_iter().map(|range| {
16034 let start = OffsetUtf16(
16035 range
16036 .head()
16037 .0
16038 .saturating_add_signed(relative_utf16_range.start),
16039 );
16040 let end = OffsetUtf16(
16041 range
16042 .head()
16043 .0
16044 .saturating_add_signed(relative_utf16_range.end),
16045 );
16046 start..end
16047 });
16048 s.select_ranges(new_ranges);
16049 });
16050 }
16051
16052 self.handle_input(text, window, cx);
16053 }
16054
16055 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16056 let Some(provider) = self.semantics_provider.as_ref() else {
16057 return false;
16058 };
16059
16060 let mut supports = false;
16061 self.buffer().update(cx, |this, cx| {
16062 this.for_each_buffer(|buffer| {
16063 supports |= provider.supports_inlay_hints(buffer, cx);
16064 });
16065 });
16066
16067 supports
16068 }
16069
16070 pub fn is_focused(&self, window: &Window) -> bool {
16071 self.focus_handle.is_focused(window)
16072 }
16073
16074 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16075 cx.emit(EditorEvent::Focused);
16076
16077 if let Some(descendant) = self
16078 .last_focused_descendant
16079 .take()
16080 .and_then(|descendant| descendant.upgrade())
16081 {
16082 window.focus(&descendant);
16083 } else {
16084 if let Some(blame) = self.blame.as_ref() {
16085 blame.update(cx, GitBlame::focus)
16086 }
16087
16088 self.blink_manager.update(cx, BlinkManager::enable);
16089 self.show_cursor_names(window, cx);
16090 self.buffer.update(cx, |buffer, cx| {
16091 buffer.finalize_last_transaction(cx);
16092 if self.leader_peer_id.is_none() {
16093 buffer.set_active_selections(
16094 &self.selections.disjoint_anchors(),
16095 self.selections.line_mode,
16096 self.cursor_shape,
16097 cx,
16098 );
16099 }
16100 });
16101 }
16102 }
16103
16104 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16105 cx.emit(EditorEvent::FocusedIn)
16106 }
16107
16108 fn handle_focus_out(
16109 &mut self,
16110 event: FocusOutEvent,
16111 _window: &mut Window,
16112 cx: &mut Context<Self>,
16113 ) {
16114 if event.blurred != self.focus_handle {
16115 self.last_focused_descendant = Some(event.blurred);
16116 }
16117 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16118 }
16119
16120 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16121 self.blink_manager.update(cx, BlinkManager::disable);
16122 self.buffer
16123 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16124
16125 if let Some(blame) = self.blame.as_ref() {
16126 blame.update(cx, GitBlame::blur)
16127 }
16128 if !self.hover_state.focused(window, cx) {
16129 hide_hover(self, cx);
16130 }
16131 if !self
16132 .context_menu
16133 .borrow()
16134 .as_ref()
16135 .is_some_and(|context_menu| context_menu.focused(window, cx))
16136 {
16137 self.hide_context_menu(window, cx);
16138 }
16139 self.discard_inline_completion(false, cx);
16140 cx.emit(EditorEvent::Blurred);
16141 cx.notify();
16142 }
16143
16144 pub fn register_action<A: Action>(
16145 &mut self,
16146 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16147 ) -> Subscription {
16148 let id = self.next_editor_action_id.post_inc();
16149 let listener = Arc::new(listener);
16150 self.editor_actions.borrow_mut().insert(
16151 id,
16152 Box::new(move |window, _| {
16153 let listener = listener.clone();
16154 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16155 let action = action.downcast_ref().unwrap();
16156 if phase == DispatchPhase::Bubble {
16157 listener(action, window, cx)
16158 }
16159 })
16160 }),
16161 );
16162
16163 let editor_actions = self.editor_actions.clone();
16164 Subscription::new(move || {
16165 editor_actions.borrow_mut().remove(&id);
16166 })
16167 }
16168
16169 pub fn file_header_size(&self) -> u32 {
16170 FILE_HEADER_HEIGHT
16171 }
16172
16173 pub fn restore(
16174 &mut self,
16175 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16176 window: &mut Window,
16177 cx: &mut Context<Self>,
16178 ) {
16179 let workspace = self.workspace();
16180 let project = self.project.as_ref();
16181 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16182 let mut tasks = Vec::new();
16183 for (buffer_id, changes) in revert_changes {
16184 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16185 buffer.update(cx, |buffer, cx| {
16186 buffer.edit(
16187 changes
16188 .into_iter()
16189 .map(|(range, text)| (range, text.to_string())),
16190 None,
16191 cx,
16192 );
16193 });
16194
16195 if let Some(project) =
16196 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16197 {
16198 project.update(cx, |project, cx| {
16199 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16200 })
16201 }
16202 }
16203 }
16204 tasks
16205 });
16206 cx.spawn_in(window, |_, mut cx| async move {
16207 for (buffer, task) in save_tasks {
16208 let result = task.await;
16209 if result.is_err() {
16210 let Some(path) = buffer
16211 .read_with(&cx, |buffer, cx| buffer.project_path(cx))
16212 .ok()
16213 else {
16214 continue;
16215 };
16216 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
16217 let Some(task) = cx
16218 .update_window_entity(&workspace, |workspace, window, cx| {
16219 workspace
16220 .open_path_preview(path, None, false, false, false, window, cx)
16221 })
16222 .ok()
16223 else {
16224 continue;
16225 };
16226 task.await.log_err();
16227 }
16228 }
16229 }
16230 })
16231 .detach();
16232 self.change_selections(None, window, cx, |selections| selections.refresh());
16233 }
16234
16235 pub fn to_pixel_point(
16236 &self,
16237 source: multi_buffer::Anchor,
16238 editor_snapshot: &EditorSnapshot,
16239 window: &mut Window,
16240 ) -> Option<gpui::Point<Pixels>> {
16241 let source_point = source.to_display_point(editor_snapshot);
16242 self.display_to_pixel_point(source_point, editor_snapshot, window)
16243 }
16244
16245 pub fn display_to_pixel_point(
16246 &self,
16247 source: DisplayPoint,
16248 editor_snapshot: &EditorSnapshot,
16249 window: &mut Window,
16250 ) -> Option<gpui::Point<Pixels>> {
16251 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
16252 let text_layout_details = self.text_layout_details(window);
16253 let scroll_top = text_layout_details
16254 .scroll_anchor
16255 .scroll_position(editor_snapshot)
16256 .y;
16257
16258 if source.row().as_f32() < scroll_top.floor() {
16259 return None;
16260 }
16261 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
16262 let source_y = line_height * (source.row().as_f32() - scroll_top);
16263 Some(gpui::Point::new(source_x, source_y))
16264 }
16265
16266 pub fn has_visible_completions_menu(&self) -> bool {
16267 !self.edit_prediction_preview_is_active()
16268 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
16269 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
16270 })
16271 }
16272
16273 pub fn register_addon<T: Addon>(&mut self, instance: T) {
16274 self.addons
16275 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
16276 }
16277
16278 pub fn unregister_addon<T: Addon>(&mut self) {
16279 self.addons.remove(&std::any::TypeId::of::<T>());
16280 }
16281
16282 pub fn addon<T: Addon>(&self) -> Option<&T> {
16283 let type_id = std::any::TypeId::of::<T>();
16284 self.addons
16285 .get(&type_id)
16286 .and_then(|item| item.to_any().downcast_ref::<T>())
16287 }
16288
16289 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
16290 let text_layout_details = self.text_layout_details(window);
16291 let style = &text_layout_details.editor_style;
16292 let font_id = window.text_system().resolve_font(&style.text.font());
16293 let font_size = style.text.font_size.to_pixels(window.rem_size());
16294 let line_height = style.text.line_height_in_pixels(window.rem_size());
16295 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
16296
16297 gpui::Size::new(em_width, line_height)
16298 }
16299
16300 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
16301 self.load_diff_task.clone()
16302 }
16303
16304 fn read_selections_from_db(
16305 &mut self,
16306 item_id: u64,
16307 workspace_id: WorkspaceId,
16308 window: &mut Window,
16309 cx: &mut Context<Editor>,
16310 ) {
16311 if !self.is_singleton(cx)
16312 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
16313 {
16314 return;
16315 }
16316 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
16317 return;
16318 };
16319 if selections.is_empty() {
16320 return;
16321 }
16322
16323 let snapshot = self.buffer.read(cx).snapshot(cx);
16324 self.change_selections(None, window, cx, |s| {
16325 s.select_ranges(selections.into_iter().map(|(start, end)| {
16326 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
16327 }));
16328 });
16329 }
16330}
16331
16332fn insert_extra_newline_brackets(
16333 buffer: &MultiBufferSnapshot,
16334 range: Range<usize>,
16335 language: &language::LanguageScope,
16336) -> bool {
16337 let leading_whitespace_len = buffer
16338 .reversed_chars_at(range.start)
16339 .take_while(|c| c.is_whitespace() && *c != '\n')
16340 .map(|c| c.len_utf8())
16341 .sum::<usize>();
16342 let trailing_whitespace_len = buffer
16343 .chars_at(range.end)
16344 .take_while(|c| c.is_whitespace() && *c != '\n')
16345 .map(|c| c.len_utf8())
16346 .sum::<usize>();
16347 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
16348
16349 language.brackets().any(|(pair, enabled)| {
16350 let pair_start = pair.start.trim_end();
16351 let pair_end = pair.end.trim_start();
16352
16353 enabled
16354 && pair.newline
16355 && buffer.contains_str_at(range.end, pair_end)
16356 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
16357 })
16358}
16359
16360fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
16361 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
16362 [(buffer, range, _)] => (*buffer, range.clone()),
16363 _ => return false,
16364 };
16365 let pair = {
16366 let mut result: Option<BracketMatch> = None;
16367
16368 for pair in buffer
16369 .all_bracket_ranges(range.clone())
16370 .filter(move |pair| {
16371 pair.open_range.start <= range.start && pair.close_range.end >= range.end
16372 })
16373 {
16374 let len = pair.close_range.end - pair.open_range.start;
16375
16376 if let Some(existing) = &result {
16377 let existing_len = existing.close_range.end - existing.open_range.start;
16378 if len > existing_len {
16379 continue;
16380 }
16381 }
16382
16383 result = Some(pair);
16384 }
16385
16386 result
16387 };
16388 let Some(pair) = pair else {
16389 return false;
16390 };
16391 pair.newline_only
16392 && buffer
16393 .chars_for_range(pair.open_range.end..range.start)
16394 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
16395 .all(|c| c.is_whitespace() && c != '\n')
16396}
16397
16398fn get_uncommitted_diff_for_buffer(
16399 project: &Entity<Project>,
16400 buffers: impl IntoIterator<Item = Entity<Buffer>>,
16401 buffer: Entity<MultiBuffer>,
16402 cx: &mut App,
16403) -> Task<()> {
16404 let mut tasks = Vec::new();
16405 project.update(cx, |project, cx| {
16406 for buffer in buffers {
16407 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
16408 }
16409 });
16410 cx.spawn(|mut cx| async move {
16411 let diffs = future::join_all(tasks).await;
16412 buffer
16413 .update(&mut cx, |buffer, cx| {
16414 for diff in diffs.into_iter().flatten() {
16415 buffer.add_diff(diff, cx);
16416 }
16417 })
16418 .ok();
16419 })
16420}
16421
16422fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
16423 let tab_size = tab_size.get() as usize;
16424 let mut width = offset;
16425
16426 for ch in text.chars() {
16427 width += if ch == '\t' {
16428 tab_size - (width % tab_size)
16429 } else {
16430 1
16431 };
16432 }
16433
16434 width - offset
16435}
16436
16437#[cfg(test)]
16438mod tests {
16439 use super::*;
16440
16441 #[test]
16442 fn test_string_size_with_expanded_tabs() {
16443 let nz = |val| NonZeroU32::new(val).unwrap();
16444 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
16445 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
16446 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
16447 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
16448 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
16449 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
16450 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
16451 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
16452 }
16453}
16454
16455/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
16456struct WordBreakingTokenizer<'a> {
16457 input: &'a str,
16458}
16459
16460impl<'a> WordBreakingTokenizer<'a> {
16461 fn new(input: &'a str) -> Self {
16462 Self { input }
16463 }
16464}
16465
16466fn is_char_ideographic(ch: char) -> bool {
16467 use unicode_script::Script::*;
16468 use unicode_script::UnicodeScript;
16469 matches!(ch.script(), Han | Tangut | Yi)
16470}
16471
16472fn is_grapheme_ideographic(text: &str) -> bool {
16473 text.chars().any(is_char_ideographic)
16474}
16475
16476fn is_grapheme_whitespace(text: &str) -> bool {
16477 text.chars().any(|x| x.is_whitespace())
16478}
16479
16480fn should_stay_with_preceding_ideograph(text: &str) -> bool {
16481 text.chars().next().map_or(false, |ch| {
16482 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
16483 })
16484}
16485
16486#[derive(PartialEq, Eq, Debug, Clone, Copy)]
16487struct WordBreakToken<'a> {
16488 token: &'a str,
16489 grapheme_len: usize,
16490 is_whitespace: bool,
16491}
16492
16493impl<'a> Iterator for WordBreakingTokenizer<'a> {
16494 /// Yields a span, the count of graphemes in the token, and whether it was
16495 /// whitespace. Note that it also breaks at word boundaries.
16496 type Item = WordBreakToken<'a>;
16497
16498 fn next(&mut self) -> Option<Self::Item> {
16499 use unicode_segmentation::UnicodeSegmentation;
16500 if self.input.is_empty() {
16501 return None;
16502 }
16503
16504 let mut iter = self.input.graphemes(true).peekable();
16505 let mut offset = 0;
16506 let mut graphemes = 0;
16507 if let Some(first_grapheme) = iter.next() {
16508 let is_whitespace = is_grapheme_whitespace(first_grapheme);
16509 offset += first_grapheme.len();
16510 graphemes += 1;
16511 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
16512 if let Some(grapheme) = iter.peek().copied() {
16513 if should_stay_with_preceding_ideograph(grapheme) {
16514 offset += grapheme.len();
16515 graphemes += 1;
16516 }
16517 }
16518 } else {
16519 let mut words = self.input[offset..].split_word_bound_indices().peekable();
16520 let mut next_word_bound = words.peek().copied();
16521 if next_word_bound.map_or(false, |(i, _)| i == 0) {
16522 next_word_bound = words.next();
16523 }
16524 while let Some(grapheme) = iter.peek().copied() {
16525 if next_word_bound.map_or(false, |(i, _)| i == offset) {
16526 break;
16527 };
16528 if is_grapheme_whitespace(grapheme) != is_whitespace {
16529 break;
16530 };
16531 offset += grapheme.len();
16532 graphemes += 1;
16533 iter.next();
16534 }
16535 }
16536 let token = &self.input[..offset];
16537 self.input = &self.input[offset..];
16538 if is_whitespace {
16539 Some(WordBreakToken {
16540 token: " ",
16541 grapheme_len: 1,
16542 is_whitespace: true,
16543 })
16544 } else {
16545 Some(WordBreakToken {
16546 token,
16547 grapheme_len: graphemes,
16548 is_whitespace: false,
16549 })
16550 }
16551 } else {
16552 None
16553 }
16554 }
16555}
16556
16557#[test]
16558fn test_word_breaking_tokenizer() {
16559 let tests: &[(&str, &[(&str, usize, bool)])] = &[
16560 ("", &[]),
16561 (" ", &[(" ", 1, true)]),
16562 ("Ʒ", &[("Ʒ", 1, false)]),
16563 ("Ǽ", &[("Ǽ", 1, false)]),
16564 ("⋑", &[("⋑", 1, false)]),
16565 ("⋑⋑", &[("⋑⋑", 2, false)]),
16566 (
16567 "原理,进而",
16568 &[
16569 ("原", 1, false),
16570 ("理,", 2, false),
16571 ("进", 1, false),
16572 ("而", 1, false),
16573 ],
16574 ),
16575 (
16576 "hello world",
16577 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
16578 ),
16579 (
16580 "hello, world",
16581 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
16582 ),
16583 (
16584 " hello world",
16585 &[
16586 (" ", 1, true),
16587 ("hello", 5, false),
16588 (" ", 1, true),
16589 ("world", 5, false),
16590 ],
16591 ),
16592 (
16593 "这是什么 \n 钢笔",
16594 &[
16595 ("这", 1, false),
16596 ("是", 1, false),
16597 ("什", 1, false),
16598 ("么", 1, false),
16599 (" ", 1, true),
16600 ("钢", 1, false),
16601 ("笔", 1, false),
16602 ],
16603 ),
16604 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
16605 ];
16606
16607 for (input, result) in tests {
16608 assert_eq!(
16609 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
16610 result
16611 .iter()
16612 .copied()
16613 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
16614 token,
16615 grapheme_len,
16616 is_whitespace,
16617 })
16618 .collect::<Vec<_>>()
16619 );
16620 }
16621}
16622
16623fn wrap_with_prefix(
16624 line_prefix: String,
16625 unwrapped_text: String,
16626 wrap_column: usize,
16627 tab_size: NonZeroU32,
16628) -> String {
16629 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
16630 let mut wrapped_text = String::new();
16631 let mut current_line = line_prefix.clone();
16632
16633 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
16634 let mut current_line_len = line_prefix_len;
16635 for WordBreakToken {
16636 token,
16637 grapheme_len,
16638 is_whitespace,
16639 } in tokenizer
16640 {
16641 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
16642 wrapped_text.push_str(current_line.trim_end());
16643 wrapped_text.push('\n');
16644 current_line.truncate(line_prefix.len());
16645 current_line_len = line_prefix_len;
16646 if !is_whitespace {
16647 current_line.push_str(token);
16648 current_line_len += grapheme_len;
16649 }
16650 } else if !is_whitespace {
16651 current_line.push_str(token);
16652 current_line_len += grapheme_len;
16653 } else if current_line_len != line_prefix_len {
16654 current_line.push(' ');
16655 current_line_len += 1;
16656 }
16657 }
16658
16659 if !current_line.is_empty() {
16660 wrapped_text.push_str(¤t_line);
16661 }
16662 wrapped_text
16663}
16664
16665#[test]
16666fn test_wrap_with_prefix() {
16667 assert_eq!(
16668 wrap_with_prefix(
16669 "# ".to_string(),
16670 "abcdefg".to_string(),
16671 4,
16672 NonZeroU32::new(4).unwrap()
16673 ),
16674 "# abcdefg"
16675 );
16676 assert_eq!(
16677 wrap_with_prefix(
16678 "".to_string(),
16679 "\thello world".to_string(),
16680 8,
16681 NonZeroU32::new(4).unwrap()
16682 ),
16683 "hello\nworld"
16684 );
16685 assert_eq!(
16686 wrap_with_prefix(
16687 "// ".to_string(),
16688 "xx \nyy zz aa bb cc".to_string(),
16689 12,
16690 NonZeroU32::new(4).unwrap()
16691 ),
16692 "// xx yy zz\n// aa bb cc"
16693 );
16694 assert_eq!(
16695 wrap_with_prefix(
16696 String::new(),
16697 "这是什么 \n 钢笔".to_string(),
16698 3,
16699 NonZeroU32::new(4).unwrap()
16700 ),
16701 "这是什\n么 钢\n笔"
16702 );
16703}
16704
16705pub trait CollaborationHub {
16706 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
16707 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
16708 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
16709}
16710
16711impl CollaborationHub for Entity<Project> {
16712 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
16713 self.read(cx).collaborators()
16714 }
16715
16716 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
16717 self.read(cx).user_store().read(cx).participant_indices()
16718 }
16719
16720 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
16721 let this = self.read(cx);
16722 let user_ids = this.collaborators().values().map(|c| c.user_id);
16723 this.user_store().read_with(cx, |user_store, cx| {
16724 user_store.participant_names(user_ids, cx)
16725 })
16726 }
16727}
16728
16729pub trait SemanticsProvider {
16730 fn hover(
16731 &self,
16732 buffer: &Entity<Buffer>,
16733 position: text::Anchor,
16734 cx: &mut App,
16735 ) -> Option<Task<Vec<project::Hover>>>;
16736
16737 fn inlay_hints(
16738 &self,
16739 buffer_handle: Entity<Buffer>,
16740 range: Range<text::Anchor>,
16741 cx: &mut App,
16742 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
16743
16744 fn resolve_inlay_hint(
16745 &self,
16746 hint: InlayHint,
16747 buffer_handle: Entity<Buffer>,
16748 server_id: LanguageServerId,
16749 cx: &mut App,
16750 ) -> Option<Task<anyhow::Result<InlayHint>>>;
16751
16752 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
16753
16754 fn document_highlights(
16755 &self,
16756 buffer: &Entity<Buffer>,
16757 position: text::Anchor,
16758 cx: &mut App,
16759 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
16760
16761 fn definitions(
16762 &self,
16763 buffer: &Entity<Buffer>,
16764 position: text::Anchor,
16765 kind: GotoDefinitionKind,
16766 cx: &mut App,
16767 ) -> Option<Task<Result<Vec<LocationLink>>>>;
16768
16769 fn range_for_rename(
16770 &self,
16771 buffer: &Entity<Buffer>,
16772 position: text::Anchor,
16773 cx: &mut App,
16774 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
16775
16776 fn perform_rename(
16777 &self,
16778 buffer: &Entity<Buffer>,
16779 position: text::Anchor,
16780 new_name: String,
16781 cx: &mut App,
16782 ) -> Option<Task<Result<ProjectTransaction>>>;
16783}
16784
16785pub trait CompletionProvider {
16786 fn completions(
16787 &self,
16788 buffer: &Entity<Buffer>,
16789 buffer_position: text::Anchor,
16790 trigger: CompletionContext,
16791 window: &mut Window,
16792 cx: &mut Context<Editor>,
16793 ) -> Task<Result<Vec<Completion>>>;
16794
16795 fn resolve_completions(
16796 &self,
16797 buffer: Entity<Buffer>,
16798 completion_indices: Vec<usize>,
16799 completions: Rc<RefCell<Box<[Completion]>>>,
16800 cx: &mut Context<Editor>,
16801 ) -> Task<Result<bool>>;
16802
16803 fn apply_additional_edits_for_completion(
16804 &self,
16805 _buffer: Entity<Buffer>,
16806 _completions: Rc<RefCell<Box<[Completion]>>>,
16807 _completion_index: usize,
16808 _push_to_history: bool,
16809 _cx: &mut Context<Editor>,
16810 ) -> Task<Result<Option<language::Transaction>>> {
16811 Task::ready(Ok(None))
16812 }
16813
16814 fn is_completion_trigger(
16815 &self,
16816 buffer: &Entity<Buffer>,
16817 position: language::Anchor,
16818 text: &str,
16819 trigger_in_words: bool,
16820 cx: &mut Context<Editor>,
16821 ) -> bool;
16822
16823 fn sort_completions(&self) -> bool {
16824 true
16825 }
16826}
16827
16828pub trait CodeActionProvider {
16829 fn id(&self) -> Arc<str>;
16830
16831 fn code_actions(
16832 &self,
16833 buffer: &Entity<Buffer>,
16834 range: Range<text::Anchor>,
16835 window: &mut Window,
16836 cx: &mut App,
16837 ) -> Task<Result<Vec<CodeAction>>>;
16838
16839 fn apply_code_action(
16840 &self,
16841 buffer_handle: Entity<Buffer>,
16842 action: CodeAction,
16843 excerpt_id: ExcerptId,
16844 push_to_history: bool,
16845 window: &mut Window,
16846 cx: &mut App,
16847 ) -> Task<Result<ProjectTransaction>>;
16848}
16849
16850impl CodeActionProvider for Entity<Project> {
16851 fn id(&self) -> Arc<str> {
16852 "project".into()
16853 }
16854
16855 fn code_actions(
16856 &self,
16857 buffer: &Entity<Buffer>,
16858 range: Range<text::Anchor>,
16859 _window: &mut Window,
16860 cx: &mut App,
16861 ) -> Task<Result<Vec<CodeAction>>> {
16862 self.update(cx, |project, cx| {
16863 project.code_actions(buffer, range, None, cx)
16864 })
16865 }
16866
16867 fn apply_code_action(
16868 &self,
16869 buffer_handle: Entity<Buffer>,
16870 action: CodeAction,
16871 _excerpt_id: ExcerptId,
16872 push_to_history: bool,
16873 _window: &mut Window,
16874 cx: &mut App,
16875 ) -> Task<Result<ProjectTransaction>> {
16876 self.update(cx, |project, cx| {
16877 project.apply_code_action(buffer_handle, action, push_to_history, cx)
16878 })
16879 }
16880}
16881
16882fn snippet_completions(
16883 project: &Project,
16884 buffer: &Entity<Buffer>,
16885 buffer_position: text::Anchor,
16886 cx: &mut App,
16887) -> Task<Result<Vec<Completion>>> {
16888 let language = buffer.read(cx).language_at(buffer_position);
16889 let language_name = language.as_ref().map(|language| language.lsp_id());
16890 let snippet_store = project.snippets().read(cx);
16891 let snippets = snippet_store.snippets_for(language_name, cx);
16892
16893 if snippets.is_empty() {
16894 return Task::ready(Ok(vec![]));
16895 }
16896 let snapshot = buffer.read(cx).text_snapshot();
16897 let chars: String = snapshot
16898 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
16899 .collect();
16900
16901 let scope = language.map(|language| language.default_scope());
16902 let executor = cx.background_executor().clone();
16903
16904 cx.background_spawn(async move {
16905 let classifier = CharClassifier::new(scope).for_completion(true);
16906 let mut last_word = chars
16907 .chars()
16908 .take_while(|c| classifier.is_word(*c))
16909 .collect::<String>();
16910 last_word = last_word.chars().rev().collect();
16911
16912 if last_word.is_empty() {
16913 return Ok(vec![]);
16914 }
16915
16916 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
16917 let to_lsp = |point: &text::Anchor| {
16918 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
16919 point_to_lsp(end)
16920 };
16921 let lsp_end = to_lsp(&buffer_position);
16922
16923 let candidates = snippets
16924 .iter()
16925 .enumerate()
16926 .flat_map(|(ix, snippet)| {
16927 snippet
16928 .prefix
16929 .iter()
16930 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
16931 })
16932 .collect::<Vec<StringMatchCandidate>>();
16933
16934 let mut matches = fuzzy::match_strings(
16935 &candidates,
16936 &last_word,
16937 last_word.chars().any(|c| c.is_uppercase()),
16938 100,
16939 &Default::default(),
16940 executor,
16941 )
16942 .await;
16943
16944 // Remove all candidates where the query's start does not match the start of any word in the candidate
16945 if let Some(query_start) = last_word.chars().next() {
16946 matches.retain(|string_match| {
16947 split_words(&string_match.string).any(|word| {
16948 // Check that the first codepoint of the word as lowercase matches the first
16949 // codepoint of the query as lowercase
16950 word.chars()
16951 .flat_map(|codepoint| codepoint.to_lowercase())
16952 .zip(query_start.to_lowercase())
16953 .all(|(word_cp, query_cp)| word_cp == query_cp)
16954 })
16955 });
16956 }
16957
16958 let matched_strings = matches
16959 .into_iter()
16960 .map(|m| m.string)
16961 .collect::<HashSet<_>>();
16962
16963 let result: Vec<Completion> = snippets
16964 .into_iter()
16965 .filter_map(|snippet| {
16966 let matching_prefix = snippet
16967 .prefix
16968 .iter()
16969 .find(|prefix| matched_strings.contains(*prefix))?;
16970 let start = as_offset - last_word.len();
16971 let start = snapshot.anchor_before(start);
16972 let range = start..buffer_position;
16973 let lsp_start = to_lsp(&start);
16974 let lsp_range = lsp::Range {
16975 start: lsp_start,
16976 end: lsp_end,
16977 };
16978 Some(Completion {
16979 old_range: range,
16980 new_text: snippet.body.clone(),
16981 source: CompletionSource::Lsp {
16982 server_id: LanguageServerId(usize::MAX),
16983 resolved: true,
16984 lsp_completion: Box::new(lsp::CompletionItem {
16985 label: snippet.prefix.first().unwrap().clone(),
16986 kind: Some(CompletionItemKind::SNIPPET),
16987 label_details: snippet.description.as_ref().map(|description| {
16988 lsp::CompletionItemLabelDetails {
16989 detail: Some(description.clone()),
16990 description: None,
16991 }
16992 }),
16993 insert_text_format: Some(InsertTextFormat::SNIPPET),
16994 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
16995 lsp::InsertReplaceEdit {
16996 new_text: snippet.body.clone(),
16997 insert: lsp_range,
16998 replace: lsp_range,
16999 },
17000 )),
17001 filter_text: Some(snippet.body.clone()),
17002 sort_text: Some(char::MAX.to_string()),
17003 ..lsp::CompletionItem::default()
17004 }),
17005 lsp_defaults: None,
17006 },
17007 label: CodeLabel {
17008 text: matching_prefix.clone(),
17009 runs: Vec::new(),
17010 filter_range: 0..matching_prefix.len(),
17011 },
17012 documentation: snippet
17013 .description
17014 .clone()
17015 .map(|description| CompletionDocumentation::SingleLine(description.into())),
17016 confirm: None,
17017 })
17018 })
17019 .collect();
17020
17021 Ok(result)
17022 })
17023}
17024
17025impl CompletionProvider for Entity<Project> {
17026 fn completions(
17027 &self,
17028 buffer: &Entity<Buffer>,
17029 buffer_position: text::Anchor,
17030 options: CompletionContext,
17031 _window: &mut Window,
17032 cx: &mut Context<Editor>,
17033 ) -> Task<Result<Vec<Completion>>> {
17034 self.update(cx, |project, cx| {
17035 let snippets = snippet_completions(project, buffer, buffer_position, cx);
17036 let project_completions = project.completions(buffer, buffer_position, options, cx);
17037 cx.background_spawn(async move {
17038 let mut completions = project_completions.await?;
17039 let snippets_completions = snippets.await?;
17040 completions.extend(snippets_completions);
17041 Ok(completions)
17042 })
17043 })
17044 }
17045
17046 fn resolve_completions(
17047 &self,
17048 buffer: Entity<Buffer>,
17049 completion_indices: Vec<usize>,
17050 completions: Rc<RefCell<Box<[Completion]>>>,
17051 cx: &mut Context<Editor>,
17052 ) -> Task<Result<bool>> {
17053 self.update(cx, |project, cx| {
17054 project.lsp_store().update(cx, |lsp_store, cx| {
17055 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17056 })
17057 })
17058 }
17059
17060 fn apply_additional_edits_for_completion(
17061 &self,
17062 buffer: Entity<Buffer>,
17063 completions: Rc<RefCell<Box<[Completion]>>>,
17064 completion_index: usize,
17065 push_to_history: bool,
17066 cx: &mut Context<Editor>,
17067 ) -> Task<Result<Option<language::Transaction>>> {
17068 self.update(cx, |project, cx| {
17069 project.lsp_store().update(cx, |lsp_store, cx| {
17070 lsp_store.apply_additional_edits_for_completion(
17071 buffer,
17072 completions,
17073 completion_index,
17074 push_to_history,
17075 cx,
17076 )
17077 })
17078 })
17079 }
17080
17081 fn is_completion_trigger(
17082 &self,
17083 buffer: &Entity<Buffer>,
17084 position: language::Anchor,
17085 text: &str,
17086 trigger_in_words: bool,
17087 cx: &mut Context<Editor>,
17088 ) -> bool {
17089 let mut chars = text.chars();
17090 let char = if let Some(char) = chars.next() {
17091 char
17092 } else {
17093 return false;
17094 };
17095 if chars.next().is_some() {
17096 return false;
17097 }
17098
17099 let buffer = buffer.read(cx);
17100 let snapshot = buffer.snapshot();
17101 if !snapshot.settings_at(position, cx).show_completions_on_input {
17102 return false;
17103 }
17104 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17105 if trigger_in_words && classifier.is_word(char) {
17106 return true;
17107 }
17108
17109 buffer.completion_triggers().contains(text)
17110 }
17111}
17112
17113impl SemanticsProvider for Entity<Project> {
17114 fn hover(
17115 &self,
17116 buffer: &Entity<Buffer>,
17117 position: text::Anchor,
17118 cx: &mut App,
17119 ) -> Option<Task<Vec<project::Hover>>> {
17120 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17121 }
17122
17123 fn document_highlights(
17124 &self,
17125 buffer: &Entity<Buffer>,
17126 position: text::Anchor,
17127 cx: &mut App,
17128 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
17129 Some(self.update(cx, |project, cx| {
17130 project.document_highlights(buffer, position, cx)
17131 }))
17132 }
17133
17134 fn definitions(
17135 &self,
17136 buffer: &Entity<Buffer>,
17137 position: text::Anchor,
17138 kind: GotoDefinitionKind,
17139 cx: &mut App,
17140 ) -> Option<Task<Result<Vec<LocationLink>>>> {
17141 Some(self.update(cx, |project, cx| match kind {
17142 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
17143 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
17144 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
17145 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
17146 }))
17147 }
17148
17149 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
17150 // TODO: make this work for remote projects
17151 self.update(cx, |this, cx| {
17152 buffer.update(cx, |buffer, cx| {
17153 this.any_language_server_supports_inlay_hints(buffer, cx)
17154 })
17155 })
17156 }
17157
17158 fn inlay_hints(
17159 &self,
17160 buffer_handle: Entity<Buffer>,
17161 range: Range<text::Anchor>,
17162 cx: &mut App,
17163 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
17164 Some(self.update(cx, |project, cx| {
17165 project.inlay_hints(buffer_handle, range, cx)
17166 }))
17167 }
17168
17169 fn resolve_inlay_hint(
17170 &self,
17171 hint: InlayHint,
17172 buffer_handle: Entity<Buffer>,
17173 server_id: LanguageServerId,
17174 cx: &mut App,
17175 ) -> Option<Task<anyhow::Result<InlayHint>>> {
17176 Some(self.update(cx, |project, cx| {
17177 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
17178 }))
17179 }
17180
17181 fn range_for_rename(
17182 &self,
17183 buffer: &Entity<Buffer>,
17184 position: text::Anchor,
17185 cx: &mut App,
17186 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
17187 Some(self.update(cx, |project, cx| {
17188 let buffer = buffer.clone();
17189 let task = project.prepare_rename(buffer.clone(), position, cx);
17190 cx.spawn(|_, mut cx| async move {
17191 Ok(match task.await? {
17192 PrepareRenameResponse::Success(range) => Some(range),
17193 PrepareRenameResponse::InvalidPosition => None,
17194 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
17195 // Fallback on using TreeSitter info to determine identifier range
17196 buffer.update(&mut cx, |buffer, _| {
17197 let snapshot = buffer.snapshot();
17198 let (range, kind) = snapshot.surrounding_word(position);
17199 if kind != Some(CharKind::Word) {
17200 return None;
17201 }
17202 Some(
17203 snapshot.anchor_before(range.start)
17204 ..snapshot.anchor_after(range.end),
17205 )
17206 })?
17207 }
17208 })
17209 })
17210 }))
17211 }
17212
17213 fn perform_rename(
17214 &self,
17215 buffer: &Entity<Buffer>,
17216 position: text::Anchor,
17217 new_name: String,
17218 cx: &mut App,
17219 ) -> Option<Task<Result<ProjectTransaction>>> {
17220 Some(self.update(cx, |project, cx| {
17221 project.perform_rename(buffer.clone(), position, new_name, cx)
17222 }))
17223 }
17224}
17225
17226fn inlay_hint_settings(
17227 location: Anchor,
17228 snapshot: &MultiBufferSnapshot,
17229 cx: &mut Context<Editor>,
17230) -> InlayHintSettings {
17231 let file = snapshot.file_at(location);
17232 let language = snapshot.language_at(location).map(|l| l.name());
17233 language_settings(language, file, cx).inlay_hints
17234}
17235
17236fn consume_contiguous_rows(
17237 contiguous_row_selections: &mut Vec<Selection<Point>>,
17238 selection: &Selection<Point>,
17239 display_map: &DisplaySnapshot,
17240 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
17241) -> (MultiBufferRow, MultiBufferRow) {
17242 contiguous_row_selections.push(selection.clone());
17243 let start_row = MultiBufferRow(selection.start.row);
17244 let mut end_row = ending_row(selection, display_map);
17245
17246 while let Some(next_selection) = selections.peek() {
17247 if next_selection.start.row <= end_row.0 {
17248 end_row = ending_row(next_selection, display_map);
17249 contiguous_row_selections.push(selections.next().unwrap().clone());
17250 } else {
17251 break;
17252 }
17253 }
17254 (start_row, end_row)
17255}
17256
17257fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
17258 if next_selection.end.column > 0 || next_selection.is_empty() {
17259 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
17260 } else {
17261 MultiBufferRow(next_selection.end.row)
17262 }
17263}
17264
17265impl EditorSnapshot {
17266 pub fn remote_selections_in_range<'a>(
17267 &'a self,
17268 range: &'a Range<Anchor>,
17269 collaboration_hub: &dyn CollaborationHub,
17270 cx: &'a App,
17271 ) -> impl 'a + Iterator<Item = RemoteSelection> {
17272 let participant_names = collaboration_hub.user_names(cx);
17273 let participant_indices = collaboration_hub.user_participant_indices(cx);
17274 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
17275 let collaborators_by_replica_id = collaborators_by_peer_id
17276 .iter()
17277 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
17278 .collect::<HashMap<_, _>>();
17279 self.buffer_snapshot
17280 .selections_in_range(range, false)
17281 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
17282 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
17283 let participant_index = participant_indices.get(&collaborator.user_id).copied();
17284 let user_name = participant_names.get(&collaborator.user_id).cloned();
17285 Some(RemoteSelection {
17286 replica_id,
17287 selection,
17288 cursor_shape,
17289 line_mode,
17290 participant_index,
17291 peer_id: collaborator.peer_id,
17292 user_name,
17293 })
17294 })
17295 }
17296
17297 pub fn hunks_for_ranges(
17298 &self,
17299 ranges: impl IntoIterator<Item = Range<Point>>,
17300 ) -> Vec<MultiBufferDiffHunk> {
17301 let mut hunks = Vec::new();
17302 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
17303 HashMap::default();
17304 for query_range in ranges {
17305 let query_rows =
17306 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
17307 for hunk in self.buffer_snapshot.diff_hunks_in_range(
17308 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
17309 ) {
17310 // Include deleted hunks that are adjacent to the query range, because
17311 // otherwise they would be missed.
17312 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
17313 if hunk.status().is_deleted() {
17314 intersects_range |= hunk.row_range.start == query_rows.end;
17315 intersects_range |= hunk.row_range.end == query_rows.start;
17316 }
17317 if intersects_range {
17318 if !processed_buffer_rows
17319 .entry(hunk.buffer_id)
17320 .or_default()
17321 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
17322 {
17323 continue;
17324 }
17325 hunks.push(hunk);
17326 }
17327 }
17328 }
17329
17330 hunks
17331 }
17332
17333 fn display_diff_hunks_for_rows<'a>(
17334 &'a self,
17335 display_rows: Range<DisplayRow>,
17336 folded_buffers: &'a HashSet<BufferId>,
17337 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
17338 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
17339 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
17340
17341 self.buffer_snapshot
17342 .diff_hunks_in_range(buffer_start..buffer_end)
17343 .filter_map(|hunk| {
17344 if folded_buffers.contains(&hunk.buffer_id) {
17345 return None;
17346 }
17347
17348 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
17349 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
17350
17351 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
17352 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
17353
17354 let display_hunk = if hunk_display_start.column() != 0 {
17355 DisplayDiffHunk::Folded {
17356 display_row: hunk_display_start.row(),
17357 }
17358 } else {
17359 let mut end_row = hunk_display_end.row();
17360 if hunk_display_end.column() > 0 {
17361 end_row.0 += 1;
17362 }
17363 let is_created_file = hunk.is_created_file();
17364 DisplayDiffHunk::Unfolded {
17365 status: hunk.status(),
17366 diff_base_byte_range: hunk.diff_base_byte_range,
17367 display_row_range: hunk_display_start.row()..end_row,
17368 multi_buffer_range: Anchor::range_in_buffer(
17369 hunk.excerpt_id,
17370 hunk.buffer_id,
17371 hunk.buffer_range,
17372 ),
17373 is_created_file,
17374 }
17375 };
17376
17377 Some(display_hunk)
17378 })
17379 }
17380
17381 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
17382 self.display_snapshot.buffer_snapshot.language_at(position)
17383 }
17384
17385 pub fn is_focused(&self) -> bool {
17386 self.is_focused
17387 }
17388
17389 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
17390 self.placeholder_text.as_ref()
17391 }
17392
17393 pub fn scroll_position(&self) -> gpui::Point<f32> {
17394 self.scroll_anchor.scroll_position(&self.display_snapshot)
17395 }
17396
17397 fn gutter_dimensions(
17398 &self,
17399 font_id: FontId,
17400 font_size: Pixels,
17401 max_line_number_width: Pixels,
17402 cx: &App,
17403 ) -> Option<GutterDimensions> {
17404 if !self.show_gutter {
17405 return None;
17406 }
17407
17408 let descent = cx.text_system().descent(font_id, font_size);
17409 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
17410 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
17411
17412 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
17413 matches!(
17414 ProjectSettings::get_global(cx).git.git_gutter,
17415 Some(GitGutterSetting::TrackedFiles)
17416 )
17417 });
17418 let gutter_settings = EditorSettings::get_global(cx).gutter;
17419 let show_line_numbers = self
17420 .show_line_numbers
17421 .unwrap_or(gutter_settings.line_numbers);
17422 let line_gutter_width = if show_line_numbers {
17423 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
17424 let min_width_for_number_on_gutter = em_advance * 4.0;
17425 max_line_number_width.max(min_width_for_number_on_gutter)
17426 } else {
17427 0.0.into()
17428 };
17429
17430 let show_code_actions = self
17431 .show_code_actions
17432 .unwrap_or(gutter_settings.code_actions);
17433
17434 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
17435
17436 let git_blame_entries_width =
17437 self.git_blame_gutter_max_author_length
17438 .map(|max_author_length| {
17439 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
17440
17441 /// The number of characters to dedicate to gaps and margins.
17442 const SPACING_WIDTH: usize = 4;
17443
17444 let max_char_count = max_author_length
17445 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
17446 + ::git::SHORT_SHA_LENGTH
17447 + MAX_RELATIVE_TIMESTAMP.len()
17448 + SPACING_WIDTH;
17449
17450 em_advance * max_char_count
17451 });
17452
17453 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
17454 left_padding += if show_code_actions || show_runnables {
17455 em_width * 3.0
17456 } else if show_git_gutter && show_line_numbers {
17457 em_width * 2.0
17458 } else if show_git_gutter || show_line_numbers {
17459 em_width
17460 } else {
17461 px(0.)
17462 };
17463
17464 let right_padding = if gutter_settings.folds && show_line_numbers {
17465 em_width * 4.0
17466 } else if gutter_settings.folds {
17467 em_width * 3.0
17468 } else if show_line_numbers {
17469 em_width
17470 } else {
17471 px(0.)
17472 };
17473
17474 Some(GutterDimensions {
17475 left_padding,
17476 right_padding,
17477 width: line_gutter_width + left_padding + right_padding,
17478 margin: -descent,
17479 git_blame_entries_width,
17480 })
17481 }
17482
17483 pub fn render_crease_toggle(
17484 &self,
17485 buffer_row: MultiBufferRow,
17486 row_contains_cursor: bool,
17487 editor: Entity<Editor>,
17488 window: &mut Window,
17489 cx: &mut App,
17490 ) -> Option<AnyElement> {
17491 let folded = self.is_line_folded(buffer_row);
17492 let mut is_foldable = false;
17493
17494 if let Some(crease) = self
17495 .crease_snapshot
17496 .query_row(buffer_row, &self.buffer_snapshot)
17497 {
17498 is_foldable = true;
17499 match crease {
17500 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
17501 if let Some(render_toggle) = render_toggle {
17502 let toggle_callback =
17503 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
17504 if folded {
17505 editor.update(cx, |editor, cx| {
17506 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
17507 });
17508 } else {
17509 editor.update(cx, |editor, cx| {
17510 editor.unfold_at(
17511 &crate::UnfoldAt { buffer_row },
17512 window,
17513 cx,
17514 )
17515 });
17516 }
17517 });
17518 return Some((render_toggle)(
17519 buffer_row,
17520 folded,
17521 toggle_callback,
17522 window,
17523 cx,
17524 ));
17525 }
17526 }
17527 }
17528 }
17529
17530 is_foldable |= self.starts_indent(buffer_row);
17531
17532 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
17533 Some(
17534 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
17535 .toggle_state(folded)
17536 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
17537 if folded {
17538 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
17539 } else {
17540 this.fold_at(&FoldAt { buffer_row }, window, cx);
17541 }
17542 }))
17543 .into_any_element(),
17544 )
17545 } else {
17546 None
17547 }
17548 }
17549
17550 pub fn render_crease_trailer(
17551 &self,
17552 buffer_row: MultiBufferRow,
17553 window: &mut Window,
17554 cx: &mut App,
17555 ) -> Option<AnyElement> {
17556 let folded = self.is_line_folded(buffer_row);
17557 if let Crease::Inline { render_trailer, .. } = self
17558 .crease_snapshot
17559 .query_row(buffer_row, &self.buffer_snapshot)?
17560 {
17561 let render_trailer = render_trailer.as_ref()?;
17562 Some(render_trailer(buffer_row, folded, window, cx))
17563 } else {
17564 None
17565 }
17566 }
17567}
17568
17569impl Deref for EditorSnapshot {
17570 type Target = DisplaySnapshot;
17571
17572 fn deref(&self) -> &Self::Target {
17573 &self.display_snapshot
17574 }
17575}
17576
17577#[derive(Clone, Debug, PartialEq, Eq)]
17578pub enum EditorEvent {
17579 InputIgnored {
17580 text: Arc<str>,
17581 },
17582 InputHandled {
17583 utf16_range_to_replace: Option<Range<isize>>,
17584 text: Arc<str>,
17585 },
17586 ExcerptsAdded {
17587 buffer: Entity<Buffer>,
17588 predecessor: ExcerptId,
17589 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
17590 },
17591 ExcerptsRemoved {
17592 ids: Vec<ExcerptId>,
17593 },
17594 BufferFoldToggled {
17595 ids: Vec<ExcerptId>,
17596 folded: bool,
17597 },
17598 ExcerptsEdited {
17599 ids: Vec<ExcerptId>,
17600 },
17601 ExcerptsExpanded {
17602 ids: Vec<ExcerptId>,
17603 },
17604 BufferEdited,
17605 Edited {
17606 transaction_id: clock::Lamport,
17607 },
17608 Reparsed(BufferId),
17609 Focused,
17610 FocusedIn,
17611 Blurred,
17612 DirtyChanged,
17613 Saved,
17614 TitleChanged,
17615 DiffBaseChanged,
17616 SelectionsChanged {
17617 local: bool,
17618 },
17619 ScrollPositionChanged {
17620 local: bool,
17621 autoscroll: bool,
17622 },
17623 Closed,
17624 TransactionUndone {
17625 transaction_id: clock::Lamport,
17626 },
17627 TransactionBegun {
17628 transaction_id: clock::Lamport,
17629 },
17630 Reloaded,
17631 CursorShapeChanged,
17632}
17633
17634impl EventEmitter<EditorEvent> for Editor {}
17635
17636impl Focusable for Editor {
17637 fn focus_handle(&self, _cx: &App) -> FocusHandle {
17638 self.focus_handle.clone()
17639 }
17640}
17641
17642impl Render for Editor {
17643 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
17644 let settings = ThemeSettings::get_global(cx);
17645
17646 let mut text_style = match self.mode {
17647 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
17648 color: cx.theme().colors().editor_foreground,
17649 font_family: settings.ui_font.family.clone(),
17650 font_features: settings.ui_font.features.clone(),
17651 font_fallbacks: settings.ui_font.fallbacks.clone(),
17652 font_size: rems(0.875).into(),
17653 font_weight: settings.ui_font.weight,
17654 line_height: relative(settings.buffer_line_height.value()),
17655 ..Default::default()
17656 },
17657 EditorMode::Full => TextStyle {
17658 color: cx.theme().colors().editor_foreground,
17659 font_family: settings.buffer_font.family.clone(),
17660 font_features: settings.buffer_font.features.clone(),
17661 font_fallbacks: settings.buffer_font.fallbacks.clone(),
17662 font_size: settings.buffer_font_size(cx).into(),
17663 font_weight: settings.buffer_font.weight,
17664 line_height: relative(settings.buffer_line_height.value()),
17665 ..Default::default()
17666 },
17667 };
17668 if let Some(text_style_refinement) = &self.text_style_refinement {
17669 text_style.refine(text_style_refinement)
17670 }
17671
17672 let background = match self.mode {
17673 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
17674 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
17675 EditorMode::Full => cx.theme().colors().editor_background,
17676 };
17677
17678 EditorElement::new(
17679 &cx.entity(),
17680 EditorStyle {
17681 background,
17682 local_player: cx.theme().players().local(),
17683 text: text_style,
17684 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
17685 syntax: cx.theme().syntax().clone(),
17686 status: cx.theme().status().clone(),
17687 inlay_hints_style: make_inlay_hints_style(cx),
17688 inline_completion_styles: make_suggestion_styles(cx),
17689 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
17690 },
17691 )
17692 }
17693}
17694
17695impl EntityInputHandler for Editor {
17696 fn text_for_range(
17697 &mut self,
17698 range_utf16: Range<usize>,
17699 adjusted_range: &mut Option<Range<usize>>,
17700 _: &mut Window,
17701 cx: &mut Context<Self>,
17702 ) -> Option<String> {
17703 let snapshot = self.buffer.read(cx).read(cx);
17704 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
17705 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
17706 if (start.0..end.0) != range_utf16 {
17707 adjusted_range.replace(start.0..end.0);
17708 }
17709 Some(snapshot.text_for_range(start..end).collect())
17710 }
17711
17712 fn selected_text_range(
17713 &mut self,
17714 ignore_disabled_input: bool,
17715 _: &mut Window,
17716 cx: &mut Context<Self>,
17717 ) -> Option<UTF16Selection> {
17718 // Prevent the IME menu from appearing when holding down an alphabetic key
17719 // while input is disabled.
17720 if !ignore_disabled_input && !self.input_enabled {
17721 return None;
17722 }
17723
17724 let selection = self.selections.newest::<OffsetUtf16>(cx);
17725 let range = selection.range();
17726
17727 Some(UTF16Selection {
17728 range: range.start.0..range.end.0,
17729 reversed: selection.reversed,
17730 })
17731 }
17732
17733 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
17734 let snapshot = self.buffer.read(cx).read(cx);
17735 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
17736 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
17737 }
17738
17739 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17740 self.clear_highlights::<InputComposition>(cx);
17741 self.ime_transaction.take();
17742 }
17743
17744 fn replace_text_in_range(
17745 &mut self,
17746 range_utf16: Option<Range<usize>>,
17747 text: &str,
17748 window: &mut Window,
17749 cx: &mut Context<Self>,
17750 ) {
17751 if !self.input_enabled {
17752 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17753 return;
17754 }
17755
17756 self.transact(window, cx, |this, window, cx| {
17757 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
17758 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17759 Some(this.selection_replacement_ranges(range_utf16, cx))
17760 } else {
17761 this.marked_text_ranges(cx)
17762 };
17763
17764 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
17765 let newest_selection_id = this.selections.newest_anchor().id;
17766 this.selections
17767 .all::<OffsetUtf16>(cx)
17768 .iter()
17769 .zip(ranges_to_replace.iter())
17770 .find_map(|(selection, range)| {
17771 if selection.id == newest_selection_id {
17772 Some(
17773 (range.start.0 as isize - selection.head().0 as isize)
17774 ..(range.end.0 as isize - selection.head().0 as isize),
17775 )
17776 } else {
17777 None
17778 }
17779 })
17780 });
17781
17782 cx.emit(EditorEvent::InputHandled {
17783 utf16_range_to_replace: range_to_replace,
17784 text: text.into(),
17785 });
17786
17787 if let Some(new_selected_ranges) = new_selected_ranges {
17788 this.change_selections(None, window, cx, |selections| {
17789 selections.select_ranges(new_selected_ranges)
17790 });
17791 this.backspace(&Default::default(), window, cx);
17792 }
17793
17794 this.handle_input(text, window, cx);
17795 });
17796
17797 if let Some(transaction) = self.ime_transaction {
17798 self.buffer.update(cx, |buffer, cx| {
17799 buffer.group_until_transaction(transaction, cx);
17800 });
17801 }
17802
17803 self.unmark_text(window, cx);
17804 }
17805
17806 fn replace_and_mark_text_in_range(
17807 &mut self,
17808 range_utf16: Option<Range<usize>>,
17809 text: &str,
17810 new_selected_range_utf16: Option<Range<usize>>,
17811 window: &mut Window,
17812 cx: &mut Context<Self>,
17813 ) {
17814 if !self.input_enabled {
17815 return;
17816 }
17817
17818 let transaction = self.transact(window, cx, |this, window, cx| {
17819 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
17820 let snapshot = this.buffer.read(cx).read(cx);
17821 if let Some(relative_range_utf16) = range_utf16.as_ref() {
17822 for marked_range in &mut marked_ranges {
17823 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
17824 marked_range.start.0 += relative_range_utf16.start;
17825 marked_range.start =
17826 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
17827 marked_range.end =
17828 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
17829 }
17830 }
17831 Some(marked_ranges)
17832 } else if let Some(range_utf16) = range_utf16 {
17833 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
17834 Some(this.selection_replacement_ranges(range_utf16, cx))
17835 } else {
17836 None
17837 };
17838
17839 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
17840 let newest_selection_id = this.selections.newest_anchor().id;
17841 this.selections
17842 .all::<OffsetUtf16>(cx)
17843 .iter()
17844 .zip(ranges_to_replace.iter())
17845 .find_map(|(selection, range)| {
17846 if selection.id == newest_selection_id {
17847 Some(
17848 (range.start.0 as isize - selection.head().0 as isize)
17849 ..(range.end.0 as isize - selection.head().0 as isize),
17850 )
17851 } else {
17852 None
17853 }
17854 })
17855 });
17856
17857 cx.emit(EditorEvent::InputHandled {
17858 utf16_range_to_replace: range_to_replace,
17859 text: text.into(),
17860 });
17861
17862 if let Some(ranges) = ranges_to_replace {
17863 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
17864 }
17865
17866 let marked_ranges = {
17867 let snapshot = this.buffer.read(cx).read(cx);
17868 this.selections
17869 .disjoint_anchors()
17870 .iter()
17871 .map(|selection| {
17872 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
17873 })
17874 .collect::<Vec<_>>()
17875 };
17876
17877 if text.is_empty() {
17878 this.unmark_text(window, cx);
17879 } else {
17880 this.highlight_text::<InputComposition>(
17881 marked_ranges.clone(),
17882 HighlightStyle {
17883 underline: Some(UnderlineStyle {
17884 thickness: px(1.),
17885 color: None,
17886 wavy: false,
17887 }),
17888 ..Default::default()
17889 },
17890 cx,
17891 );
17892 }
17893
17894 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
17895 let use_autoclose = this.use_autoclose;
17896 let use_auto_surround = this.use_auto_surround;
17897 this.set_use_autoclose(false);
17898 this.set_use_auto_surround(false);
17899 this.handle_input(text, window, cx);
17900 this.set_use_autoclose(use_autoclose);
17901 this.set_use_auto_surround(use_auto_surround);
17902
17903 if let Some(new_selected_range) = new_selected_range_utf16 {
17904 let snapshot = this.buffer.read(cx).read(cx);
17905 let new_selected_ranges = marked_ranges
17906 .into_iter()
17907 .map(|marked_range| {
17908 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
17909 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
17910 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
17911 snapshot.clip_offset_utf16(new_start, Bias::Left)
17912 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
17913 })
17914 .collect::<Vec<_>>();
17915
17916 drop(snapshot);
17917 this.change_selections(None, window, cx, |selections| {
17918 selections.select_ranges(new_selected_ranges)
17919 });
17920 }
17921 });
17922
17923 self.ime_transaction = self.ime_transaction.or(transaction);
17924 if let Some(transaction) = self.ime_transaction {
17925 self.buffer.update(cx, |buffer, cx| {
17926 buffer.group_until_transaction(transaction, cx);
17927 });
17928 }
17929
17930 if self.text_highlights::<InputComposition>(cx).is_none() {
17931 self.ime_transaction.take();
17932 }
17933 }
17934
17935 fn bounds_for_range(
17936 &mut self,
17937 range_utf16: Range<usize>,
17938 element_bounds: gpui::Bounds<Pixels>,
17939 window: &mut Window,
17940 cx: &mut Context<Self>,
17941 ) -> Option<gpui::Bounds<Pixels>> {
17942 let text_layout_details = self.text_layout_details(window);
17943 let gpui::Size {
17944 width: em_width,
17945 height: line_height,
17946 } = self.character_size(window);
17947
17948 let snapshot = self.snapshot(window, cx);
17949 let scroll_position = snapshot.scroll_position();
17950 let scroll_left = scroll_position.x * em_width;
17951
17952 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
17953 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
17954 + self.gutter_dimensions.width
17955 + self.gutter_dimensions.margin;
17956 let y = line_height * (start.row().as_f32() - scroll_position.y);
17957
17958 Some(Bounds {
17959 origin: element_bounds.origin + point(x, y),
17960 size: size(em_width, line_height),
17961 })
17962 }
17963
17964 fn character_index_for_point(
17965 &mut self,
17966 point: gpui::Point<Pixels>,
17967 _window: &mut Window,
17968 _cx: &mut Context<Self>,
17969 ) -> Option<usize> {
17970 let position_map = self.last_position_map.as_ref()?;
17971 if !position_map.text_hitbox.contains(&point) {
17972 return None;
17973 }
17974 let display_point = position_map.point_for_position(point).previous_valid;
17975 let anchor = position_map
17976 .snapshot
17977 .display_point_to_anchor(display_point, Bias::Left);
17978 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
17979 Some(utf16_offset.0)
17980 }
17981}
17982
17983trait SelectionExt {
17984 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
17985 fn spanned_rows(
17986 &self,
17987 include_end_if_at_line_start: bool,
17988 map: &DisplaySnapshot,
17989 ) -> Range<MultiBufferRow>;
17990}
17991
17992impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
17993 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
17994 let start = self
17995 .start
17996 .to_point(&map.buffer_snapshot)
17997 .to_display_point(map);
17998 let end = self
17999 .end
18000 .to_point(&map.buffer_snapshot)
18001 .to_display_point(map);
18002 if self.reversed {
18003 end..start
18004 } else {
18005 start..end
18006 }
18007 }
18008
18009 fn spanned_rows(
18010 &self,
18011 include_end_if_at_line_start: bool,
18012 map: &DisplaySnapshot,
18013 ) -> Range<MultiBufferRow> {
18014 let start = self.start.to_point(&map.buffer_snapshot);
18015 let mut end = self.end.to_point(&map.buffer_snapshot);
18016 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18017 end.row -= 1;
18018 }
18019
18020 let buffer_start = map.prev_line_boundary(start).0;
18021 let buffer_end = map.next_line_boundary(end).0;
18022 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18023 }
18024}
18025
18026impl<T: InvalidationRegion> InvalidationStack<T> {
18027 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18028 where
18029 S: Clone + ToOffset,
18030 {
18031 while let Some(region) = self.last() {
18032 let all_selections_inside_invalidation_ranges =
18033 if selections.len() == region.ranges().len() {
18034 selections
18035 .iter()
18036 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18037 .all(|(selection, invalidation_range)| {
18038 let head = selection.head().to_offset(buffer);
18039 invalidation_range.start <= head && invalidation_range.end >= head
18040 })
18041 } else {
18042 false
18043 };
18044
18045 if all_selections_inside_invalidation_ranges {
18046 break;
18047 } else {
18048 self.pop();
18049 }
18050 }
18051 }
18052}
18053
18054impl<T> Default for InvalidationStack<T> {
18055 fn default() -> Self {
18056 Self(Default::default())
18057 }
18058}
18059
18060impl<T> Deref for InvalidationStack<T> {
18061 type Target = Vec<T>;
18062
18063 fn deref(&self) -> &Self::Target {
18064 &self.0
18065 }
18066}
18067
18068impl<T> DerefMut for InvalidationStack<T> {
18069 fn deref_mut(&mut self) -> &mut Self::Target {
18070 &mut self.0
18071 }
18072}
18073
18074impl InvalidationRegion for SnippetState {
18075 fn ranges(&self) -> &[Range<Anchor>] {
18076 &self.ranges[self.active_index]
18077 }
18078}
18079
18080pub fn diagnostic_block_renderer(
18081 diagnostic: Diagnostic,
18082 max_message_rows: Option<u8>,
18083 allow_closing: bool,
18084) -> RenderBlock {
18085 let (text_without_backticks, code_ranges) =
18086 highlight_diagnostic_message(&diagnostic, max_message_rows);
18087
18088 Arc::new(move |cx: &mut BlockContext| {
18089 let group_id: SharedString = cx.block_id.to_string().into();
18090
18091 let mut text_style = cx.window.text_style().clone();
18092 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18093 let theme_settings = ThemeSettings::get_global(cx);
18094 text_style.font_family = theme_settings.buffer_font.family.clone();
18095 text_style.font_style = theme_settings.buffer_font.style;
18096 text_style.font_features = theme_settings.buffer_font.features.clone();
18097 text_style.font_weight = theme_settings.buffer_font.weight;
18098
18099 let multi_line_diagnostic = diagnostic.message.contains('\n');
18100
18101 let buttons = |diagnostic: &Diagnostic| {
18102 if multi_line_diagnostic {
18103 v_flex()
18104 } else {
18105 h_flex()
18106 }
18107 .when(allow_closing, |div| {
18108 div.children(diagnostic.is_primary.then(|| {
18109 IconButton::new("close-block", IconName::XCircle)
18110 .icon_color(Color::Muted)
18111 .size(ButtonSize::Compact)
18112 .style(ButtonStyle::Transparent)
18113 .visible_on_hover(group_id.clone())
18114 .on_click(move |_click, window, cx| {
18115 window.dispatch_action(Box::new(Cancel), cx)
18116 })
18117 .tooltip(|window, cx| {
18118 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18119 })
18120 }))
18121 })
18122 .child(
18123 IconButton::new("copy-block", IconName::Copy)
18124 .icon_color(Color::Muted)
18125 .size(ButtonSize::Compact)
18126 .style(ButtonStyle::Transparent)
18127 .visible_on_hover(group_id.clone())
18128 .on_click({
18129 let message = diagnostic.message.clone();
18130 move |_click, _, cx| {
18131 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
18132 }
18133 })
18134 .tooltip(Tooltip::text("Copy diagnostic message")),
18135 )
18136 };
18137
18138 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
18139 AvailableSpace::min_size(),
18140 cx.window,
18141 cx.app,
18142 );
18143
18144 h_flex()
18145 .id(cx.block_id)
18146 .group(group_id.clone())
18147 .relative()
18148 .size_full()
18149 .block_mouse_down()
18150 .pl(cx.gutter_dimensions.width)
18151 .w(cx.max_width - cx.gutter_dimensions.full_width())
18152 .child(
18153 div()
18154 .flex()
18155 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
18156 .flex_shrink(),
18157 )
18158 .child(buttons(&diagnostic))
18159 .child(div().flex().flex_shrink_0().child(
18160 StyledText::new(text_without_backticks.clone()).with_default_highlights(
18161 &text_style,
18162 code_ranges.iter().map(|range| {
18163 (
18164 range.clone(),
18165 HighlightStyle {
18166 font_weight: Some(FontWeight::BOLD),
18167 ..Default::default()
18168 },
18169 )
18170 }),
18171 ),
18172 ))
18173 .into_any_element()
18174 })
18175}
18176
18177fn inline_completion_edit_text(
18178 current_snapshot: &BufferSnapshot,
18179 edits: &[(Range<Anchor>, String)],
18180 edit_preview: &EditPreview,
18181 include_deletions: bool,
18182 cx: &App,
18183) -> HighlightedText {
18184 let edits = edits
18185 .iter()
18186 .map(|(anchor, text)| {
18187 (
18188 anchor.start.text_anchor..anchor.end.text_anchor,
18189 text.clone(),
18190 )
18191 })
18192 .collect::<Vec<_>>();
18193
18194 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
18195}
18196
18197pub fn highlight_diagnostic_message(
18198 diagnostic: &Diagnostic,
18199 mut max_message_rows: Option<u8>,
18200) -> (SharedString, Vec<Range<usize>>) {
18201 let mut text_without_backticks = String::new();
18202 let mut code_ranges = Vec::new();
18203
18204 if let Some(source) = &diagnostic.source {
18205 text_without_backticks.push_str(source);
18206 code_ranges.push(0..source.len());
18207 text_without_backticks.push_str(": ");
18208 }
18209
18210 let mut prev_offset = 0;
18211 let mut in_code_block = false;
18212 let has_row_limit = max_message_rows.is_some();
18213 let mut newline_indices = diagnostic
18214 .message
18215 .match_indices('\n')
18216 .filter(|_| has_row_limit)
18217 .map(|(ix, _)| ix)
18218 .fuse()
18219 .peekable();
18220
18221 for (quote_ix, _) in diagnostic
18222 .message
18223 .match_indices('`')
18224 .chain([(diagnostic.message.len(), "")])
18225 {
18226 let mut first_newline_ix = None;
18227 let mut last_newline_ix = None;
18228 while let Some(newline_ix) = newline_indices.peek() {
18229 if *newline_ix < quote_ix {
18230 if first_newline_ix.is_none() {
18231 first_newline_ix = Some(*newline_ix);
18232 }
18233 last_newline_ix = Some(*newline_ix);
18234
18235 if let Some(rows_left) = &mut max_message_rows {
18236 if *rows_left == 0 {
18237 break;
18238 } else {
18239 *rows_left -= 1;
18240 }
18241 }
18242 let _ = newline_indices.next();
18243 } else {
18244 break;
18245 }
18246 }
18247 let prev_len = text_without_backticks.len();
18248 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
18249 text_without_backticks.push_str(new_text);
18250 if in_code_block {
18251 code_ranges.push(prev_len..text_without_backticks.len());
18252 }
18253 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
18254 in_code_block = !in_code_block;
18255 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
18256 text_without_backticks.push_str("...");
18257 break;
18258 }
18259 }
18260
18261 (text_without_backticks.into(), code_ranges)
18262}
18263
18264fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
18265 match severity {
18266 DiagnosticSeverity::ERROR => colors.error,
18267 DiagnosticSeverity::WARNING => colors.warning,
18268 DiagnosticSeverity::INFORMATION => colors.info,
18269 DiagnosticSeverity::HINT => colors.info,
18270 _ => colors.ignored,
18271 }
18272}
18273
18274pub fn styled_runs_for_code_label<'a>(
18275 label: &'a CodeLabel,
18276 syntax_theme: &'a theme::SyntaxTheme,
18277) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
18278 let fade_out = HighlightStyle {
18279 fade_out: Some(0.35),
18280 ..Default::default()
18281 };
18282
18283 let mut prev_end = label.filter_range.end;
18284 label
18285 .runs
18286 .iter()
18287 .enumerate()
18288 .flat_map(move |(ix, (range, highlight_id))| {
18289 let style = if let Some(style) = highlight_id.style(syntax_theme) {
18290 style
18291 } else {
18292 return Default::default();
18293 };
18294 let mut muted_style = style;
18295 muted_style.highlight(fade_out);
18296
18297 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
18298 if range.start >= label.filter_range.end {
18299 if range.start > prev_end {
18300 runs.push((prev_end..range.start, fade_out));
18301 }
18302 runs.push((range.clone(), muted_style));
18303 } else if range.end <= label.filter_range.end {
18304 runs.push((range.clone(), style));
18305 } else {
18306 runs.push((range.start..label.filter_range.end, style));
18307 runs.push((label.filter_range.end..range.end, muted_style));
18308 }
18309 prev_end = cmp::max(prev_end, range.end);
18310
18311 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
18312 runs.push((prev_end..label.text.len(), fade_out));
18313 }
18314
18315 runs
18316 })
18317}
18318
18319pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
18320 let mut prev_index = 0;
18321 let mut prev_codepoint: Option<char> = None;
18322 text.char_indices()
18323 .chain([(text.len(), '\0')])
18324 .filter_map(move |(index, codepoint)| {
18325 let prev_codepoint = prev_codepoint.replace(codepoint)?;
18326 let is_boundary = index == text.len()
18327 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
18328 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
18329 if is_boundary {
18330 let chunk = &text[prev_index..index];
18331 prev_index = index;
18332 Some(chunk)
18333 } else {
18334 None
18335 }
18336 })
18337}
18338
18339pub trait RangeToAnchorExt: Sized {
18340 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
18341
18342 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
18343 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
18344 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
18345 }
18346}
18347
18348impl<T: ToOffset> RangeToAnchorExt for Range<T> {
18349 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
18350 let start_offset = self.start.to_offset(snapshot);
18351 let end_offset = self.end.to_offset(snapshot);
18352 if start_offset == end_offset {
18353 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
18354 } else {
18355 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
18356 }
18357 }
18358}
18359
18360pub trait RowExt {
18361 fn as_f32(&self) -> f32;
18362
18363 fn next_row(&self) -> Self;
18364
18365 fn previous_row(&self) -> Self;
18366
18367 fn minus(&self, other: Self) -> u32;
18368}
18369
18370impl RowExt for DisplayRow {
18371 fn as_f32(&self) -> f32 {
18372 self.0 as f32
18373 }
18374
18375 fn next_row(&self) -> Self {
18376 Self(self.0 + 1)
18377 }
18378
18379 fn previous_row(&self) -> Self {
18380 Self(self.0.saturating_sub(1))
18381 }
18382
18383 fn minus(&self, other: Self) -> u32 {
18384 self.0 - other.0
18385 }
18386}
18387
18388impl RowExt for MultiBufferRow {
18389 fn as_f32(&self) -> f32 {
18390 self.0 as f32
18391 }
18392
18393 fn next_row(&self) -> Self {
18394 Self(self.0 + 1)
18395 }
18396
18397 fn previous_row(&self) -> Self {
18398 Self(self.0.saturating_sub(1))
18399 }
18400
18401 fn minus(&self, other: Self) -> u32 {
18402 self.0 - other.0
18403 }
18404}
18405
18406trait RowRangeExt {
18407 type Row;
18408
18409 fn len(&self) -> usize;
18410
18411 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
18412}
18413
18414impl RowRangeExt for Range<MultiBufferRow> {
18415 type Row = MultiBufferRow;
18416
18417 fn len(&self) -> usize {
18418 (self.end.0 - self.start.0) as usize
18419 }
18420
18421 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
18422 (self.start.0..self.end.0).map(MultiBufferRow)
18423 }
18424}
18425
18426impl RowRangeExt for Range<DisplayRow> {
18427 type Row = DisplayRow;
18428
18429 fn len(&self) -> usize {
18430 (self.end.0 - self.start.0) as usize
18431 }
18432
18433 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
18434 (self.start.0..self.end.0).map(DisplayRow)
18435 }
18436}
18437
18438/// If select range has more than one line, we
18439/// just point the cursor to range.start.
18440fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
18441 if range.start.row == range.end.row {
18442 range
18443 } else {
18444 range.start..range.start
18445 }
18446}
18447pub struct KillRing(ClipboardItem);
18448impl Global for KillRing {}
18449
18450const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
18451
18452fn all_edits_insertions_or_deletions(
18453 edits: &Vec<(Range<Anchor>, String)>,
18454 snapshot: &MultiBufferSnapshot,
18455) -> bool {
18456 let mut all_insertions = true;
18457 let mut all_deletions = true;
18458
18459 for (range, new_text) in edits.iter() {
18460 let range_is_empty = range.to_offset(&snapshot).is_empty();
18461 let text_is_empty = new_text.is_empty();
18462
18463 if range_is_empty != text_is_empty {
18464 if range_is_empty {
18465 all_deletions = false;
18466 } else {
18467 all_insertions = false;
18468 }
18469 } else {
18470 return false;
18471 }
18472
18473 if !all_insertions && !all_deletions {
18474 return false;
18475 }
18476 }
18477 all_insertions || all_deletions
18478}
18479
18480struct MissingEditPredictionKeybindingTooltip;
18481
18482impl Render for MissingEditPredictionKeybindingTooltip {
18483 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18484 ui::tooltip_container(window, cx, |container, _, cx| {
18485 container
18486 .flex_shrink_0()
18487 .max_w_80()
18488 .min_h(rems_from_px(124.))
18489 .justify_between()
18490 .child(
18491 v_flex()
18492 .flex_1()
18493 .text_ui_sm(cx)
18494 .child(Label::new("Conflict with Accept Keybinding"))
18495 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
18496 )
18497 .child(
18498 h_flex()
18499 .pb_1()
18500 .gap_1()
18501 .items_end()
18502 .w_full()
18503 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
18504 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
18505 }))
18506 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
18507 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
18508 })),
18509 )
18510 })
18511 }
18512}
18513
18514#[derive(Debug, Clone, Copy, PartialEq)]
18515pub struct LineHighlight {
18516 pub background: Background,
18517 pub border: Option<gpui::Hsla>,
18518}
18519
18520impl From<Hsla> for LineHighlight {
18521 fn from(hsla: Hsla) -> Self {
18522 Self {
18523 background: hsla.into(),
18524 border: None,
18525 }
18526 }
18527}
18528
18529impl From<Background> for LineHighlight {
18530 fn from(background: Background) -> Self {
18531 Self {
18532 background,
18533 border: None,
18534 }
18535 }
18536}