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 display_map;
20mod editor_settings;
21mod editor_settings_controls;
22mod element;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26pub mod hover_popover;
27mod indent_guides;
28mod inlay_hint_cache;
29pub mod items;
30mod jsx_tag_auto_close;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50pub(crate) use actions::*;
51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
52use aho_corasick::AhoCorasick;
53use anyhow::{Context as _, Result, anyhow};
54use blink_manager::BlinkManager;
55use buffer_diff::DiffHunkStatus;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
62use editor_settings::GoToDefinitionFallback;
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
65 ShowScrollbar,
66};
67pub use editor_settings_controls::*;
68use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
69pub use element::{
70 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
71};
72use feature_flags::{Debugger, FeatureFlagAppExt};
73use futures::{
74 FutureExt,
75 future::{self, Shared, join},
76};
77use fuzzy::StringMatchCandidate;
78
79use ::git::Restore;
80use code_context_menus::{
81 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
82 CompletionsMenu, ContextMenuOrigin,
83};
84use git::blame::{GitBlame, GlobalBlameRenderer};
85use gpui::{
86 Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
87 AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
88 ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
89 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
90 KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
91 SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
92 UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
93 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
94};
95use highlight_matching_bracket::refresh_matching_bracket_highlights;
96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
97pub use hover_popover::hover_markdown_style;
98use hover_popover::{HoverState, hide_hover};
99use indent_guides::ActiveIndentGuidesState;
100use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
101pub use inline_completion::Direction;
102use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
103pub use items::MAX_TAB_TITLE_LEN;
104use itertools::Itertools;
105use language::{
106 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
107 CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
108 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
109 TransactionId, TreeSitterOptions, WordsQuery,
110 language_settings::{
111 self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
112 all_language_settings, language_settings,
113 },
114 point_from_lsp, text_diff_with_options,
115};
116use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
117use linked_editing_ranges::refresh_linked_ranges;
118use mouse_context_menu::MouseContextMenu;
119use persistence::DB;
120use project::{
121 ProjectPath,
122 debugger::breakpoint_store::{
123 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
124 },
125};
126
127pub use git::blame::BlameRenderer;
128pub use proposed_changes_editor::{
129 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
130};
131use smallvec::smallvec;
132use std::{cell::OnceCell, iter::Peekable};
133use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
134
135pub use lsp::CompletionContext;
136use lsp::{
137 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
138 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
139};
140
141use language::BufferSnapshot;
142pub use lsp_ext::lsp_tasks;
143use movement::TextLayoutDetails;
144pub use multi_buffer::{
145 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
146 RowInfo, ToOffset, ToPoint,
147};
148use multi_buffer::{
149 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
150 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
151};
152use parking_lot::Mutex;
153use project::{
154 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
155 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
156 TaskSourceKind,
157 debugger::breakpoint_store::Breakpoint,
158 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
159 project_settings::{GitGutterSetting, ProjectSettings},
160};
161use rand::prelude::*;
162use rpc::{ErrorExt, proto::*};
163use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
164use selections_collection::{
165 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
166};
167use serde::{Deserialize, Serialize};
168use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
169use smallvec::SmallVec;
170use snippet::Snippet;
171use std::sync::Arc;
172use std::{
173 any::TypeId,
174 borrow::Cow,
175 cell::RefCell,
176 cmp::{self, Ordering, Reverse},
177 mem,
178 num::NonZeroU32,
179 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
180 path::{Path, PathBuf},
181 rc::Rc,
182 time::{Duration, Instant},
183};
184pub use sum_tree::Bias;
185use sum_tree::TreeMap;
186use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
187use theme::{
188 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
189 observe_buffer_font_size_adjustment,
190};
191use ui::{
192 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
193 IconSize, Key, Tooltip, h_flex, prelude::*,
194};
195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
196use workspace::{
197 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
198 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
199 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
200 item::{ItemHandle, PreviewTabsSettings},
201 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
202 searchable::SearchEvent,
203};
204
205use crate::hover_links::{find_url, find_url_from_range};
206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
207
208pub const FILE_HEADER_HEIGHT: u32 = 2;
209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
212const MAX_LINE_LEN: usize = 1024;
213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
216#[doc(hidden)]
217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
218const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
219
220pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
221pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
222pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
223
224pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
225pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
226pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
227
228pub type RenderDiffHunkControlsFn = Arc<
229 dyn Fn(
230 u32,
231 &DiffHunkStatus,
232 Range<Anchor>,
233 bool,
234 Pixels,
235 &Entity<Editor>,
236 &mut Window,
237 &mut App,
238 ) -> AnyElement,
239>;
240
241const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
242 alt: true,
243 shift: true,
244 control: false,
245 platform: false,
246 function: false,
247};
248
249#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
250pub enum InlayId {
251 InlineCompletion(usize),
252 Hint(usize),
253}
254
255impl InlayId {
256 fn id(&self) -> usize {
257 match self {
258 Self::InlineCompletion(id) => *id,
259 Self::Hint(id) => *id,
260 }
261 }
262}
263
264pub enum DebugCurrentRowHighlight {}
265enum DocumentHighlightRead {}
266enum DocumentHighlightWrite {}
267enum InputComposition {}
268enum SelectedTextHighlight {}
269
270#[derive(Debug, Copy, Clone, PartialEq, Eq)]
271pub enum Navigated {
272 Yes,
273 No,
274}
275
276impl Navigated {
277 pub fn from_bool(yes: bool) -> Navigated {
278 if yes { Navigated::Yes } else { Navigated::No }
279 }
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
283enum DisplayDiffHunk {
284 Folded {
285 display_row: DisplayRow,
286 },
287 Unfolded {
288 is_created_file: bool,
289 diff_base_byte_range: Range<usize>,
290 display_row_range: Range<DisplayRow>,
291 multi_buffer_range: Range<Anchor>,
292 status: DiffHunkStatus,
293 },
294}
295
296pub enum HideMouseCursorOrigin {
297 TypingAction,
298 MovementAction,
299}
300
301pub fn init_settings(cx: &mut App) {
302 EditorSettings::register(cx);
303}
304
305pub fn init(cx: &mut App) {
306 init_settings(cx);
307
308 cx.set_global(GlobalBlameRenderer(Arc::new(())));
309
310 workspace::register_project_item::<Editor>(cx);
311 workspace::FollowableViewRegistry::register::<Editor>(cx);
312 workspace::register_serializable_item::<Editor>(cx);
313
314 cx.observe_new(
315 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
316 workspace.register_action(Editor::new_file);
317 workspace.register_action(Editor::new_file_vertical);
318 workspace.register_action(Editor::new_file_horizontal);
319 workspace.register_action(Editor::cancel_language_server_work);
320 },
321 )
322 .detach();
323
324 cx.on_action(move |_: &workspace::NewFile, cx| {
325 let app_state = workspace::AppState::global(cx);
326 if let Some(app_state) = app_state.upgrade() {
327 workspace::open_new(
328 Default::default(),
329 app_state,
330 cx,
331 |workspace, window, cx| {
332 Editor::new_file(workspace, &Default::default(), window, cx)
333 },
334 )
335 .detach();
336 }
337 });
338 cx.on_action(move |_: &workspace::NewWindow, cx| {
339 let app_state = workspace::AppState::global(cx);
340 if let Some(app_state) = app_state.upgrade() {
341 workspace::open_new(
342 Default::default(),
343 app_state,
344 cx,
345 |workspace, window, cx| {
346 cx.activate(true);
347 Editor::new_file(workspace, &Default::default(), window, cx)
348 },
349 )
350 .detach();
351 }
352 });
353}
354
355pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
356 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
357}
358
359pub trait DiagnosticRenderer {
360 fn render_group(
361 &self,
362 diagnostic_group: Vec<DiagnosticEntry<Point>>,
363 buffer_id: BufferId,
364 snapshot: EditorSnapshot,
365 editor: WeakEntity<Editor>,
366 cx: &mut App,
367 ) -> Vec<BlockProperties<Anchor>>;
368}
369
370pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
371
372impl gpui::Global for GlobalDiagnosticRenderer {}
373pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
374 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
375}
376
377pub struct SearchWithinRange;
378
379trait InvalidationRegion {
380 fn ranges(&self) -> &[Range<Anchor>];
381}
382
383#[derive(Clone, Debug, PartialEq)]
384pub enum SelectPhase {
385 Begin {
386 position: DisplayPoint,
387 add: bool,
388 click_count: usize,
389 },
390 BeginColumnar {
391 position: DisplayPoint,
392 reset: bool,
393 goal_column: u32,
394 },
395 Extend {
396 position: DisplayPoint,
397 click_count: usize,
398 },
399 Update {
400 position: DisplayPoint,
401 goal_column: u32,
402 scroll_delta: gpui::Point<f32>,
403 },
404 End,
405}
406
407#[derive(Clone, Debug)]
408pub enum SelectMode {
409 Character,
410 Word(Range<Anchor>),
411 Line(Range<Anchor>),
412 All,
413}
414
415#[derive(Copy, Clone, PartialEq, Eq, Debug)]
416pub enum EditorMode {
417 SingleLine {
418 auto_width: bool,
419 },
420 AutoHeight {
421 max_lines: usize,
422 },
423 Full {
424 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
425 scale_ui_elements_with_buffer_font_size: bool,
426 /// When set to `true`, the editor will render a background for the active line.
427 show_active_line_background: bool,
428 },
429}
430
431impl EditorMode {
432 pub fn full() -> Self {
433 Self::Full {
434 scale_ui_elements_with_buffer_font_size: true,
435 show_active_line_background: true,
436 }
437 }
438
439 pub fn is_full(&self) -> bool {
440 matches!(self, Self::Full { .. })
441 }
442}
443
444#[derive(Copy, Clone, Debug)]
445pub enum SoftWrap {
446 /// Prefer not to wrap at all.
447 ///
448 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
449 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
450 GitDiff,
451 /// Prefer a single line generally, unless an overly long line is encountered.
452 None,
453 /// Soft wrap lines that exceed the editor width.
454 EditorWidth,
455 /// Soft wrap lines at the preferred line length.
456 Column(u32),
457 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
458 Bounded(u32),
459}
460
461#[derive(Clone)]
462pub struct EditorStyle {
463 pub background: Hsla,
464 pub local_player: PlayerColor,
465 pub text: TextStyle,
466 pub scrollbar_width: Pixels,
467 pub syntax: Arc<SyntaxTheme>,
468 pub status: StatusColors,
469 pub inlay_hints_style: HighlightStyle,
470 pub inline_completion_styles: InlineCompletionStyles,
471 pub unnecessary_code_fade: f32,
472}
473
474impl Default for EditorStyle {
475 fn default() -> Self {
476 Self {
477 background: Hsla::default(),
478 local_player: PlayerColor::default(),
479 text: TextStyle::default(),
480 scrollbar_width: Pixels::default(),
481 syntax: Default::default(),
482 // HACK: Status colors don't have a real default.
483 // We should look into removing the status colors from the editor
484 // style and retrieve them directly from the theme.
485 status: StatusColors::dark(),
486 inlay_hints_style: HighlightStyle::default(),
487 inline_completion_styles: InlineCompletionStyles {
488 insertion: HighlightStyle::default(),
489 whitespace: HighlightStyle::default(),
490 },
491 unnecessary_code_fade: Default::default(),
492 }
493 }
494}
495
496pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
497 let show_background = language_settings::language_settings(None, None, cx)
498 .inlay_hints
499 .show_background;
500
501 HighlightStyle {
502 color: Some(cx.theme().status().hint),
503 background_color: show_background.then(|| cx.theme().status().hint_background),
504 ..HighlightStyle::default()
505 }
506}
507
508pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
509 InlineCompletionStyles {
510 insertion: HighlightStyle {
511 color: Some(cx.theme().status().predictive),
512 ..HighlightStyle::default()
513 },
514 whitespace: HighlightStyle {
515 background_color: Some(cx.theme().status().created_background),
516 ..HighlightStyle::default()
517 },
518 }
519}
520
521type CompletionId = usize;
522
523pub(crate) enum EditDisplayMode {
524 TabAccept,
525 DiffPopover,
526 Inline,
527}
528
529enum InlineCompletion {
530 Edit {
531 edits: Vec<(Range<Anchor>, String)>,
532 edit_preview: Option<EditPreview>,
533 display_mode: EditDisplayMode,
534 snapshot: BufferSnapshot,
535 },
536 Move {
537 target: Anchor,
538 snapshot: BufferSnapshot,
539 },
540}
541
542struct InlineCompletionState {
543 inlay_ids: Vec<InlayId>,
544 completion: InlineCompletion,
545 completion_id: Option<SharedString>,
546 invalidation_range: Range<Anchor>,
547}
548
549enum EditPredictionSettings {
550 Disabled,
551 Enabled {
552 show_in_menu: bool,
553 preview_requires_modifier: bool,
554 },
555}
556
557enum InlineCompletionHighlight {}
558
559#[derive(Debug, Clone)]
560struct InlineDiagnostic {
561 message: SharedString,
562 group_id: usize,
563 is_primary: bool,
564 start: Point,
565 severity: DiagnosticSeverity,
566}
567
568pub enum MenuInlineCompletionsPolicy {
569 Never,
570 ByProvider,
571}
572
573pub enum EditPredictionPreview {
574 /// Modifier is not pressed
575 Inactive { released_too_fast: bool },
576 /// Modifier pressed
577 Active {
578 since: Instant,
579 previous_scroll_position: Option<ScrollAnchor>,
580 },
581}
582
583impl EditPredictionPreview {
584 pub fn released_too_fast(&self) -> bool {
585 match self {
586 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
587 EditPredictionPreview::Active { .. } => false,
588 }
589 }
590
591 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
592 if let EditPredictionPreview::Active {
593 previous_scroll_position,
594 ..
595 } = self
596 {
597 *previous_scroll_position = scroll_position;
598 }
599 }
600}
601
602pub struct ContextMenuOptions {
603 pub min_entries_visible: usize,
604 pub max_entries_visible: usize,
605 pub placement: Option<ContextMenuPlacement>,
606}
607
608#[derive(Debug, Clone, PartialEq, Eq)]
609pub enum ContextMenuPlacement {
610 Above,
611 Below,
612}
613
614#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
615struct EditorActionId(usize);
616
617impl EditorActionId {
618 pub fn post_inc(&mut self) -> Self {
619 let answer = self.0;
620
621 *self = Self(answer + 1);
622
623 Self(answer)
624 }
625}
626
627// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
628// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
629
630type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
631type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
632
633#[derive(Default)]
634struct ScrollbarMarkerState {
635 scrollbar_size: Size<Pixels>,
636 dirty: bool,
637 markers: Arc<[PaintQuad]>,
638 pending_refresh: Option<Task<Result<()>>>,
639}
640
641impl ScrollbarMarkerState {
642 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
643 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
644 }
645}
646
647#[derive(Clone, Debug)]
648struct RunnableTasks {
649 templates: Vec<(TaskSourceKind, TaskTemplate)>,
650 offset: multi_buffer::Anchor,
651 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
652 column: u32,
653 // Values of all named captures, including those starting with '_'
654 extra_variables: HashMap<String, String>,
655 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
656 context_range: Range<BufferOffset>,
657}
658
659impl RunnableTasks {
660 fn resolve<'a>(
661 &'a self,
662 cx: &'a task::TaskContext,
663 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
664 self.templates.iter().filter_map(|(kind, template)| {
665 template
666 .resolve_task(&kind.to_id_base(), cx)
667 .map(|task| (kind.clone(), task))
668 })
669 }
670}
671
672#[derive(Clone)]
673struct ResolvedTasks {
674 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
675 position: Anchor,
676}
677
678#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
679struct BufferOffset(usize);
680
681// Addons allow storing per-editor state in other crates (e.g. Vim)
682pub trait Addon: 'static {
683 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
684
685 fn render_buffer_header_controls(
686 &self,
687 _: &ExcerptInfo,
688 _: &Window,
689 _: &App,
690 ) -> Option<AnyElement> {
691 None
692 }
693
694 fn to_any(&self) -> &dyn std::any::Any;
695}
696
697/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
698///
699/// See the [module level documentation](self) for more information.
700pub struct Editor {
701 focus_handle: FocusHandle,
702 last_focused_descendant: Option<WeakFocusHandle>,
703 /// The text buffer being edited
704 buffer: Entity<MultiBuffer>,
705 /// Map of how text in the buffer should be displayed.
706 /// Handles soft wraps, folds, fake inlay text insertions, etc.
707 pub display_map: Entity<DisplayMap>,
708 pub selections: SelectionsCollection,
709 pub scroll_manager: ScrollManager,
710 /// When inline assist editors are linked, they all render cursors because
711 /// typing enters text into each of them, even the ones that aren't focused.
712 pub(crate) show_cursor_when_unfocused: bool,
713 columnar_selection_tail: Option<Anchor>,
714 add_selections_state: Option<AddSelectionsState>,
715 select_next_state: Option<SelectNextState>,
716 select_prev_state: Option<SelectNextState>,
717 selection_history: SelectionHistory,
718 autoclose_regions: Vec<AutocloseRegion>,
719 snippet_stack: InvalidationStack<SnippetState>,
720 select_syntax_node_history: SelectSyntaxNodeHistory,
721 ime_transaction: Option<TransactionId>,
722 active_diagnostics: ActiveDiagnostic,
723 show_inline_diagnostics: bool,
724 inline_diagnostics_update: Task<()>,
725 inline_diagnostics_enabled: bool,
726 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
727 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
728 hard_wrap: Option<usize>,
729
730 // TODO: make this a access method
731 pub project: Option<Entity<Project>>,
732 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
733 completion_provider: Option<Box<dyn CompletionProvider>>,
734 collaboration_hub: Option<Box<dyn CollaborationHub>>,
735 blink_manager: Entity<BlinkManager>,
736 show_cursor_names: bool,
737 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
738 pub show_local_selections: bool,
739 mode: EditorMode,
740 show_breadcrumbs: bool,
741 show_gutter: bool,
742 show_scrollbars: bool,
743 show_line_numbers: Option<bool>,
744 use_relative_line_numbers: Option<bool>,
745 show_git_diff_gutter: Option<bool>,
746 show_code_actions: Option<bool>,
747 show_runnables: Option<bool>,
748 show_breakpoints: Option<bool>,
749 show_wrap_guides: Option<bool>,
750 show_indent_guides: Option<bool>,
751 placeholder_text: Option<Arc<str>>,
752 highlight_order: usize,
753 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
754 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
755 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
756 scrollbar_marker_state: ScrollbarMarkerState,
757 active_indent_guides_state: ActiveIndentGuidesState,
758 nav_history: Option<ItemNavHistory>,
759 context_menu: RefCell<Option<CodeContextMenu>>,
760 context_menu_options: Option<ContextMenuOptions>,
761 mouse_context_menu: Option<MouseContextMenu>,
762 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
763 signature_help_state: SignatureHelpState,
764 auto_signature_help: Option<bool>,
765 find_all_references_task_sources: Vec<Anchor>,
766 next_completion_id: CompletionId,
767 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
768 code_actions_task: Option<Task<Result<()>>>,
769 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
770 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
771 document_highlights_task: Option<Task<()>>,
772 linked_editing_range_task: Option<Task<Option<()>>>,
773 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
774 pending_rename: Option<RenameState>,
775 searchable: bool,
776 cursor_shape: CursorShape,
777 current_line_highlight: Option<CurrentLineHighlight>,
778 collapse_matches: bool,
779 autoindent_mode: Option<AutoindentMode>,
780 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
781 input_enabled: bool,
782 use_modal_editing: bool,
783 read_only: bool,
784 leader_peer_id: Option<PeerId>,
785 remote_id: Option<ViewId>,
786 hover_state: HoverState,
787 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
788 gutter_hovered: bool,
789 hovered_link_state: Option<HoveredLinkState>,
790 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
791 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
792 active_inline_completion: Option<InlineCompletionState>,
793 /// Used to prevent flickering as the user types while the menu is open
794 stale_inline_completion_in_menu: Option<InlineCompletionState>,
795 edit_prediction_settings: EditPredictionSettings,
796 inline_completions_hidden_for_vim_mode: bool,
797 show_inline_completions_override: Option<bool>,
798 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
799 edit_prediction_preview: EditPredictionPreview,
800 edit_prediction_indent_conflict: bool,
801 edit_prediction_requires_modifier_in_indent_conflict: bool,
802 inlay_hint_cache: InlayHintCache,
803 next_inlay_id: usize,
804 _subscriptions: Vec<Subscription>,
805 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
806 gutter_dimensions: GutterDimensions,
807 style: Option<EditorStyle>,
808 text_style_refinement: Option<TextStyleRefinement>,
809 next_editor_action_id: EditorActionId,
810 editor_actions:
811 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
812 use_autoclose: bool,
813 use_auto_surround: bool,
814 auto_replace_emoji_shortcode: bool,
815 jsx_tag_auto_close_enabled_in_any_buffer: bool,
816 show_git_blame_gutter: bool,
817 show_git_blame_inline: bool,
818 show_git_blame_inline_delay_task: Option<Task<()>>,
819 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
820 git_blame_inline_enabled: bool,
821 render_diff_hunk_controls: RenderDiffHunkControlsFn,
822 serialize_dirty_buffers: bool,
823 show_selection_menu: Option<bool>,
824 blame: Option<Entity<GitBlame>>,
825 blame_subscription: Option<Subscription>,
826 custom_context_menu: Option<
827 Box<
828 dyn 'static
829 + Fn(
830 &mut Self,
831 DisplayPoint,
832 &mut Window,
833 &mut Context<Self>,
834 ) -> Option<Entity<ui::ContextMenu>>,
835 >,
836 >,
837 last_bounds: Option<Bounds<Pixels>>,
838 last_position_map: Option<Rc<PositionMap>>,
839 expect_bounds_change: Option<Bounds<Pixels>>,
840 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
841 tasks_update_task: Option<Task<()>>,
842 breakpoint_store: Option<Entity<BreakpointStore>>,
843 /// Allow's a user to create a breakpoint by selecting this indicator
844 /// It should be None while a user is not hovering over the gutter
845 /// Otherwise it represents the point that the breakpoint will be shown
846 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
847 in_project_search: bool,
848 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
849 breadcrumb_header: Option<String>,
850 focused_block: Option<FocusedBlock>,
851 next_scroll_position: NextScrollCursorCenterTopBottom,
852 addons: HashMap<TypeId, Box<dyn Addon>>,
853 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
854 load_diff_task: Option<Shared<Task<()>>>,
855 selection_mark_mode: bool,
856 toggle_fold_multiple_buffers: Task<()>,
857 _scroll_cursor_center_top_bottom_task: Task<()>,
858 serialize_selections: Task<()>,
859 serialize_folds: Task<()>,
860 mouse_cursor_hidden: bool,
861 hide_mouse_mode: HideMouseMode,
862}
863
864#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
865enum NextScrollCursorCenterTopBottom {
866 #[default]
867 Center,
868 Top,
869 Bottom,
870}
871
872impl NextScrollCursorCenterTopBottom {
873 fn next(&self) -> Self {
874 match self {
875 Self::Center => Self::Top,
876 Self::Top => Self::Bottom,
877 Self::Bottom => Self::Center,
878 }
879 }
880}
881
882#[derive(Clone)]
883pub struct EditorSnapshot {
884 pub mode: EditorMode,
885 show_gutter: bool,
886 show_line_numbers: Option<bool>,
887 show_git_diff_gutter: Option<bool>,
888 show_code_actions: Option<bool>,
889 show_runnables: Option<bool>,
890 show_breakpoints: Option<bool>,
891 git_blame_gutter_max_author_length: Option<usize>,
892 pub display_snapshot: DisplaySnapshot,
893 pub placeholder_text: Option<Arc<str>>,
894 is_focused: bool,
895 scroll_anchor: ScrollAnchor,
896 ongoing_scroll: OngoingScroll,
897 current_line_highlight: CurrentLineHighlight,
898 gutter_hovered: bool,
899}
900
901#[derive(Default, Debug, Clone, Copy)]
902pub struct GutterDimensions {
903 pub left_padding: Pixels,
904 pub right_padding: Pixels,
905 pub width: Pixels,
906 pub margin: Pixels,
907 pub git_blame_entries_width: Option<Pixels>,
908}
909
910impl GutterDimensions {
911 /// The full width of the space taken up by the gutter.
912 pub fn full_width(&self) -> Pixels {
913 self.margin + self.width
914 }
915
916 /// The width of the space reserved for the fold indicators,
917 /// use alongside 'justify_end' and `gutter_width` to
918 /// right align content with the line numbers
919 pub fn fold_area_width(&self) -> Pixels {
920 self.margin + self.right_padding
921 }
922}
923
924#[derive(Debug)]
925pub struct RemoteSelection {
926 pub replica_id: ReplicaId,
927 pub selection: Selection<Anchor>,
928 pub cursor_shape: CursorShape,
929 pub peer_id: PeerId,
930 pub line_mode: bool,
931 pub participant_index: Option<ParticipantIndex>,
932 pub user_name: Option<SharedString>,
933}
934
935#[derive(Clone, Debug)]
936struct SelectionHistoryEntry {
937 selections: Arc<[Selection<Anchor>]>,
938 select_next_state: Option<SelectNextState>,
939 select_prev_state: Option<SelectNextState>,
940 add_selections_state: Option<AddSelectionsState>,
941}
942
943enum SelectionHistoryMode {
944 Normal,
945 Undoing,
946 Redoing,
947}
948
949#[derive(Clone, PartialEq, Eq, Hash)]
950struct HoveredCursor {
951 replica_id: u16,
952 selection_id: usize,
953}
954
955impl Default for SelectionHistoryMode {
956 fn default() -> Self {
957 Self::Normal
958 }
959}
960
961#[derive(Default)]
962struct SelectionHistory {
963 #[allow(clippy::type_complexity)]
964 selections_by_transaction:
965 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
966 mode: SelectionHistoryMode,
967 undo_stack: VecDeque<SelectionHistoryEntry>,
968 redo_stack: VecDeque<SelectionHistoryEntry>,
969}
970
971impl SelectionHistory {
972 fn insert_transaction(
973 &mut self,
974 transaction_id: TransactionId,
975 selections: Arc<[Selection<Anchor>]>,
976 ) {
977 self.selections_by_transaction
978 .insert(transaction_id, (selections, None));
979 }
980
981 #[allow(clippy::type_complexity)]
982 fn transaction(
983 &self,
984 transaction_id: TransactionId,
985 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
986 self.selections_by_transaction.get(&transaction_id)
987 }
988
989 #[allow(clippy::type_complexity)]
990 fn transaction_mut(
991 &mut self,
992 transaction_id: TransactionId,
993 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
994 self.selections_by_transaction.get_mut(&transaction_id)
995 }
996
997 fn push(&mut self, entry: SelectionHistoryEntry) {
998 if !entry.selections.is_empty() {
999 match self.mode {
1000 SelectionHistoryMode::Normal => {
1001 self.push_undo(entry);
1002 self.redo_stack.clear();
1003 }
1004 SelectionHistoryMode::Undoing => self.push_redo(entry),
1005 SelectionHistoryMode::Redoing => self.push_undo(entry),
1006 }
1007 }
1008 }
1009
1010 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1011 if self
1012 .undo_stack
1013 .back()
1014 .map_or(true, |e| e.selections != entry.selections)
1015 {
1016 self.undo_stack.push_back(entry);
1017 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1018 self.undo_stack.pop_front();
1019 }
1020 }
1021 }
1022
1023 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1024 if self
1025 .redo_stack
1026 .back()
1027 .map_or(true, |e| e.selections != entry.selections)
1028 {
1029 self.redo_stack.push_back(entry);
1030 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1031 self.redo_stack.pop_front();
1032 }
1033 }
1034 }
1035}
1036
1037struct RowHighlight {
1038 index: usize,
1039 range: Range<Anchor>,
1040 color: Hsla,
1041 should_autoscroll: bool,
1042}
1043
1044#[derive(Clone, Debug)]
1045struct AddSelectionsState {
1046 above: bool,
1047 stack: Vec<usize>,
1048}
1049
1050#[derive(Clone)]
1051struct SelectNextState {
1052 query: AhoCorasick,
1053 wordwise: bool,
1054 done: bool,
1055}
1056
1057impl std::fmt::Debug for SelectNextState {
1058 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1059 f.debug_struct(std::any::type_name::<Self>())
1060 .field("wordwise", &self.wordwise)
1061 .field("done", &self.done)
1062 .finish()
1063 }
1064}
1065
1066#[derive(Debug)]
1067struct AutocloseRegion {
1068 selection_id: usize,
1069 range: Range<Anchor>,
1070 pair: BracketPair,
1071}
1072
1073#[derive(Debug)]
1074struct SnippetState {
1075 ranges: Vec<Vec<Range<Anchor>>>,
1076 active_index: usize,
1077 choices: Vec<Option<Vec<String>>>,
1078}
1079
1080#[doc(hidden)]
1081pub struct RenameState {
1082 pub range: Range<Anchor>,
1083 pub old_name: Arc<str>,
1084 pub editor: Entity<Editor>,
1085 block_id: CustomBlockId,
1086}
1087
1088struct InvalidationStack<T>(Vec<T>);
1089
1090struct RegisteredInlineCompletionProvider {
1091 provider: Arc<dyn InlineCompletionProviderHandle>,
1092 _subscription: Subscription,
1093}
1094
1095#[derive(Debug, PartialEq, Eq)]
1096pub struct ActiveDiagnosticGroup {
1097 pub active_range: Range<Anchor>,
1098 pub active_message: String,
1099 pub group_id: usize,
1100 pub blocks: HashSet<CustomBlockId>,
1101}
1102
1103#[derive(Debug, PartialEq, Eq)]
1104#[allow(clippy::large_enum_variant)]
1105pub(crate) enum ActiveDiagnostic {
1106 None,
1107 All,
1108 Group(ActiveDiagnosticGroup),
1109}
1110
1111#[derive(Serialize, Deserialize, Clone, Debug)]
1112pub struct ClipboardSelection {
1113 /// The number of bytes in this selection.
1114 pub len: usize,
1115 /// Whether this was a full-line selection.
1116 pub is_entire_line: bool,
1117 /// The indentation of the first line when this content was originally copied.
1118 pub first_line_indent: u32,
1119}
1120
1121// selections, scroll behavior, was newest selection reversed
1122type SelectSyntaxNodeHistoryState = (
1123 Box<[Selection<usize>]>,
1124 SelectSyntaxNodeScrollBehavior,
1125 bool,
1126);
1127
1128#[derive(Default)]
1129struct SelectSyntaxNodeHistory {
1130 stack: Vec<SelectSyntaxNodeHistoryState>,
1131 // disable temporarily to allow changing selections without losing the stack
1132 pub disable_clearing: bool,
1133}
1134
1135impl SelectSyntaxNodeHistory {
1136 pub fn try_clear(&mut self) {
1137 if !self.disable_clearing {
1138 self.stack.clear();
1139 }
1140 }
1141
1142 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1143 self.stack.push(selection);
1144 }
1145
1146 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1147 self.stack.pop()
1148 }
1149}
1150
1151enum SelectSyntaxNodeScrollBehavior {
1152 CursorTop,
1153 FitSelection,
1154 CursorBottom,
1155}
1156
1157#[derive(Debug)]
1158pub(crate) struct NavigationData {
1159 cursor_anchor: Anchor,
1160 cursor_position: Point,
1161 scroll_anchor: ScrollAnchor,
1162 scroll_top_row: u32,
1163}
1164
1165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1166pub enum GotoDefinitionKind {
1167 Symbol,
1168 Declaration,
1169 Type,
1170 Implementation,
1171}
1172
1173#[derive(Debug, Clone)]
1174enum InlayHintRefreshReason {
1175 ModifiersChanged(bool),
1176 Toggle(bool),
1177 SettingsChange(InlayHintSettings),
1178 NewLinesShown,
1179 BufferEdited(HashSet<Arc<Language>>),
1180 RefreshRequested,
1181 ExcerptsRemoved(Vec<ExcerptId>),
1182}
1183
1184impl InlayHintRefreshReason {
1185 fn description(&self) -> &'static str {
1186 match self {
1187 Self::ModifiersChanged(_) => "modifiers changed",
1188 Self::Toggle(_) => "toggle",
1189 Self::SettingsChange(_) => "settings change",
1190 Self::NewLinesShown => "new lines shown",
1191 Self::BufferEdited(_) => "buffer edited",
1192 Self::RefreshRequested => "refresh requested",
1193 Self::ExcerptsRemoved(_) => "excerpts removed",
1194 }
1195 }
1196}
1197
1198pub enum FormatTarget {
1199 Buffers,
1200 Ranges(Vec<Range<MultiBufferPoint>>),
1201}
1202
1203pub(crate) struct FocusedBlock {
1204 id: BlockId,
1205 focus_handle: WeakFocusHandle,
1206}
1207
1208#[derive(Clone)]
1209enum JumpData {
1210 MultiBufferRow {
1211 row: MultiBufferRow,
1212 line_offset_from_top: u32,
1213 },
1214 MultiBufferPoint {
1215 excerpt_id: ExcerptId,
1216 position: Point,
1217 anchor: text::Anchor,
1218 line_offset_from_top: u32,
1219 },
1220}
1221
1222pub enum MultibufferSelectionMode {
1223 First,
1224 All,
1225}
1226
1227#[derive(Clone, Copy, Debug, Default)]
1228pub struct RewrapOptions {
1229 pub override_language_settings: bool,
1230 pub preserve_existing_whitespace: bool,
1231}
1232
1233impl Editor {
1234 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1235 let buffer = cx.new(|cx| Buffer::local("", cx));
1236 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1237 Self::new(
1238 EditorMode::SingleLine { auto_width: false },
1239 buffer,
1240 None,
1241 window,
1242 cx,
1243 )
1244 }
1245
1246 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1247 let buffer = cx.new(|cx| Buffer::local("", cx));
1248 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1249 Self::new(EditorMode::full(), buffer, None, window, cx)
1250 }
1251
1252 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1253 let buffer = cx.new(|cx| Buffer::local("", cx));
1254 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1255 Self::new(
1256 EditorMode::SingleLine { auto_width: true },
1257 buffer,
1258 None,
1259 window,
1260 cx,
1261 )
1262 }
1263
1264 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1265 let buffer = cx.new(|cx| Buffer::local("", cx));
1266 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1267 Self::new(
1268 EditorMode::AutoHeight { max_lines },
1269 buffer,
1270 None,
1271 window,
1272 cx,
1273 )
1274 }
1275
1276 pub fn for_buffer(
1277 buffer: Entity<Buffer>,
1278 project: Option<Entity<Project>>,
1279 window: &mut Window,
1280 cx: &mut Context<Self>,
1281 ) -> Self {
1282 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1283 Self::new(EditorMode::full(), buffer, project, window, cx)
1284 }
1285
1286 pub fn for_multibuffer(
1287 buffer: Entity<MultiBuffer>,
1288 project: Option<Entity<Project>>,
1289 window: &mut Window,
1290 cx: &mut Context<Self>,
1291 ) -> Self {
1292 Self::new(EditorMode::full(), buffer, project, window, cx)
1293 }
1294
1295 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1296 let mut clone = Self::new(
1297 self.mode,
1298 self.buffer.clone(),
1299 self.project.clone(),
1300 window,
1301 cx,
1302 );
1303 self.display_map.update(cx, |display_map, cx| {
1304 let snapshot = display_map.snapshot(cx);
1305 clone.display_map.update(cx, |display_map, cx| {
1306 display_map.set_state(&snapshot, cx);
1307 });
1308 });
1309 clone.folds_did_change(cx);
1310 clone.selections.clone_state(&self.selections);
1311 clone.scroll_manager.clone_state(&self.scroll_manager);
1312 clone.searchable = self.searchable;
1313 clone.read_only = self.read_only;
1314 clone
1315 }
1316
1317 pub fn new(
1318 mode: EditorMode,
1319 buffer: Entity<MultiBuffer>,
1320 project: Option<Entity<Project>>,
1321 window: &mut Window,
1322 cx: &mut Context<Self>,
1323 ) -> Self {
1324 let style = window.text_style();
1325 let font_size = style.font_size.to_pixels(window.rem_size());
1326 let editor = cx.entity().downgrade();
1327 let fold_placeholder = FoldPlaceholder {
1328 constrain_width: true,
1329 render: Arc::new(move |fold_id, fold_range, cx| {
1330 let editor = editor.clone();
1331 div()
1332 .id(fold_id)
1333 .bg(cx.theme().colors().ghost_element_background)
1334 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1335 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1336 .rounded_xs()
1337 .size_full()
1338 .cursor_pointer()
1339 .child("⋯")
1340 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1341 .on_click(move |_, _window, cx| {
1342 editor
1343 .update(cx, |editor, cx| {
1344 editor.unfold_ranges(
1345 &[fold_range.start..fold_range.end],
1346 true,
1347 false,
1348 cx,
1349 );
1350 cx.stop_propagation();
1351 })
1352 .ok();
1353 })
1354 .into_any()
1355 }),
1356 merge_adjacent: true,
1357 ..Default::default()
1358 };
1359 let display_map = cx.new(|cx| {
1360 DisplayMap::new(
1361 buffer.clone(),
1362 style.font(),
1363 font_size,
1364 None,
1365 FILE_HEADER_HEIGHT,
1366 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1367 fold_placeholder,
1368 cx,
1369 )
1370 });
1371
1372 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1373
1374 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1375
1376 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1377 .then(|| language_settings::SoftWrap::None);
1378
1379 let mut project_subscriptions = Vec::new();
1380 if mode.is_full() {
1381 if let Some(project) = project.as_ref() {
1382 project_subscriptions.push(cx.subscribe_in(
1383 project,
1384 window,
1385 |editor, _, event, window, cx| match event {
1386 project::Event::RefreshCodeLens => {
1387 // we always query lens with actions, without storing them, always refreshing them
1388 }
1389 project::Event::RefreshInlayHints => {
1390 editor
1391 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1392 }
1393 project::Event::SnippetEdit(id, snippet_edits) => {
1394 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1395 let focus_handle = editor.focus_handle(cx);
1396 if focus_handle.is_focused(window) {
1397 let snapshot = buffer.read(cx).snapshot();
1398 for (range, snippet) in snippet_edits {
1399 let editor_range =
1400 language::range_from_lsp(*range).to_offset(&snapshot);
1401 editor
1402 .insert_snippet(
1403 &[editor_range],
1404 snippet.clone(),
1405 window,
1406 cx,
1407 )
1408 .ok();
1409 }
1410 }
1411 }
1412 }
1413 _ => {}
1414 },
1415 ));
1416 if let Some(task_inventory) = project
1417 .read(cx)
1418 .task_store()
1419 .read(cx)
1420 .task_inventory()
1421 .cloned()
1422 {
1423 project_subscriptions.push(cx.observe_in(
1424 &task_inventory,
1425 window,
1426 |editor, _, window, cx| {
1427 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1428 },
1429 ));
1430 };
1431
1432 project_subscriptions.push(cx.subscribe_in(
1433 &project.read(cx).breakpoint_store(),
1434 window,
1435 |editor, _, event, window, cx| match event {
1436 BreakpointStoreEvent::ActiveDebugLineChanged => {
1437 if editor.go_to_active_debug_line(window, cx) {
1438 cx.stop_propagation();
1439 }
1440 }
1441 _ => {}
1442 },
1443 ));
1444 }
1445 }
1446
1447 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1448
1449 let inlay_hint_settings =
1450 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1451 let focus_handle = cx.focus_handle();
1452 cx.on_focus(&focus_handle, window, Self::handle_focus)
1453 .detach();
1454 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1455 .detach();
1456 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1457 .detach();
1458 cx.on_blur(&focus_handle, window, Self::handle_blur)
1459 .detach();
1460
1461 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1462 Some(false)
1463 } else {
1464 None
1465 };
1466
1467 let breakpoint_store = match (mode, project.as_ref()) {
1468 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1469 _ => None,
1470 };
1471
1472 let mut code_action_providers = Vec::new();
1473 let mut load_uncommitted_diff = None;
1474 if let Some(project) = project.clone() {
1475 load_uncommitted_diff = Some(
1476 get_uncommitted_diff_for_buffer(
1477 &project,
1478 buffer.read(cx).all_buffers(),
1479 buffer.clone(),
1480 cx,
1481 )
1482 .shared(),
1483 );
1484 code_action_providers.push(Rc::new(project) as Rc<_>);
1485 }
1486
1487 let mut this = Self {
1488 focus_handle,
1489 show_cursor_when_unfocused: false,
1490 last_focused_descendant: None,
1491 buffer: buffer.clone(),
1492 display_map: display_map.clone(),
1493 selections,
1494 scroll_manager: ScrollManager::new(cx),
1495 columnar_selection_tail: None,
1496 add_selections_state: None,
1497 select_next_state: None,
1498 select_prev_state: None,
1499 selection_history: Default::default(),
1500 autoclose_regions: Default::default(),
1501 snippet_stack: Default::default(),
1502 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1503 ime_transaction: Default::default(),
1504 active_diagnostics: ActiveDiagnostic::None,
1505 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1506 inline_diagnostics_update: Task::ready(()),
1507 inline_diagnostics: Vec::new(),
1508 soft_wrap_mode_override,
1509 hard_wrap: None,
1510 completion_provider: project.clone().map(|project| Box::new(project) as _),
1511 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1512 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1513 project,
1514 blink_manager: blink_manager.clone(),
1515 show_local_selections: true,
1516 show_scrollbars: true,
1517 mode,
1518 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1519 show_gutter: mode.is_full(),
1520 show_line_numbers: None,
1521 use_relative_line_numbers: None,
1522 show_git_diff_gutter: None,
1523 show_code_actions: None,
1524 show_runnables: None,
1525 show_breakpoints: None,
1526 show_wrap_guides: None,
1527 show_indent_guides,
1528 placeholder_text: None,
1529 highlight_order: 0,
1530 highlighted_rows: HashMap::default(),
1531 background_highlights: Default::default(),
1532 gutter_highlights: TreeMap::default(),
1533 scrollbar_marker_state: ScrollbarMarkerState::default(),
1534 active_indent_guides_state: ActiveIndentGuidesState::default(),
1535 nav_history: None,
1536 context_menu: RefCell::new(None),
1537 context_menu_options: None,
1538 mouse_context_menu: None,
1539 completion_tasks: Default::default(),
1540 signature_help_state: SignatureHelpState::default(),
1541 auto_signature_help: None,
1542 find_all_references_task_sources: Vec::new(),
1543 next_completion_id: 0,
1544 next_inlay_id: 0,
1545 code_action_providers,
1546 available_code_actions: Default::default(),
1547 code_actions_task: Default::default(),
1548 quick_selection_highlight_task: Default::default(),
1549 debounced_selection_highlight_task: Default::default(),
1550 document_highlights_task: Default::default(),
1551 linked_editing_range_task: Default::default(),
1552 pending_rename: Default::default(),
1553 searchable: true,
1554 cursor_shape: EditorSettings::get_global(cx)
1555 .cursor_shape
1556 .unwrap_or_default(),
1557 current_line_highlight: None,
1558 autoindent_mode: Some(AutoindentMode::EachLine),
1559 collapse_matches: false,
1560 workspace: None,
1561 input_enabled: true,
1562 use_modal_editing: mode.is_full(),
1563 read_only: false,
1564 use_autoclose: true,
1565 use_auto_surround: true,
1566 auto_replace_emoji_shortcode: false,
1567 jsx_tag_auto_close_enabled_in_any_buffer: false,
1568 leader_peer_id: None,
1569 remote_id: None,
1570 hover_state: Default::default(),
1571 pending_mouse_down: None,
1572 hovered_link_state: Default::default(),
1573 edit_prediction_provider: None,
1574 active_inline_completion: None,
1575 stale_inline_completion_in_menu: None,
1576 edit_prediction_preview: EditPredictionPreview::Inactive {
1577 released_too_fast: false,
1578 },
1579 inline_diagnostics_enabled: mode.is_full(),
1580 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1581
1582 gutter_hovered: false,
1583 pixel_position_of_newest_cursor: None,
1584 last_bounds: None,
1585 last_position_map: None,
1586 expect_bounds_change: None,
1587 gutter_dimensions: GutterDimensions::default(),
1588 style: None,
1589 show_cursor_names: false,
1590 hovered_cursors: Default::default(),
1591 next_editor_action_id: EditorActionId::default(),
1592 editor_actions: Rc::default(),
1593 inline_completions_hidden_for_vim_mode: false,
1594 show_inline_completions_override: None,
1595 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1596 edit_prediction_settings: EditPredictionSettings::Disabled,
1597 edit_prediction_indent_conflict: false,
1598 edit_prediction_requires_modifier_in_indent_conflict: true,
1599 custom_context_menu: None,
1600 show_git_blame_gutter: false,
1601 show_git_blame_inline: false,
1602 show_selection_menu: None,
1603 show_git_blame_inline_delay_task: None,
1604 git_blame_inline_tooltip: None,
1605 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1606 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1607 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1608 .session
1609 .restore_unsaved_buffers,
1610 blame: None,
1611 blame_subscription: None,
1612 tasks: Default::default(),
1613
1614 breakpoint_store,
1615 gutter_breakpoint_indicator: (None, None),
1616 _subscriptions: vec![
1617 cx.observe(&buffer, Self::on_buffer_changed),
1618 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1619 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1620 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1621 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1622 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1623 cx.observe_window_activation(window, |editor, window, cx| {
1624 let active = window.is_window_active();
1625 editor.blink_manager.update(cx, |blink_manager, cx| {
1626 if active {
1627 blink_manager.enable(cx);
1628 } else {
1629 blink_manager.disable(cx);
1630 }
1631 });
1632 }),
1633 ],
1634 tasks_update_task: None,
1635 linked_edit_ranges: Default::default(),
1636 in_project_search: false,
1637 previous_search_ranges: None,
1638 breadcrumb_header: None,
1639 focused_block: None,
1640 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1641 addons: HashMap::default(),
1642 registered_buffers: HashMap::default(),
1643 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1644 selection_mark_mode: false,
1645 toggle_fold_multiple_buffers: Task::ready(()),
1646 serialize_selections: Task::ready(()),
1647 serialize_folds: Task::ready(()),
1648 text_style_refinement: None,
1649 load_diff_task: load_uncommitted_diff,
1650 mouse_cursor_hidden: false,
1651 hide_mouse_mode: EditorSettings::get_global(cx)
1652 .hide_mouse
1653 .unwrap_or_default(),
1654 };
1655 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1656 this._subscriptions
1657 .push(cx.observe(breakpoints, |_, _, cx| {
1658 cx.notify();
1659 }));
1660 }
1661 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1662 this._subscriptions.extend(project_subscriptions);
1663
1664 this._subscriptions.push(cx.subscribe_in(
1665 &cx.entity(),
1666 window,
1667 |editor, _, e: &EditorEvent, window, cx| {
1668 if let EditorEvent::SelectionsChanged { local } = e {
1669 if *local {
1670 let new_anchor = editor.scroll_manager.anchor();
1671 let snapshot = editor.snapshot(window, cx);
1672 editor.update_restoration_data(cx, move |data| {
1673 data.scroll_position = (
1674 new_anchor.top_row(&snapshot.buffer_snapshot),
1675 new_anchor.offset,
1676 );
1677 });
1678 }
1679 }
1680 },
1681 ));
1682
1683 this.end_selection(window, cx);
1684 this.scroll_manager.show_scrollbars(window, cx);
1685 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1686
1687 if mode.is_full() {
1688 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1689 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1690
1691 if this.git_blame_inline_enabled {
1692 this.git_blame_inline_enabled = true;
1693 this.start_git_blame_inline(false, window, cx);
1694 }
1695
1696 this.go_to_active_debug_line(window, cx);
1697
1698 if let Some(buffer) = buffer.read(cx).as_singleton() {
1699 if let Some(project) = this.project.as_ref() {
1700 let handle = project.update(cx, |project, cx| {
1701 project.register_buffer_with_language_servers(&buffer, cx)
1702 });
1703 this.registered_buffers
1704 .insert(buffer.read(cx).remote_id(), handle);
1705 }
1706 }
1707 }
1708
1709 this.report_editor_event("Editor Opened", None, cx);
1710 this
1711 }
1712
1713 pub fn deploy_mouse_context_menu(
1714 &mut self,
1715 position: gpui::Point<Pixels>,
1716 context_menu: Entity<ContextMenu>,
1717 window: &mut Window,
1718 cx: &mut Context<Self>,
1719 ) {
1720 self.mouse_context_menu = Some(MouseContextMenu::new(
1721 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1722 context_menu,
1723 None,
1724 window,
1725 cx,
1726 ));
1727 }
1728
1729 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1730 self.mouse_context_menu
1731 .as_ref()
1732 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1733 }
1734
1735 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1736 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1737 }
1738
1739 fn key_context_internal(
1740 &self,
1741 has_active_edit_prediction: bool,
1742 window: &Window,
1743 cx: &App,
1744 ) -> KeyContext {
1745 let mut key_context = KeyContext::new_with_defaults();
1746 key_context.add("Editor");
1747 let mode = match self.mode {
1748 EditorMode::SingleLine { .. } => "single_line",
1749 EditorMode::AutoHeight { .. } => "auto_height",
1750 EditorMode::Full { .. } => "full",
1751 };
1752
1753 if EditorSettings::jupyter_enabled(cx) {
1754 key_context.add("jupyter");
1755 }
1756
1757 key_context.set("mode", mode);
1758 if self.pending_rename.is_some() {
1759 key_context.add("renaming");
1760 }
1761
1762 match self.context_menu.borrow().as_ref() {
1763 Some(CodeContextMenu::Completions(_)) => {
1764 key_context.add("menu");
1765 key_context.add("showing_completions");
1766 }
1767 Some(CodeContextMenu::CodeActions(_)) => {
1768 key_context.add("menu");
1769 key_context.add("showing_code_actions")
1770 }
1771 None => {}
1772 }
1773
1774 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1775 if !self.focus_handle(cx).contains_focused(window, cx)
1776 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1777 {
1778 for addon in self.addons.values() {
1779 addon.extend_key_context(&mut key_context, cx)
1780 }
1781 }
1782
1783 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1784 if let Some(extension) = singleton_buffer
1785 .read(cx)
1786 .file()
1787 .and_then(|file| file.path().extension()?.to_str())
1788 {
1789 key_context.set("extension", extension.to_string());
1790 }
1791 } else {
1792 key_context.add("multibuffer");
1793 }
1794
1795 if has_active_edit_prediction {
1796 if self.edit_prediction_in_conflict() {
1797 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1798 } else {
1799 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1800 key_context.add("copilot_suggestion");
1801 }
1802 }
1803
1804 if self.selection_mark_mode {
1805 key_context.add("selection_mode");
1806 }
1807
1808 key_context
1809 }
1810
1811 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1812 self.mouse_cursor_hidden = match origin {
1813 HideMouseCursorOrigin::TypingAction => {
1814 matches!(
1815 self.hide_mouse_mode,
1816 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1817 )
1818 }
1819 HideMouseCursorOrigin::MovementAction => {
1820 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1821 }
1822 };
1823 }
1824
1825 pub fn edit_prediction_in_conflict(&self) -> bool {
1826 if !self.show_edit_predictions_in_menu() {
1827 return false;
1828 }
1829
1830 let showing_completions = self
1831 .context_menu
1832 .borrow()
1833 .as_ref()
1834 .map_or(false, |context| {
1835 matches!(context, CodeContextMenu::Completions(_))
1836 });
1837
1838 showing_completions
1839 || self.edit_prediction_requires_modifier()
1840 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1841 // bindings to insert tab characters.
1842 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1843 }
1844
1845 pub fn accept_edit_prediction_keybind(
1846 &self,
1847 window: &Window,
1848 cx: &App,
1849 ) -> AcceptEditPredictionBinding {
1850 let key_context = self.key_context_internal(true, window, cx);
1851 let in_conflict = self.edit_prediction_in_conflict();
1852
1853 AcceptEditPredictionBinding(
1854 window
1855 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1856 .into_iter()
1857 .filter(|binding| {
1858 !in_conflict
1859 || binding
1860 .keystrokes()
1861 .first()
1862 .map_or(false, |keystroke| keystroke.modifiers.modified())
1863 })
1864 .rev()
1865 .min_by_key(|binding| {
1866 binding
1867 .keystrokes()
1868 .first()
1869 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1870 }),
1871 )
1872 }
1873
1874 pub fn new_file(
1875 workspace: &mut Workspace,
1876 _: &workspace::NewFile,
1877 window: &mut Window,
1878 cx: &mut Context<Workspace>,
1879 ) {
1880 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1881 "Failed to create buffer",
1882 window,
1883 cx,
1884 |e, _, _| match e.error_code() {
1885 ErrorCode::RemoteUpgradeRequired => Some(format!(
1886 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1887 e.error_tag("required").unwrap_or("the latest version")
1888 )),
1889 _ => None,
1890 },
1891 );
1892 }
1893
1894 pub fn new_in_workspace(
1895 workspace: &mut Workspace,
1896 window: &mut Window,
1897 cx: &mut Context<Workspace>,
1898 ) -> Task<Result<Entity<Editor>>> {
1899 let project = workspace.project().clone();
1900 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1901
1902 cx.spawn_in(window, async move |workspace, cx| {
1903 let buffer = create.await?;
1904 workspace.update_in(cx, |workspace, window, cx| {
1905 let editor =
1906 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1907 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1908 editor
1909 })
1910 })
1911 }
1912
1913 fn new_file_vertical(
1914 workspace: &mut Workspace,
1915 _: &workspace::NewFileSplitVertical,
1916 window: &mut Window,
1917 cx: &mut Context<Workspace>,
1918 ) {
1919 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1920 }
1921
1922 fn new_file_horizontal(
1923 workspace: &mut Workspace,
1924 _: &workspace::NewFileSplitHorizontal,
1925 window: &mut Window,
1926 cx: &mut Context<Workspace>,
1927 ) {
1928 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1929 }
1930
1931 fn new_file_in_direction(
1932 workspace: &mut Workspace,
1933 direction: SplitDirection,
1934 window: &mut Window,
1935 cx: &mut Context<Workspace>,
1936 ) {
1937 let project = workspace.project().clone();
1938 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1939
1940 cx.spawn_in(window, async move |workspace, cx| {
1941 let buffer = create.await?;
1942 workspace.update_in(cx, move |workspace, window, cx| {
1943 workspace.split_item(
1944 direction,
1945 Box::new(
1946 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1947 ),
1948 window,
1949 cx,
1950 )
1951 })?;
1952 anyhow::Ok(())
1953 })
1954 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1955 match e.error_code() {
1956 ErrorCode::RemoteUpgradeRequired => Some(format!(
1957 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1958 e.error_tag("required").unwrap_or("the latest version")
1959 )),
1960 _ => None,
1961 }
1962 });
1963 }
1964
1965 pub fn leader_peer_id(&self) -> Option<PeerId> {
1966 self.leader_peer_id
1967 }
1968
1969 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1970 &self.buffer
1971 }
1972
1973 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1974 self.workspace.as_ref()?.0.upgrade()
1975 }
1976
1977 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1978 self.buffer().read(cx).title(cx)
1979 }
1980
1981 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1982 let git_blame_gutter_max_author_length = self
1983 .render_git_blame_gutter(cx)
1984 .then(|| {
1985 if let Some(blame) = self.blame.as_ref() {
1986 let max_author_length =
1987 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1988 Some(max_author_length)
1989 } else {
1990 None
1991 }
1992 })
1993 .flatten();
1994
1995 EditorSnapshot {
1996 mode: self.mode,
1997 show_gutter: self.show_gutter,
1998 show_line_numbers: self.show_line_numbers,
1999 show_git_diff_gutter: self.show_git_diff_gutter,
2000 show_code_actions: self.show_code_actions,
2001 show_runnables: self.show_runnables,
2002 show_breakpoints: self.show_breakpoints,
2003 git_blame_gutter_max_author_length,
2004 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2005 scroll_anchor: self.scroll_manager.anchor(),
2006 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2007 placeholder_text: self.placeholder_text.clone(),
2008 is_focused: self.focus_handle.is_focused(window),
2009 current_line_highlight: self
2010 .current_line_highlight
2011 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2012 gutter_hovered: self.gutter_hovered,
2013 }
2014 }
2015
2016 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2017 self.buffer.read(cx).language_at(point, cx)
2018 }
2019
2020 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2021 self.buffer.read(cx).read(cx).file_at(point).cloned()
2022 }
2023
2024 pub fn active_excerpt(
2025 &self,
2026 cx: &App,
2027 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2028 self.buffer
2029 .read(cx)
2030 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2031 }
2032
2033 pub fn mode(&self) -> EditorMode {
2034 self.mode
2035 }
2036
2037 pub fn set_mode(&mut self, mode: EditorMode) {
2038 self.mode = mode;
2039 }
2040
2041 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2042 self.collaboration_hub.as_deref()
2043 }
2044
2045 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2046 self.collaboration_hub = Some(hub);
2047 }
2048
2049 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2050 self.in_project_search = in_project_search;
2051 }
2052
2053 pub fn set_custom_context_menu(
2054 &mut self,
2055 f: impl 'static
2056 + Fn(
2057 &mut Self,
2058 DisplayPoint,
2059 &mut Window,
2060 &mut Context<Self>,
2061 ) -> Option<Entity<ui::ContextMenu>>,
2062 ) {
2063 self.custom_context_menu = Some(Box::new(f))
2064 }
2065
2066 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2067 self.completion_provider = provider;
2068 }
2069
2070 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2071 self.semantics_provider.clone()
2072 }
2073
2074 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2075 self.semantics_provider = provider;
2076 }
2077
2078 pub fn set_edit_prediction_provider<T>(
2079 &mut self,
2080 provider: Option<Entity<T>>,
2081 window: &mut Window,
2082 cx: &mut Context<Self>,
2083 ) where
2084 T: EditPredictionProvider,
2085 {
2086 self.edit_prediction_provider =
2087 provider.map(|provider| RegisteredInlineCompletionProvider {
2088 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2089 if this.focus_handle.is_focused(window) {
2090 this.update_visible_inline_completion(window, cx);
2091 }
2092 }),
2093 provider: Arc::new(provider),
2094 });
2095 self.update_edit_prediction_settings(cx);
2096 self.refresh_inline_completion(false, false, window, cx);
2097 }
2098
2099 pub fn placeholder_text(&self) -> Option<&str> {
2100 self.placeholder_text.as_deref()
2101 }
2102
2103 pub fn set_placeholder_text(
2104 &mut self,
2105 placeholder_text: impl Into<Arc<str>>,
2106 cx: &mut Context<Self>,
2107 ) {
2108 let placeholder_text = Some(placeholder_text.into());
2109 if self.placeholder_text != placeholder_text {
2110 self.placeholder_text = placeholder_text;
2111 cx.notify();
2112 }
2113 }
2114
2115 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2116 self.cursor_shape = cursor_shape;
2117
2118 // Disrupt blink for immediate user feedback that the cursor shape has changed
2119 self.blink_manager.update(cx, BlinkManager::show_cursor);
2120
2121 cx.notify();
2122 }
2123
2124 pub fn set_current_line_highlight(
2125 &mut self,
2126 current_line_highlight: Option<CurrentLineHighlight>,
2127 ) {
2128 self.current_line_highlight = current_line_highlight;
2129 }
2130
2131 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2132 self.collapse_matches = collapse_matches;
2133 }
2134
2135 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2136 let buffers = self.buffer.read(cx).all_buffers();
2137 let Some(project) = self.project.as_ref() else {
2138 return;
2139 };
2140 project.update(cx, |project, cx| {
2141 for buffer in buffers {
2142 self.registered_buffers
2143 .entry(buffer.read(cx).remote_id())
2144 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2145 }
2146 })
2147 }
2148
2149 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2150 if self.collapse_matches {
2151 return range.start..range.start;
2152 }
2153 range.clone()
2154 }
2155
2156 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2157 if self.display_map.read(cx).clip_at_line_ends != clip {
2158 self.display_map
2159 .update(cx, |map, _| map.clip_at_line_ends = clip);
2160 }
2161 }
2162
2163 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2164 self.input_enabled = input_enabled;
2165 }
2166
2167 pub fn set_inline_completions_hidden_for_vim_mode(
2168 &mut self,
2169 hidden: bool,
2170 window: &mut Window,
2171 cx: &mut Context<Self>,
2172 ) {
2173 if hidden != self.inline_completions_hidden_for_vim_mode {
2174 self.inline_completions_hidden_for_vim_mode = hidden;
2175 if hidden {
2176 self.update_visible_inline_completion(window, cx);
2177 } else {
2178 self.refresh_inline_completion(true, false, window, cx);
2179 }
2180 }
2181 }
2182
2183 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2184 self.menu_inline_completions_policy = value;
2185 }
2186
2187 pub fn set_autoindent(&mut self, autoindent: bool) {
2188 if autoindent {
2189 self.autoindent_mode = Some(AutoindentMode::EachLine);
2190 } else {
2191 self.autoindent_mode = None;
2192 }
2193 }
2194
2195 pub fn read_only(&self, cx: &App) -> bool {
2196 self.read_only || self.buffer.read(cx).read_only()
2197 }
2198
2199 pub fn set_read_only(&mut self, read_only: bool) {
2200 self.read_only = read_only;
2201 }
2202
2203 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2204 self.use_autoclose = autoclose;
2205 }
2206
2207 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2208 self.use_auto_surround = auto_surround;
2209 }
2210
2211 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2212 self.auto_replace_emoji_shortcode = auto_replace;
2213 }
2214
2215 pub fn toggle_edit_predictions(
2216 &mut self,
2217 _: &ToggleEditPrediction,
2218 window: &mut Window,
2219 cx: &mut Context<Self>,
2220 ) {
2221 if self.show_inline_completions_override.is_some() {
2222 self.set_show_edit_predictions(None, window, cx);
2223 } else {
2224 let show_edit_predictions = !self.edit_predictions_enabled();
2225 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2226 }
2227 }
2228
2229 pub fn set_show_edit_predictions(
2230 &mut self,
2231 show_edit_predictions: Option<bool>,
2232 window: &mut Window,
2233 cx: &mut Context<Self>,
2234 ) {
2235 self.show_inline_completions_override = show_edit_predictions;
2236 self.update_edit_prediction_settings(cx);
2237
2238 if let Some(false) = show_edit_predictions {
2239 self.discard_inline_completion(false, cx);
2240 } else {
2241 self.refresh_inline_completion(false, true, window, cx);
2242 }
2243 }
2244
2245 fn inline_completions_disabled_in_scope(
2246 &self,
2247 buffer: &Entity<Buffer>,
2248 buffer_position: language::Anchor,
2249 cx: &App,
2250 ) -> bool {
2251 let snapshot = buffer.read(cx).snapshot();
2252 let settings = snapshot.settings_at(buffer_position, cx);
2253
2254 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2255 return false;
2256 };
2257
2258 scope.override_name().map_or(false, |scope_name| {
2259 settings
2260 .edit_predictions_disabled_in
2261 .iter()
2262 .any(|s| s == scope_name)
2263 })
2264 }
2265
2266 pub fn set_use_modal_editing(&mut self, to: bool) {
2267 self.use_modal_editing = to;
2268 }
2269
2270 pub fn use_modal_editing(&self) -> bool {
2271 self.use_modal_editing
2272 }
2273
2274 fn selections_did_change(
2275 &mut self,
2276 local: bool,
2277 old_cursor_position: &Anchor,
2278 show_completions: bool,
2279 window: &mut Window,
2280 cx: &mut Context<Self>,
2281 ) {
2282 window.invalidate_character_coordinates();
2283
2284 // Copy selections to primary selection buffer
2285 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2286 if local {
2287 let selections = self.selections.all::<usize>(cx);
2288 let buffer_handle = self.buffer.read(cx).read(cx);
2289
2290 let mut text = String::new();
2291 for (index, selection) in selections.iter().enumerate() {
2292 let text_for_selection = buffer_handle
2293 .text_for_range(selection.start..selection.end)
2294 .collect::<String>();
2295
2296 text.push_str(&text_for_selection);
2297 if index != selections.len() - 1 {
2298 text.push('\n');
2299 }
2300 }
2301
2302 if !text.is_empty() {
2303 cx.write_to_primary(ClipboardItem::new_string(text));
2304 }
2305 }
2306
2307 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2308 self.buffer.update(cx, |buffer, cx| {
2309 buffer.set_active_selections(
2310 &self.selections.disjoint_anchors(),
2311 self.selections.line_mode,
2312 self.cursor_shape,
2313 cx,
2314 )
2315 });
2316 }
2317 let display_map = self
2318 .display_map
2319 .update(cx, |display_map, cx| display_map.snapshot(cx));
2320 let buffer = &display_map.buffer_snapshot;
2321 self.add_selections_state = None;
2322 self.select_next_state = None;
2323 self.select_prev_state = None;
2324 self.select_syntax_node_history.try_clear();
2325 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2326 self.snippet_stack
2327 .invalidate(&self.selections.disjoint_anchors(), buffer);
2328 self.take_rename(false, window, cx);
2329
2330 let new_cursor_position = self.selections.newest_anchor().head();
2331
2332 self.push_to_nav_history(
2333 *old_cursor_position,
2334 Some(new_cursor_position.to_point(buffer)),
2335 false,
2336 cx,
2337 );
2338
2339 if local {
2340 let new_cursor_position = self.selections.newest_anchor().head();
2341 let mut context_menu = self.context_menu.borrow_mut();
2342 let completion_menu = match context_menu.as_ref() {
2343 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2344 _ => {
2345 *context_menu = None;
2346 None
2347 }
2348 };
2349 if let Some(buffer_id) = new_cursor_position.buffer_id {
2350 if !self.registered_buffers.contains_key(&buffer_id) {
2351 if let Some(project) = self.project.as_ref() {
2352 project.update(cx, |project, cx| {
2353 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2354 return;
2355 };
2356 self.registered_buffers.insert(
2357 buffer_id,
2358 project.register_buffer_with_language_servers(&buffer, cx),
2359 );
2360 })
2361 }
2362 }
2363 }
2364
2365 if let Some(completion_menu) = completion_menu {
2366 let cursor_position = new_cursor_position.to_offset(buffer);
2367 let (word_range, kind) =
2368 buffer.surrounding_word(completion_menu.initial_position, true);
2369 if kind == Some(CharKind::Word)
2370 && word_range.to_inclusive().contains(&cursor_position)
2371 {
2372 let mut completion_menu = completion_menu.clone();
2373 drop(context_menu);
2374
2375 let query = Self::completion_query(buffer, cursor_position);
2376 cx.spawn(async move |this, cx| {
2377 completion_menu
2378 .filter(query.as_deref(), cx.background_executor().clone())
2379 .await;
2380
2381 this.update(cx, |this, cx| {
2382 let mut context_menu = this.context_menu.borrow_mut();
2383 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2384 else {
2385 return;
2386 };
2387
2388 if menu.id > completion_menu.id {
2389 return;
2390 }
2391
2392 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2393 drop(context_menu);
2394 cx.notify();
2395 })
2396 })
2397 .detach();
2398
2399 if show_completions {
2400 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2401 }
2402 } else {
2403 drop(context_menu);
2404 self.hide_context_menu(window, cx);
2405 }
2406 } else {
2407 drop(context_menu);
2408 }
2409
2410 hide_hover(self, cx);
2411
2412 if old_cursor_position.to_display_point(&display_map).row()
2413 != new_cursor_position.to_display_point(&display_map).row()
2414 {
2415 self.available_code_actions.take();
2416 }
2417 self.refresh_code_actions(window, cx);
2418 self.refresh_document_highlights(cx);
2419 self.refresh_selected_text_highlights(window, cx);
2420 refresh_matching_bracket_highlights(self, window, cx);
2421 self.update_visible_inline_completion(window, cx);
2422 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2423 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2424 if self.git_blame_inline_enabled {
2425 self.start_inline_blame_timer(window, cx);
2426 }
2427 }
2428
2429 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2430 cx.emit(EditorEvent::SelectionsChanged { local });
2431
2432 let selections = &self.selections.disjoint;
2433 if selections.len() == 1 {
2434 cx.emit(SearchEvent::ActiveMatchChanged)
2435 }
2436 if local {
2437 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2438 let inmemory_selections = selections
2439 .iter()
2440 .map(|s| {
2441 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2442 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2443 })
2444 .collect();
2445 self.update_restoration_data(cx, |data| {
2446 data.selections = inmemory_selections;
2447 });
2448
2449 if WorkspaceSettings::get(None, cx).restore_on_startup
2450 != RestoreOnStartupBehavior::None
2451 {
2452 if let Some(workspace_id) =
2453 self.workspace.as_ref().and_then(|workspace| workspace.1)
2454 {
2455 let snapshot = self.buffer().read(cx).snapshot(cx);
2456 let selections = selections.clone();
2457 let background_executor = cx.background_executor().clone();
2458 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2459 self.serialize_selections = cx.background_spawn(async move {
2460 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2461 let db_selections = selections
2462 .iter()
2463 .map(|selection| {
2464 (
2465 selection.start.to_offset(&snapshot),
2466 selection.end.to_offset(&snapshot),
2467 )
2468 })
2469 .collect();
2470
2471 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2472 .await
2473 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2474 .log_err();
2475 });
2476 }
2477 }
2478 }
2479 }
2480
2481 cx.notify();
2482 }
2483
2484 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2485 use text::ToOffset as _;
2486 use text::ToPoint as _;
2487
2488 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2489 return;
2490 }
2491
2492 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2493 return;
2494 };
2495
2496 let snapshot = singleton.read(cx).snapshot();
2497 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2498 let display_snapshot = display_map.snapshot(cx);
2499
2500 display_snapshot
2501 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2502 .map(|fold| {
2503 fold.range.start.text_anchor.to_point(&snapshot)
2504 ..fold.range.end.text_anchor.to_point(&snapshot)
2505 })
2506 .collect()
2507 });
2508 self.update_restoration_data(cx, |data| {
2509 data.folds = inmemory_folds;
2510 });
2511
2512 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2513 return;
2514 };
2515 let background_executor = cx.background_executor().clone();
2516 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2517 let db_folds = self.display_map.update(cx, |display_map, cx| {
2518 display_map
2519 .snapshot(cx)
2520 .folds_in_range(0..snapshot.len())
2521 .map(|fold| {
2522 (
2523 fold.range.start.text_anchor.to_offset(&snapshot),
2524 fold.range.end.text_anchor.to_offset(&snapshot),
2525 )
2526 })
2527 .collect()
2528 });
2529 self.serialize_folds = cx.background_spawn(async move {
2530 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2531 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2532 .await
2533 .with_context(|| {
2534 format!(
2535 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2536 )
2537 })
2538 .log_err();
2539 });
2540 }
2541
2542 pub fn sync_selections(
2543 &mut self,
2544 other: Entity<Editor>,
2545 cx: &mut Context<Self>,
2546 ) -> gpui::Subscription {
2547 let other_selections = other.read(cx).selections.disjoint.to_vec();
2548 self.selections.change_with(cx, |selections| {
2549 selections.select_anchors(other_selections);
2550 });
2551
2552 let other_subscription =
2553 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2554 EditorEvent::SelectionsChanged { local: true } => {
2555 let other_selections = other.read(cx).selections.disjoint.to_vec();
2556 if other_selections.is_empty() {
2557 return;
2558 }
2559 this.selections.change_with(cx, |selections| {
2560 selections.select_anchors(other_selections);
2561 });
2562 }
2563 _ => {}
2564 });
2565
2566 let this_subscription =
2567 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2568 EditorEvent::SelectionsChanged { local: true } => {
2569 let these_selections = this.selections.disjoint.to_vec();
2570 if these_selections.is_empty() {
2571 return;
2572 }
2573 other.update(cx, |other_editor, cx| {
2574 other_editor.selections.change_with(cx, |selections| {
2575 selections.select_anchors(these_selections);
2576 })
2577 });
2578 }
2579 _ => {}
2580 });
2581
2582 Subscription::join(other_subscription, this_subscription)
2583 }
2584
2585 pub fn change_selections<R>(
2586 &mut self,
2587 autoscroll: Option<Autoscroll>,
2588 window: &mut Window,
2589 cx: &mut Context<Self>,
2590 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2591 ) -> R {
2592 self.change_selections_inner(autoscroll, true, window, cx, change)
2593 }
2594
2595 fn change_selections_inner<R>(
2596 &mut self,
2597 autoscroll: Option<Autoscroll>,
2598 request_completions: bool,
2599 window: &mut Window,
2600 cx: &mut Context<Self>,
2601 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2602 ) -> R {
2603 let old_cursor_position = self.selections.newest_anchor().head();
2604 self.push_to_selection_history();
2605
2606 let (changed, result) = self.selections.change_with(cx, change);
2607
2608 if changed {
2609 if let Some(autoscroll) = autoscroll {
2610 self.request_autoscroll(autoscroll, cx);
2611 }
2612 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2613
2614 if self.should_open_signature_help_automatically(
2615 &old_cursor_position,
2616 self.signature_help_state.backspace_pressed(),
2617 cx,
2618 ) {
2619 self.show_signature_help(&ShowSignatureHelp, window, cx);
2620 }
2621 self.signature_help_state.set_backspace_pressed(false);
2622 }
2623
2624 result
2625 }
2626
2627 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2628 where
2629 I: IntoIterator<Item = (Range<S>, T)>,
2630 S: ToOffset,
2631 T: Into<Arc<str>>,
2632 {
2633 if self.read_only(cx) {
2634 return;
2635 }
2636
2637 self.buffer
2638 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2639 }
2640
2641 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2642 where
2643 I: IntoIterator<Item = (Range<S>, T)>,
2644 S: ToOffset,
2645 T: Into<Arc<str>>,
2646 {
2647 if self.read_only(cx) {
2648 return;
2649 }
2650
2651 self.buffer.update(cx, |buffer, cx| {
2652 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2653 });
2654 }
2655
2656 pub fn edit_with_block_indent<I, S, T>(
2657 &mut self,
2658 edits: I,
2659 original_indent_columns: Vec<Option<u32>>,
2660 cx: &mut Context<Self>,
2661 ) where
2662 I: IntoIterator<Item = (Range<S>, T)>,
2663 S: ToOffset,
2664 T: Into<Arc<str>>,
2665 {
2666 if self.read_only(cx) {
2667 return;
2668 }
2669
2670 self.buffer.update(cx, |buffer, cx| {
2671 buffer.edit(
2672 edits,
2673 Some(AutoindentMode::Block {
2674 original_indent_columns,
2675 }),
2676 cx,
2677 )
2678 });
2679 }
2680
2681 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2682 self.hide_context_menu(window, cx);
2683
2684 match phase {
2685 SelectPhase::Begin {
2686 position,
2687 add,
2688 click_count,
2689 } => self.begin_selection(position, add, click_count, window, cx),
2690 SelectPhase::BeginColumnar {
2691 position,
2692 goal_column,
2693 reset,
2694 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2695 SelectPhase::Extend {
2696 position,
2697 click_count,
2698 } => self.extend_selection(position, click_count, window, cx),
2699 SelectPhase::Update {
2700 position,
2701 goal_column,
2702 scroll_delta,
2703 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2704 SelectPhase::End => self.end_selection(window, cx),
2705 }
2706 }
2707
2708 fn extend_selection(
2709 &mut self,
2710 position: DisplayPoint,
2711 click_count: usize,
2712 window: &mut Window,
2713 cx: &mut Context<Self>,
2714 ) {
2715 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2716 let tail = self.selections.newest::<usize>(cx).tail();
2717 self.begin_selection(position, false, click_count, window, cx);
2718
2719 let position = position.to_offset(&display_map, Bias::Left);
2720 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2721
2722 let mut pending_selection = self
2723 .selections
2724 .pending_anchor()
2725 .expect("extend_selection not called with pending selection");
2726 if position >= tail {
2727 pending_selection.start = tail_anchor;
2728 } else {
2729 pending_selection.end = tail_anchor;
2730 pending_selection.reversed = true;
2731 }
2732
2733 let mut pending_mode = self.selections.pending_mode().unwrap();
2734 match &mut pending_mode {
2735 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2736 _ => {}
2737 }
2738
2739 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2740 s.set_pending(pending_selection, pending_mode)
2741 });
2742 }
2743
2744 fn begin_selection(
2745 &mut self,
2746 position: DisplayPoint,
2747 add: bool,
2748 click_count: usize,
2749 window: &mut Window,
2750 cx: &mut Context<Self>,
2751 ) {
2752 if !self.focus_handle.is_focused(window) {
2753 self.last_focused_descendant = None;
2754 window.focus(&self.focus_handle);
2755 }
2756
2757 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2758 let buffer = &display_map.buffer_snapshot;
2759 let newest_selection = self.selections.newest_anchor().clone();
2760 let position = display_map.clip_point(position, Bias::Left);
2761
2762 let start;
2763 let end;
2764 let mode;
2765 let mut auto_scroll;
2766 match click_count {
2767 1 => {
2768 start = buffer.anchor_before(position.to_point(&display_map));
2769 end = start;
2770 mode = SelectMode::Character;
2771 auto_scroll = true;
2772 }
2773 2 => {
2774 let range = movement::surrounding_word(&display_map, position);
2775 start = buffer.anchor_before(range.start.to_point(&display_map));
2776 end = buffer.anchor_before(range.end.to_point(&display_map));
2777 mode = SelectMode::Word(start..end);
2778 auto_scroll = true;
2779 }
2780 3 => {
2781 let position = display_map
2782 .clip_point(position, Bias::Left)
2783 .to_point(&display_map);
2784 let line_start = display_map.prev_line_boundary(position).0;
2785 let next_line_start = buffer.clip_point(
2786 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2787 Bias::Left,
2788 );
2789 start = buffer.anchor_before(line_start);
2790 end = buffer.anchor_before(next_line_start);
2791 mode = SelectMode::Line(start..end);
2792 auto_scroll = true;
2793 }
2794 _ => {
2795 start = buffer.anchor_before(0);
2796 end = buffer.anchor_before(buffer.len());
2797 mode = SelectMode::All;
2798 auto_scroll = false;
2799 }
2800 }
2801 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2802
2803 let point_to_delete: Option<usize> = {
2804 let selected_points: Vec<Selection<Point>> =
2805 self.selections.disjoint_in_range(start..end, cx);
2806
2807 if !add || click_count > 1 {
2808 None
2809 } else if !selected_points.is_empty() {
2810 Some(selected_points[0].id)
2811 } else {
2812 let clicked_point_already_selected =
2813 self.selections.disjoint.iter().find(|selection| {
2814 selection.start.to_point(buffer) == start.to_point(buffer)
2815 || selection.end.to_point(buffer) == end.to_point(buffer)
2816 });
2817
2818 clicked_point_already_selected.map(|selection| selection.id)
2819 }
2820 };
2821
2822 let selections_count = self.selections.count();
2823
2824 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2825 if let Some(point_to_delete) = point_to_delete {
2826 s.delete(point_to_delete);
2827
2828 if selections_count == 1 {
2829 s.set_pending_anchor_range(start..end, mode);
2830 }
2831 } else {
2832 if !add {
2833 s.clear_disjoint();
2834 } else if click_count > 1 {
2835 s.delete(newest_selection.id)
2836 }
2837
2838 s.set_pending_anchor_range(start..end, mode);
2839 }
2840 });
2841 }
2842
2843 fn begin_columnar_selection(
2844 &mut self,
2845 position: DisplayPoint,
2846 goal_column: u32,
2847 reset: bool,
2848 window: &mut Window,
2849 cx: &mut Context<Self>,
2850 ) {
2851 if !self.focus_handle.is_focused(window) {
2852 self.last_focused_descendant = None;
2853 window.focus(&self.focus_handle);
2854 }
2855
2856 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2857
2858 if reset {
2859 let pointer_position = display_map
2860 .buffer_snapshot
2861 .anchor_before(position.to_point(&display_map));
2862
2863 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2864 s.clear_disjoint();
2865 s.set_pending_anchor_range(
2866 pointer_position..pointer_position,
2867 SelectMode::Character,
2868 );
2869 });
2870 }
2871
2872 let tail = self.selections.newest::<Point>(cx).tail();
2873 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2874
2875 if !reset {
2876 self.select_columns(
2877 tail.to_display_point(&display_map),
2878 position,
2879 goal_column,
2880 &display_map,
2881 window,
2882 cx,
2883 );
2884 }
2885 }
2886
2887 fn update_selection(
2888 &mut self,
2889 position: DisplayPoint,
2890 goal_column: u32,
2891 scroll_delta: gpui::Point<f32>,
2892 window: &mut Window,
2893 cx: &mut Context<Self>,
2894 ) {
2895 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2896
2897 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2898 let tail = tail.to_display_point(&display_map);
2899 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2900 } else if let Some(mut pending) = self.selections.pending_anchor() {
2901 let buffer = self.buffer.read(cx).snapshot(cx);
2902 let head;
2903 let tail;
2904 let mode = self.selections.pending_mode().unwrap();
2905 match &mode {
2906 SelectMode::Character => {
2907 head = position.to_point(&display_map);
2908 tail = pending.tail().to_point(&buffer);
2909 }
2910 SelectMode::Word(original_range) => {
2911 let original_display_range = original_range.start.to_display_point(&display_map)
2912 ..original_range.end.to_display_point(&display_map);
2913 let original_buffer_range = original_display_range.start.to_point(&display_map)
2914 ..original_display_range.end.to_point(&display_map);
2915 if movement::is_inside_word(&display_map, position)
2916 || original_display_range.contains(&position)
2917 {
2918 let word_range = movement::surrounding_word(&display_map, position);
2919 if word_range.start < original_display_range.start {
2920 head = word_range.start.to_point(&display_map);
2921 } else {
2922 head = word_range.end.to_point(&display_map);
2923 }
2924 } else {
2925 head = position.to_point(&display_map);
2926 }
2927
2928 if head <= original_buffer_range.start {
2929 tail = original_buffer_range.end;
2930 } else {
2931 tail = original_buffer_range.start;
2932 }
2933 }
2934 SelectMode::Line(original_range) => {
2935 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2936
2937 let position = display_map
2938 .clip_point(position, Bias::Left)
2939 .to_point(&display_map);
2940 let line_start = display_map.prev_line_boundary(position).0;
2941 let next_line_start = buffer.clip_point(
2942 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2943 Bias::Left,
2944 );
2945
2946 if line_start < original_range.start {
2947 head = line_start
2948 } else {
2949 head = next_line_start
2950 }
2951
2952 if head <= original_range.start {
2953 tail = original_range.end;
2954 } else {
2955 tail = original_range.start;
2956 }
2957 }
2958 SelectMode::All => {
2959 return;
2960 }
2961 };
2962
2963 if head < tail {
2964 pending.start = buffer.anchor_before(head);
2965 pending.end = buffer.anchor_before(tail);
2966 pending.reversed = true;
2967 } else {
2968 pending.start = buffer.anchor_before(tail);
2969 pending.end = buffer.anchor_before(head);
2970 pending.reversed = false;
2971 }
2972
2973 self.change_selections(None, window, cx, |s| {
2974 s.set_pending(pending, mode);
2975 });
2976 } else {
2977 log::error!("update_selection dispatched with no pending selection");
2978 return;
2979 }
2980
2981 self.apply_scroll_delta(scroll_delta, window, cx);
2982 cx.notify();
2983 }
2984
2985 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2986 self.columnar_selection_tail.take();
2987 if self.selections.pending_anchor().is_some() {
2988 let selections = self.selections.all::<usize>(cx);
2989 self.change_selections(None, window, cx, |s| {
2990 s.select(selections);
2991 s.clear_pending();
2992 });
2993 }
2994 }
2995
2996 fn select_columns(
2997 &mut self,
2998 tail: DisplayPoint,
2999 head: DisplayPoint,
3000 goal_column: u32,
3001 display_map: &DisplaySnapshot,
3002 window: &mut Window,
3003 cx: &mut Context<Self>,
3004 ) {
3005 let start_row = cmp::min(tail.row(), head.row());
3006 let end_row = cmp::max(tail.row(), head.row());
3007 let start_column = cmp::min(tail.column(), goal_column);
3008 let end_column = cmp::max(tail.column(), goal_column);
3009 let reversed = start_column < tail.column();
3010
3011 let selection_ranges = (start_row.0..=end_row.0)
3012 .map(DisplayRow)
3013 .filter_map(|row| {
3014 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3015 let start = display_map
3016 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3017 .to_point(display_map);
3018 let end = display_map
3019 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3020 .to_point(display_map);
3021 if reversed {
3022 Some(end..start)
3023 } else {
3024 Some(start..end)
3025 }
3026 } else {
3027 None
3028 }
3029 })
3030 .collect::<Vec<_>>();
3031
3032 self.change_selections(None, window, cx, |s| {
3033 s.select_ranges(selection_ranges);
3034 });
3035 cx.notify();
3036 }
3037
3038 pub fn has_pending_nonempty_selection(&self) -> bool {
3039 let pending_nonempty_selection = match self.selections.pending_anchor() {
3040 Some(Selection { start, end, .. }) => start != end,
3041 None => false,
3042 };
3043
3044 pending_nonempty_selection
3045 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3046 }
3047
3048 pub fn has_pending_selection(&self) -> bool {
3049 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3050 }
3051
3052 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3053 self.selection_mark_mode = false;
3054
3055 if self.clear_expanded_diff_hunks(cx) {
3056 cx.notify();
3057 return;
3058 }
3059 if self.dismiss_menus_and_popups(true, window, cx) {
3060 return;
3061 }
3062
3063 if self.mode.is_full()
3064 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3065 {
3066 return;
3067 }
3068
3069 cx.propagate();
3070 }
3071
3072 pub fn dismiss_menus_and_popups(
3073 &mut self,
3074 is_user_requested: bool,
3075 window: &mut Window,
3076 cx: &mut Context<Self>,
3077 ) -> bool {
3078 if self.take_rename(false, window, cx).is_some() {
3079 return true;
3080 }
3081
3082 if hide_hover(self, cx) {
3083 return true;
3084 }
3085
3086 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3087 return true;
3088 }
3089
3090 if self.hide_context_menu(window, cx).is_some() {
3091 return true;
3092 }
3093
3094 if self.mouse_context_menu.take().is_some() {
3095 return true;
3096 }
3097
3098 if is_user_requested && self.discard_inline_completion(true, cx) {
3099 return true;
3100 }
3101
3102 if self.snippet_stack.pop().is_some() {
3103 return true;
3104 }
3105
3106 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3107 self.dismiss_diagnostics(cx);
3108 return true;
3109 }
3110
3111 false
3112 }
3113
3114 fn linked_editing_ranges_for(
3115 &self,
3116 selection: Range<text::Anchor>,
3117 cx: &App,
3118 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3119 if self.linked_edit_ranges.is_empty() {
3120 return None;
3121 }
3122 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3123 selection.end.buffer_id.and_then(|end_buffer_id| {
3124 if selection.start.buffer_id != Some(end_buffer_id) {
3125 return None;
3126 }
3127 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3128 let snapshot = buffer.read(cx).snapshot();
3129 self.linked_edit_ranges
3130 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3131 .map(|ranges| (ranges, snapshot, buffer))
3132 })?;
3133 use text::ToOffset as TO;
3134 // find offset from the start of current range to current cursor position
3135 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3136
3137 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3138 let start_difference = start_offset - start_byte_offset;
3139 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3140 let end_difference = end_offset - start_byte_offset;
3141 // Current range has associated linked ranges.
3142 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3143 for range in linked_ranges.iter() {
3144 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3145 let end_offset = start_offset + end_difference;
3146 let start_offset = start_offset + start_difference;
3147 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3148 continue;
3149 }
3150 if self.selections.disjoint_anchor_ranges().any(|s| {
3151 if s.start.buffer_id != selection.start.buffer_id
3152 || s.end.buffer_id != selection.end.buffer_id
3153 {
3154 return false;
3155 }
3156 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3157 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3158 }) {
3159 continue;
3160 }
3161 let start = buffer_snapshot.anchor_after(start_offset);
3162 let end = buffer_snapshot.anchor_after(end_offset);
3163 linked_edits
3164 .entry(buffer.clone())
3165 .or_default()
3166 .push(start..end);
3167 }
3168 Some(linked_edits)
3169 }
3170
3171 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3172 let text: Arc<str> = text.into();
3173
3174 if self.read_only(cx) {
3175 return;
3176 }
3177
3178 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3179
3180 let selections = self.selections.all_adjusted(cx);
3181 let mut bracket_inserted = false;
3182 let mut edits = Vec::new();
3183 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3184 let mut new_selections = Vec::with_capacity(selections.len());
3185 let mut new_autoclose_regions = Vec::new();
3186 let snapshot = self.buffer.read(cx).read(cx);
3187 let mut clear_linked_edit_ranges = false;
3188
3189 for (selection, autoclose_region) in
3190 self.selections_with_autoclose_regions(selections, &snapshot)
3191 {
3192 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3193 // Determine if the inserted text matches the opening or closing
3194 // bracket of any of this language's bracket pairs.
3195 let mut bracket_pair = None;
3196 let mut is_bracket_pair_start = false;
3197 let mut is_bracket_pair_end = false;
3198 if !text.is_empty() {
3199 let mut bracket_pair_matching_end = None;
3200 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3201 // and they are removing the character that triggered IME popup.
3202 for (pair, enabled) in scope.brackets() {
3203 if !pair.close && !pair.surround {
3204 continue;
3205 }
3206
3207 if enabled && pair.start.ends_with(text.as_ref()) {
3208 let prefix_len = pair.start.len() - text.len();
3209 let preceding_text_matches_prefix = prefix_len == 0
3210 || (selection.start.column >= (prefix_len as u32)
3211 && snapshot.contains_str_at(
3212 Point::new(
3213 selection.start.row,
3214 selection.start.column - (prefix_len as u32),
3215 ),
3216 &pair.start[..prefix_len],
3217 ));
3218 if preceding_text_matches_prefix {
3219 bracket_pair = Some(pair.clone());
3220 is_bracket_pair_start = true;
3221 break;
3222 }
3223 }
3224 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3225 {
3226 // take first bracket pair matching end, but don't break in case a later bracket
3227 // pair matches start
3228 bracket_pair_matching_end = Some(pair.clone());
3229 }
3230 }
3231 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3232 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3233 is_bracket_pair_end = true;
3234 }
3235 }
3236
3237 if let Some(bracket_pair) = bracket_pair {
3238 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3239 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3240 let auto_surround =
3241 self.use_auto_surround && snapshot_settings.use_auto_surround;
3242 if selection.is_empty() {
3243 if is_bracket_pair_start {
3244 // If the inserted text is a suffix of an opening bracket and the
3245 // selection is preceded by the rest of the opening bracket, then
3246 // insert the closing bracket.
3247 let following_text_allows_autoclose = snapshot
3248 .chars_at(selection.start)
3249 .next()
3250 .map_or(true, |c| scope.should_autoclose_before(c));
3251
3252 let preceding_text_allows_autoclose = selection.start.column == 0
3253 || snapshot.reversed_chars_at(selection.start).next().map_or(
3254 true,
3255 |c| {
3256 bracket_pair.start != bracket_pair.end
3257 || !snapshot
3258 .char_classifier_at(selection.start)
3259 .is_word(c)
3260 },
3261 );
3262
3263 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3264 && bracket_pair.start.len() == 1
3265 {
3266 let target = bracket_pair.start.chars().next().unwrap();
3267 let current_line_count = snapshot
3268 .reversed_chars_at(selection.start)
3269 .take_while(|&c| c != '\n')
3270 .filter(|&c| c == target)
3271 .count();
3272 current_line_count % 2 == 1
3273 } else {
3274 false
3275 };
3276
3277 if autoclose
3278 && bracket_pair.close
3279 && following_text_allows_autoclose
3280 && preceding_text_allows_autoclose
3281 && !is_closing_quote
3282 {
3283 let anchor = snapshot.anchor_before(selection.end);
3284 new_selections.push((selection.map(|_| anchor), text.len()));
3285 new_autoclose_regions.push((
3286 anchor,
3287 text.len(),
3288 selection.id,
3289 bracket_pair.clone(),
3290 ));
3291 edits.push((
3292 selection.range(),
3293 format!("{}{}", text, bracket_pair.end).into(),
3294 ));
3295 bracket_inserted = true;
3296 continue;
3297 }
3298 }
3299
3300 if let Some(region) = autoclose_region {
3301 // If the selection is followed by an auto-inserted closing bracket,
3302 // then don't insert that closing bracket again; just move the selection
3303 // past the closing bracket.
3304 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3305 && text.as_ref() == region.pair.end.as_str();
3306 if should_skip {
3307 let anchor = snapshot.anchor_after(selection.end);
3308 new_selections
3309 .push((selection.map(|_| anchor), region.pair.end.len()));
3310 continue;
3311 }
3312 }
3313
3314 let always_treat_brackets_as_autoclosed = snapshot
3315 .language_settings_at(selection.start, cx)
3316 .always_treat_brackets_as_autoclosed;
3317 if always_treat_brackets_as_autoclosed
3318 && is_bracket_pair_end
3319 && snapshot.contains_str_at(selection.end, text.as_ref())
3320 {
3321 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3322 // and the inserted text is a closing bracket and the selection is followed
3323 // by the closing bracket then move the selection past the closing bracket.
3324 let anchor = snapshot.anchor_after(selection.end);
3325 new_selections.push((selection.map(|_| anchor), text.len()));
3326 continue;
3327 }
3328 }
3329 // If an opening bracket is 1 character long and is typed while
3330 // text is selected, then surround that text with the bracket pair.
3331 else if auto_surround
3332 && bracket_pair.surround
3333 && is_bracket_pair_start
3334 && bracket_pair.start.chars().count() == 1
3335 {
3336 edits.push((selection.start..selection.start, text.clone()));
3337 edits.push((
3338 selection.end..selection.end,
3339 bracket_pair.end.as_str().into(),
3340 ));
3341 bracket_inserted = true;
3342 new_selections.push((
3343 Selection {
3344 id: selection.id,
3345 start: snapshot.anchor_after(selection.start),
3346 end: snapshot.anchor_before(selection.end),
3347 reversed: selection.reversed,
3348 goal: selection.goal,
3349 },
3350 0,
3351 ));
3352 continue;
3353 }
3354 }
3355 }
3356
3357 if self.auto_replace_emoji_shortcode
3358 && selection.is_empty()
3359 && text.as_ref().ends_with(':')
3360 {
3361 if let Some(possible_emoji_short_code) =
3362 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3363 {
3364 if !possible_emoji_short_code.is_empty() {
3365 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3366 let emoji_shortcode_start = Point::new(
3367 selection.start.row,
3368 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3369 );
3370
3371 // Remove shortcode from buffer
3372 edits.push((
3373 emoji_shortcode_start..selection.start,
3374 "".to_string().into(),
3375 ));
3376 new_selections.push((
3377 Selection {
3378 id: selection.id,
3379 start: snapshot.anchor_after(emoji_shortcode_start),
3380 end: snapshot.anchor_before(selection.start),
3381 reversed: selection.reversed,
3382 goal: selection.goal,
3383 },
3384 0,
3385 ));
3386
3387 // Insert emoji
3388 let selection_start_anchor = snapshot.anchor_after(selection.start);
3389 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3390 edits.push((selection.start..selection.end, emoji.to_string().into()));
3391
3392 continue;
3393 }
3394 }
3395 }
3396 }
3397
3398 // If not handling any auto-close operation, then just replace the selected
3399 // text with the given input and move the selection to the end of the
3400 // newly inserted text.
3401 let anchor = snapshot.anchor_after(selection.end);
3402 if !self.linked_edit_ranges.is_empty() {
3403 let start_anchor = snapshot.anchor_before(selection.start);
3404
3405 let is_word_char = text.chars().next().map_or(true, |char| {
3406 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3407 classifier.is_word(char)
3408 });
3409
3410 if is_word_char {
3411 if let Some(ranges) = self
3412 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3413 {
3414 for (buffer, edits) in ranges {
3415 linked_edits
3416 .entry(buffer.clone())
3417 .or_default()
3418 .extend(edits.into_iter().map(|range| (range, text.clone())));
3419 }
3420 }
3421 } else {
3422 clear_linked_edit_ranges = true;
3423 }
3424 }
3425
3426 new_selections.push((selection.map(|_| anchor), 0));
3427 edits.push((selection.start..selection.end, text.clone()));
3428 }
3429
3430 drop(snapshot);
3431
3432 self.transact(window, cx, |this, window, cx| {
3433 if clear_linked_edit_ranges {
3434 this.linked_edit_ranges.clear();
3435 }
3436 let initial_buffer_versions =
3437 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3438
3439 this.buffer.update(cx, |buffer, cx| {
3440 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3441 });
3442 for (buffer, edits) in linked_edits {
3443 buffer.update(cx, |buffer, cx| {
3444 let snapshot = buffer.snapshot();
3445 let edits = edits
3446 .into_iter()
3447 .map(|(range, text)| {
3448 use text::ToPoint as TP;
3449 let end_point = TP::to_point(&range.end, &snapshot);
3450 let start_point = TP::to_point(&range.start, &snapshot);
3451 (start_point..end_point, text)
3452 })
3453 .sorted_by_key(|(range, _)| range.start);
3454 buffer.edit(edits, None, cx);
3455 })
3456 }
3457 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3458 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3459 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3460 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3461 .zip(new_selection_deltas)
3462 .map(|(selection, delta)| Selection {
3463 id: selection.id,
3464 start: selection.start + delta,
3465 end: selection.end + delta,
3466 reversed: selection.reversed,
3467 goal: SelectionGoal::None,
3468 })
3469 .collect::<Vec<_>>();
3470
3471 let mut i = 0;
3472 for (position, delta, selection_id, pair) in new_autoclose_regions {
3473 let position = position.to_offset(&map.buffer_snapshot) + delta;
3474 let start = map.buffer_snapshot.anchor_before(position);
3475 let end = map.buffer_snapshot.anchor_after(position);
3476 while let Some(existing_state) = this.autoclose_regions.get(i) {
3477 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3478 Ordering::Less => i += 1,
3479 Ordering::Greater => break,
3480 Ordering::Equal => {
3481 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3482 Ordering::Less => i += 1,
3483 Ordering::Equal => break,
3484 Ordering::Greater => break,
3485 }
3486 }
3487 }
3488 }
3489 this.autoclose_regions.insert(
3490 i,
3491 AutocloseRegion {
3492 selection_id,
3493 range: start..end,
3494 pair,
3495 },
3496 );
3497 }
3498
3499 let had_active_inline_completion = this.has_active_inline_completion();
3500 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3501 s.select(new_selections)
3502 });
3503
3504 if !bracket_inserted {
3505 if let Some(on_type_format_task) =
3506 this.trigger_on_type_formatting(text.to_string(), window, cx)
3507 {
3508 on_type_format_task.detach_and_log_err(cx);
3509 }
3510 }
3511
3512 let editor_settings = EditorSettings::get_global(cx);
3513 if bracket_inserted
3514 && (editor_settings.auto_signature_help
3515 || editor_settings.show_signature_help_after_edits)
3516 {
3517 this.show_signature_help(&ShowSignatureHelp, window, cx);
3518 }
3519
3520 let trigger_in_words =
3521 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3522 if this.hard_wrap.is_some() {
3523 let latest: Range<Point> = this.selections.newest(cx).range();
3524 if latest.is_empty()
3525 && this
3526 .buffer()
3527 .read(cx)
3528 .snapshot(cx)
3529 .line_len(MultiBufferRow(latest.start.row))
3530 == latest.start.column
3531 {
3532 this.rewrap_impl(
3533 RewrapOptions {
3534 override_language_settings: true,
3535 preserve_existing_whitespace: true,
3536 },
3537 cx,
3538 )
3539 }
3540 }
3541 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3542 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3543 this.refresh_inline_completion(true, false, window, cx);
3544 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3545 });
3546 }
3547
3548 fn find_possible_emoji_shortcode_at_position(
3549 snapshot: &MultiBufferSnapshot,
3550 position: Point,
3551 ) -> Option<String> {
3552 let mut chars = Vec::new();
3553 let mut found_colon = false;
3554 for char in snapshot.reversed_chars_at(position).take(100) {
3555 // Found a possible emoji shortcode in the middle of the buffer
3556 if found_colon {
3557 if char.is_whitespace() {
3558 chars.reverse();
3559 return Some(chars.iter().collect());
3560 }
3561 // If the previous character is not a whitespace, we are in the middle of a word
3562 // and we only want to complete the shortcode if the word is made up of other emojis
3563 let mut containing_word = String::new();
3564 for ch in snapshot
3565 .reversed_chars_at(position)
3566 .skip(chars.len() + 1)
3567 .take(100)
3568 {
3569 if ch.is_whitespace() {
3570 break;
3571 }
3572 containing_word.push(ch);
3573 }
3574 let containing_word = containing_word.chars().rev().collect::<String>();
3575 if util::word_consists_of_emojis(containing_word.as_str()) {
3576 chars.reverse();
3577 return Some(chars.iter().collect());
3578 }
3579 }
3580
3581 if char.is_whitespace() || !char.is_ascii() {
3582 return None;
3583 }
3584 if char == ':' {
3585 found_colon = true;
3586 } else {
3587 chars.push(char);
3588 }
3589 }
3590 // Found a possible emoji shortcode at the beginning of the buffer
3591 chars.reverse();
3592 Some(chars.iter().collect())
3593 }
3594
3595 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3596 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3597 self.transact(window, cx, |this, window, cx| {
3598 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3599 let selections = this.selections.all::<usize>(cx);
3600 let multi_buffer = this.buffer.read(cx);
3601 let buffer = multi_buffer.snapshot(cx);
3602 selections
3603 .iter()
3604 .map(|selection| {
3605 let start_point = selection.start.to_point(&buffer);
3606 let mut indent =
3607 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3608 indent.len = cmp::min(indent.len, start_point.column);
3609 let start = selection.start;
3610 let end = selection.end;
3611 let selection_is_empty = start == end;
3612 let language_scope = buffer.language_scope_at(start);
3613 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3614 &language_scope
3615 {
3616 let insert_extra_newline =
3617 insert_extra_newline_brackets(&buffer, start..end, language)
3618 || insert_extra_newline_tree_sitter(&buffer, start..end);
3619
3620 // Comment extension on newline is allowed only for cursor selections
3621 let comment_delimiter = maybe!({
3622 if !selection_is_empty {
3623 return None;
3624 }
3625
3626 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3627 return None;
3628 }
3629
3630 let delimiters = language.line_comment_prefixes();
3631 let max_len_of_delimiter =
3632 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3633 let (snapshot, range) =
3634 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3635
3636 let mut index_of_first_non_whitespace = 0;
3637 let comment_candidate = snapshot
3638 .chars_for_range(range)
3639 .skip_while(|c| {
3640 let should_skip = c.is_whitespace();
3641 if should_skip {
3642 index_of_first_non_whitespace += 1;
3643 }
3644 should_skip
3645 })
3646 .take(max_len_of_delimiter)
3647 .collect::<String>();
3648 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3649 comment_candidate.starts_with(comment_prefix.as_ref())
3650 })?;
3651 let cursor_is_placed_after_comment_marker =
3652 index_of_first_non_whitespace + comment_prefix.len()
3653 <= start_point.column as usize;
3654 if cursor_is_placed_after_comment_marker {
3655 Some(comment_prefix.clone())
3656 } else {
3657 None
3658 }
3659 });
3660 (comment_delimiter, insert_extra_newline)
3661 } else {
3662 (None, false)
3663 };
3664
3665 let capacity_for_delimiter = comment_delimiter
3666 .as_deref()
3667 .map(str::len)
3668 .unwrap_or_default();
3669 let mut new_text =
3670 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3671 new_text.push('\n');
3672 new_text.extend(indent.chars());
3673 if let Some(delimiter) = &comment_delimiter {
3674 new_text.push_str(delimiter);
3675 }
3676 if insert_extra_newline {
3677 new_text = new_text.repeat(2);
3678 }
3679
3680 let anchor = buffer.anchor_after(end);
3681 let new_selection = selection.map(|_| anchor);
3682 (
3683 (start..end, new_text),
3684 (insert_extra_newline, new_selection),
3685 )
3686 })
3687 .unzip()
3688 };
3689
3690 this.edit_with_autoindent(edits, cx);
3691 let buffer = this.buffer.read(cx).snapshot(cx);
3692 let new_selections = selection_fixup_info
3693 .into_iter()
3694 .map(|(extra_newline_inserted, new_selection)| {
3695 let mut cursor = new_selection.end.to_point(&buffer);
3696 if extra_newline_inserted {
3697 cursor.row -= 1;
3698 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3699 }
3700 new_selection.map(|_| cursor)
3701 })
3702 .collect();
3703
3704 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3705 s.select(new_selections)
3706 });
3707 this.refresh_inline_completion(true, false, window, cx);
3708 });
3709 }
3710
3711 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3712 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3713
3714 let buffer = self.buffer.read(cx);
3715 let snapshot = buffer.snapshot(cx);
3716
3717 let mut edits = Vec::new();
3718 let mut rows = Vec::new();
3719
3720 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3721 let cursor = selection.head();
3722 let row = cursor.row;
3723
3724 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3725
3726 let newline = "\n".to_string();
3727 edits.push((start_of_line..start_of_line, newline));
3728
3729 rows.push(row + rows_inserted as u32);
3730 }
3731
3732 self.transact(window, cx, |editor, window, cx| {
3733 editor.edit(edits, cx);
3734
3735 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3736 let mut index = 0;
3737 s.move_cursors_with(|map, _, _| {
3738 let row = rows[index];
3739 index += 1;
3740
3741 let point = Point::new(row, 0);
3742 let boundary = map.next_line_boundary(point).1;
3743 let clipped = map.clip_point(boundary, Bias::Left);
3744
3745 (clipped, SelectionGoal::None)
3746 });
3747 });
3748
3749 let mut indent_edits = Vec::new();
3750 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3751 for row in rows {
3752 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3753 for (row, indent) in indents {
3754 if indent.len == 0 {
3755 continue;
3756 }
3757
3758 let text = match indent.kind {
3759 IndentKind::Space => " ".repeat(indent.len as usize),
3760 IndentKind::Tab => "\t".repeat(indent.len as usize),
3761 };
3762 let point = Point::new(row.0, 0);
3763 indent_edits.push((point..point, text));
3764 }
3765 }
3766 editor.edit(indent_edits, cx);
3767 });
3768 }
3769
3770 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3771 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3772
3773 let buffer = self.buffer.read(cx);
3774 let snapshot = buffer.snapshot(cx);
3775
3776 let mut edits = Vec::new();
3777 let mut rows = Vec::new();
3778 let mut rows_inserted = 0;
3779
3780 for selection in self.selections.all_adjusted(cx) {
3781 let cursor = selection.head();
3782 let row = cursor.row;
3783
3784 let point = Point::new(row + 1, 0);
3785 let start_of_line = snapshot.clip_point(point, Bias::Left);
3786
3787 let newline = "\n".to_string();
3788 edits.push((start_of_line..start_of_line, newline));
3789
3790 rows_inserted += 1;
3791 rows.push(row + rows_inserted);
3792 }
3793
3794 self.transact(window, cx, |editor, window, cx| {
3795 editor.edit(edits, cx);
3796
3797 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3798 let mut index = 0;
3799 s.move_cursors_with(|map, _, _| {
3800 let row = rows[index];
3801 index += 1;
3802
3803 let point = Point::new(row, 0);
3804 let boundary = map.next_line_boundary(point).1;
3805 let clipped = map.clip_point(boundary, Bias::Left);
3806
3807 (clipped, SelectionGoal::None)
3808 });
3809 });
3810
3811 let mut indent_edits = Vec::new();
3812 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3813 for row in rows {
3814 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3815 for (row, indent) in indents {
3816 if indent.len == 0 {
3817 continue;
3818 }
3819
3820 let text = match indent.kind {
3821 IndentKind::Space => " ".repeat(indent.len as usize),
3822 IndentKind::Tab => "\t".repeat(indent.len as usize),
3823 };
3824 let point = Point::new(row.0, 0);
3825 indent_edits.push((point..point, text));
3826 }
3827 }
3828 editor.edit(indent_edits, cx);
3829 });
3830 }
3831
3832 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3833 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3834 original_indent_columns: Vec::new(),
3835 });
3836 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3837 }
3838
3839 fn insert_with_autoindent_mode(
3840 &mut self,
3841 text: &str,
3842 autoindent_mode: Option<AutoindentMode>,
3843 window: &mut Window,
3844 cx: &mut Context<Self>,
3845 ) {
3846 if self.read_only(cx) {
3847 return;
3848 }
3849
3850 let text: Arc<str> = text.into();
3851 self.transact(window, cx, |this, window, cx| {
3852 let old_selections = this.selections.all_adjusted(cx);
3853 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3854 let anchors = {
3855 let snapshot = buffer.read(cx);
3856 old_selections
3857 .iter()
3858 .map(|s| {
3859 let anchor = snapshot.anchor_after(s.head());
3860 s.map(|_| anchor)
3861 })
3862 .collect::<Vec<_>>()
3863 };
3864 buffer.edit(
3865 old_selections
3866 .iter()
3867 .map(|s| (s.start..s.end, text.clone())),
3868 autoindent_mode,
3869 cx,
3870 );
3871 anchors
3872 });
3873
3874 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3875 s.select_anchors(selection_anchors);
3876 });
3877
3878 cx.notify();
3879 });
3880 }
3881
3882 fn trigger_completion_on_input(
3883 &mut self,
3884 text: &str,
3885 trigger_in_words: bool,
3886 window: &mut Window,
3887 cx: &mut Context<Self>,
3888 ) {
3889 let ignore_completion_provider = self
3890 .context_menu
3891 .borrow()
3892 .as_ref()
3893 .map(|menu| match menu {
3894 CodeContextMenu::Completions(completions_menu) => {
3895 completions_menu.ignore_completion_provider
3896 }
3897 CodeContextMenu::CodeActions(_) => false,
3898 })
3899 .unwrap_or(false);
3900
3901 if ignore_completion_provider {
3902 self.show_word_completions(&ShowWordCompletions, window, cx);
3903 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3904 self.show_completions(
3905 &ShowCompletions {
3906 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3907 },
3908 window,
3909 cx,
3910 );
3911 } else {
3912 self.hide_context_menu(window, cx);
3913 }
3914 }
3915
3916 fn is_completion_trigger(
3917 &self,
3918 text: &str,
3919 trigger_in_words: bool,
3920 cx: &mut Context<Self>,
3921 ) -> bool {
3922 let position = self.selections.newest_anchor().head();
3923 let multibuffer = self.buffer.read(cx);
3924 let Some(buffer) = position
3925 .buffer_id
3926 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3927 else {
3928 return false;
3929 };
3930
3931 if let Some(completion_provider) = &self.completion_provider {
3932 completion_provider.is_completion_trigger(
3933 &buffer,
3934 position.text_anchor,
3935 text,
3936 trigger_in_words,
3937 cx,
3938 )
3939 } else {
3940 false
3941 }
3942 }
3943
3944 /// If any empty selections is touching the start of its innermost containing autoclose
3945 /// region, expand it to select the brackets.
3946 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3947 let selections = self.selections.all::<usize>(cx);
3948 let buffer = self.buffer.read(cx).read(cx);
3949 let new_selections = self
3950 .selections_with_autoclose_regions(selections, &buffer)
3951 .map(|(mut selection, region)| {
3952 if !selection.is_empty() {
3953 return selection;
3954 }
3955
3956 if let Some(region) = region {
3957 let mut range = region.range.to_offset(&buffer);
3958 if selection.start == range.start && range.start >= region.pair.start.len() {
3959 range.start -= region.pair.start.len();
3960 if buffer.contains_str_at(range.start, ®ion.pair.start)
3961 && buffer.contains_str_at(range.end, ®ion.pair.end)
3962 {
3963 range.end += region.pair.end.len();
3964 selection.start = range.start;
3965 selection.end = range.end;
3966
3967 return selection;
3968 }
3969 }
3970 }
3971
3972 let always_treat_brackets_as_autoclosed = buffer
3973 .language_settings_at(selection.start, cx)
3974 .always_treat_brackets_as_autoclosed;
3975
3976 if !always_treat_brackets_as_autoclosed {
3977 return selection;
3978 }
3979
3980 if let Some(scope) = buffer.language_scope_at(selection.start) {
3981 for (pair, enabled) in scope.brackets() {
3982 if !enabled || !pair.close {
3983 continue;
3984 }
3985
3986 if buffer.contains_str_at(selection.start, &pair.end) {
3987 let pair_start_len = pair.start.len();
3988 if buffer.contains_str_at(
3989 selection.start.saturating_sub(pair_start_len),
3990 &pair.start,
3991 ) {
3992 selection.start -= pair_start_len;
3993 selection.end += pair.end.len();
3994
3995 return selection;
3996 }
3997 }
3998 }
3999 }
4000
4001 selection
4002 })
4003 .collect();
4004
4005 drop(buffer);
4006 self.change_selections(None, window, cx, |selections| {
4007 selections.select(new_selections)
4008 });
4009 }
4010
4011 /// Iterate the given selections, and for each one, find the smallest surrounding
4012 /// autoclose region. This uses the ordering of the selections and the autoclose
4013 /// regions to avoid repeated comparisons.
4014 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4015 &'a self,
4016 selections: impl IntoIterator<Item = Selection<D>>,
4017 buffer: &'a MultiBufferSnapshot,
4018 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4019 let mut i = 0;
4020 let mut regions = self.autoclose_regions.as_slice();
4021 selections.into_iter().map(move |selection| {
4022 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4023
4024 let mut enclosing = None;
4025 while let Some(pair_state) = regions.get(i) {
4026 if pair_state.range.end.to_offset(buffer) < range.start {
4027 regions = ®ions[i + 1..];
4028 i = 0;
4029 } else if pair_state.range.start.to_offset(buffer) > range.end {
4030 break;
4031 } else {
4032 if pair_state.selection_id == selection.id {
4033 enclosing = Some(pair_state);
4034 }
4035 i += 1;
4036 }
4037 }
4038
4039 (selection, enclosing)
4040 })
4041 }
4042
4043 /// Remove any autoclose regions that no longer contain their selection.
4044 fn invalidate_autoclose_regions(
4045 &mut self,
4046 mut selections: &[Selection<Anchor>],
4047 buffer: &MultiBufferSnapshot,
4048 ) {
4049 self.autoclose_regions.retain(|state| {
4050 let mut i = 0;
4051 while let Some(selection) = selections.get(i) {
4052 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4053 selections = &selections[1..];
4054 continue;
4055 }
4056 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4057 break;
4058 }
4059 if selection.id == state.selection_id {
4060 return true;
4061 } else {
4062 i += 1;
4063 }
4064 }
4065 false
4066 });
4067 }
4068
4069 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4070 let offset = position.to_offset(buffer);
4071 let (word_range, kind) = buffer.surrounding_word(offset, true);
4072 if offset > word_range.start && kind == Some(CharKind::Word) {
4073 Some(
4074 buffer
4075 .text_for_range(word_range.start..offset)
4076 .collect::<String>(),
4077 )
4078 } else {
4079 None
4080 }
4081 }
4082
4083 pub fn toggle_inlay_hints(
4084 &mut self,
4085 _: &ToggleInlayHints,
4086 _: &mut Window,
4087 cx: &mut Context<Self>,
4088 ) {
4089 self.refresh_inlay_hints(
4090 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4091 cx,
4092 );
4093 }
4094
4095 pub fn inlay_hints_enabled(&self) -> bool {
4096 self.inlay_hint_cache.enabled
4097 }
4098
4099 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4100 if self.semantics_provider.is_none() || !self.mode.is_full() {
4101 return;
4102 }
4103
4104 let reason_description = reason.description();
4105 let ignore_debounce = matches!(
4106 reason,
4107 InlayHintRefreshReason::SettingsChange(_)
4108 | InlayHintRefreshReason::Toggle(_)
4109 | InlayHintRefreshReason::ExcerptsRemoved(_)
4110 | InlayHintRefreshReason::ModifiersChanged(_)
4111 );
4112 let (invalidate_cache, required_languages) = match reason {
4113 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4114 match self.inlay_hint_cache.modifiers_override(enabled) {
4115 Some(enabled) => {
4116 if enabled {
4117 (InvalidationStrategy::RefreshRequested, None)
4118 } else {
4119 self.splice_inlays(
4120 &self
4121 .visible_inlay_hints(cx)
4122 .iter()
4123 .map(|inlay| inlay.id)
4124 .collect::<Vec<InlayId>>(),
4125 Vec::new(),
4126 cx,
4127 );
4128 return;
4129 }
4130 }
4131 None => return,
4132 }
4133 }
4134 InlayHintRefreshReason::Toggle(enabled) => {
4135 if self.inlay_hint_cache.toggle(enabled) {
4136 if enabled {
4137 (InvalidationStrategy::RefreshRequested, None)
4138 } else {
4139 self.splice_inlays(
4140 &self
4141 .visible_inlay_hints(cx)
4142 .iter()
4143 .map(|inlay| inlay.id)
4144 .collect::<Vec<InlayId>>(),
4145 Vec::new(),
4146 cx,
4147 );
4148 return;
4149 }
4150 } else {
4151 return;
4152 }
4153 }
4154 InlayHintRefreshReason::SettingsChange(new_settings) => {
4155 match self.inlay_hint_cache.update_settings(
4156 &self.buffer,
4157 new_settings,
4158 self.visible_inlay_hints(cx),
4159 cx,
4160 ) {
4161 ControlFlow::Break(Some(InlaySplice {
4162 to_remove,
4163 to_insert,
4164 })) => {
4165 self.splice_inlays(&to_remove, to_insert, cx);
4166 return;
4167 }
4168 ControlFlow::Break(None) => return,
4169 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4170 }
4171 }
4172 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4173 if let Some(InlaySplice {
4174 to_remove,
4175 to_insert,
4176 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4177 {
4178 self.splice_inlays(&to_remove, to_insert, cx);
4179 }
4180 self.display_map.update(cx, |display_map, _| {
4181 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4182 });
4183 return;
4184 }
4185 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4186 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4187 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4188 }
4189 InlayHintRefreshReason::RefreshRequested => {
4190 (InvalidationStrategy::RefreshRequested, None)
4191 }
4192 };
4193
4194 if let Some(InlaySplice {
4195 to_remove,
4196 to_insert,
4197 }) = self.inlay_hint_cache.spawn_hint_refresh(
4198 reason_description,
4199 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4200 invalidate_cache,
4201 ignore_debounce,
4202 cx,
4203 ) {
4204 self.splice_inlays(&to_remove, to_insert, cx);
4205 }
4206 }
4207
4208 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4209 self.display_map
4210 .read(cx)
4211 .current_inlays()
4212 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4213 .cloned()
4214 .collect()
4215 }
4216
4217 pub fn excerpts_for_inlay_hints_query(
4218 &self,
4219 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4220 cx: &mut Context<Editor>,
4221 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4222 let Some(project) = self.project.as_ref() else {
4223 return HashMap::default();
4224 };
4225 let project = project.read(cx);
4226 let multi_buffer = self.buffer().read(cx);
4227 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4228 let multi_buffer_visible_start = self
4229 .scroll_manager
4230 .anchor()
4231 .anchor
4232 .to_point(&multi_buffer_snapshot);
4233 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4234 multi_buffer_visible_start
4235 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4236 Bias::Left,
4237 );
4238 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4239 multi_buffer_snapshot
4240 .range_to_buffer_ranges(multi_buffer_visible_range)
4241 .into_iter()
4242 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4243 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4244 let buffer_file = project::File::from_dyn(buffer.file())?;
4245 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4246 let worktree_entry = buffer_worktree
4247 .read(cx)
4248 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4249 if worktree_entry.is_ignored {
4250 return None;
4251 }
4252
4253 let language = buffer.language()?;
4254 if let Some(restrict_to_languages) = restrict_to_languages {
4255 if !restrict_to_languages.contains(language) {
4256 return None;
4257 }
4258 }
4259 Some((
4260 excerpt_id,
4261 (
4262 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4263 buffer.version().clone(),
4264 excerpt_visible_range,
4265 ),
4266 ))
4267 })
4268 .collect()
4269 }
4270
4271 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4272 TextLayoutDetails {
4273 text_system: window.text_system().clone(),
4274 editor_style: self.style.clone().unwrap(),
4275 rem_size: window.rem_size(),
4276 scroll_anchor: self.scroll_manager.anchor(),
4277 visible_rows: self.visible_line_count(),
4278 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4279 }
4280 }
4281
4282 pub fn splice_inlays(
4283 &self,
4284 to_remove: &[InlayId],
4285 to_insert: Vec<Inlay>,
4286 cx: &mut Context<Self>,
4287 ) {
4288 self.display_map.update(cx, |display_map, cx| {
4289 display_map.splice_inlays(to_remove, to_insert, cx)
4290 });
4291 cx.notify();
4292 }
4293
4294 fn trigger_on_type_formatting(
4295 &self,
4296 input: String,
4297 window: &mut Window,
4298 cx: &mut Context<Self>,
4299 ) -> Option<Task<Result<()>>> {
4300 if input.len() != 1 {
4301 return None;
4302 }
4303
4304 let project = self.project.as_ref()?;
4305 let position = self.selections.newest_anchor().head();
4306 let (buffer, buffer_position) = self
4307 .buffer
4308 .read(cx)
4309 .text_anchor_for_position(position, cx)?;
4310
4311 let settings = language_settings::language_settings(
4312 buffer
4313 .read(cx)
4314 .language_at(buffer_position)
4315 .map(|l| l.name()),
4316 buffer.read(cx).file(),
4317 cx,
4318 );
4319 if !settings.use_on_type_format {
4320 return None;
4321 }
4322
4323 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4324 // hence we do LSP request & edit on host side only — add formats to host's history.
4325 let push_to_lsp_host_history = true;
4326 // If this is not the host, append its history with new edits.
4327 let push_to_client_history = project.read(cx).is_via_collab();
4328
4329 let on_type_formatting = project.update(cx, |project, cx| {
4330 project.on_type_format(
4331 buffer.clone(),
4332 buffer_position,
4333 input,
4334 push_to_lsp_host_history,
4335 cx,
4336 )
4337 });
4338 Some(cx.spawn_in(window, async move |editor, cx| {
4339 if let Some(transaction) = on_type_formatting.await? {
4340 if push_to_client_history {
4341 buffer
4342 .update(cx, |buffer, _| {
4343 buffer.push_transaction(transaction, Instant::now());
4344 buffer.finalize_last_transaction();
4345 })
4346 .ok();
4347 }
4348 editor.update(cx, |editor, cx| {
4349 editor.refresh_document_highlights(cx);
4350 })?;
4351 }
4352 Ok(())
4353 }))
4354 }
4355
4356 pub fn show_word_completions(
4357 &mut self,
4358 _: &ShowWordCompletions,
4359 window: &mut Window,
4360 cx: &mut Context<Self>,
4361 ) {
4362 self.open_completions_menu(true, None, window, cx);
4363 }
4364
4365 pub fn show_completions(
4366 &mut self,
4367 options: &ShowCompletions,
4368 window: &mut Window,
4369 cx: &mut Context<Self>,
4370 ) {
4371 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4372 }
4373
4374 fn open_completions_menu(
4375 &mut self,
4376 ignore_completion_provider: bool,
4377 trigger: Option<&str>,
4378 window: &mut Window,
4379 cx: &mut Context<Self>,
4380 ) {
4381 if self.pending_rename.is_some() {
4382 return;
4383 }
4384 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4385 return;
4386 }
4387
4388 let position = self.selections.newest_anchor().head();
4389 if position.diff_base_anchor.is_some() {
4390 return;
4391 }
4392 let (buffer, buffer_position) =
4393 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4394 output
4395 } else {
4396 return;
4397 };
4398 let buffer_snapshot = buffer.read(cx).snapshot();
4399 let show_completion_documentation = buffer_snapshot
4400 .settings_at(buffer_position, cx)
4401 .show_completion_documentation;
4402
4403 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4404
4405 let trigger_kind = match trigger {
4406 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4407 CompletionTriggerKind::TRIGGER_CHARACTER
4408 }
4409 _ => CompletionTriggerKind::INVOKED,
4410 };
4411 let completion_context = CompletionContext {
4412 trigger_character: trigger.and_then(|trigger| {
4413 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4414 Some(String::from(trigger))
4415 } else {
4416 None
4417 }
4418 }),
4419 trigger_kind,
4420 };
4421
4422 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4423 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4424 let word_to_exclude = buffer_snapshot
4425 .text_for_range(old_range.clone())
4426 .collect::<String>();
4427 (
4428 buffer_snapshot.anchor_before(old_range.start)
4429 ..buffer_snapshot.anchor_after(old_range.end),
4430 Some(word_to_exclude),
4431 )
4432 } else {
4433 (buffer_position..buffer_position, None)
4434 };
4435
4436 let completion_settings = language_settings(
4437 buffer_snapshot
4438 .language_at(buffer_position)
4439 .map(|language| language.name()),
4440 buffer_snapshot.file(),
4441 cx,
4442 )
4443 .completions;
4444
4445 // The document can be large, so stay in reasonable bounds when searching for words,
4446 // otherwise completion pop-up might be slow to appear.
4447 const WORD_LOOKUP_ROWS: u32 = 5_000;
4448 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4449 let min_word_search = buffer_snapshot.clip_point(
4450 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4451 Bias::Left,
4452 );
4453 let max_word_search = buffer_snapshot.clip_point(
4454 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4455 Bias::Right,
4456 );
4457 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4458 ..buffer_snapshot.point_to_offset(max_word_search);
4459
4460 let provider = self
4461 .completion_provider
4462 .as_ref()
4463 .filter(|_| !ignore_completion_provider);
4464 let skip_digits = query
4465 .as_ref()
4466 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4467
4468 let (mut words, provided_completions) = match provider {
4469 Some(provider) => {
4470 let completions = provider.completions(
4471 position.excerpt_id,
4472 &buffer,
4473 buffer_position,
4474 completion_context,
4475 window,
4476 cx,
4477 );
4478
4479 let words = match completion_settings.words {
4480 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4481 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4482 .background_spawn(async move {
4483 buffer_snapshot.words_in_range(WordsQuery {
4484 fuzzy_contents: None,
4485 range: word_search_range,
4486 skip_digits,
4487 })
4488 }),
4489 };
4490
4491 (words, completions)
4492 }
4493 None => (
4494 cx.background_spawn(async move {
4495 buffer_snapshot.words_in_range(WordsQuery {
4496 fuzzy_contents: None,
4497 range: word_search_range,
4498 skip_digits,
4499 })
4500 }),
4501 Task::ready(Ok(None)),
4502 ),
4503 };
4504
4505 let sort_completions = provider
4506 .as_ref()
4507 .map_or(false, |provider| provider.sort_completions());
4508
4509 let filter_completions = provider
4510 .as_ref()
4511 .map_or(true, |provider| provider.filter_completions());
4512
4513 let id = post_inc(&mut self.next_completion_id);
4514 let task = cx.spawn_in(window, async move |editor, cx| {
4515 async move {
4516 editor.update(cx, |this, _| {
4517 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4518 })?;
4519
4520 let mut completions = Vec::new();
4521 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4522 completions.extend(provided_completions);
4523 if completion_settings.words == WordsCompletionMode::Fallback {
4524 words = Task::ready(BTreeMap::default());
4525 }
4526 }
4527
4528 let mut words = words.await;
4529 if let Some(word_to_exclude) = &word_to_exclude {
4530 words.remove(word_to_exclude);
4531 }
4532 for lsp_completion in &completions {
4533 words.remove(&lsp_completion.new_text);
4534 }
4535 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4536 replace_range: old_range.clone(),
4537 new_text: word.clone(),
4538 label: CodeLabel::plain(word, None),
4539 icon_path: None,
4540 documentation: None,
4541 source: CompletionSource::BufferWord {
4542 word_range,
4543 resolved: false,
4544 },
4545 insert_text_mode: Some(InsertTextMode::AS_IS),
4546 confirm: None,
4547 }));
4548
4549 let menu = if completions.is_empty() {
4550 None
4551 } else {
4552 let mut menu = CompletionsMenu::new(
4553 id,
4554 sort_completions,
4555 show_completion_documentation,
4556 ignore_completion_provider,
4557 position,
4558 buffer.clone(),
4559 completions.into(),
4560 );
4561
4562 menu.filter(
4563 if filter_completions {
4564 query.as_deref()
4565 } else {
4566 None
4567 },
4568 cx.background_executor().clone(),
4569 )
4570 .await;
4571
4572 menu.visible().then_some(menu)
4573 };
4574
4575 editor.update_in(cx, |editor, window, cx| {
4576 match editor.context_menu.borrow().as_ref() {
4577 None => {}
4578 Some(CodeContextMenu::Completions(prev_menu)) => {
4579 if prev_menu.id > id {
4580 return;
4581 }
4582 }
4583 _ => return,
4584 }
4585
4586 if editor.focus_handle.is_focused(window) && menu.is_some() {
4587 let mut menu = menu.unwrap();
4588 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4589
4590 *editor.context_menu.borrow_mut() =
4591 Some(CodeContextMenu::Completions(menu));
4592
4593 if editor.show_edit_predictions_in_menu() {
4594 editor.update_visible_inline_completion(window, cx);
4595 } else {
4596 editor.discard_inline_completion(false, cx);
4597 }
4598
4599 cx.notify();
4600 } else if editor.completion_tasks.len() <= 1 {
4601 // If there are no more completion tasks and the last menu was
4602 // empty, we should hide it.
4603 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4604 // If it was already hidden and we don't show inline
4605 // completions in the menu, we should also show the
4606 // inline-completion when available.
4607 if was_hidden && editor.show_edit_predictions_in_menu() {
4608 editor.update_visible_inline_completion(window, cx);
4609 }
4610 }
4611 })?;
4612
4613 anyhow::Ok(())
4614 }
4615 .log_err()
4616 .await
4617 });
4618
4619 self.completion_tasks.push((id, task));
4620 }
4621
4622 #[cfg(feature = "test-support")]
4623 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4624 let menu = self.context_menu.borrow();
4625 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4626 let completions = menu.completions.borrow();
4627 Some(completions.to_vec())
4628 } else {
4629 None
4630 }
4631 }
4632
4633 pub fn confirm_completion(
4634 &mut self,
4635 action: &ConfirmCompletion,
4636 window: &mut Window,
4637 cx: &mut Context<Self>,
4638 ) -> Option<Task<Result<()>>> {
4639 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4640 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4641 }
4642
4643 pub fn confirm_completion_insert(
4644 &mut self,
4645 _: &ConfirmCompletionInsert,
4646 window: &mut Window,
4647 cx: &mut Context<Self>,
4648 ) -> Option<Task<Result<()>>> {
4649 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4650 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4651 }
4652
4653 pub fn confirm_completion_replace(
4654 &mut self,
4655 _: &ConfirmCompletionReplace,
4656 window: &mut Window,
4657 cx: &mut Context<Self>,
4658 ) -> Option<Task<Result<()>>> {
4659 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4660 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4661 }
4662
4663 pub fn compose_completion(
4664 &mut self,
4665 action: &ComposeCompletion,
4666 window: &mut Window,
4667 cx: &mut Context<Self>,
4668 ) -> Option<Task<Result<()>>> {
4669 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4670 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4671 }
4672
4673 fn do_completion(
4674 &mut self,
4675 item_ix: Option<usize>,
4676 intent: CompletionIntent,
4677 window: &mut Window,
4678 cx: &mut Context<Editor>,
4679 ) -> Option<Task<Result<()>>> {
4680 use language::ToOffset as _;
4681
4682 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4683 else {
4684 return None;
4685 };
4686
4687 let candidate_id = {
4688 let entries = completions_menu.entries.borrow();
4689 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4690 if self.show_edit_predictions_in_menu() {
4691 self.discard_inline_completion(true, cx);
4692 }
4693 mat.candidate_id
4694 };
4695
4696 let buffer_handle = completions_menu.buffer;
4697 let completion = completions_menu
4698 .completions
4699 .borrow()
4700 .get(candidate_id)?
4701 .clone();
4702 cx.stop_propagation();
4703
4704 let snippet;
4705 let new_text;
4706 if completion.is_snippet() {
4707 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4708 new_text = snippet.as_ref().unwrap().text.clone();
4709 } else {
4710 snippet = None;
4711 new_text = completion.new_text.clone();
4712 };
4713
4714 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4715 let buffer = buffer_handle.read(cx);
4716 let snapshot = self.buffer.read(cx).snapshot(cx);
4717 let replace_range_multibuffer = {
4718 let excerpt = snapshot
4719 .excerpt_containing(self.selections.newest_anchor().range())
4720 .unwrap();
4721 let multibuffer_anchor = snapshot
4722 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4723 .unwrap()
4724 ..snapshot
4725 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4726 .unwrap();
4727 multibuffer_anchor.start.to_offset(&snapshot)
4728 ..multibuffer_anchor.end.to_offset(&snapshot)
4729 };
4730 let newest_anchor = self.selections.newest_anchor();
4731 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4732 return None;
4733 }
4734
4735 let old_text = buffer
4736 .text_for_range(replace_range.clone())
4737 .collect::<String>();
4738 let lookbehind = newest_anchor
4739 .start
4740 .text_anchor
4741 .to_offset(buffer)
4742 .saturating_sub(replace_range.start);
4743 let lookahead = replace_range
4744 .end
4745 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4746 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4747 let suffix = &old_text[lookbehind.min(old_text.len())..];
4748
4749 let selections = self.selections.all::<usize>(cx);
4750 let mut ranges = Vec::new();
4751 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4752
4753 for selection in &selections {
4754 let range = if selection.id == newest_anchor.id {
4755 replace_range_multibuffer.clone()
4756 } else {
4757 let mut range = selection.range();
4758
4759 // if prefix is present, don't duplicate it
4760 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4761 range.start = range.start.saturating_sub(lookbehind);
4762
4763 // if suffix is also present, mimic the newest cursor and replace it
4764 if selection.id != newest_anchor.id
4765 && snapshot.contains_str_at(range.end, suffix)
4766 {
4767 range.end += lookahead;
4768 }
4769 }
4770 range
4771 };
4772
4773 ranges.push(range);
4774
4775 if !self.linked_edit_ranges.is_empty() {
4776 let start_anchor = snapshot.anchor_before(selection.head());
4777 let end_anchor = snapshot.anchor_after(selection.tail());
4778 if let Some(ranges) = self
4779 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4780 {
4781 for (buffer, edits) in ranges {
4782 linked_edits
4783 .entry(buffer.clone())
4784 .or_default()
4785 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
4786 }
4787 }
4788 }
4789 }
4790
4791 cx.emit(EditorEvent::InputHandled {
4792 utf16_range_to_replace: None,
4793 text: new_text.clone().into(),
4794 });
4795
4796 self.transact(window, cx, |this, window, cx| {
4797 if let Some(mut snippet) = snippet {
4798 snippet.text = new_text.to_string();
4799 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4800 } else {
4801 this.buffer.update(cx, |buffer, cx| {
4802 let auto_indent = match completion.insert_text_mode {
4803 Some(InsertTextMode::AS_IS) => None,
4804 _ => this.autoindent_mode.clone(),
4805 };
4806 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
4807 buffer.edit(edits, auto_indent, cx);
4808 });
4809 }
4810 for (buffer, edits) in linked_edits {
4811 buffer.update(cx, |buffer, cx| {
4812 let snapshot = buffer.snapshot();
4813 let edits = edits
4814 .into_iter()
4815 .map(|(range, text)| {
4816 use text::ToPoint as TP;
4817 let end_point = TP::to_point(&range.end, &snapshot);
4818 let start_point = TP::to_point(&range.start, &snapshot);
4819 (start_point..end_point, text)
4820 })
4821 .sorted_by_key(|(range, _)| range.start);
4822 buffer.edit(edits, None, cx);
4823 })
4824 }
4825
4826 this.refresh_inline_completion(true, false, window, cx);
4827 });
4828
4829 let show_new_completions_on_confirm = completion
4830 .confirm
4831 .as_ref()
4832 .map_or(false, |confirm| confirm(intent, window, cx));
4833 if show_new_completions_on_confirm {
4834 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4835 }
4836
4837 let provider = self.completion_provider.as_ref()?;
4838 drop(completion);
4839 let apply_edits = provider.apply_additional_edits_for_completion(
4840 buffer_handle,
4841 completions_menu.completions.clone(),
4842 candidate_id,
4843 true,
4844 cx,
4845 );
4846
4847 let editor_settings = EditorSettings::get_global(cx);
4848 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4849 // After the code completion is finished, users often want to know what signatures are needed.
4850 // so we should automatically call signature_help
4851 self.show_signature_help(&ShowSignatureHelp, window, cx);
4852 }
4853
4854 Some(cx.foreground_executor().spawn(async move {
4855 apply_edits.await?;
4856 Ok(())
4857 }))
4858 }
4859
4860 fn prepare_code_actions_task(
4861 &mut self,
4862 action: &ToggleCodeActions,
4863 window: &mut Window,
4864 cx: &mut Context<Self>,
4865 ) -> Task<Option<(Entity<Buffer>, CodeActionContents)>> {
4866 let snapshot = self.snapshot(window, cx);
4867 let multibuffer_point = action
4868 .deployed_from_indicator
4869 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4870 .unwrap_or_else(|| self.selections.newest::<Point>(cx).head());
4871
4872 let Some((buffer, buffer_row)) = snapshot
4873 .buffer_snapshot
4874 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4875 .and_then(|(buffer_snapshot, range)| {
4876 self.buffer
4877 .read(cx)
4878 .buffer(buffer_snapshot.remote_id())
4879 .map(|buffer| (buffer, range.start.row))
4880 })
4881 else {
4882 return Task::ready(None);
4883 };
4884
4885 let (_, code_actions) = self
4886 .available_code_actions
4887 .clone()
4888 .and_then(|(location, code_actions)| {
4889 let snapshot = location.buffer.read(cx).snapshot();
4890 let point_range = location.range.to_point(&snapshot);
4891 let point_range = point_range.start.row..=point_range.end.row;
4892 if point_range.contains(&buffer_row) {
4893 Some((location, code_actions))
4894 } else {
4895 None
4896 }
4897 })
4898 .unzip();
4899
4900 let buffer_id = buffer.read(cx).remote_id();
4901 let tasks = self
4902 .tasks
4903 .get(&(buffer_id, buffer_row))
4904 .map(|t| Arc::new(t.to_owned()));
4905
4906 if tasks.is_none() && code_actions.is_none() {
4907 return Task::ready(None);
4908 }
4909
4910 self.completion_tasks.clear();
4911 self.discard_inline_completion(false, cx);
4912
4913 let task_context = tasks
4914 .as_ref()
4915 .zip(self.project.clone())
4916 .map(|(tasks, project)| {
4917 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4918 });
4919
4920 cx.spawn_in(window, async move |_, cx| {
4921 let task_context = match task_context {
4922 Some(task_context) => task_context.await,
4923 None => None,
4924 };
4925 let resolved_tasks =
4926 tasks
4927 .zip(task_context)
4928 .map(|(tasks, task_context)| ResolvedTasks {
4929 templates: tasks.resolve(&task_context).collect(),
4930 position: snapshot
4931 .buffer_snapshot
4932 .anchor_before(Point::new(multibuffer_point.row, tasks.column)),
4933 });
4934 let code_action_contents = cx
4935 .update(|_, cx| CodeActionContents::new(resolved_tasks, code_actions, cx))
4936 .ok()?;
4937 Some((buffer, code_action_contents))
4938 })
4939 }
4940
4941 pub fn toggle_code_actions(
4942 &mut self,
4943 action: &ToggleCodeActions,
4944 window: &mut Window,
4945 cx: &mut Context<Self>,
4946 ) {
4947 let mut context_menu = self.context_menu.borrow_mut();
4948 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4949 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4950 // Toggle if we're selecting the same one
4951 *context_menu = None;
4952 cx.notify();
4953 return;
4954 } else {
4955 // Otherwise, clear it and start a new one
4956 *context_menu = None;
4957 cx.notify();
4958 }
4959 }
4960 drop(context_menu);
4961
4962 let deployed_from_indicator = action.deployed_from_indicator;
4963 let mut task = self.code_actions_task.take();
4964 let action = action.clone();
4965
4966 cx.spawn_in(window, async move |editor, cx| {
4967 while let Some(prev_task) = task {
4968 prev_task.await.log_err();
4969 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4970 }
4971
4972 let context_menu_task = editor.update_in(cx, |editor, window, cx| {
4973 if !editor.focus_handle.is_focused(window) {
4974 return Some(Task::ready(Ok(())));
4975 }
4976 let debugger_flag = cx.has_flag::<Debugger>();
4977 let code_actions_task = editor.prepare_code_actions_task(&action, window, cx);
4978 Some(cx.spawn_in(window, async move |editor, cx| {
4979 if let Some((buffer, code_action_contents)) = code_actions_task.await {
4980 let spawn_straight_away =
4981 code_action_contents.tasks().map_or(false, |tasks| {
4982 tasks
4983 .templates
4984 .iter()
4985 .filter(|task| {
4986 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4987 debugger_flag
4988 } else {
4989 true
4990 }
4991 })
4992 .count()
4993 == 1
4994 }) && code_action_contents
4995 .actions
4996 .as_ref()
4997 .map_or(true, |actions| actions.is_empty());
4998 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4999 *editor.context_menu.borrow_mut() =
5000 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5001 buffer,
5002 actions: code_action_contents,
5003 selected_item: Default::default(),
5004 scroll_handle: UniformListScrollHandle::default(),
5005 deployed_from_indicator,
5006 }));
5007 if spawn_straight_away {
5008 if let Some(task) = editor.confirm_code_action(
5009 &ConfirmCodeAction {
5010 item_ix: Some(0),
5011 from_mouse_context_menu: false,
5012 },
5013 window,
5014 cx,
5015 ) {
5016 cx.notify();
5017 return task;
5018 }
5019 }
5020 cx.notify();
5021 Task::ready(Ok(()))
5022 }) {
5023 task.await
5024 } else {
5025 Ok(())
5026 }
5027 } else {
5028 Ok(())
5029 }
5030 }))
5031 })?;
5032 if let Some(task) = context_menu_task {
5033 task.await?;
5034 }
5035
5036 Ok::<_, anyhow::Error>(())
5037 })
5038 .detach_and_log_err(cx);
5039 }
5040
5041 pub fn confirm_code_action(
5042 &mut self,
5043 action: &ConfirmCodeAction,
5044 window: &mut Window,
5045 cx: &mut Context<Self>,
5046 ) -> Option<Task<Result<()>>> {
5047 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5048
5049 let (action, buffer) = if action.from_mouse_context_menu {
5050 if let Some(menu) = self.mouse_context_menu.take() {
5051 let code_action = menu.code_action?;
5052 let index = action.item_ix?;
5053 let action = code_action.actions.get(index)?;
5054 (action, code_action.buffer)
5055 } else {
5056 return None;
5057 }
5058 } else {
5059 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5060 let action_ix = action.item_ix.unwrap_or(menu.selected_item);
5061 let action = menu.actions.get(action_ix)?;
5062 let buffer = menu.buffer;
5063 (action, buffer)
5064 } else {
5065 return None;
5066 }
5067 };
5068
5069 let title = action.label();
5070 let workspace = self.workspace()?;
5071
5072 match action {
5073 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5074 match resolved_task.task_type() {
5075 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5076 workspace::tasks::schedule_resolved_task(
5077 workspace,
5078 task_source_kind,
5079 resolved_task,
5080 false,
5081 cx,
5082 );
5083
5084 Some(Task::ready(Ok(())))
5085 }),
5086 task::TaskType::Debug(debug_args) => {
5087 if debug_args.locator.is_some() {
5088 workspace.update(cx, |workspace, cx| {
5089 workspace::tasks::schedule_resolved_task(
5090 workspace,
5091 task_source_kind,
5092 resolved_task,
5093 false,
5094 cx,
5095 );
5096 });
5097
5098 return Some(Task::ready(Ok(())));
5099 }
5100
5101 if let Some(project) = self.project.as_ref() {
5102 project
5103 .update(cx, |project, cx| {
5104 project.start_debug_session(
5105 resolved_task.resolved_debug_adapter_config().unwrap(),
5106 cx,
5107 )
5108 })
5109 .detach_and_log_err(cx);
5110 Some(Task::ready(Ok(())))
5111 } else {
5112 Some(Task::ready(Ok(())))
5113 }
5114 }
5115 }
5116 }
5117 CodeActionsItem::CodeAction {
5118 excerpt_id,
5119 action,
5120 provider,
5121 } => {
5122 let apply_code_action =
5123 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5124 let workspace = workspace.downgrade();
5125 Some(cx.spawn_in(window, async move |editor, cx| {
5126 let project_transaction = apply_code_action.await?;
5127 Self::open_project_transaction(
5128 &editor,
5129 workspace,
5130 project_transaction,
5131 title,
5132 cx,
5133 )
5134 .await
5135 }))
5136 }
5137 }
5138 }
5139
5140 pub async fn open_project_transaction(
5141 this: &WeakEntity<Editor>,
5142 workspace: WeakEntity<Workspace>,
5143 transaction: ProjectTransaction,
5144 title: String,
5145 cx: &mut AsyncWindowContext,
5146 ) -> Result<()> {
5147 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5148 cx.update(|_, cx| {
5149 entries.sort_unstable_by_key(|(buffer, _)| {
5150 buffer.read(cx).file().map(|f| f.path().clone())
5151 });
5152 })?;
5153
5154 // If the project transaction's edits are all contained within this editor, then
5155 // avoid opening a new editor to display them.
5156
5157 if let Some((buffer, transaction)) = entries.first() {
5158 if entries.len() == 1 {
5159 let excerpt = this.update(cx, |editor, cx| {
5160 editor
5161 .buffer()
5162 .read(cx)
5163 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5164 })?;
5165 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5166 if excerpted_buffer == *buffer {
5167 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5168 let excerpt_range = excerpt_range.to_offset(buffer);
5169 buffer
5170 .edited_ranges_for_transaction::<usize>(transaction)
5171 .all(|range| {
5172 excerpt_range.start <= range.start
5173 && excerpt_range.end >= range.end
5174 })
5175 })?;
5176
5177 if all_edits_within_excerpt {
5178 return Ok(());
5179 }
5180 }
5181 }
5182 }
5183 } else {
5184 return Ok(());
5185 }
5186
5187 let mut ranges_to_highlight = Vec::new();
5188 let excerpt_buffer = cx.new(|cx| {
5189 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5190 for (buffer_handle, transaction) in &entries {
5191 let edited_ranges = buffer_handle
5192 .read(cx)
5193 .edited_ranges_for_transaction::<Point>(transaction)
5194 .collect::<Vec<_>>();
5195 let (ranges, _) = multibuffer.set_excerpts_for_path(
5196 PathKey::for_buffer(buffer_handle, cx),
5197 buffer_handle.clone(),
5198 edited_ranges,
5199 DEFAULT_MULTIBUFFER_CONTEXT,
5200 cx,
5201 );
5202
5203 ranges_to_highlight.extend(ranges);
5204 }
5205 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5206 multibuffer
5207 })?;
5208
5209 workspace.update_in(cx, |workspace, window, cx| {
5210 let project = workspace.project().clone();
5211 let editor =
5212 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5213 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5214 editor.update(cx, |editor, cx| {
5215 editor.highlight_background::<Self>(
5216 &ranges_to_highlight,
5217 |theme| theme.editor_highlighted_line_background,
5218 cx,
5219 );
5220 });
5221 })?;
5222
5223 Ok(())
5224 }
5225
5226 pub fn clear_code_action_providers(&mut self) {
5227 self.code_action_providers.clear();
5228 self.available_code_actions.take();
5229 }
5230
5231 pub fn add_code_action_provider(
5232 &mut self,
5233 provider: Rc<dyn CodeActionProvider>,
5234 window: &mut Window,
5235 cx: &mut Context<Self>,
5236 ) {
5237 if self
5238 .code_action_providers
5239 .iter()
5240 .any(|existing_provider| existing_provider.id() == provider.id())
5241 {
5242 return;
5243 }
5244
5245 self.code_action_providers.push(provider);
5246 self.refresh_code_actions(window, cx);
5247 }
5248
5249 pub fn remove_code_action_provider(
5250 &mut self,
5251 id: Arc<str>,
5252 window: &mut Window,
5253 cx: &mut Context<Self>,
5254 ) {
5255 self.code_action_providers
5256 .retain(|provider| provider.id() != id);
5257 self.refresh_code_actions(window, cx);
5258 }
5259
5260 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5261 let newest_selection = self.selections.newest_anchor().clone();
5262 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5263 let buffer = self.buffer.read(cx);
5264 if newest_selection.head().diff_base_anchor.is_some() {
5265 return None;
5266 }
5267 let (start_buffer, start) =
5268 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5269 let (end_buffer, end) =
5270 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5271 if start_buffer != end_buffer {
5272 return None;
5273 }
5274
5275 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5276 cx.background_executor()
5277 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5278 .await;
5279
5280 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5281 let providers = this.code_action_providers.clone();
5282 let tasks = this
5283 .code_action_providers
5284 .iter()
5285 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5286 .collect::<Vec<_>>();
5287 (providers, tasks)
5288 })?;
5289
5290 let mut actions = Vec::new();
5291 for (provider, provider_actions) in
5292 providers.into_iter().zip(future::join_all(tasks).await)
5293 {
5294 if let Some(provider_actions) = provider_actions.log_err() {
5295 actions.extend(provider_actions.into_iter().map(|action| {
5296 AvailableCodeAction {
5297 excerpt_id: newest_selection.start.excerpt_id,
5298 action,
5299 provider: provider.clone(),
5300 }
5301 }));
5302 }
5303 }
5304
5305 this.update(cx, |this, cx| {
5306 this.available_code_actions = if actions.is_empty() {
5307 None
5308 } else {
5309 Some((
5310 Location {
5311 buffer: start_buffer,
5312 range: start..end,
5313 },
5314 actions.into(),
5315 ))
5316 };
5317 cx.notify();
5318 })
5319 }));
5320 None
5321 }
5322
5323 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5324 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5325 self.show_git_blame_inline = false;
5326
5327 self.show_git_blame_inline_delay_task =
5328 Some(cx.spawn_in(window, async move |this, cx| {
5329 cx.background_executor().timer(delay).await;
5330
5331 this.update(cx, |this, cx| {
5332 this.show_git_blame_inline = true;
5333 cx.notify();
5334 })
5335 .log_err();
5336 }));
5337 }
5338 }
5339
5340 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5341 if self.pending_rename.is_some() {
5342 return None;
5343 }
5344
5345 let provider = self.semantics_provider.clone()?;
5346 let buffer = self.buffer.read(cx);
5347 let newest_selection = self.selections.newest_anchor().clone();
5348 let cursor_position = newest_selection.head();
5349 let (cursor_buffer, cursor_buffer_position) =
5350 buffer.text_anchor_for_position(cursor_position, cx)?;
5351 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5352 if cursor_buffer != tail_buffer {
5353 return None;
5354 }
5355 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5356 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5357 cx.background_executor()
5358 .timer(Duration::from_millis(debounce))
5359 .await;
5360
5361 let highlights = if let Some(highlights) = cx
5362 .update(|cx| {
5363 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5364 })
5365 .ok()
5366 .flatten()
5367 {
5368 highlights.await.log_err()
5369 } else {
5370 None
5371 };
5372
5373 if let Some(highlights) = highlights {
5374 this.update(cx, |this, cx| {
5375 if this.pending_rename.is_some() {
5376 return;
5377 }
5378
5379 let buffer_id = cursor_position.buffer_id;
5380 let buffer = this.buffer.read(cx);
5381 if !buffer
5382 .text_anchor_for_position(cursor_position, cx)
5383 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5384 {
5385 return;
5386 }
5387
5388 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5389 let mut write_ranges = Vec::new();
5390 let mut read_ranges = Vec::new();
5391 for highlight in highlights {
5392 for (excerpt_id, excerpt_range) in
5393 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5394 {
5395 let start = highlight
5396 .range
5397 .start
5398 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5399 let end = highlight
5400 .range
5401 .end
5402 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5403 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5404 continue;
5405 }
5406
5407 let range = Anchor {
5408 buffer_id,
5409 excerpt_id,
5410 text_anchor: start,
5411 diff_base_anchor: None,
5412 }..Anchor {
5413 buffer_id,
5414 excerpt_id,
5415 text_anchor: end,
5416 diff_base_anchor: None,
5417 };
5418 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5419 write_ranges.push(range);
5420 } else {
5421 read_ranges.push(range);
5422 }
5423 }
5424 }
5425
5426 this.highlight_background::<DocumentHighlightRead>(
5427 &read_ranges,
5428 |theme| theme.editor_document_highlight_read_background,
5429 cx,
5430 );
5431 this.highlight_background::<DocumentHighlightWrite>(
5432 &write_ranges,
5433 |theme| theme.editor_document_highlight_write_background,
5434 cx,
5435 );
5436 cx.notify();
5437 })
5438 .log_err();
5439 }
5440 }));
5441 None
5442 }
5443
5444 fn prepare_highlight_query_from_selection(
5445 &mut self,
5446 cx: &mut Context<Editor>,
5447 ) -> Option<(String, Range<Anchor>)> {
5448 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5449 return None;
5450 }
5451 if !EditorSettings::get_global(cx).selection_highlight {
5452 return None;
5453 }
5454 if self.selections.count() != 1 || self.selections.line_mode {
5455 return None;
5456 }
5457 let selection = self.selections.newest::<Point>(cx);
5458 if selection.is_empty() || selection.start.row != selection.end.row {
5459 return None;
5460 }
5461 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5462 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5463 let query = multi_buffer_snapshot
5464 .text_for_range(selection_anchor_range.clone())
5465 .collect::<String>();
5466 if query.trim().is_empty() {
5467 return None;
5468 }
5469 Some((query, selection_anchor_range))
5470 }
5471
5472 fn update_selection_occurrence_highlights(
5473 &mut self,
5474 query_text: String,
5475 query_range: Range<Anchor>,
5476 multi_buffer_range_to_query: Range<Point>,
5477 use_debounce: bool,
5478 window: &mut Window,
5479 cx: &mut Context<Editor>,
5480 ) -> Task<()> {
5481 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5482 cx.spawn_in(window, async move |editor, cx| {
5483 if use_debounce {
5484 cx.background_executor()
5485 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5486 .await;
5487 }
5488 let match_task = cx.background_spawn(async move {
5489 let buffer_ranges = multi_buffer_snapshot
5490 .range_to_buffer_ranges(multi_buffer_range_to_query)
5491 .into_iter()
5492 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5493 let mut match_ranges = Vec::new();
5494 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5495 match_ranges.extend(
5496 project::search::SearchQuery::text(
5497 query_text.clone(),
5498 false,
5499 false,
5500 false,
5501 Default::default(),
5502 Default::default(),
5503 None,
5504 )
5505 .unwrap()
5506 .search(&buffer_snapshot, Some(search_range.clone()))
5507 .await
5508 .into_iter()
5509 .filter_map(|match_range| {
5510 let match_start = buffer_snapshot
5511 .anchor_after(search_range.start + match_range.start);
5512 let match_end =
5513 buffer_snapshot.anchor_before(search_range.start + match_range.end);
5514 let match_anchor_range = Anchor::range_in_buffer(
5515 excerpt_id,
5516 buffer_snapshot.remote_id(),
5517 match_start..match_end,
5518 );
5519 (match_anchor_range != query_range).then_some(match_anchor_range)
5520 }),
5521 );
5522 }
5523 match_ranges
5524 });
5525 let match_ranges = match_task.await;
5526 editor
5527 .update_in(cx, |editor, _, cx| {
5528 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5529 if !match_ranges.is_empty() {
5530 editor.highlight_background::<SelectedTextHighlight>(
5531 &match_ranges,
5532 |theme| theme.editor_document_highlight_bracket_background,
5533 cx,
5534 )
5535 }
5536 })
5537 .log_err();
5538 })
5539 }
5540
5541 fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
5542 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5543 else {
5544 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5545 self.quick_selection_highlight_task.take();
5546 self.debounced_selection_highlight_task.take();
5547 return;
5548 };
5549 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5550 if self
5551 .quick_selection_highlight_task
5552 .as_ref()
5553 .map_or(true, |(prev_anchor_range, _)| {
5554 prev_anchor_range != &query_range
5555 })
5556 {
5557 let multi_buffer_visible_start = self
5558 .scroll_manager
5559 .anchor()
5560 .anchor
5561 .to_point(&multi_buffer_snapshot);
5562 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5563 multi_buffer_visible_start
5564 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5565 Bias::Left,
5566 );
5567 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5568 self.quick_selection_highlight_task = Some((
5569 query_range.clone(),
5570 self.update_selection_occurrence_highlights(
5571 query_text.clone(),
5572 query_range.clone(),
5573 multi_buffer_visible_range,
5574 false,
5575 window,
5576 cx,
5577 ),
5578 ));
5579 }
5580 if self
5581 .debounced_selection_highlight_task
5582 .as_ref()
5583 .map_or(true, |(prev_anchor_range, _)| {
5584 prev_anchor_range != &query_range
5585 })
5586 {
5587 let multi_buffer_start = multi_buffer_snapshot
5588 .anchor_before(0)
5589 .to_point(&multi_buffer_snapshot);
5590 let multi_buffer_end = multi_buffer_snapshot
5591 .anchor_after(multi_buffer_snapshot.len())
5592 .to_point(&multi_buffer_snapshot);
5593 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5594 self.debounced_selection_highlight_task = Some((
5595 query_range.clone(),
5596 self.update_selection_occurrence_highlights(
5597 query_text,
5598 query_range,
5599 multi_buffer_full_range,
5600 true,
5601 window,
5602 cx,
5603 ),
5604 ));
5605 }
5606 }
5607
5608 pub fn refresh_inline_completion(
5609 &mut self,
5610 debounce: bool,
5611 user_requested: bool,
5612 window: &mut Window,
5613 cx: &mut Context<Self>,
5614 ) -> Option<()> {
5615 let provider = self.edit_prediction_provider()?;
5616 let cursor = self.selections.newest_anchor().head();
5617 let (buffer, cursor_buffer_position) =
5618 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5619
5620 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5621 self.discard_inline_completion(false, cx);
5622 return None;
5623 }
5624
5625 if !user_requested
5626 && (!self.should_show_edit_predictions()
5627 || !self.is_focused(window)
5628 || buffer.read(cx).is_empty())
5629 {
5630 self.discard_inline_completion(false, cx);
5631 return None;
5632 }
5633
5634 self.update_visible_inline_completion(window, cx);
5635 provider.refresh(
5636 self.project.clone(),
5637 buffer,
5638 cursor_buffer_position,
5639 debounce,
5640 cx,
5641 );
5642 Some(())
5643 }
5644
5645 fn show_edit_predictions_in_menu(&self) -> bool {
5646 match self.edit_prediction_settings {
5647 EditPredictionSettings::Disabled => false,
5648 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5649 }
5650 }
5651
5652 pub fn edit_predictions_enabled(&self) -> bool {
5653 match self.edit_prediction_settings {
5654 EditPredictionSettings::Disabled => false,
5655 EditPredictionSettings::Enabled { .. } => true,
5656 }
5657 }
5658
5659 fn edit_prediction_requires_modifier(&self) -> bool {
5660 match self.edit_prediction_settings {
5661 EditPredictionSettings::Disabled => false,
5662 EditPredictionSettings::Enabled {
5663 preview_requires_modifier,
5664 ..
5665 } => preview_requires_modifier,
5666 }
5667 }
5668
5669 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5670 if self.edit_prediction_provider.is_none() {
5671 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5672 } else {
5673 let selection = self.selections.newest_anchor();
5674 let cursor = selection.head();
5675
5676 if let Some((buffer, cursor_buffer_position)) =
5677 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5678 {
5679 self.edit_prediction_settings =
5680 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5681 }
5682 }
5683 }
5684
5685 fn edit_prediction_settings_at_position(
5686 &self,
5687 buffer: &Entity<Buffer>,
5688 buffer_position: language::Anchor,
5689 cx: &App,
5690 ) -> EditPredictionSettings {
5691 if !self.mode.is_full()
5692 || !self.show_inline_completions_override.unwrap_or(true)
5693 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5694 {
5695 return EditPredictionSettings::Disabled;
5696 }
5697
5698 let buffer = buffer.read(cx);
5699
5700 let file = buffer.file();
5701
5702 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5703 return EditPredictionSettings::Disabled;
5704 };
5705
5706 let by_provider = matches!(
5707 self.menu_inline_completions_policy,
5708 MenuInlineCompletionsPolicy::ByProvider
5709 );
5710
5711 let show_in_menu = by_provider
5712 && self
5713 .edit_prediction_provider
5714 .as_ref()
5715 .map_or(false, |provider| {
5716 provider.provider.show_completions_in_menu()
5717 });
5718
5719 let preview_requires_modifier =
5720 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5721
5722 EditPredictionSettings::Enabled {
5723 show_in_menu,
5724 preview_requires_modifier,
5725 }
5726 }
5727
5728 fn should_show_edit_predictions(&self) -> bool {
5729 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5730 }
5731
5732 pub fn edit_prediction_preview_is_active(&self) -> bool {
5733 matches!(
5734 self.edit_prediction_preview,
5735 EditPredictionPreview::Active { .. }
5736 )
5737 }
5738
5739 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5740 let cursor = self.selections.newest_anchor().head();
5741 if let Some((buffer, cursor_position)) =
5742 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5743 {
5744 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5745 } else {
5746 false
5747 }
5748 }
5749
5750 fn edit_predictions_enabled_in_buffer(
5751 &self,
5752 buffer: &Entity<Buffer>,
5753 buffer_position: language::Anchor,
5754 cx: &App,
5755 ) -> bool {
5756 maybe!({
5757 if self.read_only(cx) {
5758 return Some(false);
5759 }
5760 let provider = self.edit_prediction_provider()?;
5761 if !provider.is_enabled(&buffer, buffer_position, cx) {
5762 return Some(false);
5763 }
5764 let buffer = buffer.read(cx);
5765 let Some(file) = buffer.file() else {
5766 return Some(true);
5767 };
5768 let settings = all_language_settings(Some(file), cx);
5769 Some(settings.edit_predictions_enabled_for_file(file, cx))
5770 })
5771 .unwrap_or(false)
5772 }
5773
5774 fn cycle_inline_completion(
5775 &mut self,
5776 direction: Direction,
5777 window: &mut Window,
5778 cx: &mut Context<Self>,
5779 ) -> Option<()> {
5780 let provider = self.edit_prediction_provider()?;
5781 let cursor = self.selections.newest_anchor().head();
5782 let (buffer, cursor_buffer_position) =
5783 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5784 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5785 return None;
5786 }
5787
5788 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5789 self.update_visible_inline_completion(window, cx);
5790
5791 Some(())
5792 }
5793
5794 pub fn show_inline_completion(
5795 &mut self,
5796 _: &ShowEditPrediction,
5797 window: &mut Window,
5798 cx: &mut Context<Self>,
5799 ) {
5800 if !self.has_active_inline_completion() {
5801 self.refresh_inline_completion(false, true, window, cx);
5802 return;
5803 }
5804
5805 self.update_visible_inline_completion(window, cx);
5806 }
5807
5808 pub fn display_cursor_names(
5809 &mut self,
5810 _: &DisplayCursorNames,
5811 window: &mut Window,
5812 cx: &mut Context<Self>,
5813 ) {
5814 self.show_cursor_names(window, cx);
5815 }
5816
5817 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5818 self.show_cursor_names = true;
5819 cx.notify();
5820 cx.spawn_in(window, async move |this, cx| {
5821 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5822 this.update(cx, |this, cx| {
5823 this.show_cursor_names = false;
5824 cx.notify()
5825 })
5826 .ok()
5827 })
5828 .detach();
5829 }
5830
5831 pub fn next_edit_prediction(
5832 &mut self,
5833 _: &NextEditPrediction,
5834 window: &mut Window,
5835 cx: &mut Context<Self>,
5836 ) {
5837 if self.has_active_inline_completion() {
5838 self.cycle_inline_completion(Direction::Next, window, cx);
5839 } else {
5840 let is_copilot_disabled = self
5841 .refresh_inline_completion(false, true, window, cx)
5842 .is_none();
5843 if is_copilot_disabled {
5844 cx.propagate();
5845 }
5846 }
5847 }
5848
5849 pub fn previous_edit_prediction(
5850 &mut self,
5851 _: &PreviousEditPrediction,
5852 window: &mut Window,
5853 cx: &mut Context<Self>,
5854 ) {
5855 if self.has_active_inline_completion() {
5856 self.cycle_inline_completion(Direction::Prev, window, cx);
5857 } else {
5858 let is_copilot_disabled = self
5859 .refresh_inline_completion(false, true, window, cx)
5860 .is_none();
5861 if is_copilot_disabled {
5862 cx.propagate();
5863 }
5864 }
5865 }
5866
5867 pub fn accept_edit_prediction(
5868 &mut self,
5869 _: &AcceptEditPrediction,
5870 window: &mut Window,
5871 cx: &mut Context<Self>,
5872 ) {
5873 if self.show_edit_predictions_in_menu() {
5874 self.hide_context_menu(window, cx);
5875 }
5876
5877 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5878 return;
5879 };
5880
5881 self.report_inline_completion_event(
5882 active_inline_completion.completion_id.clone(),
5883 true,
5884 cx,
5885 );
5886
5887 match &active_inline_completion.completion {
5888 InlineCompletion::Move { target, .. } => {
5889 let target = *target;
5890
5891 if let Some(position_map) = &self.last_position_map {
5892 if position_map
5893 .visible_row_range
5894 .contains(&target.to_display_point(&position_map.snapshot).row())
5895 || !self.edit_prediction_requires_modifier()
5896 {
5897 self.unfold_ranges(&[target..target], true, false, cx);
5898 // Note that this is also done in vim's handler of the Tab action.
5899 self.change_selections(
5900 Some(Autoscroll::newest()),
5901 window,
5902 cx,
5903 |selections| {
5904 selections.select_anchor_ranges([target..target]);
5905 },
5906 );
5907 self.clear_row_highlights::<EditPredictionPreview>();
5908
5909 self.edit_prediction_preview
5910 .set_previous_scroll_position(None);
5911 } else {
5912 self.edit_prediction_preview
5913 .set_previous_scroll_position(Some(
5914 position_map.snapshot.scroll_anchor,
5915 ));
5916
5917 self.highlight_rows::<EditPredictionPreview>(
5918 target..target,
5919 cx.theme().colors().editor_highlighted_line_background,
5920 true,
5921 cx,
5922 );
5923 self.request_autoscroll(Autoscroll::fit(), cx);
5924 }
5925 }
5926 }
5927 InlineCompletion::Edit { edits, .. } => {
5928 if let Some(provider) = self.edit_prediction_provider() {
5929 provider.accept(cx);
5930 }
5931
5932 let snapshot = self.buffer.read(cx).snapshot(cx);
5933 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5934
5935 self.buffer.update(cx, |buffer, cx| {
5936 buffer.edit(edits.iter().cloned(), None, cx)
5937 });
5938
5939 self.change_selections(None, window, cx, |s| {
5940 s.select_anchor_ranges([last_edit_end..last_edit_end])
5941 });
5942
5943 self.update_visible_inline_completion(window, cx);
5944 if self.active_inline_completion.is_none() {
5945 self.refresh_inline_completion(true, true, window, cx);
5946 }
5947
5948 cx.notify();
5949 }
5950 }
5951
5952 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5953 }
5954
5955 pub fn accept_partial_inline_completion(
5956 &mut self,
5957 _: &AcceptPartialEditPrediction,
5958 window: &mut Window,
5959 cx: &mut Context<Self>,
5960 ) {
5961 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5962 return;
5963 };
5964 if self.selections.count() != 1 {
5965 return;
5966 }
5967
5968 self.report_inline_completion_event(
5969 active_inline_completion.completion_id.clone(),
5970 true,
5971 cx,
5972 );
5973
5974 match &active_inline_completion.completion {
5975 InlineCompletion::Move { target, .. } => {
5976 let target = *target;
5977 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5978 selections.select_anchor_ranges([target..target]);
5979 });
5980 }
5981 InlineCompletion::Edit { edits, .. } => {
5982 // Find an insertion that starts at the cursor position.
5983 let snapshot = self.buffer.read(cx).snapshot(cx);
5984 let cursor_offset = self.selections.newest::<usize>(cx).head();
5985 let insertion = edits.iter().find_map(|(range, text)| {
5986 let range = range.to_offset(&snapshot);
5987 if range.is_empty() && range.start == cursor_offset {
5988 Some(text)
5989 } else {
5990 None
5991 }
5992 });
5993
5994 if let Some(text) = insertion {
5995 let mut partial_completion = text
5996 .chars()
5997 .by_ref()
5998 .take_while(|c| c.is_alphabetic())
5999 .collect::<String>();
6000 if partial_completion.is_empty() {
6001 partial_completion = text
6002 .chars()
6003 .by_ref()
6004 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6005 .collect::<String>();
6006 }
6007
6008 cx.emit(EditorEvent::InputHandled {
6009 utf16_range_to_replace: None,
6010 text: partial_completion.clone().into(),
6011 });
6012
6013 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6014
6015 self.refresh_inline_completion(true, true, window, cx);
6016 cx.notify();
6017 } else {
6018 self.accept_edit_prediction(&Default::default(), window, cx);
6019 }
6020 }
6021 }
6022 }
6023
6024 fn discard_inline_completion(
6025 &mut self,
6026 should_report_inline_completion_event: bool,
6027 cx: &mut Context<Self>,
6028 ) -> bool {
6029 if should_report_inline_completion_event {
6030 let completion_id = self
6031 .active_inline_completion
6032 .as_ref()
6033 .and_then(|active_completion| active_completion.completion_id.clone());
6034
6035 self.report_inline_completion_event(completion_id, false, cx);
6036 }
6037
6038 if let Some(provider) = self.edit_prediction_provider() {
6039 provider.discard(cx);
6040 }
6041
6042 self.take_active_inline_completion(cx)
6043 }
6044
6045 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6046 let Some(provider) = self.edit_prediction_provider() else {
6047 return;
6048 };
6049
6050 let Some((_, buffer, _)) = self
6051 .buffer
6052 .read(cx)
6053 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6054 else {
6055 return;
6056 };
6057
6058 let extension = buffer
6059 .read(cx)
6060 .file()
6061 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6062
6063 let event_type = match accepted {
6064 true => "Edit Prediction Accepted",
6065 false => "Edit Prediction Discarded",
6066 };
6067 telemetry::event!(
6068 event_type,
6069 provider = provider.name(),
6070 prediction_id = id,
6071 suggestion_accepted = accepted,
6072 file_extension = extension,
6073 );
6074 }
6075
6076 pub fn has_active_inline_completion(&self) -> bool {
6077 self.active_inline_completion.is_some()
6078 }
6079
6080 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6081 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6082 return false;
6083 };
6084
6085 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6086 self.clear_highlights::<InlineCompletionHighlight>(cx);
6087 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6088 true
6089 }
6090
6091 /// Returns true when we're displaying the edit prediction popover below the cursor
6092 /// like we are not previewing and the LSP autocomplete menu is visible
6093 /// or we are in `when_holding_modifier` mode.
6094 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6095 if self.edit_prediction_preview_is_active()
6096 || !self.show_edit_predictions_in_menu()
6097 || !self.edit_predictions_enabled()
6098 {
6099 return false;
6100 }
6101
6102 if self.has_visible_completions_menu() {
6103 return true;
6104 }
6105
6106 has_completion && self.edit_prediction_requires_modifier()
6107 }
6108
6109 fn handle_modifiers_changed(
6110 &mut self,
6111 modifiers: Modifiers,
6112 position_map: &PositionMap,
6113 window: &mut Window,
6114 cx: &mut Context<Self>,
6115 ) {
6116 if self.show_edit_predictions_in_menu() {
6117 self.update_edit_prediction_preview(&modifiers, window, cx);
6118 }
6119
6120 self.update_selection_mode(&modifiers, position_map, window, cx);
6121
6122 let mouse_position = window.mouse_position();
6123 if !position_map.text_hitbox.is_hovered(window) {
6124 return;
6125 }
6126
6127 self.update_hovered_link(
6128 position_map.point_for_position(mouse_position),
6129 &position_map.snapshot,
6130 modifiers,
6131 window,
6132 cx,
6133 )
6134 }
6135
6136 fn update_selection_mode(
6137 &mut self,
6138 modifiers: &Modifiers,
6139 position_map: &PositionMap,
6140 window: &mut Window,
6141 cx: &mut Context<Self>,
6142 ) {
6143 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6144 return;
6145 }
6146
6147 let mouse_position = window.mouse_position();
6148 let point_for_position = position_map.point_for_position(mouse_position);
6149 let position = point_for_position.previous_valid;
6150
6151 self.select(
6152 SelectPhase::BeginColumnar {
6153 position,
6154 reset: false,
6155 goal_column: point_for_position.exact_unclipped.column(),
6156 },
6157 window,
6158 cx,
6159 );
6160 }
6161
6162 fn update_edit_prediction_preview(
6163 &mut self,
6164 modifiers: &Modifiers,
6165 window: &mut Window,
6166 cx: &mut Context<Self>,
6167 ) {
6168 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6169 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6170 return;
6171 };
6172
6173 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6174 if matches!(
6175 self.edit_prediction_preview,
6176 EditPredictionPreview::Inactive { .. }
6177 ) {
6178 self.edit_prediction_preview = EditPredictionPreview::Active {
6179 previous_scroll_position: None,
6180 since: Instant::now(),
6181 };
6182
6183 self.update_visible_inline_completion(window, cx);
6184 cx.notify();
6185 }
6186 } else if let EditPredictionPreview::Active {
6187 previous_scroll_position,
6188 since,
6189 } = self.edit_prediction_preview
6190 {
6191 if let (Some(previous_scroll_position), Some(position_map)) =
6192 (previous_scroll_position, self.last_position_map.as_ref())
6193 {
6194 self.set_scroll_position(
6195 previous_scroll_position
6196 .scroll_position(&position_map.snapshot.display_snapshot),
6197 window,
6198 cx,
6199 );
6200 }
6201
6202 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6203 released_too_fast: since.elapsed() < Duration::from_millis(200),
6204 };
6205 self.clear_row_highlights::<EditPredictionPreview>();
6206 self.update_visible_inline_completion(window, cx);
6207 cx.notify();
6208 }
6209 }
6210
6211 fn update_visible_inline_completion(
6212 &mut self,
6213 _window: &mut Window,
6214 cx: &mut Context<Self>,
6215 ) -> Option<()> {
6216 let selection = self.selections.newest_anchor();
6217 let cursor = selection.head();
6218 let multibuffer = self.buffer.read(cx).snapshot(cx);
6219 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6220 let excerpt_id = cursor.excerpt_id;
6221
6222 let show_in_menu = self.show_edit_predictions_in_menu();
6223 let completions_menu_has_precedence = !show_in_menu
6224 && (self.context_menu.borrow().is_some()
6225 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6226
6227 if completions_menu_has_precedence
6228 || !offset_selection.is_empty()
6229 || self
6230 .active_inline_completion
6231 .as_ref()
6232 .map_or(false, |completion| {
6233 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6234 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6235 !invalidation_range.contains(&offset_selection.head())
6236 })
6237 {
6238 self.discard_inline_completion(false, cx);
6239 return None;
6240 }
6241
6242 self.take_active_inline_completion(cx);
6243 let Some(provider) = self.edit_prediction_provider() else {
6244 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6245 return None;
6246 };
6247
6248 let (buffer, cursor_buffer_position) =
6249 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6250
6251 self.edit_prediction_settings =
6252 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6253
6254 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6255
6256 if self.edit_prediction_indent_conflict {
6257 let cursor_point = cursor.to_point(&multibuffer);
6258
6259 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6260
6261 if let Some((_, indent)) = indents.iter().next() {
6262 if indent.len == cursor_point.column {
6263 self.edit_prediction_indent_conflict = false;
6264 }
6265 }
6266 }
6267
6268 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6269 let edits = inline_completion
6270 .edits
6271 .into_iter()
6272 .flat_map(|(range, new_text)| {
6273 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6274 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6275 Some((start..end, new_text))
6276 })
6277 .collect::<Vec<_>>();
6278 if edits.is_empty() {
6279 return None;
6280 }
6281
6282 let first_edit_start = edits.first().unwrap().0.start;
6283 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6284 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6285
6286 let last_edit_end = edits.last().unwrap().0.end;
6287 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6288 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6289
6290 let cursor_row = cursor.to_point(&multibuffer).row;
6291
6292 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6293
6294 let mut inlay_ids = Vec::new();
6295 let invalidation_row_range;
6296 let move_invalidation_row_range = if cursor_row < edit_start_row {
6297 Some(cursor_row..edit_end_row)
6298 } else if cursor_row > edit_end_row {
6299 Some(edit_start_row..cursor_row)
6300 } else {
6301 None
6302 };
6303 let is_move =
6304 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6305 let completion = if is_move {
6306 invalidation_row_range =
6307 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6308 let target = first_edit_start;
6309 InlineCompletion::Move { target, snapshot }
6310 } else {
6311 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6312 && !self.inline_completions_hidden_for_vim_mode;
6313
6314 if show_completions_in_buffer {
6315 if edits
6316 .iter()
6317 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6318 {
6319 let mut inlays = Vec::new();
6320 for (range, new_text) in &edits {
6321 let inlay = Inlay::inline_completion(
6322 post_inc(&mut self.next_inlay_id),
6323 range.start,
6324 new_text.as_str(),
6325 );
6326 inlay_ids.push(inlay.id);
6327 inlays.push(inlay);
6328 }
6329
6330 self.splice_inlays(&[], inlays, cx);
6331 } else {
6332 let background_color = cx.theme().status().deleted_background;
6333 self.highlight_text::<InlineCompletionHighlight>(
6334 edits.iter().map(|(range, _)| range.clone()).collect(),
6335 HighlightStyle {
6336 background_color: Some(background_color),
6337 ..Default::default()
6338 },
6339 cx,
6340 );
6341 }
6342 }
6343
6344 invalidation_row_range = edit_start_row..edit_end_row;
6345
6346 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6347 if provider.show_tab_accept_marker() {
6348 EditDisplayMode::TabAccept
6349 } else {
6350 EditDisplayMode::Inline
6351 }
6352 } else {
6353 EditDisplayMode::DiffPopover
6354 };
6355
6356 InlineCompletion::Edit {
6357 edits,
6358 edit_preview: inline_completion.edit_preview,
6359 display_mode,
6360 snapshot,
6361 }
6362 };
6363
6364 let invalidation_range = multibuffer
6365 .anchor_before(Point::new(invalidation_row_range.start, 0))
6366 ..multibuffer.anchor_after(Point::new(
6367 invalidation_row_range.end,
6368 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6369 ));
6370
6371 self.stale_inline_completion_in_menu = None;
6372 self.active_inline_completion = Some(InlineCompletionState {
6373 inlay_ids,
6374 completion,
6375 completion_id: inline_completion.id,
6376 invalidation_range,
6377 });
6378
6379 cx.notify();
6380
6381 Some(())
6382 }
6383
6384 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6385 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6386 }
6387
6388 fn render_code_actions_indicator(
6389 &self,
6390 _style: &EditorStyle,
6391 row: DisplayRow,
6392 is_active: bool,
6393 breakpoint: Option<&(Anchor, Breakpoint)>,
6394 cx: &mut Context<Self>,
6395 ) -> Option<IconButton> {
6396 let color = Color::Muted;
6397 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6398 let show_tooltip = !self.context_menu_visible();
6399
6400 if self.available_code_actions.is_some() {
6401 Some(
6402 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6403 .shape(ui::IconButtonShape::Square)
6404 .icon_size(IconSize::XSmall)
6405 .icon_color(color)
6406 .toggle_state(is_active)
6407 .when(show_tooltip, |this| {
6408 this.tooltip({
6409 let focus_handle = self.focus_handle.clone();
6410 move |window, cx| {
6411 Tooltip::for_action_in(
6412 "Toggle Code Actions",
6413 &ToggleCodeActions {
6414 deployed_from_indicator: None,
6415 },
6416 &focus_handle,
6417 window,
6418 cx,
6419 )
6420 }
6421 })
6422 })
6423 .on_click(cx.listener(move |editor, _e, window, cx| {
6424 window.focus(&editor.focus_handle(cx));
6425 editor.toggle_code_actions(
6426 &ToggleCodeActions {
6427 deployed_from_indicator: Some(row),
6428 },
6429 window,
6430 cx,
6431 );
6432 }))
6433 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6434 editor.set_breakpoint_context_menu(
6435 row,
6436 position,
6437 event.down.position,
6438 window,
6439 cx,
6440 );
6441 })),
6442 )
6443 } else {
6444 None
6445 }
6446 }
6447
6448 fn clear_tasks(&mut self) {
6449 self.tasks.clear()
6450 }
6451
6452 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6453 if self.tasks.insert(key, value).is_some() {
6454 // This case should hopefully be rare, but just in case...
6455 log::error!(
6456 "multiple different run targets found on a single line, only the last target will be rendered"
6457 )
6458 }
6459 }
6460
6461 /// Get all display points of breakpoints that will be rendered within editor
6462 ///
6463 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6464 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6465 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6466 fn active_breakpoints(
6467 &self,
6468 range: Range<DisplayRow>,
6469 window: &mut Window,
6470 cx: &mut Context<Self>,
6471 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6472 let mut breakpoint_display_points = HashMap::default();
6473
6474 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6475 return breakpoint_display_points;
6476 };
6477
6478 let snapshot = self.snapshot(window, cx);
6479
6480 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6481 let Some(project) = self.project.as_ref() else {
6482 return breakpoint_display_points;
6483 };
6484
6485 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6486 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6487
6488 for (buffer_snapshot, range, excerpt_id) in
6489 multi_buffer_snapshot.range_to_buffer_ranges(range)
6490 {
6491 let Some(buffer) = project.read_with(cx, |this, cx| {
6492 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6493 }) else {
6494 continue;
6495 };
6496 let breakpoints = breakpoint_store.read(cx).breakpoints(
6497 &buffer,
6498 Some(
6499 buffer_snapshot.anchor_before(range.start)
6500 ..buffer_snapshot.anchor_after(range.end),
6501 ),
6502 buffer_snapshot,
6503 cx,
6504 );
6505 for (anchor, breakpoint) in breakpoints {
6506 let multi_buffer_anchor =
6507 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6508 let position = multi_buffer_anchor
6509 .to_point(&multi_buffer_snapshot)
6510 .to_display_point(&snapshot);
6511
6512 breakpoint_display_points
6513 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6514 }
6515 }
6516
6517 breakpoint_display_points
6518 }
6519
6520 fn breakpoint_context_menu(
6521 &self,
6522 anchor: Anchor,
6523 window: &mut Window,
6524 cx: &mut Context<Self>,
6525 ) -> Entity<ui::ContextMenu> {
6526 let weak_editor = cx.weak_entity();
6527 let focus_handle = self.focus_handle(cx);
6528
6529 let row = self
6530 .buffer
6531 .read(cx)
6532 .snapshot(cx)
6533 .summary_for_anchor::<Point>(&anchor)
6534 .row;
6535
6536 let breakpoint = self
6537 .breakpoint_at_row(row, window, cx)
6538 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6539
6540 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6541 "Edit Log Breakpoint"
6542 } else {
6543 "Set Log Breakpoint"
6544 };
6545
6546 let condition_breakpoint_msg = if breakpoint
6547 .as_ref()
6548 .is_some_and(|bp| bp.1.condition.is_some())
6549 {
6550 "Edit Condition Breakpoint"
6551 } else {
6552 "Set Condition Breakpoint"
6553 };
6554
6555 let hit_condition_breakpoint_msg = if breakpoint
6556 .as_ref()
6557 .is_some_and(|bp| bp.1.hit_condition.is_some())
6558 {
6559 "Edit Hit Condition Breakpoint"
6560 } else {
6561 "Set Hit Condition Breakpoint"
6562 };
6563
6564 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6565 "Unset Breakpoint"
6566 } else {
6567 "Set Breakpoint"
6568 };
6569
6570 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6571 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6572
6573 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6574 BreakpointState::Enabled => Some("Disable"),
6575 BreakpointState::Disabled => Some("Enable"),
6576 });
6577
6578 let (anchor, breakpoint) =
6579 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6580
6581 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6582 menu.on_blur_subscription(Subscription::new(|| {}))
6583 .context(focus_handle)
6584 .when(run_to_cursor, |this| {
6585 let weak_editor = weak_editor.clone();
6586 this.entry("Run to cursor", None, move |window, cx| {
6587 weak_editor
6588 .update(cx, |editor, cx| {
6589 editor.change_selections(None, window, cx, |s| {
6590 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6591 });
6592 })
6593 .ok();
6594
6595 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6596 })
6597 .separator()
6598 })
6599 .when_some(toggle_state_msg, |this, msg| {
6600 this.entry(msg, None, {
6601 let weak_editor = weak_editor.clone();
6602 let breakpoint = breakpoint.clone();
6603 move |_window, cx| {
6604 weak_editor
6605 .update(cx, |this, cx| {
6606 this.edit_breakpoint_at_anchor(
6607 anchor,
6608 breakpoint.as_ref().clone(),
6609 BreakpointEditAction::InvertState,
6610 cx,
6611 );
6612 })
6613 .log_err();
6614 }
6615 })
6616 })
6617 .entry(set_breakpoint_msg, None, {
6618 let weak_editor = weak_editor.clone();
6619 let breakpoint = breakpoint.clone();
6620 move |_window, cx| {
6621 weak_editor
6622 .update(cx, |this, cx| {
6623 this.edit_breakpoint_at_anchor(
6624 anchor,
6625 breakpoint.as_ref().clone(),
6626 BreakpointEditAction::Toggle,
6627 cx,
6628 );
6629 })
6630 .log_err();
6631 }
6632 })
6633 .entry(log_breakpoint_msg, None, {
6634 let breakpoint = breakpoint.clone();
6635 let weak_editor = weak_editor.clone();
6636 move |window, cx| {
6637 weak_editor
6638 .update(cx, |this, cx| {
6639 this.add_edit_breakpoint_block(
6640 anchor,
6641 breakpoint.as_ref(),
6642 BreakpointPromptEditAction::Log,
6643 window,
6644 cx,
6645 );
6646 })
6647 .log_err();
6648 }
6649 })
6650 .entry(condition_breakpoint_msg, None, {
6651 let breakpoint = breakpoint.clone();
6652 let weak_editor = weak_editor.clone();
6653 move |window, cx| {
6654 weak_editor
6655 .update(cx, |this, cx| {
6656 this.add_edit_breakpoint_block(
6657 anchor,
6658 breakpoint.as_ref(),
6659 BreakpointPromptEditAction::Condition,
6660 window,
6661 cx,
6662 );
6663 })
6664 .log_err();
6665 }
6666 })
6667 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6668 weak_editor
6669 .update(cx, |this, cx| {
6670 this.add_edit_breakpoint_block(
6671 anchor,
6672 breakpoint.as_ref(),
6673 BreakpointPromptEditAction::HitCondition,
6674 window,
6675 cx,
6676 );
6677 })
6678 .log_err();
6679 })
6680 })
6681 }
6682
6683 fn render_breakpoint(
6684 &self,
6685 position: Anchor,
6686 row: DisplayRow,
6687 breakpoint: &Breakpoint,
6688 cx: &mut Context<Self>,
6689 ) -> IconButton {
6690 let (color, icon) = {
6691 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6692 (false, false) => ui::IconName::DebugBreakpoint,
6693 (true, false) => ui::IconName::DebugLogBreakpoint,
6694 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6695 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6696 };
6697
6698 let color = if self
6699 .gutter_breakpoint_indicator
6700 .0
6701 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6702 {
6703 Color::Hint
6704 } else {
6705 Color::Debugger
6706 };
6707
6708 (color, icon)
6709 };
6710
6711 let breakpoint = Arc::from(breakpoint.clone());
6712
6713 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6714 .icon_size(IconSize::XSmall)
6715 .size(ui::ButtonSize::None)
6716 .icon_color(color)
6717 .style(ButtonStyle::Transparent)
6718 .on_click(cx.listener({
6719 let breakpoint = breakpoint.clone();
6720
6721 move |editor, event: &ClickEvent, window, cx| {
6722 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6723 BreakpointEditAction::InvertState
6724 } else {
6725 BreakpointEditAction::Toggle
6726 };
6727
6728 window.focus(&editor.focus_handle(cx));
6729 editor.edit_breakpoint_at_anchor(
6730 position,
6731 breakpoint.as_ref().clone(),
6732 edit_action,
6733 cx,
6734 );
6735 }
6736 }))
6737 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6738 editor.set_breakpoint_context_menu(
6739 row,
6740 Some(position),
6741 event.down.position,
6742 window,
6743 cx,
6744 );
6745 }))
6746 }
6747
6748 fn build_tasks_context(
6749 project: &Entity<Project>,
6750 buffer: &Entity<Buffer>,
6751 buffer_row: u32,
6752 tasks: &Arc<RunnableTasks>,
6753 cx: &mut Context<Self>,
6754 ) -> Task<Option<task::TaskContext>> {
6755 let position = Point::new(buffer_row, tasks.column);
6756 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6757 let location = Location {
6758 buffer: buffer.clone(),
6759 range: range_start..range_start,
6760 };
6761 // Fill in the environmental variables from the tree-sitter captures
6762 let mut captured_task_variables = TaskVariables::default();
6763 for (capture_name, value) in tasks.extra_variables.clone() {
6764 captured_task_variables.insert(
6765 task::VariableName::Custom(capture_name.into()),
6766 value.clone(),
6767 );
6768 }
6769 project.update(cx, |project, cx| {
6770 project.task_store().update(cx, |task_store, cx| {
6771 task_store.task_context_for_location(captured_task_variables, location, cx)
6772 })
6773 })
6774 }
6775
6776 pub fn spawn_nearest_task(
6777 &mut self,
6778 action: &SpawnNearestTask,
6779 window: &mut Window,
6780 cx: &mut Context<Self>,
6781 ) {
6782 let Some((workspace, _)) = self.workspace.clone() else {
6783 return;
6784 };
6785 let Some(project) = self.project.clone() else {
6786 return;
6787 };
6788
6789 // Try to find a closest, enclosing node using tree-sitter that has a
6790 // task
6791 let Some((buffer, buffer_row, tasks)) = self
6792 .find_enclosing_node_task(cx)
6793 // Or find the task that's closest in row-distance.
6794 .or_else(|| self.find_closest_task(cx))
6795 else {
6796 return;
6797 };
6798
6799 let reveal_strategy = action.reveal;
6800 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6801 cx.spawn_in(window, async move |_, cx| {
6802 let context = task_context.await?;
6803 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6804
6805 let resolved = resolved_task.resolved.as_mut()?;
6806 resolved.reveal = reveal_strategy;
6807
6808 workspace
6809 .update(cx, |workspace, cx| {
6810 workspace::tasks::schedule_resolved_task(
6811 workspace,
6812 task_source_kind,
6813 resolved_task,
6814 false,
6815 cx,
6816 );
6817 })
6818 .ok()
6819 })
6820 .detach();
6821 }
6822
6823 fn find_closest_task(
6824 &mut self,
6825 cx: &mut Context<Self>,
6826 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6827 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6828
6829 let ((buffer_id, row), tasks) = self
6830 .tasks
6831 .iter()
6832 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6833
6834 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6835 let tasks = Arc::new(tasks.to_owned());
6836 Some((buffer, *row, tasks))
6837 }
6838
6839 fn find_enclosing_node_task(
6840 &mut self,
6841 cx: &mut Context<Self>,
6842 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6843 let snapshot = self.buffer.read(cx).snapshot(cx);
6844 let offset = self.selections.newest::<usize>(cx).head();
6845 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6846 let buffer_id = excerpt.buffer().remote_id();
6847
6848 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6849 let mut cursor = layer.node().walk();
6850
6851 while cursor.goto_first_child_for_byte(offset).is_some() {
6852 if cursor.node().end_byte() == offset {
6853 cursor.goto_next_sibling();
6854 }
6855 }
6856
6857 // Ascend to the smallest ancestor that contains the range and has a task.
6858 loop {
6859 let node = cursor.node();
6860 let node_range = node.byte_range();
6861 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6862
6863 // Check if this node contains our offset
6864 if node_range.start <= offset && node_range.end >= offset {
6865 // If it contains offset, check for task
6866 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6867 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6868 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6869 }
6870 }
6871
6872 if !cursor.goto_parent() {
6873 break;
6874 }
6875 }
6876 None
6877 }
6878
6879 fn render_run_indicator(
6880 &self,
6881 _style: &EditorStyle,
6882 is_active: bool,
6883 row: DisplayRow,
6884 breakpoint: Option<(Anchor, Breakpoint)>,
6885 cx: &mut Context<Self>,
6886 ) -> IconButton {
6887 let color = Color::Muted;
6888 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6889
6890 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6891 .shape(ui::IconButtonShape::Square)
6892 .icon_size(IconSize::XSmall)
6893 .icon_color(color)
6894 .toggle_state(is_active)
6895 .on_click(cx.listener(move |editor, _e, window, cx| {
6896 window.focus(&editor.focus_handle(cx));
6897 editor.toggle_code_actions(
6898 &ToggleCodeActions {
6899 deployed_from_indicator: Some(row),
6900 },
6901 window,
6902 cx,
6903 );
6904 }))
6905 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6906 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6907 }))
6908 }
6909
6910 pub fn context_menu_visible(&self) -> bool {
6911 !self.edit_prediction_preview_is_active()
6912 && self
6913 .context_menu
6914 .borrow()
6915 .as_ref()
6916 .map_or(false, |menu| menu.visible())
6917 }
6918
6919 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6920 self.context_menu
6921 .borrow()
6922 .as_ref()
6923 .map(|menu| menu.origin())
6924 }
6925
6926 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6927 self.context_menu_options = Some(options);
6928 }
6929
6930 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6931 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6932
6933 fn render_edit_prediction_popover(
6934 &mut self,
6935 text_bounds: &Bounds<Pixels>,
6936 content_origin: gpui::Point<Pixels>,
6937 editor_snapshot: &EditorSnapshot,
6938 visible_row_range: Range<DisplayRow>,
6939 scroll_top: f32,
6940 scroll_bottom: f32,
6941 line_layouts: &[LineWithInvisibles],
6942 line_height: Pixels,
6943 scroll_pixel_position: gpui::Point<Pixels>,
6944 newest_selection_head: Option<DisplayPoint>,
6945 editor_width: Pixels,
6946 style: &EditorStyle,
6947 window: &mut Window,
6948 cx: &mut App,
6949 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6950 let active_inline_completion = self.active_inline_completion.as_ref()?;
6951
6952 if self.edit_prediction_visible_in_cursor_popover(true) {
6953 return None;
6954 }
6955
6956 match &active_inline_completion.completion {
6957 InlineCompletion::Move { target, .. } => {
6958 let target_display_point = target.to_display_point(editor_snapshot);
6959
6960 if self.edit_prediction_requires_modifier() {
6961 if !self.edit_prediction_preview_is_active() {
6962 return None;
6963 }
6964
6965 self.render_edit_prediction_modifier_jump_popover(
6966 text_bounds,
6967 content_origin,
6968 visible_row_range,
6969 line_layouts,
6970 line_height,
6971 scroll_pixel_position,
6972 newest_selection_head,
6973 target_display_point,
6974 window,
6975 cx,
6976 )
6977 } else {
6978 self.render_edit_prediction_eager_jump_popover(
6979 text_bounds,
6980 content_origin,
6981 editor_snapshot,
6982 visible_row_range,
6983 scroll_top,
6984 scroll_bottom,
6985 line_height,
6986 scroll_pixel_position,
6987 target_display_point,
6988 editor_width,
6989 window,
6990 cx,
6991 )
6992 }
6993 }
6994 InlineCompletion::Edit {
6995 display_mode: EditDisplayMode::Inline,
6996 ..
6997 } => None,
6998 InlineCompletion::Edit {
6999 display_mode: EditDisplayMode::TabAccept,
7000 edits,
7001 ..
7002 } => {
7003 let range = &edits.first()?.0;
7004 let target_display_point = range.end.to_display_point(editor_snapshot);
7005
7006 self.render_edit_prediction_end_of_line_popover(
7007 "Accept",
7008 editor_snapshot,
7009 visible_row_range,
7010 target_display_point,
7011 line_height,
7012 scroll_pixel_position,
7013 content_origin,
7014 editor_width,
7015 window,
7016 cx,
7017 )
7018 }
7019 InlineCompletion::Edit {
7020 edits,
7021 edit_preview,
7022 display_mode: EditDisplayMode::DiffPopover,
7023 snapshot,
7024 } => self.render_edit_prediction_diff_popover(
7025 text_bounds,
7026 content_origin,
7027 editor_snapshot,
7028 visible_row_range,
7029 line_layouts,
7030 line_height,
7031 scroll_pixel_position,
7032 newest_selection_head,
7033 editor_width,
7034 style,
7035 edits,
7036 edit_preview,
7037 snapshot,
7038 window,
7039 cx,
7040 ),
7041 }
7042 }
7043
7044 fn render_edit_prediction_modifier_jump_popover(
7045 &mut self,
7046 text_bounds: &Bounds<Pixels>,
7047 content_origin: gpui::Point<Pixels>,
7048 visible_row_range: Range<DisplayRow>,
7049 line_layouts: &[LineWithInvisibles],
7050 line_height: Pixels,
7051 scroll_pixel_position: gpui::Point<Pixels>,
7052 newest_selection_head: Option<DisplayPoint>,
7053 target_display_point: DisplayPoint,
7054 window: &mut Window,
7055 cx: &mut App,
7056 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7057 let scrolled_content_origin =
7058 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7059
7060 const SCROLL_PADDING_Y: Pixels = px(12.);
7061
7062 if target_display_point.row() < visible_row_range.start {
7063 return self.render_edit_prediction_scroll_popover(
7064 |_| SCROLL_PADDING_Y,
7065 IconName::ArrowUp,
7066 visible_row_range,
7067 line_layouts,
7068 newest_selection_head,
7069 scrolled_content_origin,
7070 window,
7071 cx,
7072 );
7073 } else if target_display_point.row() >= visible_row_range.end {
7074 return self.render_edit_prediction_scroll_popover(
7075 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7076 IconName::ArrowDown,
7077 visible_row_range,
7078 line_layouts,
7079 newest_selection_head,
7080 scrolled_content_origin,
7081 window,
7082 cx,
7083 );
7084 }
7085
7086 const POLE_WIDTH: Pixels = px(2.);
7087
7088 let line_layout =
7089 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7090 let target_column = target_display_point.column() as usize;
7091
7092 let target_x = line_layout.x_for_index(target_column);
7093 let target_y =
7094 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7095
7096 let flag_on_right = target_x < text_bounds.size.width / 2.;
7097
7098 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7099 border_color.l += 0.001;
7100
7101 let mut element = v_flex()
7102 .items_end()
7103 .when(flag_on_right, |el| el.items_start())
7104 .child(if flag_on_right {
7105 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7106 .rounded_bl(px(0.))
7107 .rounded_tl(px(0.))
7108 .border_l_2()
7109 .border_color(border_color)
7110 } else {
7111 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7112 .rounded_br(px(0.))
7113 .rounded_tr(px(0.))
7114 .border_r_2()
7115 .border_color(border_color)
7116 })
7117 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7118 .into_any();
7119
7120 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7121
7122 let mut origin = scrolled_content_origin + point(target_x, target_y)
7123 - point(
7124 if flag_on_right {
7125 POLE_WIDTH
7126 } else {
7127 size.width - POLE_WIDTH
7128 },
7129 size.height - line_height,
7130 );
7131
7132 origin.x = origin.x.max(content_origin.x);
7133
7134 element.prepaint_at(origin, window, cx);
7135
7136 Some((element, origin))
7137 }
7138
7139 fn render_edit_prediction_scroll_popover(
7140 &mut self,
7141 to_y: impl Fn(Size<Pixels>) -> Pixels,
7142 scroll_icon: IconName,
7143 visible_row_range: Range<DisplayRow>,
7144 line_layouts: &[LineWithInvisibles],
7145 newest_selection_head: Option<DisplayPoint>,
7146 scrolled_content_origin: gpui::Point<Pixels>,
7147 window: &mut Window,
7148 cx: &mut App,
7149 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7150 let mut element = self
7151 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7152 .into_any();
7153
7154 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7155
7156 let cursor = newest_selection_head?;
7157 let cursor_row_layout =
7158 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7159 let cursor_column = cursor.column() as usize;
7160
7161 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7162
7163 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7164
7165 element.prepaint_at(origin, window, cx);
7166 Some((element, origin))
7167 }
7168
7169 fn render_edit_prediction_eager_jump_popover(
7170 &mut self,
7171 text_bounds: &Bounds<Pixels>,
7172 content_origin: gpui::Point<Pixels>,
7173 editor_snapshot: &EditorSnapshot,
7174 visible_row_range: Range<DisplayRow>,
7175 scroll_top: f32,
7176 scroll_bottom: f32,
7177 line_height: Pixels,
7178 scroll_pixel_position: gpui::Point<Pixels>,
7179 target_display_point: DisplayPoint,
7180 editor_width: Pixels,
7181 window: &mut Window,
7182 cx: &mut App,
7183 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7184 if target_display_point.row().as_f32() < scroll_top {
7185 let mut element = self
7186 .render_edit_prediction_line_popover(
7187 "Jump to Edit",
7188 Some(IconName::ArrowUp),
7189 window,
7190 cx,
7191 )?
7192 .into_any();
7193
7194 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7195 let offset = point(
7196 (text_bounds.size.width - size.width) / 2.,
7197 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7198 );
7199
7200 let origin = text_bounds.origin + offset;
7201 element.prepaint_at(origin, window, cx);
7202 Some((element, origin))
7203 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7204 let mut element = self
7205 .render_edit_prediction_line_popover(
7206 "Jump to Edit",
7207 Some(IconName::ArrowDown),
7208 window,
7209 cx,
7210 )?
7211 .into_any();
7212
7213 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7214 let offset = point(
7215 (text_bounds.size.width - size.width) / 2.,
7216 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7217 );
7218
7219 let origin = text_bounds.origin + offset;
7220 element.prepaint_at(origin, window, cx);
7221 Some((element, origin))
7222 } else {
7223 self.render_edit_prediction_end_of_line_popover(
7224 "Jump to Edit",
7225 editor_snapshot,
7226 visible_row_range,
7227 target_display_point,
7228 line_height,
7229 scroll_pixel_position,
7230 content_origin,
7231 editor_width,
7232 window,
7233 cx,
7234 )
7235 }
7236 }
7237
7238 fn render_edit_prediction_end_of_line_popover(
7239 self: &mut Editor,
7240 label: &'static str,
7241 editor_snapshot: &EditorSnapshot,
7242 visible_row_range: Range<DisplayRow>,
7243 target_display_point: DisplayPoint,
7244 line_height: Pixels,
7245 scroll_pixel_position: gpui::Point<Pixels>,
7246 content_origin: gpui::Point<Pixels>,
7247 editor_width: Pixels,
7248 window: &mut Window,
7249 cx: &mut App,
7250 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7251 let target_line_end = DisplayPoint::new(
7252 target_display_point.row(),
7253 editor_snapshot.line_len(target_display_point.row()),
7254 );
7255
7256 let mut element = self
7257 .render_edit_prediction_line_popover(label, None, window, cx)?
7258 .into_any();
7259
7260 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7261
7262 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7263
7264 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7265 let mut origin = start_point
7266 + line_origin
7267 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7268 origin.x = origin.x.max(content_origin.x);
7269
7270 let max_x = content_origin.x + editor_width - size.width;
7271
7272 if origin.x > max_x {
7273 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7274
7275 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7276 origin.y += offset;
7277 IconName::ArrowUp
7278 } else {
7279 origin.y -= offset;
7280 IconName::ArrowDown
7281 };
7282
7283 element = self
7284 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7285 .into_any();
7286
7287 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7288
7289 origin.x = content_origin.x + editor_width - size.width - px(2.);
7290 }
7291
7292 element.prepaint_at(origin, window, cx);
7293 Some((element, origin))
7294 }
7295
7296 fn render_edit_prediction_diff_popover(
7297 self: &Editor,
7298 text_bounds: &Bounds<Pixels>,
7299 content_origin: gpui::Point<Pixels>,
7300 editor_snapshot: &EditorSnapshot,
7301 visible_row_range: Range<DisplayRow>,
7302 line_layouts: &[LineWithInvisibles],
7303 line_height: Pixels,
7304 scroll_pixel_position: gpui::Point<Pixels>,
7305 newest_selection_head: Option<DisplayPoint>,
7306 editor_width: Pixels,
7307 style: &EditorStyle,
7308 edits: &Vec<(Range<Anchor>, String)>,
7309 edit_preview: &Option<language::EditPreview>,
7310 snapshot: &language::BufferSnapshot,
7311 window: &mut Window,
7312 cx: &mut App,
7313 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7314 let edit_start = edits
7315 .first()
7316 .unwrap()
7317 .0
7318 .start
7319 .to_display_point(editor_snapshot);
7320 let edit_end = edits
7321 .last()
7322 .unwrap()
7323 .0
7324 .end
7325 .to_display_point(editor_snapshot);
7326
7327 let is_visible = visible_row_range.contains(&edit_start.row())
7328 || visible_row_range.contains(&edit_end.row());
7329 if !is_visible {
7330 return None;
7331 }
7332
7333 let highlighted_edits =
7334 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7335
7336 let styled_text = highlighted_edits.to_styled_text(&style.text);
7337 let line_count = highlighted_edits.text.lines().count();
7338
7339 const BORDER_WIDTH: Pixels = px(1.);
7340
7341 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7342 let has_keybind = keybind.is_some();
7343
7344 let mut element = h_flex()
7345 .items_start()
7346 .child(
7347 h_flex()
7348 .bg(cx.theme().colors().editor_background)
7349 .border(BORDER_WIDTH)
7350 .shadow_sm()
7351 .border_color(cx.theme().colors().border)
7352 .rounded_l_lg()
7353 .when(line_count > 1, |el| el.rounded_br_lg())
7354 .pr_1()
7355 .child(styled_text),
7356 )
7357 .child(
7358 h_flex()
7359 .h(line_height + BORDER_WIDTH * 2.)
7360 .px_1p5()
7361 .gap_1()
7362 // Workaround: For some reason, there's a gap if we don't do this
7363 .ml(-BORDER_WIDTH)
7364 .shadow(smallvec![gpui::BoxShadow {
7365 color: gpui::black().opacity(0.05),
7366 offset: point(px(1.), px(1.)),
7367 blur_radius: px(2.),
7368 spread_radius: px(0.),
7369 }])
7370 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7371 .border(BORDER_WIDTH)
7372 .border_color(cx.theme().colors().border)
7373 .rounded_r_lg()
7374 .id("edit_prediction_diff_popover_keybind")
7375 .when(!has_keybind, |el| {
7376 let status_colors = cx.theme().status();
7377
7378 el.bg(status_colors.error_background)
7379 .border_color(status_colors.error.opacity(0.6))
7380 .child(Icon::new(IconName::Info).color(Color::Error))
7381 .cursor_default()
7382 .hoverable_tooltip(move |_window, cx| {
7383 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7384 })
7385 })
7386 .children(keybind),
7387 )
7388 .into_any();
7389
7390 let longest_row =
7391 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7392 let longest_line_width = if visible_row_range.contains(&longest_row) {
7393 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7394 } else {
7395 layout_line(
7396 longest_row,
7397 editor_snapshot,
7398 style,
7399 editor_width,
7400 |_| false,
7401 window,
7402 cx,
7403 )
7404 .width
7405 };
7406
7407 let viewport_bounds =
7408 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7409 right: -EditorElement::SCROLLBAR_WIDTH,
7410 ..Default::default()
7411 });
7412
7413 let x_after_longest =
7414 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7415 - scroll_pixel_position.x;
7416
7417 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7418
7419 // Fully visible if it can be displayed within the window (allow overlapping other
7420 // panes). However, this is only allowed if the popover starts within text_bounds.
7421 let can_position_to_the_right = x_after_longest < text_bounds.right()
7422 && x_after_longest + element_bounds.width < viewport_bounds.right();
7423
7424 let mut origin = if can_position_to_the_right {
7425 point(
7426 x_after_longest,
7427 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7428 - scroll_pixel_position.y,
7429 )
7430 } else {
7431 let cursor_row = newest_selection_head.map(|head| head.row());
7432 let above_edit = edit_start
7433 .row()
7434 .0
7435 .checked_sub(line_count as u32)
7436 .map(DisplayRow);
7437 let below_edit = Some(edit_end.row() + 1);
7438 let above_cursor =
7439 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7440 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7441
7442 // Place the edit popover adjacent to the edit if there is a location
7443 // available that is onscreen and does not obscure the cursor. Otherwise,
7444 // place it adjacent to the cursor.
7445 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7446 .into_iter()
7447 .flatten()
7448 .find(|&start_row| {
7449 let end_row = start_row + line_count as u32;
7450 visible_row_range.contains(&start_row)
7451 && visible_row_range.contains(&end_row)
7452 && cursor_row.map_or(true, |cursor_row| {
7453 !((start_row..end_row).contains(&cursor_row))
7454 })
7455 })?;
7456
7457 content_origin
7458 + point(
7459 -scroll_pixel_position.x,
7460 row_target.as_f32() * line_height - scroll_pixel_position.y,
7461 )
7462 };
7463
7464 origin.x -= BORDER_WIDTH;
7465
7466 window.defer_draw(element, origin, 1);
7467
7468 // Do not return an element, since it will already be drawn due to defer_draw.
7469 None
7470 }
7471
7472 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7473 px(30.)
7474 }
7475
7476 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7477 if self.read_only(cx) {
7478 cx.theme().players().read_only()
7479 } else {
7480 self.style.as_ref().unwrap().local_player
7481 }
7482 }
7483
7484 fn render_edit_prediction_accept_keybind(
7485 &self,
7486 window: &mut Window,
7487 cx: &App,
7488 ) -> Option<AnyElement> {
7489 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7490 let accept_keystroke = accept_binding.keystroke()?;
7491
7492 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7493
7494 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7495 Color::Accent
7496 } else {
7497 Color::Muted
7498 };
7499
7500 h_flex()
7501 .px_0p5()
7502 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7503 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7504 .text_size(TextSize::XSmall.rems(cx))
7505 .child(h_flex().children(ui::render_modifiers(
7506 &accept_keystroke.modifiers,
7507 PlatformStyle::platform(),
7508 Some(modifiers_color),
7509 Some(IconSize::XSmall.rems().into()),
7510 true,
7511 )))
7512 .when(is_platform_style_mac, |parent| {
7513 parent.child(accept_keystroke.key.clone())
7514 })
7515 .when(!is_platform_style_mac, |parent| {
7516 parent.child(
7517 Key::new(
7518 util::capitalize(&accept_keystroke.key),
7519 Some(Color::Default),
7520 )
7521 .size(Some(IconSize::XSmall.rems().into())),
7522 )
7523 })
7524 .into_any()
7525 .into()
7526 }
7527
7528 fn render_edit_prediction_line_popover(
7529 &self,
7530 label: impl Into<SharedString>,
7531 icon: Option<IconName>,
7532 window: &mut Window,
7533 cx: &App,
7534 ) -> Option<Stateful<Div>> {
7535 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7536
7537 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7538 let has_keybind = keybind.is_some();
7539
7540 let result = h_flex()
7541 .id("ep-line-popover")
7542 .py_0p5()
7543 .pl_1()
7544 .pr(padding_right)
7545 .gap_1()
7546 .rounded_md()
7547 .border_1()
7548 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7549 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7550 .shadow_sm()
7551 .when(!has_keybind, |el| {
7552 let status_colors = cx.theme().status();
7553
7554 el.bg(status_colors.error_background)
7555 .border_color(status_colors.error.opacity(0.6))
7556 .pl_2()
7557 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7558 .cursor_default()
7559 .hoverable_tooltip(move |_window, cx| {
7560 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7561 })
7562 })
7563 .children(keybind)
7564 .child(
7565 Label::new(label)
7566 .size(LabelSize::Small)
7567 .when(!has_keybind, |el| {
7568 el.color(cx.theme().status().error.into()).strikethrough()
7569 }),
7570 )
7571 .when(!has_keybind, |el| {
7572 el.child(
7573 h_flex().ml_1().child(
7574 Icon::new(IconName::Info)
7575 .size(IconSize::Small)
7576 .color(cx.theme().status().error.into()),
7577 ),
7578 )
7579 })
7580 .when_some(icon, |element, icon| {
7581 element.child(
7582 div()
7583 .mt(px(1.5))
7584 .child(Icon::new(icon).size(IconSize::Small)),
7585 )
7586 });
7587
7588 Some(result)
7589 }
7590
7591 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7592 let accent_color = cx.theme().colors().text_accent;
7593 let editor_bg_color = cx.theme().colors().editor_background;
7594 editor_bg_color.blend(accent_color.opacity(0.1))
7595 }
7596
7597 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7598 let accent_color = cx.theme().colors().text_accent;
7599 let editor_bg_color = cx.theme().colors().editor_background;
7600 editor_bg_color.blend(accent_color.opacity(0.6))
7601 }
7602
7603 fn render_edit_prediction_cursor_popover(
7604 &self,
7605 min_width: Pixels,
7606 max_width: Pixels,
7607 cursor_point: Point,
7608 style: &EditorStyle,
7609 accept_keystroke: Option<&gpui::Keystroke>,
7610 _window: &Window,
7611 cx: &mut Context<Editor>,
7612 ) -> Option<AnyElement> {
7613 let provider = self.edit_prediction_provider.as_ref()?;
7614
7615 if provider.provider.needs_terms_acceptance(cx) {
7616 return Some(
7617 h_flex()
7618 .min_w(min_width)
7619 .flex_1()
7620 .px_2()
7621 .py_1()
7622 .gap_3()
7623 .elevation_2(cx)
7624 .hover(|style| style.bg(cx.theme().colors().element_hover))
7625 .id("accept-terms")
7626 .cursor_pointer()
7627 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7628 .on_click(cx.listener(|this, _event, window, cx| {
7629 cx.stop_propagation();
7630 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7631 window.dispatch_action(
7632 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7633 cx,
7634 );
7635 }))
7636 .child(
7637 h_flex()
7638 .flex_1()
7639 .gap_2()
7640 .child(Icon::new(IconName::ZedPredict))
7641 .child(Label::new("Accept Terms of Service"))
7642 .child(div().w_full())
7643 .child(
7644 Icon::new(IconName::ArrowUpRight)
7645 .color(Color::Muted)
7646 .size(IconSize::Small),
7647 )
7648 .into_any_element(),
7649 )
7650 .into_any(),
7651 );
7652 }
7653
7654 let is_refreshing = provider.provider.is_refreshing(cx);
7655
7656 fn pending_completion_container() -> Div {
7657 h_flex()
7658 .h_full()
7659 .flex_1()
7660 .gap_2()
7661 .child(Icon::new(IconName::ZedPredict))
7662 }
7663
7664 let completion = match &self.active_inline_completion {
7665 Some(prediction) => {
7666 if !self.has_visible_completions_menu() {
7667 const RADIUS: Pixels = px(6.);
7668 const BORDER_WIDTH: Pixels = px(1.);
7669
7670 return Some(
7671 h_flex()
7672 .elevation_2(cx)
7673 .border(BORDER_WIDTH)
7674 .border_color(cx.theme().colors().border)
7675 .when(accept_keystroke.is_none(), |el| {
7676 el.border_color(cx.theme().status().error)
7677 })
7678 .rounded(RADIUS)
7679 .rounded_tl(px(0.))
7680 .overflow_hidden()
7681 .child(div().px_1p5().child(match &prediction.completion {
7682 InlineCompletion::Move { target, snapshot } => {
7683 use text::ToPoint as _;
7684 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7685 {
7686 Icon::new(IconName::ZedPredictDown)
7687 } else {
7688 Icon::new(IconName::ZedPredictUp)
7689 }
7690 }
7691 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7692 }))
7693 .child(
7694 h_flex()
7695 .gap_1()
7696 .py_1()
7697 .px_2()
7698 .rounded_r(RADIUS - BORDER_WIDTH)
7699 .border_l_1()
7700 .border_color(cx.theme().colors().border)
7701 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7702 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7703 el.child(
7704 Label::new("Hold")
7705 .size(LabelSize::Small)
7706 .when(accept_keystroke.is_none(), |el| {
7707 el.strikethrough()
7708 })
7709 .line_height_style(LineHeightStyle::UiLabel),
7710 )
7711 })
7712 .id("edit_prediction_cursor_popover_keybind")
7713 .when(accept_keystroke.is_none(), |el| {
7714 let status_colors = cx.theme().status();
7715
7716 el.bg(status_colors.error_background)
7717 .border_color(status_colors.error.opacity(0.6))
7718 .child(Icon::new(IconName::Info).color(Color::Error))
7719 .cursor_default()
7720 .hoverable_tooltip(move |_window, cx| {
7721 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7722 .into()
7723 })
7724 })
7725 .when_some(
7726 accept_keystroke.as_ref(),
7727 |el, accept_keystroke| {
7728 el.child(h_flex().children(ui::render_modifiers(
7729 &accept_keystroke.modifiers,
7730 PlatformStyle::platform(),
7731 Some(Color::Default),
7732 Some(IconSize::XSmall.rems().into()),
7733 false,
7734 )))
7735 },
7736 ),
7737 )
7738 .into_any(),
7739 );
7740 }
7741
7742 self.render_edit_prediction_cursor_popover_preview(
7743 prediction,
7744 cursor_point,
7745 style,
7746 cx,
7747 )?
7748 }
7749
7750 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7751 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7752 stale_completion,
7753 cursor_point,
7754 style,
7755 cx,
7756 )?,
7757
7758 None => {
7759 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7760 }
7761 },
7762
7763 None => pending_completion_container().child(Label::new("No Prediction")),
7764 };
7765
7766 let completion = if is_refreshing {
7767 completion
7768 .with_animation(
7769 "loading-completion",
7770 Animation::new(Duration::from_secs(2))
7771 .repeat()
7772 .with_easing(pulsating_between(0.4, 0.8)),
7773 |label, delta| label.opacity(delta),
7774 )
7775 .into_any_element()
7776 } else {
7777 completion.into_any_element()
7778 };
7779
7780 let has_completion = self.active_inline_completion.is_some();
7781
7782 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7783 Some(
7784 h_flex()
7785 .min_w(min_width)
7786 .max_w(max_width)
7787 .flex_1()
7788 .elevation_2(cx)
7789 .border_color(cx.theme().colors().border)
7790 .child(
7791 div()
7792 .flex_1()
7793 .py_1()
7794 .px_2()
7795 .overflow_hidden()
7796 .child(completion),
7797 )
7798 .when_some(accept_keystroke, |el, accept_keystroke| {
7799 if !accept_keystroke.modifiers.modified() {
7800 return el;
7801 }
7802
7803 el.child(
7804 h_flex()
7805 .h_full()
7806 .border_l_1()
7807 .rounded_r_lg()
7808 .border_color(cx.theme().colors().border)
7809 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7810 .gap_1()
7811 .py_1()
7812 .px_2()
7813 .child(
7814 h_flex()
7815 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7816 .when(is_platform_style_mac, |parent| parent.gap_1())
7817 .child(h_flex().children(ui::render_modifiers(
7818 &accept_keystroke.modifiers,
7819 PlatformStyle::platform(),
7820 Some(if !has_completion {
7821 Color::Muted
7822 } else {
7823 Color::Default
7824 }),
7825 None,
7826 false,
7827 ))),
7828 )
7829 .child(Label::new("Preview").into_any_element())
7830 .opacity(if has_completion { 1.0 } else { 0.4 }),
7831 )
7832 })
7833 .into_any(),
7834 )
7835 }
7836
7837 fn render_edit_prediction_cursor_popover_preview(
7838 &self,
7839 completion: &InlineCompletionState,
7840 cursor_point: Point,
7841 style: &EditorStyle,
7842 cx: &mut Context<Editor>,
7843 ) -> Option<Div> {
7844 use text::ToPoint as _;
7845
7846 fn render_relative_row_jump(
7847 prefix: impl Into<String>,
7848 current_row: u32,
7849 target_row: u32,
7850 ) -> Div {
7851 let (row_diff, arrow) = if target_row < current_row {
7852 (current_row - target_row, IconName::ArrowUp)
7853 } else {
7854 (target_row - current_row, IconName::ArrowDown)
7855 };
7856
7857 h_flex()
7858 .child(
7859 Label::new(format!("{}{}", prefix.into(), row_diff))
7860 .color(Color::Muted)
7861 .size(LabelSize::Small),
7862 )
7863 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7864 }
7865
7866 match &completion.completion {
7867 InlineCompletion::Move {
7868 target, snapshot, ..
7869 } => Some(
7870 h_flex()
7871 .px_2()
7872 .gap_2()
7873 .flex_1()
7874 .child(
7875 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7876 Icon::new(IconName::ZedPredictDown)
7877 } else {
7878 Icon::new(IconName::ZedPredictUp)
7879 },
7880 )
7881 .child(Label::new("Jump to Edit")),
7882 ),
7883
7884 InlineCompletion::Edit {
7885 edits,
7886 edit_preview,
7887 snapshot,
7888 display_mode: _,
7889 } => {
7890 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7891
7892 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7893 &snapshot,
7894 &edits,
7895 edit_preview.as_ref()?,
7896 true,
7897 cx,
7898 )
7899 .first_line_preview();
7900
7901 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7902 .with_default_highlights(&style.text, highlighted_edits.highlights);
7903
7904 let preview = h_flex()
7905 .gap_1()
7906 .min_w_16()
7907 .child(styled_text)
7908 .when(has_more_lines, |parent| parent.child("…"));
7909
7910 let left = if first_edit_row != cursor_point.row {
7911 render_relative_row_jump("", cursor_point.row, first_edit_row)
7912 .into_any_element()
7913 } else {
7914 Icon::new(IconName::ZedPredict).into_any_element()
7915 };
7916
7917 Some(
7918 h_flex()
7919 .h_full()
7920 .flex_1()
7921 .gap_2()
7922 .pr_1()
7923 .overflow_x_hidden()
7924 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7925 .child(left)
7926 .child(preview),
7927 )
7928 }
7929 }
7930 }
7931
7932 fn render_context_menu(
7933 &self,
7934 style: &EditorStyle,
7935 max_height_in_lines: u32,
7936 window: &mut Window,
7937 cx: &mut Context<Editor>,
7938 ) -> Option<AnyElement> {
7939 let menu = self.context_menu.borrow();
7940 let menu = menu.as_ref()?;
7941 if !menu.visible() {
7942 return None;
7943 };
7944 Some(menu.render(style, max_height_in_lines, window, cx))
7945 }
7946
7947 fn render_context_menu_aside(
7948 &mut self,
7949 max_size: Size<Pixels>,
7950 window: &mut Window,
7951 cx: &mut Context<Editor>,
7952 ) -> Option<AnyElement> {
7953 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7954 if menu.visible() {
7955 menu.render_aside(self, max_size, window, cx)
7956 } else {
7957 None
7958 }
7959 })
7960 }
7961
7962 fn hide_context_menu(
7963 &mut self,
7964 window: &mut Window,
7965 cx: &mut Context<Self>,
7966 ) -> Option<CodeContextMenu> {
7967 cx.notify();
7968 self.completion_tasks.clear();
7969 let context_menu = self.context_menu.borrow_mut().take();
7970 self.stale_inline_completion_in_menu.take();
7971 self.update_visible_inline_completion(window, cx);
7972 context_menu
7973 }
7974
7975 fn show_snippet_choices(
7976 &mut self,
7977 choices: &Vec<String>,
7978 selection: Range<Anchor>,
7979 cx: &mut Context<Self>,
7980 ) {
7981 if selection.start.buffer_id.is_none() {
7982 return;
7983 }
7984 let buffer_id = selection.start.buffer_id.unwrap();
7985 let buffer = self.buffer().read(cx).buffer(buffer_id);
7986 let id = post_inc(&mut self.next_completion_id);
7987
7988 if let Some(buffer) = buffer {
7989 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7990 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7991 ));
7992 }
7993 }
7994
7995 pub fn insert_snippet(
7996 &mut self,
7997 insertion_ranges: &[Range<usize>],
7998 snippet: Snippet,
7999 window: &mut Window,
8000 cx: &mut Context<Self>,
8001 ) -> Result<()> {
8002 struct Tabstop<T> {
8003 is_end_tabstop: bool,
8004 ranges: Vec<Range<T>>,
8005 choices: Option<Vec<String>>,
8006 }
8007
8008 let tabstops = self.buffer.update(cx, |buffer, cx| {
8009 let snippet_text: Arc<str> = snippet.text.clone().into();
8010 let edits = insertion_ranges
8011 .iter()
8012 .cloned()
8013 .map(|range| (range, snippet_text.clone()));
8014 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8015
8016 let snapshot = &*buffer.read(cx);
8017 let snippet = &snippet;
8018 snippet
8019 .tabstops
8020 .iter()
8021 .map(|tabstop| {
8022 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8023 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8024 });
8025 let mut tabstop_ranges = tabstop
8026 .ranges
8027 .iter()
8028 .flat_map(|tabstop_range| {
8029 let mut delta = 0_isize;
8030 insertion_ranges.iter().map(move |insertion_range| {
8031 let insertion_start = insertion_range.start as isize + delta;
8032 delta +=
8033 snippet.text.len() as isize - insertion_range.len() as isize;
8034
8035 let start = ((insertion_start + tabstop_range.start) as usize)
8036 .min(snapshot.len());
8037 let end = ((insertion_start + tabstop_range.end) as usize)
8038 .min(snapshot.len());
8039 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8040 })
8041 })
8042 .collect::<Vec<_>>();
8043 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8044
8045 Tabstop {
8046 is_end_tabstop,
8047 ranges: tabstop_ranges,
8048 choices: tabstop.choices.clone(),
8049 }
8050 })
8051 .collect::<Vec<_>>()
8052 });
8053 if let Some(tabstop) = tabstops.first() {
8054 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8055 s.select_ranges(tabstop.ranges.iter().cloned());
8056 });
8057
8058 if let Some(choices) = &tabstop.choices {
8059 if let Some(selection) = tabstop.ranges.first() {
8060 self.show_snippet_choices(choices, selection.clone(), cx)
8061 }
8062 }
8063
8064 // If we're already at the last tabstop and it's at the end of the snippet,
8065 // we're done, we don't need to keep the state around.
8066 if !tabstop.is_end_tabstop {
8067 let choices = tabstops
8068 .iter()
8069 .map(|tabstop| tabstop.choices.clone())
8070 .collect();
8071
8072 let ranges = tabstops
8073 .into_iter()
8074 .map(|tabstop| tabstop.ranges)
8075 .collect::<Vec<_>>();
8076
8077 self.snippet_stack.push(SnippetState {
8078 active_index: 0,
8079 ranges,
8080 choices,
8081 });
8082 }
8083
8084 // Check whether the just-entered snippet ends with an auto-closable bracket.
8085 if self.autoclose_regions.is_empty() {
8086 let snapshot = self.buffer.read(cx).snapshot(cx);
8087 for selection in &mut self.selections.all::<Point>(cx) {
8088 let selection_head = selection.head();
8089 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8090 continue;
8091 };
8092
8093 let mut bracket_pair = None;
8094 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8095 let prev_chars = snapshot
8096 .reversed_chars_at(selection_head)
8097 .collect::<String>();
8098 for (pair, enabled) in scope.brackets() {
8099 if enabled
8100 && pair.close
8101 && prev_chars.starts_with(pair.start.as_str())
8102 && next_chars.starts_with(pair.end.as_str())
8103 {
8104 bracket_pair = Some(pair.clone());
8105 break;
8106 }
8107 }
8108 if let Some(pair) = bracket_pair {
8109 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8110 let autoclose_enabled =
8111 self.use_autoclose && snapshot_settings.use_autoclose;
8112 if autoclose_enabled {
8113 let start = snapshot.anchor_after(selection_head);
8114 let end = snapshot.anchor_after(selection_head);
8115 self.autoclose_regions.push(AutocloseRegion {
8116 selection_id: selection.id,
8117 range: start..end,
8118 pair,
8119 });
8120 }
8121 }
8122 }
8123 }
8124 }
8125 Ok(())
8126 }
8127
8128 pub fn move_to_next_snippet_tabstop(
8129 &mut self,
8130 window: &mut Window,
8131 cx: &mut Context<Self>,
8132 ) -> bool {
8133 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8134 }
8135
8136 pub fn move_to_prev_snippet_tabstop(
8137 &mut self,
8138 window: &mut Window,
8139 cx: &mut Context<Self>,
8140 ) -> bool {
8141 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8142 }
8143
8144 pub fn move_to_snippet_tabstop(
8145 &mut self,
8146 bias: Bias,
8147 window: &mut Window,
8148 cx: &mut Context<Self>,
8149 ) -> bool {
8150 if let Some(mut snippet) = self.snippet_stack.pop() {
8151 match bias {
8152 Bias::Left => {
8153 if snippet.active_index > 0 {
8154 snippet.active_index -= 1;
8155 } else {
8156 self.snippet_stack.push(snippet);
8157 return false;
8158 }
8159 }
8160 Bias::Right => {
8161 if snippet.active_index + 1 < snippet.ranges.len() {
8162 snippet.active_index += 1;
8163 } else {
8164 self.snippet_stack.push(snippet);
8165 return false;
8166 }
8167 }
8168 }
8169 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8170 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8171 s.select_anchor_ranges(current_ranges.iter().cloned())
8172 });
8173
8174 if let Some(choices) = &snippet.choices[snippet.active_index] {
8175 if let Some(selection) = current_ranges.first() {
8176 self.show_snippet_choices(&choices, selection.clone(), cx);
8177 }
8178 }
8179
8180 // If snippet state is not at the last tabstop, push it back on the stack
8181 if snippet.active_index + 1 < snippet.ranges.len() {
8182 self.snippet_stack.push(snippet);
8183 }
8184 return true;
8185 }
8186 }
8187
8188 false
8189 }
8190
8191 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8192 self.transact(window, cx, |this, window, cx| {
8193 this.select_all(&SelectAll, window, cx);
8194 this.insert("", window, cx);
8195 });
8196 }
8197
8198 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8199 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8200 self.transact(window, cx, |this, window, cx| {
8201 this.select_autoclose_pair(window, cx);
8202 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8203 if !this.linked_edit_ranges.is_empty() {
8204 let selections = this.selections.all::<MultiBufferPoint>(cx);
8205 let snapshot = this.buffer.read(cx).snapshot(cx);
8206
8207 for selection in selections.iter() {
8208 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8209 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8210 if selection_start.buffer_id != selection_end.buffer_id {
8211 continue;
8212 }
8213 if let Some(ranges) =
8214 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8215 {
8216 for (buffer, entries) in ranges {
8217 linked_ranges.entry(buffer).or_default().extend(entries);
8218 }
8219 }
8220 }
8221 }
8222
8223 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8224 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8225 for selection in &mut selections {
8226 if selection.is_empty() {
8227 let old_head = selection.head();
8228 let mut new_head =
8229 movement::left(&display_map, old_head.to_display_point(&display_map))
8230 .to_point(&display_map);
8231 if let Some((buffer, line_buffer_range)) = display_map
8232 .buffer_snapshot
8233 .buffer_line_for_row(MultiBufferRow(old_head.row))
8234 {
8235 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8236 let indent_len = match indent_size.kind {
8237 IndentKind::Space => {
8238 buffer.settings_at(line_buffer_range.start, cx).tab_size
8239 }
8240 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8241 };
8242 if old_head.column <= indent_size.len && old_head.column > 0 {
8243 let indent_len = indent_len.get();
8244 new_head = cmp::min(
8245 new_head,
8246 MultiBufferPoint::new(
8247 old_head.row,
8248 ((old_head.column - 1) / indent_len) * indent_len,
8249 ),
8250 );
8251 }
8252 }
8253
8254 selection.set_head(new_head, SelectionGoal::None);
8255 }
8256 }
8257
8258 this.signature_help_state.set_backspace_pressed(true);
8259 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8260 s.select(selections)
8261 });
8262 this.insert("", window, cx);
8263 let empty_str: Arc<str> = Arc::from("");
8264 for (buffer, edits) in linked_ranges {
8265 let snapshot = buffer.read(cx).snapshot();
8266 use text::ToPoint as TP;
8267
8268 let edits = edits
8269 .into_iter()
8270 .map(|range| {
8271 let end_point = TP::to_point(&range.end, &snapshot);
8272 let mut start_point = TP::to_point(&range.start, &snapshot);
8273
8274 if end_point == start_point {
8275 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8276 .saturating_sub(1);
8277 start_point =
8278 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8279 };
8280
8281 (start_point..end_point, empty_str.clone())
8282 })
8283 .sorted_by_key(|(range, _)| range.start)
8284 .collect::<Vec<_>>();
8285 buffer.update(cx, |this, cx| {
8286 this.edit(edits, None, cx);
8287 })
8288 }
8289 this.refresh_inline_completion(true, false, window, cx);
8290 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8291 });
8292 }
8293
8294 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8295 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8296 self.transact(window, cx, |this, window, cx| {
8297 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8298 s.move_with(|map, selection| {
8299 if selection.is_empty() {
8300 let cursor = movement::right(map, selection.head());
8301 selection.end = cursor;
8302 selection.reversed = true;
8303 selection.goal = SelectionGoal::None;
8304 }
8305 })
8306 });
8307 this.insert("", window, cx);
8308 this.refresh_inline_completion(true, false, window, cx);
8309 });
8310 }
8311
8312 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8313 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8314 if self.move_to_prev_snippet_tabstop(window, cx) {
8315 return;
8316 }
8317 self.outdent(&Outdent, window, cx);
8318 }
8319
8320 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8321 if self.move_to_next_snippet_tabstop(window, cx) {
8322 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8323 return;
8324 }
8325 if self.read_only(cx) {
8326 return;
8327 }
8328 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8329 let mut selections = self.selections.all_adjusted(cx);
8330 let buffer = self.buffer.read(cx);
8331 let snapshot = buffer.snapshot(cx);
8332 let rows_iter = selections.iter().map(|s| s.head().row);
8333 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8334
8335 let mut edits = Vec::new();
8336 let mut prev_edited_row = 0;
8337 let mut row_delta = 0;
8338 for selection in &mut selections {
8339 if selection.start.row != prev_edited_row {
8340 row_delta = 0;
8341 }
8342 prev_edited_row = selection.end.row;
8343
8344 // If the selection is non-empty, then increase the indentation of the selected lines.
8345 if !selection.is_empty() {
8346 row_delta =
8347 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8348 continue;
8349 }
8350
8351 // If the selection is empty and the cursor is in the leading whitespace before the
8352 // suggested indentation, then auto-indent the line.
8353 let cursor = selection.head();
8354 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8355 if let Some(suggested_indent) =
8356 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8357 {
8358 if cursor.column < suggested_indent.len
8359 && cursor.column <= current_indent.len
8360 && current_indent.len <= suggested_indent.len
8361 {
8362 selection.start = Point::new(cursor.row, suggested_indent.len);
8363 selection.end = selection.start;
8364 if row_delta == 0 {
8365 edits.extend(Buffer::edit_for_indent_size_adjustment(
8366 cursor.row,
8367 current_indent,
8368 suggested_indent,
8369 ));
8370 row_delta = suggested_indent.len - current_indent.len;
8371 }
8372 continue;
8373 }
8374 }
8375
8376 // Otherwise, insert a hard or soft tab.
8377 let settings = buffer.language_settings_at(cursor, cx);
8378 let tab_size = if settings.hard_tabs {
8379 IndentSize::tab()
8380 } else {
8381 let tab_size = settings.tab_size.get();
8382 let indent_remainder = snapshot
8383 .text_for_range(Point::new(cursor.row, 0)..cursor)
8384 .flat_map(str::chars)
8385 .fold(row_delta % tab_size, |counter: u32, c| {
8386 if c == '\t' {
8387 0
8388 } else {
8389 (counter + 1) % tab_size
8390 }
8391 });
8392
8393 let chars_to_next_tab_stop = tab_size - indent_remainder;
8394 IndentSize::spaces(chars_to_next_tab_stop)
8395 };
8396 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8397 selection.end = selection.start;
8398 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8399 row_delta += tab_size.len;
8400 }
8401
8402 self.transact(window, cx, |this, window, cx| {
8403 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8404 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8405 s.select(selections)
8406 });
8407 this.refresh_inline_completion(true, false, window, cx);
8408 });
8409 }
8410
8411 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8412 if self.read_only(cx) {
8413 return;
8414 }
8415 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8416 let mut selections = self.selections.all::<Point>(cx);
8417 let mut prev_edited_row = 0;
8418 let mut row_delta = 0;
8419 let mut edits = Vec::new();
8420 let buffer = self.buffer.read(cx);
8421 let snapshot = buffer.snapshot(cx);
8422 for selection in &mut selections {
8423 if selection.start.row != prev_edited_row {
8424 row_delta = 0;
8425 }
8426 prev_edited_row = selection.end.row;
8427
8428 row_delta =
8429 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8430 }
8431
8432 self.transact(window, cx, |this, window, cx| {
8433 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8434 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8435 s.select(selections)
8436 });
8437 });
8438 }
8439
8440 fn indent_selection(
8441 buffer: &MultiBuffer,
8442 snapshot: &MultiBufferSnapshot,
8443 selection: &mut Selection<Point>,
8444 edits: &mut Vec<(Range<Point>, String)>,
8445 delta_for_start_row: u32,
8446 cx: &App,
8447 ) -> u32 {
8448 let settings = buffer.language_settings_at(selection.start, cx);
8449 let tab_size = settings.tab_size.get();
8450 let indent_kind = if settings.hard_tabs {
8451 IndentKind::Tab
8452 } else {
8453 IndentKind::Space
8454 };
8455 let mut start_row = selection.start.row;
8456 let mut end_row = selection.end.row + 1;
8457
8458 // If a selection ends at the beginning of a line, don't indent
8459 // that last line.
8460 if selection.end.column == 0 && selection.end.row > selection.start.row {
8461 end_row -= 1;
8462 }
8463
8464 // Avoid re-indenting a row that has already been indented by a
8465 // previous selection, but still update this selection's column
8466 // to reflect that indentation.
8467 if delta_for_start_row > 0 {
8468 start_row += 1;
8469 selection.start.column += delta_for_start_row;
8470 if selection.end.row == selection.start.row {
8471 selection.end.column += delta_for_start_row;
8472 }
8473 }
8474
8475 let mut delta_for_end_row = 0;
8476 let has_multiple_rows = start_row + 1 != end_row;
8477 for row in start_row..end_row {
8478 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8479 let indent_delta = match (current_indent.kind, indent_kind) {
8480 (IndentKind::Space, IndentKind::Space) => {
8481 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8482 IndentSize::spaces(columns_to_next_tab_stop)
8483 }
8484 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8485 (_, IndentKind::Tab) => IndentSize::tab(),
8486 };
8487
8488 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8489 0
8490 } else {
8491 selection.start.column
8492 };
8493 let row_start = Point::new(row, start);
8494 edits.push((
8495 row_start..row_start,
8496 indent_delta.chars().collect::<String>(),
8497 ));
8498
8499 // Update this selection's endpoints to reflect the indentation.
8500 if row == selection.start.row {
8501 selection.start.column += indent_delta.len;
8502 }
8503 if row == selection.end.row {
8504 selection.end.column += indent_delta.len;
8505 delta_for_end_row = indent_delta.len;
8506 }
8507 }
8508
8509 if selection.start.row == selection.end.row {
8510 delta_for_start_row + delta_for_end_row
8511 } else {
8512 delta_for_end_row
8513 }
8514 }
8515
8516 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8517 if self.read_only(cx) {
8518 return;
8519 }
8520 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8521 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8522 let selections = self.selections.all::<Point>(cx);
8523 let mut deletion_ranges = Vec::new();
8524 let mut last_outdent = None;
8525 {
8526 let buffer = self.buffer.read(cx);
8527 let snapshot = buffer.snapshot(cx);
8528 for selection in &selections {
8529 let settings = buffer.language_settings_at(selection.start, cx);
8530 let tab_size = settings.tab_size.get();
8531 let mut rows = selection.spanned_rows(false, &display_map);
8532
8533 // Avoid re-outdenting a row that has already been outdented by a
8534 // previous selection.
8535 if let Some(last_row) = last_outdent {
8536 if last_row == rows.start {
8537 rows.start = rows.start.next_row();
8538 }
8539 }
8540 let has_multiple_rows = rows.len() > 1;
8541 for row in rows.iter_rows() {
8542 let indent_size = snapshot.indent_size_for_line(row);
8543 if indent_size.len > 0 {
8544 let deletion_len = match indent_size.kind {
8545 IndentKind::Space => {
8546 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8547 if columns_to_prev_tab_stop == 0 {
8548 tab_size
8549 } else {
8550 columns_to_prev_tab_stop
8551 }
8552 }
8553 IndentKind::Tab => 1,
8554 };
8555 let start = if has_multiple_rows
8556 || deletion_len > selection.start.column
8557 || indent_size.len < selection.start.column
8558 {
8559 0
8560 } else {
8561 selection.start.column - deletion_len
8562 };
8563 deletion_ranges.push(
8564 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8565 );
8566 last_outdent = Some(row);
8567 }
8568 }
8569 }
8570 }
8571
8572 self.transact(window, cx, |this, window, cx| {
8573 this.buffer.update(cx, |buffer, cx| {
8574 let empty_str: Arc<str> = Arc::default();
8575 buffer.edit(
8576 deletion_ranges
8577 .into_iter()
8578 .map(|range| (range, empty_str.clone())),
8579 None,
8580 cx,
8581 );
8582 });
8583 let selections = this.selections.all::<usize>(cx);
8584 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8585 s.select(selections)
8586 });
8587 });
8588 }
8589
8590 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8591 if self.read_only(cx) {
8592 return;
8593 }
8594 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8595 let selections = self
8596 .selections
8597 .all::<usize>(cx)
8598 .into_iter()
8599 .map(|s| s.range());
8600
8601 self.transact(window, cx, |this, window, cx| {
8602 this.buffer.update(cx, |buffer, cx| {
8603 buffer.autoindent_ranges(selections, cx);
8604 });
8605 let selections = this.selections.all::<usize>(cx);
8606 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8607 s.select(selections)
8608 });
8609 });
8610 }
8611
8612 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8613 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8614 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8615 let selections = self.selections.all::<Point>(cx);
8616
8617 let mut new_cursors = Vec::new();
8618 let mut edit_ranges = Vec::new();
8619 let mut selections = selections.iter().peekable();
8620 while let Some(selection) = selections.next() {
8621 let mut rows = selection.spanned_rows(false, &display_map);
8622 let goal_display_column = selection.head().to_display_point(&display_map).column();
8623
8624 // Accumulate contiguous regions of rows that we want to delete.
8625 while let Some(next_selection) = selections.peek() {
8626 let next_rows = next_selection.spanned_rows(false, &display_map);
8627 if next_rows.start <= rows.end {
8628 rows.end = next_rows.end;
8629 selections.next().unwrap();
8630 } else {
8631 break;
8632 }
8633 }
8634
8635 let buffer = &display_map.buffer_snapshot;
8636 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8637 let edit_end;
8638 let cursor_buffer_row;
8639 if buffer.max_point().row >= rows.end.0 {
8640 // If there's a line after the range, delete the \n from the end of the row range
8641 // and position the cursor on the next line.
8642 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8643 cursor_buffer_row = rows.end;
8644 } else {
8645 // If there isn't a line after the range, delete the \n from the line before the
8646 // start of the row range and position the cursor there.
8647 edit_start = edit_start.saturating_sub(1);
8648 edit_end = buffer.len();
8649 cursor_buffer_row = rows.start.previous_row();
8650 }
8651
8652 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8653 *cursor.column_mut() =
8654 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8655
8656 new_cursors.push((
8657 selection.id,
8658 buffer.anchor_after(cursor.to_point(&display_map)),
8659 ));
8660 edit_ranges.push(edit_start..edit_end);
8661 }
8662
8663 self.transact(window, cx, |this, window, cx| {
8664 let buffer = this.buffer.update(cx, |buffer, cx| {
8665 let empty_str: Arc<str> = Arc::default();
8666 buffer.edit(
8667 edit_ranges
8668 .into_iter()
8669 .map(|range| (range, empty_str.clone())),
8670 None,
8671 cx,
8672 );
8673 buffer.snapshot(cx)
8674 });
8675 let new_selections = new_cursors
8676 .into_iter()
8677 .map(|(id, cursor)| {
8678 let cursor = cursor.to_point(&buffer);
8679 Selection {
8680 id,
8681 start: cursor,
8682 end: cursor,
8683 reversed: false,
8684 goal: SelectionGoal::None,
8685 }
8686 })
8687 .collect();
8688
8689 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8690 s.select(new_selections);
8691 });
8692 });
8693 }
8694
8695 pub fn join_lines_impl(
8696 &mut self,
8697 insert_whitespace: bool,
8698 window: &mut Window,
8699 cx: &mut Context<Self>,
8700 ) {
8701 if self.read_only(cx) {
8702 return;
8703 }
8704 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8705 for selection in self.selections.all::<Point>(cx) {
8706 let start = MultiBufferRow(selection.start.row);
8707 // Treat single line selections as if they include the next line. Otherwise this action
8708 // would do nothing for single line selections individual cursors.
8709 let end = if selection.start.row == selection.end.row {
8710 MultiBufferRow(selection.start.row + 1)
8711 } else {
8712 MultiBufferRow(selection.end.row)
8713 };
8714
8715 if let Some(last_row_range) = row_ranges.last_mut() {
8716 if start <= last_row_range.end {
8717 last_row_range.end = end;
8718 continue;
8719 }
8720 }
8721 row_ranges.push(start..end);
8722 }
8723
8724 let snapshot = self.buffer.read(cx).snapshot(cx);
8725 let mut cursor_positions = Vec::new();
8726 for row_range in &row_ranges {
8727 let anchor = snapshot.anchor_before(Point::new(
8728 row_range.end.previous_row().0,
8729 snapshot.line_len(row_range.end.previous_row()),
8730 ));
8731 cursor_positions.push(anchor..anchor);
8732 }
8733
8734 self.transact(window, cx, |this, window, cx| {
8735 for row_range in row_ranges.into_iter().rev() {
8736 for row in row_range.iter_rows().rev() {
8737 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8738 let next_line_row = row.next_row();
8739 let indent = snapshot.indent_size_for_line(next_line_row);
8740 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8741
8742 let replace =
8743 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8744 " "
8745 } else {
8746 ""
8747 };
8748
8749 this.buffer.update(cx, |buffer, cx| {
8750 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8751 });
8752 }
8753 }
8754
8755 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8756 s.select_anchor_ranges(cursor_positions)
8757 });
8758 });
8759 }
8760
8761 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8762 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8763 self.join_lines_impl(true, window, cx);
8764 }
8765
8766 pub fn sort_lines_case_sensitive(
8767 &mut self,
8768 _: &SortLinesCaseSensitive,
8769 window: &mut Window,
8770 cx: &mut Context<Self>,
8771 ) {
8772 self.manipulate_lines(window, cx, |lines| lines.sort())
8773 }
8774
8775 pub fn sort_lines_case_insensitive(
8776 &mut self,
8777 _: &SortLinesCaseInsensitive,
8778 window: &mut Window,
8779 cx: &mut Context<Self>,
8780 ) {
8781 self.manipulate_lines(window, cx, |lines| {
8782 lines.sort_by_key(|line| line.to_lowercase())
8783 })
8784 }
8785
8786 pub fn unique_lines_case_insensitive(
8787 &mut self,
8788 _: &UniqueLinesCaseInsensitive,
8789 window: &mut Window,
8790 cx: &mut Context<Self>,
8791 ) {
8792 self.manipulate_lines(window, cx, |lines| {
8793 let mut seen = HashSet::default();
8794 lines.retain(|line| seen.insert(line.to_lowercase()));
8795 })
8796 }
8797
8798 pub fn unique_lines_case_sensitive(
8799 &mut self,
8800 _: &UniqueLinesCaseSensitive,
8801 window: &mut Window,
8802 cx: &mut Context<Self>,
8803 ) {
8804 self.manipulate_lines(window, cx, |lines| {
8805 let mut seen = HashSet::default();
8806 lines.retain(|line| seen.insert(*line));
8807 })
8808 }
8809
8810 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8811 let Some(project) = self.project.clone() else {
8812 return;
8813 };
8814 self.reload(project, window, cx)
8815 .detach_and_notify_err(window, cx);
8816 }
8817
8818 pub fn restore_file(
8819 &mut self,
8820 _: &::git::RestoreFile,
8821 window: &mut Window,
8822 cx: &mut Context<Self>,
8823 ) {
8824 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8825 let mut buffer_ids = HashSet::default();
8826 let snapshot = self.buffer().read(cx).snapshot(cx);
8827 for selection in self.selections.all::<usize>(cx) {
8828 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8829 }
8830
8831 let buffer = self.buffer().read(cx);
8832 let ranges = buffer_ids
8833 .into_iter()
8834 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8835 .collect::<Vec<_>>();
8836
8837 self.restore_hunks_in_ranges(ranges, window, cx);
8838 }
8839
8840 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8841 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8842 let selections = self
8843 .selections
8844 .all(cx)
8845 .into_iter()
8846 .map(|s| s.range())
8847 .collect();
8848 self.restore_hunks_in_ranges(selections, window, cx);
8849 }
8850
8851 pub fn restore_hunks_in_ranges(
8852 &mut self,
8853 ranges: Vec<Range<Point>>,
8854 window: &mut Window,
8855 cx: &mut Context<Editor>,
8856 ) {
8857 let mut revert_changes = HashMap::default();
8858 let chunk_by = self
8859 .snapshot(window, cx)
8860 .hunks_for_ranges(ranges)
8861 .into_iter()
8862 .chunk_by(|hunk| hunk.buffer_id);
8863 for (buffer_id, hunks) in &chunk_by {
8864 let hunks = hunks.collect::<Vec<_>>();
8865 for hunk in &hunks {
8866 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8867 }
8868 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8869 }
8870 drop(chunk_by);
8871 if !revert_changes.is_empty() {
8872 self.transact(window, cx, |editor, window, cx| {
8873 editor.restore(revert_changes, window, cx);
8874 });
8875 }
8876 }
8877
8878 pub fn open_active_item_in_terminal(
8879 &mut self,
8880 _: &OpenInTerminal,
8881 window: &mut Window,
8882 cx: &mut Context<Self>,
8883 ) {
8884 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8885 let project_path = buffer.read(cx).project_path(cx)?;
8886 let project = self.project.as_ref()?.read(cx);
8887 let entry = project.entry_for_path(&project_path, cx)?;
8888 let parent = match &entry.canonical_path {
8889 Some(canonical_path) => canonical_path.to_path_buf(),
8890 None => project.absolute_path(&project_path, cx)?,
8891 }
8892 .parent()?
8893 .to_path_buf();
8894 Some(parent)
8895 }) {
8896 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8897 }
8898 }
8899
8900 fn set_breakpoint_context_menu(
8901 &mut self,
8902 display_row: DisplayRow,
8903 position: Option<Anchor>,
8904 clicked_point: gpui::Point<Pixels>,
8905 window: &mut Window,
8906 cx: &mut Context<Self>,
8907 ) {
8908 if !cx.has_flag::<Debugger>() {
8909 return;
8910 }
8911 let source = self
8912 .buffer
8913 .read(cx)
8914 .snapshot(cx)
8915 .anchor_before(Point::new(display_row.0, 0u32));
8916
8917 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8918
8919 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8920 self,
8921 source,
8922 clicked_point,
8923 None,
8924 context_menu,
8925 window,
8926 cx,
8927 );
8928 }
8929
8930 fn add_edit_breakpoint_block(
8931 &mut self,
8932 anchor: Anchor,
8933 breakpoint: &Breakpoint,
8934 edit_action: BreakpointPromptEditAction,
8935 window: &mut Window,
8936 cx: &mut Context<Self>,
8937 ) {
8938 let weak_editor = cx.weak_entity();
8939 let bp_prompt = cx.new(|cx| {
8940 BreakpointPromptEditor::new(
8941 weak_editor,
8942 anchor,
8943 breakpoint.clone(),
8944 edit_action,
8945 window,
8946 cx,
8947 )
8948 });
8949
8950 let height = bp_prompt.update(cx, |this, cx| {
8951 this.prompt
8952 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8953 });
8954 let cloned_prompt = bp_prompt.clone();
8955 let blocks = vec![BlockProperties {
8956 style: BlockStyle::Sticky,
8957 placement: BlockPlacement::Above(anchor),
8958 height: Some(height),
8959 render: Arc::new(move |cx| {
8960 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8961 cloned_prompt.clone().into_any_element()
8962 }),
8963 priority: 0,
8964 }];
8965
8966 let focus_handle = bp_prompt.focus_handle(cx);
8967 window.focus(&focus_handle);
8968
8969 let block_ids = self.insert_blocks(blocks, None, cx);
8970 bp_prompt.update(cx, |prompt, _| {
8971 prompt.add_block_ids(block_ids);
8972 });
8973 }
8974
8975 pub(crate) fn breakpoint_at_row(
8976 &self,
8977 row: u32,
8978 window: &mut Window,
8979 cx: &mut Context<Self>,
8980 ) -> Option<(Anchor, Breakpoint)> {
8981 let snapshot = self.snapshot(window, cx);
8982 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8983
8984 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
8985 }
8986
8987 pub(crate) fn breakpoint_at_anchor(
8988 &self,
8989 breakpoint_position: Anchor,
8990 snapshot: &EditorSnapshot,
8991 cx: &mut Context<Self>,
8992 ) -> Option<(Anchor, Breakpoint)> {
8993 let project = self.project.clone()?;
8994
8995 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8996 snapshot
8997 .buffer_snapshot
8998 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8999 })?;
9000
9001 let enclosing_excerpt = breakpoint_position.excerpt_id;
9002 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9003 let buffer_snapshot = buffer.read(cx).snapshot();
9004
9005 let row = buffer_snapshot
9006 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9007 .row;
9008
9009 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9010 let anchor_end = snapshot
9011 .buffer_snapshot
9012 .anchor_after(Point::new(row, line_len));
9013
9014 let bp = self
9015 .breakpoint_store
9016 .as_ref()?
9017 .read_with(cx, |breakpoint_store, cx| {
9018 breakpoint_store
9019 .breakpoints(
9020 &buffer,
9021 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9022 &buffer_snapshot,
9023 cx,
9024 )
9025 .next()
9026 .and_then(|(anchor, bp)| {
9027 let breakpoint_row = buffer_snapshot
9028 .summary_for_anchor::<text::PointUtf16>(anchor)
9029 .row;
9030
9031 if breakpoint_row == row {
9032 snapshot
9033 .buffer_snapshot
9034 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9035 .map(|anchor| (anchor, bp.clone()))
9036 } else {
9037 None
9038 }
9039 })
9040 });
9041 bp
9042 }
9043
9044 pub fn edit_log_breakpoint(
9045 &mut self,
9046 _: &EditLogBreakpoint,
9047 window: &mut Window,
9048 cx: &mut Context<Self>,
9049 ) {
9050 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9051 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9052 message: None,
9053 state: BreakpointState::Enabled,
9054 condition: None,
9055 hit_condition: None,
9056 });
9057
9058 self.add_edit_breakpoint_block(
9059 anchor,
9060 &breakpoint,
9061 BreakpointPromptEditAction::Log,
9062 window,
9063 cx,
9064 );
9065 }
9066 }
9067
9068 fn breakpoints_at_cursors(
9069 &self,
9070 window: &mut Window,
9071 cx: &mut Context<Self>,
9072 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9073 let snapshot = self.snapshot(window, cx);
9074 let cursors = self
9075 .selections
9076 .disjoint_anchors()
9077 .into_iter()
9078 .map(|selection| {
9079 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9080
9081 let breakpoint_position = self
9082 .breakpoint_at_row(cursor_position.row, window, cx)
9083 .map(|bp| bp.0)
9084 .unwrap_or_else(|| {
9085 snapshot
9086 .display_snapshot
9087 .buffer_snapshot
9088 .anchor_after(Point::new(cursor_position.row, 0))
9089 });
9090
9091 let breakpoint = self
9092 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9093 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9094
9095 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9096 })
9097 // There might be multiple cursors on the same line; all of them should have the same anchors though as their breakpoints positions, which makes it possible to sort and dedup the list.
9098 .collect::<HashMap<Anchor, _>>();
9099
9100 cursors.into_iter().collect()
9101 }
9102
9103 pub fn enable_breakpoint(
9104 &mut self,
9105 _: &crate::actions::EnableBreakpoint,
9106 window: &mut Window,
9107 cx: &mut Context<Self>,
9108 ) {
9109 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9110 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9111 continue;
9112 };
9113 self.edit_breakpoint_at_anchor(
9114 anchor,
9115 breakpoint,
9116 BreakpointEditAction::InvertState,
9117 cx,
9118 );
9119 }
9120 }
9121
9122 pub fn disable_breakpoint(
9123 &mut self,
9124 _: &crate::actions::DisableBreakpoint,
9125 window: &mut Window,
9126 cx: &mut Context<Self>,
9127 ) {
9128 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9129 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9130 continue;
9131 };
9132 self.edit_breakpoint_at_anchor(
9133 anchor,
9134 breakpoint,
9135 BreakpointEditAction::InvertState,
9136 cx,
9137 );
9138 }
9139 }
9140
9141 pub fn toggle_breakpoint(
9142 &mut self,
9143 _: &crate::actions::ToggleBreakpoint,
9144 window: &mut Window,
9145 cx: &mut Context<Self>,
9146 ) {
9147 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9148 if let Some(breakpoint) = breakpoint {
9149 self.edit_breakpoint_at_anchor(
9150 anchor,
9151 breakpoint,
9152 BreakpointEditAction::Toggle,
9153 cx,
9154 );
9155 } else {
9156 self.edit_breakpoint_at_anchor(
9157 anchor,
9158 Breakpoint::new_standard(),
9159 BreakpointEditAction::Toggle,
9160 cx,
9161 );
9162 }
9163 }
9164 }
9165
9166 pub fn edit_breakpoint_at_anchor(
9167 &mut self,
9168 breakpoint_position: Anchor,
9169 breakpoint: Breakpoint,
9170 edit_action: BreakpointEditAction,
9171 cx: &mut Context<Self>,
9172 ) {
9173 let Some(breakpoint_store) = &self.breakpoint_store else {
9174 return;
9175 };
9176
9177 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9178 if breakpoint_position == Anchor::min() {
9179 self.buffer()
9180 .read(cx)
9181 .excerpt_buffer_ids()
9182 .into_iter()
9183 .next()
9184 } else {
9185 None
9186 }
9187 }) else {
9188 return;
9189 };
9190
9191 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9192 return;
9193 };
9194
9195 breakpoint_store.update(cx, |breakpoint_store, cx| {
9196 breakpoint_store.toggle_breakpoint(
9197 buffer,
9198 (breakpoint_position.text_anchor, breakpoint),
9199 edit_action,
9200 cx,
9201 );
9202 });
9203
9204 cx.notify();
9205 }
9206
9207 #[cfg(any(test, feature = "test-support"))]
9208 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9209 self.breakpoint_store.clone()
9210 }
9211
9212 pub fn prepare_restore_change(
9213 &self,
9214 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9215 hunk: &MultiBufferDiffHunk,
9216 cx: &mut App,
9217 ) -> Option<()> {
9218 if hunk.is_created_file() {
9219 return None;
9220 }
9221 let buffer = self.buffer.read(cx);
9222 let diff = buffer.diff_for(hunk.buffer_id)?;
9223 let buffer = buffer.buffer(hunk.buffer_id)?;
9224 let buffer = buffer.read(cx);
9225 let original_text = diff
9226 .read(cx)
9227 .base_text()
9228 .as_rope()
9229 .slice(hunk.diff_base_byte_range.clone());
9230 let buffer_snapshot = buffer.snapshot();
9231 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9232 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9233 probe
9234 .0
9235 .start
9236 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9237 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9238 }) {
9239 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9240 Some(())
9241 } else {
9242 None
9243 }
9244 }
9245
9246 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9247 self.manipulate_lines(window, cx, |lines| lines.reverse())
9248 }
9249
9250 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9251 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9252 }
9253
9254 fn manipulate_lines<Fn>(
9255 &mut self,
9256 window: &mut Window,
9257 cx: &mut Context<Self>,
9258 mut callback: Fn,
9259 ) where
9260 Fn: FnMut(&mut Vec<&str>),
9261 {
9262 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9263
9264 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9265 let buffer = self.buffer.read(cx).snapshot(cx);
9266
9267 let mut edits = Vec::new();
9268
9269 let selections = self.selections.all::<Point>(cx);
9270 let mut selections = selections.iter().peekable();
9271 let mut contiguous_row_selections = Vec::new();
9272 let mut new_selections = Vec::new();
9273 let mut added_lines = 0;
9274 let mut removed_lines = 0;
9275
9276 while let Some(selection) = selections.next() {
9277 let (start_row, end_row) = consume_contiguous_rows(
9278 &mut contiguous_row_selections,
9279 selection,
9280 &display_map,
9281 &mut selections,
9282 );
9283
9284 let start_point = Point::new(start_row.0, 0);
9285 let end_point = Point::new(
9286 end_row.previous_row().0,
9287 buffer.line_len(end_row.previous_row()),
9288 );
9289 let text = buffer
9290 .text_for_range(start_point..end_point)
9291 .collect::<String>();
9292
9293 let mut lines = text.split('\n').collect_vec();
9294
9295 let lines_before = lines.len();
9296 callback(&mut lines);
9297 let lines_after = lines.len();
9298
9299 edits.push((start_point..end_point, lines.join("\n")));
9300
9301 // Selections must change based on added and removed line count
9302 let start_row =
9303 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9304 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9305 new_selections.push(Selection {
9306 id: selection.id,
9307 start: start_row,
9308 end: end_row,
9309 goal: SelectionGoal::None,
9310 reversed: selection.reversed,
9311 });
9312
9313 if lines_after > lines_before {
9314 added_lines += lines_after - lines_before;
9315 } else if lines_before > lines_after {
9316 removed_lines += lines_before - lines_after;
9317 }
9318 }
9319
9320 self.transact(window, cx, |this, window, cx| {
9321 let buffer = this.buffer.update(cx, |buffer, cx| {
9322 buffer.edit(edits, None, cx);
9323 buffer.snapshot(cx)
9324 });
9325
9326 // Recalculate offsets on newly edited buffer
9327 let new_selections = new_selections
9328 .iter()
9329 .map(|s| {
9330 let start_point = Point::new(s.start.0, 0);
9331 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9332 Selection {
9333 id: s.id,
9334 start: buffer.point_to_offset(start_point),
9335 end: buffer.point_to_offset(end_point),
9336 goal: s.goal,
9337 reversed: s.reversed,
9338 }
9339 })
9340 .collect();
9341
9342 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9343 s.select(new_selections);
9344 });
9345
9346 this.request_autoscroll(Autoscroll::fit(), cx);
9347 });
9348 }
9349
9350 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9351 self.manipulate_text(window, cx, |text| {
9352 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9353 if has_upper_case_characters {
9354 text.to_lowercase()
9355 } else {
9356 text.to_uppercase()
9357 }
9358 })
9359 }
9360
9361 pub fn convert_to_upper_case(
9362 &mut self,
9363 _: &ConvertToUpperCase,
9364 window: &mut Window,
9365 cx: &mut Context<Self>,
9366 ) {
9367 self.manipulate_text(window, cx, |text| text.to_uppercase())
9368 }
9369
9370 pub fn convert_to_lower_case(
9371 &mut self,
9372 _: &ConvertToLowerCase,
9373 window: &mut Window,
9374 cx: &mut Context<Self>,
9375 ) {
9376 self.manipulate_text(window, cx, |text| text.to_lowercase())
9377 }
9378
9379 pub fn convert_to_title_case(
9380 &mut self,
9381 _: &ConvertToTitleCase,
9382 window: &mut Window,
9383 cx: &mut Context<Self>,
9384 ) {
9385 self.manipulate_text(window, cx, |text| {
9386 text.split('\n')
9387 .map(|line| line.to_case(Case::Title))
9388 .join("\n")
9389 })
9390 }
9391
9392 pub fn convert_to_snake_case(
9393 &mut self,
9394 _: &ConvertToSnakeCase,
9395 window: &mut Window,
9396 cx: &mut Context<Self>,
9397 ) {
9398 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9399 }
9400
9401 pub fn convert_to_kebab_case(
9402 &mut self,
9403 _: &ConvertToKebabCase,
9404 window: &mut Window,
9405 cx: &mut Context<Self>,
9406 ) {
9407 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9408 }
9409
9410 pub fn convert_to_upper_camel_case(
9411 &mut self,
9412 _: &ConvertToUpperCamelCase,
9413 window: &mut Window,
9414 cx: &mut Context<Self>,
9415 ) {
9416 self.manipulate_text(window, cx, |text| {
9417 text.split('\n')
9418 .map(|line| line.to_case(Case::UpperCamel))
9419 .join("\n")
9420 })
9421 }
9422
9423 pub fn convert_to_lower_camel_case(
9424 &mut self,
9425 _: &ConvertToLowerCamelCase,
9426 window: &mut Window,
9427 cx: &mut Context<Self>,
9428 ) {
9429 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9430 }
9431
9432 pub fn convert_to_opposite_case(
9433 &mut self,
9434 _: &ConvertToOppositeCase,
9435 window: &mut Window,
9436 cx: &mut Context<Self>,
9437 ) {
9438 self.manipulate_text(window, cx, |text| {
9439 text.chars()
9440 .fold(String::with_capacity(text.len()), |mut t, c| {
9441 if c.is_uppercase() {
9442 t.extend(c.to_lowercase());
9443 } else {
9444 t.extend(c.to_uppercase());
9445 }
9446 t
9447 })
9448 })
9449 }
9450
9451 pub fn convert_to_rot13(
9452 &mut self,
9453 _: &ConvertToRot13,
9454 window: &mut Window,
9455 cx: &mut Context<Self>,
9456 ) {
9457 self.manipulate_text(window, cx, |text| {
9458 text.chars()
9459 .map(|c| match c {
9460 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9461 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9462 _ => c,
9463 })
9464 .collect()
9465 })
9466 }
9467
9468 pub fn convert_to_rot47(
9469 &mut self,
9470 _: &ConvertToRot47,
9471 window: &mut Window,
9472 cx: &mut Context<Self>,
9473 ) {
9474 self.manipulate_text(window, cx, |text| {
9475 text.chars()
9476 .map(|c| {
9477 let code_point = c as u32;
9478 if code_point >= 33 && code_point <= 126 {
9479 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9480 }
9481 c
9482 })
9483 .collect()
9484 })
9485 }
9486
9487 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9488 where
9489 Fn: FnMut(&str) -> String,
9490 {
9491 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9492 let buffer = self.buffer.read(cx).snapshot(cx);
9493
9494 let mut new_selections = Vec::new();
9495 let mut edits = Vec::new();
9496 let mut selection_adjustment = 0i32;
9497
9498 for selection in self.selections.all::<usize>(cx) {
9499 let selection_is_empty = selection.is_empty();
9500
9501 let (start, end) = if selection_is_empty {
9502 let word_range = movement::surrounding_word(
9503 &display_map,
9504 selection.start.to_display_point(&display_map),
9505 );
9506 let start = word_range.start.to_offset(&display_map, Bias::Left);
9507 let end = word_range.end.to_offset(&display_map, Bias::Left);
9508 (start, end)
9509 } else {
9510 (selection.start, selection.end)
9511 };
9512
9513 let text = buffer.text_for_range(start..end).collect::<String>();
9514 let old_length = text.len() as i32;
9515 let text = callback(&text);
9516
9517 new_selections.push(Selection {
9518 start: (start as i32 - selection_adjustment) as usize,
9519 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9520 goal: SelectionGoal::None,
9521 ..selection
9522 });
9523
9524 selection_adjustment += old_length - text.len() as i32;
9525
9526 edits.push((start..end, text));
9527 }
9528
9529 self.transact(window, cx, |this, window, cx| {
9530 this.buffer.update(cx, |buffer, cx| {
9531 buffer.edit(edits, None, cx);
9532 });
9533
9534 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9535 s.select(new_selections);
9536 });
9537
9538 this.request_autoscroll(Autoscroll::fit(), cx);
9539 });
9540 }
9541
9542 pub fn duplicate(
9543 &mut self,
9544 upwards: bool,
9545 whole_lines: bool,
9546 window: &mut Window,
9547 cx: &mut Context<Self>,
9548 ) {
9549 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9550
9551 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9552 let buffer = &display_map.buffer_snapshot;
9553 let selections = self.selections.all::<Point>(cx);
9554
9555 let mut edits = Vec::new();
9556 let mut selections_iter = selections.iter().peekable();
9557 while let Some(selection) = selections_iter.next() {
9558 let mut rows = selection.spanned_rows(false, &display_map);
9559 // duplicate line-wise
9560 if whole_lines || selection.start == selection.end {
9561 // Avoid duplicating the same lines twice.
9562 while let Some(next_selection) = selections_iter.peek() {
9563 let next_rows = next_selection.spanned_rows(false, &display_map);
9564 if next_rows.start < rows.end {
9565 rows.end = next_rows.end;
9566 selections_iter.next().unwrap();
9567 } else {
9568 break;
9569 }
9570 }
9571
9572 // Copy the text from the selected row region and splice it either at the start
9573 // or end of the region.
9574 let start = Point::new(rows.start.0, 0);
9575 let end = Point::new(
9576 rows.end.previous_row().0,
9577 buffer.line_len(rows.end.previous_row()),
9578 );
9579 let text = buffer
9580 .text_for_range(start..end)
9581 .chain(Some("\n"))
9582 .collect::<String>();
9583 let insert_location = if upwards {
9584 Point::new(rows.end.0, 0)
9585 } else {
9586 start
9587 };
9588 edits.push((insert_location..insert_location, text));
9589 } else {
9590 // duplicate character-wise
9591 let start = selection.start;
9592 let end = selection.end;
9593 let text = buffer.text_for_range(start..end).collect::<String>();
9594 edits.push((selection.end..selection.end, text));
9595 }
9596 }
9597
9598 self.transact(window, cx, |this, _, cx| {
9599 this.buffer.update(cx, |buffer, cx| {
9600 buffer.edit(edits, None, cx);
9601 });
9602
9603 this.request_autoscroll(Autoscroll::fit(), cx);
9604 });
9605 }
9606
9607 pub fn duplicate_line_up(
9608 &mut self,
9609 _: &DuplicateLineUp,
9610 window: &mut Window,
9611 cx: &mut Context<Self>,
9612 ) {
9613 self.duplicate(true, true, window, cx);
9614 }
9615
9616 pub fn duplicate_line_down(
9617 &mut self,
9618 _: &DuplicateLineDown,
9619 window: &mut Window,
9620 cx: &mut Context<Self>,
9621 ) {
9622 self.duplicate(false, true, window, cx);
9623 }
9624
9625 pub fn duplicate_selection(
9626 &mut self,
9627 _: &DuplicateSelection,
9628 window: &mut Window,
9629 cx: &mut Context<Self>,
9630 ) {
9631 self.duplicate(false, false, window, cx);
9632 }
9633
9634 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9635 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9636
9637 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9638 let buffer = self.buffer.read(cx).snapshot(cx);
9639
9640 let mut edits = Vec::new();
9641 let mut unfold_ranges = Vec::new();
9642 let mut refold_creases = Vec::new();
9643
9644 let selections = self.selections.all::<Point>(cx);
9645 let mut selections = selections.iter().peekable();
9646 let mut contiguous_row_selections = Vec::new();
9647 let mut new_selections = Vec::new();
9648
9649 while let Some(selection) = selections.next() {
9650 // Find all the selections that span a contiguous row range
9651 let (start_row, end_row) = consume_contiguous_rows(
9652 &mut contiguous_row_selections,
9653 selection,
9654 &display_map,
9655 &mut selections,
9656 );
9657
9658 // Move the text spanned by the row range to be before the line preceding the row range
9659 if start_row.0 > 0 {
9660 let range_to_move = Point::new(
9661 start_row.previous_row().0,
9662 buffer.line_len(start_row.previous_row()),
9663 )
9664 ..Point::new(
9665 end_row.previous_row().0,
9666 buffer.line_len(end_row.previous_row()),
9667 );
9668 let insertion_point = display_map
9669 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9670 .0;
9671
9672 // Don't move lines across excerpts
9673 if buffer
9674 .excerpt_containing(insertion_point..range_to_move.end)
9675 .is_some()
9676 {
9677 let text = buffer
9678 .text_for_range(range_to_move.clone())
9679 .flat_map(|s| s.chars())
9680 .skip(1)
9681 .chain(['\n'])
9682 .collect::<String>();
9683
9684 edits.push((
9685 buffer.anchor_after(range_to_move.start)
9686 ..buffer.anchor_before(range_to_move.end),
9687 String::new(),
9688 ));
9689 let insertion_anchor = buffer.anchor_after(insertion_point);
9690 edits.push((insertion_anchor..insertion_anchor, text));
9691
9692 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9693
9694 // Move selections up
9695 new_selections.extend(contiguous_row_selections.drain(..).map(
9696 |mut selection| {
9697 selection.start.row -= row_delta;
9698 selection.end.row -= row_delta;
9699 selection
9700 },
9701 ));
9702
9703 // Move folds up
9704 unfold_ranges.push(range_to_move.clone());
9705 for fold in display_map.folds_in_range(
9706 buffer.anchor_before(range_to_move.start)
9707 ..buffer.anchor_after(range_to_move.end),
9708 ) {
9709 let mut start = fold.range.start.to_point(&buffer);
9710 let mut end = fold.range.end.to_point(&buffer);
9711 start.row -= row_delta;
9712 end.row -= row_delta;
9713 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9714 }
9715 }
9716 }
9717
9718 // If we didn't move line(s), preserve the existing selections
9719 new_selections.append(&mut contiguous_row_selections);
9720 }
9721
9722 self.transact(window, cx, |this, window, cx| {
9723 this.unfold_ranges(&unfold_ranges, true, true, cx);
9724 this.buffer.update(cx, |buffer, cx| {
9725 for (range, text) in edits {
9726 buffer.edit([(range, text)], None, cx);
9727 }
9728 });
9729 this.fold_creases(refold_creases, true, window, cx);
9730 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9731 s.select(new_selections);
9732 })
9733 });
9734 }
9735
9736 pub fn move_line_down(
9737 &mut self,
9738 _: &MoveLineDown,
9739 window: &mut Window,
9740 cx: &mut Context<Self>,
9741 ) {
9742 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9743
9744 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9745 let buffer = self.buffer.read(cx).snapshot(cx);
9746
9747 let mut edits = Vec::new();
9748 let mut unfold_ranges = Vec::new();
9749 let mut refold_creases = Vec::new();
9750
9751 let selections = self.selections.all::<Point>(cx);
9752 let mut selections = selections.iter().peekable();
9753 let mut contiguous_row_selections = Vec::new();
9754 let mut new_selections = Vec::new();
9755
9756 while let Some(selection) = selections.next() {
9757 // Find all the selections that span a contiguous row range
9758 let (start_row, end_row) = consume_contiguous_rows(
9759 &mut contiguous_row_selections,
9760 selection,
9761 &display_map,
9762 &mut selections,
9763 );
9764
9765 // Move the text spanned by the row range to be after the last line of the row range
9766 if end_row.0 <= buffer.max_point().row {
9767 let range_to_move =
9768 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9769 let insertion_point = display_map
9770 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9771 .0;
9772
9773 // Don't move lines across excerpt boundaries
9774 if buffer
9775 .excerpt_containing(range_to_move.start..insertion_point)
9776 .is_some()
9777 {
9778 let mut text = String::from("\n");
9779 text.extend(buffer.text_for_range(range_to_move.clone()));
9780 text.pop(); // Drop trailing newline
9781 edits.push((
9782 buffer.anchor_after(range_to_move.start)
9783 ..buffer.anchor_before(range_to_move.end),
9784 String::new(),
9785 ));
9786 let insertion_anchor = buffer.anchor_after(insertion_point);
9787 edits.push((insertion_anchor..insertion_anchor, text));
9788
9789 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9790
9791 // Move selections down
9792 new_selections.extend(contiguous_row_selections.drain(..).map(
9793 |mut selection| {
9794 selection.start.row += row_delta;
9795 selection.end.row += row_delta;
9796 selection
9797 },
9798 ));
9799
9800 // Move folds down
9801 unfold_ranges.push(range_to_move.clone());
9802 for fold in display_map.folds_in_range(
9803 buffer.anchor_before(range_to_move.start)
9804 ..buffer.anchor_after(range_to_move.end),
9805 ) {
9806 let mut start = fold.range.start.to_point(&buffer);
9807 let mut end = fold.range.end.to_point(&buffer);
9808 start.row += row_delta;
9809 end.row += row_delta;
9810 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9811 }
9812 }
9813 }
9814
9815 // If we didn't move line(s), preserve the existing selections
9816 new_selections.append(&mut contiguous_row_selections);
9817 }
9818
9819 self.transact(window, cx, |this, window, cx| {
9820 this.unfold_ranges(&unfold_ranges, true, true, cx);
9821 this.buffer.update(cx, |buffer, cx| {
9822 for (range, text) in edits {
9823 buffer.edit([(range, text)], None, cx);
9824 }
9825 });
9826 this.fold_creases(refold_creases, true, window, cx);
9827 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9828 s.select(new_selections)
9829 });
9830 });
9831 }
9832
9833 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9834 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9835 let text_layout_details = &self.text_layout_details(window);
9836 self.transact(window, cx, |this, window, cx| {
9837 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9838 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9839 s.move_with(|display_map, selection| {
9840 if !selection.is_empty() {
9841 return;
9842 }
9843
9844 let mut head = selection.head();
9845 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9846 if head.column() == display_map.line_len(head.row()) {
9847 transpose_offset = display_map
9848 .buffer_snapshot
9849 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9850 }
9851
9852 if transpose_offset == 0 {
9853 return;
9854 }
9855
9856 *head.column_mut() += 1;
9857 head = display_map.clip_point(head, Bias::Right);
9858 let goal = SelectionGoal::HorizontalPosition(
9859 display_map
9860 .x_for_display_point(head, text_layout_details)
9861 .into(),
9862 );
9863 selection.collapse_to(head, goal);
9864
9865 let transpose_start = display_map
9866 .buffer_snapshot
9867 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9868 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9869 let transpose_end = display_map
9870 .buffer_snapshot
9871 .clip_offset(transpose_offset + 1, Bias::Right);
9872 if let Some(ch) =
9873 display_map.buffer_snapshot.chars_at(transpose_start).next()
9874 {
9875 edits.push((transpose_start..transpose_offset, String::new()));
9876 edits.push((transpose_end..transpose_end, ch.to_string()));
9877 }
9878 }
9879 });
9880 edits
9881 });
9882 this.buffer
9883 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9884 let selections = this.selections.all::<usize>(cx);
9885 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9886 s.select(selections);
9887 });
9888 });
9889 }
9890
9891 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9892 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9893 self.rewrap_impl(RewrapOptions::default(), cx)
9894 }
9895
9896 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9897 let buffer = self.buffer.read(cx).snapshot(cx);
9898 let selections = self.selections.all::<Point>(cx);
9899 let mut selections = selections.iter().peekable();
9900
9901 let mut edits = Vec::new();
9902 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9903
9904 while let Some(selection) = selections.next() {
9905 let mut start_row = selection.start.row;
9906 let mut end_row = selection.end.row;
9907
9908 // Skip selections that overlap with a range that has already been rewrapped.
9909 let selection_range = start_row..end_row;
9910 if rewrapped_row_ranges
9911 .iter()
9912 .any(|range| range.overlaps(&selection_range))
9913 {
9914 continue;
9915 }
9916
9917 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9918
9919 // Since not all lines in the selection may be at the same indent
9920 // level, choose the indent size that is the most common between all
9921 // of the lines.
9922 //
9923 // If there is a tie, we use the deepest indent.
9924 let (indent_size, indent_end) = {
9925 let mut indent_size_occurrences = HashMap::default();
9926 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9927
9928 for row in start_row..=end_row {
9929 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9930 rows_by_indent_size.entry(indent).or_default().push(row);
9931 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9932 }
9933
9934 let indent_size = indent_size_occurrences
9935 .into_iter()
9936 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9937 .map(|(indent, _)| indent)
9938 .unwrap_or_default();
9939 let row = rows_by_indent_size[&indent_size][0];
9940 let indent_end = Point::new(row, indent_size.len);
9941
9942 (indent_size, indent_end)
9943 };
9944
9945 let mut line_prefix = indent_size.chars().collect::<String>();
9946
9947 let mut inside_comment = false;
9948 if let Some(comment_prefix) =
9949 buffer
9950 .language_scope_at(selection.head())
9951 .and_then(|language| {
9952 language
9953 .line_comment_prefixes()
9954 .iter()
9955 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9956 .cloned()
9957 })
9958 {
9959 line_prefix.push_str(&comment_prefix);
9960 inside_comment = true;
9961 }
9962
9963 let language_settings = buffer.language_settings_at(selection.head(), cx);
9964 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9965 RewrapBehavior::InComments => inside_comment,
9966 RewrapBehavior::InSelections => !selection.is_empty(),
9967 RewrapBehavior::Anywhere => true,
9968 };
9969
9970 let should_rewrap = options.override_language_settings
9971 || allow_rewrap_based_on_language
9972 || self.hard_wrap.is_some();
9973 if !should_rewrap {
9974 continue;
9975 }
9976
9977 if selection.is_empty() {
9978 'expand_upwards: while start_row > 0 {
9979 let prev_row = start_row - 1;
9980 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9981 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9982 {
9983 start_row = prev_row;
9984 } else {
9985 break 'expand_upwards;
9986 }
9987 }
9988
9989 'expand_downwards: while end_row < buffer.max_point().row {
9990 let next_row = end_row + 1;
9991 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9992 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9993 {
9994 end_row = next_row;
9995 } else {
9996 break 'expand_downwards;
9997 }
9998 }
9999 }
10000
10001 let start = Point::new(start_row, 0);
10002 let start_offset = start.to_offset(&buffer);
10003 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10004 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10005 let Some(lines_without_prefixes) = selection_text
10006 .lines()
10007 .map(|line| {
10008 line.strip_prefix(&line_prefix)
10009 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10010 .ok_or_else(|| {
10011 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10012 })
10013 })
10014 .collect::<Result<Vec<_>, _>>()
10015 .log_err()
10016 else {
10017 continue;
10018 };
10019
10020 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10021 buffer
10022 .language_settings_at(Point::new(start_row, 0), cx)
10023 .preferred_line_length as usize
10024 });
10025 let wrapped_text = wrap_with_prefix(
10026 line_prefix,
10027 lines_without_prefixes.join("\n"),
10028 wrap_column,
10029 tab_size,
10030 options.preserve_existing_whitespace,
10031 );
10032
10033 // TODO: should always use char-based diff while still supporting cursor behavior that
10034 // matches vim.
10035 let mut diff_options = DiffOptions::default();
10036 if options.override_language_settings {
10037 diff_options.max_word_diff_len = 0;
10038 diff_options.max_word_diff_line_count = 0;
10039 } else {
10040 diff_options.max_word_diff_len = usize::MAX;
10041 diff_options.max_word_diff_line_count = usize::MAX;
10042 }
10043
10044 for (old_range, new_text) in
10045 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10046 {
10047 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10048 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10049 edits.push((edit_start..edit_end, new_text));
10050 }
10051
10052 rewrapped_row_ranges.push(start_row..=end_row);
10053 }
10054
10055 self.buffer
10056 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10057 }
10058
10059 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10060 let mut text = String::new();
10061 let buffer = self.buffer.read(cx).snapshot(cx);
10062 let mut selections = self.selections.all::<Point>(cx);
10063 let mut clipboard_selections = Vec::with_capacity(selections.len());
10064 {
10065 let max_point = buffer.max_point();
10066 let mut is_first = true;
10067 for selection in &mut selections {
10068 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10069 if is_entire_line {
10070 selection.start = Point::new(selection.start.row, 0);
10071 if !selection.is_empty() && selection.end.column == 0 {
10072 selection.end = cmp::min(max_point, selection.end);
10073 } else {
10074 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10075 }
10076 selection.goal = SelectionGoal::None;
10077 }
10078 if is_first {
10079 is_first = false;
10080 } else {
10081 text += "\n";
10082 }
10083 let mut len = 0;
10084 for chunk in buffer.text_for_range(selection.start..selection.end) {
10085 text.push_str(chunk);
10086 len += chunk.len();
10087 }
10088 clipboard_selections.push(ClipboardSelection {
10089 len,
10090 is_entire_line,
10091 first_line_indent: buffer
10092 .indent_size_for_line(MultiBufferRow(selection.start.row))
10093 .len,
10094 });
10095 }
10096 }
10097
10098 self.transact(window, cx, |this, window, cx| {
10099 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10100 s.select(selections);
10101 });
10102 this.insert("", window, cx);
10103 });
10104 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10105 }
10106
10107 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10108 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10109 let item = self.cut_common(window, cx);
10110 cx.write_to_clipboard(item);
10111 }
10112
10113 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10114 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10115 self.change_selections(None, window, cx, |s| {
10116 s.move_with(|snapshot, sel| {
10117 if sel.is_empty() {
10118 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10119 }
10120 });
10121 });
10122 let item = self.cut_common(window, cx);
10123 cx.set_global(KillRing(item))
10124 }
10125
10126 pub fn kill_ring_yank(
10127 &mut self,
10128 _: &KillRingYank,
10129 window: &mut Window,
10130 cx: &mut Context<Self>,
10131 ) {
10132 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10133 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10134 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10135 (kill_ring.text().to_string(), kill_ring.metadata_json())
10136 } else {
10137 return;
10138 }
10139 } else {
10140 return;
10141 };
10142 self.do_paste(&text, metadata, false, window, cx);
10143 }
10144
10145 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10146 self.do_copy(true, cx);
10147 }
10148
10149 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10150 self.do_copy(false, cx);
10151 }
10152
10153 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10154 let selections = self.selections.all::<Point>(cx);
10155 let buffer = self.buffer.read(cx).read(cx);
10156 let mut text = String::new();
10157
10158 let mut clipboard_selections = Vec::with_capacity(selections.len());
10159 {
10160 let max_point = buffer.max_point();
10161 let mut is_first = true;
10162 for selection in &selections {
10163 let mut start = selection.start;
10164 let mut end = selection.end;
10165 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10166 if is_entire_line {
10167 start = Point::new(start.row, 0);
10168 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10169 }
10170
10171 let mut trimmed_selections = Vec::new();
10172 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10173 let row = MultiBufferRow(start.row);
10174 let first_indent = buffer.indent_size_for_line(row);
10175 if first_indent.len == 0 || start.column > first_indent.len {
10176 trimmed_selections.push(start..end);
10177 } else {
10178 trimmed_selections.push(
10179 Point::new(row.0, first_indent.len)
10180 ..Point::new(row.0, buffer.line_len(row)),
10181 );
10182 for row in start.row + 1..=end.row {
10183 let mut line_len = buffer.line_len(MultiBufferRow(row));
10184 if row == end.row {
10185 line_len = end.column;
10186 }
10187 if line_len == 0 {
10188 trimmed_selections
10189 .push(Point::new(row, 0)..Point::new(row, line_len));
10190 continue;
10191 }
10192 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10193 if row_indent_size.len >= first_indent.len {
10194 trimmed_selections.push(
10195 Point::new(row, first_indent.len)..Point::new(row, line_len),
10196 );
10197 } else {
10198 trimmed_selections.clear();
10199 trimmed_selections.push(start..end);
10200 break;
10201 }
10202 }
10203 }
10204 } else {
10205 trimmed_selections.push(start..end);
10206 }
10207
10208 for trimmed_range in trimmed_selections {
10209 if is_first {
10210 is_first = false;
10211 } else {
10212 text += "\n";
10213 }
10214 let mut len = 0;
10215 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10216 text.push_str(chunk);
10217 len += chunk.len();
10218 }
10219 clipboard_selections.push(ClipboardSelection {
10220 len,
10221 is_entire_line,
10222 first_line_indent: buffer
10223 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10224 .len,
10225 });
10226 }
10227 }
10228 }
10229
10230 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10231 text,
10232 clipboard_selections,
10233 ));
10234 }
10235
10236 pub fn do_paste(
10237 &mut self,
10238 text: &String,
10239 clipboard_selections: Option<Vec<ClipboardSelection>>,
10240 handle_entire_lines: bool,
10241 window: &mut Window,
10242 cx: &mut Context<Self>,
10243 ) {
10244 if self.read_only(cx) {
10245 return;
10246 }
10247
10248 let clipboard_text = Cow::Borrowed(text);
10249
10250 self.transact(window, cx, |this, window, cx| {
10251 if let Some(mut clipboard_selections) = clipboard_selections {
10252 let old_selections = this.selections.all::<usize>(cx);
10253 let all_selections_were_entire_line =
10254 clipboard_selections.iter().all(|s| s.is_entire_line);
10255 let first_selection_indent_column =
10256 clipboard_selections.first().map(|s| s.first_line_indent);
10257 if clipboard_selections.len() != old_selections.len() {
10258 clipboard_selections.drain(..);
10259 }
10260 let cursor_offset = this.selections.last::<usize>(cx).head();
10261 let mut auto_indent_on_paste = true;
10262
10263 this.buffer.update(cx, |buffer, cx| {
10264 let snapshot = buffer.read(cx);
10265 auto_indent_on_paste = snapshot
10266 .language_settings_at(cursor_offset, cx)
10267 .auto_indent_on_paste;
10268
10269 let mut start_offset = 0;
10270 let mut edits = Vec::new();
10271 let mut original_indent_columns = Vec::new();
10272 for (ix, selection) in old_selections.iter().enumerate() {
10273 let to_insert;
10274 let entire_line;
10275 let original_indent_column;
10276 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10277 let end_offset = start_offset + clipboard_selection.len;
10278 to_insert = &clipboard_text[start_offset..end_offset];
10279 entire_line = clipboard_selection.is_entire_line;
10280 start_offset = end_offset + 1;
10281 original_indent_column = Some(clipboard_selection.first_line_indent);
10282 } else {
10283 to_insert = clipboard_text.as_str();
10284 entire_line = all_selections_were_entire_line;
10285 original_indent_column = first_selection_indent_column
10286 }
10287
10288 // If the corresponding selection was empty when this slice of the
10289 // clipboard text was written, then the entire line containing the
10290 // selection was copied. If this selection is also currently empty,
10291 // then paste the line before the current line of the buffer.
10292 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10293 let column = selection.start.to_point(&snapshot).column as usize;
10294 let line_start = selection.start - column;
10295 line_start..line_start
10296 } else {
10297 selection.range()
10298 };
10299
10300 edits.push((range, to_insert));
10301 original_indent_columns.push(original_indent_column);
10302 }
10303 drop(snapshot);
10304
10305 buffer.edit(
10306 edits,
10307 if auto_indent_on_paste {
10308 Some(AutoindentMode::Block {
10309 original_indent_columns,
10310 })
10311 } else {
10312 None
10313 },
10314 cx,
10315 );
10316 });
10317
10318 let selections = this.selections.all::<usize>(cx);
10319 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10320 s.select(selections)
10321 });
10322 } else {
10323 this.insert(&clipboard_text, window, cx);
10324 }
10325 });
10326 }
10327
10328 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10329 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10330 if let Some(item) = cx.read_from_clipboard() {
10331 let entries = item.entries();
10332
10333 match entries.first() {
10334 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10335 // of all the pasted entries.
10336 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10337 .do_paste(
10338 clipboard_string.text(),
10339 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10340 true,
10341 window,
10342 cx,
10343 ),
10344 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10345 }
10346 }
10347 }
10348
10349 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10350 if self.read_only(cx) {
10351 return;
10352 }
10353
10354 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10355
10356 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10357 if let Some((selections, _)) =
10358 self.selection_history.transaction(transaction_id).cloned()
10359 {
10360 self.change_selections(None, window, cx, |s| {
10361 s.select_anchors(selections.to_vec());
10362 });
10363 } else {
10364 log::error!(
10365 "No entry in selection_history found for undo. \
10366 This may correspond to a bug where undo does not update the selection. \
10367 If this is occurring, please add details to \
10368 https://github.com/zed-industries/zed/issues/22692"
10369 );
10370 }
10371 self.request_autoscroll(Autoscroll::fit(), cx);
10372 self.unmark_text(window, cx);
10373 self.refresh_inline_completion(true, false, window, cx);
10374 cx.emit(EditorEvent::Edited { transaction_id });
10375 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10376 }
10377 }
10378
10379 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10380 if self.read_only(cx) {
10381 return;
10382 }
10383
10384 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10385
10386 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10387 if let Some((_, Some(selections))) =
10388 self.selection_history.transaction(transaction_id).cloned()
10389 {
10390 self.change_selections(None, window, cx, |s| {
10391 s.select_anchors(selections.to_vec());
10392 });
10393 } else {
10394 log::error!(
10395 "No entry in selection_history found for redo. \
10396 This may correspond to a bug where undo does not update the selection. \
10397 If this is occurring, please add details to \
10398 https://github.com/zed-industries/zed/issues/22692"
10399 );
10400 }
10401 self.request_autoscroll(Autoscroll::fit(), cx);
10402 self.unmark_text(window, cx);
10403 self.refresh_inline_completion(true, false, window, cx);
10404 cx.emit(EditorEvent::Edited { transaction_id });
10405 }
10406 }
10407
10408 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10409 self.buffer
10410 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10411 }
10412
10413 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10414 self.buffer
10415 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10416 }
10417
10418 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10419 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10420 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10421 s.move_with(|map, selection| {
10422 let cursor = if selection.is_empty() {
10423 movement::left(map, selection.start)
10424 } else {
10425 selection.start
10426 };
10427 selection.collapse_to(cursor, SelectionGoal::None);
10428 });
10429 })
10430 }
10431
10432 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10433 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10434 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10435 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10436 })
10437 }
10438
10439 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10440 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10441 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10442 s.move_with(|map, selection| {
10443 let cursor = if selection.is_empty() {
10444 movement::right(map, selection.end)
10445 } else {
10446 selection.end
10447 };
10448 selection.collapse_to(cursor, SelectionGoal::None)
10449 });
10450 })
10451 }
10452
10453 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10454 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10455 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10456 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10457 })
10458 }
10459
10460 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10461 if self.take_rename(true, window, cx).is_some() {
10462 return;
10463 }
10464
10465 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10466 cx.propagate();
10467 return;
10468 }
10469
10470 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10471
10472 let text_layout_details = &self.text_layout_details(window);
10473 let selection_count = self.selections.count();
10474 let first_selection = self.selections.first_anchor();
10475
10476 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10477 s.move_with(|map, selection| {
10478 if !selection.is_empty() {
10479 selection.goal = SelectionGoal::None;
10480 }
10481 let (cursor, goal) = movement::up(
10482 map,
10483 selection.start,
10484 selection.goal,
10485 false,
10486 text_layout_details,
10487 );
10488 selection.collapse_to(cursor, goal);
10489 });
10490 });
10491
10492 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10493 {
10494 cx.propagate();
10495 }
10496 }
10497
10498 pub fn move_up_by_lines(
10499 &mut self,
10500 action: &MoveUpByLines,
10501 window: &mut Window,
10502 cx: &mut Context<Self>,
10503 ) {
10504 if self.take_rename(true, window, cx).is_some() {
10505 return;
10506 }
10507
10508 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10509 cx.propagate();
10510 return;
10511 }
10512
10513 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10514
10515 let text_layout_details = &self.text_layout_details(window);
10516
10517 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10518 s.move_with(|map, selection| {
10519 if !selection.is_empty() {
10520 selection.goal = SelectionGoal::None;
10521 }
10522 let (cursor, goal) = movement::up_by_rows(
10523 map,
10524 selection.start,
10525 action.lines,
10526 selection.goal,
10527 false,
10528 text_layout_details,
10529 );
10530 selection.collapse_to(cursor, goal);
10531 });
10532 })
10533 }
10534
10535 pub fn move_down_by_lines(
10536 &mut self,
10537 action: &MoveDownByLines,
10538 window: &mut Window,
10539 cx: &mut Context<Self>,
10540 ) {
10541 if self.take_rename(true, window, cx).is_some() {
10542 return;
10543 }
10544
10545 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10546 cx.propagate();
10547 return;
10548 }
10549
10550 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10551
10552 let text_layout_details = &self.text_layout_details(window);
10553
10554 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10555 s.move_with(|map, selection| {
10556 if !selection.is_empty() {
10557 selection.goal = SelectionGoal::None;
10558 }
10559 let (cursor, goal) = movement::down_by_rows(
10560 map,
10561 selection.start,
10562 action.lines,
10563 selection.goal,
10564 false,
10565 text_layout_details,
10566 );
10567 selection.collapse_to(cursor, goal);
10568 });
10569 })
10570 }
10571
10572 pub fn select_down_by_lines(
10573 &mut self,
10574 action: &SelectDownByLines,
10575 window: &mut Window,
10576 cx: &mut Context<Self>,
10577 ) {
10578 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10579 let text_layout_details = &self.text_layout_details(window);
10580 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10581 s.move_heads_with(|map, head, goal| {
10582 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10583 })
10584 })
10585 }
10586
10587 pub fn select_up_by_lines(
10588 &mut self,
10589 action: &SelectUpByLines,
10590 window: &mut Window,
10591 cx: &mut Context<Self>,
10592 ) {
10593 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10594 let text_layout_details = &self.text_layout_details(window);
10595 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10596 s.move_heads_with(|map, head, goal| {
10597 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10598 })
10599 })
10600 }
10601
10602 pub fn select_page_up(
10603 &mut self,
10604 _: &SelectPageUp,
10605 window: &mut Window,
10606 cx: &mut Context<Self>,
10607 ) {
10608 let Some(row_count) = self.visible_row_count() else {
10609 return;
10610 };
10611
10612 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10613
10614 let text_layout_details = &self.text_layout_details(window);
10615
10616 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10617 s.move_heads_with(|map, head, goal| {
10618 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10619 })
10620 })
10621 }
10622
10623 pub fn move_page_up(
10624 &mut self,
10625 action: &MovePageUp,
10626 window: &mut Window,
10627 cx: &mut Context<Self>,
10628 ) {
10629 if self.take_rename(true, window, cx).is_some() {
10630 return;
10631 }
10632
10633 if self
10634 .context_menu
10635 .borrow_mut()
10636 .as_mut()
10637 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10638 .unwrap_or(false)
10639 {
10640 return;
10641 }
10642
10643 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10644 cx.propagate();
10645 return;
10646 }
10647
10648 let Some(row_count) = self.visible_row_count() else {
10649 return;
10650 };
10651
10652 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10653
10654 let autoscroll = if action.center_cursor {
10655 Autoscroll::center()
10656 } else {
10657 Autoscroll::fit()
10658 };
10659
10660 let text_layout_details = &self.text_layout_details(window);
10661
10662 self.change_selections(Some(autoscroll), window, cx, |s| {
10663 s.move_with(|map, selection| {
10664 if !selection.is_empty() {
10665 selection.goal = SelectionGoal::None;
10666 }
10667 let (cursor, goal) = movement::up_by_rows(
10668 map,
10669 selection.end,
10670 row_count,
10671 selection.goal,
10672 false,
10673 text_layout_details,
10674 );
10675 selection.collapse_to(cursor, goal);
10676 });
10677 });
10678 }
10679
10680 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10681 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10682 let text_layout_details = &self.text_layout_details(window);
10683 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10684 s.move_heads_with(|map, head, goal| {
10685 movement::up(map, head, goal, false, text_layout_details)
10686 })
10687 })
10688 }
10689
10690 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10691 self.take_rename(true, window, cx);
10692
10693 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10694 cx.propagate();
10695 return;
10696 }
10697
10698 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10699
10700 let text_layout_details = &self.text_layout_details(window);
10701 let selection_count = self.selections.count();
10702 let first_selection = self.selections.first_anchor();
10703
10704 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10705 s.move_with(|map, selection| {
10706 if !selection.is_empty() {
10707 selection.goal = SelectionGoal::None;
10708 }
10709 let (cursor, goal) = movement::down(
10710 map,
10711 selection.end,
10712 selection.goal,
10713 false,
10714 text_layout_details,
10715 );
10716 selection.collapse_to(cursor, goal);
10717 });
10718 });
10719
10720 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10721 {
10722 cx.propagate();
10723 }
10724 }
10725
10726 pub fn select_page_down(
10727 &mut self,
10728 _: &SelectPageDown,
10729 window: &mut Window,
10730 cx: &mut Context<Self>,
10731 ) {
10732 let Some(row_count) = self.visible_row_count() else {
10733 return;
10734 };
10735
10736 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10737
10738 let text_layout_details = &self.text_layout_details(window);
10739
10740 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10741 s.move_heads_with(|map, head, goal| {
10742 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10743 })
10744 })
10745 }
10746
10747 pub fn move_page_down(
10748 &mut self,
10749 action: &MovePageDown,
10750 window: &mut Window,
10751 cx: &mut Context<Self>,
10752 ) {
10753 if self.take_rename(true, window, cx).is_some() {
10754 return;
10755 }
10756
10757 if self
10758 .context_menu
10759 .borrow_mut()
10760 .as_mut()
10761 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10762 .unwrap_or(false)
10763 {
10764 return;
10765 }
10766
10767 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10768 cx.propagate();
10769 return;
10770 }
10771
10772 let Some(row_count) = self.visible_row_count() else {
10773 return;
10774 };
10775
10776 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10777
10778 let autoscroll = if action.center_cursor {
10779 Autoscroll::center()
10780 } else {
10781 Autoscroll::fit()
10782 };
10783
10784 let text_layout_details = &self.text_layout_details(window);
10785 self.change_selections(Some(autoscroll), window, cx, |s| {
10786 s.move_with(|map, selection| {
10787 if !selection.is_empty() {
10788 selection.goal = SelectionGoal::None;
10789 }
10790 let (cursor, goal) = movement::down_by_rows(
10791 map,
10792 selection.end,
10793 row_count,
10794 selection.goal,
10795 false,
10796 text_layout_details,
10797 );
10798 selection.collapse_to(cursor, goal);
10799 });
10800 });
10801 }
10802
10803 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10804 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10805 let text_layout_details = &self.text_layout_details(window);
10806 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10807 s.move_heads_with(|map, head, goal| {
10808 movement::down(map, head, goal, false, text_layout_details)
10809 })
10810 });
10811 }
10812
10813 pub fn context_menu_first(
10814 &mut self,
10815 _: &ContextMenuFirst,
10816 _window: &mut Window,
10817 cx: &mut Context<Self>,
10818 ) {
10819 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10820 context_menu.select_first(self.completion_provider.as_deref(), cx);
10821 }
10822 }
10823
10824 pub fn context_menu_prev(
10825 &mut self,
10826 _: &ContextMenuPrevious,
10827 _window: &mut Window,
10828 cx: &mut Context<Self>,
10829 ) {
10830 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10831 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10832 }
10833 }
10834
10835 pub fn context_menu_next(
10836 &mut self,
10837 _: &ContextMenuNext,
10838 _window: &mut Window,
10839 cx: &mut Context<Self>,
10840 ) {
10841 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10842 context_menu.select_next(self.completion_provider.as_deref(), cx);
10843 }
10844 }
10845
10846 pub fn context_menu_last(
10847 &mut self,
10848 _: &ContextMenuLast,
10849 _window: &mut Window,
10850 cx: &mut Context<Self>,
10851 ) {
10852 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10853 context_menu.select_last(self.completion_provider.as_deref(), cx);
10854 }
10855 }
10856
10857 pub fn move_to_previous_word_start(
10858 &mut self,
10859 _: &MoveToPreviousWordStart,
10860 window: &mut Window,
10861 cx: &mut Context<Self>,
10862 ) {
10863 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10864 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10865 s.move_cursors_with(|map, head, _| {
10866 (
10867 movement::previous_word_start(map, head),
10868 SelectionGoal::None,
10869 )
10870 });
10871 })
10872 }
10873
10874 pub fn move_to_previous_subword_start(
10875 &mut self,
10876 _: &MoveToPreviousSubwordStart,
10877 window: &mut Window,
10878 cx: &mut Context<Self>,
10879 ) {
10880 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10881 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10882 s.move_cursors_with(|map, head, _| {
10883 (
10884 movement::previous_subword_start(map, head),
10885 SelectionGoal::None,
10886 )
10887 });
10888 })
10889 }
10890
10891 pub fn select_to_previous_word_start(
10892 &mut self,
10893 _: &SelectToPreviousWordStart,
10894 window: &mut Window,
10895 cx: &mut Context<Self>,
10896 ) {
10897 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10898 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10899 s.move_heads_with(|map, head, _| {
10900 (
10901 movement::previous_word_start(map, head),
10902 SelectionGoal::None,
10903 )
10904 });
10905 })
10906 }
10907
10908 pub fn select_to_previous_subword_start(
10909 &mut self,
10910 _: &SelectToPreviousSubwordStart,
10911 window: &mut Window,
10912 cx: &mut Context<Self>,
10913 ) {
10914 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10915 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10916 s.move_heads_with(|map, head, _| {
10917 (
10918 movement::previous_subword_start(map, head),
10919 SelectionGoal::None,
10920 )
10921 });
10922 })
10923 }
10924
10925 pub fn delete_to_previous_word_start(
10926 &mut self,
10927 action: &DeleteToPreviousWordStart,
10928 window: &mut Window,
10929 cx: &mut Context<Self>,
10930 ) {
10931 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10932 self.transact(window, cx, |this, window, cx| {
10933 this.select_autoclose_pair(window, cx);
10934 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10935 s.move_with(|map, selection| {
10936 if selection.is_empty() {
10937 let cursor = if action.ignore_newlines {
10938 movement::previous_word_start(map, selection.head())
10939 } else {
10940 movement::previous_word_start_or_newline(map, selection.head())
10941 };
10942 selection.set_head(cursor, SelectionGoal::None);
10943 }
10944 });
10945 });
10946 this.insert("", window, cx);
10947 });
10948 }
10949
10950 pub fn delete_to_previous_subword_start(
10951 &mut self,
10952 _: &DeleteToPreviousSubwordStart,
10953 window: &mut Window,
10954 cx: &mut Context<Self>,
10955 ) {
10956 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10957 self.transact(window, cx, |this, window, cx| {
10958 this.select_autoclose_pair(window, cx);
10959 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10960 s.move_with(|map, selection| {
10961 if selection.is_empty() {
10962 let cursor = movement::previous_subword_start(map, selection.head());
10963 selection.set_head(cursor, SelectionGoal::None);
10964 }
10965 });
10966 });
10967 this.insert("", window, cx);
10968 });
10969 }
10970
10971 pub fn move_to_next_word_end(
10972 &mut self,
10973 _: &MoveToNextWordEnd,
10974 window: &mut Window,
10975 cx: &mut Context<Self>,
10976 ) {
10977 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10978 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10979 s.move_cursors_with(|map, head, _| {
10980 (movement::next_word_end(map, head), SelectionGoal::None)
10981 });
10982 })
10983 }
10984
10985 pub fn move_to_next_subword_end(
10986 &mut self,
10987 _: &MoveToNextSubwordEnd,
10988 window: &mut Window,
10989 cx: &mut Context<Self>,
10990 ) {
10991 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10992 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10993 s.move_cursors_with(|map, head, _| {
10994 (movement::next_subword_end(map, head), SelectionGoal::None)
10995 });
10996 })
10997 }
10998
10999 pub fn select_to_next_word_end(
11000 &mut self,
11001 _: &SelectToNextWordEnd,
11002 window: &mut Window,
11003 cx: &mut Context<Self>,
11004 ) {
11005 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11006 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11007 s.move_heads_with(|map, head, _| {
11008 (movement::next_word_end(map, head), SelectionGoal::None)
11009 });
11010 })
11011 }
11012
11013 pub fn select_to_next_subword_end(
11014 &mut self,
11015 _: &SelectToNextSubwordEnd,
11016 window: &mut Window,
11017 cx: &mut Context<Self>,
11018 ) {
11019 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11020 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11021 s.move_heads_with(|map, head, _| {
11022 (movement::next_subword_end(map, head), SelectionGoal::None)
11023 });
11024 })
11025 }
11026
11027 pub fn delete_to_next_word_end(
11028 &mut self,
11029 action: &DeleteToNextWordEnd,
11030 window: &mut Window,
11031 cx: &mut Context<Self>,
11032 ) {
11033 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11034 self.transact(window, cx, |this, window, cx| {
11035 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11036 s.move_with(|map, selection| {
11037 if selection.is_empty() {
11038 let cursor = if action.ignore_newlines {
11039 movement::next_word_end(map, selection.head())
11040 } else {
11041 movement::next_word_end_or_newline(map, selection.head())
11042 };
11043 selection.set_head(cursor, SelectionGoal::None);
11044 }
11045 });
11046 });
11047 this.insert("", window, cx);
11048 });
11049 }
11050
11051 pub fn delete_to_next_subword_end(
11052 &mut self,
11053 _: &DeleteToNextSubwordEnd,
11054 window: &mut Window,
11055 cx: &mut Context<Self>,
11056 ) {
11057 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11058 self.transact(window, cx, |this, window, cx| {
11059 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11060 s.move_with(|map, selection| {
11061 if selection.is_empty() {
11062 let cursor = movement::next_subword_end(map, selection.head());
11063 selection.set_head(cursor, SelectionGoal::None);
11064 }
11065 });
11066 });
11067 this.insert("", window, cx);
11068 });
11069 }
11070
11071 pub fn move_to_beginning_of_line(
11072 &mut self,
11073 action: &MoveToBeginningOfLine,
11074 window: &mut Window,
11075 cx: &mut Context<Self>,
11076 ) {
11077 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11078 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11079 s.move_cursors_with(|map, head, _| {
11080 (
11081 movement::indented_line_beginning(
11082 map,
11083 head,
11084 action.stop_at_soft_wraps,
11085 action.stop_at_indent,
11086 ),
11087 SelectionGoal::None,
11088 )
11089 });
11090 })
11091 }
11092
11093 pub fn select_to_beginning_of_line(
11094 &mut self,
11095 action: &SelectToBeginningOfLine,
11096 window: &mut Window,
11097 cx: &mut Context<Self>,
11098 ) {
11099 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11100 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11101 s.move_heads_with(|map, head, _| {
11102 (
11103 movement::indented_line_beginning(
11104 map,
11105 head,
11106 action.stop_at_soft_wraps,
11107 action.stop_at_indent,
11108 ),
11109 SelectionGoal::None,
11110 )
11111 });
11112 });
11113 }
11114
11115 pub fn delete_to_beginning_of_line(
11116 &mut self,
11117 action: &DeleteToBeginningOfLine,
11118 window: &mut Window,
11119 cx: &mut Context<Self>,
11120 ) {
11121 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11122 self.transact(window, cx, |this, window, cx| {
11123 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11124 s.move_with(|_, selection| {
11125 selection.reversed = true;
11126 });
11127 });
11128
11129 this.select_to_beginning_of_line(
11130 &SelectToBeginningOfLine {
11131 stop_at_soft_wraps: false,
11132 stop_at_indent: action.stop_at_indent,
11133 },
11134 window,
11135 cx,
11136 );
11137 this.backspace(&Backspace, window, cx);
11138 });
11139 }
11140
11141 pub fn move_to_end_of_line(
11142 &mut self,
11143 action: &MoveToEndOfLine,
11144 window: &mut Window,
11145 cx: &mut Context<Self>,
11146 ) {
11147 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11148 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11149 s.move_cursors_with(|map, head, _| {
11150 (
11151 movement::line_end(map, head, action.stop_at_soft_wraps),
11152 SelectionGoal::None,
11153 )
11154 });
11155 })
11156 }
11157
11158 pub fn select_to_end_of_line(
11159 &mut self,
11160 action: &SelectToEndOfLine,
11161 window: &mut Window,
11162 cx: &mut Context<Self>,
11163 ) {
11164 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11165 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11166 s.move_heads_with(|map, head, _| {
11167 (
11168 movement::line_end(map, head, action.stop_at_soft_wraps),
11169 SelectionGoal::None,
11170 )
11171 });
11172 })
11173 }
11174
11175 pub fn delete_to_end_of_line(
11176 &mut self,
11177 _: &DeleteToEndOfLine,
11178 window: &mut Window,
11179 cx: &mut Context<Self>,
11180 ) {
11181 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11182 self.transact(window, cx, |this, window, cx| {
11183 this.select_to_end_of_line(
11184 &SelectToEndOfLine {
11185 stop_at_soft_wraps: false,
11186 },
11187 window,
11188 cx,
11189 );
11190 this.delete(&Delete, window, cx);
11191 });
11192 }
11193
11194 pub fn cut_to_end_of_line(
11195 &mut self,
11196 _: &CutToEndOfLine,
11197 window: &mut Window,
11198 cx: &mut Context<Self>,
11199 ) {
11200 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11201 self.transact(window, cx, |this, window, cx| {
11202 this.select_to_end_of_line(
11203 &SelectToEndOfLine {
11204 stop_at_soft_wraps: false,
11205 },
11206 window,
11207 cx,
11208 );
11209 this.cut(&Cut, window, cx);
11210 });
11211 }
11212
11213 pub fn move_to_start_of_paragraph(
11214 &mut self,
11215 _: &MoveToStartOfParagraph,
11216 window: &mut Window,
11217 cx: &mut Context<Self>,
11218 ) {
11219 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11220 cx.propagate();
11221 return;
11222 }
11223 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11224 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11225 s.move_with(|map, selection| {
11226 selection.collapse_to(
11227 movement::start_of_paragraph(map, selection.head(), 1),
11228 SelectionGoal::None,
11229 )
11230 });
11231 })
11232 }
11233
11234 pub fn move_to_end_of_paragraph(
11235 &mut self,
11236 _: &MoveToEndOfParagraph,
11237 window: &mut Window,
11238 cx: &mut Context<Self>,
11239 ) {
11240 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11241 cx.propagate();
11242 return;
11243 }
11244 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11245 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11246 s.move_with(|map, selection| {
11247 selection.collapse_to(
11248 movement::end_of_paragraph(map, selection.head(), 1),
11249 SelectionGoal::None,
11250 )
11251 });
11252 })
11253 }
11254
11255 pub fn select_to_start_of_paragraph(
11256 &mut self,
11257 _: &SelectToStartOfParagraph,
11258 window: &mut Window,
11259 cx: &mut Context<Self>,
11260 ) {
11261 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11262 cx.propagate();
11263 return;
11264 }
11265 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11266 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11267 s.move_heads_with(|map, head, _| {
11268 (
11269 movement::start_of_paragraph(map, head, 1),
11270 SelectionGoal::None,
11271 )
11272 });
11273 })
11274 }
11275
11276 pub fn select_to_end_of_paragraph(
11277 &mut self,
11278 _: &SelectToEndOfParagraph,
11279 window: &mut Window,
11280 cx: &mut Context<Self>,
11281 ) {
11282 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11283 cx.propagate();
11284 return;
11285 }
11286 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11287 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11288 s.move_heads_with(|map, head, _| {
11289 (
11290 movement::end_of_paragraph(map, head, 1),
11291 SelectionGoal::None,
11292 )
11293 });
11294 })
11295 }
11296
11297 pub fn move_to_start_of_excerpt(
11298 &mut self,
11299 _: &MoveToStartOfExcerpt,
11300 window: &mut Window,
11301 cx: &mut Context<Self>,
11302 ) {
11303 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11304 cx.propagate();
11305 return;
11306 }
11307 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11308 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11309 s.move_with(|map, selection| {
11310 selection.collapse_to(
11311 movement::start_of_excerpt(
11312 map,
11313 selection.head(),
11314 workspace::searchable::Direction::Prev,
11315 ),
11316 SelectionGoal::None,
11317 )
11318 });
11319 })
11320 }
11321
11322 pub fn move_to_start_of_next_excerpt(
11323 &mut self,
11324 _: &MoveToStartOfNextExcerpt,
11325 window: &mut Window,
11326 cx: &mut Context<Self>,
11327 ) {
11328 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11329 cx.propagate();
11330 return;
11331 }
11332
11333 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11334 s.move_with(|map, selection| {
11335 selection.collapse_to(
11336 movement::start_of_excerpt(
11337 map,
11338 selection.head(),
11339 workspace::searchable::Direction::Next,
11340 ),
11341 SelectionGoal::None,
11342 )
11343 });
11344 })
11345 }
11346
11347 pub fn move_to_end_of_excerpt(
11348 &mut self,
11349 _: &MoveToEndOfExcerpt,
11350 window: &mut Window,
11351 cx: &mut Context<Self>,
11352 ) {
11353 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11354 cx.propagate();
11355 return;
11356 }
11357 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11358 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11359 s.move_with(|map, selection| {
11360 selection.collapse_to(
11361 movement::end_of_excerpt(
11362 map,
11363 selection.head(),
11364 workspace::searchable::Direction::Next,
11365 ),
11366 SelectionGoal::None,
11367 )
11368 });
11369 })
11370 }
11371
11372 pub fn move_to_end_of_previous_excerpt(
11373 &mut self,
11374 _: &MoveToEndOfPreviousExcerpt,
11375 window: &mut Window,
11376 cx: &mut Context<Self>,
11377 ) {
11378 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11379 cx.propagate();
11380 return;
11381 }
11382 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11383 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11384 s.move_with(|map, selection| {
11385 selection.collapse_to(
11386 movement::end_of_excerpt(
11387 map,
11388 selection.head(),
11389 workspace::searchable::Direction::Prev,
11390 ),
11391 SelectionGoal::None,
11392 )
11393 });
11394 })
11395 }
11396
11397 pub fn select_to_start_of_excerpt(
11398 &mut self,
11399 _: &SelectToStartOfExcerpt,
11400 window: &mut Window,
11401 cx: &mut Context<Self>,
11402 ) {
11403 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11404 cx.propagate();
11405 return;
11406 }
11407 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11408 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11409 s.move_heads_with(|map, head, _| {
11410 (
11411 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11412 SelectionGoal::None,
11413 )
11414 });
11415 })
11416 }
11417
11418 pub fn select_to_start_of_next_excerpt(
11419 &mut self,
11420 _: &SelectToStartOfNextExcerpt,
11421 window: &mut Window,
11422 cx: &mut Context<Self>,
11423 ) {
11424 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11425 cx.propagate();
11426 return;
11427 }
11428 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11429 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11430 s.move_heads_with(|map, head, _| {
11431 (
11432 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11433 SelectionGoal::None,
11434 )
11435 });
11436 })
11437 }
11438
11439 pub fn select_to_end_of_excerpt(
11440 &mut self,
11441 _: &SelectToEndOfExcerpt,
11442 window: &mut Window,
11443 cx: &mut Context<Self>,
11444 ) {
11445 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11446 cx.propagate();
11447 return;
11448 }
11449 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11450 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11451 s.move_heads_with(|map, head, _| {
11452 (
11453 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11454 SelectionGoal::None,
11455 )
11456 });
11457 })
11458 }
11459
11460 pub fn select_to_end_of_previous_excerpt(
11461 &mut self,
11462 _: &SelectToEndOfPreviousExcerpt,
11463 window: &mut Window,
11464 cx: &mut Context<Self>,
11465 ) {
11466 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11467 cx.propagate();
11468 return;
11469 }
11470 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11471 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11472 s.move_heads_with(|map, head, _| {
11473 (
11474 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11475 SelectionGoal::None,
11476 )
11477 });
11478 })
11479 }
11480
11481 pub fn move_to_beginning(
11482 &mut self,
11483 _: &MoveToBeginning,
11484 window: &mut Window,
11485 cx: &mut Context<Self>,
11486 ) {
11487 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11488 cx.propagate();
11489 return;
11490 }
11491 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11492 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11493 s.select_ranges(vec![0..0]);
11494 });
11495 }
11496
11497 pub fn select_to_beginning(
11498 &mut self,
11499 _: &SelectToBeginning,
11500 window: &mut Window,
11501 cx: &mut Context<Self>,
11502 ) {
11503 let mut selection = self.selections.last::<Point>(cx);
11504 selection.set_head(Point::zero(), SelectionGoal::None);
11505 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11506 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11507 s.select(vec![selection]);
11508 });
11509 }
11510
11511 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11512 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11513 cx.propagate();
11514 return;
11515 }
11516 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11517 let cursor = self.buffer.read(cx).read(cx).len();
11518 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11519 s.select_ranges(vec![cursor..cursor])
11520 });
11521 }
11522
11523 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11524 self.nav_history = nav_history;
11525 }
11526
11527 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11528 self.nav_history.as_ref()
11529 }
11530
11531 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11532 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11533 }
11534
11535 fn push_to_nav_history(
11536 &mut self,
11537 cursor_anchor: Anchor,
11538 new_position: Option<Point>,
11539 is_deactivate: bool,
11540 cx: &mut Context<Self>,
11541 ) {
11542 if let Some(nav_history) = self.nav_history.as_mut() {
11543 let buffer = self.buffer.read(cx).read(cx);
11544 let cursor_position = cursor_anchor.to_point(&buffer);
11545 let scroll_state = self.scroll_manager.anchor();
11546 let scroll_top_row = scroll_state.top_row(&buffer);
11547 drop(buffer);
11548
11549 if let Some(new_position) = new_position {
11550 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11551 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11552 return;
11553 }
11554 }
11555
11556 nav_history.push(
11557 Some(NavigationData {
11558 cursor_anchor,
11559 cursor_position,
11560 scroll_anchor: scroll_state,
11561 scroll_top_row,
11562 }),
11563 cx,
11564 );
11565 cx.emit(EditorEvent::PushedToNavHistory {
11566 anchor: cursor_anchor,
11567 is_deactivate,
11568 })
11569 }
11570 }
11571
11572 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11573 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11574 let buffer = self.buffer.read(cx).snapshot(cx);
11575 let mut selection = self.selections.first::<usize>(cx);
11576 selection.set_head(buffer.len(), SelectionGoal::None);
11577 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11578 s.select(vec![selection]);
11579 });
11580 }
11581
11582 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11583 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11584 let end = self.buffer.read(cx).read(cx).len();
11585 self.change_selections(None, window, cx, |s| {
11586 s.select_ranges(vec![0..end]);
11587 });
11588 }
11589
11590 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11591 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11592 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11593 let mut selections = self.selections.all::<Point>(cx);
11594 let max_point = display_map.buffer_snapshot.max_point();
11595 for selection in &mut selections {
11596 let rows = selection.spanned_rows(true, &display_map);
11597 selection.start = Point::new(rows.start.0, 0);
11598 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11599 selection.reversed = false;
11600 }
11601 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11602 s.select(selections);
11603 });
11604 }
11605
11606 pub fn split_selection_into_lines(
11607 &mut self,
11608 _: &SplitSelectionIntoLines,
11609 window: &mut Window,
11610 cx: &mut Context<Self>,
11611 ) {
11612 let selections = self
11613 .selections
11614 .all::<Point>(cx)
11615 .into_iter()
11616 .map(|selection| selection.start..selection.end)
11617 .collect::<Vec<_>>();
11618 self.unfold_ranges(&selections, true, true, cx);
11619
11620 let mut new_selection_ranges = Vec::new();
11621 {
11622 let buffer = self.buffer.read(cx).read(cx);
11623 for selection in selections {
11624 for row in selection.start.row..selection.end.row {
11625 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11626 new_selection_ranges.push(cursor..cursor);
11627 }
11628
11629 let is_multiline_selection = selection.start.row != selection.end.row;
11630 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11631 // so this action feels more ergonomic when paired with other selection operations
11632 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11633 if !should_skip_last {
11634 new_selection_ranges.push(selection.end..selection.end);
11635 }
11636 }
11637 }
11638 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11639 s.select_ranges(new_selection_ranges);
11640 });
11641 }
11642
11643 pub fn add_selection_above(
11644 &mut self,
11645 _: &AddSelectionAbove,
11646 window: &mut Window,
11647 cx: &mut Context<Self>,
11648 ) {
11649 self.add_selection(true, window, cx);
11650 }
11651
11652 pub fn add_selection_below(
11653 &mut self,
11654 _: &AddSelectionBelow,
11655 window: &mut Window,
11656 cx: &mut Context<Self>,
11657 ) {
11658 self.add_selection(false, window, cx);
11659 }
11660
11661 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11662 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11663
11664 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11665 let mut selections = self.selections.all::<Point>(cx);
11666 let text_layout_details = self.text_layout_details(window);
11667 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11668 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11669 let range = oldest_selection.display_range(&display_map).sorted();
11670
11671 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11672 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11673 let positions = start_x.min(end_x)..start_x.max(end_x);
11674
11675 selections.clear();
11676 let mut stack = Vec::new();
11677 for row in range.start.row().0..=range.end.row().0 {
11678 if let Some(selection) = self.selections.build_columnar_selection(
11679 &display_map,
11680 DisplayRow(row),
11681 &positions,
11682 oldest_selection.reversed,
11683 &text_layout_details,
11684 ) {
11685 stack.push(selection.id);
11686 selections.push(selection);
11687 }
11688 }
11689
11690 if above {
11691 stack.reverse();
11692 }
11693
11694 AddSelectionsState { above, stack }
11695 });
11696
11697 let last_added_selection = *state.stack.last().unwrap();
11698 let mut new_selections = Vec::new();
11699 if above == state.above {
11700 let end_row = if above {
11701 DisplayRow(0)
11702 } else {
11703 display_map.max_point().row()
11704 };
11705
11706 'outer: for selection in selections {
11707 if selection.id == last_added_selection {
11708 let range = selection.display_range(&display_map).sorted();
11709 debug_assert_eq!(range.start.row(), range.end.row());
11710 let mut row = range.start.row();
11711 let positions =
11712 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11713 px(start)..px(end)
11714 } else {
11715 let start_x =
11716 display_map.x_for_display_point(range.start, &text_layout_details);
11717 let end_x =
11718 display_map.x_for_display_point(range.end, &text_layout_details);
11719 start_x.min(end_x)..start_x.max(end_x)
11720 };
11721
11722 while row != end_row {
11723 if above {
11724 row.0 -= 1;
11725 } else {
11726 row.0 += 1;
11727 }
11728
11729 if let Some(new_selection) = self.selections.build_columnar_selection(
11730 &display_map,
11731 row,
11732 &positions,
11733 selection.reversed,
11734 &text_layout_details,
11735 ) {
11736 state.stack.push(new_selection.id);
11737 if above {
11738 new_selections.push(new_selection);
11739 new_selections.push(selection);
11740 } else {
11741 new_selections.push(selection);
11742 new_selections.push(new_selection);
11743 }
11744
11745 continue 'outer;
11746 }
11747 }
11748 }
11749
11750 new_selections.push(selection);
11751 }
11752 } else {
11753 new_selections = selections;
11754 new_selections.retain(|s| s.id != last_added_selection);
11755 state.stack.pop();
11756 }
11757
11758 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11759 s.select(new_selections);
11760 });
11761 if state.stack.len() > 1 {
11762 self.add_selections_state = Some(state);
11763 }
11764 }
11765
11766 pub fn select_next_match_internal(
11767 &mut self,
11768 display_map: &DisplaySnapshot,
11769 replace_newest: bool,
11770 autoscroll: Option<Autoscroll>,
11771 window: &mut Window,
11772 cx: &mut Context<Self>,
11773 ) -> Result<()> {
11774 fn select_next_match_ranges(
11775 this: &mut Editor,
11776 range: Range<usize>,
11777 replace_newest: bool,
11778 auto_scroll: Option<Autoscroll>,
11779 window: &mut Window,
11780 cx: &mut Context<Editor>,
11781 ) {
11782 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11783 this.change_selections(auto_scroll, window, cx, |s| {
11784 if replace_newest {
11785 s.delete(s.newest_anchor().id);
11786 }
11787 s.insert_range(range.clone());
11788 });
11789 }
11790
11791 let buffer = &display_map.buffer_snapshot;
11792 let mut selections = self.selections.all::<usize>(cx);
11793 if let Some(mut select_next_state) = self.select_next_state.take() {
11794 let query = &select_next_state.query;
11795 if !select_next_state.done {
11796 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11797 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11798 let mut next_selected_range = None;
11799
11800 let bytes_after_last_selection =
11801 buffer.bytes_in_range(last_selection.end..buffer.len());
11802 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11803 let query_matches = query
11804 .stream_find_iter(bytes_after_last_selection)
11805 .map(|result| (last_selection.end, result))
11806 .chain(
11807 query
11808 .stream_find_iter(bytes_before_first_selection)
11809 .map(|result| (0, result)),
11810 );
11811
11812 for (start_offset, query_match) in query_matches {
11813 let query_match = query_match.unwrap(); // can only fail due to I/O
11814 let offset_range =
11815 start_offset + query_match.start()..start_offset + query_match.end();
11816 let display_range = offset_range.start.to_display_point(display_map)
11817 ..offset_range.end.to_display_point(display_map);
11818
11819 if !select_next_state.wordwise
11820 || (!movement::is_inside_word(display_map, display_range.start)
11821 && !movement::is_inside_word(display_map, display_range.end))
11822 {
11823 // TODO: This is n^2, because we might check all the selections
11824 if !selections
11825 .iter()
11826 .any(|selection| selection.range().overlaps(&offset_range))
11827 {
11828 next_selected_range = Some(offset_range);
11829 break;
11830 }
11831 }
11832 }
11833
11834 if let Some(next_selected_range) = next_selected_range {
11835 select_next_match_ranges(
11836 self,
11837 next_selected_range,
11838 replace_newest,
11839 autoscroll,
11840 window,
11841 cx,
11842 );
11843 } else {
11844 select_next_state.done = true;
11845 }
11846 }
11847
11848 self.select_next_state = Some(select_next_state);
11849 } else {
11850 let mut only_carets = true;
11851 let mut same_text_selected = true;
11852 let mut selected_text = None;
11853
11854 let mut selections_iter = selections.iter().peekable();
11855 while let Some(selection) = selections_iter.next() {
11856 if selection.start != selection.end {
11857 only_carets = false;
11858 }
11859
11860 if same_text_selected {
11861 if selected_text.is_none() {
11862 selected_text =
11863 Some(buffer.text_for_range(selection.range()).collect::<String>());
11864 }
11865
11866 if let Some(next_selection) = selections_iter.peek() {
11867 if next_selection.range().len() == selection.range().len() {
11868 let next_selected_text = buffer
11869 .text_for_range(next_selection.range())
11870 .collect::<String>();
11871 if Some(next_selected_text) != selected_text {
11872 same_text_selected = false;
11873 selected_text = None;
11874 }
11875 } else {
11876 same_text_selected = false;
11877 selected_text = None;
11878 }
11879 }
11880 }
11881 }
11882
11883 if only_carets {
11884 for selection in &mut selections {
11885 let word_range = movement::surrounding_word(
11886 display_map,
11887 selection.start.to_display_point(display_map),
11888 );
11889 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11890 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11891 selection.goal = SelectionGoal::None;
11892 selection.reversed = false;
11893 select_next_match_ranges(
11894 self,
11895 selection.start..selection.end,
11896 replace_newest,
11897 autoscroll,
11898 window,
11899 cx,
11900 );
11901 }
11902
11903 if selections.len() == 1 {
11904 let selection = selections
11905 .last()
11906 .expect("ensured that there's only one selection");
11907 let query = buffer
11908 .text_for_range(selection.start..selection.end)
11909 .collect::<String>();
11910 let is_empty = query.is_empty();
11911 let select_state = SelectNextState {
11912 query: AhoCorasick::new(&[query])?,
11913 wordwise: true,
11914 done: is_empty,
11915 };
11916 self.select_next_state = Some(select_state);
11917 } else {
11918 self.select_next_state = None;
11919 }
11920 } else if let Some(selected_text) = selected_text {
11921 self.select_next_state = Some(SelectNextState {
11922 query: AhoCorasick::new(&[selected_text])?,
11923 wordwise: false,
11924 done: false,
11925 });
11926 self.select_next_match_internal(
11927 display_map,
11928 replace_newest,
11929 autoscroll,
11930 window,
11931 cx,
11932 )?;
11933 }
11934 }
11935 Ok(())
11936 }
11937
11938 pub fn select_all_matches(
11939 &mut self,
11940 _action: &SelectAllMatches,
11941 window: &mut Window,
11942 cx: &mut Context<Self>,
11943 ) -> Result<()> {
11944 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11945
11946 self.push_to_selection_history();
11947 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11948
11949 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11950 let Some(select_next_state) = self.select_next_state.as_mut() else {
11951 return Ok(());
11952 };
11953 if select_next_state.done {
11954 return Ok(());
11955 }
11956
11957 let mut new_selections = Vec::new();
11958
11959 let reversed = self.selections.oldest::<usize>(cx).reversed;
11960 let buffer = &display_map.buffer_snapshot;
11961 let query_matches = select_next_state
11962 .query
11963 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11964
11965 for query_match in query_matches.into_iter() {
11966 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11967 let offset_range = if reversed {
11968 query_match.end()..query_match.start()
11969 } else {
11970 query_match.start()..query_match.end()
11971 };
11972 let display_range = offset_range.start.to_display_point(&display_map)
11973 ..offset_range.end.to_display_point(&display_map);
11974
11975 if !select_next_state.wordwise
11976 || (!movement::is_inside_word(&display_map, display_range.start)
11977 && !movement::is_inside_word(&display_map, display_range.end))
11978 {
11979 new_selections.push(offset_range.start..offset_range.end);
11980 }
11981 }
11982
11983 select_next_state.done = true;
11984 self.unfold_ranges(&new_selections.clone(), false, false, cx);
11985 self.change_selections(None, window, cx, |selections| {
11986 selections.select_ranges(new_selections)
11987 });
11988
11989 Ok(())
11990 }
11991
11992 pub fn select_next(
11993 &mut self,
11994 action: &SelectNext,
11995 window: &mut Window,
11996 cx: &mut Context<Self>,
11997 ) -> Result<()> {
11998 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11999 self.push_to_selection_history();
12000 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12001 self.select_next_match_internal(
12002 &display_map,
12003 action.replace_newest,
12004 Some(Autoscroll::newest()),
12005 window,
12006 cx,
12007 )?;
12008 Ok(())
12009 }
12010
12011 pub fn select_previous(
12012 &mut self,
12013 action: &SelectPrevious,
12014 window: &mut Window,
12015 cx: &mut Context<Self>,
12016 ) -> Result<()> {
12017 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12018 self.push_to_selection_history();
12019 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12020 let buffer = &display_map.buffer_snapshot;
12021 let mut selections = self.selections.all::<usize>(cx);
12022 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12023 let query = &select_prev_state.query;
12024 if !select_prev_state.done {
12025 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12026 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12027 let mut next_selected_range = None;
12028 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12029 let bytes_before_last_selection =
12030 buffer.reversed_bytes_in_range(0..last_selection.start);
12031 let bytes_after_first_selection =
12032 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12033 let query_matches = query
12034 .stream_find_iter(bytes_before_last_selection)
12035 .map(|result| (last_selection.start, result))
12036 .chain(
12037 query
12038 .stream_find_iter(bytes_after_first_selection)
12039 .map(|result| (buffer.len(), result)),
12040 );
12041 for (end_offset, query_match) in query_matches {
12042 let query_match = query_match.unwrap(); // can only fail due to I/O
12043 let offset_range =
12044 end_offset - query_match.end()..end_offset - query_match.start();
12045 let display_range = offset_range.start.to_display_point(&display_map)
12046 ..offset_range.end.to_display_point(&display_map);
12047
12048 if !select_prev_state.wordwise
12049 || (!movement::is_inside_word(&display_map, display_range.start)
12050 && !movement::is_inside_word(&display_map, display_range.end))
12051 {
12052 next_selected_range = Some(offset_range);
12053 break;
12054 }
12055 }
12056
12057 if let Some(next_selected_range) = next_selected_range {
12058 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12059 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12060 if action.replace_newest {
12061 s.delete(s.newest_anchor().id);
12062 }
12063 s.insert_range(next_selected_range);
12064 });
12065 } else {
12066 select_prev_state.done = true;
12067 }
12068 }
12069
12070 self.select_prev_state = Some(select_prev_state);
12071 } else {
12072 let mut only_carets = true;
12073 let mut same_text_selected = true;
12074 let mut selected_text = None;
12075
12076 let mut selections_iter = selections.iter().peekable();
12077 while let Some(selection) = selections_iter.next() {
12078 if selection.start != selection.end {
12079 only_carets = false;
12080 }
12081
12082 if same_text_selected {
12083 if selected_text.is_none() {
12084 selected_text =
12085 Some(buffer.text_for_range(selection.range()).collect::<String>());
12086 }
12087
12088 if let Some(next_selection) = selections_iter.peek() {
12089 if next_selection.range().len() == selection.range().len() {
12090 let next_selected_text = buffer
12091 .text_for_range(next_selection.range())
12092 .collect::<String>();
12093 if Some(next_selected_text) != selected_text {
12094 same_text_selected = false;
12095 selected_text = None;
12096 }
12097 } else {
12098 same_text_selected = false;
12099 selected_text = None;
12100 }
12101 }
12102 }
12103 }
12104
12105 if only_carets {
12106 for selection in &mut selections {
12107 let word_range = movement::surrounding_word(
12108 &display_map,
12109 selection.start.to_display_point(&display_map),
12110 );
12111 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12112 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12113 selection.goal = SelectionGoal::None;
12114 selection.reversed = false;
12115 }
12116 if selections.len() == 1 {
12117 let selection = selections
12118 .last()
12119 .expect("ensured that there's only one selection");
12120 let query = buffer
12121 .text_for_range(selection.start..selection.end)
12122 .collect::<String>();
12123 let is_empty = query.is_empty();
12124 let select_state = SelectNextState {
12125 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12126 wordwise: true,
12127 done: is_empty,
12128 };
12129 self.select_prev_state = Some(select_state);
12130 } else {
12131 self.select_prev_state = None;
12132 }
12133
12134 self.unfold_ranges(
12135 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12136 false,
12137 true,
12138 cx,
12139 );
12140 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12141 s.select(selections);
12142 });
12143 } else if let Some(selected_text) = selected_text {
12144 self.select_prev_state = Some(SelectNextState {
12145 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12146 wordwise: false,
12147 done: false,
12148 });
12149 self.select_previous(action, window, cx)?;
12150 }
12151 }
12152 Ok(())
12153 }
12154
12155 pub fn find_next_match(
12156 &mut self,
12157 _: &FindNextMatch,
12158 window: &mut Window,
12159 cx: &mut Context<Self>,
12160 ) -> Result<()> {
12161 let selections = self.selections.disjoint_anchors();
12162 match selections.first() {
12163 Some(first) if selections.len() >= 2 => {
12164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12165 s.select_ranges([first.range()]);
12166 });
12167 }
12168 _ => self.select_next(
12169 &SelectNext {
12170 replace_newest: true,
12171 },
12172 window,
12173 cx,
12174 )?,
12175 }
12176 Ok(())
12177 }
12178
12179 pub fn find_previous_match(
12180 &mut self,
12181 _: &FindPreviousMatch,
12182 window: &mut Window,
12183 cx: &mut Context<Self>,
12184 ) -> Result<()> {
12185 let selections = self.selections.disjoint_anchors();
12186 match selections.last() {
12187 Some(last) if selections.len() >= 2 => {
12188 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12189 s.select_ranges([last.range()]);
12190 });
12191 }
12192 _ => self.select_previous(
12193 &SelectPrevious {
12194 replace_newest: true,
12195 },
12196 window,
12197 cx,
12198 )?,
12199 }
12200 Ok(())
12201 }
12202
12203 pub fn toggle_comments(
12204 &mut self,
12205 action: &ToggleComments,
12206 window: &mut Window,
12207 cx: &mut Context<Self>,
12208 ) {
12209 if self.read_only(cx) {
12210 return;
12211 }
12212 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12213 let text_layout_details = &self.text_layout_details(window);
12214 self.transact(window, cx, |this, window, cx| {
12215 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12216 let mut edits = Vec::new();
12217 let mut selection_edit_ranges = Vec::new();
12218 let mut last_toggled_row = None;
12219 let snapshot = this.buffer.read(cx).read(cx);
12220 let empty_str: Arc<str> = Arc::default();
12221 let mut suffixes_inserted = Vec::new();
12222 let ignore_indent = action.ignore_indent;
12223
12224 fn comment_prefix_range(
12225 snapshot: &MultiBufferSnapshot,
12226 row: MultiBufferRow,
12227 comment_prefix: &str,
12228 comment_prefix_whitespace: &str,
12229 ignore_indent: bool,
12230 ) -> Range<Point> {
12231 let indent_size = if ignore_indent {
12232 0
12233 } else {
12234 snapshot.indent_size_for_line(row).len
12235 };
12236
12237 let start = Point::new(row.0, indent_size);
12238
12239 let mut line_bytes = snapshot
12240 .bytes_in_range(start..snapshot.max_point())
12241 .flatten()
12242 .copied();
12243
12244 // If this line currently begins with the line comment prefix, then record
12245 // the range containing the prefix.
12246 if line_bytes
12247 .by_ref()
12248 .take(comment_prefix.len())
12249 .eq(comment_prefix.bytes())
12250 {
12251 // Include any whitespace that matches the comment prefix.
12252 let matching_whitespace_len = line_bytes
12253 .zip(comment_prefix_whitespace.bytes())
12254 .take_while(|(a, b)| a == b)
12255 .count() as u32;
12256 let end = Point::new(
12257 start.row,
12258 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12259 );
12260 start..end
12261 } else {
12262 start..start
12263 }
12264 }
12265
12266 fn comment_suffix_range(
12267 snapshot: &MultiBufferSnapshot,
12268 row: MultiBufferRow,
12269 comment_suffix: &str,
12270 comment_suffix_has_leading_space: bool,
12271 ) -> Range<Point> {
12272 let end = Point::new(row.0, snapshot.line_len(row));
12273 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12274
12275 let mut line_end_bytes = snapshot
12276 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12277 .flatten()
12278 .copied();
12279
12280 let leading_space_len = if suffix_start_column > 0
12281 && line_end_bytes.next() == Some(b' ')
12282 && comment_suffix_has_leading_space
12283 {
12284 1
12285 } else {
12286 0
12287 };
12288
12289 // If this line currently begins with the line comment prefix, then record
12290 // the range containing the prefix.
12291 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12292 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12293 start..end
12294 } else {
12295 end..end
12296 }
12297 }
12298
12299 // TODO: Handle selections that cross excerpts
12300 for selection in &mut selections {
12301 let start_column = snapshot
12302 .indent_size_for_line(MultiBufferRow(selection.start.row))
12303 .len;
12304 let language = if let Some(language) =
12305 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12306 {
12307 language
12308 } else {
12309 continue;
12310 };
12311
12312 selection_edit_ranges.clear();
12313
12314 // If multiple selections contain a given row, avoid processing that
12315 // row more than once.
12316 let mut start_row = MultiBufferRow(selection.start.row);
12317 if last_toggled_row == Some(start_row) {
12318 start_row = start_row.next_row();
12319 }
12320 let end_row =
12321 if selection.end.row > selection.start.row && selection.end.column == 0 {
12322 MultiBufferRow(selection.end.row - 1)
12323 } else {
12324 MultiBufferRow(selection.end.row)
12325 };
12326 last_toggled_row = Some(end_row);
12327
12328 if start_row > end_row {
12329 continue;
12330 }
12331
12332 // If the language has line comments, toggle those.
12333 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12334
12335 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12336 if ignore_indent {
12337 full_comment_prefixes = full_comment_prefixes
12338 .into_iter()
12339 .map(|s| Arc::from(s.trim_end()))
12340 .collect();
12341 }
12342
12343 if !full_comment_prefixes.is_empty() {
12344 let first_prefix = full_comment_prefixes
12345 .first()
12346 .expect("prefixes is non-empty");
12347 let prefix_trimmed_lengths = full_comment_prefixes
12348 .iter()
12349 .map(|p| p.trim_end_matches(' ').len())
12350 .collect::<SmallVec<[usize; 4]>>();
12351
12352 let mut all_selection_lines_are_comments = true;
12353
12354 for row in start_row.0..=end_row.0 {
12355 let row = MultiBufferRow(row);
12356 if start_row < end_row && snapshot.is_line_blank(row) {
12357 continue;
12358 }
12359
12360 let prefix_range = full_comment_prefixes
12361 .iter()
12362 .zip(prefix_trimmed_lengths.iter().copied())
12363 .map(|(prefix, trimmed_prefix_len)| {
12364 comment_prefix_range(
12365 snapshot.deref(),
12366 row,
12367 &prefix[..trimmed_prefix_len],
12368 &prefix[trimmed_prefix_len..],
12369 ignore_indent,
12370 )
12371 })
12372 .max_by_key(|range| range.end.column - range.start.column)
12373 .expect("prefixes is non-empty");
12374
12375 if prefix_range.is_empty() {
12376 all_selection_lines_are_comments = false;
12377 }
12378
12379 selection_edit_ranges.push(prefix_range);
12380 }
12381
12382 if all_selection_lines_are_comments {
12383 edits.extend(
12384 selection_edit_ranges
12385 .iter()
12386 .cloned()
12387 .map(|range| (range, empty_str.clone())),
12388 );
12389 } else {
12390 let min_column = selection_edit_ranges
12391 .iter()
12392 .map(|range| range.start.column)
12393 .min()
12394 .unwrap_or(0);
12395 edits.extend(selection_edit_ranges.iter().map(|range| {
12396 let position = Point::new(range.start.row, min_column);
12397 (position..position, first_prefix.clone())
12398 }));
12399 }
12400 } else if let Some((full_comment_prefix, comment_suffix)) =
12401 language.block_comment_delimiters()
12402 {
12403 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12404 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12405 let prefix_range = comment_prefix_range(
12406 snapshot.deref(),
12407 start_row,
12408 comment_prefix,
12409 comment_prefix_whitespace,
12410 ignore_indent,
12411 );
12412 let suffix_range = comment_suffix_range(
12413 snapshot.deref(),
12414 end_row,
12415 comment_suffix.trim_start_matches(' '),
12416 comment_suffix.starts_with(' '),
12417 );
12418
12419 if prefix_range.is_empty() || suffix_range.is_empty() {
12420 edits.push((
12421 prefix_range.start..prefix_range.start,
12422 full_comment_prefix.clone(),
12423 ));
12424 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12425 suffixes_inserted.push((end_row, comment_suffix.len()));
12426 } else {
12427 edits.push((prefix_range, empty_str.clone()));
12428 edits.push((suffix_range, empty_str.clone()));
12429 }
12430 } else {
12431 continue;
12432 }
12433 }
12434
12435 drop(snapshot);
12436 this.buffer.update(cx, |buffer, cx| {
12437 buffer.edit(edits, None, cx);
12438 });
12439
12440 // Adjust selections so that they end before any comment suffixes that
12441 // were inserted.
12442 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12443 let mut selections = this.selections.all::<Point>(cx);
12444 let snapshot = this.buffer.read(cx).read(cx);
12445 for selection in &mut selections {
12446 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12447 match row.cmp(&MultiBufferRow(selection.end.row)) {
12448 Ordering::Less => {
12449 suffixes_inserted.next();
12450 continue;
12451 }
12452 Ordering::Greater => break,
12453 Ordering::Equal => {
12454 if selection.end.column == snapshot.line_len(row) {
12455 if selection.is_empty() {
12456 selection.start.column -= suffix_len as u32;
12457 }
12458 selection.end.column -= suffix_len as u32;
12459 }
12460 break;
12461 }
12462 }
12463 }
12464 }
12465
12466 drop(snapshot);
12467 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12468 s.select(selections)
12469 });
12470
12471 let selections = this.selections.all::<Point>(cx);
12472 let selections_on_single_row = selections.windows(2).all(|selections| {
12473 selections[0].start.row == selections[1].start.row
12474 && selections[0].end.row == selections[1].end.row
12475 && selections[0].start.row == selections[0].end.row
12476 });
12477 let selections_selecting = selections
12478 .iter()
12479 .any(|selection| selection.start != selection.end);
12480 let advance_downwards = action.advance_downwards
12481 && selections_on_single_row
12482 && !selections_selecting
12483 && !matches!(this.mode, EditorMode::SingleLine { .. });
12484
12485 if advance_downwards {
12486 let snapshot = this.buffer.read(cx).snapshot(cx);
12487
12488 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12489 s.move_cursors_with(|display_snapshot, display_point, _| {
12490 let mut point = display_point.to_point(display_snapshot);
12491 point.row += 1;
12492 point = snapshot.clip_point(point, Bias::Left);
12493 let display_point = point.to_display_point(display_snapshot);
12494 let goal = SelectionGoal::HorizontalPosition(
12495 display_snapshot
12496 .x_for_display_point(display_point, text_layout_details)
12497 .into(),
12498 );
12499 (display_point, goal)
12500 })
12501 });
12502 }
12503 });
12504 }
12505
12506 pub fn select_enclosing_symbol(
12507 &mut self,
12508 _: &SelectEnclosingSymbol,
12509 window: &mut Window,
12510 cx: &mut Context<Self>,
12511 ) {
12512 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12513
12514 let buffer = self.buffer.read(cx).snapshot(cx);
12515 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12516
12517 fn update_selection(
12518 selection: &Selection<usize>,
12519 buffer_snap: &MultiBufferSnapshot,
12520 ) -> Option<Selection<usize>> {
12521 let cursor = selection.head();
12522 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12523 for symbol in symbols.iter().rev() {
12524 let start = symbol.range.start.to_offset(buffer_snap);
12525 let end = symbol.range.end.to_offset(buffer_snap);
12526 let new_range = start..end;
12527 if start < selection.start || end > selection.end {
12528 return Some(Selection {
12529 id: selection.id,
12530 start: new_range.start,
12531 end: new_range.end,
12532 goal: SelectionGoal::None,
12533 reversed: selection.reversed,
12534 });
12535 }
12536 }
12537 None
12538 }
12539
12540 let mut selected_larger_symbol = false;
12541 let new_selections = old_selections
12542 .iter()
12543 .map(|selection| match update_selection(selection, &buffer) {
12544 Some(new_selection) => {
12545 if new_selection.range() != selection.range() {
12546 selected_larger_symbol = true;
12547 }
12548 new_selection
12549 }
12550 None => selection.clone(),
12551 })
12552 .collect::<Vec<_>>();
12553
12554 if selected_larger_symbol {
12555 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12556 s.select(new_selections);
12557 });
12558 }
12559 }
12560
12561 pub fn select_larger_syntax_node(
12562 &mut self,
12563 _: &SelectLargerSyntaxNode,
12564 window: &mut Window,
12565 cx: &mut Context<Self>,
12566 ) {
12567 let Some(visible_row_count) = self.visible_row_count() else {
12568 return;
12569 };
12570 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12571 if old_selections.is_empty() {
12572 return;
12573 }
12574
12575 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12576
12577 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12578 let buffer = self.buffer.read(cx).snapshot(cx);
12579
12580 let mut selected_larger_node = false;
12581 let mut new_selections = old_selections
12582 .iter()
12583 .map(|selection| {
12584 let old_range = selection.start..selection.end;
12585 let mut new_range = old_range.clone();
12586 let mut new_node = None;
12587 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12588 {
12589 new_node = Some(node);
12590 new_range = match containing_range {
12591 MultiOrSingleBufferOffsetRange::Single(_) => break,
12592 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12593 };
12594 if !display_map.intersects_fold(new_range.start)
12595 && !display_map.intersects_fold(new_range.end)
12596 {
12597 break;
12598 }
12599 }
12600
12601 if let Some(node) = new_node {
12602 // Log the ancestor, to support using this action as a way to explore TreeSitter
12603 // nodes. Parent and grandparent are also logged because this operation will not
12604 // visit nodes that have the same range as their parent.
12605 log::info!("Node: {node:?}");
12606 let parent = node.parent();
12607 log::info!("Parent: {parent:?}");
12608 let grandparent = parent.and_then(|x| x.parent());
12609 log::info!("Grandparent: {grandparent:?}");
12610 }
12611
12612 selected_larger_node |= new_range != old_range;
12613 Selection {
12614 id: selection.id,
12615 start: new_range.start,
12616 end: new_range.end,
12617 goal: SelectionGoal::None,
12618 reversed: selection.reversed,
12619 }
12620 })
12621 .collect::<Vec<_>>();
12622
12623 if !selected_larger_node {
12624 return; // don't put this call in the history
12625 }
12626
12627 // scroll based on transformation done to the last selection created by the user
12628 let (last_old, last_new) = old_selections
12629 .last()
12630 .zip(new_selections.last().cloned())
12631 .expect("old_selections isn't empty");
12632
12633 // revert selection
12634 let is_selection_reversed = {
12635 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12636 new_selections.last_mut().expect("checked above").reversed =
12637 should_newest_selection_be_reversed;
12638 should_newest_selection_be_reversed
12639 };
12640
12641 if selected_larger_node {
12642 self.select_syntax_node_history.disable_clearing = true;
12643 self.change_selections(None, window, cx, |s| {
12644 s.select(new_selections.clone());
12645 });
12646 self.select_syntax_node_history.disable_clearing = false;
12647 }
12648
12649 let start_row = last_new.start.to_display_point(&display_map).row().0;
12650 let end_row = last_new.end.to_display_point(&display_map).row().0;
12651 let selection_height = end_row - start_row + 1;
12652 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12653
12654 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12655 let scroll_behavior = if fits_on_the_screen {
12656 self.request_autoscroll(Autoscroll::fit(), cx);
12657 SelectSyntaxNodeScrollBehavior::FitSelection
12658 } else if is_selection_reversed {
12659 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12660 SelectSyntaxNodeScrollBehavior::CursorTop
12661 } else {
12662 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12663 SelectSyntaxNodeScrollBehavior::CursorBottom
12664 };
12665
12666 self.select_syntax_node_history.push((
12667 old_selections,
12668 scroll_behavior,
12669 is_selection_reversed,
12670 ));
12671 }
12672
12673 pub fn select_smaller_syntax_node(
12674 &mut self,
12675 _: &SelectSmallerSyntaxNode,
12676 window: &mut Window,
12677 cx: &mut Context<Self>,
12678 ) {
12679 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12680
12681 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12682 self.select_syntax_node_history.pop()
12683 {
12684 if let Some(selection) = selections.last_mut() {
12685 selection.reversed = is_selection_reversed;
12686 }
12687
12688 self.select_syntax_node_history.disable_clearing = true;
12689 self.change_selections(None, window, cx, |s| {
12690 s.select(selections.to_vec());
12691 });
12692 self.select_syntax_node_history.disable_clearing = false;
12693
12694 match scroll_behavior {
12695 SelectSyntaxNodeScrollBehavior::CursorTop => {
12696 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12697 }
12698 SelectSyntaxNodeScrollBehavior::FitSelection => {
12699 self.request_autoscroll(Autoscroll::fit(), cx);
12700 }
12701 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12702 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12703 }
12704 }
12705 }
12706 }
12707
12708 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12709 if !EditorSettings::get_global(cx).gutter.runnables {
12710 self.clear_tasks();
12711 return Task::ready(());
12712 }
12713 let project = self.project.as_ref().map(Entity::downgrade);
12714 let task_sources = self.lsp_task_sources(cx);
12715 cx.spawn_in(window, async move |editor, cx| {
12716 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12717 let Some(project) = project.and_then(|p| p.upgrade()) else {
12718 return;
12719 };
12720 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12721 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12722 }) else {
12723 return;
12724 };
12725
12726 let hide_runnables = project
12727 .update(cx, |project, cx| {
12728 // Do not display any test indicators in non-dev server remote projects.
12729 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12730 })
12731 .unwrap_or(true);
12732 if hide_runnables {
12733 return;
12734 }
12735 let new_rows =
12736 cx.background_spawn({
12737 let snapshot = display_snapshot.clone();
12738 async move {
12739 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12740 }
12741 })
12742 .await;
12743 let Ok(lsp_tasks) =
12744 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12745 else {
12746 return;
12747 };
12748 let lsp_tasks = lsp_tasks.await;
12749
12750 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12751 lsp_tasks
12752 .into_iter()
12753 .flat_map(|(kind, tasks)| {
12754 tasks.into_iter().filter_map(move |(location, task)| {
12755 Some((kind.clone(), location?, task))
12756 })
12757 })
12758 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12759 let buffer = location.target.buffer;
12760 let buffer_snapshot = buffer.read(cx).snapshot();
12761 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12762 |(excerpt_id, snapshot, _)| {
12763 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12764 display_snapshot
12765 .buffer_snapshot
12766 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12767 } else {
12768 None
12769 }
12770 },
12771 );
12772 if let Some(offset) = offset {
12773 let task_buffer_range =
12774 location.target.range.to_point(&buffer_snapshot);
12775 let context_buffer_range =
12776 task_buffer_range.to_offset(&buffer_snapshot);
12777 let context_range = BufferOffset(context_buffer_range.start)
12778 ..BufferOffset(context_buffer_range.end);
12779
12780 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12781 .or_insert_with(|| RunnableTasks {
12782 templates: Vec::new(),
12783 offset,
12784 column: task_buffer_range.start.column,
12785 extra_variables: HashMap::default(),
12786 context_range,
12787 })
12788 .templates
12789 .push((kind, task.original_task().clone()));
12790 }
12791
12792 acc
12793 })
12794 }) else {
12795 return;
12796 };
12797
12798 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12799 editor
12800 .update(cx, |editor, _| {
12801 editor.clear_tasks();
12802 for (key, mut value) in rows {
12803 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12804 value.templates.extend(lsp_tasks.templates);
12805 }
12806
12807 editor.insert_tasks(key, value);
12808 }
12809 for (key, value) in lsp_tasks_by_rows {
12810 editor.insert_tasks(key, value);
12811 }
12812 })
12813 .ok();
12814 })
12815 }
12816 fn fetch_runnable_ranges(
12817 snapshot: &DisplaySnapshot,
12818 range: Range<Anchor>,
12819 ) -> Vec<language::RunnableRange> {
12820 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12821 }
12822
12823 fn runnable_rows(
12824 project: Entity<Project>,
12825 snapshot: DisplaySnapshot,
12826 runnable_ranges: Vec<RunnableRange>,
12827 mut cx: AsyncWindowContext,
12828 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12829 runnable_ranges
12830 .into_iter()
12831 .filter_map(|mut runnable| {
12832 let tasks = cx
12833 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12834 .ok()?;
12835 if tasks.is_empty() {
12836 return None;
12837 }
12838
12839 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12840
12841 let row = snapshot
12842 .buffer_snapshot
12843 .buffer_line_for_row(MultiBufferRow(point.row))?
12844 .1
12845 .start
12846 .row;
12847
12848 let context_range =
12849 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12850 Some((
12851 (runnable.buffer_id, row),
12852 RunnableTasks {
12853 templates: tasks,
12854 offset: snapshot
12855 .buffer_snapshot
12856 .anchor_before(runnable.run_range.start),
12857 context_range,
12858 column: point.column,
12859 extra_variables: runnable.extra_captures,
12860 },
12861 ))
12862 })
12863 .collect()
12864 }
12865
12866 fn templates_with_tags(
12867 project: &Entity<Project>,
12868 runnable: &mut Runnable,
12869 cx: &mut App,
12870 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12871 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12872 let (worktree_id, file) = project
12873 .buffer_for_id(runnable.buffer, cx)
12874 .and_then(|buffer| buffer.read(cx).file())
12875 .map(|file| (file.worktree_id(cx), file.clone()))
12876 .unzip();
12877
12878 (
12879 project.task_store().read(cx).task_inventory().cloned(),
12880 worktree_id,
12881 file,
12882 )
12883 });
12884
12885 let mut templates_with_tags = mem::take(&mut runnable.tags)
12886 .into_iter()
12887 .flat_map(|RunnableTag(tag)| {
12888 inventory
12889 .as_ref()
12890 .into_iter()
12891 .flat_map(|inventory| {
12892 inventory.read(cx).list_tasks(
12893 file.clone(),
12894 Some(runnable.language.clone()),
12895 worktree_id,
12896 cx,
12897 )
12898 })
12899 .filter(move |(_, template)| {
12900 template.tags.iter().any(|source_tag| source_tag == &tag)
12901 })
12902 })
12903 .sorted_by_key(|(kind, _)| kind.to_owned())
12904 .collect::<Vec<_>>();
12905 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12906 // Strongest source wins; if we have worktree tag binding, prefer that to
12907 // global and language bindings;
12908 // if we have a global binding, prefer that to language binding.
12909 let first_mismatch = templates_with_tags
12910 .iter()
12911 .position(|(tag_source, _)| tag_source != leading_tag_source);
12912 if let Some(index) = first_mismatch {
12913 templates_with_tags.truncate(index);
12914 }
12915 }
12916
12917 templates_with_tags
12918 }
12919
12920 pub fn move_to_enclosing_bracket(
12921 &mut self,
12922 _: &MoveToEnclosingBracket,
12923 window: &mut Window,
12924 cx: &mut Context<Self>,
12925 ) {
12926 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12927 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12928 s.move_offsets_with(|snapshot, selection| {
12929 let Some(enclosing_bracket_ranges) =
12930 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12931 else {
12932 return;
12933 };
12934
12935 let mut best_length = usize::MAX;
12936 let mut best_inside = false;
12937 let mut best_in_bracket_range = false;
12938 let mut best_destination = None;
12939 for (open, close) in enclosing_bracket_ranges {
12940 let close = close.to_inclusive();
12941 let length = close.end() - open.start;
12942 let inside = selection.start >= open.end && selection.end <= *close.start();
12943 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12944 || close.contains(&selection.head());
12945
12946 // If best is next to a bracket and current isn't, skip
12947 if !in_bracket_range && best_in_bracket_range {
12948 continue;
12949 }
12950
12951 // Prefer smaller lengths unless best is inside and current isn't
12952 if length > best_length && (best_inside || !inside) {
12953 continue;
12954 }
12955
12956 best_length = length;
12957 best_inside = inside;
12958 best_in_bracket_range = in_bracket_range;
12959 best_destination = Some(
12960 if close.contains(&selection.start) && close.contains(&selection.end) {
12961 if inside { open.end } else { open.start }
12962 } else if inside {
12963 *close.start()
12964 } else {
12965 *close.end()
12966 },
12967 );
12968 }
12969
12970 if let Some(destination) = best_destination {
12971 selection.collapse_to(destination, SelectionGoal::None);
12972 }
12973 })
12974 });
12975 }
12976
12977 pub fn undo_selection(
12978 &mut self,
12979 _: &UndoSelection,
12980 window: &mut Window,
12981 cx: &mut Context<Self>,
12982 ) {
12983 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12984 self.end_selection(window, cx);
12985 self.selection_history.mode = SelectionHistoryMode::Undoing;
12986 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12987 self.change_selections(None, window, cx, |s| {
12988 s.select_anchors(entry.selections.to_vec())
12989 });
12990 self.select_next_state = entry.select_next_state;
12991 self.select_prev_state = entry.select_prev_state;
12992 self.add_selections_state = entry.add_selections_state;
12993 self.request_autoscroll(Autoscroll::newest(), cx);
12994 }
12995 self.selection_history.mode = SelectionHistoryMode::Normal;
12996 }
12997
12998 pub fn redo_selection(
12999 &mut self,
13000 _: &RedoSelection,
13001 window: &mut Window,
13002 cx: &mut Context<Self>,
13003 ) {
13004 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13005 self.end_selection(window, cx);
13006 self.selection_history.mode = SelectionHistoryMode::Redoing;
13007 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13008 self.change_selections(None, window, cx, |s| {
13009 s.select_anchors(entry.selections.to_vec())
13010 });
13011 self.select_next_state = entry.select_next_state;
13012 self.select_prev_state = entry.select_prev_state;
13013 self.add_selections_state = entry.add_selections_state;
13014 self.request_autoscroll(Autoscroll::newest(), cx);
13015 }
13016 self.selection_history.mode = SelectionHistoryMode::Normal;
13017 }
13018
13019 pub fn expand_excerpts(
13020 &mut self,
13021 action: &ExpandExcerpts,
13022 _: &mut Window,
13023 cx: &mut Context<Self>,
13024 ) {
13025 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13026 }
13027
13028 pub fn expand_excerpts_down(
13029 &mut self,
13030 action: &ExpandExcerptsDown,
13031 _: &mut Window,
13032 cx: &mut Context<Self>,
13033 ) {
13034 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13035 }
13036
13037 pub fn expand_excerpts_up(
13038 &mut self,
13039 action: &ExpandExcerptsUp,
13040 _: &mut Window,
13041 cx: &mut Context<Self>,
13042 ) {
13043 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13044 }
13045
13046 pub fn expand_excerpts_for_direction(
13047 &mut self,
13048 lines: u32,
13049 direction: ExpandExcerptDirection,
13050
13051 cx: &mut Context<Self>,
13052 ) {
13053 let selections = self.selections.disjoint_anchors();
13054
13055 let lines = if lines == 0 {
13056 EditorSettings::get_global(cx).expand_excerpt_lines
13057 } else {
13058 lines
13059 };
13060
13061 self.buffer.update(cx, |buffer, cx| {
13062 let snapshot = buffer.snapshot(cx);
13063 let mut excerpt_ids = selections
13064 .iter()
13065 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13066 .collect::<Vec<_>>();
13067 excerpt_ids.sort();
13068 excerpt_ids.dedup();
13069 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13070 })
13071 }
13072
13073 pub fn expand_excerpt(
13074 &mut self,
13075 excerpt: ExcerptId,
13076 direction: ExpandExcerptDirection,
13077 window: &mut Window,
13078 cx: &mut Context<Self>,
13079 ) {
13080 let current_scroll_position = self.scroll_position(cx);
13081 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13082 let mut should_scroll_up = false;
13083
13084 if direction == ExpandExcerptDirection::Down {
13085 let multi_buffer = self.buffer.read(cx);
13086 let snapshot = multi_buffer.snapshot(cx);
13087 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13088 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13089 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13090 let buffer_snapshot = buffer.read(cx).snapshot();
13091 let excerpt_end_row =
13092 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13093 let last_row = buffer_snapshot.max_point().row;
13094 let lines_below = last_row.saturating_sub(excerpt_end_row);
13095 should_scroll_up = lines_below >= lines_to_expand;
13096 }
13097 }
13098 }
13099 }
13100
13101 self.buffer.update(cx, |buffer, cx| {
13102 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13103 });
13104
13105 if should_scroll_up {
13106 let new_scroll_position =
13107 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13108 self.set_scroll_position(new_scroll_position, window, cx);
13109 }
13110 }
13111
13112 pub fn go_to_singleton_buffer_point(
13113 &mut self,
13114 point: Point,
13115 window: &mut Window,
13116 cx: &mut Context<Self>,
13117 ) {
13118 self.go_to_singleton_buffer_range(point..point, window, cx);
13119 }
13120
13121 pub fn go_to_singleton_buffer_range(
13122 &mut self,
13123 range: Range<Point>,
13124 window: &mut Window,
13125 cx: &mut Context<Self>,
13126 ) {
13127 let multibuffer = self.buffer().read(cx);
13128 let Some(buffer) = multibuffer.as_singleton() else {
13129 return;
13130 };
13131 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13132 return;
13133 };
13134 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13135 return;
13136 };
13137 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13138 s.select_anchor_ranges([start..end])
13139 });
13140 }
13141
13142 pub fn go_to_diagnostic(
13143 &mut self,
13144 _: &GoToDiagnostic,
13145 window: &mut Window,
13146 cx: &mut Context<Self>,
13147 ) {
13148 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13149 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13150 }
13151
13152 pub fn go_to_prev_diagnostic(
13153 &mut self,
13154 _: &GoToPreviousDiagnostic,
13155 window: &mut Window,
13156 cx: &mut Context<Self>,
13157 ) {
13158 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13159 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13160 }
13161
13162 pub fn go_to_diagnostic_impl(
13163 &mut self,
13164 direction: Direction,
13165 window: &mut Window,
13166 cx: &mut Context<Self>,
13167 ) {
13168 let buffer = self.buffer.read(cx).snapshot(cx);
13169 let selection = self.selections.newest::<usize>(cx);
13170
13171 let mut active_group_id = None;
13172 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13173 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13174 active_group_id = Some(active_group.group_id);
13175 }
13176 }
13177
13178 fn filtered(
13179 snapshot: EditorSnapshot,
13180 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13181 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13182 diagnostics
13183 .filter(|entry| entry.range.start != entry.range.end)
13184 .filter(|entry| !entry.diagnostic.is_unnecessary)
13185 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13186 }
13187
13188 let snapshot = self.snapshot(window, cx);
13189 let before = filtered(
13190 snapshot.clone(),
13191 buffer
13192 .diagnostics_in_range(0..selection.start)
13193 .filter(|entry| entry.range.start <= selection.start),
13194 );
13195 let after = filtered(
13196 snapshot,
13197 buffer
13198 .diagnostics_in_range(selection.start..buffer.len())
13199 .filter(|entry| entry.range.start >= selection.start),
13200 );
13201
13202 let mut found: Option<DiagnosticEntry<usize>> = None;
13203 if direction == Direction::Prev {
13204 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13205 {
13206 for diagnostic in prev_diagnostics.into_iter().rev() {
13207 if diagnostic.range.start != selection.start
13208 || active_group_id
13209 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13210 {
13211 found = Some(diagnostic);
13212 break 'outer;
13213 }
13214 }
13215 }
13216 } else {
13217 for diagnostic in after.chain(before) {
13218 if diagnostic.range.start != selection.start
13219 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13220 {
13221 found = Some(diagnostic);
13222 break;
13223 }
13224 }
13225 }
13226 let Some(next_diagnostic) = found else {
13227 return;
13228 };
13229
13230 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13231 return;
13232 };
13233 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13234 s.select_ranges(vec![
13235 next_diagnostic.range.start..next_diagnostic.range.start,
13236 ])
13237 });
13238 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13239 self.refresh_inline_completion(false, true, window, cx);
13240 }
13241
13242 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13243 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13244 let snapshot = self.snapshot(window, cx);
13245 let selection = self.selections.newest::<Point>(cx);
13246 self.go_to_hunk_before_or_after_position(
13247 &snapshot,
13248 selection.head(),
13249 Direction::Next,
13250 window,
13251 cx,
13252 );
13253 }
13254
13255 pub fn go_to_hunk_before_or_after_position(
13256 &mut self,
13257 snapshot: &EditorSnapshot,
13258 position: Point,
13259 direction: Direction,
13260 window: &mut Window,
13261 cx: &mut Context<Editor>,
13262 ) {
13263 let row = if direction == Direction::Next {
13264 self.hunk_after_position(snapshot, position)
13265 .map(|hunk| hunk.row_range.start)
13266 } else {
13267 self.hunk_before_position(snapshot, position)
13268 };
13269
13270 if let Some(row) = row {
13271 let destination = Point::new(row.0, 0);
13272 let autoscroll = Autoscroll::center();
13273
13274 self.unfold_ranges(&[destination..destination], false, false, cx);
13275 self.change_selections(Some(autoscroll), window, cx, |s| {
13276 s.select_ranges([destination..destination]);
13277 });
13278 }
13279 }
13280
13281 fn hunk_after_position(
13282 &mut self,
13283 snapshot: &EditorSnapshot,
13284 position: Point,
13285 ) -> Option<MultiBufferDiffHunk> {
13286 snapshot
13287 .buffer_snapshot
13288 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13289 .find(|hunk| hunk.row_range.start.0 > position.row)
13290 .or_else(|| {
13291 snapshot
13292 .buffer_snapshot
13293 .diff_hunks_in_range(Point::zero()..position)
13294 .find(|hunk| hunk.row_range.end.0 < position.row)
13295 })
13296 }
13297
13298 fn go_to_prev_hunk(
13299 &mut self,
13300 _: &GoToPreviousHunk,
13301 window: &mut Window,
13302 cx: &mut Context<Self>,
13303 ) {
13304 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13305 let snapshot = self.snapshot(window, cx);
13306 let selection = self.selections.newest::<Point>(cx);
13307 self.go_to_hunk_before_or_after_position(
13308 &snapshot,
13309 selection.head(),
13310 Direction::Prev,
13311 window,
13312 cx,
13313 );
13314 }
13315
13316 fn hunk_before_position(
13317 &mut self,
13318 snapshot: &EditorSnapshot,
13319 position: Point,
13320 ) -> Option<MultiBufferRow> {
13321 snapshot
13322 .buffer_snapshot
13323 .diff_hunk_before(position)
13324 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13325 }
13326
13327 fn go_to_line<T: 'static>(
13328 &mut self,
13329 position: Anchor,
13330 highlight_color: Option<Hsla>,
13331 window: &mut Window,
13332 cx: &mut Context<Self>,
13333 ) {
13334 let snapshot = self.snapshot(window, cx).display_snapshot;
13335 let position = position.to_point(&snapshot.buffer_snapshot);
13336 let start = snapshot
13337 .buffer_snapshot
13338 .clip_point(Point::new(position.row, 0), Bias::Left);
13339 let end = start + Point::new(1, 0);
13340 let start = snapshot.buffer_snapshot.anchor_before(start);
13341 let end = snapshot.buffer_snapshot.anchor_before(end);
13342
13343 self.highlight_rows::<T>(
13344 start..end,
13345 highlight_color
13346 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13347 false,
13348 cx,
13349 );
13350 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13351 }
13352
13353 pub fn go_to_definition(
13354 &mut self,
13355 _: &GoToDefinition,
13356 window: &mut Window,
13357 cx: &mut Context<Self>,
13358 ) -> Task<Result<Navigated>> {
13359 let definition =
13360 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13361 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13362 cx.spawn_in(window, async move |editor, cx| {
13363 if definition.await? == Navigated::Yes {
13364 return Ok(Navigated::Yes);
13365 }
13366 match fallback_strategy {
13367 GoToDefinitionFallback::None => Ok(Navigated::No),
13368 GoToDefinitionFallback::FindAllReferences => {
13369 match editor.update_in(cx, |editor, window, cx| {
13370 editor.find_all_references(&FindAllReferences, window, cx)
13371 })? {
13372 Some(references) => references.await,
13373 None => Ok(Navigated::No),
13374 }
13375 }
13376 }
13377 })
13378 }
13379
13380 pub fn go_to_declaration(
13381 &mut self,
13382 _: &GoToDeclaration,
13383 window: &mut Window,
13384 cx: &mut Context<Self>,
13385 ) -> Task<Result<Navigated>> {
13386 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13387 }
13388
13389 pub fn go_to_declaration_split(
13390 &mut self,
13391 _: &GoToDeclaration,
13392 window: &mut Window,
13393 cx: &mut Context<Self>,
13394 ) -> Task<Result<Navigated>> {
13395 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13396 }
13397
13398 pub fn go_to_implementation(
13399 &mut self,
13400 _: &GoToImplementation,
13401 window: &mut Window,
13402 cx: &mut Context<Self>,
13403 ) -> Task<Result<Navigated>> {
13404 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13405 }
13406
13407 pub fn go_to_implementation_split(
13408 &mut self,
13409 _: &GoToImplementationSplit,
13410 window: &mut Window,
13411 cx: &mut Context<Self>,
13412 ) -> Task<Result<Navigated>> {
13413 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13414 }
13415
13416 pub fn go_to_type_definition(
13417 &mut self,
13418 _: &GoToTypeDefinition,
13419 window: &mut Window,
13420 cx: &mut Context<Self>,
13421 ) -> Task<Result<Navigated>> {
13422 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13423 }
13424
13425 pub fn go_to_definition_split(
13426 &mut self,
13427 _: &GoToDefinitionSplit,
13428 window: &mut Window,
13429 cx: &mut Context<Self>,
13430 ) -> Task<Result<Navigated>> {
13431 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13432 }
13433
13434 pub fn go_to_type_definition_split(
13435 &mut self,
13436 _: &GoToTypeDefinitionSplit,
13437 window: &mut Window,
13438 cx: &mut Context<Self>,
13439 ) -> Task<Result<Navigated>> {
13440 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13441 }
13442
13443 fn go_to_definition_of_kind(
13444 &mut self,
13445 kind: GotoDefinitionKind,
13446 split: bool,
13447 window: &mut Window,
13448 cx: &mut Context<Self>,
13449 ) -> Task<Result<Navigated>> {
13450 let Some(provider) = self.semantics_provider.clone() else {
13451 return Task::ready(Ok(Navigated::No));
13452 };
13453 let head = self.selections.newest::<usize>(cx).head();
13454 let buffer = self.buffer.read(cx);
13455 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13456 text_anchor
13457 } else {
13458 return Task::ready(Ok(Navigated::No));
13459 };
13460
13461 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13462 return Task::ready(Ok(Navigated::No));
13463 };
13464
13465 cx.spawn_in(window, async move |editor, cx| {
13466 let definitions = definitions.await?;
13467 let navigated = editor
13468 .update_in(cx, |editor, window, cx| {
13469 editor.navigate_to_hover_links(
13470 Some(kind),
13471 definitions
13472 .into_iter()
13473 .filter(|location| {
13474 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13475 })
13476 .map(HoverLink::Text)
13477 .collect::<Vec<_>>(),
13478 split,
13479 window,
13480 cx,
13481 )
13482 })?
13483 .await?;
13484 anyhow::Ok(navigated)
13485 })
13486 }
13487
13488 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13489 let selection = self.selections.newest_anchor();
13490 let head = selection.head();
13491 let tail = selection.tail();
13492
13493 let Some((buffer, start_position)) =
13494 self.buffer.read(cx).text_anchor_for_position(head, cx)
13495 else {
13496 return;
13497 };
13498
13499 let end_position = if head != tail {
13500 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13501 return;
13502 };
13503 Some(pos)
13504 } else {
13505 None
13506 };
13507
13508 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13509 let url = if let Some(end_pos) = end_position {
13510 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13511 } else {
13512 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13513 };
13514
13515 if let Some(url) = url {
13516 editor.update(cx, |_, cx| {
13517 cx.open_url(&url);
13518 })
13519 } else {
13520 Ok(())
13521 }
13522 });
13523
13524 url_finder.detach();
13525 }
13526
13527 pub fn open_selected_filename(
13528 &mut self,
13529 _: &OpenSelectedFilename,
13530 window: &mut Window,
13531 cx: &mut Context<Self>,
13532 ) {
13533 let Some(workspace) = self.workspace() else {
13534 return;
13535 };
13536
13537 let position = self.selections.newest_anchor().head();
13538
13539 let Some((buffer, buffer_position)) =
13540 self.buffer.read(cx).text_anchor_for_position(position, cx)
13541 else {
13542 return;
13543 };
13544
13545 let project = self.project.clone();
13546
13547 cx.spawn_in(window, async move |_, cx| {
13548 let result = find_file(&buffer, project, buffer_position, cx).await;
13549
13550 if let Some((_, path)) = result {
13551 workspace
13552 .update_in(cx, |workspace, window, cx| {
13553 workspace.open_resolved_path(path, window, cx)
13554 })?
13555 .await?;
13556 }
13557 anyhow::Ok(())
13558 })
13559 .detach();
13560 }
13561
13562 pub(crate) fn navigate_to_hover_links(
13563 &mut self,
13564 kind: Option<GotoDefinitionKind>,
13565 mut definitions: Vec<HoverLink>,
13566 split: bool,
13567 window: &mut Window,
13568 cx: &mut Context<Editor>,
13569 ) -> Task<Result<Navigated>> {
13570 // If there is one definition, just open it directly
13571 if definitions.len() == 1 {
13572 let definition = definitions.pop().unwrap();
13573
13574 enum TargetTaskResult {
13575 Location(Option<Location>),
13576 AlreadyNavigated,
13577 }
13578
13579 let target_task = match definition {
13580 HoverLink::Text(link) => {
13581 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13582 }
13583 HoverLink::InlayHint(lsp_location, server_id) => {
13584 let computation =
13585 self.compute_target_location(lsp_location, server_id, window, cx);
13586 cx.background_spawn(async move {
13587 let location = computation.await?;
13588 Ok(TargetTaskResult::Location(location))
13589 })
13590 }
13591 HoverLink::Url(url) => {
13592 cx.open_url(&url);
13593 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13594 }
13595 HoverLink::File(path) => {
13596 if let Some(workspace) = self.workspace() {
13597 cx.spawn_in(window, async move |_, cx| {
13598 workspace
13599 .update_in(cx, |workspace, window, cx| {
13600 workspace.open_resolved_path(path, window, cx)
13601 })?
13602 .await
13603 .map(|_| TargetTaskResult::AlreadyNavigated)
13604 })
13605 } else {
13606 Task::ready(Ok(TargetTaskResult::Location(None)))
13607 }
13608 }
13609 };
13610 cx.spawn_in(window, async move |editor, cx| {
13611 let target = match target_task.await.context("target resolution task")? {
13612 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13613 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13614 TargetTaskResult::Location(Some(target)) => target,
13615 };
13616
13617 editor.update_in(cx, |editor, window, cx| {
13618 let Some(workspace) = editor.workspace() else {
13619 return Navigated::No;
13620 };
13621 let pane = workspace.read(cx).active_pane().clone();
13622
13623 let range = target.range.to_point(target.buffer.read(cx));
13624 let range = editor.range_for_match(&range);
13625 let range = collapse_multiline_range(range);
13626
13627 if !split
13628 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13629 {
13630 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13631 } else {
13632 window.defer(cx, move |window, cx| {
13633 let target_editor: Entity<Self> =
13634 workspace.update(cx, |workspace, cx| {
13635 let pane = if split {
13636 workspace.adjacent_pane(window, cx)
13637 } else {
13638 workspace.active_pane().clone()
13639 };
13640
13641 workspace.open_project_item(
13642 pane,
13643 target.buffer.clone(),
13644 true,
13645 true,
13646 window,
13647 cx,
13648 )
13649 });
13650 target_editor.update(cx, |target_editor, cx| {
13651 // When selecting a definition in a different buffer, disable the nav history
13652 // to avoid creating a history entry at the previous cursor location.
13653 pane.update(cx, |pane, _| pane.disable_history());
13654 target_editor.go_to_singleton_buffer_range(range, window, cx);
13655 pane.update(cx, |pane, _| pane.enable_history());
13656 });
13657 });
13658 }
13659 Navigated::Yes
13660 })
13661 })
13662 } else if !definitions.is_empty() {
13663 cx.spawn_in(window, async move |editor, cx| {
13664 let (title, location_tasks, workspace) = editor
13665 .update_in(cx, |editor, window, cx| {
13666 let tab_kind = match kind {
13667 Some(GotoDefinitionKind::Implementation) => "Implementations",
13668 _ => "Definitions",
13669 };
13670 let title = definitions
13671 .iter()
13672 .find_map(|definition| match definition {
13673 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13674 let buffer = origin.buffer.read(cx);
13675 format!(
13676 "{} for {}",
13677 tab_kind,
13678 buffer
13679 .text_for_range(origin.range.clone())
13680 .collect::<String>()
13681 )
13682 }),
13683 HoverLink::InlayHint(_, _) => None,
13684 HoverLink::Url(_) => None,
13685 HoverLink::File(_) => None,
13686 })
13687 .unwrap_or(tab_kind.to_string());
13688 let location_tasks = definitions
13689 .into_iter()
13690 .map(|definition| match definition {
13691 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13692 HoverLink::InlayHint(lsp_location, server_id) => editor
13693 .compute_target_location(lsp_location, server_id, window, cx),
13694 HoverLink::Url(_) => Task::ready(Ok(None)),
13695 HoverLink::File(_) => Task::ready(Ok(None)),
13696 })
13697 .collect::<Vec<_>>();
13698 (title, location_tasks, editor.workspace().clone())
13699 })
13700 .context("location tasks preparation")?;
13701
13702 let locations = future::join_all(location_tasks)
13703 .await
13704 .into_iter()
13705 .filter_map(|location| location.transpose())
13706 .collect::<Result<_>>()
13707 .context("location tasks")?;
13708
13709 let Some(workspace) = workspace else {
13710 return Ok(Navigated::No);
13711 };
13712 let opened = workspace
13713 .update_in(cx, |workspace, window, cx| {
13714 Self::open_locations_in_multibuffer(
13715 workspace,
13716 locations,
13717 title,
13718 split,
13719 MultibufferSelectionMode::First,
13720 window,
13721 cx,
13722 )
13723 })
13724 .ok();
13725
13726 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13727 })
13728 } else {
13729 Task::ready(Ok(Navigated::No))
13730 }
13731 }
13732
13733 fn compute_target_location(
13734 &self,
13735 lsp_location: lsp::Location,
13736 server_id: LanguageServerId,
13737 window: &mut Window,
13738 cx: &mut Context<Self>,
13739 ) -> Task<anyhow::Result<Option<Location>>> {
13740 let Some(project) = self.project.clone() else {
13741 return Task::ready(Ok(None));
13742 };
13743
13744 cx.spawn_in(window, async move |editor, cx| {
13745 let location_task = editor.update(cx, |_, cx| {
13746 project.update(cx, |project, cx| {
13747 let language_server_name = project
13748 .language_server_statuses(cx)
13749 .find(|(id, _)| server_id == *id)
13750 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13751 language_server_name.map(|language_server_name| {
13752 project.open_local_buffer_via_lsp(
13753 lsp_location.uri.clone(),
13754 server_id,
13755 language_server_name,
13756 cx,
13757 )
13758 })
13759 })
13760 })?;
13761 let location = match location_task {
13762 Some(task) => Some({
13763 let target_buffer_handle = task.await.context("open local buffer")?;
13764 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13765 let target_start = target_buffer
13766 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13767 let target_end = target_buffer
13768 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13769 target_buffer.anchor_after(target_start)
13770 ..target_buffer.anchor_before(target_end)
13771 })?;
13772 Location {
13773 buffer: target_buffer_handle,
13774 range,
13775 }
13776 }),
13777 None => None,
13778 };
13779 Ok(location)
13780 })
13781 }
13782
13783 pub fn find_all_references(
13784 &mut self,
13785 _: &FindAllReferences,
13786 window: &mut Window,
13787 cx: &mut Context<Self>,
13788 ) -> Option<Task<Result<Navigated>>> {
13789 let selection = self.selections.newest::<usize>(cx);
13790 let multi_buffer = self.buffer.read(cx);
13791 let head = selection.head();
13792
13793 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13794 let head_anchor = multi_buffer_snapshot.anchor_at(
13795 head,
13796 if head < selection.tail() {
13797 Bias::Right
13798 } else {
13799 Bias::Left
13800 },
13801 );
13802
13803 match self
13804 .find_all_references_task_sources
13805 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13806 {
13807 Ok(_) => {
13808 log::info!(
13809 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13810 );
13811 return None;
13812 }
13813 Err(i) => {
13814 self.find_all_references_task_sources.insert(i, head_anchor);
13815 }
13816 }
13817
13818 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13819 let workspace = self.workspace()?;
13820 let project = workspace.read(cx).project().clone();
13821 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13822 Some(cx.spawn_in(window, async move |editor, cx| {
13823 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13824 if let Ok(i) = editor
13825 .find_all_references_task_sources
13826 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13827 {
13828 editor.find_all_references_task_sources.remove(i);
13829 }
13830 });
13831
13832 let locations = references.await?;
13833 if locations.is_empty() {
13834 return anyhow::Ok(Navigated::No);
13835 }
13836
13837 workspace.update_in(cx, |workspace, window, cx| {
13838 let title = locations
13839 .first()
13840 .as_ref()
13841 .map(|location| {
13842 let buffer = location.buffer.read(cx);
13843 format!(
13844 "References to `{}`",
13845 buffer
13846 .text_for_range(location.range.clone())
13847 .collect::<String>()
13848 )
13849 })
13850 .unwrap();
13851 Self::open_locations_in_multibuffer(
13852 workspace,
13853 locations,
13854 title,
13855 false,
13856 MultibufferSelectionMode::First,
13857 window,
13858 cx,
13859 );
13860 Navigated::Yes
13861 })
13862 }))
13863 }
13864
13865 /// Opens a multibuffer with the given project locations in it
13866 pub fn open_locations_in_multibuffer(
13867 workspace: &mut Workspace,
13868 mut locations: Vec<Location>,
13869 title: String,
13870 split: bool,
13871 multibuffer_selection_mode: MultibufferSelectionMode,
13872 window: &mut Window,
13873 cx: &mut Context<Workspace>,
13874 ) {
13875 // If there are multiple definitions, open them in a multibuffer
13876 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13877 let mut locations = locations.into_iter().peekable();
13878 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13879 let capability = workspace.project().read(cx).capability();
13880
13881 let excerpt_buffer = cx.new(|cx| {
13882 let mut multibuffer = MultiBuffer::new(capability);
13883 while let Some(location) = locations.next() {
13884 let buffer = location.buffer.read(cx);
13885 let mut ranges_for_buffer = Vec::new();
13886 let range = location.range.to_point(buffer);
13887 ranges_for_buffer.push(range.clone());
13888
13889 while let Some(next_location) = locations.peek() {
13890 if next_location.buffer == location.buffer {
13891 ranges_for_buffer.push(next_location.range.to_point(buffer));
13892 locations.next();
13893 } else {
13894 break;
13895 }
13896 }
13897
13898 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13899 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13900 PathKey::for_buffer(&location.buffer, cx),
13901 location.buffer.clone(),
13902 ranges_for_buffer,
13903 DEFAULT_MULTIBUFFER_CONTEXT,
13904 cx,
13905 );
13906 ranges.extend(new_ranges)
13907 }
13908
13909 multibuffer.with_title(title)
13910 });
13911
13912 let editor = cx.new(|cx| {
13913 Editor::for_multibuffer(
13914 excerpt_buffer,
13915 Some(workspace.project().clone()),
13916 window,
13917 cx,
13918 )
13919 });
13920 editor.update(cx, |editor, cx| {
13921 match multibuffer_selection_mode {
13922 MultibufferSelectionMode::First => {
13923 if let Some(first_range) = ranges.first() {
13924 editor.change_selections(None, window, cx, |selections| {
13925 selections.clear_disjoint();
13926 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13927 });
13928 }
13929 editor.highlight_background::<Self>(
13930 &ranges,
13931 |theme| theme.editor_highlighted_line_background,
13932 cx,
13933 );
13934 }
13935 MultibufferSelectionMode::All => {
13936 editor.change_selections(None, window, cx, |selections| {
13937 selections.clear_disjoint();
13938 selections.select_anchor_ranges(ranges);
13939 });
13940 }
13941 }
13942 editor.register_buffers_with_language_servers(cx);
13943 });
13944
13945 let item = Box::new(editor);
13946 let item_id = item.item_id();
13947
13948 if split {
13949 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13950 } else {
13951 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13952 let (preview_item_id, preview_item_idx) =
13953 workspace.active_pane().update(cx, |pane, _| {
13954 (pane.preview_item_id(), pane.preview_item_idx())
13955 });
13956
13957 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13958
13959 if let Some(preview_item_id) = preview_item_id {
13960 workspace.active_pane().update(cx, |pane, cx| {
13961 pane.remove_item(preview_item_id, false, false, window, cx);
13962 });
13963 }
13964 } else {
13965 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13966 }
13967 }
13968 workspace.active_pane().update(cx, |pane, cx| {
13969 pane.set_preview_item_id(Some(item_id), cx);
13970 });
13971 }
13972
13973 pub fn rename(
13974 &mut self,
13975 _: &Rename,
13976 window: &mut Window,
13977 cx: &mut Context<Self>,
13978 ) -> Option<Task<Result<()>>> {
13979 use language::ToOffset as _;
13980
13981 let provider = self.semantics_provider.clone()?;
13982 let selection = self.selections.newest_anchor().clone();
13983 let (cursor_buffer, cursor_buffer_position) = self
13984 .buffer
13985 .read(cx)
13986 .text_anchor_for_position(selection.head(), cx)?;
13987 let (tail_buffer, cursor_buffer_position_end) = self
13988 .buffer
13989 .read(cx)
13990 .text_anchor_for_position(selection.tail(), cx)?;
13991 if tail_buffer != cursor_buffer {
13992 return None;
13993 }
13994
13995 let snapshot = cursor_buffer.read(cx).snapshot();
13996 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13997 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13998 let prepare_rename = provider
13999 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14000 .unwrap_or_else(|| Task::ready(Ok(None)));
14001 drop(snapshot);
14002
14003 Some(cx.spawn_in(window, async move |this, cx| {
14004 let rename_range = if let Some(range) = prepare_rename.await? {
14005 Some(range)
14006 } else {
14007 this.update(cx, |this, cx| {
14008 let buffer = this.buffer.read(cx).snapshot(cx);
14009 let mut buffer_highlights = this
14010 .document_highlights_for_position(selection.head(), &buffer)
14011 .filter(|highlight| {
14012 highlight.start.excerpt_id == selection.head().excerpt_id
14013 && highlight.end.excerpt_id == selection.head().excerpt_id
14014 });
14015 buffer_highlights
14016 .next()
14017 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14018 })?
14019 };
14020 if let Some(rename_range) = rename_range {
14021 this.update_in(cx, |this, window, cx| {
14022 let snapshot = cursor_buffer.read(cx).snapshot();
14023 let rename_buffer_range = rename_range.to_offset(&snapshot);
14024 let cursor_offset_in_rename_range =
14025 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14026 let cursor_offset_in_rename_range_end =
14027 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14028
14029 this.take_rename(false, window, cx);
14030 let buffer = this.buffer.read(cx).read(cx);
14031 let cursor_offset = selection.head().to_offset(&buffer);
14032 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14033 let rename_end = rename_start + rename_buffer_range.len();
14034 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14035 let mut old_highlight_id = None;
14036 let old_name: Arc<str> = buffer
14037 .chunks(rename_start..rename_end, true)
14038 .map(|chunk| {
14039 if old_highlight_id.is_none() {
14040 old_highlight_id = chunk.syntax_highlight_id;
14041 }
14042 chunk.text
14043 })
14044 .collect::<String>()
14045 .into();
14046
14047 drop(buffer);
14048
14049 // Position the selection in the rename editor so that it matches the current selection.
14050 this.show_local_selections = false;
14051 let rename_editor = cx.new(|cx| {
14052 let mut editor = Editor::single_line(window, cx);
14053 editor.buffer.update(cx, |buffer, cx| {
14054 buffer.edit([(0..0, old_name.clone())], None, cx)
14055 });
14056 let rename_selection_range = match cursor_offset_in_rename_range
14057 .cmp(&cursor_offset_in_rename_range_end)
14058 {
14059 Ordering::Equal => {
14060 editor.select_all(&SelectAll, window, cx);
14061 return editor;
14062 }
14063 Ordering::Less => {
14064 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14065 }
14066 Ordering::Greater => {
14067 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14068 }
14069 };
14070 if rename_selection_range.end > old_name.len() {
14071 editor.select_all(&SelectAll, window, cx);
14072 } else {
14073 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14074 s.select_ranges([rename_selection_range]);
14075 });
14076 }
14077 editor
14078 });
14079 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14080 if e == &EditorEvent::Focused {
14081 cx.emit(EditorEvent::FocusedIn)
14082 }
14083 })
14084 .detach();
14085
14086 let write_highlights =
14087 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14088 let read_highlights =
14089 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14090 let ranges = write_highlights
14091 .iter()
14092 .flat_map(|(_, ranges)| ranges.iter())
14093 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14094 .cloned()
14095 .collect();
14096
14097 this.highlight_text::<Rename>(
14098 ranges,
14099 HighlightStyle {
14100 fade_out: Some(0.6),
14101 ..Default::default()
14102 },
14103 cx,
14104 );
14105 let rename_focus_handle = rename_editor.focus_handle(cx);
14106 window.focus(&rename_focus_handle);
14107 let block_id = this.insert_blocks(
14108 [BlockProperties {
14109 style: BlockStyle::Flex,
14110 placement: BlockPlacement::Below(range.start),
14111 height: Some(1),
14112 render: Arc::new({
14113 let rename_editor = rename_editor.clone();
14114 move |cx: &mut BlockContext| {
14115 let mut text_style = cx.editor_style.text.clone();
14116 if let Some(highlight_style) = old_highlight_id
14117 .and_then(|h| h.style(&cx.editor_style.syntax))
14118 {
14119 text_style = text_style.highlight(highlight_style);
14120 }
14121 div()
14122 .block_mouse_down()
14123 .pl(cx.anchor_x)
14124 .child(EditorElement::new(
14125 &rename_editor,
14126 EditorStyle {
14127 background: cx.theme().system().transparent,
14128 local_player: cx.editor_style.local_player,
14129 text: text_style,
14130 scrollbar_width: cx.editor_style.scrollbar_width,
14131 syntax: cx.editor_style.syntax.clone(),
14132 status: cx.editor_style.status.clone(),
14133 inlay_hints_style: HighlightStyle {
14134 font_weight: Some(FontWeight::BOLD),
14135 ..make_inlay_hints_style(cx.app)
14136 },
14137 inline_completion_styles: make_suggestion_styles(
14138 cx.app,
14139 ),
14140 ..EditorStyle::default()
14141 },
14142 ))
14143 .into_any_element()
14144 }
14145 }),
14146 priority: 0,
14147 }],
14148 Some(Autoscroll::fit()),
14149 cx,
14150 )[0];
14151 this.pending_rename = Some(RenameState {
14152 range,
14153 old_name,
14154 editor: rename_editor,
14155 block_id,
14156 });
14157 })?;
14158 }
14159
14160 Ok(())
14161 }))
14162 }
14163
14164 pub fn confirm_rename(
14165 &mut self,
14166 _: &ConfirmRename,
14167 window: &mut Window,
14168 cx: &mut Context<Self>,
14169 ) -> Option<Task<Result<()>>> {
14170 let rename = self.take_rename(false, window, cx)?;
14171 let workspace = self.workspace()?.downgrade();
14172 let (buffer, start) = self
14173 .buffer
14174 .read(cx)
14175 .text_anchor_for_position(rename.range.start, cx)?;
14176 let (end_buffer, _) = self
14177 .buffer
14178 .read(cx)
14179 .text_anchor_for_position(rename.range.end, cx)?;
14180 if buffer != end_buffer {
14181 return None;
14182 }
14183
14184 let old_name = rename.old_name;
14185 let new_name = rename.editor.read(cx).text(cx);
14186
14187 let rename = self.semantics_provider.as_ref()?.perform_rename(
14188 &buffer,
14189 start,
14190 new_name.clone(),
14191 cx,
14192 )?;
14193
14194 Some(cx.spawn_in(window, async move |editor, cx| {
14195 let project_transaction = rename.await?;
14196 Self::open_project_transaction(
14197 &editor,
14198 workspace,
14199 project_transaction,
14200 format!("Rename: {} → {}", old_name, new_name),
14201 cx,
14202 )
14203 .await?;
14204
14205 editor.update(cx, |editor, cx| {
14206 editor.refresh_document_highlights(cx);
14207 })?;
14208 Ok(())
14209 }))
14210 }
14211
14212 fn take_rename(
14213 &mut self,
14214 moving_cursor: bool,
14215 window: &mut Window,
14216 cx: &mut Context<Self>,
14217 ) -> Option<RenameState> {
14218 let rename = self.pending_rename.take()?;
14219 if rename.editor.focus_handle(cx).is_focused(window) {
14220 window.focus(&self.focus_handle);
14221 }
14222
14223 self.remove_blocks(
14224 [rename.block_id].into_iter().collect(),
14225 Some(Autoscroll::fit()),
14226 cx,
14227 );
14228 self.clear_highlights::<Rename>(cx);
14229 self.show_local_selections = true;
14230
14231 if moving_cursor {
14232 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14233 editor.selections.newest::<usize>(cx).head()
14234 });
14235
14236 // Update the selection to match the position of the selection inside
14237 // the rename editor.
14238 let snapshot = self.buffer.read(cx).read(cx);
14239 let rename_range = rename.range.to_offset(&snapshot);
14240 let cursor_in_editor = snapshot
14241 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14242 .min(rename_range.end);
14243 drop(snapshot);
14244
14245 self.change_selections(None, window, cx, |s| {
14246 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14247 });
14248 } else {
14249 self.refresh_document_highlights(cx);
14250 }
14251
14252 Some(rename)
14253 }
14254
14255 pub fn pending_rename(&self) -> Option<&RenameState> {
14256 self.pending_rename.as_ref()
14257 }
14258
14259 fn format(
14260 &mut self,
14261 _: &Format,
14262 window: &mut Window,
14263 cx: &mut Context<Self>,
14264 ) -> Option<Task<Result<()>>> {
14265 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14266
14267 let project = match &self.project {
14268 Some(project) => project.clone(),
14269 None => return None,
14270 };
14271
14272 Some(self.perform_format(
14273 project,
14274 FormatTrigger::Manual,
14275 FormatTarget::Buffers,
14276 window,
14277 cx,
14278 ))
14279 }
14280
14281 fn format_selections(
14282 &mut self,
14283 _: &FormatSelections,
14284 window: &mut Window,
14285 cx: &mut Context<Self>,
14286 ) -> Option<Task<Result<()>>> {
14287 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14288
14289 let project = match &self.project {
14290 Some(project) => project.clone(),
14291 None => return None,
14292 };
14293
14294 let ranges = self
14295 .selections
14296 .all_adjusted(cx)
14297 .into_iter()
14298 .map(|selection| selection.range())
14299 .collect_vec();
14300
14301 Some(self.perform_format(
14302 project,
14303 FormatTrigger::Manual,
14304 FormatTarget::Ranges(ranges),
14305 window,
14306 cx,
14307 ))
14308 }
14309
14310 fn perform_format(
14311 &mut self,
14312 project: Entity<Project>,
14313 trigger: FormatTrigger,
14314 target: FormatTarget,
14315 window: &mut Window,
14316 cx: &mut Context<Self>,
14317 ) -> Task<Result<()>> {
14318 let buffer = self.buffer.clone();
14319 let (buffers, target) = match target {
14320 FormatTarget::Buffers => {
14321 let mut buffers = buffer.read(cx).all_buffers();
14322 if trigger == FormatTrigger::Save {
14323 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14324 }
14325 (buffers, LspFormatTarget::Buffers)
14326 }
14327 FormatTarget::Ranges(selection_ranges) => {
14328 let multi_buffer = buffer.read(cx);
14329 let snapshot = multi_buffer.read(cx);
14330 let mut buffers = HashSet::default();
14331 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14332 BTreeMap::new();
14333 for selection_range in selection_ranges {
14334 for (buffer, buffer_range, _) in
14335 snapshot.range_to_buffer_ranges(selection_range)
14336 {
14337 let buffer_id = buffer.remote_id();
14338 let start = buffer.anchor_before(buffer_range.start);
14339 let end = buffer.anchor_after(buffer_range.end);
14340 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14341 buffer_id_to_ranges
14342 .entry(buffer_id)
14343 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14344 .or_insert_with(|| vec![start..end]);
14345 }
14346 }
14347 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14348 }
14349 };
14350
14351 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14352 let selections_prev = transaction_id_prev
14353 .and_then(|transaction_id_prev| {
14354 // default to selections as they were after the last edit, if we have them,
14355 // instead of how they are now.
14356 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14357 // will take you back to where you made the last edit, instead of staying where you scrolled
14358 self.selection_history
14359 .transaction(transaction_id_prev)
14360 .map(|t| t.0.clone())
14361 })
14362 .unwrap_or_else(|| {
14363 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14364 self.selections.disjoint_anchors()
14365 });
14366
14367 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14368 let format = project.update(cx, |project, cx| {
14369 project.format(buffers, target, true, trigger, cx)
14370 });
14371
14372 cx.spawn_in(window, async move |editor, cx| {
14373 let transaction = futures::select_biased! {
14374 transaction = format.log_err().fuse() => transaction,
14375 () = timeout => {
14376 log::warn!("timed out waiting for formatting");
14377 None
14378 }
14379 };
14380
14381 buffer
14382 .update(cx, |buffer, cx| {
14383 if let Some(transaction) = transaction {
14384 if !buffer.is_singleton() {
14385 buffer.push_transaction(&transaction.0, cx);
14386 }
14387 }
14388 cx.notify();
14389 })
14390 .ok();
14391
14392 if let Some(transaction_id_now) =
14393 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14394 {
14395 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14396 if has_new_transaction {
14397 _ = editor.update(cx, |editor, _| {
14398 editor
14399 .selection_history
14400 .insert_transaction(transaction_id_now, selections_prev);
14401 });
14402 }
14403 }
14404
14405 Ok(())
14406 })
14407 }
14408
14409 fn organize_imports(
14410 &mut self,
14411 _: &OrganizeImports,
14412 window: &mut Window,
14413 cx: &mut Context<Self>,
14414 ) -> Option<Task<Result<()>>> {
14415 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14416 let project = match &self.project {
14417 Some(project) => project.clone(),
14418 None => return None,
14419 };
14420 Some(self.perform_code_action_kind(
14421 project,
14422 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14423 window,
14424 cx,
14425 ))
14426 }
14427
14428 fn perform_code_action_kind(
14429 &mut self,
14430 project: Entity<Project>,
14431 kind: CodeActionKind,
14432 window: &mut Window,
14433 cx: &mut Context<Self>,
14434 ) -> Task<Result<()>> {
14435 let buffer = self.buffer.clone();
14436 let buffers = buffer.read(cx).all_buffers();
14437 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14438 let apply_action = project.update(cx, |project, cx| {
14439 project.apply_code_action_kind(buffers, kind, true, cx)
14440 });
14441 cx.spawn_in(window, async move |_, cx| {
14442 let transaction = futures::select_biased! {
14443 () = timeout => {
14444 log::warn!("timed out waiting for executing code action");
14445 None
14446 }
14447 transaction = apply_action.log_err().fuse() => transaction,
14448 };
14449 buffer
14450 .update(cx, |buffer, cx| {
14451 // check if we need this
14452 if let Some(transaction) = transaction {
14453 if !buffer.is_singleton() {
14454 buffer.push_transaction(&transaction.0, cx);
14455 }
14456 }
14457 cx.notify();
14458 })
14459 .ok();
14460 Ok(())
14461 })
14462 }
14463
14464 fn restart_language_server(
14465 &mut self,
14466 _: &RestartLanguageServer,
14467 _: &mut Window,
14468 cx: &mut Context<Self>,
14469 ) {
14470 if let Some(project) = self.project.clone() {
14471 self.buffer.update(cx, |multi_buffer, cx| {
14472 project.update(cx, |project, cx| {
14473 project.restart_language_servers_for_buffers(
14474 multi_buffer.all_buffers().into_iter().collect(),
14475 cx,
14476 );
14477 });
14478 })
14479 }
14480 }
14481
14482 fn stop_language_server(
14483 &mut self,
14484 _: &StopLanguageServer,
14485 _: &mut Window,
14486 cx: &mut Context<Self>,
14487 ) {
14488 if let Some(project) = self.project.clone() {
14489 self.buffer.update(cx, |multi_buffer, cx| {
14490 project.update(cx, |project, cx| {
14491 project.stop_language_servers_for_buffers(
14492 multi_buffer.all_buffers().into_iter().collect(),
14493 cx,
14494 );
14495 cx.emit(project::Event::RefreshInlayHints);
14496 });
14497 });
14498 }
14499 }
14500
14501 fn cancel_language_server_work(
14502 workspace: &mut Workspace,
14503 _: &actions::CancelLanguageServerWork,
14504 _: &mut Window,
14505 cx: &mut Context<Workspace>,
14506 ) {
14507 let project = workspace.project();
14508 let buffers = workspace
14509 .active_item(cx)
14510 .and_then(|item| item.act_as::<Editor>(cx))
14511 .map_or(HashSet::default(), |editor| {
14512 editor.read(cx).buffer.read(cx).all_buffers()
14513 });
14514 project.update(cx, |project, cx| {
14515 project.cancel_language_server_work_for_buffers(buffers, cx);
14516 });
14517 }
14518
14519 fn show_character_palette(
14520 &mut self,
14521 _: &ShowCharacterPalette,
14522 window: &mut Window,
14523 _: &mut Context<Self>,
14524 ) {
14525 window.show_character_palette();
14526 }
14527
14528 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14529 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14530 let buffer = self.buffer.read(cx).snapshot(cx);
14531 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14532 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14533 let is_valid = buffer
14534 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14535 .any(|entry| {
14536 entry.diagnostic.is_primary
14537 && !entry.range.is_empty()
14538 && entry.range.start == primary_range_start
14539 && entry.diagnostic.message == active_diagnostics.active_message
14540 });
14541
14542 if !is_valid {
14543 self.dismiss_diagnostics(cx);
14544 }
14545 }
14546 }
14547
14548 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14549 match &self.active_diagnostics {
14550 ActiveDiagnostic::Group(group) => Some(group),
14551 _ => None,
14552 }
14553 }
14554
14555 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14556 self.dismiss_diagnostics(cx);
14557 self.active_diagnostics = ActiveDiagnostic::All;
14558 }
14559
14560 fn activate_diagnostics(
14561 &mut self,
14562 buffer_id: BufferId,
14563 diagnostic: DiagnosticEntry<usize>,
14564 window: &mut Window,
14565 cx: &mut Context<Self>,
14566 ) {
14567 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14568 return;
14569 }
14570 self.dismiss_diagnostics(cx);
14571 let snapshot = self.snapshot(window, cx);
14572 let Some(diagnostic_renderer) = cx
14573 .try_global::<GlobalDiagnosticRenderer>()
14574 .map(|g| g.0.clone())
14575 else {
14576 return;
14577 };
14578 let buffer = self.buffer.read(cx).snapshot(cx);
14579
14580 let diagnostic_group = buffer
14581 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14582 .collect::<Vec<_>>();
14583
14584 let blocks = diagnostic_renderer.render_group(
14585 diagnostic_group,
14586 buffer_id,
14587 snapshot,
14588 cx.weak_entity(),
14589 cx,
14590 );
14591
14592 let blocks = self.display_map.update(cx, |display_map, cx| {
14593 display_map.insert_blocks(blocks, cx).into_iter().collect()
14594 });
14595 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14596 active_range: buffer.anchor_before(diagnostic.range.start)
14597 ..buffer.anchor_after(diagnostic.range.end),
14598 active_message: diagnostic.diagnostic.message.clone(),
14599 group_id: diagnostic.diagnostic.group_id,
14600 blocks,
14601 });
14602 cx.notify();
14603 }
14604
14605 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14606 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14607 return;
14608 };
14609
14610 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14611 if let ActiveDiagnostic::Group(group) = prev {
14612 self.display_map.update(cx, |display_map, cx| {
14613 display_map.remove_blocks(group.blocks, cx);
14614 });
14615 cx.notify();
14616 }
14617 }
14618
14619 /// Disable inline diagnostics rendering for this editor.
14620 pub fn disable_inline_diagnostics(&mut self) {
14621 self.inline_diagnostics_enabled = false;
14622 self.inline_diagnostics_update = Task::ready(());
14623 self.inline_diagnostics.clear();
14624 }
14625
14626 pub fn inline_diagnostics_enabled(&self) -> bool {
14627 self.inline_diagnostics_enabled
14628 }
14629
14630 pub fn show_inline_diagnostics(&self) -> bool {
14631 self.show_inline_diagnostics
14632 }
14633
14634 pub fn toggle_inline_diagnostics(
14635 &mut self,
14636 _: &ToggleInlineDiagnostics,
14637 window: &mut Window,
14638 cx: &mut Context<Editor>,
14639 ) {
14640 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14641 self.refresh_inline_diagnostics(false, window, cx);
14642 }
14643
14644 fn refresh_inline_diagnostics(
14645 &mut self,
14646 debounce: bool,
14647 window: &mut Window,
14648 cx: &mut Context<Self>,
14649 ) {
14650 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14651 self.inline_diagnostics_update = Task::ready(());
14652 self.inline_diagnostics.clear();
14653 return;
14654 }
14655
14656 let debounce_ms = ProjectSettings::get_global(cx)
14657 .diagnostics
14658 .inline
14659 .update_debounce_ms;
14660 let debounce = if debounce && debounce_ms > 0 {
14661 Some(Duration::from_millis(debounce_ms))
14662 } else {
14663 None
14664 };
14665 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14666 let editor = editor.upgrade().unwrap();
14667
14668 if let Some(debounce) = debounce {
14669 cx.background_executor().timer(debounce).await;
14670 }
14671 let Some(snapshot) = editor
14672 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14673 .ok()
14674 else {
14675 return;
14676 };
14677
14678 let new_inline_diagnostics = cx
14679 .background_spawn(async move {
14680 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14681 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14682 let message = diagnostic_entry
14683 .diagnostic
14684 .message
14685 .split_once('\n')
14686 .map(|(line, _)| line)
14687 .map(SharedString::new)
14688 .unwrap_or_else(|| {
14689 SharedString::from(diagnostic_entry.diagnostic.message)
14690 });
14691 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14692 let (Ok(i) | Err(i)) = inline_diagnostics
14693 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14694 inline_diagnostics.insert(
14695 i,
14696 (
14697 start_anchor,
14698 InlineDiagnostic {
14699 message,
14700 group_id: diagnostic_entry.diagnostic.group_id,
14701 start: diagnostic_entry.range.start.to_point(&snapshot),
14702 is_primary: diagnostic_entry.diagnostic.is_primary,
14703 severity: diagnostic_entry.diagnostic.severity,
14704 },
14705 ),
14706 );
14707 }
14708 inline_diagnostics
14709 })
14710 .await;
14711
14712 editor
14713 .update(cx, |editor, cx| {
14714 editor.inline_diagnostics = new_inline_diagnostics;
14715 cx.notify();
14716 })
14717 .ok();
14718 });
14719 }
14720
14721 pub fn set_selections_from_remote(
14722 &mut self,
14723 selections: Vec<Selection<Anchor>>,
14724 pending_selection: Option<Selection<Anchor>>,
14725 window: &mut Window,
14726 cx: &mut Context<Self>,
14727 ) {
14728 let old_cursor_position = self.selections.newest_anchor().head();
14729 self.selections.change_with(cx, |s| {
14730 s.select_anchors(selections);
14731 if let Some(pending_selection) = pending_selection {
14732 s.set_pending(pending_selection, SelectMode::Character);
14733 } else {
14734 s.clear_pending();
14735 }
14736 });
14737 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14738 }
14739
14740 fn push_to_selection_history(&mut self) {
14741 self.selection_history.push(SelectionHistoryEntry {
14742 selections: self.selections.disjoint_anchors(),
14743 select_next_state: self.select_next_state.clone(),
14744 select_prev_state: self.select_prev_state.clone(),
14745 add_selections_state: self.add_selections_state.clone(),
14746 });
14747 }
14748
14749 pub fn transact(
14750 &mut self,
14751 window: &mut Window,
14752 cx: &mut Context<Self>,
14753 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14754 ) -> Option<TransactionId> {
14755 self.start_transaction_at(Instant::now(), window, cx);
14756 update(self, window, cx);
14757 self.end_transaction_at(Instant::now(), cx)
14758 }
14759
14760 pub fn start_transaction_at(
14761 &mut self,
14762 now: Instant,
14763 window: &mut Window,
14764 cx: &mut Context<Self>,
14765 ) {
14766 self.end_selection(window, cx);
14767 if let Some(tx_id) = self
14768 .buffer
14769 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14770 {
14771 self.selection_history
14772 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14773 cx.emit(EditorEvent::TransactionBegun {
14774 transaction_id: tx_id,
14775 })
14776 }
14777 }
14778
14779 pub fn end_transaction_at(
14780 &mut self,
14781 now: Instant,
14782 cx: &mut Context<Self>,
14783 ) -> Option<TransactionId> {
14784 if let Some(transaction_id) = self
14785 .buffer
14786 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14787 {
14788 if let Some((_, end_selections)) =
14789 self.selection_history.transaction_mut(transaction_id)
14790 {
14791 *end_selections = Some(self.selections.disjoint_anchors());
14792 } else {
14793 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14794 }
14795
14796 cx.emit(EditorEvent::Edited { transaction_id });
14797 Some(transaction_id)
14798 } else {
14799 None
14800 }
14801 }
14802
14803 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14804 if self.selection_mark_mode {
14805 self.change_selections(None, window, cx, |s| {
14806 s.move_with(|_, sel| {
14807 sel.collapse_to(sel.head(), SelectionGoal::None);
14808 });
14809 })
14810 }
14811 self.selection_mark_mode = true;
14812 cx.notify();
14813 }
14814
14815 pub fn swap_selection_ends(
14816 &mut self,
14817 _: &actions::SwapSelectionEnds,
14818 window: &mut Window,
14819 cx: &mut Context<Self>,
14820 ) {
14821 self.change_selections(None, window, cx, |s| {
14822 s.move_with(|_, sel| {
14823 if sel.start != sel.end {
14824 sel.reversed = !sel.reversed
14825 }
14826 });
14827 });
14828 self.request_autoscroll(Autoscroll::newest(), cx);
14829 cx.notify();
14830 }
14831
14832 pub fn toggle_fold(
14833 &mut self,
14834 _: &actions::ToggleFold,
14835 window: &mut Window,
14836 cx: &mut Context<Self>,
14837 ) {
14838 if self.is_singleton(cx) {
14839 let selection = self.selections.newest::<Point>(cx);
14840
14841 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14842 let range = if selection.is_empty() {
14843 let point = selection.head().to_display_point(&display_map);
14844 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14845 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14846 .to_point(&display_map);
14847 start..end
14848 } else {
14849 selection.range()
14850 };
14851 if display_map.folds_in_range(range).next().is_some() {
14852 self.unfold_lines(&Default::default(), window, cx)
14853 } else {
14854 self.fold(&Default::default(), window, cx)
14855 }
14856 } else {
14857 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14858 let buffer_ids: HashSet<_> = self
14859 .selections
14860 .disjoint_anchor_ranges()
14861 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14862 .collect();
14863
14864 let should_unfold = buffer_ids
14865 .iter()
14866 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14867
14868 for buffer_id in buffer_ids {
14869 if should_unfold {
14870 self.unfold_buffer(buffer_id, cx);
14871 } else {
14872 self.fold_buffer(buffer_id, cx);
14873 }
14874 }
14875 }
14876 }
14877
14878 pub fn toggle_fold_recursive(
14879 &mut self,
14880 _: &actions::ToggleFoldRecursive,
14881 window: &mut Window,
14882 cx: &mut Context<Self>,
14883 ) {
14884 let selection = self.selections.newest::<Point>(cx);
14885
14886 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14887 let range = if selection.is_empty() {
14888 let point = selection.head().to_display_point(&display_map);
14889 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14890 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14891 .to_point(&display_map);
14892 start..end
14893 } else {
14894 selection.range()
14895 };
14896 if display_map.folds_in_range(range).next().is_some() {
14897 self.unfold_recursive(&Default::default(), window, cx)
14898 } else {
14899 self.fold_recursive(&Default::default(), window, cx)
14900 }
14901 }
14902
14903 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14904 if self.is_singleton(cx) {
14905 let mut to_fold = Vec::new();
14906 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14907 let selections = self.selections.all_adjusted(cx);
14908
14909 for selection in selections {
14910 let range = selection.range().sorted();
14911 let buffer_start_row = range.start.row;
14912
14913 if range.start.row != range.end.row {
14914 let mut found = false;
14915 let mut row = range.start.row;
14916 while row <= range.end.row {
14917 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14918 {
14919 found = true;
14920 row = crease.range().end.row + 1;
14921 to_fold.push(crease);
14922 } else {
14923 row += 1
14924 }
14925 }
14926 if found {
14927 continue;
14928 }
14929 }
14930
14931 for row in (0..=range.start.row).rev() {
14932 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14933 if crease.range().end.row >= buffer_start_row {
14934 to_fold.push(crease);
14935 if row <= range.start.row {
14936 break;
14937 }
14938 }
14939 }
14940 }
14941 }
14942
14943 self.fold_creases(to_fold, true, window, cx);
14944 } else {
14945 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14946 let buffer_ids = self
14947 .selections
14948 .disjoint_anchor_ranges()
14949 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14950 .collect::<HashSet<_>>();
14951 for buffer_id in buffer_ids {
14952 self.fold_buffer(buffer_id, cx);
14953 }
14954 }
14955 }
14956
14957 fn fold_at_level(
14958 &mut self,
14959 fold_at: &FoldAtLevel,
14960 window: &mut Window,
14961 cx: &mut Context<Self>,
14962 ) {
14963 if !self.buffer.read(cx).is_singleton() {
14964 return;
14965 }
14966
14967 let fold_at_level = fold_at.0;
14968 let snapshot = self.buffer.read(cx).snapshot(cx);
14969 let mut to_fold = Vec::new();
14970 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14971
14972 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14973 while start_row < end_row {
14974 match self
14975 .snapshot(window, cx)
14976 .crease_for_buffer_row(MultiBufferRow(start_row))
14977 {
14978 Some(crease) => {
14979 let nested_start_row = crease.range().start.row + 1;
14980 let nested_end_row = crease.range().end.row;
14981
14982 if current_level < fold_at_level {
14983 stack.push((nested_start_row, nested_end_row, current_level + 1));
14984 } else if current_level == fold_at_level {
14985 to_fold.push(crease);
14986 }
14987
14988 start_row = nested_end_row + 1;
14989 }
14990 None => start_row += 1,
14991 }
14992 }
14993 }
14994
14995 self.fold_creases(to_fold, true, window, cx);
14996 }
14997
14998 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14999 if self.buffer.read(cx).is_singleton() {
15000 let mut fold_ranges = Vec::new();
15001 let snapshot = self.buffer.read(cx).snapshot(cx);
15002
15003 for row in 0..snapshot.max_row().0 {
15004 if let Some(foldable_range) = self
15005 .snapshot(window, cx)
15006 .crease_for_buffer_row(MultiBufferRow(row))
15007 {
15008 fold_ranges.push(foldable_range);
15009 }
15010 }
15011
15012 self.fold_creases(fold_ranges, true, window, cx);
15013 } else {
15014 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15015 editor
15016 .update_in(cx, |editor, _, cx| {
15017 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15018 editor.fold_buffer(buffer_id, cx);
15019 }
15020 })
15021 .ok();
15022 });
15023 }
15024 }
15025
15026 pub fn fold_function_bodies(
15027 &mut self,
15028 _: &actions::FoldFunctionBodies,
15029 window: &mut Window,
15030 cx: &mut Context<Self>,
15031 ) {
15032 let snapshot = self.buffer.read(cx).snapshot(cx);
15033
15034 let ranges = snapshot
15035 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15036 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15037 .collect::<Vec<_>>();
15038
15039 let creases = ranges
15040 .into_iter()
15041 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15042 .collect();
15043
15044 self.fold_creases(creases, true, window, cx);
15045 }
15046
15047 pub fn fold_recursive(
15048 &mut self,
15049 _: &actions::FoldRecursive,
15050 window: &mut Window,
15051 cx: &mut Context<Self>,
15052 ) {
15053 let mut to_fold = Vec::new();
15054 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15055 let selections = self.selections.all_adjusted(cx);
15056
15057 for selection in selections {
15058 let range = selection.range().sorted();
15059 let buffer_start_row = range.start.row;
15060
15061 if range.start.row != range.end.row {
15062 let mut found = false;
15063 for row in range.start.row..=range.end.row {
15064 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15065 found = true;
15066 to_fold.push(crease);
15067 }
15068 }
15069 if found {
15070 continue;
15071 }
15072 }
15073
15074 for row in (0..=range.start.row).rev() {
15075 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15076 if crease.range().end.row >= buffer_start_row {
15077 to_fold.push(crease);
15078 } else {
15079 break;
15080 }
15081 }
15082 }
15083 }
15084
15085 self.fold_creases(to_fold, true, window, cx);
15086 }
15087
15088 pub fn fold_at(
15089 &mut self,
15090 buffer_row: MultiBufferRow,
15091 window: &mut Window,
15092 cx: &mut Context<Self>,
15093 ) {
15094 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15095
15096 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15097 let autoscroll = self
15098 .selections
15099 .all::<Point>(cx)
15100 .iter()
15101 .any(|selection| crease.range().overlaps(&selection.range()));
15102
15103 self.fold_creases(vec![crease], autoscroll, window, cx);
15104 }
15105 }
15106
15107 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15108 if self.is_singleton(cx) {
15109 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15110 let buffer = &display_map.buffer_snapshot;
15111 let selections = self.selections.all::<Point>(cx);
15112 let ranges = selections
15113 .iter()
15114 .map(|s| {
15115 let range = s.display_range(&display_map).sorted();
15116 let mut start = range.start.to_point(&display_map);
15117 let mut end = range.end.to_point(&display_map);
15118 start.column = 0;
15119 end.column = buffer.line_len(MultiBufferRow(end.row));
15120 start..end
15121 })
15122 .collect::<Vec<_>>();
15123
15124 self.unfold_ranges(&ranges, true, true, cx);
15125 } else {
15126 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15127 let buffer_ids = self
15128 .selections
15129 .disjoint_anchor_ranges()
15130 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15131 .collect::<HashSet<_>>();
15132 for buffer_id in buffer_ids {
15133 self.unfold_buffer(buffer_id, cx);
15134 }
15135 }
15136 }
15137
15138 pub fn unfold_recursive(
15139 &mut self,
15140 _: &UnfoldRecursive,
15141 _window: &mut Window,
15142 cx: &mut Context<Self>,
15143 ) {
15144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15145 let selections = self.selections.all::<Point>(cx);
15146 let ranges = selections
15147 .iter()
15148 .map(|s| {
15149 let mut range = s.display_range(&display_map).sorted();
15150 *range.start.column_mut() = 0;
15151 *range.end.column_mut() = display_map.line_len(range.end.row());
15152 let start = range.start.to_point(&display_map);
15153 let end = range.end.to_point(&display_map);
15154 start..end
15155 })
15156 .collect::<Vec<_>>();
15157
15158 self.unfold_ranges(&ranges, true, true, cx);
15159 }
15160
15161 pub fn unfold_at(
15162 &mut self,
15163 buffer_row: MultiBufferRow,
15164 _window: &mut Window,
15165 cx: &mut Context<Self>,
15166 ) {
15167 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15168
15169 let intersection_range = Point::new(buffer_row.0, 0)
15170 ..Point::new(
15171 buffer_row.0,
15172 display_map.buffer_snapshot.line_len(buffer_row),
15173 );
15174
15175 let autoscroll = self
15176 .selections
15177 .all::<Point>(cx)
15178 .iter()
15179 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15180
15181 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15182 }
15183
15184 pub fn unfold_all(
15185 &mut self,
15186 _: &actions::UnfoldAll,
15187 _window: &mut Window,
15188 cx: &mut Context<Self>,
15189 ) {
15190 if self.buffer.read(cx).is_singleton() {
15191 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15192 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15193 } else {
15194 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15195 editor
15196 .update(cx, |editor, cx| {
15197 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15198 editor.unfold_buffer(buffer_id, cx);
15199 }
15200 })
15201 .ok();
15202 });
15203 }
15204 }
15205
15206 pub fn fold_selected_ranges(
15207 &mut self,
15208 _: &FoldSelectedRanges,
15209 window: &mut Window,
15210 cx: &mut Context<Self>,
15211 ) {
15212 let selections = self.selections.all_adjusted(cx);
15213 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15214 let ranges = selections
15215 .into_iter()
15216 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15217 .collect::<Vec<_>>();
15218 self.fold_creases(ranges, true, window, cx);
15219 }
15220
15221 pub fn fold_ranges<T: ToOffset + Clone>(
15222 &mut self,
15223 ranges: Vec<Range<T>>,
15224 auto_scroll: bool,
15225 window: &mut Window,
15226 cx: &mut Context<Self>,
15227 ) {
15228 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15229 let ranges = ranges
15230 .into_iter()
15231 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15232 .collect::<Vec<_>>();
15233 self.fold_creases(ranges, auto_scroll, window, cx);
15234 }
15235
15236 pub fn fold_creases<T: ToOffset + Clone>(
15237 &mut self,
15238 creases: Vec<Crease<T>>,
15239 auto_scroll: bool,
15240 _window: &mut Window,
15241 cx: &mut Context<Self>,
15242 ) {
15243 if creases.is_empty() {
15244 return;
15245 }
15246
15247 let mut buffers_affected = HashSet::default();
15248 let multi_buffer = self.buffer().read(cx);
15249 for crease in &creases {
15250 if let Some((_, buffer, _)) =
15251 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15252 {
15253 buffers_affected.insert(buffer.read(cx).remote_id());
15254 };
15255 }
15256
15257 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15258
15259 if auto_scroll {
15260 self.request_autoscroll(Autoscroll::fit(), cx);
15261 }
15262
15263 cx.notify();
15264
15265 self.scrollbar_marker_state.dirty = true;
15266 self.folds_did_change(cx);
15267 }
15268
15269 /// Removes any folds whose ranges intersect any of the given ranges.
15270 pub fn unfold_ranges<T: ToOffset + Clone>(
15271 &mut self,
15272 ranges: &[Range<T>],
15273 inclusive: bool,
15274 auto_scroll: bool,
15275 cx: &mut Context<Self>,
15276 ) {
15277 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15278 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15279 });
15280 self.folds_did_change(cx);
15281 }
15282
15283 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15284 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15285 return;
15286 }
15287 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15288 self.display_map.update(cx, |display_map, cx| {
15289 display_map.fold_buffers([buffer_id], cx)
15290 });
15291 cx.emit(EditorEvent::BufferFoldToggled {
15292 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15293 folded: true,
15294 });
15295 cx.notify();
15296 }
15297
15298 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15299 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15300 return;
15301 }
15302 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15303 self.display_map.update(cx, |display_map, cx| {
15304 display_map.unfold_buffers([buffer_id], cx);
15305 });
15306 cx.emit(EditorEvent::BufferFoldToggled {
15307 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15308 folded: false,
15309 });
15310 cx.notify();
15311 }
15312
15313 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15314 self.display_map.read(cx).is_buffer_folded(buffer)
15315 }
15316
15317 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15318 self.display_map.read(cx).folded_buffers()
15319 }
15320
15321 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15322 self.display_map.update(cx, |display_map, cx| {
15323 display_map.disable_header_for_buffer(buffer_id, cx);
15324 });
15325 cx.notify();
15326 }
15327
15328 /// Removes any folds with the given ranges.
15329 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15330 &mut self,
15331 ranges: &[Range<T>],
15332 type_id: TypeId,
15333 auto_scroll: bool,
15334 cx: &mut Context<Self>,
15335 ) {
15336 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15337 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15338 });
15339 self.folds_did_change(cx);
15340 }
15341
15342 fn remove_folds_with<T: ToOffset + Clone>(
15343 &mut self,
15344 ranges: &[Range<T>],
15345 auto_scroll: bool,
15346 cx: &mut Context<Self>,
15347 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15348 ) {
15349 if ranges.is_empty() {
15350 return;
15351 }
15352
15353 let mut buffers_affected = HashSet::default();
15354 let multi_buffer = self.buffer().read(cx);
15355 for range in ranges {
15356 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15357 buffers_affected.insert(buffer.read(cx).remote_id());
15358 };
15359 }
15360
15361 self.display_map.update(cx, update);
15362
15363 if auto_scroll {
15364 self.request_autoscroll(Autoscroll::fit(), cx);
15365 }
15366
15367 cx.notify();
15368 self.scrollbar_marker_state.dirty = true;
15369 self.active_indent_guides_state.dirty = true;
15370 }
15371
15372 pub fn update_fold_widths(
15373 &mut self,
15374 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15375 cx: &mut Context<Self>,
15376 ) -> bool {
15377 self.display_map
15378 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15379 }
15380
15381 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15382 self.display_map.read(cx).fold_placeholder.clone()
15383 }
15384
15385 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15386 self.buffer.update(cx, |buffer, cx| {
15387 buffer.set_all_diff_hunks_expanded(cx);
15388 });
15389 }
15390
15391 pub fn expand_all_diff_hunks(
15392 &mut self,
15393 _: &ExpandAllDiffHunks,
15394 _window: &mut Window,
15395 cx: &mut Context<Self>,
15396 ) {
15397 self.buffer.update(cx, |buffer, cx| {
15398 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15399 });
15400 }
15401
15402 pub fn toggle_selected_diff_hunks(
15403 &mut self,
15404 _: &ToggleSelectedDiffHunks,
15405 _window: &mut Window,
15406 cx: &mut Context<Self>,
15407 ) {
15408 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15409 self.toggle_diff_hunks_in_ranges(ranges, cx);
15410 }
15411
15412 pub fn diff_hunks_in_ranges<'a>(
15413 &'a self,
15414 ranges: &'a [Range<Anchor>],
15415 buffer: &'a MultiBufferSnapshot,
15416 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15417 ranges.iter().flat_map(move |range| {
15418 let end_excerpt_id = range.end.excerpt_id;
15419 let range = range.to_point(buffer);
15420 let mut peek_end = range.end;
15421 if range.end.row < buffer.max_row().0 {
15422 peek_end = Point::new(range.end.row + 1, 0);
15423 }
15424 buffer
15425 .diff_hunks_in_range(range.start..peek_end)
15426 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15427 })
15428 }
15429
15430 pub fn has_stageable_diff_hunks_in_ranges(
15431 &self,
15432 ranges: &[Range<Anchor>],
15433 snapshot: &MultiBufferSnapshot,
15434 ) -> bool {
15435 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15436 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15437 }
15438
15439 pub fn toggle_staged_selected_diff_hunks(
15440 &mut self,
15441 _: &::git::ToggleStaged,
15442 _: &mut Window,
15443 cx: &mut Context<Self>,
15444 ) {
15445 let snapshot = self.buffer.read(cx).snapshot(cx);
15446 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15447 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15448 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15449 }
15450
15451 pub fn set_render_diff_hunk_controls(
15452 &mut self,
15453 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15454 cx: &mut Context<Self>,
15455 ) {
15456 self.render_diff_hunk_controls = render_diff_hunk_controls;
15457 cx.notify();
15458 }
15459
15460 pub fn stage_and_next(
15461 &mut self,
15462 _: &::git::StageAndNext,
15463 window: &mut Window,
15464 cx: &mut Context<Self>,
15465 ) {
15466 self.do_stage_or_unstage_and_next(true, window, cx);
15467 }
15468
15469 pub fn unstage_and_next(
15470 &mut self,
15471 _: &::git::UnstageAndNext,
15472 window: &mut Window,
15473 cx: &mut Context<Self>,
15474 ) {
15475 self.do_stage_or_unstage_and_next(false, window, cx);
15476 }
15477
15478 pub fn stage_or_unstage_diff_hunks(
15479 &mut self,
15480 stage: bool,
15481 ranges: Vec<Range<Anchor>>,
15482 cx: &mut Context<Self>,
15483 ) {
15484 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15485 cx.spawn(async move |this, cx| {
15486 task.await?;
15487 this.update(cx, |this, cx| {
15488 let snapshot = this.buffer.read(cx).snapshot(cx);
15489 let chunk_by = this
15490 .diff_hunks_in_ranges(&ranges, &snapshot)
15491 .chunk_by(|hunk| hunk.buffer_id);
15492 for (buffer_id, hunks) in &chunk_by {
15493 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15494 }
15495 })
15496 })
15497 .detach_and_log_err(cx);
15498 }
15499
15500 fn save_buffers_for_ranges_if_needed(
15501 &mut self,
15502 ranges: &[Range<Anchor>],
15503 cx: &mut Context<Editor>,
15504 ) -> Task<Result<()>> {
15505 let multibuffer = self.buffer.read(cx);
15506 let snapshot = multibuffer.read(cx);
15507 let buffer_ids: HashSet<_> = ranges
15508 .iter()
15509 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15510 .collect();
15511 drop(snapshot);
15512
15513 let mut buffers = HashSet::default();
15514 for buffer_id in buffer_ids {
15515 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15516 let buffer = buffer_entity.read(cx);
15517 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15518 {
15519 buffers.insert(buffer_entity);
15520 }
15521 }
15522 }
15523
15524 if let Some(project) = &self.project {
15525 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15526 } else {
15527 Task::ready(Ok(()))
15528 }
15529 }
15530
15531 fn do_stage_or_unstage_and_next(
15532 &mut self,
15533 stage: bool,
15534 window: &mut Window,
15535 cx: &mut Context<Self>,
15536 ) {
15537 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15538
15539 if ranges.iter().any(|range| range.start != range.end) {
15540 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15541 return;
15542 }
15543
15544 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15545 let snapshot = self.snapshot(window, cx);
15546 let position = self.selections.newest::<Point>(cx).head();
15547 let mut row = snapshot
15548 .buffer_snapshot
15549 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15550 .find(|hunk| hunk.row_range.start.0 > position.row)
15551 .map(|hunk| hunk.row_range.start);
15552
15553 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15554 // Outside of the project diff editor, wrap around to the beginning.
15555 if !all_diff_hunks_expanded {
15556 row = row.or_else(|| {
15557 snapshot
15558 .buffer_snapshot
15559 .diff_hunks_in_range(Point::zero()..position)
15560 .find(|hunk| hunk.row_range.end.0 < position.row)
15561 .map(|hunk| hunk.row_range.start)
15562 });
15563 }
15564
15565 if let Some(row) = row {
15566 let destination = Point::new(row.0, 0);
15567 let autoscroll = Autoscroll::center();
15568
15569 self.unfold_ranges(&[destination..destination], false, false, cx);
15570 self.change_selections(Some(autoscroll), window, cx, |s| {
15571 s.select_ranges([destination..destination]);
15572 });
15573 }
15574 }
15575
15576 fn do_stage_or_unstage(
15577 &self,
15578 stage: bool,
15579 buffer_id: BufferId,
15580 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15581 cx: &mut App,
15582 ) -> Option<()> {
15583 let project = self.project.as_ref()?;
15584 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15585 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15586 let buffer_snapshot = buffer.read(cx).snapshot();
15587 let file_exists = buffer_snapshot
15588 .file()
15589 .is_some_and(|file| file.disk_state().exists());
15590 diff.update(cx, |diff, cx| {
15591 diff.stage_or_unstage_hunks(
15592 stage,
15593 &hunks
15594 .map(|hunk| buffer_diff::DiffHunk {
15595 buffer_range: hunk.buffer_range,
15596 diff_base_byte_range: hunk.diff_base_byte_range,
15597 secondary_status: hunk.secondary_status,
15598 range: Point::zero()..Point::zero(), // unused
15599 })
15600 .collect::<Vec<_>>(),
15601 &buffer_snapshot,
15602 file_exists,
15603 cx,
15604 )
15605 });
15606 None
15607 }
15608
15609 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15610 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15611 self.buffer
15612 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15613 }
15614
15615 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15616 self.buffer.update(cx, |buffer, cx| {
15617 let ranges = vec![Anchor::min()..Anchor::max()];
15618 if !buffer.all_diff_hunks_expanded()
15619 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15620 {
15621 buffer.collapse_diff_hunks(ranges, cx);
15622 true
15623 } else {
15624 false
15625 }
15626 })
15627 }
15628
15629 fn toggle_diff_hunks_in_ranges(
15630 &mut self,
15631 ranges: Vec<Range<Anchor>>,
15632 cx: &mut Context<Editor>,
15633 ) {
15634 self.buffer.update(cx, |buffer, cx| {
15635 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15636 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15637 })
15638 }
15639
15640 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15641 self.buffer.update(cx, |buffer, cx| {
15642 let snapshot = buffer.snapshot(cx);
15643 let excerpt_id = range.end.excerpt_id;
15644 let point_range = range.to_point(&snapshot);
15645 let expand = !buffer.single_hunk_is_expanded(range, cx);
15646 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15647 })
15648 }
15649
15650 pub(crate) fn apply_all_diff_hunks(
15651 &mut self,
15652 _: &ApplyAllDiffHunks,
15653 window: &mut Window,
15654 cx: &mut Context<Self>,
15655 ) {
15656 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15657
15658 let buffers = self.buffer.read(cx).all_buffers();
15659 for branch_buffer in buffers {
15660 branch_buffer.update(cx, |branch_buffer, cx| {
15661 branch_buffer.merge_into_base(Vec::new(), cx);
15662 });
15663 }
15664
15665 if let Some(project) = self.project.clone() {
15666 self.save(true, project, window, cx).detach_and_log_err(cx);
15667 }
15668 }
15669
15670 pub(crate) fn apply_selected_diff_hunks(
15671 &mut self,
15672 _: &ApplyDiffHunk,
15673 window: &mut Window,
15674 cx: &mut Context<Self>,
15675 ) {
15676 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15677 let snapshot = self.snapshot(window, cx);
15678 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15679 let mut ranges_by_buffer = HashMap::default();
15680 self.transact(window, cx, |editor, _window, cx| {
15681 for hunk in hunks {
15682 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15683 ranges_by_buffer
15684 .entry(buffer.clone())
15685 .or_insert_with(Vec::new)
15686 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15687 }
15688 }
15689
15690 for (buffer, ranges) in ranges_by_buffer {
15691 buffer.update(cx, |buffer, cx| {
15692 buffer.merge_into_base(ranges, cx);
15693 });
15694 }
15695 });
15696
15697 if let Some(project) = self.project.clone() {
15698 self.save(true, project, window, cx).detach_and_log_err(cx);
15699 }
15700 }
15701
15702 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15703 if hovered != self.gutter_hovered {
15704 self.gutter_hovered = hovered;
15705 cx.notify();
15706 }
15707 }
15708
15709 pub fn insert_blocks(
15710 &mut self,
15711 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15712 autoscroll: Option<Autoscroll>,
15713 cx: &mut Context<Self>,
15714 ) -> Vec<CustomBlockId> {
15715 let blocks = self
15716 .display_map
15717 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15718 if let Some(autoscroll) = autoscroll {
15719 self.request_autoscroll(autoscroll, cx);
15720 }
15721 cx.notify();
15722 blocks
15723 }
15724
15725 pub fn resize_blocks(
15726 &mut self,
15727 heights: HashMap<CustomBlockId, u32>,
15728 autoscroll: Option<Autoscroll>,
15729 cx: &mut Context<Self>,
15730 ) {
15731 self.display_map
15732 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15733 if let Some(autoscroll) = autoscroll {
15734 self.request_autoscroll(autoscroll, cx);
15735 }
15736 cx.notify();
15737 }
15738
15739 pub fn replace_blocks(
15740 &mut self,
15741 renderers: HashMap<CustomBlockId, RenderBlock>,
15742 autoscroll: Option<Autoscroll>,
15743 cx: &mut Context<Self>,
15744 ) {
15745 self.display_map
15746 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15747 if let Some(autoscroll) = autoscroll {
15748 self.request_autoscroll(autoscroll, cx);
15749 }
15750 cx.notify();
15751 }
15752
15753 pub fn remove_blocks(
15754 &mut self,
15755 block_ids: HashSet<CustomBlockId>,
15756 autoscroll: Option<Autoscroll>,
15757 cx: &mut Context<Self>,
15758 ) {
15759 self.display_map.update(cx, |display_map, cx| {
15760 display_map.remove_blocks(block_ids, cx)
15761 });
15762 if let Some(autoscroll) = autoscroll {
15763 self.request_autoscroll(autoscroll, cx);
15764 }
15765 cx.notify();
15766 }
15767
15768 pub fn row_for_block(
15769 &self,
15770 block_id: CustomBlockId,
15771 cx: &mut Context<Self>,
15772 ) -> Option<DisplayRow> {
15773 self.display_map
15774 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15775 }
15776
15777 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15778 self.focused_block = Some(focused_block);
15779 }
15780
15781 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15782 self.focused_block.take()
15783 }
15784
15785 pub fn insert_creases(
15786 &mut self,
15787 creases: impl IntoIterator<Item = Crease<Anchor>>,
15788 cx: &mut Context<Self>,
15789 ) -> Vec<CreaseId> {
15790 self.display_map
15791 .update(cx, |map, cx| map.insert_creases(creases, cx))
15792 }
15793
15794 pub fn remove_creases(
15795 &mut self,
15796 ids: impl IntoIterator<Item = CreaseId>,
15797 cx: &mut Context<Self>,
15798 ) {
15799 self.display_map
15800 .update(cx, |map, cx| map.remove_creases(ids, cx));
15801 }
15802
15803 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15804 self.display_map
15805 .update(cx, |map, cx| map.snapshot(cx))
15806 .longest_row()
15807 }
15808
15809 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15810 self.display_map
15811 .update(cx, |map, cx| map.snapshot(cx))
15812 .max_point()
15813 }
15814
15815 pub fn text(&self, cx: &App) -> String {
15816 self.buffer.read(cx).read(cx).text()
15817 }
15818
15819 pub fn is_empty(&self, cx: &App) -> bool {
15820 self.buffer.read(cx).read(cx).is_empty()
15821 }
15822
15823 pub fn text_option(&self, cx: &App) -> Option<String> {
15824 let text = self.text(cx);
15825 let text = text.trim();
15826
15827 if text.is_empty() {
15828 return None;
15829 }
15830
15831 Some(text.to_string())
15832 }
15833
15834 pub fn set_text(
15835 &mut self,
15836 text: impl Into<Arc<str>>,
15837 window: &mut Window,
15838 cx: &mut Context<Self>,
15839 ) {
15840 self.transact(window, cx, |this, _, cx| {
15841 this.buffer
15842 .read(cx)
15843 .as_singleton()
15844 .expect("you can only call set_text on editors for singleton buffers")
15845 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15846 });
15847 }
15848
15849 pub fn display_text(&self, cx: &mut App) -> String {
15850 self.display_map
15851 .update(cx, |map, cx| map.snapshot(cx))
15852 .text()
15853 }
15854
15855 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15856 let mut wrap_guides = smallvec::smallvec![];
15857
15858 if self.show_wrap_guides == Some(false) {
15859 return wrap_guides;
15860 }
15861
15862 let settings = self.buffer.read(cx).language_settings(cx);
15863 if settings.show_wrap_guides {
15864 match self.soft_wrap_mode(cx) {
15865 SoftWrap::Column(soft_wrap) => {
15866 wrap_guides.push((soft_wrap as usize, true));
15867 }
15868 SoftWrap::Bounded(soft_wrap) => {
15869 wrap_guides.push((soft_wrap as usize, true));
15870 }
15871 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15872 }
15873 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15874 }
15875
15876 wrap_guides
15877 }
15878
15879 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15880 let settings = self.buffer.read(cx).language_settings(cx);
15881 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15882 match mode {
15883 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15884 SoftWrap::None
15885 }
15886 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15887 language_settings::SoftWrap::PreferredLineLength => {
15888 SoftWrap::Column(settings.preferred_line_length)
15889 }
15890 language_settings::SoftWrap::Bounded => {
15891 SoftWrap::Bounded(settings.preferred_line_length)
15892 }
15893 }
15894 }
15895
15896 pub fn set_soft_wrap_mode(
15897 &mut self,
15898 mode: language_settings::SoftWrap,
15899
15900 cx: &mut Context<Self>,
15901 ) {
15902 self.soft_wrap_mode_override = Some(mode);
15903 cx.notify();
15904 }
15905
15906 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15907 self.hard_wrap = hard_wrap;
15908 cx.notify();
15909 }
15910
15911 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15912 self.text_style_refinement = Some(style);
15913 }
15914
15915 /// called by the Element so we know what style we were most recently rendered with.
15916 pub(crate) fn set_style(
15917 &mut self,
15918 style: EditorStyle,
15919 window: &mut Window,
15920 cx: &mut Context<Self>,
15921 ) {
15922 let rem_size = window.rem_size();
15923 self.display_map.update(cx, |map, cx| {
15924 map.set_font(
15925 style.text.font(),
15926 style.text.font_size.to_pixels(rem_size),
15927 cx,
15928 )
15929 });
15930 self.style = Some(style);
15931 }
15932
15933 pub fn style(&self) -> Option<&EditorStyle> {
15934 self.style.as_ref()
15935 }
15936
15937 // Called by the element. This method is not designed to be called outside of the editor
15938 // element's layout code because it does not notify when rewrapping is computed synchronously.
15939 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15940 self.display_map
15941 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15942 }
15943
15944 pub fn set_soft_wrap(&mut self) {
15945 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15946 }
15947
15948 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15949 if self.soft_wrap_mode_override.is_some() {
15950 self.soft_wrap_mode_override.take();
15951 } else {
15952 let soft_wrap = match self.soft_wrap_mode(cx) {
15953 SoftWrap::GitDiff => return,
15954 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15955 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15956 language_settings::SoftWrap::None
15957 }
15958 };
15959 self.soft_wrap_mode_override = Some(soft_wrap);
15960 }
15961 cx.notify();
15962 }
15963
15964 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15965 let Some(workspace) = self.workspace() else {
15966 return;
15967 };
15968 let fs = workspace.read(cx).app_state().fs.clone();
15969 let current_show = TabBarSettings::get_global(cx).show;
15970 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15971 setting.show = Some(!current_show);
15972 });
15973 }
15974
15975 pub fn toggle_indent_guides(
15976 &mut self,
15977 _: &ToggleIndentGuides,
15978 _: &mut Window,
15979 cx: &mut Context<Self>,
15980 ) {
15981 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15982 self.buffer
15983 .read(cx)
15984 .language_settings(cx)
15985 .indent_guides
15986 .enabled
15987 });
15988 self.show_indent_guides = Some(!currently_enabled);
15989 cx.notify();
15990 }
15991
15992 fn should_show_indent_guides(&self) -> Option<bool> {
15993 self.show_indent_guides
15994 }
15995
15996 pub fn toggle_line_numbers(
15997 &mut self,
15998 _: &ToggleLineNumbers,
15999 _: &mut Window,
16000 cx: &mut Context<Self>,
16001 ) {
16002 let mut editor_settings = EditorSettings::get_global(cx).clone();
16003 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16004 EditorSettings::override_global(editor_settings, cx);
16005 }
16006
16007 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16008 if let Some(show_line_numbers) = self.show_line_numbers {
16009 return show_line_numbers;
16010 }
16011 EditorSettings::get_global(cx).gutter.line_numbers
16012 }
16013
16014 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16015 self.use_relative_line_numbers
16016 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16017 }
16018
16019 pub fn toggle_relative_line_numbers(
16020 &mut self,
16021 _: &ToggleRelativeLineNumbers,
16022 _: &mut Window,
16023 cx: &mut Context<Self>,
16024 ) {
16025 let is_relative = self.should_use_relative_line_numbers(cx);
16026 self.set_relative_line_number(Some(!is_relative), cx)
16027 }
16028
16029 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16030 self.use_relative_line_numbers = is_relative;
16031 cx.notify();
16032 }
16033
16034 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16035 self.show_gutter = show_gutter;
16036 cx.notify();
16037 }
16038
16039 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16040 self.show_scrollbars = show_scrollbars;
16041 cx.notify();
16042 }
16043
16044 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16045 self.show_line_numbers = Some(show_line_numbers);
16046 cx.notify();
16047 }
16048
16049 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16050 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16051 cx.notify();
16052 }
16053
16054 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16055 self.show_code_actions = Some(show_code_actions);
16056 cx.notify();
16057 }
16058
16059 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16060 self.show_runnables = Some(show_runnables);
16061 cx.notify();
16062 }
16063
16064 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16065 self.show_breakpoints = Some(show_breakpoints);
16066 cx.notify();
16067 }
16068
16069 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16070 if self.display_map.read(cx).masked != masked {
16071 self.display_map.update(cx, |map, _| map.masked = masked);
16072 }
16073 cx.notify()
16074 }
16075
16076 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16077 self.show_wrap_guides = Some(show_wrap_guides);
16078 cx.notify();
16079 }
16080
16081 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16082 self.show_indent_guides = Some(show_indent_guides);
16083 cx.notify();
16084 }
16085
16086 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16087 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16088 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16089 if let Some(dir) = file.abs_path(cx).parent() {
16090 return Some(dir.to_owned());
16091 }
16092 }
16093
16094 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16095 return Some(project_path.path.to_path_buf());
16096 }
16097 }
16098
16099 None
16100 }
16101
16102 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16103 self.active_excerpt(cx)?
16104 .1
16105 .read(cx)
16106 .file()
16107 .and_then(|f| f.as_local())
16108 }
16109
16110 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16111 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16112 let buffer = buffer.read(cx);
16113 if let Some(project_path) = buffer.project_path(cx) {
16114 let project = self.project.as_ref()?.read(cx);
16115 project.absolute_path(&project_path, cx)
16116 } else {
16117 buffer
16118 .file()
16119 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16120 }
16121 })
16122 }
16123
16124 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16125 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16126 let project_path = buffer.read(cx).project_path(cx)?;
16127 let project = self.project.as_ref()?.read(cx);
16128 let entry = project.entry_for_path(&project_path, cx)?;
16129 let path = entry.path.to_path_buf();
16130 Some(path)
16131 })
16132 }
16133
16134 pub fn reveal_in_finder(
16135 &mut self,
16136 _: &RevealInFileManager,
16137 _window: &mut Window,
16138 cx: &mut Context<Self>,
16139 ) {
16140 if let Some(target) = self.target_file(cx) {
16141 cx.reveal_path(&target.abs_path(cx));
16142 }
16143 }
16144
16145 pub fn copy_path(
16146 &mut self,
16147 _: &zed_actions::workspace::CopyPath,
16148 _window: &mut Window,
16149 cx: &mut Context<Self>,
16150 ) {
16151 if let Some(path) = self.target_file_abs_path(cx) {
16152 if let Some(path) = path.to_str() {
16153 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16154 }
16155 }
16156 }
16157
16158 pub fn copy_relative_path(
16159 &mut self,
16160 _: &zed_actions::workspace::CopyRelativePath,
16161 _window: &mut Window,
16162 cx: &mut Context<Self>,
16163 ) {
16164 if let Some(path) = self.target_file_path(cx) {
16165 if let Some(path) = path.to_str() {
16166 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16167 }
16168 }
16169 }
16170
16171 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16172 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16173 buffer.read(cx).project_path(cx)
16174 } else {
16175 None
16176 }
16177 }
16178
16179 // Returns true if the editor handled a go-to-line request
16180 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16181 maybe!({
16182 let breakpoint_store = self.breakpoint_store.as_ref()?;
16183
16184 let Some((_, _, active_position)) =
16185 breakpoint_store.read(cx).active_position().cloned()
16186 else {
16187 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16188 return None;
16189 };
16190
16191 let snapshot = self
16192 .project
16193 .as_ref()?
16194 .read(cx)
16195 .buffer_for_id(active_position.buffer_id?, cx)?
16196 .read(cx)
16197 .snapshot();
16198
16199 let mut handled = false;
16200 for (id, ExcerptRange { context, .. }) in self
16201 .buffer
16202 .read(cx)
16203 .excerpts_for_buffer(active_position.buffer_id?, cx)
16204 {
16205 if context.start.cmp(&active_position, &snapshot).is_ge()
16206 || context.end.cmp(&active_position, &snapshot).is_lt()
16207 {
16208 continue;
16209 }
16210 let snapshot = self.buffer.read(cx).snapshot(cx);
16211 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16212
16213 handled = true;
16214 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16215 self.go_to_line::<DebugCurrentRowHighlight>(
16216 multibuffer_anchor,
16217 Some(cx.theme().colors().editor_debugger_active_line_background),
16218 window,
16219 cx,
16220 );
16221
16222 cx.notify();
16223 }
16224 handled.then_some(())
16225 })
16226 .is_some()
16227 }
16228
16229 pub fn copy_file_name_without_extension(
16230 &mut self,
16231 _: &CopyFileNameWithoutExtension,
16232 _: &mut Window,
16233 cx: &mut Context<Self>,
16234 ) {
16235 if let Some(file) = self.target_file(cx) {
16236 if let Some(file_stem) = file.path().file_stem() {
16237 if let Some(name) = file_stem.to_str() {
16238 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16239 }
16240 }
16241 }
16242 }
16243
16244 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16245 if let Some(file) = self.target_file(cx) {
16246 if let Some(file_name) = file.path().file_name() {
16247 if let Some(name) = file_name.to_str() {
16248 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16249 }
16250 }
16251 }
16252 }
16253
16254 pub fn toggle_git_blame(
16255 &mut self,
16256 _: &::git::Blame,
16257 window: &mut Window,
16258 cx: &mut Context<Self>,
16259 ) {
16260 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16261
16262 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16263 self.start_git_blame(true, window, cx);
16264 }
16265
16266 cx.notify();
16267 }
16268
16269 pub fn toggle_git_blame_inline(
16270 &mut self,
16271 _: &ToggleGitBlameInline,
16272 window: &mut Window,
16273 cx: &mut Context<Self>,
16274 ) {
16275 self.toggle_git_blame_inline_internal(true, window, cx);
16276 cx.notify();
16277 }
16278
16279 pub fn open_git_blame_commit(
16280 &mut self,
16281 _: &OpenGitBlameCommit,
16282 window: &mut Window,
16283 cx: &mut Context<Self>,
16284 ) {
16285 self.open_git_blame_commit_internal(window, cx);
16286 }
16287
16288 fn open_git_blame_commit_internal(
16289 &mut self,
16290 window: &mut Window,
16291 cx: &mut Context<Self>,
16292 ) -> Option<()> {
16293 let blame = self.blame.as_ref()?;
16294 let snapshot = self.snapshot(window, cx);
16295 let cursor = self.selections.newest::<Point>(cx).head();
16296 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16297 let blame_entry = blame
16298 .update(cx, |blame, cx| {
16299 blame
16300 .blame_for_rows(
16301 &[RowInfo {
16302 buffer_id: Some(buffer.remote_id()),
16303 buffer_row: Some(point.row),
16304 ..Default::default()
16305 }],
16306 cx,
16307 )
16308 .next()
16309 })
16310 .flatten()?;
16311 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16312 let repo = blame.read(cx).repository(cx)?;
16313 let workspace = self.workspace()?.downgrade();
16314 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16315 None
16316 }
16317
16318 pub fn git_blame_inline_enabled(&self) -> bool {
16319 self.git_blame_inline_enabled
16320 }
16321
16322 pub fn toggle_selection_menu(
16323 &mut self,
16324 _: &ToggleSelectionMenu,
16325 _: &mut Window,
16326 cx: &mut Context<Self>,
16327 ) {
16328 self.show_selection_menu = self
16329 .show_selection_menu
16330 .map(|show_selections_menu| !show_selections_menu)
16331 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16332
16333 cx.notify();
16334 }
16335
16336 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16337 self.show_selection_menu
16338 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16339 }
16340
16341 fn start_git_blame(
16342 &mut self,
16343 user_triggered: bool,
16344 window: &mut Window,
16345 cx: &mut Context<Self>,
16346 ) {
16347 if let Some(project) = self.project.as_ref() {
16348 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16349 return;
16350 };
16351
16352 if buffer.read(cx).file().is_none() {
16353 return;
16354 }
16355
16356 let focused = self.focus_handle(cx).contains_focused(window, cx);
16357
16358 let project = project.clone();
16359 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16360 self.blame_subscription =
16361 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16362 self.blame = Some(blame);
16363 }
16364 }
16365
16366 fn toggle_git_blame_inline_internal(
16367 &mut self,
16368 user_triggered: bool,
16369 window: &mut Window,
16370 cx: &mut Context<Self>,
16371 ) {
16372 if self.git_blame_inline_enabled {
16373 self.git_blame_inline_enabled = false;
16374 self.show_git_blame_inline = false;
16375 self.show_git_blame_inline_delay_task.take();
16376 } else {
16377 self.git_blame_inline_enabled = true;
16378 self.start_git_blame_inline(user_triggered, window, cx);
16379 }
16380
16381 cx.notify();
16382 }
16383
16384 fn start_git_blame_inline(
16385 &mut self,
16386 user_triggered: bool,
16387 window: &mut Window,
16388 cx: &mut Context<Self>,
16389 ) {
16390 self.start_git_blame(user_triggered, window, cx);
16391
16392 if ProjectSettings::get_global(cx)
16393 .git
16394 .inline_blame_delay()
16395 .is_some()
16396 {
16397 self.start_inline_blame_timer(window, cx);
16398 } else {
16399 self.show_git_blame_inline = true
16400 }
16401 }
16402
16403 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16404 self.blame.as_ref()
16405 }
16406
16407 pub fn show_git_blame_gutter(&self) -> bool {
16408 self.show_git_blame_gutter
16409 }
16410
16411 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16412 self.show_git_blame_gutter && self.has_blame_entries(cx)
16413 }
16414
16415 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16416 self.show_git_blame_inline
16417 && (self.focus_handle.is_focused(window)
16418 || self
16419 .git_blame_inline_tooltip
16420 .as_ref()
16421 .and_then(|t| t.upgrade())
16422 .is_some())
16423 && !self.newest_selection_head_on_empty_line(cx)
16424 && self.has_blame_entries(cx)
16425 }
16426
16427 fn has_blame_entries(&self, cx: &App) -> bool {
16428 self.blame()
16429 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16430 }
16431
16432 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16433 let cursor_anchor = self.selections.newest_anchor().head();
16434
16435 let snapshot = self.buffer.read(cx).snapshot(cx);
16436 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16437
16438 snapshot.line_len(buffer_row) == 0
16439 }
16440
16441 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16442 let buffer_and_selection = maybe!({
16443 let selection = self.selections.newest::<Point>(cx);
16444 let selection_range = selection.range();
16445
16446 let multi_buffer = self.buffer().read(cx);
16447 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16448 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16449
16450 let (buffer, range, _) = if selection.reversed {
16451 buffer_ranges.first()
16452 } else {
16453 buffer_ranges.last()
16454 }?;
16455
16456 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16457 ..text::ToPoint::to_point(&range.end, &buffer).row;
16458 Some((
16459 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16460 selection,
16461 ))
16462 });
16463
16464 let Some((buffer, selection)) = buffer_and_selection else {
16465 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16466 };
16467
16468 let Some(project) = self.project.as_ref() else {
16469 return Task::ready(Err(anyhow!("editor does not have project")));
16470 };
16471
16472 project.update(cx, |project, cx| {
16473 project.get_permalink_to_line(&buffer, selection, cx)
16474 })
16475 }
16476
16477 pub fn copy_permalink_to_line(
16478 &mut self,
16479 _: &CopyPermalinkToLine,
16480 window: &mut Window,
16481 cx: &mut Context<Self>,
16482 ) {
16483 let permalink_task = self.get_permalink_to_line(cx);
16484 let workspace = self.workspace();
16485
16486 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16487 Ok(permalink) => {
16488 cx.update(|_, cx| {
16489 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16490 })
16491 .ok();
16492 }
16493 Err(err) => {
16494 let message = format!("Failed to copy permalink: {err}");
16495
16496 Err::<(), anyhow::Error>(err).log_err();
16497
16498 if let Some(workspace) = workspace {
16499 workspace
16500 .update_in(cx, |workspace, _, cx| {
16501 struct CopyPermalinkToLine;
16502
16503 workspace.show_toast(
16504 Toast::new(
16505 NotificationId::unique::<CopyPermalinkToLine>(),
16506 message,
16507 ),
16508 cx,
16509 )
16510 })
16511 .ok();
16512 }
16513 }
16514 })
16515 .detach();
16516 }
16517
16518 pub fn copy_file_location(
16519 &mut self,
16520 _: &CopyFileLocation,
16521 _: &mut Window,
16522 cx: &mut Context<Self>,
16523 ) {
16524 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16525 if let Some(file) = self.target_file(cx) {
16526 if let Some(path) = file.path().to_str() {
16527 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16528 }
16529 }
16530 }
16531
16532 pub fn open_permalink_to_line(
16533 &mut self,
16534 _: &OpenPermalinkToLine,
16535 window: &mut Window,
16536 cx: &mut Context<Self>,
16537 ) {
16538 let permalink_task = self.get_permalink_to_line(cx);
16539 let workspace = self.workspace();
16540
16541 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16542 Ok(permalink) => {
16543 cx.update(|_, cx| {
16544 cx.open_url(permalink.as_ref());
16545 })
16546 .ok();
16547 }
16548 Err(err) => {
16549 let message = format!("Failed to open permalink: {err}");
16550
16551 Err::<(), anyhow::Error>(err).log_err();
16552
16553 if let Some(workspace) = workspace {
16554 workspace
16555 .update(cx, |workspace, cx| {
16556 struct OpenPermalinkToLine;
16557
16558 workspace.show_toast(
16559 Toast::new(
16560 NotificationId::unique::<OpenPermalinkToLine>(),
16561 message,
16562 ),
16563 cx,
16564 )
16565 })
16566 .ok();
16567 }
16568 }
16569 })
16570 .detach();
16571 }
16572
16573 pub fn insert_uuid_v4(
16574 &mut self,
16575 _: &InsertUuidV4,
16576 window: &mut Window,
16577 cx: &mut Context<Self>,
16578 ) {
16579 self.insert_uuid(UuidVersion::V4, window, cx);
16580 }
16581
16582 pub fn insert_uuid_v7(
16583 &mut self,
16584 _: &InsertUuidV7,
16585 window: &mut Window,
16586 cx: &mut Context<Self>,
16587 ) {
16588 self.insert_uuid(UuidVersion::V7, window, cx);
16589 }
16590
16591 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16592 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16593 self.transact(window, cx, |this, window, cx| {
16594 let edits = this
16595 .selections
16596 .all::<Point>(cx)
16597 .into_iter()
16598 .map(|selection| {
16599 let uuid = match version {
16600 UuidVersion::V4 => uuid::Uuid::new_v4(),
16601 UuidVersion::V7 => uuid::Uuid::now_v7(),
16602 };
16603
16604 (selection.range(), uuid.to_string())
16605 });
16606 this.edit(edits, cx);
16607 this.refresh_inline_completion(true, false, window, cx);
16608 });
16609 }
16610
16611 pub fn open_selections_in_multibuffer(
16612 &mut self,
16613 _: &OpenSelectionsInMultibuffer,
16614 window: &mut Window,
16615 cx: &mut Context<Self>,
16616 ) {
16617 let multibuffer = self.buffer.read(cx);
16618
16619 let Some(buffer) = multibuffer.as_singleton() else {
16620 return;
16621 };
16622
16623 let Some(workspace) = self.workspace() else {
16624 return;
16625 };
16626
16627 let locations = self
16628 .selections
16629 .disjoint_anchors()
16630 .iter()
16631 .map(|range| Location {
16632 buffer: buffer.clone(),
16633 range: range.start.text_anchor..range.end.text_anchor,
16634 })
16635 .collect::<Vec<_>>();
16636
16637 let title = multibuffer.title(cx).to_string();
16638
16639 cx.spawn_in(window, async move |_, cx| {
16640 workspace.update_in(cx, |workspace, window, cx| {
16641 Self::open_locations_in_multibuffer(
16642 workspace,
16643 locations,
16644 format!("Selections for '{title}'"),
16645 false,
16646 MultibufferSelectionMode::All,
16647 window,
16648 cx,
16649 );
16650 })
16651 })
16652 .detach();
16653 }
16654
16655 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16656 /// last highlight added will be used.
16657 ///
16658 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16659 pub fn highlight_rows<T: 'static>(
16660 &mut self,
16661 range: Range<Anchor>,
16662 color: Hsla,
16663 should_autoscroll: bool,
16664 cx: &mut Context<Self>,
16665 ) {
16666 let snapshot = self.buffer().read(cx).snapshot(cx);
16667 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16668 let ix = row_highlights.binary_search_by(|highlight| {
16669 Ordering::Equal
16670 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16671 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16672 });
16673
16674 if let Err(mut ix) = ix {
16675 let index = post_inc(&mut self.highlight_order);
16676
16677 // If this range intersects with the preceding highlight, then merge it with
16678 // the preceding highlight. Otherwise insert a new highlight.
16679 let mut merged = false;
16680 if ix > 0 {
16681 let prev_highlight = &mut row_highlights[ix - 1];
16682 if prev_highlight
16683 .range
16684 .end
16685 .cmp(&range.start, &snapshot)
16686 .is_ge()
16687 {
16688 ix -= 1;
16689 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16690 prev_highlight.range.end = range.end;
16691 }
16692 merged = true;
16693 prev_highlight.index = index;
16694 prev_highlight.color = color;
16695 prev_highlight.should_autoscroll = should_autoscroll;
16696 }
16697 }
16698
16699 if !merged {
16700 row_highlights.insert(
16701 ix,
16702 RowHighlight {
16703 range: range.clone(),
16704 index,
16705 color,
16706 should_autoscroll,
16707 },
16708 );
16709 }
16710
16711 // If any of the following highlights intersect with this one, merge them.
16712 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16713 let highlight = &row_highlights[ix];
16714 if next_highlight
16715 .range
16716 .start
16717 .cmp(&highlight.range.end, &snapshot)
16718 .is_le()
16719 {
16720 if next_highlight
16721 .range
16722 .end
16723 .cmp(&highlight.range.end, &snapshot)
16724 .is_gt()
16725 {
16726 row_highlights[ix].range.end = next_highlight.range.end;
16727 }
16728 row_highlights.remove(ix + 1);
16729 } else {
16730 break;
16731 }
16732 }
16733 }
16734 }
16735
16736 /// Remove any highlighted row ranges of the given type that intersect the
16737 /// given ranges.
16738 pub fn remove_highlighted_rows<T: 'static>(
16739 &mut self,
16740 ranges_to_remove: Vec<Range<Anchor>>,
16741 cx: &mut Context<Self>,
16742 ) {
16743 let snapshot = self.buffer().read(cx).snapshot(cx);
16744 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16745 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16746 row_highlights.retain(|highlight| {
16747 while let Some(range_to_remove) = ranges_to_remove.peek() {
16748 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16749 Ordering::Less | Ordering::Equal => {
16750 ranges_to_remove.next();
16751 }
16752 Ordering::Greater => {
16753 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16754 Ordering::Less | Ordering::Equal => {
16755 return false;
16756 }
16757 Ordering::Greater => break,
16758 }
16759 }
16760 }
16761 }
16762
16763 true
16764 })
16765 }
16766
16767 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16768 pub fn clear_row_highlights<T: 'static>(&mut self) {
16769 self.highlighted_rows.remove(&TypeId::of::<T>());
16770 }
16771
16772 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16773 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16774 self.highlighted_rows
16775 .get(&TypeId::of::<T>())
16776 .map_or(&[] as &[_], |vec| vec.as_slice())
16777 .iter()
16778 .map(|highlight| (highlight.range.clone(), highlight.color))
16779 }
16780
16781 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16782 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16783 /// Allows to ignore certain kinds of highlights.
16784 pub fn highlighted_display_rows(
16785 &self,
16786 window: &mut Window,
16787 cx: &mut App,
16788 ) -> BTreeMap<DisplayRow, LineHighlight> {
16789 let snapshot = self.snapshot(window, cx);
16790 let mut used_highlight_orders = HashMap::default();
16791 self.highlighted_rows
16792 .iter()
16793 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16794 .fold(
16795 BTreeMap::<DisplayRow, LineHighlight>::new(),
16796 |mut unique_rows, highlight| {
16797 let start = highlight.range.start.to_display_point(&snapshot);
16798 let end = highlight.range.end.to_display_point(&snapshot);
16799 let start_row = start.row().0;
16800 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16801 && end.column() == 0
16802 {
16803 end.row().0.saturating_sub(1)
16804 } else {
16805 end.row().0
16806 };
16807 for row in start_row..=end_row {
16808 let used_index =
16809 used_highlight_orders.entry(row).or_insert(highlight.index);
16810 if highlight.index >= *used_index {
16811 *used_index = highlight.index;
16812 unique_rows.insert(DisplayRow(row), highlight.color.into());
16813 }
16814 }
16815 unique_rows
16816 },
16817 )
16818 }
16819
16820 pub fn highlighted_display_row_for_autoscroll(
16821 &self,
16822 snapshot: &DisplaySnapshot,
16823 ) -> Option<DisplayRow> {
16824 self.highlighted_rows
16825 .values()
16826 .flat_map(|highlighted_rows| highlighted_rows.iter())
16827 .filter_map(|highlight| {
16828 if highlight.should_autoscroll {
16829 Some(highlight.range.start.to_display_point(snapshot).row())
16830 } else {
16831 None
16832 }
16833 })
16834 .min()
16835 }
16836
16837 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16838 self.highlight_background::<SearchWithinRange>(
16839 ranges,
16840 |colors| colors.editor_document_highlight_read_background,
16841 cx,
16842 )
16843 }
16844
16845 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16846 self.breadcrumb_header = Some(new_header);
16847 }
16848
16849 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16850 self.clear_background_highlights::<SearchWithinRange>(cx);
16851 }
16852
16853 pub fn highlight_background<T: 'static>(
16854 &mut self,
16855 ranges: &[Range<Anchor>],
16856 color_fetcher: fn(&ThemeColors) -> Hsla,
16857 cx: &mut Context<Self>,
16858 ) {
16859 self.background_highlights
16860 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16861 self.scrollbar_marker_state.dirty = true;
16862 cx.notify();
16863 }
16864
16865 pub fn clear_background_highlights<T: 'static>(
16866 &mut self,
16867 cx: &mut Context<Self>,
16868 ) -> Option<BackgroundHighlight> {
16869 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16870 if !text_highlights.1.is_empty() {
16871 self.scrollbar_marker_state.dirty = true;
16872 cx.notify();
16873 }
16874 Some(text_highlights)
16875 }
16876
16877 pub fn highlight_gutter<T: 'static>(
16878 &mut self,
16879 ranges: &[Range<Anchor>],
16880 color_fetcher: fn(&App) -> Hsla,
16881 cx: &mut Context<Self>,
16882 ) {
16883 self.gutter_highlights
16884 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16885 cx.notify();
16886 }
16887
16888 pub fn clear_gutter_highlights<T: 'static>(
16889 &mut self,
16890 cx: &mut Context<Self>,
16891 ) -> Option<GutterHighlight> {
16892 cx.notify();
16893 self.gutter_highlights.remove(&TypeId::of::<T>())
16894 }
16895
16896 #[cfg(feature = "test-support")]
16897 pub fn all_text_background_highlights(
16898 &self,
16899 window: &mut Window,
16900 cx: &mut Context<Self>,
16901 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16902 let snapshot = self.snapshot(window, cx);
16903 let buffer = &snapshot.buffer_snapshot;
16904 let start = buffer.anchor_before(0);
16905 let end = buffer.anchor_after(buffer.len());
16906 let theme = cx.theme().colors();
16907 self.background_highlights_in_range(start..end, &snapshot, theme)
16908 }
16909
16910 #[cfg(feature = "test-support")]
16911 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16912 let snapshot = self.buffer().read(cx).snapshot(cx);
16913
16914 let highlights = self
16915 .background_highlights
16916 .get(&TypeId::of::<items::BufferSearchHighlights>());
16917
16918 if let Some((_color, ranges)) = highlights {
16919 ranges
16920 .iter()
16921 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16922 .collect_vec()
16923 } else {
16924 vec![]
16925 }
16926 }
16927
16928 fn document_highlights_for_position<'a>(
16929 &'a self,
16930 position: Anchor,
16931 buffer: &'a MultiBufferSnapshot,
16932 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16933 let read_highlights = self
16934 .background_highlights
16935 .get(&TypeId::of::<DocumentHighlightRead>())
16936 .map(|h| &h.1);
16937 let write_highlights = self
16938 .background_highlights
16939 .get(&TypeId::of::<DocumentHighlightWrite>())
16940 .map(|h| &h.1);
16941 let left_position = position.bias_left(buffer);
16942 let right_position = position.bias_right(buffer);
16943 read_highlights
16944 .into_iter()
16945 .chain(write_highlights)
16946 .flat_map(move |ranges| {
16947 let start_ix = match ranges.binary_search_by(|probe| {
16948 let cmp = probe.end.cmp(&left_position, buffer);
16949 if cmp.is_ge() {
16950 Ordering::Greater
16951 } else {
16952 Ordering::Less
16953 }
16954 }) {
16955 Ok(i) | Err(i) => i,
16956 };
16957
16958 ranges[start_ix..]
16959 .iter()
16960 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16961 })
16962 }
16963
16964 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16965 self.background_highlights
16966 .get(&TypeId::of::<T>())
16967 .map_or(false, |(_, highlights)| !highlights.is_empty())
16968 }
16969
16970 pub fn background_highlights_in_range(
16971 &self,
16972 search_range: Range<Anchor>,
16973 display_snapshot: &DisplaySnapshot,
16974 theme: &ThemeColors,
16975 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16976 let mut results = Vec::new();
16977 for (color_fetcher, ranges) in self.background_highlights.values() {
16978 let color = color_fetcher(theme);
16979 let start_ix = match ranges.binary_search_by(|probe| {
16980 let cmp = probe
16981 .end
16982 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16983 if cmp.is_gt() {
16984 Ordering::Greater
16985 } else {
16986 Ordering::Less
16987 }
16988 }) {
16989 Ok(i) | Err(i) => i,
16990 };
16991 for range in &ranges[start_ix..] {
16992 if range
16993 .start
16994 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16995 .is_ge()
16996 {
16997 break;
16998 }
16999
17000 let start = range.start.to_display_point(display_snapshot);
17001 let end = range.end.to_display_point(display_snapshot);
17002 results.push((start..end, color))
17003 }
17004 }
17005 results
17006 }
17007
17008 pub fn background_highlight_row_ranges<T: 'static>(
17009 &self,
17010 search_range: Range<Anchor>,
17011 display_snapshot: &DisplaySnapshot,
17012 count: usize,
17013 ) -> Vec<RangeInclusive<DisplayPoint>> {
17014 let mut results = Vec::new();
17015 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17016 return vec![];
17017 };
17018
17019 let start_ix = match ranges.binary_search_by(|probe| {
17020 let cmp = probe
17021 .end
17022 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17023 if cmp.is_gt() {
17024 Ordering::Greater
17025 } else {
17026 Ordering::Less
17027 }
17028 }) {
17029 Ok(i) | Err(i) => i,
17030 };
17031 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17032 if let (Some(start_display), Some(end_display)) = (start, end) {
17033 results.push(
17034 start_display.to_display_point(display_snapshot)
17035 ..=end_display.to_display_point(display_snapshot),
17036 );
17037 }
17038 };
17039 let mut start_row: Option<Point> = None;
17040 let mut end_row: Option<Point> = None;
17041 if ranges.len() > count {
17042 return Vec::new();
17043 }
17044 for range in &ranges[start_ix..] {
17045 if range
17046 .start
17047 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17048 .is_ge()
17049 {
17050 break;
17051 }
17052 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17053 if let Some(current_row) = &end_row {
17054 if end.row == current_row.row {
17055 continue;
17056 }
17057 }
17058 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17059 if start_row.is_none() {
17060 assert_eq!(end_row, None);
17061 start_row = Some(start);
17062 end_row = Some(end);
17063 continue;
17064 }
17065 if let Some(current_end) = end_row.as_mut() {
17066 if start.row > current_end.row + 1 {
17067 push_region(start_row, end_row);
17068 start_row = Some(start);
17069 end_row = Some(end);
17070 } else {
17071 // Merge two hunks.
17072 *current_end = end;
17073 }
17074 } else {
17075 unreachable!();
17076 }
17077 }
17078 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17079 push_region(start_row, end_row);
17080 results
17081 }
17082
17083 pub fn gutter_highlights_in_range(
17084 &self,
17085 search_range: Range<Anchor>,
17086 display_snapshot: &DisplaySnapshot,
17087 cx: &App,
17088 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17089 let mut results = Vec::new();
17090 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17091 let color = color_fetcher(cx);
17092 let start_ix = match ranges.binary_search_by(|probe| {
17093 let cmp = probe
17094 .end
17095 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17096 if cmp.is_gt() {
17097 Ordering::Greater
17098 } else {
17099 Ordering::Less
17100 }
17101 }) {
17102 Ok(i) | Err(i) => i,
17103 };
17104 for range in &ranges[start_ix..] {
17105 if range
17106 .start
17107 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17108 .is_ge()
17109 {
17110 break;
17111 }
17112
17113 let start = range.start.to_display_point(display_snapshot);
17114 let end = range.end.to_display_point(display_snapshot);
17115 results.push((start..end, color))
17116 }
17117 }
17118 results
17119 }
17120
17121 /// Get the text ranges corresponding to the redaction query
17122 pub fn redacted_ranges(
17123 &self,
17124 search_range: Range<Anchor>,
17125 display_snapshot: &DisplaySnapshot,
17126 cx: &App,
17127 ) -> Vec<Range<DisplayPoint>> {
17128 display_snapshot
17129 .buffer_snapshot
17130 .redacted_ranges(search_range, |file| {
17131 if let Some(file) = file {
17132 file.is_private()
17133 && EditorSettings::get(
17134 Some(SettingsLocation {
17135 worktree_id: file.worktree_id(cx),
17136 path: file.path().as_ref(),
17137 }),
17138 cx,
17139 )
17140 .redact_private_values
17141 } else {
17142 false
17143 }
17144 })
17145 .map(|range| {
17146 range.start.to_display_point(display_snapshot)
17147 ..range.end.to_display_point(display_snapshot)
17148 })
17149 .collect()
17150 }
17151
17152 pub fn highlight_text<T: 'static>(
17153 &mut self,
17154 ranges: Vec<Range<Anchor>>,
17155 style: HighlightStyle,
17156 cx: &mut Context<Self>,
17157 ) {
17158 self.display_map.update(cx, |map, _| {
17159 map.highlight_text(TypeId::of::<T>(), ranges, style)
17160 });
17161 cx.notify();
17162 }
17163
17164 pub(crate) fn highlight_inlays<T: 'static>(
17165 &mut self,
17166 highlights: Vec<InlayHighlight>,
17167 style: HighlightStyle,
17168 cx: &mut Context<Self>,
17169 ) {
17170 self.display_map.update(cx, |map, _| {
17171 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17172 });
17173 cx.notify();
17174 }
17175
17176 pub fn text_highlights<'a, T: 'static>(
17177 &'a self,
17178 cx: &'a App,
17179 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17180 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17181 }
17182
17183 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17184 let cleared = self
17185 .display_map
17186 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17187 if cleared {
17188 cx.notify();
17189 }
17190 }
17191
17192 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17193 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17194 && self.focus_handle.is_focused(window)
17195 }
17196
17197 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17198 self.show_cursor_when_unfocused = is_enabled;
17199 cx.notify();
17200 }
17201
17202 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17203 cx.notify();
17204 }
17205
17206 fn on_buffer_event(
17207 &mut self,
17208 multibuffer: &Entity<MultiBuffer>,
17209 event: &multi_buffer::Event,
17210 window: &mut Window,
17211 cx: &mut Context<Self>,
17212 ) {
17213 match event {
17214 multi_buffer::Event::Edited {
17215 singleton_buffer_edited,
17216 edited_buffer: buffer_edited,
17217 } => {
17218 self.scrollbar_marker_state.dirty = true;
17219 self.active_indent_guides_state.dirty = true;
17220 self.refresh_active_diagnostics(cx);
17221 self.refresh_code_actions(window, cx);
17222 if self.has_active_inline_completion() {
17223 self.update_visible_inline_completion(window, cx);
17224 }
17225 if let Some(buffer) = buffer_edited {
17226 let buffer_id = buffer.read(cx).remote_id();
17227 if !self.registered_buffers.contains_key(&buffer_id) {
17228 if let Some(project) = self.project.as_ref() {
17229 project.update(cx, |project, cx| {
17230 self.registered_buffers.insert(
17231 buffer_id,
17232 project.register_buffer_with_language_servers(&buffer, cx),
17233 );
17234 })
17235 }
17236 }
17237 }
17238 cx.emit(EditorEvent::BufferEdited);
17239 cx.emit(SearchEvent::MatchesInvalidated);
17240 if *singleton_buffer_edited {
17241 if let Some(project) = &self.project {
17242 #[allow(clippy::mutable_key_type)]
17243 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17244 multibuffer
17245 .all_buffers()
17246 .into_iter()
17247 .filter_map(|buffer| {
17248 buffer.update(cx, |buffer, cx| {
17249 let language = buffer.language()?;
17250 let should_discard = project.update(cx, |project, cx| {
17251 project.is_local()
17252 && !project.has_language_servers_for(buffer, cx)
17253 });
17254 should_discard.not().then_some(language.clone())
17255 })
17256 })
17257 .collect::<HashSet<_>>()
17258 });
17259 if !languages_affected.is_empty() {
17260 self.refresh_inlay_hints(
17261 InlayHintRefreshReason::BufferEdited(languages_affected),
17262 cx,
17263 );
17264 }
17265 }
17266 }
17267
17268 let Some(project) = &self.project else { return };
17269 let (telemetry, is_via_ssh) = {
17270 let project = project.read(cx);
17271 let telemetry = project.client().telemetry().clone();
17272 let is_via_ssh = project.is_via_ssh();
17273 (telemetry, is_via_ssh)
17274 };
17275 refresh_linked_ranges(self, window, cx);
17276 telemetry.log_edit_event("editor", is_via_ssh);
17277 }
17278 multi_buffer::Event::ExcerptsAdded {
17279 buffer,
17280 predecessor,
17281 excerpts,
17282 } => {
17283 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17284 let buffer_id = buffer.read(cx).remote_id();
17285 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17286 if let Some(project) = &self.project {
17287 get_uncommitted_diff_for_buffer(
17288 project,
17289 [buffer.clone()],
17290 self.buffer.clone(),
17291 cx,
17292 )
17293 .detach();
17294 }
17295 }
17296 cx.emit(EditorEvent::ExcerptsAdded {
17297 buffer: buffer.clone(),
17298 predecessor: *predecessor,
17299 excerpts: excerpts.clone(),
17300 });
17301 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17302 }
17303 multi_buffer::Event::ExcerptsRemoved { ids } => {
17304 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17305 let buffer = self.buffer.read(cx);
17306 self.registered_buffers
17307 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17308 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17309 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17310 }
17311 multi_buffer::Event::ExcerptsEdited {
17312 excerpt_ids,
17313 buffer_ids,
17314 } => {
17315 self.display_map.update(cx, |map, cx| {
17316 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17317 });
17318 cx.emit(EditorEvent::ExcerptsEdited {
17319 ids: excerpt_ids.clone(),
17320 })
17321 }
17322 multi_buffer::Event::ExcerptsExpanded { ids } => {
17323 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17324 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17325 }
17326 multi_buffer::Event::Reparsed(buffer_id) => {
17327 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17328 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17329
17330 cx.emit(EditorEvent::Reparsed(*buffer_id));
17331 }
17332 multi_buffer::Event::DiffHunksToggled => {
17333 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17334 }
17335 multi_buffer::Event::LanguageChanged(buffer_id) => {
17336 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17337 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17338 cx.emit(EditorEvent::Reparsed(*buffer_id));
17339 cx.notify();
17340 }
17341 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17342 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17343 multi_buffer::Event::FileHandleChanged
17344 | multi_buffer::Event::Reloaded
17345 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17346 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17347 multi_buffer::Event::DiagnosticsUpdated => {
17348 self.refresh_active_diagnostics(cx);
17349 self.refresh_inline_diagnostics(true, window, cx);
17350 self.scrollbar_marker_state.dirty = true;
17351 cx.notify();
17352 }
17353 _ => {}
17354 };
17355 }
17356
17357 fn on_display_map_changed(
17358 &mut self,
17359 _: Entity<DisplayMap>,
17360 _: &mut Window,
17361 cx: &mut Context<Self>,
17362 ) {
17363 cx.notify();
17364 }
17365
17366 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17367 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17368 self.update_edit_prediction_settings(cx);
17369 self.refresh_inline_completion(true, false, window, cx);
17370 self.refresh_inlay_hints(
17371 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17372 self.selections.newest_anchor().head(),
17373 &self.buffer.read(cx).snapshot(cx),
17374 cx,
17375 )),
17376 cx,
17377 );
17378
17379 let old_cursor_shape = self.cursor_shape;
17380
17381 {
17382 let editor_settings = EditorSettings::get_global(cx);
17383 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17384 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17385 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17386 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17387 }
17388
17389 if old_cursor_shape != self.cursor_shape {
17390 cx.emit(EditorEvent::CursorShapeChanged);
17391 }
17392
17393 let project_settings = ProjectSettings::get_global(cx);
17394 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17395
17396 if self.mode.is_full() {
17397 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17398 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17399 if self.show_inline_diagnostics != show_inline_diagnostics {
17400 self.show_inline_diagnostics = show_inline_diagnostics;
17401 self.refresh_inline_diagnostics(false, window, cx);
17402 }
17403
17404 if self.git_blame_inline_enabled != inline_blame_enabled {
17405 self.toggle_git_blame_inline_internal(false, window, cx);
17406 }
17407 }
17408
17409 cx.notify();
17410 }
17411
17412 pub fn set_searchable(&mut self, searchable: bool) {
17413 self.searchable = searchable;
17414 }
17415
17416 pub fn searchable(&self) -> bool {
17417 self.searchable
17418 }
17419
17420 fn open_proposed_changes_editor(
17421 &mut self,
17422 _: &OpenProposedChangesEditor,
17423 window: &mut Window,
17424 cx: &mut Context<Self>,
17425 ) {
17426 let Some(workspace) = self.workspace() else {
17427 cx.propagate();
17428 return;
17429 };
17430
17431 let selections = self.selections.all::<usize>(cx);
17432 let multi_buffer = self.buffer.read(cx);
17433 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17434 let mut new_selections_by_buffer = HashMap::default();
17435 for selection in selections {
17436 for (buffer, range, _) in
17437 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17438 {
17439 let mut range = range.to_point(buffer);
17440 range.start.column = 0;
17441 range.end.column = buffer.line_len(range.end.row);
17442 new_selections_by_buffer
17443 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17444 .or_insert(Vec::new())
17445 .push(range)
17446 }
17447 }
17448
17449 let proposed_changes_buffers = new_selections_by_buffer
17450 .into_iter()
17451 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17452 .collect::<Vec<_>>();
17453 let proposed_changes_editor = cx.new(|cx| {
17454 ProposedChangesEditor::new(
17455 "Proposed changes",
17456 proposed_changes_buffers,
17457 self.project.clone(),
17458 window,
17459 cx,
17460 )
17461 });
17462
17463 window.defer(cx, move |window, cx| {
17464 workspace.update(cx, |workspace, cx| {
17465 workspace.active_pane().update(cx, |pane, cx| {
17466 pane.add_item(
17467 Box::new(proposed_changes_editor),
17468 true,
17469 true,
17470 None,
17471 window,
17472 cx,
17473 );
17474 });
17475 });
17476 });
17477 }
17478
17479 pub fn open_excerpts_in_split(
17480 &mut self,
17481 _: &OpenExcerptsSplit,
17482 window: &mut Window,
17483 cx: &mut Context<Self>,
17484 ) {
17485 self.open_excerpts_common(None, true, window, cx)
17486 }
17487
17488 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17489 self.open_excerpts_common(None, false, window, cx)
17490 }
17491
17492 fn open_excerpts_common(
17493 &mut self,
17494 jump_data: Option<JumpData>,
17495 split: bool,
17496 window: &mut Window,
17497 cx: &mut Context<Self>,
17498 ) {
17499 let Some(workspace) = self.workspace() else {
17500 cx.propagate();
17501 return;
17502 };
17503
17504 if self.buffer.read(cx).is_singleton() {
17505 cx.propagate();
17506 return;
17507 }
17508
17509 let mut new_selections_by_buffer = HashMap::default();
17510 match &jump_data {
17511 Some(JumpData::MultiBufferPoint {
17512 excerpt_id,
17513 position,
17514 anchor,
17515 line_offset_from_top,
17516 }) => {
17517 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17518 if let Some(buffer) = multi_buffer_snapshot
17519 .buffer_id_for_excerpt(*excerpt_id)
17520 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17521 {
17522 let buffer_snapshot = buffer.read(cx).snapshot();
17523 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17524 language::ToPoint::to_point(anchor, &buffer_snapshot)
17525 } else {
17526 buffer_snapshot.clip_point(*position, Bias::Left)
17527 };
17528 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17529 new_selections_by_buffer.insert(
17530 buffer,
17531 (
17532 vec![jump_to_offset..jump_to_offset],
17533 Some(*line_offset_from_top),
17534 ),
17535 );
17536 }
17537 }
17538 Some(JumpData::MultiBufferRow {
17539 row,
17540 line_offset_from_top,
17541 }) => {
17542 let point = MultiBufferPoint::new(row.0, 0);
17543 if let Some((buffer, buffer_point, _)) =
17544 self.buffer.read(cx).point_to_buffer_point(point, cx)
17545 {
17546 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17547 new_selections_by_buffer
17548 .entry(buffer)
17549 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17550 .0
17551 .push(buffer_offset..buffer_offset)
17552 }
17553 }
17554 None => {
17555 let selections = self.selections.all::<usize>(cx);
17556 let multi_buffer = self.buffer.read(cx);
17557 for selection in selections {
17558 for (snapshot, range, _, anchor) in multi_buffer
17559 .snapshot(cx)
17560 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17561 {
17562 if let Some(anchor) = anchor {
17563 // selection is in a deleted hunk
17564 let Some(buffer_id) = anchor.buffer_id else {
17565 continue;
17566 };
17567 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17568 continue;
17569 };
17570 let offset = text::ToOffset::to_offset(
17571 &anchor.text_anchor,
17572 &buffer_handle.read(cx).snapshot(),
17573 );
17574 let range = offset..offset;
17575 new_selections_by_buffer
17576 .entry(buffer_handle)
17577 .or_insert((Vec::new(), None))
17578 .0
17579 .push(range)
17580 } else {
17581 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17582 else {
17583 continue;
17584 };
17585 new_selections_by_buffer
17586 .entry(buffer_handle)
17587 .or_insert((Vec::new(), None))
17588 .0
17589 .push(range)
17590 }
17591 }
17592 }
17593 }
17594 }
17595
17596 new_selections_by_buffer
17597 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17598
17599 if new_selections_by_buffer.is_empty() {
17600 return;
17601 }
17602
17603 // We defer the pane interaction because we ourselves are a workspace item
17604 // and activating a new item causes the pane to call a method on us reentrantly,
17605 // which panics if we're on the stack.
17606 window.defer(cx, move |window, cx| {
17607 workspace.update(cx, |workspace, cx| {
17608 let pane = if split {
17609 workspace.adjacent_pane(window, cx)
17610 } else {
17611 workspace.active_pane().clone()
17612 };
17613
17614 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17615 let editor = buffer
17616 .read(cx)
17617 .file()
17618 .is_none()
17619 .then(|| {
17620 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17621 // so `workspace.open_project_item` will never find them, always opening a new editor.
17622 // Instead, we try to activate the existing editor in the pane first.
17623 let (editor, pane_item_index) =
17624 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17625 let editor = item.downcast::<Editor>()?;
17626 let singleton_buffer =
17627 editor.read(cx).buffer().read(cx).as_singleton()?;
17628 if singleton_buffer == buffer {
17629 Some((editor, i))
17630 } else {
17631 None
17632 }
17633 })?;
17634 pane.update(cx, |pane, cx| {
17635 pane.activate_item(pane_item_index, true, true, window, cx)
17636 });
17637 Some(editor)
17638 })
17639 .flatten()
17640 .unwrap_or_else(|| {
17641 workspace.open_project_item::<Self>(
17642 pane.clone(),
17643 buffer,
17644 true,
17645 true,
17646 window,
17647 cx,
17648 )
17649 });
17650
17651 editor.update(cx, |editor, cx| {
17652 let autoscroll = match scroll_offset {
17653 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17654 None => Autoscroll::newest(),
17655 };
17656 let nav_history = editor.nav_history.take();
17657 editor.change_selections(Some(autoscroll), window, cx, |s| {
17658 s.select_ranges(ranges);
17659 });
17660 editor.nav_history = nav_history;
17661 });
17662 }
17663 })
17664 });
17665 }
17666
17667 // For now, don't allow opening excerpts in buffers that aren't backed by
17668 // regular project files.
17669 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17670 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17671 }
17672
17673 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17674 let snapshot = self.buffer.read(cx).read(cx);
17675 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17676 Some(
17677 ranges
17678 .iter()
17679 .map(move |range| {
17680 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17681 })
17682 .collect(),
17683 )
17684 }
17685
17686 fn selection_replacement_ranges(
17687 &self,
17688 range: Range<OffsetUtf16>,
17689 cx: &mut App,
17690 ) -> Vec<Range<OffsetUtf16>> {
17691 let selections = self.selections.all::<OffsetUtf16>(cx);
17692 let newest_selection = selections
17693 .iter()
17694 .max_by_key(|selection| selection.id)
17695 .unwrap();
17696 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17697 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17698 let snapshot = self.buffer.read(cx).read(cx);
17699 selections
17700 .into_iter()
17701 .map(|mut selection| {
17702 selection.start.0 =
17703 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17704 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17705 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17706 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17707 })
17708 .collect()
17709 }
17710
17711 fn report_editor_event(
17712 &self,
17713 event_type: &'static str,
17714 file_extension: Option<String>,
17715 cx: &App,
17716 ) {
17717 if cfg!(any(test, feature = "test-support")) {
17718 return;
17719 }
17720
17721 let Some(project) = &self.project else { return };
17722
17723 // If None, we are in a file without an extension
17724 let file = self
17725 .buffer
17726 .read(cx)
17727 .as_singleton()
17728 .and_then(|b| b.read(cx).file());
17729 let file_extension = file_extension.or(file
17730 .as_ref()
17731 .and_then(|file| Path::new(file.file_name(cx)).extension())
17732 .and_then(|e| e.to_str())
17733 .map(|a| a.to_string()));
17734
17735 let vim_mode = cx
17736 .global::<SettingsStore>()
17737 .raw_user_settings()
17738 .get("vim_mode")
17739 == Some(&serde_json::Value::Bool(true));
17740
17741 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17742 let copilot_enabled = edit_predictions_provider
17743 == language::language_settings::EditPredictionProvider::Copilot;
17744 let copilot_enabled_for_language = self
17745 .buffer
17746 .read(cx)
17747 .language_settings(cx)
17748 .show_edit_predictions;
17749
17750 let project = project.read(cx);
17751 telemetry::event!(
17752 event_type,
17753 file_extension,
17754 vim_mode,
17755 copilot_enabled,
17756 copilot_enabled_for_language,
17757 edit_predictions_provider,
17758 is_via_ssh = project.is_via_ssh(),
17759 );
17760 }
17761
17762 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17763 /// with each line being an array of {text, highlight} objects.
17764 fn copy_highlight_json(
17765 &mut self,
17766 _: &CopyHighlightJson,
17767 window: &mut Window,
17768 cx: &mut Context<Self>,
17769 ) {
17770 #[derive(Serialize)]
17771 struct Chunk<'a> {
17772 text: String,
17773 highlight: Option<&'a str>,
17774 }
17775
17776 let snapshot = self.buffer.read(cx).snapshot(cx);
17777 let range = self
17778 .selected_text_range(false, window, cx)
17779 .and_then(|selection| {
17780 if selection.range.is_empty() {
17781 None
17782 } else {
17783 Some(selection.range)
17784 }
17785 })
17786 .unwrap_or_else(|| 0..snapshot.len());
17787
17788 let chunks = snapshot.chunks(range, true);
17789 let mut lines = Vec::new();
17790 let mut line: VecDeque<Chunk> = VecDeque::new();
17791
17792 let Some(style) = self.style.as_ref() else {
17793 return;
17794 };
17795
17796 for chunk in chunks {
17797 let highlight = chunk
17798 .syntax_highlight_id
17799 .and_then(|id| id.name(&style.syntax));
17800 let mut chunk_lines = chunk.text.split('\n').peekable();
17801 while let Some(text) = chunk_lines.next() {
17802 let mut merged_with_last_token = false;
17803 if let Some(last_token) = line.back_mut() {
17804 if last_token.highlight == highlight {
17805 last_token.text.push_str(text);
17806 merged_with_last_token = true;
17807 }
17808 }
17809
17810 if !merged_with_last_token {
17811 line.push_back(Chunk {
17812 text: text.into(),
17813 highlight,
17814 });
17815 }
17816
17817 if chunk_lines.peek().is_some() {
17818 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17819 line.pop_front();
17820 }
17821 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17822 line.pop_back();
17823 }
17824
17825 lines.push(mem::take(&mut line));
17826 }
17827 }
17828 }
17829
17830 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17831 return;
17832 };
17833 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17834 }
17835
17836 pub fn open_context_menu(
17837 &mut self,
17838 _: &OpenContextMenu,
17839 window: &mut Window,
17840 cx: &mut Context<Self>,
17841 ) {
17842 self.request_autoscroll(Autoscroll::newest(), cx);
17843 let position = self.selections.newest_display(cx).start;
17844 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17845 }
17846
17847 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17848 &self.inlay_hint_cache
17849 }
17850
17851 pub fn replay_insert_event(
17852 &mut self,
17853 text: &str,
17854 relative_utf16_range: Option<Range<isize>>,
17855 window: &mut Window,
17856 cx: &mut Context<Self>,
17857 ) {
17858 if !self.input_enabled {
17859 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17860 return;
17861 }
17862 if let Some(relative_utf16_range) = relative_utf16_range {
17863 let selections = self.selections.all::<OffsetUtf16>(cx);
17864 self.change_selections(None, window, cx, |s| {
17865 let new_ranges = selections.into_iter().map(|range| {
17866 let start = OffsetUtf16(
17867 range
17868 .head()
17869 .0
17870 .saturating_add_signed(relative_utf16_range.start),
17871 );
17872 let end = OffsetUtf16(
17873 range
17874 .head()
17875 .0
17876 .saturating_add_signed(relative_utf16_range.end),
17877 );
17878 start..end
17879 });
17880 s.select_ranges(new_ranges);
17881 });
17882 }
17883
17884 self.handle_input(text, window, cx);
17885 }
17886
17887 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17888 let Some(provider) = self.semantics_provider.as_ref() else {
17889 return false;
17890 };
17891
17892 let mut supports = false;
17893 self.buffer().update(cx, |this, cx| {
17894 this.for_each_buffer(|buffer| {
17895 supports |= provider.supports_inlay_hints(buffer, cx);
17896 });
17897 });
17898
17899 supports
17900 }
17901
17902 pub fn is_focused(&self, window: &Window) -> bool {
17903 self.focus_handle.is_focused(window)
17904 }
17905
17906 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17907 cx.emit(EditorEvent::Focused);
17908
17909 if let Some(descendant) = self
17910 .last_focused_descendant
17911 .take()
17912 .and_then(|descendant| descendant.upgrade())
17913 {
17914 window.focus(&descendant);
17915 } else {
17916 if let Some(blame) = self.blame.as_ref() {
17917 blame.update(cx, GitBlame::focus)
17918 }
17919
17920 self.blink_manager.update(cx, BlinkManager::enable);
17921 self.show_cursor_names(window, cx);
17922 self.buffer.update(cx, |buffer, cx| {
17923 buffer.finalize_last_transaction(cx);
17924 if self.leader_peer_id.is_none() {
17925 buffer.set_active_selections(
17926 &self.selections.disjoint_anchors(),
17927 self.selections.line_mode,
17928 self.cursor_shape,
17929 cx,
17930 );
17931 }
17932 });
17933 }
17934 }
17935
17936 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17937 cx.emit(EditorEvent::FocusedIn)
17938 }
17939
17940 fn handle_focus_out(
17941 &mut self,
17942 event: FocusOutEvent,
17943 _window: &mut Window,
17944 cx: &mut Context<Self>,
17945 ) {
17946 if event.blurred != self.focus_handle {
17947 self.last_focused_descendant = Some(event.blurred);
17948 }
17949 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17950 }
17951
17952 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17953 self.blink_manager.update(cx, BlinkManager::disable);
17954 self.buffer
17955 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17956
17957 if let Some(blame) = self.blame.as_ref() {
17958 blame.update(cx, GitBlame::blur)
17959 }
17960 if !self.hover_state.focused(window, cx) {
17961 hide_hover(self, cx);
17962 }
17963 if !self
17964 .context_menu
17965 .borrow()
17966 .as_ref()
17967 .is_some_and(|context_menu| context_menu.focused(window, cx))
17968 {
17969 self.hide_context_menu(window, cx);
17970 }
17971 self.discard_inline_completion(false, cx);
17972 cx.emit(EditorEvent::Blurred);
17973 cx.notify();
17974 }
17975
17976 pub fn register_action<A: Action>(
17977 &mut self,
17978 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17979 ) -> Subscription {
17980 let id = self.next_editor_action_id.post_inc();
17981 let listener = Arc::new(listener);
17982 self.editor_actions.borrow_mut().insert(
17983 id,
17984 Box::new(move |window, _| {
17985 let listener = listener.clone();
17986 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17987 let action = action.downcast_ref().unwrap();
17988 if phase == DispatchPhase::Bubble {
17989 listener(action, window, cx)
17990 }
17991 })
17992 }),
17993 );
17994
17995 let editor_actions = self.editor_actions.clone();
17996 Subscription::new(move || {
17997 editor_actions.borrow_mut().remove(&id);
17998 })
17999 }
18000
18001 pub fn file_header_size(&self) -> u32 {
18002 FILE_HEADER_HEIGHT
18003 }
18004
18005 pub fn restore(
18006 &mut self,
18007 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18008 window: &mut Window,
18009 cx: &mut Context<Self>,
18010 ) {
18011 let workspace = self.workspace();
18012 let project = self.project.as_ref();
18013 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18014 let mut tasks = Vec::new();
18015 for (buffer_id, changes) in revert_changes {
18016 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18017 buffer.update(cx, |buffer, cx| {
18018 buffer.edit(
18019 changes
18020 .into_iter()
18021 .map(|(range, text)| (range, text.to_string())),
18022 None,
18023 cx,
18024 );
18025 });
18026
18027 if let Some(project) =
18028 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18029 {
18030 project.update(cx, |project, cx| {
18031 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18032 })
18033 }
18034 }
18035 }
18036 tasks
18037 });
18038 cx.spawn_in(window, async move |_, cx| {
18039 for (buffer, task) in save_tasks {
18040 let result = task.await;
18041 if result.is_err() {
18042 let Some(path) = buffer
18043 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18044 .ok()
18045 else {
18046 continue;
18047 };
18048 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18049 let Some(task) = cx
18050 .update_window_entity(&workspace, |workspace, window, cx| {
18051 workspace
18052 .open_path_preview(path, None, false, false, false, window, cx)
18053 })
18054 .ok()
18055 else {
18056 continue;
18057 };
18058 task.await.log_err();
18059 }
18060 }
18061 }
18062 })
18063 .detach();
18064 self.change_selections(None, window, cx, |selections| selections.refresh());
18065 }
18066
18067 pub fn to_pixel_point(
18068 &self,
18069 source: multi_buffer::Anchor,
18070 editor_snapshot: &EditorSnapshot,
18071 window: &mut Window,
18072 ) -> Option<gpui::Point<Pixels>> {
18073 let source_point = source.to_display_point(editor_snapshot);
18074 self.display_to_pixel_point(source_point, editor_snapshot, window)
18075 }
18076
18077 pub fn display_to_pixel_point(
18078 &self,
18079 source: DisplayPoint,
18080 editor_snapshot: &EditorSnapshot,
18081 window: &mut Window,
18082 ) -> Option<gpui::Point<Pixels>> {
18083 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18084 let text_layout_details = self.text_layout_details(window);
18085 let scroll_top = text_layout_details
18086 .scroll_anchor
18087 .scroll_position(editor_snapshot)
18088 .y;
18089
18090 if source.row().as_f32() < scroll_top.floor() {
18091 return None;
18092 }
18093 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18094 let source_y = line_height * (source.row().as_f32() - scroll_top);
18095 Some(gpui::Point::new(source_x, source_y))
18096 }
18097
18098 pub fn has_visible_completions_menu(&self) -> bool {
18099 !self.edit_prediction_preview_is_active()
18100 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18101 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18102 })
18103 }
18104
18105 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18106 self.addons
18107 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18108 }
18109
18110 pub fn unregister_addon<T: Addon>(&mut self) {
18111 self.addons.remove(&std::any::TypeId::of::<T>());
18112 }
18113
18114 pub fn addon<T: Addon>(&self) -> Option<&T> {
18115 let type_id = std::any::TypeId::of::<T>();
18116 self.addons
18117 .get(&type_id)
18118 .and_then(|item| item.to_any().downcast_ref::<T>())
18119 }
18120
18121 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18122 let text_layout_details = self.text_layout_details(window);
18123 let style = &text_layout_details.editor_style;
18124 let font_id = window.text_system().resolve_font(&style.text.font());
18125 let font_size = style.text.font_size.to_pixels(window.rem_size());
18126 let line_height = style.text.line_height_in_pixels(window.rem_size());
18127 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18128
18129 gpui::Size::new(em_width, line_height)
18130 }
18131
18132 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18133 self.load_diff_task.clone()
18134 }
18135
18136 fn read_metadata_from_db(
18137 &mut self,
18138 item_id: u64,
18139 workspace_id: WorkspaceId,
18140 window: &mut Window,
18141 cx: &mut Context<Editor>,
18142 ) {
18143 if self.is_singleton(cx)
18144 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18145 {
18146 let buffer_snapshot = OnceCell::new();
18147
18148 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18149 if !folds.is_empty() {
18150 let snapshot =
18151 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18152 self.fold_ranges(
18153 folds
18154 .into_iter()
18155 .map(|(start, end)| {
18156 snapshot.clip_offset(start, Bias::Left)
18157 ..snapshot.clip_offset(end, Bias::Right)
18158 })
18159 .collect(),
18160 false,
18161 window,
18162 cx,
18163 );
18164 }
18165 }
18166
18167 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18168 if !selections.is_empty() {
18169 let snapshot =
18170 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18171 self.change_selections(None, window, cx, |s| {
18172 s.select_ranges(selections.into_iter().map(|(start, end)| {
18173 snapshot.clip_offset(start, Bias::Left)
18174 ..snapshot.clip_offset(end, Bias::Right)
18175 }));
18176 });
18177 }
18178 };
18179 }
18180
18181 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18182 }
18183}
18184
18185// Consider user intent and default settings
18186fn choose_completion_range(
18187 completion: &Completion,
18188 intent: CompletionIntent,
18189 buffer: &Entity<Buffer>,
18190 cx: &mut Context<Editor>,
18191) -> Range<usize> {
18192 fn should_replace(
18193 completion: &Completion,
18194 insert_range: &Range<text::Anchor>,
18195 intent: CompletionIntent,
18196 completion_mode_setting: LspInsertMode,
18197 buffer: &Buffer,
18198 ) -> bool {
18199 // specific actions take precedence over settings
18200 match intent {
18201 CompletionIntent::CompleteWithInsert => return false,
18202 CompletionIntent::CompleteWithReplace => return true,
18203 CompletionIntent::Complete | CompletionIntent::Compose => {}
18204 }
18205
18206 match completion_mode_setting {
18207 LspInsertMode::Insert => false,
18208 LspInsertMode::Replace => true,
18209 LspInsertMode::ReplaceSubsequence => {
18210 let mut text_to_replace = buffer.chars_for_range(
18211 buffer.anchor_before(completion.replace_range.start)
18212 ..buffer.anchor_after(completion.replace_range.end),
18213 );
18214 let mut completion_text = completion.new_text.chars();
18215
18216 // is `text_to_replace` a subsequence of `completion_text`
18217 text_to_replace
18218 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18219 }
18220 LspInsertMode::ReplaceSuffix => {
18221 let range_after_cursor = insert_range.end..completion.replace_range.end;
18222
18223 let text_after_cursor = buffer
18224 .text_for_range(
18225 buffer.anchor_before(range_after_cursor.start)
18226 ..buffer.anchor_after(range_after_cursor.end),
18227 )
18228 .collect::<String>();
18229 completion.new_text.ends_with(&text_after_cursor)
18230 }
18231 }
18232 }
18233
18234 let buffer = buffer.read(cx);
18235
18236 if let CompletionSource::Lsp {
18237 insert_range: Some(insert_range),
18238 ..
18239 } = &completion.source
18240 {
18241 let completion_mode_setting =
18242 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18243 .completions
18244 .lsp_insert_mode;
18245
18246 if !should_replace(
18247 completion,
18248 &insert_range,
18249 intent,
18250 completion_mode_setting,
18251 buffer,
18252 ) {
18253 return insert_range.to_offset(buffer);
18254 }
18255 }
18256
18257 completion.replace_range.to_offset(buffer)
18258}
18259
18260fn insert_extra_newline_brackets(
18261 buffer: &MultiBufferSnapshot,
18262 range: Range<usize>,
18263 language: &language::LanguageScope,
18264) -> bool {
18265 let leading_whitespace_len = buffer
18266 .reversed_chars_at(range.start)
18267 .take_while(|c| c.is_whitespace() && *c != '\n')
18268 .map(|c| c.len_utf8())
18269 .sum::<usize>();
18270 let trailing_whitespace_len = buffer
18271 .chars_at(range.end)
18272 .take_while(|c| c.is_whitespace() && *c != '\n')
18273 .map(|c| c.len_utf8())
18274 .sum::<usize>();
18275 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18276
18277 language.brackets().any(|(pair, enabled)| {
18278 let pair_start = pair.start.trim_end();
18279 let pair_end = pair.end.trim_start();
18280
18281 enabled
18282 && pair.newline
18283 && buffer.contains_str_at(range.end, pair_end)
18284 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18285 })
18286}
18287
18288fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18289 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18290 [(buffer, range, _)] => (*buffer, range.clone()),
18291 _ => return false,
18292 };
18293 let pair = {
18294 let mut result: Option<BracketMatch> = None;
18295
18296 for pair in buffer
18297 .all_bracket_ranges(range.clone())
18298 .filter(move |pair| {
18299 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18300 })
18301 {
18302 let len = pair.close_range.end - pair.open_range.start;
18303
18304 if let Some(existing) = &result {
18305 let existing_len = existing.close_range.end - existing.open_range.start;
18306 if len > existing_len {
18307 continue;
18308 }
18309 }
18310
18311 result = Some(pair);
18312 }
18313
18314 result
18315 };
18316 let Some(pair) = pair else {
18317 return false;
18318 };
18319 pair.newline_only
18320 && buffer
18321 .chars_for_range(pair.open_range.end..range.start)
18322 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18323 .all(|c| c.is_whitespace() && c != '\n')
18324}
18325
18326fn get_uncommitted_diff_for_buffer(
18327 project: &Entity<Project>,
18328 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18329 buffer: Entity<MultiBuffer>,
18330 cx: &mut App,
18331) -> Task<()> {
18332 let mut tasks = Vec::new();
18333 project.update(cx, |project, cx| {
18334 for buffer in buffers {
18335 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18336 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18337 }
18338 }
18339 });
18340 cx.spawn(async move |cx| {
18341 let diffs = future::join_all(tasks).await;
18342 buffer
18343 .update(cx, |buffer, cx| {
18344 for diff in diffs.into_iter().flatten() {
18345 buffer.add_diff(diff, cx);
18346 }
18347 })
18348 .ok();
18349 })
18350}
18351
18352fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18353 let tab_size = tab_size.get() as usize;
18354 let mut width = offset;
18355
18356 for ch in text.chars() {
18357 width += if ch == '\t' {
18358 tab_size - (width % tab_size)
18359 } else {
18360 1
18361 };
18362 }
18363
18364 width - offset
18365}
18366
18367#[cfg(test)]
18368mod tests {
18369 use super::*;
18370
18371 #[test]
18372 fn test_string_size_with_expanded_tabs() {
18373 let nz = |val| NonZeroU32::new(val).unwrap();
18374 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18375 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18376 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18377 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18378 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18379 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18380 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18381 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18382 }
18383}
18384
18385/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18386struct WordBreakingTokenizer<'a> {
18387 input: &'a str,
18388}
18389
18390impl<'a> WordBreakingTokenizer<'a> {
18391 fn new(input: &'a str) -> Self {
18392 Self { input }
18393 }
18394}
18395
18396fn is_char_ideographic(ch: char) -> bool {
18397 use unicode_script::Script::*;
18398 use unicode_script::UnicodeScript;
18399 matches!(ch.script(), Han | Tangut | Yi)
18400}
18401
18402fn is_grapheme_ideographic(text: &str) -> bool {
18403 text.chars().any(is_char_ideographic)
18404}
18405
18406fn is_grapheme_whitespace(text: &str) -> bool {
18407 text.chars().any(|x| x.is_whitespace())
18408}
18409
18410fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18411 text.chars().next().map_or(false, |ch| {
18412 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18413 })
18414}
18415
18416#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18417enum WordBreakToken<'a> {
18418 Word { token: &'a str, grapheme_len: usize },
18419 InlineWhitespace { token: &'a str, grapheme_len: usize },
18420 Newline,
18421}
18422
18423impl<'a> Iterator for WordBreakingTokenizer<'a> {
18424 /// Yields a span, the count of graphemes in the token, and whether it was
18425 /// whitespace. Note that it also breaks at word boundaries.
18426 type Item = WordBreakToken<'a>;
18427
18428 fn next(&mut self) -> Option<Self::Item> {
18429 use unicode_segmentation::UnicodeSegmentation;
18430 if self.input.is_empty() {
18431 return None;
18432 }
18433
18434 let mut iter = self.input.graphemes(true).peekable();
18435 let mut offset = 0;
18436 let mut grapheme_len = 0;
18437 if let Some(first_grapheme) = iter.next() {
18438 let is_newline = first_grapheme == "\n";
18439 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18440 offset += first_grapheme.len();
18441 grapheme_len += 1;
18442 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18443 if let Some(grapheme) = iter.peek().copied() {
18444 if should_stay_with_preceding_ideograph(grapheme) {
18445 offset += grapheme.len();
18446 grapheme_len += 1;
18447 }
18448 }
18449 } else {
18450 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18451 let mut next_word_bound = words.peek().copied();
18452 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18453 next_word_bound = words.next();
18454 }
18455 while let Some(grapheme) = iter.peek().copied() {
18456 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18457 break;
18458 };
18459 if is_grapheme_whitespace(grapheme) != is_whitespace
18460 || (grapheme == "\n") != is_newline
18461 {
18462 break;
18463 };
18464 offset += grapheme.len();
18465 grapheme_len += 1;
18466 iter.next();
18467 }
18468 }
18469 let token = &self.input[..offset];
18470 self.input = &self.input[offset..];
18471 if token == "\n" {
18472 Some(WordBreakToken::Newline)
18473 } else if is_whitespace {
18474 Some(WordBreakToken::InlineWhitespace {
18475 token,
18476 grapheme_len,
18477 })
18478 } else {
18479 Some(WordBreakToken::Word {
18480 token,
18481 grapheme_len,
18482 })
18483 }
18484 } else {
18485 None
18486 }
18487 }
18488}
18489
18490#[test]
18491fn test_word_breaking_tokenizer() {
18492 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18493 ("", &[]),
18494 (" ", &[whitespace(" ", 2)]),
18495 ("Ʒ", &[word("Ʒ", 1)]),
18496 ("Ǽ", &[word("Ǽ", 1)]),
18497 ("⋑", &[word("⋑", 1)]),
18498 ("⋑⋑", &[word("⋑⋑", 2)]),
18499 (
18500 "原理,进而",
18501 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18502 ),
18503 (
18504 "hello world",
18505 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18506 ),
18507 (
18508 "hello, world",
18509 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18510 ),
18511 (
18512 " hello world",
18513 &[
18514 whitespace(" ", 2),
18515 word("hello", 5),
18516 whitespace(" ", 1),
18517 word("world", 5),
18518 ],
18519 ),
18520 (
18521 "这是什么 \n 钢笔",
18522 &[
18523 word("这", 1),
18524 word("是", 1),
18525 word("什", 1),
18526 word("么", 1),
18527 whitespace(" ", 1),
18528 newline(),
18529 whitespace(" ", 1),
18530 word("钢", 1),
18531 word("笔", 1),
18532 ],
18533 ),
18534 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18535 ];
18536
18537 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18538 WordBreakToken::Word {
18539 token,
18540 grapheme_len,
18541 }
18542 }
18543
18544 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18545 WordBreakToken::InlineWhitespace {
18546 token,
18547 grapheme_len,
18548 }
18549 }
18550
18551 fn newline() -> WordBreakToken<'static> {
18552 WordBreakToken::Newline
18553 }
18554
18555 for (input, result) in tests {
18556 assert_eq!(
18557 WordBreakingTokenizer::new(input)
18558 .collect::<Vec<_>>()
18559 .as_slice(),
18560 *result,
18561 );
18562 }
18563}
18564
18565fn wrap_with_prefix(
18566 line_prefix: String,
18567 unwrapped_text: String,
18568 wrap_column: usize,
18569 tab_size: NonZeroU32,
18570 preserve_existing_whitespace: bool,
18571) -> String {
18572 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18573 let mut wrapped_text = String::new();
18574 let mut current_line = line_prefix.clone();
18575
18576 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18577 let mut current_line_len = line_prefix_len;
18578 let mut in_whitespace = false;
18579 for token in tokenizer {
18580 let have_preceding_whitespace = in_whitespace;
18581 match token {
18582 WordBreakToken::Word {
18583 token,
18584 grapheme_len,
18585 } => {
18586 in_whitespace = false;
18587 if current_line_len + grapheme_len > wrap_column
18588 && current_line_len != line_prefix_len
18589 {
18590 wrapped_text.push_str(current_line.trim_end());
18591 wrapped_text.push('\n');
18592 current_line.truncate(line_prefix.len());
18593 current_line_len = line_prefix_len;
18594 }
18595 current_line.push_str(token);
18596 current_line_len += grapheme_len;
18597 }
18598 WordBreakToken::InlineWhitespace {
18599 mut token,
18600 mut grapheme_len,
18601 } => {
18602 in_whitespace = true;
18603 if have_preceding_whitespace && !preserve_existing_whitespace {
18604 continue;
18605 }
18606 if !preserve_existing_whitespace {
18607 token = " ";
18608 grapheme_len = 1;
18609 }
18610 if current_line_len + grapheme_len > wrap_column {
18611 wrapped_text.push_str(current_line.trim_end());
18612 wrapped_text.push('\n');
18613 current_line.truncate(line_prefix.len());
18614 current_line_len = line_prefix_len;
18615 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18616 current_line.push_str(token);
18617 current_line_len += grapheme_len;
18618 }
18619 }
18620 WordBreakToken::Newline => {
18621 in_whitespace = true;
18622 if preserve_existing_whitespace {
18623 wrapped_text.push_str(current_line.trim_end());
18624 wrapped_text.push('\n');
18625 current_line.truncate(line_prefix.len());
18626 current_line_len = line_prefix_len;
18627 } else if have_preceding_whitespace {
18628 continue;
18629 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18630 {
18631 wrapped_text.push_str(current_line.trim_end());
18632 wrapped_text.push('\n');
18633 current_line.truncate(line_prefix.len());
18634 current_line_len = line_prefix_len;
18635 } else if current_line_len != line_prefix_len {
18636 current_line.push(' ');
18637 current_line_len += 1;
18638 }
18639 }
18640 }
18641 }
18642
18643 if !current_line.is_empty() {
18644 wrapped_text.push_str(¤t_line);
18645 }
18646 wrapped_text
18647}
18648
18649#[test]
18650fn test_wrap_with_prefix() {
18651 assert_eq!(
18652 wrap_with_prefix(
18653 "# ".to_string(),
18654 "abcdefg".to_string(),
18655 4,
18656 NonZeroU32::new(4).unwrap(),
18657 false,
18658 ),
18659 "# abcdefg"
18660 );
18661 assert_eq!(
18662 wrap_with_prefix(
18663 "".to_string(),
18664 "\thello world".to_string(),
18665 8,
18666 NonZeroU32::new(4).unwrap(),
18667 false,
18668 ),
18669 "hello\nworld"
18670 );
18671 assert_eq!(
18672 wrap_with_prefix(
18673 "// ".to_string(),
18674 "xx \nyy zz aa bb cc".to_string(),
18675 12,
18676 NonZeroU32::new(4).unwrap(),
18677 false,
18678 ),
18679 "// xx yy zz\n// aa bb cc"
18680 );
18681 assert_eq!(
18682 wrap_with_prefix(
18683 String::new(),
18684 "这是什么 \n 钢笔".to_string(),
18685 3,
18686 NonZeroU32::new(4).unwrap(),
18687 false,
18688 ),
18689 "这是什\n么 钢\n笔"
18690 );
18691}
18692
18693pub trait CollaborationHub {
18694 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18695 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18696 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18697}
18698
18699impl CollaborationHub for Entity<Project> {
18700 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18701 self.read(cx).collaborators()
18702 }
18703
18704 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18705 self.read(cx).user_store().read(cx).participant_indices()
18706 }
18707
18708 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18709 let this = self.read(cx);
18710 let user_ids = this.collaborators().values().map(|c| c.user_id);
18711 this.user_store().read_with(cx, |user_store, cx| {
18712 user_store.participant_names(user_ids, cx)
18713 })
18714 }
18715}
18716
18717pub trait SemanticsProvider {
18718 fn hover(
18719 &self,
18720 buffer: &Entity<Buffer>,
18721 position: text::Anchor,
18722 cx: &mut App,
18723 ) -> Option<Task<Vec<project::Hover>>>;
18724
18725 fn inlay_hints(
18726 &self,
18727 buffer_handle: Entity<Buffer>,
18728 range: Range<text::Anchor>,
18729 cx: &mut App,
18730 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18731
18732 fn resolve_inlay_hint(
18733 &self,
18734 hint: InlayHint,
18735 buffer_handle: Entity<Buffer>,
18736 server_id: LanguageServerId,
18737 cx: &mut App,
18738 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18739
18740 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18741
18742 fn document_highlights(
18743 &self,
18744 buffer: &Entity<Buffer>,
18745 position: text::Anchor,
18746 cx: &mut App,
18747 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18748
18749 fn definitions(
18750 &self,
18751 buffer: &Entity<Buffer>,
18752 position: text::Anchor,
18753 kind: GotoDefinitionKind,
18754 cx: &mut App,
18755 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18756
18757 fn range_for_rename(
18758 &self,
18759 buffer: &Entity<Buffer>,
18760 position: text::Anchor,
18761 cx: &mut App,
18762 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18763
18764 fn perform_rename(
18765 &self,
18766 buffer: &Entity<Buffer>,
18767 position: text::Anchor,
18768 new_name: String,
18769 cx: &mut App,
18770 ) -> Option<Task<Result<ProjectTransaction>>>;
18771}
18772
18773pub trait CompletionProvider {
18774 fn completions(
18775 &self,
18776 excerpt_id: ExcerptId,
18777 buffer: &Entity<Buffer>,
18778 buffer_position: text::Anchor,
18779 trigger: CompletionContext,
18780 window: &mut Window,
18781 cx: &mut Context<Editor>,
18782 ) -> Task<Result<Option<Vec<Completion>>>>;
18783
18784 fn resolve_completions(
18785 &self,
18786 buffer: Entity<Buffer>,
18787 completion_indices: Vec<usize>,
18788 completions: Rc<RefCell<Box<[Completion]>>>,
18789 cx: &mut Context<Editor>,
18790 ) -> Task<Result<bool>>;
18791
18792 fn apply_additional_edits_for_completion(
18793 &self,
18794 _buffer: Entity<Buffer>,
18795 _completions: Rc<RefCell<Box<[Completion]>>>,
18796 _completion_index: usize,
18797 _push_to_history: bool,
18798 _cx: &mut Context<Editor>,
18799 ) -> Task<Result<Option<language::Transaction>>> {
18800 Task::ready(Ok(None))
18801 }
18802
18803 fn is_completion_trigger(
18804 &self,
18805 buffer: &Entity<Buffer>,
18806 position: language::Anchor,
18807 text: &str,
18808 trigger_in_words: bool,
18809 cx: &mut Context<Editor>,
18810 ) -> bool;
18811
18812 fn sort_completions(&self) -> bool {
18813 true
18814 }
18815
18816 fn filter_completions(&self) -> bool {
18817 true
18818 }
18819}
18820
18821pub trait CodeActionProvider {
18822 fn id(&self) -> Arc<str>;
18823
18824 fn code_actions(
18825 &self,
18826 buffer: &Entity<Buffer>,
18827 range: Range<text::Anchor>,
18828 window: &mut Window,
18829 cx: &mut App,
18830 ) -> Task<Result<Vec<CodeAction>>>;
18831
18832 fn apply_code_action(
18833 &self,
18834 buffer_handle: Entity<Buffer>,
18835 action: CodeAction,
18836 excerpt_id: ExcerptId,
18837 push_to_history: bool,
18838 window: &mut Window,
18839 cx: &mut App,
18840 ) -> Task<Result<ProjectTransaction>>;
18841}
18842
18843impl CodeActionProvider for Entity<Project> {
18844 fn id(&self) -> Arc<str> {
18845 "project".into()
18846 }
18847
18848 fn code_actions(
18849 &self,
18850 buffer: &Entity<Buffer>,
18851 range: Range<text::Anchor>,
18852 _window: &mut Window,
18853 cx: &mut App,
18854 ) -> Task<Result<Vec<CodeAction>>> {
18855 self.update(cx, |project, cx| {
18856 let code_lens = project.code_lens(buffer, range.clone(), cx);
18857 let code_actions = project.code_actions(buffer, range, None, cx);
18858 cx.background_spawn(async move {
18859 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18860 Ok(code_lens
18861 .context("code lens fetch")?
18862 .into_iter()
18863 .chain(code_actions.context("code action fetch")?)
18864 .collect())
18865 })
18866 })
18867 }
18868
18869 fn apply_code_action(
18870 &self,
18871 buffer_handle: Entity<Buffer>,
18872 action: CodeAction,
18873 _excerpt_id: ExcerptId,
18874 push_to_history: bool,
18875 _window: &mut Window,
18876 cx: &mut App,
18877 ) -> Task<Result<ProjectTransaction>> {
18878 self.update(cx, |project, cx| {
18879 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18880 })
18881 }
18882}
18883
18884fn snippet_completions(
18885 project: &Project,
18886 buffer: &Entity<Buffer>,
18887 buffer_position: text::Anchor,
18888 cx: &mut App,
18889) -> Task<Result<Vec<Completion>>> {
18890 let languages = buffer.read(cx).languages_at(buffer_position);
18891 let snippet_store = project.snippets().read(cx);
18892
18893 let scopes: Vec<_> = languages
18894 .iter()
18895 .filter_map(|language| {
18896 let language_name = language.lsp_id();
18897 let snippets = snippet_store.snippets_for(Some(language_name), cx);
18898
18899 if snippets.is_empty() {
18900 None
18901 } else {
18902 Some((language.default_scope(), snippets))
18903 }
18904 })
18905 .collect();
18906
18907 if scopes.is_empty() {
18908 return Task::ready(Ok(vec![]));
18909 }
18910
18911 let snapshot = buffer.read(cx).text_snapshot();
18912 let chars: String = snapshot
18913 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18914 .collect();
18915 let executor = cx.background_executor().clone();
18916
18917 cx.background_spawn(async move {
18918 let mut all_results: Vec<Completion> = Vec::new();
18919 for (scope, snippets) in scopes.into_iter() {
18920 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18921 let mut last_word = chars
18922 .chars()
18923 .take_while(|c| classifier.is_word(*c))
18924 .collect::<String>();
18925 last_word = last_word.chars().rev().collect();
18926
18927 if last_word.is_empty() {
18928 return Ok(vec![]);
18929 }
18930
18931 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18932 let to_lsp = |point: &text::Anchor| {
18933 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18934 point_to_lsp(end)
18935 };
18936 let lsp_end = to_lsp(&buffer_position);
18937
18938 let candidates = snippets
18939 .iter()
18940 .enumerate()
18941 .flat_map(|(ix, snippet)| {
18942 snippet
18943 .prefix
18944 .iter()
18945 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18946 })
18947 .collect::<Vec<StringMatchCandidate>>();
18948
18949 let mut matches = fuzzy::match_strings(
18950 &candidates,
18951 &last_word,
18952 last_word.chars().any(|c| c.is_uppercase()),
18953 100,
18954 &Default::default(),
18955 executor.clone(),
18956 )
18957 .await;
18958
18959 // Remove all candidates where the query's start does not match the start of any word in the candidate
18960 if let Some(query_start) = last_word.chars().next() {
18961 matches.retain(|string_match| {
18962 split_words(&string_match.string).any(|word| {
18963 // Check that the first codepoint of the word as lowercase matches the first
18964 // codepoint of the query as lowercase
18965 word.chars()
18966 .flat_map(|codepoint| codepoint.to_lowercase())
18967 .zip(query_start.to_lowercase())
18968 .all(|(word_cp, query_cp)| word_cp == query_cp)
18969 })
18970 });
18971 }
18972
18973 let matched_strings = matches
18974 .into_iter()
18975 .map(|m| m.string)
18976 .collect::<HashSet<_>>();
18977
18978 let mut result: Vec<Completion> = snippets
18979 .iter()
18980 .filter_map(|snippet| {
18981 let matching_prefix = snippet
18982 .prefix
18983 .iter()
18984 .find(|prefix| matched_strings.contains(*prefix))?;
18985 let start = as_offset - last_word.len();
18986 let start = snapshot.anchor_before(start);
18987 let range = start..buffer_position;
18988 let lsp_start = to_lsp(&start);
18989 let lsp_range = lsp::Range {
18990 start: lsp_start,
18991 end: lsp_end,
18992 };
18993 Some(Completion {
18994 replace_range: range,
18995 new_text: snippet.body.clone(),
18996 source: CompletionSource::Lsp {
18997 insert_range: None,
18998 server_id: LanguageServerId(usize::MAX),
18999 resolved: true,
19000 lsp_completion: Box::new(lsp::CompletionItem {
19001 label: snippet.prefix.first().unwrap().clone(),
19002 kind: Some(CompletionItemKind::SNIPPET),
19003 label_details: snippet.description.as_ref().map(|description| {
19004 lsp::CompletionItemLabelDetails {
19005 detail: Some(description.clone()),
19006 description: None,
19007 }
19008 }),
19009 insert_text_format: Some(InsertTextFormat::SNIPPET),
19010 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19011 lsp::InsertReplaceEdit {
19012 new_text: snippet.body.clone(),
19013 insert: lsp_range,
19014 replace: lsp_range,
19015 },
19016 )),
19017 filter_text: Some(snippet.body.clone()),
19018 sort_text: Some(char::MAX.to_string()),
19019 ..lsp::CompletionItem::default()
19020 }),
19021 lsp_defaults: None,
19022 },
19023 label: CodeLabel {
19024 text: matching_prefix.clone(),
19025 runs: Vec::new(),
19026 filter_range: 0..matching_prefix.len(),
19027 },
19028 icon_path: None,
19029 documentation: snippet.description.clone().map(|description| {
19030 CompletionDocumentation::SingleLine(description.into())
19031 }),
19032 insert_text_mode: None,
19033 confirm: None,
19034 })
19035 })
19036 .collect();
19037
19038 all_results.append(&mut result);
19039 }
19040
19041 Ok(all_results)
19042 })
19043}
19044
19045impl CompletionProvider for Entity<Project> {
19046 fn completions(
19047 &self,
19048 _excerpt_id: ExcerptId,
19049 buffer: &Entity<Buffer>,
19050 buffer_position: text::Anchor,
19051 options: CompletionContext,
19052 _window: &mut Window,
19053 cx: &mut Context<Editor>,
19054 ) -> Task<Result<Option<Vec<Completion>>>> {
19055 self.update(cx, |project, cx| {
19056 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19057 let project_completions = project.completions(buffer, buffer_position, options, cx);
19058 cx.background_spawn(async move {
19059 let snippets_completions = snippets.await?;
19060 match project_completions.await? {
19061 Some(mut completions) => {
19062 completions.extend(snippets_completions);
19063 Ok(Some(completions))
19064 }
19065 None => {
19066 if snippets_completions.is_empty() {
19067 Ok(None)
19068 } else {
19069 Ok(Some(snippets_completions))
19070 }
19071 }
19072 }
19073 })
19074 })
19075 }
19076
19077 fn resolve_completions(
19078 &self,
19079 buffer: Entity<Buffer>,
19080 completion_indices: Vec<usize>,
19081 completions: Rc<RefCell<Box<[Completion]>>>,
19082 cx: &mut Context<Editor>,
19083 ) -> Task<Result<bool>> {
19084 self.update(cx, |project, cx| {
19085 project.lsp_store().update(cx, |lsp_store, cx| {
19086 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19087 })
19088 })
19089 }
19090
19091 fn apply_additional_edits_for_completion(
19092 &self,
19093 buffer: Entity<Buffer>,
19094 completions: Rc<RefCell<Box<[Completion]>>>,
19095 completion_index: usize,
19096 push_to_history: bool,
19097 cx: &mut Context<Editor>,
19098 ) -> Task<Result<Option<language::Transaction>>> {
19099 self.update(cx, |project, cx| {
19100 project.lsp_store().update(cx, |lsp_store, cx| {
19101 lsp_store.apply_additional_edits_for_completion(
19102 buffer,
19103 completions,
19104 completion_index,
19105 push_to_history,
19106 cx,
19107 )
19108 })
19109 })
19110 }
19111
19112 fn is_completion_trigger(
19113 &self,
19114 buffer: &Entity<Buffer>,
19115 position: language::Anchor,
19116 text: &str,
19117 trigger_in_words: bool,
19118 cx: &mut Context<Editor>,
19119 ) -> bool {
19120 let mut chars = text.chars();
19121 let char = if let Some(char) = chars.next() {
19122 char
19123 } else {
19124 return false;
19125 };
19126 if chars.next().is_some() {
19127 return false;
19128 }
19129
19130 let buffer = buffer.read(cx);
19131 let snapshot = buffer.snapshot();
19132 if !snapshot.settings_at(position, cx).show_completions_on_input {
19133 return false;
19134 }
19135 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19136 if trigger_in_words && classifier.is_word(char) {
19137 return true;
19138 }
19139
19140 buffer.completion_triggers().contains(text)
19141 }
19142}
19143
19144impl SemanticsProvider for Entity<Project> {
19145 fn hover(
19146 &self,
19147 buffer: &Entity<Buffer>,
19148 position: text::Anchor,
19149 cx: &mut App,
19150 ) -> Option<Task<Vec<project::Hover>>> {
19151 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19152 }
19153
19154 fn document_highlights(
19155 &self,
19156 buffer: &Entity<Buffer>,
19157 position: text::Anchor,
19158 cx: &mut App,
19159 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19160 Some(self.update(cx, |project, cx| {
19161 project.document_highlights(buffer, position, cx)
19162 }))
19163 }
19164
19165 fn definitions(
19166 &self,
19167 buffer: &Entity<Buffer>,
19168 position: text::Anchor,
19169 kind: GotoDefinitionKind,
19170 cx: &mut App,
19171 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19172 Some(self.update(cx, |project, cx| match kind {
19173 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19174 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19175 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19176 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19177 }))
19178 }
19179
19180 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19181 // TODO: make this work for remote projects
19182 self.update(cx, |this, cx| {
19183 buffer.update(cx, |buffer, cx| {
19184 this.any_language_server_supports_inlay_hints(buffer, cx)
19185 })
19186 })
19187 }
19188
19189 fn inlay_hints(
19190 &self,
19191 buffer_handle: Entity<Buffer>,
19192 range: Range<text::Anchor>,
19193 cx: &mut App,
19194 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19195 Some(self.update(cx, |project, cx| {
19196 project.inlay_hints(buffer_handle, range, cx)
19197 }))
19198 }
19199
19200 fn resolve_inlay_hint(
19201 &self,
19202 hint: InlayHint,
19203 buffer_handle: Entity<Buffer>,
19204 server_id: LanguageServerId,
19205 cx: &mut App,
19206 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19207 Some(self.update(cx, |project, cx| {
19208 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19209 }))
19210 }
19211
19212 fn range_for_rename(
19213 &self,
19214 buffer: &Entity<Buffer>,
19215 position: text::Anchor,
19216 cx: &mut App,
19217 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19218 Some(self.update(cx, |project, cx| {
19219 let buffer = buffer.clone();
19220 let task = project.prepare_rename(buffer.clone(), position, cx);
19221 cx.spawn(async move |_, cx| {
19222 Ok(match task.await? {
19223 PrepareRenameResponse::Success(range) => Some(range),
19224 PrepareRenameResponse::InvalidPosition => None,
19225 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19226 // Fallback on using TreeSitter info to determine identifier range
19227 buffer.update(cx, |buffer, _| {
19228 let snapshot = buffer.snapshot();
19229 let (range, kind) = snapshot.surrounding_word(position);
19230 if kind != Some(CharKind::Word) {
19231 return None;
19232 }
19233 Some(
19234 snapshot.anchor_before(range.start)
19235 ..snapshot.anchor_after(range.end),
19236 )
19237 })?
19238 }
19239 })
19240 })
19241 }))
19242 }
19243
19244 fn perform_rename(
19245 &self,
19246 buffer: &Entity<Buffer>,
19247 position: text::Anchor,
19248 new_name: String,
19249 cx: &mut App,
19250 ) -> Option<Task<Result<ProjectTransaction>>> {
19251 Some(self.update(cx, |project, cx| {
19252 project.perform_rename(buffer.clone(), position, new_name, cx)
19253 }))
19254 }
19255}
19256
19257fn inlay_hint_settings(
19258 location: Anchor,
19259 snapshot: &MultiBufferSnapshot,
19260 cx: &mut Context<Editor>,
19261) -> InlayHintSettings {
19262 let file = snapshot.file_at(location);
19263 let language = snapshot.language_at(location).map(|l| l.name());
19264 language_settings(language, file, cx).inlay_hints
19265}
19266
19267fn consume_contiguous_rows(
19268 contiguous_row_selections: &mut Vec<Selection<Point>>,
19269 selection: &Selection<Point>,
19270 display_map: &DisplaySnapshot,
19271 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19272) -> (MultiBufferRow, MultiBufferRow) {
19273 contiguous_row_selections.push(selection.clone());
19274 let start_row = MultiBufferRow(selection.start.row);
19275 let mut end_row = ending_row(selection, display_map);
19276
19277 while let Some(next_selection) = selections.peek() {
19278 if next_selection.start.row <= end_row.0 {
19279 end_row = ending_row(next_selection, display_map);
19280 contiguous_row_selections.push(selections.next().unwrap().clone());
19281 } else {
19282 break;
19283 }
19284 }
19285 (start_row, end_row)
19286}
19287
19288fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19289 if next_selection.end.column > 0 || next_selection.is_empty() {
19290 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19291 } else {
19292 MultiBufferRow(next_selection.end.row)
19293 }
19294}
19295
19296impl EditorSnapshot {
19297 pub fn remote_selections_in_range<'a>(
19298 &'a self,
19299 range: &'a Range<Anchor>,
19300 collaboration_hub: &dyn CollaborationHub,
19301 cx: &'a App,
19302 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19303 let participant_names = collaboration_hub.user_names(cx);
19304 let participant_indices = collaboration_hub.user_participant_indices(cx);
19305 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19306 let collaborators_by_replica_id = collaborators_by_peer_id
19307 .iter()
19308 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19309 .collect::<HashMap<_, _>>();
19310 self.buffer_snapshot
19311 .selections_in_range(range, false)
19312 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19313 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19314 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19315 let user_name = participant_names.get(&collaborator.user_id).cloned();
19316 Some(RemoteSelection {
19317 replica_id,
19318 selection,
19319 cursor_shape,
19320 line_mode,
19321 participant_index,
19322 peer_id: collaborator.peer_id,
19323 user_name,
19324 })
19325 })
19326 }
19327
19328 pub fn hunks_for_ranges(
19329 &self,
19330 ranges: impl IntoIterator<Item = Range<Point>>,
19331 ) -> Vec<MultiBufferDiffHunk> {
19332 let mut hunks = Vec::new();
19333 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19334 HashMap::default();
19335 for query_range in ranges {
19336 let query_rows =
19337 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19338 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19339 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19340 ) {
19341 // Include deleted hunks that are adjacent to the query range, because
19342 // otherwise they would be missed.
19343 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19344 if hunk.status().is_deleted() {
19345 intersects_range |= hunk.row_range.start == query_rows.end;
19346 intersects_range |= hunk.row_range.end == query_rows.start;
19347 }
19348 if intersects_range {
19349 if !processed_buffer_rows
19350 .entry(hunk.buffer_id)
19351 .or_default()
19352 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19353 {
19354 continue;
19355 }
19356 hunks.push(hunk);
19357 }
19358 }
19359 }
19360
19361 hunks
19362 }
19363
19364 fn display_diff_hunks_for_rows<'a>(
19365 &'a self,
19366 display_rows: Range<DisplayRow>,
19367 folded_buffers: &'a HashSet<BufferId>,
19368 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19369 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19370 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19371
19372 self.buffer_snapshot
19373 .diff_hunks_in_range(buffer_start..buffer_end)
19374 .filter_map(|hunk| {
19375 if folded_buffers.contains(&hunk.buffer_id) {
19376 return None;
19377 }
19378
19379 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19380 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19381
19382 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19383 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19384
19385 let display_hunk = if hunk_display_start.column() != 0 {
19386 DisplayDiffHunk::Folded {
19387 display_row: hunk_display_start.row(),
19388 }
19389 } else {
19390 let mut end_row = hunk_display_end.row();
19391 if hunk_display_end.column() > 0 {
19392 end_row.0 += 1;
19393 }
19394 let is_created_file = hunk.is_created_file();
19395 DisplayDiffHunk::Unfolded {
19396 status: hunk.status(),
19397 diff_base_byte_range: hunk.diff_base_byte_range,
19398 display_row_range: hunk_display_start.row()..end_row,
19399 multi_buffer_range: Anchor::range_in_buffer(
19400 hunk.excerpt_id,
19401 hunk.buffer_id,
19402 hunk.buffer_range,
19403 ),
19404 is_created_file,
19405 }
19406 };
19407
19408 Some(display_hunk)
19409 })
19410 }
19411
19412 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19413 self.display_snapshot.buffer_snapshot.language_at(position)
19414 }
19415
19416 pub fn is_focused(&self) -> bool {
19417 self.is_focused
19418 }
19419
19420 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19421 self.placeholder_text.as_ref()
19422 }
19423
19424 pub fn scroll_position(&self) -> gpui::Point<f32> {
19425 self.scroll_anchor.scroll_position(&self.display_snapshot)
19426 }
19427
19428 fn gutter_dimensions(
19429 &self,
19430 font_id: FontId,
19431 font_size: Pixels,
19432 max_line_number_width: Pixels,
19433 cx: &App,
19434 ) -> Option<GutterDimensions> {
19435 if !self.show_gutter {
19436 return None;
19437 }
19438
19439 let descent = cx.text_system().descent(font_id, font_size);
19440 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19441 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19442
19443 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19444 matches!(
19445 ProjectSettings::get_global(cx).git.git_gutter,
19446 Some(GitGutterSetting::TrackedFiles)
19447 )
19448 });
19449 let gutter_settings = EditorSettings::get_global(cx).gutter;
19450 let show_line_numbers = self
19451 .show_line_numbers
19452 .unwrap_or(gutter_settings.line_numbers);
19453 let line_gutter_width = if show_line_numbers {
19454 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19455 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19456 max_line_number_width.max(min_width_for_number_on_gutter)
19457 } else {
19458 0.0.into()
19459 };
19460
19461 let show_code_actions = self
19462 .show_code_actions
19463 .unwrap_or(gutter_settings.code_actions);
19464
19465 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19466 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19467
19468 let git_blame_entries_width =
19469 self.git_blame_gutter_max_author_length
19470 .map(|max_author_length| {
19471 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19472 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19473
19474 /// The number of characters to dedicate to gaps and margins.
19475 const SPACING_WIDTH: usize = 4;
19476
19477 let max_char_count = max_author_length.min(renderer.max_author_length())
19478 + ::git::SHORT_SHA_LENGTH
19479 + MAX_RELATIVE_TIMESTAMP.len()
19480 + SPACING_WIDTH;
19481
19482 em_advance * max_char_count
19483 });
19484
19485 let is_singleton = self.buffer_snapshot.is_singleton();
19486
19487 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19488 left_padding += if !is_singleton {
19489 em_width * 4.0
19490 } else if show_code_actions || show_runnables || show_breakpoints {
19491 em_width * 3.0
19492 } else if show_git_gutter && show_line_numbers {
19493 em_width * 2.0
19494 } else if show_git_gutter || show_line_numbers {
19495 em_width
19496 } else {
19497 px(0.)
19498 };
19499
19500 let shows_folds = is_singleton && gutter_settings.folds;
19501
19502 let right_padding = if shows_folds && show_line_numbers {
19503 em_width * 4.0
19504 } else if shows_folds || (!is_singleton && show_line_numbers) {
19505 em_width * 3.0
19506 } else if show_line_numbers {
19507 em_width
19508 } else {
19509 px(0.)
19510 };
19511
19512 Some(GutterDimensions {
19513 left_padding,
19514 right_padding,
19515 width: line_gutter_width + left_padding + right_padding,
19516 margin: -descent,
19517 git_blame_entries_width,
19518 })
19519 }
19520
19521 pub fn render_crease_toggle(
19522 &self,
19523 buffer_row: MultiBufferRow,
19524 row_contains_cursor: bool,
19525 editor: Entity<Editor>,
19526 window: &mut Window,
19527 cx: &mut App,
19528 ) -> Option<AnyElement> {
19529 let folded = self.is_line_folded(buffer_row);
19530 let mut is_foldable = false;
19531
19532 if let Some(crease) = self
19533 .crease_snapshot
19534 .query_row(buffer_row, &self.buffer_snapshot)
19535 {
19536 is_foldable = true;
19537 match crease {
19538 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19539 if let Some(render_toggle) = render_toggle {
19540 let toggle_callback =
19541 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19542 if folded {
19543 editor.update(cx, |editor, cx| {
19544 editor.fold_at(buffer_row, window, cx)
19545 });
19546 } else {
19547 editor.update(cx, |editor, cx| {
19548 editor.unfold_at(buffer_row, window, cx)
19549 });
19550 }
19551 });
19552 return Some((render_toggle)(
19553 buffer_row,
19554 folded,
19555 toggle_callback,
19556 window,
19557 cx,
19558 ));
19559 }
19560 }
19561 }
19562 }
19563
19564 is_foldable |= self.starts_indent(buffer_row);
19565
19566 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19567 Some(
19568 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19569 .toggle_state(folded)
19570 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19571 if folded {
19572 this.unfold_at(buffer_row, window, cx);
19573 } else {
19574 this.fold_at(buffer_row, window, cx);
19575 }
19576 }))
19577 .into_any_element(),
19578 )
19579 } else {
19580 None
19581 }
19582 }
19583
19584 pub fn render_crease_trailer(
19585 &self,
19586 buffer_row: MultiBufferRow,
19587 window: &mut Window,
19588 cx: &mut App,
19589 ) -> Option<AnyElement> {
19590 let folded = self.is_line_folded(buffer_row);
19591 if let Crease::Inline { render_trailer, .. } = self
19592 .crease_snapshot
19593 .query_row(buffer_row, &self.buffer_snapshot)?
19594 {
19595 let render_trailer = render_trailer.as_ref()?;
19596 Some(render_trailer(buffer_row, folded, window, cx))
19597 } else {
19598 None
19599 }
19600 }
19601}
19602
19603impl Deref for EditorSnapshot {
19604 type Target = DisplaySnapshot;
19605
19606 fn deref(&self) -> &Self::Target {
19607 &self.display_snapshot
19608 }
19609}
19610
19611#[derive(Clone, Debug, PartialEq, Eq)]
19612pub enum EditorEvent {
19613 InputIgnored {
19614 text: Arc<str>,
19615 },
19616 InputHandled {
19617 utf16_range_to_replace: Option<Range<isize>>,
19618 text: Arc<str>,
19619 },
19620 ExcerptsAdded {
19621 buffer: Entity<Buffer>,
19622 predecessor: ExcerptId,
19623 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19624 },
19625 ExcerptsRemoved {
19626 ids: Vec<ExcerptId>,
19627 },
19628 BufferFoldToggled {
19629 ids: Vec<ExcerptId>,
19630 folded: bool,
19631 },
19632 ExcerptsEdited {
19633 ids: Vec<ExcerptId>,
19634 },
19635 ExcerptsExpanded {
19636 ids: Vec<ExcerptId>,
19637 },
19638 BufferEdited,
19639 Edited {
19640 transaction_id: clock::Lamport,
19641 },
19642 Reparsed(BufferId),
19643 Focused,
19644 FocusedIn,
19645 Blurred,
19646 DirtyChanged,
19647 Saved,
19648 TitleChanged,
19649 DiffBaseChanged,
19650 SelectionsChanged {
19651 local: bool,
19652 },
19653 ScrollPositionChanged {
19654 local: bool,
19655 autoscroll: bool,
19656 },
19657 Closed,
19658 TransactionUndone {
19659 transaction_id: clock::Lamport,
19660 },
19661 TransactionBegun {
19662 transaction_id: clock::Lamport,
19663 },
19664 Reloaded,
19665 CursorShapeChanged,
19666 PushedToNavHistory {
19667 anchor: Anchor,
19668 is_deactivate: bool,
19669 },
19670}
19671
19672impl EventEmitter<EditorEvent> for Editor {}
19673
19674impl Focusable for Editor {
19675 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19676 self.focus_handle.clone()
19677 }
19678}
19679
19680impl Render for Editor {
19681 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19682 let settings = ThemeSettings::get_global(cx);
19683
19684 let mut text_style = match self.mode {
19685 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19686 color: cx.theme().colors().editor_foreground,
19687 font_family: settings.ui_font.family.clone(),
19688 font_features: settings.ui_font.features.clone(),
19689 font_fallbacks: settings.ui_font.fallbacks.clone(),
19690 font_size: rems(0.875).into(),
19691 font_weight: settings.ui_font.weight,
19692 line_height: relative(settings.buffer_line_height.value()),
19693 ..Default::default()
19694 },
19695 EditorMode::Full { .. } => TextStyle {
19696 color: cx.theme().colors().editor_foreground,
19697 font_family: settings.buffer_font.family.clone(),
19698 font_features: settings.buffer_font.features.clone(),
19699 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19700 font_size: settings.buffer_font_size(cx).into(),
19701 font_weight: settings.buffer_font.weight,
19702 line_height: relative(settings.buffer_line_height.value()),
19703 ..Default::default()
19704 },
19705 };
19706 if let Some(text_style_refinement) = &self.text_style_refinement {
19707 text_style.refine(text_style_refinement)
19708 }
19709
19710 let background = match self.mode {
19711 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19712 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19713 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19714 };
19715
19716 EditorElement::new(
19717 &cx.entity(),
19718 EditorStyle {
19719 background,
19720 local_player: cx.theme().players().local(),
19721 text: text_style,
19722 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19723 syntax: cx.theme().syntax().clone(),
19724 status: cx.theme().status().clone(),
19725 inlay_hints_style: make_inlay_hints_style(cx),
19726 inline_completion_styles: make_suggestion_styles(cx),
19727 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19728 },
19729 )
19730 }
19731}
19732
19733impl EntityInputHandler for Editor {
19734 fn text_for_range(
19735 &mut self,
19736 range_utf16: Range<usize>,
19737 adjusted_range: &mut Option<Range<usize>>,
19738 _: &mut Window,
19739 cx: &mut Context<Self>,
19740 ) -> Option<String> {
19741 let snapshot = self.buffer.read(cx).read(cx);
19742 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19743 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19744 if (start.0..end.0) != range_utf16 {
19745 adjusted_range.replace(start.0..end.0);
19746 }
19747 Some(snapshot.text_for_range(start..end).collect())
19748 }
19749
19750 fn selected_text_range(
19751 &mut self,
19752 ignore_disabled_input: bool,
19753 _: &mut Window,
19754 cx: &mut Context<Self>,
19755 ) -> Option<UTF16Selection> {
19756 // Prevent the IME menu from appearing when holding down an alphabetic key
19757 // while input is disabled.
19758 if !ignore_disabled_input && !self.input_enabled {
19759 return None;
19760 }
19761
19762 let selection = self.selections.newest::<OffsetUtf16>(cx);
19763 let range = selection.range();
19764
19765 Some(UTF16Selection {
19766 range: range.start.0..range.end.0,
19767 reversed: selection.reversed,
19768 })
19769 }
19770
19771 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19772 let snapshot = self.buffer.read(cx).read(cx);
19773 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19774 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19775 }
19776
19777 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19778 self.clear_highlights::<InputComposition>(cx);
19779 self.ime_transaction.take();
19780 }
19781
19782 fn replace_text_in_range(
19783 &mut self,
19784 range_utf16: Option<Range<usize>>,
19785 text: &str,
19786 window: &mut Window,
19787 cx: &mut Context<Self>,
19788 ) {
19789 if !self.input_enabled {
19790 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19791 return;
19792 }
19793
19794 self.transact(window, cx, |this, window, cx| {
19795 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19796 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19797 Some(this.selection_replacement_ranges(range_utf16, cx))
19798 } else {
19799 this.marked_text_ranges(cx)
19800 };
19801
19802 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19803 let newest_selection_id = this.selections.newest_anchor().id;
19804 this.selections
19805 .all::<OffsetUtf16>(cx)
19806 .iter()
19807 .zip(ranges_to_replace.iter())
19808 .find_map(|(selection, range)| {
19809 if selection.id == newest_selection_id {
19810 Some(
19811 (range.start.0 as isize - selection.head().0 as isize)
19812 ..(range.end.0 as isize - selection.head().0 as isize),
19813 )
19814 } else {
19815 None
19816 }
19817 })
19818 });
19819
19820 cx.emit(EditorEvent::InputHandled {
19821 utf16_range_to_replace: range_to_replace,
19822 text: text.into(),
19823 });
19824
19825 if let Some(new_selected_ranges) = new_selected_ranges {
19826 this.change_selections(None, window, cx, |selections| {
19827 selections.select_ranges(new_selected_ranges)
19828 });
19829 this.backspace(&Default::default(), window, cx);
19830 }
19831
19832 this.handle_input(text, window, cx);
19833 });
19834
19835 if let Some(transaction) = self.ime_transaction {
19836 self.buffer.update(cx, |buffer, cx| {
19837 buffer.group_until_transaction(transaction, cx);
19838 });
19839 }
19840
19841 self.unmark_text(window, cx);
19842 }
19843
19844 fn replace_and_mark_text_in_range(
19845 &mut self,
19846 range_utf16: Option<Range<usize>>,
19847 text: &str,
19848 new_selected_range_utf16: Option<Range<usize>>,
19849 window: &mut Window,
19850 cx: &mut Context<Self>,
19851 ) {
19852 if !self.input_enabled {
19853 return;
19854 }
19855
19856 let transaction = self.transact(window, cx, |this, window, cx| {
19857 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19858 let snapshot = this.buffer.read(cx).read(cx);
19859 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19860 for marked_range in &mut marked_ranges {
19861 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19862 marked_range.start.0 += relative_range_utf16.start;
19863 marked_range.start =
19864 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19865 marked_range.end =
19866 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19867 }
19868 }
19869 Some(marked_ranges)
19870 } else if let Some(range_utf16) = range_utf16 {
19871 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19872 Some(this.selection_replacement_ranges(range_utf16, cx))
19873 } else {
19874 None
19875 };
19876
19877 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19878 let newest_selection_id = this.selections.newest_anchor().id;
19879 this.selections
19880 .all::<OffsetUtf16>(cx)
19881 .iter()
19882 .zip(ranges_to_replace.iter())
19883 .find_map(|(selection, range)| {
19884 if selection.id == newest_selection_id {
19885 Some(
19886 (range.start.0 as isize - selection.head().0 as isize)
19887 ..(range.end.0 as isize - selection.head().0 as isize),
19888 )
19889 } else {
19890 None
19891 }
19892 })
19893 });
19894
19895 cx.emit(EditorEvent::InputHandled {
19896 utf16_range_to_replace: range_to_replace,
19897 text: text.into(),
19898 });
19899
19900 if let Some(ranges) = ranges_to_replace {
19901 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19902 }
19903
19904 let marked_ranges = {
19905 let snapshot = this.buffer.read(cx).read(cx);
19906 this.selections
19907 .disjoint_anchors()
19908 .iter()
19909 .map(|selection| {
19910 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19911 })
19912 .collect::<Vec<_>>()
19913 };
19914
19915 if text.is_empty() {
19916 this.unmark_text(window, cx);
19917 } else {
19918 this.highlight_text::<InputComposition>(
19919 marked_ranges.clone(),
19920 HighlightStyle {
19921 underline: Some(UnderlineStyle {
19922 thickness: px(1.),
19923 color: None,
19924 wavy: false,
19925 }),
19926 ..Default::default()
19927 },
19928 cx,
19929 );
19930 }
19931
19932 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19933 let use_autoclose = this.use_autoclose;
19934 let use_auto_surround = this.use_auto_surround;
19935 this.set_use_autoclose(false);
19936 this.set_use_auto_surround(false);
19937 this.handle_input(text, window, cx);
19938 this.set_use_autoclose(use_autoclose);
19939 this.set_use_auto_surround(use_auto_surround);
19940
19941 if let Some(new_selected_range) = new_selected_range_utf16 {
19942 let snapshot = this.buffer.read(cx).read(cx);
19943 let new_selected_ranges = marked_ranges
19944 .into_iter()
19945 .map(|marked_range| {
19946 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19947 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19948 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19949 snapshot.clip_offset_utf16(new_start, Bias::Left)
19950 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19951 })
19952 .collect::<Vec<_>>();
19953
19954 drop(snapshot);
19955 this.change_selections(None, window, cx, |selections| {
19956 selections.select_ranges(new_selected_ranges)
19957 });
19958 }
19959 });
19960
19961 self.ime_transaction = self.ime_transaction.or(transaction);
19962 if let Some(transaction) = self.ime_transaction {
19963 self.buffer.update(cx, |buffer, cx| {
19964 buffer.group_until_transaction(transaction, cx);
19965 });
19966 }
19967
19968 if self.text_highlights::<InputComposition>(cx).is_none() {
19969 self.ime_transaction.take();
19970 }
19971 }
19972
19973 fn bounds_for_range(
19974 &mut self,
19975 range_utf16: Range<usize>,
19976 element_bounds: gpui::Bounds<Pixels>,
19977 window: &mut Window,
19978 cx: &mut Context<Self>,
19979 ) -> Option<gpui::Bounds<Pixels>> {
19980 let text_layout_details = self.text_layout_details(window);
19981 let gpui::Size {
19982 width: em_width,
19983 height: line_height,
19984 } = self.character_size(window);
19985
19986 let snapshot = self.snapshot(window, cx);
19987 let scroll_position = snapshot.scroll_position();
19988 let scroll_left = scroll_position.x * em_width;
19989
19990 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19991 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19992 + self.gutter_dimensions.width
19993 + self.gutter_dimensions.margin;
19994 let y = line_height * (start.row().as_f32() - scroll_position.y);
19995
19996 Some(Bounds {
19997 origin: element_bounds.origin + point(x, y),
19998 size: size(em_width, line_height),
19999 })
20000 }
20001
20002 fn character_index_for_point(
20003 &mut self,
20004 point: gpui::Point<Pixels>,
20005 _window: &mut Window,
20006 _cx: &mut Context<Self>,
20007 ) -> Option<usize> {
20008 let position_map = self.last_position_map.as_ref()?;
20009 if !position_map.text_hitbox.contains(&point) {
20010 return None;
20011 }
20012 let display_point = position_map.point_for_position(point).previous_valid;
20013 let anchor = position_map
20014 .snapshot
20015 .display_point_to_anchor(display_point, Bias::Left);
20016 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20017 Some(utf16_offset.0)
20018 }
20019}
20020
20021trait SelectionExt {
20022 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20023 fn spanned_rows(
20024 &self,
20025 include_end_if_at_line_start: bool,
20026 map: &DisplaySnapshot,
20027 ) -> Range<MultiBufferRow>;
20028}
20029
20030impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20031 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20032 let start = self
20033 .start
20034 .to_point(&map.buffer_snapshot)
20035 .to_display_point(map);
20036 let end = self
20037 .end
20038 .to_point(&map.buffer_snapshot)
20039 .to_display_point(map);
20040 if self.reversed {
20041 end..start
20042 } else {
20043 start..end
20044 }
20045 }
20046
20047 fn spanned_rows(
20048 &self,
20049 include_end_if_at_line_start: bool,
20050 map: &DisplaySnapshot,
20051 ) -> Range<MultiBufferRow> {
20052 let start = self.start.to_point(&map.buffer_snapshot);
20053 let mut end = self.end.to_point(&map.buffer_snapshot);
20054 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20055 end.row -= 1;
20056 }
20057
20058 let buffer_start = map.prev_line_boundary(start).0;
20059 let buffer_end = map.next_line_boundary(end).0;
20060 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20061 }
20062}
20063
20064impl<T: InvalidationRegion> InvalidationStack<T> {
20065 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20066 where
20067 S: Clone + ToOffset,
20068 {
20069 while let Some(region) = self.last() {
20070 let all_selections_inside_invalidation_ranges =
20071 if selections.len() == region.ranges().len() {
20072 selections
20073 .iter()
20074 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20075 .all(|(selection, invalidation_range)| {
20076 let head = selection.head().to_offset(buffer);
20077 invalidation_range.start <= head && invalidation_range.end >= head
20078 })
20079 } else {
20080 false
20081 };
20082
20083 if all_selections_inside_invalidation_ranges {
20084 break;
20085 } else {
20086 self.pop();
20087 }
20088 }
20089 }
20090}
20091
20092impl<T> Default for InvalidationStack<T> {
20093 fn default() -> Self {
20094 Self(Default::default())
20095 }
20096}
20097
20098impl<T> Deref for InvalidationStack<T> {
20099 type Target = Vec<T>;
20100
20101 fn deref(&self) -> &Self::Target {
20102 &self.0
20103 }
20104}
20105
20106impl<T> DerefMut for InvalidationStack<T> {
20107 fn deref_mut(&mut self) -> &mut Self::Target {
20108 &mut self.0
20109 }
20110}
20111
20112impl InvalidationRegion for SnippetState {
20113 fn ranges(&self) -> &[Range<Anchor>] {
20114 &self.ranges[self.active_index]
20115 }
20116}
20117
20118fn inline_completion_edit_text(
20119 current_snapshot: &BufferSnapshot,
20120 edits: &[(Range<Anchor>, String)],
20121 edit_preview: &EditPreview,
20122 include_deletions: bool,
20123 cx: &App,
20124) -> HighlightedText {
20125 let edits = edits
20126 .iter()
20127 .map(|(anchor, text)| {
20128 (
20129 anchor.start.text_anchor..anchor.end.text_anchor,
20130 text.clone(),
20131 )
20132 })
20133 .collect::<Vec<_>>();
20134
20135 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20136}
20137
20138pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20139 match severity {
20140 DiagnosticSeverity::ERROR => colors.error,
20141 DiagnosticSeverity::WARNING => colors.warning,
20142 DiagnosticSeverity::INFORMATION => colors.info,
20143 DiagnosticSeverity::HINT => colors.info,
20144 _ => colors.ignored,
20145 }
20146}
20147
20148pub fn styled_runs_for_code_label<'a>(
20149 label: &'a CodeLabel,
20150 syntax_theme: &'a theme::SyntaxTheme,
20151) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20152 let fade_out = HighlightStyle {
20153 fade_out: Some(0.35),
20154 ..Default::default()
20155 };
20156
20157 let mut prev_end = label.filter_range.end;
20158 label
20159 .runs
20160 .iter()
20161 .enumerate()
20162 .flat_map(move |(ix, (range, highlight_id))| {
20163 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20164 style
20165 } else {
20166 return Default::default();
20167 };
20168 let mut muted_style = style;
20169 muted_style.highlight(fade_out);
20170
20171 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20172 if range.start >= label.filter_range.end {
20173 if range.start > prev_end {
20174 runs.push((prev_end..range.start, fade_out));
20175 }
20176 runs.push((range.clone(), muted_style));
20177 } else if range.end <= label.filter_range.end {
20178 runs.push((range.clone(), style));
20179 } else {
20180 runs.push((range.start..label.filter_range.end, style));
20181 runs.push((label.filter_range.end..range.end, muted_style));
20182 }
20183 prev_end = cmp::max(prev_end, range.end);
20184
20185 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20186 runs.push((prev_end..label.text.len(), fade_out));
20187 }
20188
20189 runs
20190 })
20191}
20192
20193pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20194 let mut prev_index = 0;
20195 let mut prev_codepoint: Option<char> = None;
20196 text.char_indices()
20197 .chain([(text.len(), '\0')])
20198 .filter_map(move |(index, codepoint)| {
20199 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20200 let is_boundary = index == text.len()
20201 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20202 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20203 if is_boundary {
20204 let chunk = &text[prev_index..index];
20205 prev_index = index;
20206 Some(chunk)
20207 } else {
20208 None
20209 }
20210 })
20211}
20212
20213pub trait RangeToAnchorExt: Sized {
20214 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20215
20216 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20217 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20218 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20219 }
20220}
20221
20222impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20223 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20224 let start_offset = self.start.to_offset(snapshot);
20225 let end_offset = self.end.to_offset(snapshot);
20226 if start_offset == end_offset {
20227 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20228 } else {
20229 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20230 }
20231 }
20232}
20233
20234pub trait RowExt {
20235 fn as_f32(&self) -> f32;
20236
20237 fn next_row(&self) -> Self;
20238
20239 fn previous_row(&self) -> Self;
20240
20241 fn minus(&self, other: Self) -> u32;
20242}
20243
20244impl RowExt for DisplayRow {
20245 fn as_f32(&self) -> f32 {
20246 self.0 as f32
20247 }
20248
20249 fn next_row(&self) -> Self {
20250 Self(self.0 + 1)
20251 }
20252
20253 fn previous_row(&self) -> Self {
20254 Self(self.0.saturating_sub(1))
20255 }
20256
20257 fn minus(&self, other: Self) -> u32 {
20258 self.0 - other.0
20259 }
20260}
20261
20262impl RowExt for MultiBufferRow {
20263 fn as_f32(&self) -> f32 {
20264 self.0 as f32
20265 }
20266
20267 fn next_row(&self) -> Self {
20268 Self(self.0 + 1)
20269 }
20270
20271 fn previous_row(&self) -> Self {
20272 Self(self.0.saturating_sub(1))
20273 }
20274
20275 fn minus(&self, other: Self) -> u32 {
20276 self.0 - other.0
20277 }
20278}
20279
20280trait RowRangeExt {
20281 type Row;
20282
20283 fn len(&self) -> usize;
20284
20285 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20286}
20287
20288impl RowRangeExt for Range<MultiBufferRow> {
20289 type Row = MultiBufferRow;
20290
20291 fn len(&self) -> usize {
20292 (self.end.0 - self.start.0) as usize
20293 }
20294
20295 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20296 (self.start.0..self.end.0).map(MultiBufferRow)
20297 }
20298}
20299
20300impl RowRangeExt for Range<DisplayRow> {
20301 type Row = DisplayRow;
20302
20303 fn len(&self) -> usize {
20304 (self.end.0 - self.start.0) as usize
20305 }
20306
20307 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20308 (self.start.0..self.end.0).map(DisplayRow)
20309 }
20310}
20311
20312/// If select range has more than one line, we
20313/// just point the cursor to range.start.
20314fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20315 if range.start.row == range.end.row {
20316 range
20317 } else {
20318 range.start..range.start
20319 }
20320}
20321pub struct KillRing(ClipboardItem);
20322impl Global for KillRing {}
20323
20324const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20325
20326enum BreakpointPromptEditAction {
20327 Log,
20328 Condition,
20329 HitCondition,
20330}
20331
20332struct BreakpointPromptEditor {
20333 pub(crate) prompt: Entity<Editor>,
20334 editor: WeakEntity<Editor>,
20335 breakpoint_anchor: Anchor,
20336 breakpoint: Breakpoint,
20337 edit_action: BreakpointPromptEditAction,
20338 block_ids: HashSet<CustomBlockId>,
20339 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20340 _subscriptions: Vec<Subscription>,
20341}
20342
20343impl BreakpointPromptEditor {
20344 const MAX_LINES: u8 = 4;
20345
20346 fn new(
20347 editor: WeakEntity<Editor>,
20348 breakpoint_anchor: Anchor,
20349 breakpoint: Breakpoint,
20350 edit_action: BreakpointPromptEditAction,
20351 window: &mut Window,
20352 cx: &mut Context<Self>,
20353 ) -> Self {
20354 let base_text = match edit_action {
20355 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20356 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20357 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20358 }
20359 .map(|msg| msg.to_string())
20360 .unwrap_or_default();
20361
20362 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20363 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20364
20365 let prompt = cx.new(|cx| {
20366 let mut prompt = Editor::new(
20367 EditorMode::AutoHeight {
20368 max_lines: Self::MAX_LINES as usize,
20369 },
20370 buffer,
20371 None,
20372 window,
20373 cx,
20374 );
20375 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20376 prompt.set_show_cursor_when_unfocused(false, cx);
20377 prompt.set_placeholder_text(
20378 match edit_action {
20379 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20380 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20381 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20382 },
20383 cx,
20384 );
20385
20386 prompt
20387 });
20388
20389 Self {
20390 prompt,
20391 editor,
20392 breakpoint_anchor,
20393 breakpoint,
20394 edit_action,
20395 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20396 block_ids: Default::default(),
20397 _subscriptions: vec![],
20398 }
20399 }
20400
20401 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20402 self.block_ids.extend(block_ids)
20403 }
20404
20405 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20406 if let Some(editor) = self.editor.upgrade() {
20407 let message = self
20408 .prompt
20409 .read(cx)
20410 .buffer
20411 .read(cx)
20412 .as_singleton()
20413 .expect("A multi buffer in breakpoint prompt isn't possible")
20414 .read(cx)
20415 .as_rope()
20416 .to_string();
20417
20418 editor.update(cx, |editor, cx| {
20419 editor.edit_breakpoint_at_anchor(
20420 self.breakpoint_anchor,
20421 self.breakpoint.clone(),
20422 match self.edit_action {
20423 BreakpointPromptEditAction::Log => {
20424 BreakpointEditAction::EditLogMessage(message.into())
20425 }
20426 BreakpointPromptEditAction::Condition => {
20427 BreakpointEditAction::EditCondition(message.into())
20428 }
20429 BreakpointPromptEditAction::HitCondition => {
20430 BreakpointEditAction::EditHitCondition(message.into())
20431 }
20432 },
20433 cx,
20434 );
20435
20436 editor.remove_blocks(self.block_ids.clone(), None, cx);
20437 cx.focus_self(window);
20438 });
20439 }
20440 }
20441
20442 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20443 self.editor
20444 .update(cx, |editor, cx| {
20445 editor.remove_blocks(self.block_ids.clone(), None, cx);
20446 window.focus(&editor.focus_handle);
20447 })
20448 .log_err();
20449 }
20450
20451 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20452 let settings = ThemeSettings::get_global(cx);
20453 let text_style = TextStyle {
20454 color: if self.prompt.read(cx).read_only(cx) {
20455 cx.theme().colors().text_disabled
20456 } else {
20457 cx.theme().colors().text
20458 },
20459 font_family: settings.buffer_font.family.clone(),
20460 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20461 font_size: settings.buffer_font_size(cx).into(),
20462 font_weight: settings.buffer_font.weight,
20463 line_height: relative(settings.buffer_line_height.value()),
20464 ..Default::default()
20465 };
20466 EditorElement::new(
20467 &self.prompt,
20468 EditorStyle {
20469 background: cx.theme().colors().editor_background,
20470 local_player: cx.theme().players().local(),
20471 text: text_style,
20472 ..Default::default()
20473 },
20474 )
20475 }
20476}
20477
20478impl Render for BreakpointPromptEditor {
20479 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20480 let gutter_dimensions = *self.gutter_dimensions.lock();
20481 h_flex()
20482 .key_context("Editor")
20483 .bg(cx.theme().colors().editor_background)
20484 .border_y_1()
20485 .border_color(cx.theme().status().info_border)
20486 .size_full()
20487 .py(window.line_height() / 2.5)
20488 .on_action(cx.listener(Self::confirm))
20489 .on_action(cx.listener(Self::cancel))
20490 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20491 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20492 }
20493}
20494
20495impl Focusable for BreakpointPromptEditor {
20496 fn focus_handle(&self, cx: &App) -> FocusHandle {
20497 self.prompt.focus_handle(cx)
20498 }
20499}
20500
20501fn all_edits_insertions_or_deletions(
20502 edits: &Vec<(Range<Anchor>, String)>,
20503 snapshot: &MultiBufferSnapshot,
20504) -> bool {
20505 let mut all_insertions = true;
20506 let mut all_deletions = true;
20507
20508 for (range, new_text) in edits.iter() {
20509 let range_is_empty = range.to_offset(&snapshot).is_empty();
20510 let text_is_empty = new_text.is_empty();
20511
20512 if range_is_empty != text_is_empty {
20513 if range_is_empty {
20514 all_deletions = false;
20515 } else {
20516 all_insertions = false;
20517 }
20518 } else {
20519 return false;
20520 }
20521
20522 if !all_insertions && !all_deletions {
20523 return false;
20524 }
20525 }
20526 all_insertions || all_deletions
20527}
20528
20529struct MissingEditPredictionKeybindingTooltip;
20530
20531impl Render for MissingEditPredictionKeybindingTooltip {
20532 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20533 ui::tooltip_container(window, cx, |container, _, cx| {
20534 container
20535 .flex_shrink_0()
20536 .max_w_80()
20537 .min_h(rems_from_px(124.))
20538 .justify_between()
20539 .child(
20540 v_flex()
20541 .flex_1()
20542 .text_ui_sm(cx)
20543 .child(Label::new("Conflict with Accept Keybinding"))
20544 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20545 )
20546 .child(
20547 h_flex()
20548 .pb_1()
20549 .gap_1()
20550 .items_end()
20551 .w_full()
20552 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20553 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20554 }))
20555 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20556 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20557 })),
20558 )
20559 })
20560 }
20561}
20562
20563#[derive(Debug, Clone, Copy, PartialEq)]
20564pub struct LineHighlight {
20565 pub background: Background,
20566 pub border: Option<gpui::Hsla>,
20567}
20568
20569impl From<Hsla> for LineHighlight {
20570 fn from(hsla: Hsla) -> Self {
20571 Self {
20572 background: hsla.into(),
20573 border: None,
20574 }
20575 }
20576}
20577
20578impl From<Background> for LineHighlight {
20579 fn from(background: Background) -> Self {
20580 Self {
20581 background,
20582 border: None,
20583 }
20584 }
20585}
20586
20587fn render_diff_hunk_controls(
20588 row: u32,
20589 status: &DiffHunkStatus,
20590 hunk_range: Range<Anchor>,
20591 is_created_file: bool,
20592 line_height: Pixels,
20593 editor: &Entity<Editor>,
20594 _window: &mut Window,
20595 cx: &mut App,
20596) -> AnyElement {
20597 h_flex()
20598 .h(line_height)
20599 .mr_1()
20600 .gap_1()
20601 .px_0p5()
20602 .pb_1()
20603 .border_x_1()
20604 .border_b_1()
20605 .border_color(cx.theme().colors().border_variant)
20606 .rounded_b_lg()
20607 .bg(cx.theme().colors().editor_background)
20608 .gap_1()
20609 .occlude()
20610 .shadow_md()
20611 .child(if status.has_secondary_hunk() {
20612 Button::new(("stage", row as u64), "Stage")
20613 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20614 .tooltip({
20615 let focus_handle = editor.focus_handle(cx);
20616 move |window, cx| {
20617 Tooltip::for_action_in(
20618 "Stage Hunk",
20619 &::git::ToggleStaged,
20620 &focus_handle,
20621 window,
20622 cx,
20623 )
20624 }
20625 })
20626 .on_click({
20627 let editor = editor.clone();
20628 move |_event, _window, cx| {
20629 editor.update(cx, |editor, cx| {
20630 editor.stage_or_unstage_diff_hunks(
20631 true,
20632 vec![hunk_range.start..hunk_range.start],
20633 cx,
20634 );
20635 });
20636 }
20637 })
20638 } else {
20639 Button::new(("unstage", row as u64), "Unstage")
20640 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20641 .tooltip({
20642 let focus_handle = editor.focus_handle(cx);
20643 move |window, cx| {
20644 Tooltip::for_action_in(
20645 "Unstage Hunk",
20646 &::git::ToggleStaged,
20647 &focus_handle,
20648 window,
20649 cx,
20650 )
20651 }
20652 })
20653 .on_click({
20654 let editor = editor.clone();
20655 move |_event, _window, cx| {
20656 editor.update(cx, |editor, cx| {
20657 editor.stage_or_unstage_diff_hunks(
20658 false,
20659 vec![hunk_range.start..hunk_range.start],
20660 cx,
20661 );
20662 });
20663 }
20664 })
20665 })
20666 .child(
20667 Button::new(("restore", row as u64), "Restore")
20668 .tooltip({
20669 let focus_handle = editor.focus_handle(cx);
20670 move |window, cx| {
20671 Tooltip::for_action_in(
20672 "Restore Hunk",
20673 &::git::Restore,
20674 &focus_handle,
20675 window,
20676 cx,
20677 )
20678 }
20679 })
20680 .on_click({
20681 let editor = editor.clone();
20682 move |_event, window, cx| {
20683 editor.update(cx, |editor, cx| {
20684 let snapshot = editor.snapshot(window, cx);
20685 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20686 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20687 });
20688 }
20689 })
20690 .disabled(is_created_file),
20691 )
20692 .when(
20693 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20694 |el| {
20695 el.child(
20696 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20697 .shape(IconButtonShape::Square)
20698 .icon_size(IconSize::Small)
20699 // .disabled(!has_multiple_hunks)
20700 .tooltip({
20701 let focus_handle = editor.focus_handle(cx);
20702 move |window, cx| {
20703 Tooltip::for_action_in(
20704 "Next Hunk",
20705 &GoToHunk,
20706 &focus_handle,
20707 window,
20708 cx,
20709 )
20710 }
20711 })
20712 .on_click({
20713 let editor = editor.clone();
20714 move |_event, window, cx| {
20715 editor.update(cx, |editor, cx| {
20716 let snapshot = editor.snapshot(window, cx);
20717 let position =
20718 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20719 editor.go_to_hunk_before_or_after_position(
20720 &snapshot,
20721 position,
20722 Direction::Next,
20723 window,
20724 cx,
20725 );
20726 editor.expand_selected_diff_hunks(cx);
20727 });
20728 }
20729 }),
20730 )
20731 .child(
20732 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20733 .shape(IconButtonShape::Square)
20734 .icon_size(IconSize::Small)
20735 // .disabled(!has_multiple_hunks)
20736 .tooltip({
20737 let focus_handle = editor.focus_handle(cx);
20738 move |window, cx| {
20739 Tooltip::for_action_in(
20740 "Previous Hunk",
20741 &GoToPreviousHunk,
20742 &focus_handle,
20743 window,
20744 cx,
20745 )
20746 }
20747 })
20748 .on_click({
20749 let editor = editor.clone();
20750 move |_event, window, cx| {
20751 editor.update(cx, |editor, cx| {
20752 let snapshot = editor.snapshot(window, cx);
20753 let point =
20754 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20755 editor.go_to_hunk_before_or_after_position(
20756 &snapshot,
20757 point,
20758 Direction::Prev,
20759 window,
20760 cx,
20761 );
20762 editor.expand_selected_diff_hunks(cx);
20763 });
20764 }
20765 }),
20766 )
20767 },
20768 )
20769 .into_any_element()
20770}