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);
218
219pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
220pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
221pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
222
223pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
224pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
225pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
226
227pub type RenderDiffHunkControlsFn = Arc<
228 dyn Fn(
229 u32,
230 &DiffHunkStatus,
231 Range<Anchor>,
232 bool,
233 Pixels,
234 &Entity<Editor>,
235 &mut Window,
236 &mut App,
237 ) -> AnyElement,
238>;
239
240const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
241 alt: true,
242 shift: true,
243 control: false,
244 platform: false,
245 function: false,
246};
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
249pub enum InlayId {
250 InlineCompletion(usize),
251 Hint(usize),
252}
253
254impl InlayId {
255 fn id(&self) -> usize {
256 match self {
257 Self::InlineCompletion(id) => *id,
258 Self::Hint(id) => *id,
259 }
260 }
261}
262
263pub enum DebugCurrentRowHighlight {}
264enum DocumentHighlightRead {}
265enum DocumentHighlightWrite {}
266enum InputComposition {}
267enum SelectedTextHighlight {}
268
269#[derive(Debug, Copy, Clone, PartialEq, Eq)]
270pub enum Navigated {
271 Yes,
272 No,
273}
274
275impl Navigated {
276 pub fn from_bool(yes: bool) -> Navigated {
277 if yes { Navigated::Yes } else { Navigated::No }
278 }
279}
280
281#[derive(Debug, Clone, PartialEq, Eq)]
282enum DisplayDiffHunk {
283 Folded {
284 display_row: DisplayRow,
285 },
286 Unfolded {
287 is_created_file: bool,
288 diff_base_byte_range: Range<usize>,
289 display_row_range: Range<DisplayRow>,
290 multi_buffer_range: Range<Anchor>,
291 status: DiffHunkStatus,
292 },
293}
294
295pub enum HideMouseCursorOrigin {
296 TypingAction,
297 MovementAction,
298}
299
300pub fn init_settings(cx: &mut App) {
301 EditorSettings::register(cx);
302}
303
304pub fn init(cx: &mut App) {
305 init_settings(cx);
306
307 cx.set_global(GlobalBlameRenderer(Arc::new(())));
308
309 workspace::register_project_item::<Editor>(cx);
310 workspace::FollowableViewRegistry::register::<Editor>(cx);
311 workspace::register_serializable_item::<Editor>(cx);
312
313 cx.observe_new(
314 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
315 workspace.register_action(Editor::new_file);
316 workspace.register_action(Editor::new_file_vertical);
317 workspace.register_action(Editor::new_file_horizontal);
318 workspace.register_action(Editor::cancel_language_server_work);
319 },
320 )
321 .detach();
322
323 cx.on_action(move |_: &workspace::NewFile, cx| {
324 let app_state = workspace::AppState::global(cx);
325 if let Some(app_state) = app_state.upgrade() {
326 workspace::open_new(
327 Default::default(),
328 app_state,
329 cx,
330 |workspace, window, cx| {
331 Editor::new_file(workspace, &Default::default(), window, cx)
332 },
333 )
334 .detach();
335 }
336 });
337 cx.on_action(move |_: &workspace::NewWindow, cx| {
338 let app_state = workspace::AppState::global(cx);
339 if let Some(app_state) = app_state.upgrade() {
340 workspace::open_new(
341 Default::default(),
342 app_state,
343 cx,
344 |workspace, window, cx| {
345 cx.activate(true);
346 Editor::new_file(workspace, &Default::default(), window, cx)
347 },
348 )
349 .detach();
350 }
351 });
352}
353
354pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
355 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
356}
357
358pub trait DiagnosticRenderer {
359 fn render_group(
360 &self,
361 diagnostic_group: Vec<DiagnosticEntry<Point>>,
362 buffer_id: BufferId,
363 snapshot: EditorSnapshot,
364 editor: WeakEntity<Editor>,
365 cx: &mut App,
366 ) -> Vec<BlockProperties<Anchor>>;
367}
368
369pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
370
371impl gpui::Global for GlobalDiagnosticRenderer {}
372pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
373 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
374}
375
376pub struct SearchWithinRange;
377
378trait InvalidationRegion {
379 fn ranges(&self) -> &[Range<Anchor>];
380}
381
382#[derive(Clone, Debug, PartialEq)]
383pub enum SelectPhase {
384 Begin {
385 position: DisplayPoint,
386 add: bool,
387 click_count: usize,
388 },
389 BeginColumnar {
390 position: DisplayPoint,
391 reset: bool,
392 goal_column: u32,
393 },
394 Extend {
395 position: DisplayPoint,
396 click_count: usize,
397 },
398 Update {
399 position: DisplayPoint,
400 goal_column: u32,
401 scroll_delta: gpui::Point<f32>,
402 },
403 End,
404}
405
406#[derive(Clone, Debug)]
407pub enum SelectMode {
408 Character,
409 Word(Range<Anchor>),
410 Line(Range<Anchor>),
411 All,
412}
413
414#[derive(Copy, Clone, PartialEq, Eq, Debug)]
415pub enum EditorMode {
416 SingleLine {
417 auto_width: bool,
418 },
419 AutoHeight {
420 max_lines: usize,
421 },
422 Full {
423 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
424 scale_ui_elements_with_buffer_font_size: bool,
425 /// When set to `true`, the editor will render a background for the active line.
426 show_active_line_background: bool,
427 },
428}
429
430impl EditorMode {
431 pub fn full() -> Self {
432 Self::Full {
433 scale_ui_elements_with_buffer_font_size: true,
434 show_active_line_background: true,
435 }
436 }
437
438 pub fn is_full(&self) -> bool {
439 matches!(self, Self::Full { .. })
440 }
441}
442
443#[derive(Copy, Clone, Debug)]
444pub enum SoftWrap {
445 /// Prefer not to wrap at all.
446 ///
447 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
448 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
449 GitDiff,
450 /// Prefer a single line generally, unless an overly long line is encountered.
451 None,
452 /// Soft wrap lines that exceed the editor width.
453 EditorWidth,
454 /// Soft wrap lines at the preferred line length.
455 Column(u32),
456 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
457 Bounded(u32),
458}
459
460#[derive(Clone)]
461pub struct EditorStyle {
462 pub background: Hsla,
463 pub local_player: PlayerColor,
464 pub text: TextStyle,
465 pub scrollbar_width: Pixels,
466 pub syntax: Arc<SyntaxTheme>,
467 pub status: StatusColors,
468 pub inlay_hints_style: HighlightStyle,
469 pub inline_completion_styles: InlineCompletionStyles,
470 pub unnecessary_code_fade: f32,
471}
472
473impl Default for EditorStyle {
474 fn default() -> Self {
475 Self {
476 background: Hsla::default(),
477 local_player: PlayerColor::default(),
478 text: TextStyle::default(),
479 scrollbar_width: Pixels::default(),
480 syntax: Default::default(),
481 // HACK: Status colors don't have a real default.
482 // We should look into removing the status colors from the editor
483 // style and retrieve them directly from the theme.
484 status: StatusColors::dark(),
485 inlay_hints_style: HighlightStyle::default(),
486 inline_completion_styles: InlineCompletionStyles {
487 insertion: HighlightStyle::default(),
488 whitespace: HighlightStyle::default(),
489 },
490 unnecessary_code_fade: Default::default(),
491 }
492 }
493}
494
495pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
496 let show_background = language_settings::language_settings(None, None, cx)
497 .inlay_hints
498 .show_background;
499
500 HighlightStyle {
501 color: Some(cx.theme().status().hint),
502 background_color: show_background.then(|| cx.theme().status().hint_background),
503 ..HighlightStyle::default()
504 }
505}
506
507pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
508 InlineCompletionStyles {
509 insertion: HighlightStyle {
510 color: Some(cx.theme().status().predictive),
511 ..HighlightStyle::default()
512 },
513 whitespace: HighlightStyle {
514 background_color: Some(cx.theme().status().created_background),
515 ..HighlightStyle::default()
516 },
517 }
518}
519
520type CompletionId = usize;
521
522pub(crate) enum EditDisplayMode {
523 TabAccept,
524 DiffPopover,
525 Inline,
526}
527
528enum InlineCompletion {
529 Edit {
530 edits: Vec<(Range<Anchor>, String)>,
531 edit_preview: Option<EditPreview>,
532 display_mode: EditDisplayMode,
533 snapshot: BufferSnapshot,
534 },
535 Move {
536 target: Anchor,
537 snapshot: BufferSnapshot,
538 },
539}
540
541struct InlineCompletionState {
542 inlay_ids: Vec<InlayId>,
543 completion: InlineCompletion,
544 completion_id: Option<SharedString>,
545 invalidation_range: Range<Anchor>,
546}
547
548enum EditPredictionSettings {
549 Disabled,
550 Enabled {
551 show_in_menu: bool,
552 preview_requires_modifier: bool,
553 },
554}
555
556enum InlineCompletionHighlight {}
557
558#[derive(Debug, Clone)]
559struct InlineDiagnostic {
560 message: SharedString,
561 group_id: usize,
562 is_primary: bool,
563 start: Point,
564 severity: DiagnosticSeverity,
565}
566
567pub enum MenuInlineCompletionsPolicy {
568 Never,
569 ByProvider,
570}
571
572pub enum EditPredictionPreview {
573 /// Modifier is not pressed
574 Inactive { released_too_fast: bool },
575 /// Modifier pressed
576 Active {
577 since: Instant,
578 previous_scroll_position: Option<ScrollAnchor>,
579 },
580}
581
582impl EditPredictionPreview {
583 pub fn released_too_fast(&self) -> bool {
584 match self {
585 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
586 EditPredictionPreview::Active { .. } => false,
587 }
588 }
589
590 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
591 if let EditPredictionPreview::Active {
592 previous_scroll_position,
593 ..
594 } = self
595 {
596 *previous_scroll_position = scroll_position;
597 }
598 }
599}
600
601pub struct ContextMenuOptions {
602 pub min_entries_visible: usize,
603 pub max_entries_visible: usize,
604 pub placement: Option<ContextMenuPlacement>,
605}
606
607#[derive(Debug, Clone, PartialEq, Eq)]
608pub enum ContextMenuPlacement {
609 Above,
610 Below,
611}
612
613#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
614struct EditorActionId(usize);
615
616impl EditorActionId {
617 pub fn post_inc(&mut self) -> Self {
618 let answer = self.0;
619
620 *self = Self(answer + 1);
621
622 Self(answer)
623 }
624}
625
626// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
627// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
628
629type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
630type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
631
632#[derive(Default)]
633struct ScrollbarMarkerState {
634 scrollbar_size: Size<Pixels>,
635 dirty: bool,
636 markers: Arc<[PaintQuad]>,
637 pending_refresh: Option<Task<Result<()>>>,
638}
639
640impl ScrollbarMarkerState {
641 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
642 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
643 }
644}
645
646#[derive(Clone, Debug)]
647struct RunnableTasks {
648 templates: Vec<(TaskSourceKind, TaskTemplate)>,
649 offset: multi_buffer::Anchor,
650 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
651 column: u32,
652 // Values of all named captures, including those starting with '_'
653 extra_variables: HashMap<String, String>,
654 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
655 context_range: Range<BufferOffset>,
656}
657
658impl RunnableTasks {
659 fn resolve<'a>(
660 &'a self,
661 cx: &'a task::TaskContext,
662 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
663 self.templates.iter().filter_map(|(kind, template)| {
664 template
665 .resolve_task(&kind.to_id_base(), cx)
666 .map(|task| (kind.clone(), task))
667 })
668 }
669}
670
671#[derive(Clone)]
672struct ResolvedTasks {
673 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
674 position: Anchor,
675}
676
677#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
678struct BufferOffset(usize);
679
680// Addons allow storing per-editor state in other crates (e.g. Vim)
681pub trait Addon: 'static {
682 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
683
684 fn render_buffer_header_controls(
685 &self,
686 _: &ExcerptInfo,
687 _: &Window,
688 _: &App,
689 ) -> Option<AnyElement> {
690 None
691 }
692
693 fn to_any(&self) -> &dyn std::any::Any;
694}
695
696/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
697///
698/// See the [module level documentation](self) for more information.
699pub struct Editor {
700 focus_handle: FocusHandle,
701 last_focused_descendant: Option<WeakFocusHandle>,
702 /// The text buffer being edited
703 buffer: Entity<MultiBuffer>,
704 /// Map of how text in the buffer should be displayed.
705 /// Handles soft wraps, folds, fake inlay text insertions, etc.
706 pub display_map: Entity<DisplayMap>,
707 pub selections: SelectionsCollection,
708 pub scroll_manager: ScrollManager,
709 /// When inline assist editors are linked, they all render cursors because
710 /// typing enters text into each of them, even the ones that aren't focused.
711 pub(crate) show_cursor_when_unfocused: bool,
712 columnar_selection_tail: Option<Anchor>,
713 add_selections_state: Option<AddSelectionsState>,
714 select_next_state: Option<SelectNextState>,
715 select_prev_state: Option<SelectNextState>,
716 selection_history: SelectionHistory,
717 autoclose_regions: Vec<AutocloseRegion>,
718 snippet_stack: InvalidationStack<SnippetState>,
719 select_syntax_node_history: SelectSyntaxNodeHistory,
720 ime_transaction: Option<TransactionId>,
721 active_diagnostics: ActiveDiagnostic,
722 show_inline_diagnostics: bool,
723 inline_diagnostics_update: Task<()>,
724 inline_diagnostics_enabled: bool,
725 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
726 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
727 hard_wrap: Option<usize>,
728
729 // TODO: make this a access method
730 pub project: Option<Entity<Project>>,
731 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
732 completion_provider: Option<Box<dyn CompletionProvider>>,
733 collaboration_hub: Option<Box<dyn CollaborationHub>>,
734 blink_manager: Entity<BlinkManager>,
735 show_cursor_names: bool,
736 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
737 pub show_local_selections: bool,
738 mode: EditorMode,
739 show_breadcrumbs: bool,
740 show_gutter: bool,
741 show_scrollbars: bool,
742 show_line_numbers: Option<bool>,
743 use_relative_line_numbers: Option<bool>,
744 show_git_diff_gutter: Option<bool>,
745 show_code_actions: Option<bool>,
746 show_runnables: Option<bool>,
747 show_breakpoints: Option<bool>,
748 show_wrap_guides: Option<bool>,
749 show_indent_guides: Option<bool>,
750 placeholder_text: Option<Arc<str>>,
751 highlight_order: usize,
752 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
753 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
754 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
755 scrollbar_marker_state: ScrollbarMarkerState,
756 active_indent_guides_state: ActiveIndentGuidesState,
757 nav_history: Option<ItemNavHistory>,
758 context_menu: RefCell<Option<CodeContextMenu>>,
759 context_menu_options: Option<ContextMenuOptions>,
760 mouse_context_menu: Option<MouseContextMenu>,
761 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
762 signature_help_state: SignatureHelpState,
763 auto_signature_help: Option<bool>,
764 find_all_references_task_sources: Vec<Anchor>,
765 next_completion_id: CompletionId,
766 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
767 code_actions_task: Option<Task<Result<()>>>,
768 selection_highlight_task: Option<Task<()>>,
769 document_highlights_task: Option<Task<()>>,
770 linked_editing_range_task: Option<Task<Option<()>>>,
771 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
772 pending_rename: Option<RenameState>,
773 searchable: bool,
774 cursor_shape: CursorShape,
775 current_line_highlight: Option<CurrentLineHighlight>,
776 collapse_matches: bool,
777 autoindent_mode: Option<AutoindentMode>,
778 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
779 input_enabled: bool,
780 use_modal_editing: bool,
781 read_only: bool,
782 leader_peer_id: Option<PeerId>,
783 remote_id: Option<ViewId>,
784 hover_state: HoverState,
785 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
786 gutter_hovered: bool,
787 hovered_link_state: Option<HoveredLinkState>,
788 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
789 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
790 active_inline_completion: Option<InlineCompletionState>,
791 /// Used to prevent flickering as the user types while the menu is open
792 stale_inline_completion_in_menu: Option<InlineCompletionState>,
793 edit_prediction_settings: EditPredictionSettings,
794 inline_completions_hidden_for_vim_mode: bool,
795 show_inline_completions_override: Option<bool>,
796 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
797 edit_prediction_preview: EditPredictionPreview,
798 edit_prediction_indent_conflict: bool,
799 edit_prediction_requires_modifier_in_indent_conflict: bool,
800 inlay_hint_cache: InlayHintCache,
801 next_inlay_id: usize,
802 _subscriptions: Vec<Subscription>,
803 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
804 gutter_dimensions: GutterDimensions,
805 style: Option<EditorStyle>,
806 text_style_refinement: Option<TextStyleRefinement>,
807 next_editor_action_id: EditorActionId,
808 editor_actions:
809 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
810 use_autoclose: bool,
811 use_auto_surround: bool,
812 auto_replace_emoji_shortcode: bool,
813 jsx_tag_auto_close_enabled_in_any_buffer: bool,
814 show_git_blame_gutter: bool,
815 show_git_blame_inline: bool,
816 show_git_blame_inline_delay_task: Option<Task<()>>,
817 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
818 git_blame_inline_enabled: bool,
819 render_diff_hunk_controls: RenderDiffHunkControlsFn,
820 serialize_dirty_buffers: bool,
821 show_selection_menu: Option<bool>,
822 blame: Option<Entity<GitBlame>>,
823 blame_subscription: Option<Subscription>,
824 custom_context_menu: Option<
825 Box<
826 dyn 'static
827 + Fn(
828 &mut Self,
829 DisplayPoint,
830 &mut Window,
831 &mut Context<Self>,
832 ) -> Option<Entity<ui::ContextMenu>>,
833 >,
834 >,
835 last_bounds: Option<Bounds<Pixels>>,
836 last_position_map: Option<Rc<PositionMap>>,
837 expect_bounds_change: Option<Bounds<Pixels>>,
838 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
839 tasks_update_task: Option<Task<()>>,
840 breakpoint_store: Option<Entity<BreakpointStore>>,
841 /// Allow's a user to create a breakpoint by selecting this indicator
842 /// It should be None while a user is not hovering over the gutter
843 /// Otherwise it represents the point that the breakpoint will be shown
844 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
845 in_project_search: bool,
846 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
847 breadcrumb_header: Option<String>,
848 focused_block: Option<FocusedBlock>,
849 next_scroll_position: NextScrollCursorCenterTopBottom,
850 addons: HashMap<TypeId, Box<dyn Addon>>,
851 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
852 load_diff_task: Option<Shared<Task<()>>>,
853 selection_mark_mode: bool,
854 toggle_fold_multiple_buffers: Task<()>,
855 _scroll_cursor_center_top_bottom_task: Task<()>,
856 serialize_selections: Task<()>,
857 serialize_folds: Task<()>,
858 mouse_cursor_hidden: bool,
859 hide_mouse_mode: HideMouseMode,
860}
861
862#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
863enum NextScrollCursorCenterTopBottom {
864 #[default]
865 Center,
866 Top,
867 Bottom,
868}
869
870impl NextScrollCursorCenterTopBottom {
871 fn next(&self) -> Self {
872 match self {
873 Self::Center => Self::Top,
874 Self::Top => Self::Bottom,
875 Self::Bottom => Self::Center,
876 }
877 }
878}
879
880#[derive(Clone)]
881pub struct EditorSnapshot {
882 pub mode: EditorMode,
883 show_gutter: bool,
884 show_line_numbers: Option<bool>,
885 show_git_diff_gutter: Option<bool>,
886 show_code_actions: Option<bool>,
887 show_runnables: Option<bool>,
888 show_breakpoints: Option<bool>,
889 git_blame_gutter_max_author_length: Option<usize>,
890 pub display_snapshot: DisplaySnapshot,
891 pub placeholder_text: Option<Arc<str>>,
892 is_focused: bool,
893 scroll_anchor: ScrollAnchor,
894 ongoing_scroll: OngoingScroll,
895 current_line_highlight: CurrentLineHighlight,
896 gutter_hovered: bool,
897}
898
899#[derive(Default, Debug, Clone, Copy)]
900pub struct GutterDimensions {
901 pub left_padding: Pixels,
902 pub right_padding: Pixels,
903 pub width: Pixels,
904 pub margin: Pixels,
905 pub git_blame_entries_width: Option<Pixels>,
906}
907
908impl GutterDimensions {
909 /// The full width of the space taken up by the gutter.
910 pub fn full_width(&self) -> Pixels {
911 self.margin + self.width
912 }
913
914 /// The width of the space reserved for the fold indicators,
915 /// use alongside 'justify_end' and `gutter_width` to
916 /// right align content with the line numbers
917 pub fn fold_area_width(&self) -> Pixels {
918 self.margin + self.right_padding
919 }
920}
921
922#[derive(Debug)]
923pub struct RemoteSelection {
924 pub replica_id: ReplicaId,
925 pub selection: Selection<Anchor>,
926 pub cursor_shape: CursorShape,
927 pub peer_id: PeerId,
928 pub line_mode: bool,
929 pub participant_index: Option<ParticipantIndex>,
930 pub user_name: Option<SharedString>,
931}
932
933#[derive(Clone, Debug)]
934struct SelectionHistoryEntry {
935 selections: Arc<[Selection<Anchor>]>,
936 select_next_state: Option<SelectNextState>,
937 select_prev_state: Option<SelectNextState>,
938 add_selections_state: Option<AddSelectionsState>,
939}
940
941enum SelectionHistoryMode {
942 Normal,
943 Undoing,
944 Redoing,
945}
946
947#[derive(Clone, PartialEq, Eq, Hash)]
948struct HoveredCursor {
949 replica_id: u16,
950 selection_id: usize,
951}
952
953impl Default for SelectionHistoryMode {
954 fn default() -> Self {
955 Self::Normal
956 }
957}
958
959#[derive(Default)]
960struct SelectionHistory {
961 #[allow(clippy::type_complexity)]
962 selections_by_transaction:
963 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
964 mode: SelectionHistoryMode,
965 undo_stack: VecDeque<SelectionHistoryEntry>,
966 redo_stack: VecDeque<SelectionHistoryEntry>,
967}
968
969impl SelectionHistory {
970 fn insert_transaction(
971 &mut self,
972 transaction_id: TransactionId,
973 selections: Arc<[Selection<Anchor>]>,
974 ) {
975 self.selections_by_transaction
976 .insert(transaction_id, (selections, None));
977 }
978
979 #[allow(clippy::type_complexity)]
980 fn transaction(
981 &self,
982 transaction_id: TransactionId,
983 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
984 self.selections_by_transaction.get(&transaction_id)
985 }
986
987 #[allow(clippy::type_complexity)]
988 fn transaction_mut(
989 &mut self,
990 transaction_id: TransactionId,
991 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
992 self.selections_by_transaction.get_mut(&transaction_id)
993 }
994
995 fn push(&mut self, entry: SelectionHistoryEntry) {
996 if !entry.selections.is_empty() {
997 match self.mode {
998 SelectionHistoryMode::Normal => {
999 self.push_undo(entry);
1000 self.redo_stack.clear();
1001 }
1002 SelectionHistoryMode::Undoing => self.push_redo(entry),
1003 SelectionHistoryMode::Redoing => self.push_undo(entry),
1004 }
1005 }
1006 }
1007
1008 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1009 if self
1010 .undo_stack
1011 .back()
1012 .map_or(true, |e| e.selections != entry.selections)
1013 {
1014 self.undo_stack.push_back(entry);
1015 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1016 self.undo_stack.pop_front();
1017 }
1018 }
1019 }
1020
1021 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1022 if self
1023 .redo_stack
1024 .back()
1025 .map_or(true, |e| e.selections != entry.selections)
1026 {
1027 self.redo_stack.push_back(entry);
1028 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1029 self.redo_stack.pop_front();
1030 }
1031 }
1032 }
1033}
1034
1035struct RowHighlight {
1036 index: usize,
1037 range: Range<Anchor>,
1038 color: Hsla,
1039 should_autoscroll: bool,
1040}
1041
1042#[derive(Clone, Debug)]
1043struct AddSelectionsState {
1044 above: bool,
1045 stack: Vec<usize>,
1046}
1047
1048#[derive(Clone)]
1049struct SelectNextState {
1050 query: AhoCorasick,
1051 wordwise: bool,
1052 done: bool,
1053}
1054
1055impl std::fmt::Debug for SelectNextState {
1056 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1057 f.debug_struct(std::any::type_name::<Self>())
1058 .field("wordwise", &self.wordwise)
1059 .field("done", &self.done)
1060 .finish()
1061 }
1062}
1063
1064#[derive(Debug)]
1065struct AutocloseRegion {
1066 selection_id: usize,
1067 range: Range<Anchor>,
1068 pair: BracketPair,
1069}
1070
1071#[derive(Debug)]
1072struct SnippetState {
1073 ranges: Vec<Vec<Range<Anchor>>>,
1074 active_index: usize,
1075 choices: Vec<Option<Vec<String>>>,
1076}
1077
1078#[doc(hidden)]
1079pub struct RenameState {
1080 pub range: Range<Anchor>,
1081 pub old_name: Arc<str>,
1082 pub editor: Entity<Editor>,
1083 block_id: CustomBlockId,
1084}
1085
1086struct InvalidationStack<T>(Vec<T>);
1087
1088struct RegisteredInlineCompletionProvider {
1089 provider: Arc<dyn InlineCompletionProviderHandle>,
1090 _subscription: Subscription,
1091}
1092
1093#[derive(Debug, PartialEq, Eq)]
1094pub struct ActiveDiagnosticGroup {
1095 pub active_range: Range<Anchor>,
1096 pub active_message: String,
1097 pub group_id: usize,
1098 pub blocks: HashSet<CustomBlockId>,
1099}
1100
1101#[derive(Debug, PartialEq, Eq)]
1102#[allow(clippy::large_enum_variant)]
1103pub(crate) enum ActiveDiagnostic {
1104 None,
1105 All,
1106 Group(ActiveDiagnosticGroup),
1107}
1108
1109#[derive(Serialize, Deserialize, Clone, Debug)]
1110pub struct ClipboardSelection {
1111 /// The number of bytes in this selection.
1112 pub len: usize,
1113 /// Whether this was a full-line selection.
1114 pub is_entire_line: bool,
1115 /// The indentation of the first line when this content was originally copied.
1116 pub first_line_indent: u32,
1117}
1118
1119// selections, scroll behavior, was newest selection reversed
1120type SelectSyntaxNodeHistoryState = (
1121 Box<[Selection<usize>]>,
1122 SelectSyntaxNodeScrollBehavior,
1123 bool,
1124);
1125
1126#[derive(Default)]
1127struct SelectSyntaxNodeHistory {
1128 stack: Vec<SelectSyntaxNodeHistoryState>,
1129 // disable temporarily to allow changing selections without losing the stack
1130 pub disable_clearing: bool,
1131}
1132
1133impl SelectSyntaxNodeHistory {
1134 pub fn try_clear(&mut self) {
1135 if !self.disable_clearing {
1136 self.stack.clear();
1137 }
1138 }
1139
1140 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1141 self.stack.push(selection);
1142 }
1143
1144 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1145 self.stack.pop()
1146 }
1147}
1148
1149enum SelectSyntaxNodeScrollBehavior {
1150 CursorTop,
1151 FitSelection,
1152 CursorBottom,
1153}
1154
1155#[derive(Debug)]
1156pub(crate) struct NavigationData {
1157 cursor_anchor: Anchor,
1158 cursor_position: Point,
1159 scroll_anchor: ScrollAnchor,
1160 scroll_top_row: u32,
1161}
1162
1163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1164pub enum GotoDefinitionKind {
1165 Symbol,
1166 Declaration,
1167 Type,
1168 Implementation,
1169}
1170
1171#[derive(Debug, Clone)]
1172enum InlayHintRefreshReason {
1173 ModifiersChanged(bool),
1174 Toggle(bool),
1175 SettingsChange(InlayHintSettings),
1176 NewLinesShown,
1177 BufferEdited(HashSet<Arc<Language>>),
1178 RefreshRequested,
1179 ExcerptsRemoved(Vec<ExcerptId>),
1180}
1181
1182impl InlayHintRefreshReason {
1183 fn description(&self) -> &'static str {
1184 match self {
1185 Self::ModifiersChanged(_) => "modifiers changed",
1186 Self::Toggle(_) => "toggle",
1187 Self::SettingsChange(_) => "settings change",
1188 Self::NewLinesShown => "new lines shown",
1189 Self::BufferEdited(_) => "buffer edited",
1190 Self::RefreshRequested => "refresh requested",
1191 Self::ExcerptsRemoved(_) => "excerpts removed",
1192 }
1193 }
1194}
1195
1196pub enum FormatTarget {
1197 Buffers,
1198 Ranges(Vec<Range<MultiBufferPoint>>),
1199}
1200
1201pub(crate) struct FocusedBlock {
1202 id: BlockId,
1203 focus_handle: WeakFocusHandle,
1204}
1205
1206#[derive(Clone)]
1207enum JumpData {
1208 MultiBufferRow {
1209 row: MultiBufferRow,
1210 line_offset_from_top: u32,
1211 },
1212 MultiBufferPoint {
1213 excerpt_id: ExcerptId,
1214 position: Point,
1215 anchor: text::Anchor,
1216 line_offset_from_top: u32,
1217 },
1218}
1219
1220pub enum MultibufferSelectionMode {
1221 First,
1222 All,
1223}
1224
1225#[derive(Clone, Copy, Debug, Default)]
1226pub struct RewrapOptions {
1227 pub override_language_settings: bool,
1228 pub preserve_existing_whitespace: bool,
1229}
1230
1231impl Editor {
1232 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1233 let buffer = cx.new(|cx| Buffer::local("", cx));
1234 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1235 Self::new(
1236 EditorMode::SingleLine { auto_width: false },
1237 buffer,
1238 None,
1239 window,
1240 cx,
1241 )
1242 }
1243
1244 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1245 let buffer = cx.new(|cx| Buffer::local("", cx));
1246 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1247 Self::new(EditorMode::full(), buffer, None, window, cx)
1248 }
1249
1250 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1251 let buffer = cx.new(|cx| Buffer::local("", cx));
1252 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1253 Self::new(
1254 EditorMode::SingleLine { auto_width: true },
1255 buffer,
1256 None,
1257 window,
1258 cx,
1259 )
1260 }
1261
1262 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1263 let buffer = cx.new(|cx| Buffer::local("", cx));
1264 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1265 Self::new(
1266 EditorMode::AutoHeight { max_lines },
1267 buffer,
1268 None,
1269 window,
1270 cx,
1271 )
1272 }
1273
1274 pub fn for_buffer(
1275 buffer: Entity<Buffer>,
1276 project: Option<Entity<Project>>,
1277 window: &mut Window,
1278 cx: &mut Context<Self>,
1279 ) -> Self {
1280 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1281 Self::new(EditorMode::full(), buffer, project, window, cx)
1282 }
1283
1284 pub fn for_multibuffer(
1285 buffer: Entity<MultiBuffer>,
1286 project: Option<Entity<Project>>,
1287 window: &mut Window,
1288 cx: &mut Context<Self>,
1289 ) -> Self {
1290 Self::new(EditorMode::full(), buffer, project, window, cx)
1291 }
1292
1293 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1294 let mut clone = Self::new(
1295 self.mode,
1296 self.buffer.clone(),
1297 self.project.clone(),
1298 window,
1299 cx,
1300 );
1301 self.display_map.update(cx, |display_map, cx| {
1302 let snapshot = display_map.snapshot(cx);
1303 clone.display_map.update(cx, |display_map, cx| {
1304 display_map.set_state(&snapshot, cx);
1305 });
1306 });
1307 clone.folds_did_change(cx);
1308 clone.selections.clone_state(&self.selections);
1309 clone.scroll_manager.clone_state(&self.scroll_manager);
1310 clone.searchable = self.searchable;
1311 clone.read_only = self.read_only;
1312 clone
1313 }
1314
1315 pub fn new(
1316 mode: EditorMode,
1317 buffer: Entity<MultiBuffer>,
1318 project: Option<Entity<Project>>,
1319 window: &mut Window,
1320 cx: &mut Context<Self>,
1321 ) -> Self {
1322 let style = window.text_style();
1323 let font_size = style.font_size.to_pixels(window.rem_size());
1324 let editor = cx.entity().downgrade();
1325 let fold_placeholder = FoldPlaceholder {
1326 constrain_width: true,
1327 render: Arc::new(move |fold_id, fold_range, cx| {
1328 let editor = editor.clone();
1329 div()
1330 .id(fold_id)
1331 .bg(cx.theme().colors().ghost_element_background)
1332 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1333 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1334 .rounded_xs()
1335 .size_full()
1336 .cursor_pointer()
1337 .child("⋯")
1338 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1339 .on_click(move |_, _window, cx| {
1340 editor
1341 .update(cx, |editor, cx| {
1342 editor.unfold_ranges(
1343 &[fold_range.start..fold_range.end],
1344 true,
1345 false,
1346 cx,
1347 );
1348 cx.stop_propagation();
1349 })
1350 .ok();
1351 })
1352 .into_any()
1353 }),
1354 merge_adjacent: true,
1355 ..Default::default()
1356 };
1357 let display_map = cx.new(|cx| {
1358 DisplayMap::new(
1359 buffer.clone(),
1360 style.font(),
1361 font_size,
1362 None,
1363 FILE_HEADER_HEIGHT,
1364 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1365 fold_placeholder,
1366 cx,
1367 )
1368 });
1369
1370 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1371
1372 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1373
1374 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1375 .then(|| language_settings::SoftWrap::None);
1376
1377 let mut project_subscriptions = Vec::new();
1378 if mode.is_full() {
1379 if let Some(project) = project.as_ref() {
1380 project_subscriptions.push(cx.subscribe_in(
1381 project,
1382 window,
1383 |editor, _, event, window, cx| match event {
1384 project::Event::RefreshCodeLens => {
1385 // we always query lens with actions, without storing them, always refreshing them
1386 }
1387 project::Event::RefreshInlayHints => {
1388 editor
1389 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1390 }
1391 project::Event::SnippetEdit(id, snippet_edits) => {
1392 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1393 let focus_handle = editor.focus_handle(cx);
1394 if focus_handle.is_focused(window) {
1395 let snapshot = buffer.read(cx).snapshot();
1396 for (range, snippet) in snippet_edits {
1397 let editor_range =
1398 language::range_from_lsp(*range).to_offset(&snapshot);
1399 editor
1400 .insert_snippet(
1401 &[editor_range],
1402 snippet.clone(),
1403 window,
1404 cx,
1405 )
1406 .ok();
1407 }
1408 }
1409 }
1410 }
1411 _ => {}
1412 },
1413 ));
1414 if let Some(task_inventory) = project
1415 .read(cx)
1416 .task_store()
1417 .read(cx)
1418 .task_inventory()
1419 .cloned()
1420 {
1421 project_subscriptions.push(cx.observe_in(
1422 &task_inventory,
1423 window,
1424 |editor, _, window, cx| {
1425 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1426 },
1427 ));
1428 };
1429
1430 project_subscriptions.push(cx.subscribe_in(
1431 &project.read(cx).breakpoint_store(),
1432 window,
1433 |editor, _, event, window, cx| match event {
1434 BreakpointStoreEvent::ActiveDebugLineChanged => {
1435 if editor.go_to_active_debug_line(window, cx) {
1436 cx.stop_propagation();
1437 }
1438 }
1439 _ => {}
1440 },
1441 ));
1442 }
1443 }
1444
1445 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1446
1447 let inlay_hint_settings =
1448 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1449 let focus_handle = cx.focus_handle();
1450 cx.on_focus(&focus_handle, window, Self::handle_focus)
1451 .detach();
1452 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1453 .detach();
1454 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1455 .detach();
1456 cx.on_blur(&focus_handle, window, Self::handle_blur)
1457 .detach();
1458
1459 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1460 Some(false)
1461 } else {
1462 None
1463 };
1464
1465 let breakpoint_store = match (mode, project.as_ref()) {
1466 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1467 _ => None,
1468 };
1469
1470 let mut code_action_providers = Vec::new();
1471 let mut load_uncommitted_diff = None;
1472 if let Some(project) = project.clone() {
1473 load_uncommitted_diff = Some(
1474 get_uncommitted_diff_for_buffer(
1475 &project,
1476 buffer.read(cx).all_buffers(),
1477 buffer.clone(),
1478 cx,
1479 )
1480 .shared(),
1481 );
1482 code_action_providers.push(Rc::new(project) as Rc<_>);
1483 }
1484
1485 let mut this = Self {
1486 focus_handle,
1487 show_cursor_when_unfocused: false,
1488 last_focused_descendant: None,
1489 buffer: buffer.clone(),
1490 display_map: display_map.clone(),
1491 selections,
1492 scroll_manager: ScrollManager::new(cx),
1493 columnar_selection_tail: None,
1494 add_selections_state: None,
1495 select_next_state: None,
1496 select_prev_state: None,
1497 selection_history: Default::default(),
1498 autoclose_regions: Default::default(),
1499 snippet_stack: Default::default(),
1500 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1501 ime_transaction: Default::default(),
1502 active_diagnostics: ActiveDiagnostic::None,
1503 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1504 inline_diagnostics_update: Task::ready(()),
1505 inline_diagnostics: Vec::new(),
1506 soft_wrap_mode_override,
1507 hard_wrap: None,
1508 completion_provider: project.clone().map(|project| Box::new(project) as _),
1509 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1510 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1511 project,
1512 blink_manager: blink_manager.clone(),
1513 show_local_selections: true,
1514 show_scrollbars: true,
1515 mode,
1516 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1517 show_gutter: mode.is_full(),
1518 show_line_numbers: None,
1519 use_relative_line_numbers: None,
1520 show_git_diff_gutter: None,
1521 show_code_actions: None,
1522 show_runnables: None,
1523 show_breakpoints: None,
1524 show_wrap_guides: None,
1525 show_indent_guides,
1526 placeholder_text: None,
1527 highlight_order: 0,
1528 highlighted_rows: HashMap::default(),
1529 background_highlights: Default::default(),
1530 gutter_highlights: TreeMap::default(),
1531 scrollbar_marker_state: ScrollbarMarkerState::default(),
1532 active_indent_guides_state: ActiveIndentGuidesState::default(),
1533 nav_history: None,
1534 context_menu: RefCell::new(None),
1535 context_menu_options: None,
1536 mouse_context_menu: None,
1537 completion_tasks: Default::default(),
1538 signature_help_state: SignatureHelpState::default(),
1539 auto_signature_help: None,
1540 find_all_references_task_sources: Vec::new(),
1541 next_completion_id: 0,
1542 next_inlay_id: 0,
1543 code_action_providers,
1544 available_code_actions: Default::default(),
1545 code_actions_task: Default::default(),
1546 selection_highlight_task: Default::default(),
1547 document_highlights_task: Default::default(),
1548 linked_editing_range_task: Default::default(),
1549 pending_rename: Default::default(),
1550 searchable: true,
1551 cursor_shape: EditorSettings::get_global(cx)
1552 .cursor_shape
1553 .unwrap_or_default(),
1554 current_line_highlight: None,
1555 autoindent_mode: Some(AutoindentMode::EachLine),
1556 collapse_matches: false,
1557 workspace: None,
1558 input_enabled: true,
1559 use_modal_editing: mode.is_full(),
1560 read_only: false,
1561 use_autoclose: true,
1562 use_auto_surround: true,
1563 auto_replace_emoji_shortcode: false,
1564 jsx_tag_auto_close_enabled_in_any_buffer: false,
1565 leader_peer_id: None,
1566 remote_id: None,
1567 hover_state: Default::default(),
1568 pending_mouse_down: None,
1569 hovered_link_state: Default::default(),
1570 edit_prediction_provider: None,
1571 active_inline_completion: None,
1572 stale_inline_completion_in_menu: None,
1573 edit_prediction_preview: EditPredictionPreview::Inactive {
1574 released_too_fast: false,
1575 },
1576 inline_diagnostics_enabled: mode.is_full(),
1577 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1578
1579 gutter_hovered: false,
1580 pixel_position_of_newest_cursor: None,
1581 last_bounds: None,
1582 last_position_map: None,
1583 expect_bounds_change: None,
1584 gutter_dimensions: GutterDimensions::default(),
1585 style: None,
1586 show_cursor_names: false,
1587 hovered_cursors: Default::default(),
1588 next_editor_action_id: EditorActionId::default(),
1589 editor_actions: Rc::default(),
1590 inline_completions_hidden_for_vim_mode: false,
1591 show_inline_completions_override: None,
1592 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1593 edit_prediction_settings: EditPredictionSettings::Disabled,
1594 edit_prediction_indent_conflict: false,
1595 edit_prediction_requires_modifier_in_indent_conflict: true,
1596 custom_context_menu: None,
1597 show_git_blame_gutter: false,
1598 show_git_blame_inline: false,
1599 show_selection_menu: None,
1600 show_git_blame_inline_delay_task: None,
1601 git_blame_inline_tooltip: None,
1602 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1603 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1604 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1605 .session
1606 .restore_unsaved_buffers,
1607 blame: None,
1608 blame_subscription: None,
1609 tasks: Default::default(),
1610
1611 breakpoint_store,
1612 gutter_breakpoint_indicator: (None, None),
1613 _subscriptions: vec![
1614 cx.observe(&buffer, Self::on_buffer_changed),
1615 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1616 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1617 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1618 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1619 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1620 cx.observe_window_activation(window, |editor, window, cx| {
1621 let active = window.is_window_active();
1622 editor.blink_manager.update(cx, |blink_manager, cx| {
1623 if active {
1624 blink_manager.enable(cx);
1625 } else {
1626 blink_manager.disable(cx);
1627 }
1628 });
1629 }),
1630 ],
1631 tasks_update_task: None,
1632 linked_edit_ranges: Default::default(),
1633 in_project_search: false,
1634 previous_search_ranges: None,
1635 breadcrumb_header: None,
1636 focused_block: None,
1637 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1638 addons: HashMap::default(),
1639 registered_buffers: HashMap::default(),
1640 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1641 selection_mark_mode: false,
1642 toggle_fold_multiple_buffers: Task::ready(()),
1643 serialize_selections: Task::ready(()),
1644 serialize_folds: Task::ready(()),
1645 text_style_refinement: None,
1646 load_diff_task: load_uncommitted_diff,
1647 mouse_cursor_hidden: false,
1648 hide_mouse_mode: EditorSettings::get_global(cx)
1649 .hide_mouse
1650 .unwrap_or_default(),
1651 };
1652 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1653 this._subscriptions
1654 .push(cx.observe(breakpoints, |_, _, cx| {
1655 cx.notify();
1656 }));
1657 }
1658 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1659 this._subscriptions.extend(project_subscriptions);
1660
1661 this._subscriptions.push(cx.subscribe_in(
1662 &cx.entity(),
1663 window,
1664 |editor, _, e: &EditorEvent, window, cx| {
1665 if let EditorEvent::SelectionsChanged { local } = e {
1666 if *local {
1667 let new_anchor = editor.scroll_manager.anchor();
1668 let snapshot = editor.snapshot(window, cx);
1669 editor.update_restoration_data(cx, move |data| {
1670 data.scroll_position = (
1671 new_anchor.top_row(&snapshot.buffer_snapshot),
1672 new_anchor.offset,
1673 );
1674 });
1675 }
1676 }
1677 },
1678 ));
1679
1680 this.end_selection(window, cx);
1681 this.scroll_manager.show_scrollbars(window, cx);
1682 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1683
1684 if mode.is_full() {
1685 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1686 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1687
1688 if this.git_blame_inline_enabled {
1689 this.git_blame_inline_enabled = true;
1690 this.start_git_blame_inline(false, window, cx);
1691 }
1692
1693 this.go_to_active_debug_line(window, cx);
1694
1695 if let Some(buffer) = buffer.read(cx).as_singleton() {
1696 if let Some(project) = this.project.as_ref() {
1697 let handle = project.update(cx, |project, cx| {
1698 project.register_buffer_with_language_servers(&buffer, cx)
1699 });
1700 this.registered_buffers
1701 .insert(buffer.read(cx).remote_id(), handle);
1702 }
1703 }
1704 }
1705
1706 this.report_editor_event("Editor Opened", None, cx);
1707 this
1708 }
1709
1710 pub fn deploy_mouse_context_menu(
1711 &mut self,
1712 position: gpui::Point<Pixels>,
1713 context_menu: Entity<ContextMenu>,
1714 window: &mut Window,
1715 cx: &mut Context<Self>,
1716 ) {
1717 self.mouse_context_menu = Some(MouseContextMenu::new(
1718 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1719 context_menu,
1720 None,
1721 window,
1722 cx,
1723 ));
1724 }
1725
1726 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1727 self.mouse_context_menu
1728 .as_ref()
1729 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1730 }
1731
1732 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1733 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1734 }
1735
1736 fn key_context_internal(
1737 &self,
1738 has_active_edit_prediction: bool,
1739 window: &Window,
1740 cx: &App,
1741 ) -> KeyContext {
1742 let mut key_context = KeyContext::new_with_defaults();
1743 key_context.add("Editor");
1744 let mode = match self.mode {
1745 EditorMode::SingleLine { .. } => "single_line",
1746 EditorMode::AutoHeight { .. } => "auto_height",
1747 EditorMode::Full { .. } => "full",
1748 };
1749
1750 if EditorSettings::jupyter_enabled(cx) {
1751 key_context.add("jupyter");
1752 }
1753
1754 key_context.set("mode", mode);
1755 if self.pending_rename.is_some() {
1756 key_context.add("renaming");
1757 }
1758
1759 match self.context_menu.borrow().as_ref() {
1760 Some(CodeContextMenu::Completions(_)) => {
1761 key_context.add("menu");
1762 key_context.add("showing_completions");
1763 }
1764 Some(CodeContextMenu::CodeActions(_)) => {
1765 key_context.add("menu");
1766 key_context.add("showing_code_actions")
1767 }
1768 None => {}
1769 }
1770
1771 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1772 if !self.focus_handle(cx).contains_focused(window, cx)
1773 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1774 {
1775 for addon in self.addons.values() {
1776 addon.extend_key_context(&mut key_context, cx)
1777 }
1778 }
1779
1780 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1781 if let Some(extension) = singleton_buffer
1782 .read(cx)
1783 .file()
1784 .and_then(|file| file.path().extension()?.to_str())
1785 {
1786 key_context.set("extension", extension.to_string());
1787 }
1788 } else {
1789 key_context.add("multibuffer");
1790 }
1791
1792 if has_active_edit_prediction {
1793 if self.edit_prediction_in_conflict() {
1794 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1795 } else {
1796 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1797 key_context.add("copilot_suggestion");
1798 }
1799 }
1800
1801 if self.selection_mark_mode {
1802 key_context.add("selection_mode");
1803 }
1804
1805 key_context
1806 }
1807
1808 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1809 self.mouse_cursor_hidden = match origin {
1810 HideMouseCursorOrigin::TypingAction => {
1811 matches!(
1812 self.hide_mouse_mode,
1813 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1814 )
1815 }
1816 HideMouseCursorOrigin::MovementAction => {
1817 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1818 }
1819 };
1820 }
1821
1822 pub fn edit_prediction_in_conflict(&self) -> bool {
1823 if !self.show_edit_predictions_in_menu() {
1824 return false;
1825 }
1826
1827 let showing_completions = self
1828 .context_menu
1829 .borrow()
1830 .as_ref()
1831 .map_or(false, |context| {
1832 matches!(context, CodeContextMenu::Completions(_))
1833 });
1834
1835 showing_completions
1836 || self.edit_prediction_requires_modifier()
1837 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1838 // bindings to insert tab characters.
1839 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1840 }
1841
1842 pub fn accept_edit_prediction_keybind(
1843 &self,
1844 window: &Window,
1845 cx: &App,
1846 ) -> AcceptEditPredictionBinding {
1847 let key_context = self.key_context_internal(true, window, cx);
1848 let in_conflict = self.edit_prediction_in_conflict();
1849
1850 AcceptEditPredictionBinding(
1851 window
1852 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1853 .into_iter()
1854 .filter(|binding| {
1855 !in_conflict
1856 || binding
1857 .keystrokes()
1858 .first()
1859 .map_or(false, |keystroke| keystroke.modifiers.modified())
1860 })
1861 .rev()
1862 .min_by_key(|binding| {
1863 binding
1864 .keystrokes()
1865 .first()
1866 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1867 }),
1868 )
1869 }
1870
1871 pub fn new_file(
1872 workspace: &mut Workspace,
1873 _: &workspace::NewFile,
1874 window: &mut Window,
1875 cx: &mut Context<Workspace>,
1876 ) {
1877 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1878 "Failed to create buffer",
1879 window,
1880 cx,
1881 |e, _, _| match e.error_code() {
1882 ErrorCode::RemoteUpgradeRequired => Some(format!(
1883 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1884 e.error_tag("required").unwrap_or("the latest version")
1885 )),
1886 _ => None,
1887 },
1888 );
1889 }
1890
1891 pub fn new_in_workspace(
1892 workspace: &mut Workspace,
1893 window: &mut Window,
1894 cx: &mut Context<Workspace>,
1895 ) -> Task<Result<Entity<Editor>>> {
1896 let project = workspace.project().clone();
1897 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1898
1899 cx.spawn_in(window, async move |workspace, cx| {
1900 let buffer = create.await?;
1901 workspace.update_in(cx, |workspace, window, cx| {
1902 let editor =
1903 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1904 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1905 editor
1906 })
1907 })
1908 }
1909
1910 fn new_file_vertical(
1911 workspace: &mut Workspace,
1912 _: &workspace::NewFileSplitVertical,
1913 window: &mut Window,
1914 cx: &mut Context<Workspace>,
1915 ) {
1916 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1917 }
1918
1919 fn new_file_horizontal(
1920 workspace: &mut Workspace,
1921 _: &workspace::NewFileSplitHorizontal,
1922 window: &mut Window,
1923 cx: &mut Context<Workspace>,
1924 ) {
1925 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1926 }
1927
1928 fn new_file_in_direction(
1929 workspace: &mut Workspace,
1930 direction: SplitDirection,
1931 window: &mut Window,
1932 cx: &mut Context<Workspace>,
1933 ) {
1934 let project = workspace.project().clone();
1935 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1936
1937 cx.spawn_in(window, async move |workspace, cx| {
1938 let buffer = create.await?;
1939 workspace.update_in(cx, move |workspace, window, cx| {
1940 workspace.split_item(
1941 direction,
1942 Box::new(
1943 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1944 ),
1945 window,
1946 cx,
1947 )
1948 })?;
1949 anyhow::Ok(())
1950 })
1951 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1952 match e.error_code() {
1953 ErrorCode::RemoteUpgradeRequired => Some(format!(
1954 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1955 e.error_tag("required").unwrap_or("the latest version")
1956 )),
1957 _ => None,
1958 }
1959 });
1960 }
1961
1962 pub fn leader_peer_id(&self) -> Option<PeerId> {
1963 self.leader_peer_id
1964 }
1965
1966 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1967 &self.buffer
1968 }
1969
1970 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1971 self.workspace.as_ref()?.0.upgrade()
1972 }
1973
1974 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1975 self.buffer().read(cx).title(cx)
1976 }
1977
1978 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1979 let git_blame_gutter_max_author_length = self
1980 .render_git_blame_gutter(cx)
1981 .then(|| {
1982 if let Some(blame) = self.blame.as_ref() {
1983 let max_author_length =
1984 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1985 Some(max_author_length)
1986 } else {
1987 None
1988 }
1989 })
1990 .flatten();
1991
1992 EditorSnapshot {
1993 mode: self.mode,
1994 show_gutter: self.show_gutter,
1995 show_line_numbers: self.show_line_numbers,
1996 show_git_diff_gutter: self.show_git_diff_gutter,
1997 show_code_actions: self.show_code_actions,
1998 show_runnables: self.show_runnables,
1999 show_breakpoints: self.show_breakpoints,
2000 git_blame_gutter_max_author_length,
2001 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2002 scroll_anchor: self.scroll_manager.anchor(),
2003 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2004 placeholder_text: self.placeholder_text.clone(),
2005 is_focused: self.focus_handle.is_focused(window),
2006 current_line_highlight: self
2007 .current_line_highlight
2008 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2009 gutter_hovered: self.gutter_hovered,
2010 }
2011 }
2012
2013 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2014 self.buffer.read(cx).language_at(point, cx)
2015 }
2016
2017 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2018 self.buffer.read(cx).read(cx).file_at(point).cloned()
2019 }
2020
2021 pub fn active_excerpt(
2022 &self,
2023 cx: &App,
2024 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2025 self.buffer
2026 .read(cx)
2027 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2028 }
2029
2030 pub fn mode(&self) -> EditorMode {
2031 self.mode
2032 }
2033
2034 pub fn set_mode(&mut self, mode: EditorMode) {
2035 self.mode = mode;
2036 }
2037
2038 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2039 self.collaboration_hub.as_deref()
2040 }
2041
2042 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2043 self.collaboration_hub = Some(hub);
2044 }
2045
2046 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2047 self.in_project_search = in_project_search;
2048 }
2049
2050 pub fn set_custom_context_menu(
2051 &mut self,
2052 f: impl 'static
2053 + Fn(
2054 &mut Self,
2055 DisplayPoint,
2056 &mut Window,
2057 &mut Context<Self>,
2058 ) -> Option<Entity<ui::ContextMenu>>,
2059 ) {
2060 self.custom_context_menu = Some(Box::new(f))
2061 }
2062
2063 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2064 self.completion_provider = provider;
2065 }
2066
2067 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2068 self.semantics_provider.clone()
2069 }
2070
2071 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2072 self.semantics_provider = provider;
2073 }
2074
2075 pub fn set_edit_prediction_provider<T>(
2076 &mut self,
2077 provider: Option<Entity<T>>,
2078 window: &mut Window,
2079 cx: &mut Context<Self>,
2080 ) where
2081 T: EditPredictionProvider,
2082 {
2083 self.edit_prediction_provider =
2084 provider.map(|provider| RegisteredInlineCompletionProvider {
2085 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2086 if this.focus_handle.is_focused(window) {
2087 this.update_visible_inline_completion(window, cx);
2088 }
2089 }),
2090 provider: Arc::new(provider),
2091 });
2092 self.update_edit_prediction_settings(cx);
2093 self.refresh_inline_completion(false, false, window, cx);
2094 }
2095
2096 pub fn placeholder_text(&self) -> Option<&str> {
2097 self.placeholder_text.as_deref()
2098 }
2099
2100 pub fn set_placeholder_text(
2101 &mut self,
2102 placeholder_text: impl Into<Arc<str>>,
2103 cx: &mut Context<Self>,
2104 ) {
2105 let placeholder_text = Some(placeholder_text.into());
2106 if self.placeholder_text != placeholder_text {
2107 self.placeholder_text = placeholder_text;
2108 cx.notify();
2109 }
2110 }
2111
2112 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2113 self.cursor_shape = cursor_shape;
2114
2115 // Disrupt blink for immediate user feedback that the cursor shape has changed
2116 self.blink_manager.update(cx, BlinkManager::show_cursor);
2117
2118 cx.notify();
2119 }
2120
2121 pub fn set_current_line_highlight(
2122 &mut self,
2123 current_line_highlight: Option<CurrentLineHighlight>,
2124 ) {
2125 self.current_line_highlight = current_line_highlight;
2126 }
2127
2128 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2129 self.collapse_matches = collapse_matches;
2130 }
2131
2132 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2133 let buffers = self.buffer.read(cx).all_buffers();
2134 let Some(project) = self.project.as_ref() else {
2135 return;
2136 };
2137 project.update(cx, |project, cx| {
2138 for buffer in buffers {
2139 self.registered_buffers
2140 .entry(buffer.read(cx).remote_id())
2141 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2142 }
2143 })
2144 }
2145
2146 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2147 if self.collapse_matches {
2148 return range.start..range.start;
2149 }
2150 range.clone()
2151 }
2152
2153 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2154 if self.display_map.read(cx).clip_at_line_ends != clip {
2155 self.display_map
2156 .update(cx, |map, _| map.clip_at_line_ends = clip);
2157 }
2158 }
2159
2160 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2161 self.input_enabled = input_enabled;
2162 }
2163
2164 pub fn set_inline_completions_hidden_for_vim_mode(
2165 &mut self,
2166 hidden: bool,
2167 window: &mut Window,
2168 cx: &mut Context<Self>,
2169 ) {
2170 if hidden != self.inline_completions_hidden_for_vim_mode {
2171 self.inline_completions_hidden_for_vim_mode = hidden;
2172 if hidden {
2173 self.update_visible_inline_completion(window, cx);
2174 } else {
2175 self.refresh_inline_completion(true, false, window, cx);
2176 }
2177 }
2178 }
2179
2180 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2181 self.menu_inline_completions_policy = value;
2182 }
2183
2184 pub fn set_autoindent(&mut self, autoindent: bool) {
2185 if autoindent {
2186 self.autoindent_mode = Some(AutoindentMode::EachLine);
2187 } else {
2188 self.autoindent_mode = None;
2189 }
2190 }
2191
2192 pub fn read_only(&self, cx: &App) -> bool {
2193 self.read_only || self.buffer.read(cx).read_only()
2194 }
2195
2196 pub fn set_read_only(&mut self, read_only: bool) {
2197 self.read_only = read_only;
2198 }
2199
2200 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2201 self.use_autoclose = autoclose;
2202 }
2203
2204 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2205 self.use_auto_surround = auto_surround;
2206 }
2207
2208 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2209 self.auto_replace_emoji_shortcode = auto_replace;
2210 }
2211
2212 pub fn toggle_edit_predictions(
2213 &mut self,
2214 _: &ToggleEditPrediction,
2215 window: &mut Window,
2216 cx: &mut Context<Self>,
2217 ) {
2218 if self.show_inline_completions_override.is_some() {
2219 self.set_show_edit_predictions(None, window, cx);
2220 } else {
2221 let show_edit_predictions = !self.edit_predictions_enabled();
2222 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2223 }
2224 }
2225
2226 pub fn set_show_edit_predictions(
2227 &mut self,
2228 show_edit_predictions: Option<bool>,
2229 window: &mut Window,
2230 cx: &mut Context<Self>,
2231 ) {
2232 self.show_inline_completions_override = show_edit_predictions;
2233 self.update_edit_prediction_settings(cx);
2234
2235 if let Some(false) = show_edit_predictions {
2236 self.discard_inline_completion(false, cx);
2237 } else {
2238 self.refresh_inline_completion(false, true, window, cx);
2239 }
2240 }
2241
2242 fn inline_completions_disabled_in_scope(
2243 &self,
2244 buffer: &Entity<Buffer>,
2245 buffer_position: language::Anchor,
2246 cx: &App,
2247 ) -> bool {
2248 let snapshot = buffer.read(cx).snapshot();
2249 let settings = snapshot.settings_at(buffer_position, cx);
2250
2251 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2252 return false;
2253 };
2254
2255 scope.override_name().map_or(false, |scope_name| {
2256 settings
2257 .edit_predictions_disabled_in
2258 .iter()
2259 .any(|s| s == scope_name)
2260 })
2261 }
2262
2263 pub fn set_use_modal_editing(&mut self, to: bool) {
2264 self.use_modal_editing = to;
2265 }
2266
2267 pub fn use_modal_editing(&self) -> bool {
2268 self.use_modal_editing
2269 }
2270
2271 fn selections_did_change(
2272 &mut self,
2273 local: bool,
2274 old_cursor_position: &Anchor,
2275 show_completions: bool,
2276 window: &mut Window,
2277 cx: &mut Context<Self>,
2278 ) {
2279 window.invalidate_character_coordinates();
2280
2281 // Copy selections to primary selection buffer
2282 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2283 if local {
2284 let selections = self.selections.all::<usize>(cx);
2285 let buffer_handle = self.buffer.read(cx).read(cx);
2286
2287 let mut text = String::new();
2288 for (index, selection) in selections.iter().enumerate() {
2289 let text_for_selection = buffer_handle
2290 .text_for_range(selection.start..selection.end)
2291 .collect::<String>();
2292
2293 text.push_str(&text_for_selection);
2294 if index != selections.len() - 1 {
2295 text.push('\n');
2296 }
2297 }
2298
2299 if !text.is_empty() {
2300 cx.write_to_primary(ClipboardItem::new_string(text));
2301 }
2302 }
2303
2304 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2305 self.buffer.update(cx, |buffer, cx| {
2306 buffer.set_active_selections(
2307 &self.selections.disjoint_anchors(),
2308 self.selections.line_mode,
2309 self.cursor_shape,
2310 cx,
2311 )
2312 });
2313 }
2314 let display_map = self
2315 .display_map
2316 .update(cx, |display_map, cx| display_map.snapshot(cx));
2317 let buffer = &display_map.buffer_snapshot;
2318 self.add_selections_state = None;
2319 self.select_next_state = None;
2320 self.select_prev_state = None;
2321 self.select_syntax_node_history.try_clear();
2322 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2323 self.snippet_stack
2324 .invalidate(&self.selections.disjoint_anchors(), buffer);
2325 self.take_rename(false, window, cx);
2326
2327 let new_cursor_position = self.selections.newest_anchor().head();
2328
2329 self.push_to_nav_history(
2330 *old_cursor_position,
2331 Some(new_cursor_position.to_point(buffer)),
2332 false,
2333 cx,
2334 );
2335
2336 if local {
2337 let new_cursor_position = self.selections.newest_anchor().head();
2338 let mut context_menu = self.context_menu.borrow_mut();
2339 let completion_menu = match context_menu.as_ref() {
2340 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2341 _ => {
2342 *context_menu = None;
2343 None
2344 }
2345 };
2346 if let Some(buffer_id) = new_cursor_position.buffer_id {
2347 if !self.registered_buffers.contains_key(&buffer_id) {
2348 if let Some(project) = self.project.as_ref() {
2349 project.update(cx, |project, cx| {
2350 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2351 return;
2352 };
2353 self.registered_buffers.insert(
2354 buffer_id,
2355 project.register_buffer_with_language_servers(&buffer, cx),
2356 );
2357 })
2358 }
2359 }
2360 }
2361
2362 if let Some(completion_menu) = completion_menu {
2363 let cursor_position = new_cursor_position.to_offset(buffer);
2364 let (word_range, kind) =
2365 buffer.surrounding_word(completion_menu.initial_position, true);
2366 if kind == Some(CharKind::Word)
2367 && word_range.to_inclusive().contains(&cursor_position)
2368 {
2369 let mut completion_menu = completion_menu.clone();
2370 drop(context_menu);
2371
2372 let query = Self::completion_query(buffer, cursor_position);
2373 cx.spawn(async move |this, cx| {
2374 completion_menu
2375 .filter(query.as_deref(), cx.background_executor().clone())
2376 .await;
2377
2378 this.update(cx, |this, cx| {
2379 let mut context_menu = this.context_menu.borrow_mut();
2380 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2381 else {
2382 return;
2383 };
2384
2385 if menu.id > completion_menu.id {
2386 return;
2387 }
2388
2389 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2390 drop(context_menu);
2391 cx.notify();
2392 })
2393 })
2394 .detach();
2395
2396 if show_completions {
2397 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2398 }
2399 } else {
2400 drop(context_menu);
2401 self.hide_context_menu(window, cx);
2402 }
2403 } else {
2404 drop(context_menu);
2405 }
2406
2407 hide_hover(self, cx);
2408
2409 if old_cursor_position.to_display_point(&display_map).row()
2410 != new_cursor_position.to_display_point(&display_map).row()
2411 {
2412 self.available_code_actions.take();
2413 }
2414 self.refresh_code_actions(window, cx);
2415 self.refresh_document_highlights(cx);
2416 self.refresh_selected_text_highlights(window, cx);
2417 refresh_matching_bracket_highlights(self, window, cx);
2418 self.update_visible_inline_completion(window, cx);
2419 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2420 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2421 if self.git_blame_inline_enabled {
2422 self.start_inline_blame_timer(window, cx);
2423 }
2424 }
2425
2426 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2427 cx.emit(EditorEvent::SelectionsChanged { local });
2428
2429 let selections = &self.selections.disjoint;
2430 if selections.len() == 1 {
2431 cx.emit(SearchEvent::ActiveMatchChanged)
2432 }
2433 if local {
2434 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2435 let inmemory_selections = selections
2436 .iter()
2437 .map(|s| {
2438 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2439 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2440 })
2441 .collect();
2442 self.update_restoration_data(cx, |data| {
2443 data.selections = inmemory_selections;
2444 });
2445
2446 if WorkspaceSettings::get(None, cx).restore_on_startup
2447 != RestoreOnStartupBehavior::None
2448 {
2449 if let Some(workspace_id) =
2450 self.workspace.as_ref().and_then(|workspace| workspace.1)
2451 {
2452 let snapshot = self.buffer().read(cx).snapshot(cx);
2453 let selections = selections.clone();
2454 let background_executor = cx.background_executor().clone();
2455 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2456 self.serialize_selections = cx.background_spawn(async move {
2457 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2458 let db_selections = selections
2459 .iter()
2460 .map(|selection| {
2461 (
2462 selection.start.to_offset(&snapshot),
2463 selection.end.to_offset(&snapshot),
2464 )
2465 })
2466 .collect();
2467
2468 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2469 .await
2470 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2471 .log_err();
2472 });
2473 }
2474 }
2475 }
2476 }
2477
2478 cx.notify();
2479 }
2480
2481 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2482 use text::ToOffset as _;
2483 use text::ToPoint as _;
2484
2485 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2486 return;
2487 }
2488
2489 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2490 return;
2491 };
2492
2493 let snapshot = singleton.read(cx).snapshot();
2494 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2495 let display_snapshot = display_map.snapshot(cx);
2496
2497 display_snapshot
2498 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2499 .map(|fold| {
2500 fold.range.start.text_anchor.to_point(&snapshot)
2501 ..fold.range.end.text_anchor.to_point(&snapshot)
2502 })
2503 .collect()
2504 });
2505 self.update_restoration_data(cx, |data| {
2506 data.folds = inmemory_folds;
2507 });
2508
2509 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2510 return;
2511 };
2512 let background_executor = cx.background_executor().clone();
2513 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2514 let db_folds = self.display_map.update(cx, |display_map, cx| {
2515 display_map
2516 .snapshot(cx)
2517 .folds_in_range(0..snapshot.len())
2518 .map(|fold| {
2519 (
2520 fold.range.start.text_anchor.to_offset(&snapshot),
2521 fold.range.end.text_anchor.to_offset(&snapshot),
2522 )
2523 })
2524 .collect()
2525 });
2526 self.serialize_folds = cx.background_spawn(async move {
2527 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2528 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2529 .await
2530 .with_context(|| {
2531 format!(
2532 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2533 )
2534 })
2535 .log_err();
2536 });
2537 }
2538
2539 pub fn sync_selections(
2540 &mut self,
2541 other: Entity<Editor>,
2542 cx: &mut Context<Self>,
2543 ) -> gpui::Subscription {
2544 let other_selections = other.read(cx).selections.disjoint.to_vec();
2545 self.selections.change_with(cx, |selections| {
2546 selections.select_anchors(other_selections);
2547 });
2548
2549 let other_subscription =
2550 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2551 EditorEvent::SelectionsChanged { local: true } => {
2552 let other_selections = other.read(cx).selections.disjoint.to_vec();
2553 if other_selections.is_empty() {
2554 return;
2555 }
2556 this.selections.change_with(cx, |selections| {
2557 selections.select_anchors(other_selections);
2558 });
2559 }
2560 _ => {}
2561 });
2562
2563 let this_subscription =
2564 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2565 EditorEvent::SelectionsChanged { local: true } => {
2566 let these_selections = this.selections.disjoint.to_vec();
2567 if these_selections.is_empty() {
2568 return;
2569 }
2570 other.update(cx, |other_editor, cx| {
2571 other_editor.selections.change_with(cx, |selections| {
2572 selections.select_anchors(these_selections);
2573 })
2574 });
2575 }
2576 _ => {}
2577 });
2578
2579 Subscription::join(other_subscription, this_subscription)
2580 }
2581
2582 pub fn change_selections<R>(
2583 &mut self,
2584 autoscroll: Option<Autoscroll>,
2585 window: &mut Window,
2586 cx: &mut Context<Self>,
2587 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2588 ) -> R {
2589 self.change_selections_inner(autoscroll, true, window, cx, change)
2590 }
2591
2592 fn change_selections_inner<R>(
2593 &mut self,
2594 autoscroll: Option<Autoscroll>,
2595 request_completions: bool,
2596 window: &mut Window,
2597 cx: &mut Context<Self>,
2598 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2599 ) -> R {
2600 let old_cursor_position = self.selections.newest_anchor().head();
2601 self.push_to_selection_history();
2602
2603 let (changed, result) = self.selections.change_with(cx, change);
2604
2605 if changed {
2606 if let Some(autoscroll) = autoscroll {
2607 self.request_autoscroll(autoscroll, cx);
2608 }
2609 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2610
2611 if self.should_open_signature_help_automatically(
2612 &old_cursor_position,
2613 self.signature_help_state.backspace_pressed(),
2614 cx,
2615 ) {
2616 self.show_signature_help(&ShowSignatureHelp, window, cx);
2617 }
2618 self.signature_help_state.set_backspace_pressed(false);
2619 }
2620
2621 result
2622 }
2623
2624 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2625 where
2626 I: IntoIterator<Item = (Range<S>, T)>,
2627 S: ToOffset,
2628 T: Into<Arc<str>>,
2629 {
2630 if self.read_only(cx) {
2631 return;
2632 }
2633
2634 self.buffer
2635 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2636 }
2637
2638 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2639 where
2640 I: IntoIterator<Item = (Range<S>, T)>,
2641 S: ToOffset,
2642 T: Into<Arc<str>>,
2643 {
2644 if self.read_only(cx) {
2645 return;
2646 }
2647
2648 self.buffer.update(cx, |buffer, cx| {
2649 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2650 });
2651 }
2652
2653 pub fn edit_with_block_indent<I, S, T>(
2654 &mut self,
2655 edits: I,
2656 original_indent_columns: Vec<Option<u32>>,
2657 cx: &mut Context<Self>,
2658 ) where
2659 I: IntoIterator<Item = (Range<S>, T)>,
2660 S: ToOffset,
2661 T: Into<Arc<str>>,
2662 {
2663 if self.read_only(cx) {
2664 return;
2665 }
2666
2667 self.buffer.update(cx, |buffer, cx| {
2668 buffer.edit(
2669 edits,
2670 Some(AutoindentMode::Block {
2671 original_indent_columns,
2672 }),
2673 cx,
2674 )
2675 });
2676 }
2677
2678 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2679 self.hide_context_menu(window, cx);
2680
2681 match phase {
2682 SelectPhase::Begin {
2683 position,
2684 add,
2685 click_count,
2686 } => self.begin_selection(position, add, click_count, window, cx),
2687 SelectPhase::BeginColumnar {
2688 position,
2689 goal_column,
2690 reset,
2691 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2692 SelectPhase::Extend {
2693 position,
2694 click_count,
2695 } => self.extend_selection(position, click_count, window, cx),
2696 SelectPhase::Update {
2697 position,
2698 goal_column,
2699 scroll_delta,
2700 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2701 SelectPhase::End => self.end_selection(window, cx),
2702 }
2703 }
2704
2705 fn extend_selection(
2706 &mut self,
2707 position: DisplayPoint,
2708 click_count: usize,
2709 window: &mut Window,
2710 cx: &mut Context<Self>,
2711 ) {
2712 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2713 let tail = self.selections.newest::<usize>(cx).tail();
2714 self.begin_selection(position, false, click_count, window, cx);
2715
2716 let position = position.to_offset(&display_map, Bias::Left);
2717 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2718
2719 let mut pending_selection = self
2720 .selections
2721 .pending_anchor()
2722 .expect("extend_selection not called with pending selection");
2723 if position >= tail {
2724 pending_selection.start = tail_anchor;
2725 } else {
2726 pending_selection.end = tail_anchor;
2727 pending_selection.reversed = true;
2728 }
2729
2730 let mut pending_mode = self.selections.pending_mode().unwrap();
2731 match &mut pending_mode {
2732 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2733 _ => {}
2734 }
2735
2736 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2737 s.set_pending(pending_selection, pending_mode)
2738 });
2739 }
2740
2741 fn begin_selection(
2742 &mut self,
2743 position: DisplayPoint,
2744 add: bool,
2745 click_count: usize,
2746 window: &mut Window,
2747 cx: &mut Context<Self>,
2748 ) {
2749 if !self.focus_handle.is_focused(window) {
2750 self.last_focused_descendant = None;
2751 window.focus(&self.focus_handle);
2752 }
2753
2754 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2755 let buffer = &display_map.buffer_snapshot;
2756 let newest_selection = self.selections.newest_anchor().clone();
2757 let position = display_map.clip_point(position, Bias::Left);
2758
2759 let start;
2760 let end;
2761 let mode;
2762 let mut auto_scroll;
2763 match click_count {
2764 1 => {
2765 start = buffer.anchor_before(position.to_point(&display_map));
2766 end = start;
2767 mode = SelectMode::Character;
2768 auto_scroll = true;
2769 }
2770 2 => {
2771 let range = movement::surrounding_word(&display_map, position);
2772 start = buffer.anchor_before(range.start.to_point(&display_map));
2773 end = buffer.anchor_before(range.end.to_point(&display_map));
2774 mode = SelectMode::Word(start..end);
2775 auto_scroll = true;
2776 }
2777 3 => {
2778 let position = display_map
2779 .clip_point(position, Bias::Left)
2780 .to_point(&display_map);
2781 let line_start = display_map.prev_line_boundary(position).0;
2782 let next_line_start = buffer.clip_point(
2783 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2784 Bias::Left,
2785 );
2786 start = buffer.anchor_before(line_start);
2787 end = buffer.anchor_before(next_line_start);
2788 mode = SelectMode::Line(start..end);
2789 auto_scroll = true;
2790 }
2791 _ => {
2792 start = buffer.anchor_before(0);
2793 end = buffer.anchor_before(buffer.len());
2794 mode = SelectMode::All;
2795 auto_scroll = false;
2796 }
2797 }
2798 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2799
2800 let point_to_delete: Option<usize> = {
2801 let selected_points: Vec<Selection<Point>> =
2802 self.selections.disjoint_in_range(start..end, cx);
2803
2804 if !add || click_count > 1 {
2805 None
2806 } else if !selected_points.is_empty() {
2807 Some(selected_points[0].id)
2808 } else {
2809 let clicked_point_already_selected =
2810 self.selections.disjoint.iter().find(|selection| {
2811 selection.start.to_point(buffer) == start.to_point(buffer)
2812 || selection.end.to_point(buffer) == end.to_point(buffer)
2813 });
2814
2815 clicked_point_already_selected.map(|selection| selection.id)
2816 }
2817 };
2818
2819 let selections_count = self.selections.count();
2820
2821 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2822 if let Some(point_to_delete) = point_to_delete {
2823 s.delete(point_to_delete);
2824
2825 if selections_count == 1 {
2826 s.set_pending_anchor_range(start..end, mode);
2827 }
2828 } else {
2829 if !add {
2830 s.clear_disjoint();
2831 } else if click_count > 1 {
2832 s.delete(newest_selection.id)
2833 }
2834
2835 s.set_pending_anchor_range(start..end, mode);
2836 }
2837 });
2838 }
2839
2840 fn begin_columnar_selection(
2841 &mut self,
2842 position: DisplayPoint,
2843 goal_column: u32,
2844 reset: bool,
2845 window: &mut Window,
2846 cx: &mut Context<Self>,
2847 ) {
2848 if !self.focus_handle.is_focused(window) {
2849 self.last_focused_descendant = None;
2850 window.focus(&self.focus_handle);
2851 }
2852
2853 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2854
2855 if reset {
2856 let pointer_position = display_map
2857 .buffer_snapshot
2858 .anchor_before(position.to_point(&display_map));
2859
2860 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2861 s.clear_disjoint();
2862 s.set_pending_anchor_range(
2863 pointer_position..pointer_position,
2864 SelectMode::Character,
2865 );
2866 });
2867 }
2868
2869 let tail = self.selections.newest::<Point>(cx).tail();
2870 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2871
2872 if !reset {
2873 self.select_columns(
2874 tail.to_display_point(&display_map),
2875 position,
2876 goal_column,
2877 &display_map,
2878 window,
2879 cx,
2880 );
2881 }
2882 }
2883
2884 fn update_selection(
2885 &mut self,
2886 position: DisplayPoint,
2887 goal_column: u32,
2888 scroll_delta: gpui::Point<f32>,
2889 window: &mut Window,
2890 cx: &mut Context<Self>,
2891 ) {
2892 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2893
2894 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2895 let tail = tail.to_display_point(&display_map);
2896 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2897 } else if let Some(mut pending) = self.selections.pending_anchor() {
2898 let buffer = self.buffer.read(cx).snapshot(cx);
2899 let head;
2900 let tail;
2901 let mode = self.selections.pending_mode().unwrap();
2902 match &mode {
2903 SelectMode::Character => {
2904 head = position.to_point(&display_map);
2905 tail = pending.tail().to_point(&buffer);
2906 }
2907 SelectMode::Word(original_range) => {
2908 let original_display_range = original_range.start.to_display_point(&display_map)
2909 ..original_range.end.to_display_point(&display_map);
2910 let original_buffer_range = original_display_range.start.to_point(&display_map)
2911 ..original_display_range.end.to_point(&display_map);
2912 if movement::is_inside_word(&display_map, position)
2913 || original_display_range.contains(&position)
2914 {
2915 let word_range = movement::surrounding_word(&display_map, position);
2916 if word_range.start < original_display_range.start {
2917 head = word_range.start.to_point(&display_map);
2918 } else {
2919 head = word_range.end.to_point(&display_map);
2920 }
2921 } else {
2922 head = position.to_point(&display_map);
2923 }
2924
2925 if head <= original_buffer_range.start {
2926 tail = original_buffer_range.end;
2927 } else {
2928 tail = original_buffer_range.start;
2929 }
2930 }
2931 SelectMode::Line(original_range) => {
2932 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2933
2934 let position = display_map
2935 .clip_point(position, Bias::Left)
2936 .to_point(&display_map);
2937 let line_start = display_map.prev_line_boundary(position).0;
2938 let next_line_start = buffer.clip_point(
2939 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2940 Bias::Left,
2941 );
2942
2943 if line_start < original_range.start {
2944 head = line_start
2945 } else {
2946 head = next_line_start
2947 }
2948
2949 if head <= original_range.start {
2950 tail = original_range.end;
2951 } else {
2952 tail = original_range.start;
2953 }
2954 }
2955 SelectMode::All => {
2956 return;
2957 }
2958 };
2959
2960 if head < tail {
2961 pending.start = buffer.anchor_before(head);
2962 pending.end = buffer.anchor_before(tail);
2963 pending.reversed = true;
2964 } else {
2965 pending.start = buffer.anchor_before(tail);
2966 pending.end = buffer.anchor_before(head);
2967 pending.reversed = false;
2968 }
2969
2970 self.change_selections(None, window, cx, |s| {
2971 s.set_pending(pending, mode);
2972 });
2973 } else {
2974 log::error!("update_selection dispatched with no pending selection");
2975 return;
2976 }
2977
2978 self.apply_scroll_delta(scroll_delta, window, cx);
2979 cx.notify();
2980 }
2981
2982 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2983 self.columnar_selection_tail.take();
2984 if self.selections.pending_anchor().is_some() {
2985 let selections = self.selections.all::<usize>(cx);
2986 self.change_selections(None, window, cx, |s| {
2987 s.select(selections);
2988 s.clear_pending();
2989 });
2990 }
2991 }
2992
2993 fn select_columns(
2994 &mut self,
2995 tail: DisplayPoint,
2996 head: DisplayPoint,
2997 goal_column: u32,
2998 display_map: &DisplaySnapshot,
2999 window: &mut Window,
3000 cx: &mut Context<Self>,
3001 ) {
3002 let start_row = cmp::min(tail.row(), head.row());
3003 let end_row = cmp::max(tail.row(), head.row());
3004 let start_column = cmp::min(tail.column(), goal_column);
3005 let end_column = cmp::max(tail.column(), goal_column);
3006 let reversed = start_column < tail.column();
3007
3008 let selection_ranges = (start_row.0..=end_row.0)
3009 .map(DisplayRow)
3010 .filter_map(|row| {
3011 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3012 let start = display_map
3013 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3014 .to_point(display_map);
3015 let end = display_map
3016 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3017 .to_point(display_map);
3018 if reversed {
3019 Some(end..start)
3020 } else {
3021 Some(start..end)
3022 }
3023 } else {
3024 None
3025 }
3026 })
3027 .collect::<Vec<_>>();
3028
3029 self.change_selections(None, window, cx, |s| {
3030 s.select_ranges(selection_ranges);
3031 });
3032 cx.notify();
3033 }
3034
3035 pub fn has_pending_nonempty_selection(&self) -> bool {
3036 let pending_nonempty_selection = match self.selections.pending_anchor() {
3037 Some(Selection { start, end, .. }) => start != end,
3038 None => false,
3039 };
3040
3041 pending_nonempty_selection
3042 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3043 }
3044
3045 pub fn has_pending_selection(&self) -> bool {
3046 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3047 }
3048
3049 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3050 self.selection_mark_mode = false;
3051
3052 if self.clear_expanded_diff_hunks(cx) {
3053 cx.notify();
3054 return;
3055 }
3056 if self.dismiss_menus_and_popups(true, window, cx) {
3057 return;
3058 }
3059
3060 if self.mode.is_full()
3061 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3062 {
3063 return;
3064 }
3065
3066 cx.propagate();
3067 }
3068
3069 pub fn dismiss_menus_and_popups(
3070 &mut self,
3071 is_user_requested: bool,
3072 window: &mut Window,
3073 cx: &mut Context<Self>,
3074 ) -> bool {
3075 if self.take_rename(false, window, cx).is_some() {
3076 return true;
3077 }
3078
3079 if hide_hover(self, cx) {
3080 return true;
3081 }
3082
3083 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3084 return true;
3085 }
3086
3087 if self.hide_context_menu(window, cx).is_some() {
3088 return true;
3089 }
3090
3091 if self.mouse_context_menu.take().is_some() {
3092 return true;
3093 }
3094
3095 if is_user_requested && self.discard_inline_completion(true, cx) {
3096 return true;
3097 }
3098
3099 if self.snippet_stack.pop().is_some() {
3100 return true;
3101 }
3102
3103 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3104 self.dismiss_diagnostics(cx);
3105 return true;
3106 }
3107
3108 false
3109 }
3110
3111 fn linked_editing_ranges_for(
3112 &self,
3113 selection: Range<text::Anchor>,
3114 cx: &App,
3115 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3116 if self.linked_edit_ranges.is_empty() {
3117 return None;
3118 }
3119 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3120 selection.end.buffer_id.and_then(|end_buffer_id| {
3121 if selection.start.buffer_id != Some(end_buffer_id) {
3122 return None;
3123 }
3124 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3125 let snapshot = buffer.read(cx).snapshot();
3126 self.linked_edit_ranges
3127 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3128 .map(|ranges| (ranges, snapshot, buffer))
3129 })?;
3130 use text::ToOffset as TO;
3131 // find offset from the start of current range to current cursor position
3132 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3133
3134 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3135 let start_difference = start_offset - start_byte_offset;
3136 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3137 let end_difference = end_offset - start_byte_offset;
3138 // Current range has associated linked ranges.
3139 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3140 for range in linked_ranges.iter() {
3141 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3142 let end_offset = start_offset + end_difference;
3143 let start_offset = start_offset + start_difference;
3144 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3145 continue;
3146 }
3147 if self.selections.disjoint_anchor_ranges().any(|s| {
3148 if s.start.buffer_id != selection.start.buffer_id
3149 || s.end.buffer_id != selection.end.buffer_id
3150 {
3151 return false;
3152 }
3153 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3154 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3155 }) {
3156 continue;
3157 }
3158 let start = buffer_snapshot.anchor_after(start_offset);
3159 let end = buffer_snapshot.anchor_after(end_offset);
3160 linked_edits
3161 .entry(buffer.clone())
3162 .or_default()
3163 .push(start..end);
3164 }
3165 Some(linked_edits)
3166 }
3167
3168 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3169 let text: Arc<str> = text.into();
3170
3171 if self.read_only(cx) {
3172 return;
3173 }
3174
3175 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3176
3177 let selections = self.selections.all_adjusted(cx);
3178 let mut bracket_inserted = false;
3179 let mut edits = Vec::new();
3180 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3181 let mut new_selections = Vec::with_capacity(selections.len());
3182 let mut new_autoclose_regions = Vec::new();
3183 let snapshot = self.buffer.read(cx).read(cx);
3184 let mut clear_linked_edit_ranges = false;
3185
3186 for (selection, autoclose_region) in
3187 self.selections_with_autoclose_regions(selections, &snapshot)
3188 {
3189 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3190 // Determine if the inserted text matches the opening or closing
3191 // bracket of any of this language's bracket pairs.
3192 let mut bracket_pair = None;
3193 let mut is_bracket_pair_start = false;
3194 let mut is_bracket_pair_end = false;
3195 if !text.is_empty() {
3196 let mut bracket_pair_matching_end = None;
3197 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3198 // and they are removing the character that triggered IME popup.
3199 for (pair, enabled) in scope.brackets() {
3200 if !pair.close && !pair.surround {
3201 continue;
3202 }
3203
3204 if enabled && pair.start.ends_with(text.as_ref()) {
3205 let prefix_len = pair.start.len() - text.len();
3206 let preceding_text_matches_prefix = prefix_len == 0
3207 || (selection.start.column >= (prefix_len as u32)
3208 && snapshot.contains_str_at(
3209 Point::new(
3210 selection.start.row,
3211 selection.start.column - (prefix_len as u32),
3212 ),
3213 &pair.start[..prefix_len],
3214 ));
3215 if preceding_text_matches_prefix {
3216 bracket_pair = Some(pair.clone());
3217 is_bracket_pair_start = true;
3218 break;
3219 }
3220 }
3221 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3222 {
3223 // take first bracket pair matching end, but don't break in case a later bracket
3224 // pair matches start
3225 bracket_pair_matching_end = Some(pair.clone());
3226 }
3227 }
3228 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3229 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3230 is_bracket_pair_end = true;
3231 }
3232 }
3233
3234 if let Some(bracket_pair) = bracket_pair {
3235 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3236 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3237 let auto_surround =
3238 self.use_auto_surround && snapshot_settings.use_auto_surround;
3239 if selection.is_empty() {
3240 if is_bracket_pair_start {
3241 // If the inserted text is a suffix of an opening bracket and the
3242 // selection is preceded by the rest of the opening bracket, then
3243 // insert the closing bracket.
3244 let following_text_allows_autoclose = snapshot
3245 .chars_at(selection.start)
3246 .next()
3247 .map_or(true, |c| scope.should_autoclose_before(c));
3248
3249 let preceding_text_allows_autoclose = selection.start.column == 0
3250 || snapshot.reversed_chars_at(selection.start).next().map_or(
3251 true,
3252 |c| {
3253 bracket_pair.start != bracket_pair.end
3254 || !snapshot
3255 .char_classifier_at(selection.start)
3256 .is_word(c)
3257 },
3258 );
3259
3260 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3261 && bracket_pair.start.len() == 1
3262 {
3263 let target = bracket_pair.start.chars().next().unwrap();
3264 let current_line_count = snapshot
3265 .reversed_chars_at(selection.start)
3266 .take_while(|&c| c != '\n')
3267 .filter(|&c| c == target)
3268 .count();
3269 current_line_count % 2 == 1
3270 } else {
3271 false
3272 };
3273
3274 if autoclose
3275 && bracket_pair.close
3276 && following_text_allows_autoclose
3277 && preceding_text_allows_autoclose
3278 && !is_closing_quote
3279 {
3280 let anchor = snapshot.anchor_before(selection.end);
3281 new_selections.push((selection.map(|_| anchor), text.len()));
3282 new_autoclose_regions.push((
3283 anchor,
3284 text.len(),
3285 selection.id,
3286 bracket_pair.clone(),
3287 ));
3288 edits.push((
3289 selection.range(),
3290 format!("{}{}", text, bracket_pair.end).into(),
3291 ));
3292 bracket_inserted = true;
3293 continue;
3294 }
3295 }
3296
3297 if let Some(region) = autoclose_region {
3298 // If the selection is followed by an auto-inserted closing bracket,
3299 // then don't insert that closing bracket again; just move the selection
3300 // past the closing bracket.
3301 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3302 && text.as_ref() == region.pair.end.as_str();
3303 if should_skip {
3304 let anchor = snapshot.anchor_after(selection.end);
3305 new_selections
3306 .push((selection.map(|_| anchor), region.pair.end.len()));
3307 continue;
3308 }
3309 }
3310
3311 let always_treat_brackets_as_autoclosed = snapshot
3312 .language_settings_at(selection.start, cx)
3313 .always_treat_brackets_as_autoclosed;
3314 if always_treat_brackets_as_autoclosed
3315 && is_bracket_pair_end
3316 && snapshot.contains_str_at(selection.end, text.as_ref())
3317 {
3318 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3319 // and the inserted text is a closing bracket and the selection is followed
3320 // by the closing bracket then move the selection past the closing bracket.
3321 let anchor = snapshot.anchor_after(selection.end);
3322 new_selections.push((selection.map(|_| anchor), text.len()));
3323 continue;
3324 }
3325 }
3326 // If an opening bracket is 1 character long and is typed while
3327 // text is selected, then surround that text with the bracket pair.
3328 else if auto_surround
3329 && bracket_pair.surround
3330 && is_bracket_pair_start
3331 && bracket_pair.start.chars().count() == 1
3332 {
3333 edits.push((selection.start..selection.start, text.clone()));
3334 edits.push((
3335 selection.end..selection.end,
3336 bracket_pair.end.as_str().into(),
3337 ));
3338 bracket_inserted = true;
3339 new_selections.push((
3340 Selection {
3341 id: selection.id,
3342 start: snapshot.anchor_after(selection.start),
3343 end: snapshot.anchor_before(selection.end),
3344 reversed: selection.reversed,
3345 goal: selection.goal,
3346 },
3347 0,
3348 ));
3349 continue;
3350 }
3351 }
3352 }
3353
3354 if self.auto_replace_emoji_shortcode
3355 && selection.is_empty()
3356 && text.as_ref().ends_with(':')
3357 {
3358 if let Some(possible_emoji_short_code) =
3359 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3360 {
3361 if !possible_emoji_short_code.is_empty() {
3362 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3363 let emoji_shortcode_start = Point::new(
3364 selection.start.row,
3365 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3366 );
3367
3368 // Remove shortcode from buffer
3369 edits.push((
3370 emoji_shortcode_start..selection.start,
3371 "".to_string().into(),
3372 ));
3373 new_selections.push((
3374 Selection {
3375 id: selection.id,
3376 start: snapshot.anchor_after(emoji_shortcode_start),
3377 end: snapshot.anchor_before(selection.start),
3378 reversed: selection.reversed,
3379 goal: selection.goal,
3380 },
3381 0,
3382 ));
3383
3384 // Insert emoji
3385 let selection_start_anchor = snapshot.anchor_after(selection.start);
3386 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3387 edits.push((selection.start..selection.end, emoji.to_string().into()));
3388
3389 continue;
3390 }
3391 }
3392 }
3393 }
3394
3395 // If not handling any auto-close operation, then just replace the selected
3396 // text with the given input and move the selection to the end of the
3397 // newly inserted text.
3398 let anchor = snapshot.anchor_after(selection.end);
3399 if !self.linked_edit_ranges.is_empty() {
3400 let start_anchor = snapshot.anchor_before(selection.start);
3401
3402 let is_word_char = text.chars().next().map_or(true, |char| {
3403 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3404 classifier.is_word(char)
3405 });
3406
3407 if is_word_char {
3408 if let Some(ranges) = self
3409 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3410 {
3411 for (buffer, edits) in ranges {
3412 linked_edits
3413 .entry(buffer.clone())
3414 .or_default()
3415 .extend(edits.into_iter().map(|range| (range, text.clone())));
3416 }
3417 }
3418 } else {
3419 clear_linked_edit_ranges = true;
3420 }
3421 }
3422
3423 new_selections.push((selection.map(|_| anchor), 0));
3424 edits.push((selection.start..selection.end, text.clone()));
3425 }
3426
3427 drop(snapshot);
3428
3429 self.transact(window, cx, |this, window, cx| {
3430 if clear_linked_edit_ranges {
3431 this.linked_edit_ranges.clear();
3432 }
3433 let initial_buffer_versions =
3434 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3435
3436 this.buffer.update(cx, |buffer, cx| {
3437 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3438 });
3439 for (buffer, edits) in linked_edits {
3440 buffer.update(cx, |buffer, cx| {
3441 let snapshot = buffer.snapshot();
3442 let edits = edits
3443 .into_iter()
3444 .map(|(range, text)| {
3445 use text::ToPoint as TP;
3446 let end_point = TP::to_point(&range.end, &snapshot);
3447 let start_point = TP::to_point(&range.start, &snapshot);
3448 (start_point..end_point, text)
3449 })
3450 .sorted_by_key(|(range, _)| range.start);
3451 buffer.edit(edits, None, cx);
3452 })
3453 }
3454 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3455 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3456 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3457 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3458 .zip(new_selection_deltas)
3459 .map(|(selection, delta)| Selection {
3460 id: selection.id,
3461 start: selection.start + delta,
3462 end: selection.end + delta,
3463 reversed: selection.reversed,
3464 goal: SelectionGoal::None,
3465 })
3466 .collect::<Vec<_>>();
3467
3468 let mut i = 0;
3469 for (position, delta, selection_id, pair) in new_autoclose_regions {
3470 let position = position.to_offset(&map.buffer_snapshot) + delta;
3471 let start = map.buffer_snapshot.anchor_before(position);
3472 let end = map.buffer_snapshot.anchor_after(position);
3473 while let Some(existing_state) = this.autoclose_regions.get(i) {
3474 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3475 Ordering::Less => i += 1,
3476 Ordering::Greater => break,
3477 Ordering::Equal => {
3478 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3479 Ordering::Less => i += 1,
3480 Ordering::Equal => break,
3481 Ordering::Greater => break,
3482 }
3483 }
3484 }
3485 }
3486 this.autoclose_regions.insert(
3487 i,
3488 AutocloseRegion {
3489 selection_id,
3490 range: start..end,
3491 pair,
3492 },
3493 );
3494 }
3495
3496 let had_active_inline_completion = this.has_active_inline_completion();
3497 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3498 s.select(new_selections)
3499 });
3500
3501 if !bracket_inserted {
3502 if let Some(on_type_format_task) =
3503 this.trigger_on_type_formatting(text.to_string(), window, cx)
3504 {
3505 on_type_format_task.detach_and_log_err(cx);
3506 }
3507 }
3508
3509 let editor_settings = EditorSettings::get_global(cx);
3510 if bracket_inserted
3511 && (editor_settings.auto_signature_help
3512 || editor_settings.show_signature_help_after_edits)
3513 {
3514 this.show_signature_help(&ShowSignatureHelp, window, cx);
3515 }
3516
3517 let trigger_in_words =
3518 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3519 if this.hard_wrap.is_some() {
3520 let latest: Range<Point> = this.selections.newest(cx).range();
3521 if latest.is_empty()
3522 && this
3523 .buffer()
3524 .read(cx)
3525 .snapshot(cx)
3526 .line_len(MultiBufferRow(latest.start.row))
3527 == latest.start.column
3528 {
3529 this.rewrap_impl(
3530 RewrapOptions {
3531 override_language_settings: true,
3532 preserve_existing_whitespace: true,
3533 },
3534 cx,
3535 )
3536 }
3537 }
3538 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3539 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3540 this.refresh_inline_completion(true, false, window, cx);
3541 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3542 });
3543 }
3544
3545 fn find_possible_emoji_shortcode_at_position(
3546 snapshot: &MultiBufferSnapshot,
3547 position: Point,
3548 ) -> Option<String> {
3549 let mut chars = Vec::new();
3550 let mut found_colon = false;
3551 for char in snapshot.reversed_chars_at(position).take(100) {
3552 // Found a possible emoji shortcode in the middle of the buffer
3553 if found_colon {
3554 if char.is_whitespace() {
3555 chars.reverse();
3556 return Some(chars.iter().collect());
3557 }
3558 // If the previous character is not a whitespace, we are in the middle of a word
3559 // and we only want to complete the shortcode if the word is made up of other emojis
3560 let mut containing_word = String::new();
3561 for ch in snapshot
3562 .reversed_chars_at(position)
3563 .skip(chars.len() + 1)
3564 .take(100)
3565 {
3566 if ch.is_whitespace() {
3567 break;
3568 }
3569 containing_word.push(ch);
3570 }
3571 let containing_word = containing_word.chars().rev().collect::<String>();
3572 if util::word_consists_of_emojis(containing_word.as_str()) {
3573 chars.reverse();
3574 return Some(chars.iter().collect());
3575 }
3576 }
3577
3578 if char.is_whitespace() || !char.is_ascii() {
3579 return None;
3580 }
3581 if char == ':' {
3582 found_colon = true;
3583 } else {
3584 chars.push(char);
3585 }
3586 }
3587 // Found a possible emoji shortcode at the beginning of the buffer
3588 chars.reverse();
3589 Some(chars.iter().collect())
3590 }
3591
3592 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3593 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3594 self.transact(window, cx, |this, window, cx| {
3595 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3596 let selections = this.selections.all::<usize>(cx);
3597 let multi_buffer = this.buffer.read(cx);
3598 let buffer = multi_buffer.snapshot(cx);
3599 selections
3600 .iter()
3601 .map(|selection| {
3602 let start_point = selection.start.to_point(&buffer);
3603 let mut indent =
3604 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3605 indent.len = cmp::min(indent.len, start_point.column);
3606 let start = selection.start;
3607 let end = selection.end;
3608 let selection_is_empty = start == end;
3609 let language_scope = buffer.language_scope_at(start);
3610 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3611 &language_scope
3612 {
3613 let insert_extra_newline =
3614 insert_extra_newline_brackets(&buffer, start..end, language)
3615 || insert_extra_newline_tree_sitter(&buffer, start..end);
3616
3617 // Comment extension on newline is allowed only for cursor selections
3618 let comment_delimiter = maybe!({
3619 if !selection_is_empty {
3620 return None;
3621 }
3622
3623 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3624 return None;
3625 }
3626
3627 let delimiters = language.line_comment_prefixes();
3628 let max_len_of_delimiter =
3629 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3630 let (snapshot, range) =
3631 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3632
3633 let mut index_of_first_non_whitespace = 0;
3634 let comment_candidate = snapshot
3635 .chars_for_range(range)
3636 .skip_while(|c| {
3637 let should_skip = c.is_whitespace();
3638 if should_skip {
3639 index_of_first_non_whitespace += 1;
3640 }
3641 should_skip
3642 })
3643 .take(max_len_of_delimiter)
3644 .collect::<String>();
3645 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3646 comment_candidate.starts_with(comment_prefix.as_ref())
3647 })?;
3648 let cursor_is_placed_after_comment_marker =
3649 index_of_first_non_whitespace + comment_prefix.len()
3650 <= start_point.column as usize;
3651 if cursor_is_placed_after_comment_marker {
3652 Some(comment_prefix.clone())
3653 } else {
3654 None
3655 }
3656 });
3657 (comment_delimiter, insert_extra_newline)
3658 } else {
3659 (None, false)
3660 };
3661
3662 let capacity_for_delimiter = comment_delimiter
3663 .as_deref()
3664 .map(str::len)
3665 .unwrap_or_default();
3666 let mut new_text =
3667 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3668 new_text.push('\n');
3669 new_text.extend(indent.chars());
3670 if let Some(delimiter) = &comment_delimiter {
3671 new_text.push_str(delimiter);
3672 }
3673 if insert_extra_newline {
3674 new_text = new_text.repeat(2);
3675 }
3676
3677 let anchor = buffer.anchor_after(end);
3678 let new_selection = selection.map(|_| anchor);
3679 (
3680 (start..end, new_text),
3681 (insert_extra_newline, new_selection),
3682 )
3683 })
3684 .unzip()
3685 };
3686
3687 this.edit_with_autoindent(edits, cx);
3688 let buffer = this.buffer.read(cx).snapshot(cx);
3689 let new_selections = selection_fixup_info
3690 .into_iter()
3691 .map(|(extra_newline_inserted, new_selection)| {
3692 let mut cursor = new_selection.end.to_point(&buffer);
3693 if extra_newline_inserted {
3694 cursor.row -= 1;
3695 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3696 }
3697 new_selection.map(|_| cursor)
3698 })
3699 .collect();
3700
3701 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3702 s.select(new_selections)
3703 });
3704 this.refresh_inline_completion(true, false, window, cx);
3705 });
3706 }
3707
3708 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3709 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3710
3711 let buffer = self.buffer.read(cx);
3712 let snapshot = buffer.snapshot(cx);
3713
3714 let mut edits = Vec::new();
3715 let mut rows = Vec::new();
3716
3717 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3718 let cursor = selection.head();
3719 let row = cursor.row;
3720
3721 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3722
3723 let newline = "\n".to_string();
3724 edits.push((start_of_line..start_of_line, newline));
3725
3726 rows.push(row + rows_inserted as u32);
3727 }
3728
3729 self.transact(window, cx, |editor, window, cx| {
3730 editor.edit(edits, cx);
3731
3732 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3733 let mut index = 0;
3734 s.move_cursors_with(|map, _, _| {
3735 let row = rows[index];
3736 index += 1;
3737
3738 let point = Point::new(row, 0);
3739 let boundary = map.next_line_boundary(point).1;
3740 let clipped = map.clip_point(boundary, Bias::Left);
3741
3742 (clipped, SelectionGoal::None)
3743 });
3744 });
3745
3746 let mut indent_edits = Vec::new();
3747 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3748 for row in rows {
3749 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3750 for (row, indent) in indents {
3751 if indent.len == 0 {
3752 continue;
3753 }
3754
3755 let text = match indent.kind {
3756 IndentKind::Space => " ".repeat(indent.len as usize),
3757 IndentKind::Tab => "\t".repeat(indent.len as usize),
3758 };
3759 let point = Point::new(row.0, 0);
3760 indent_edits.push((point..point, text));
3761 }
3762 }
3763 editor.edit(indent_edits, cx);
3764 });
3765 }
3766
3767 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3768 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3769
3770 let buffer = self.buffer.read(cx);
3771 let snapshot = buffer.snapshot(cx);
3772
3773 let mut edits = Vec::new();
3774 let mut rows = Vec::new();
3775 let mut rows_inserted = 0;
3776
3777 for selection in self.selections.all_adjusted(cx) {
3778 let cursor = selection.head();
3779 let row = cursor.row;
3780
3781 let point = Point::new(row + 1, 0);
3782 let start_of_line = snapshot.clip_point(point, Bias::Left);
3783
3784 let newline = "\n".to_string();
3785 edits.push((start_of_line..start_of_line, newline));
3786
3787 rows_inserted += 1;
3788 rows.push(row + rows_inserted);
3789 }
3790
3791 self.transact(window, cx, |editor, window, cx| {
3792 editor.edit(edits, cx);
3793
3794 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3795 let mut index = 0;
3796 s.move_cursors_with(|map, _, _| {
3797 let row = rows[index];
3798 index += 1;
3799
3800 let point = Point::new(row, 0);
3801 let boundary = map.next_line_boundary(point).1;
3802 let clipped = map.clip_point(boundary, Bias::Left);
3803
3804 (clipped, SelectionGoal::None)
3805 });
3806 });
3807
3808 let mut indent_edits = Vec::new();
3809 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3810 for row in rows {
3811 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3812 for (row, indent) in indents {
3813 if indent.len == 0 {
3814 continue;
3815 }
3816
3817 let text = match indent.kind {
3818 IndentKind::Space => " ".repeat(indent.len as usize),
3819 IndentKind::Tab => "\t".repeat(indent.len as usize),
3820 };
3821 let point = Point::new(row.0, 0);
3822 indent_edits.push((point..point, text));
3823 }
3824 }
3825 editor.edit(indent_edits, cx);
3826 });
3827 }
3828
3829 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3830 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3831 original_indent_columns: Vec::new(),
3832 });
3833 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3834 }
3835
3836 fn insert_with_autoindent_mode(
3837 &mut self,
3838 text: &str,
3839 autoindent_mode: Option<AutoindentMode>,
3840 window: &mut Window,
3841 cx: &mut Context<Self>,
3842 ) {
3843 if self.read_only(cx) {
3844 return;
3845 }
3846
3847 let text: Arc<str> = text.into();
3848 self.transact(window, cx, |this, window, cx| {
3849 let old_selections = this.selections.all_adjusted(cx);
3850 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3851 let anchors = {
3852 let snapshot = buffer.read(cx);
3853 old_selections
3854 .iter()
3855 .map(|s| {
3856 let anchor = snapshot.anchor_after(s.head());
3857 s.map(|_| anchor)
3858 })
3859 .collect::<Vec<_>>()
3860 };
3861 buffer.edit(
3862 old_selections
3863 .iter()
3864 .map(|s| (s.start..s.end, text.clone())),
3865 autoindent_mode,
3866 cx,
3867 );
3868 anchors
3869 });
3870
3871 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3872 s.select_anchors(selection_anchors);
3873 });
3874
3875 cx.notify();
3876 });
3877 }
3878
3879 fn trigger_completion_on_input(
3880 &mut self,
3881 text: &str,
3882 trigger_in_words: bool,
3883 window: &mut Window,
3884 cx: &mut Context<Self>,
3885 ) {
3886 let ignore_completion_provider = self
3887 .context_menu
3888 .borrow()
3889 .as_ref()
3890 .map(|menu| match menu {
3891 CodeContextMenu::Completions(completions_menu) => {
3892 completions_menu.ignore_completion_provider
3893 }
3894 CodeContextMenu::CodeActions(_) => false,
3895 })
3896 .unwrap_or(false);
3897
3898 if ignore_completion_provider {
3899 self.show_word_completions(&ShowWordCompletions, window, cx);
3900 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3901 self.show_completions(
3902 &ShowCompletions {
3903 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3904 },
3905 window,
3906 cx,
3907 );
3908 } else {
3909 self.hide_context_menu(window, cx);
3910 }
3911 }
3912
3913 fn is_completion_trigger(
3914 &self,
3915 text: &str,
3916 trigger_in_words: bool,
3917 cx: &mut Context<Self>,
3918 ) -> bool {
3919 let position = self.selections.newest_anchor().head();
3920 let multibuffer = self.buffer.read(cx);
3921 let Some(buffer) = position
3922 .buffer_id
3923 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3924 else {
3925 return false;
3926 };
3927
3928 if let Some(completion_provider) = &self.completion_provider {
3929 completion_provider.is_completion_trigger(
3930 &buffer,
3931 position.text_anchor,
3932 text,
3933 trigger_in_words,
3934 cx,
3935 )
3936 } else {
3937 false
3938 }
3939 }
3940
3941 /// If any empty selections is touching the start of its innermost containing autoclose
3942 /// region, expand it to select the brackets.
3943 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3944 let selections = self.selections.all::<usize>(cx);
3945 let buffer = self.buffer.read(cx).read(cx);
3946 let new_selections = self
3947 .selections_with_autoclose_regions(selections, &buffer)
3948 .map(|(mut selection, region)| {
3949 if !selection.is_empty() {
3950 return selection;
3951 }
3952
3953 if let Some(region) = region {
3954 let mut range = region.range.to_offset(&buffer);
3955 if selection.start == range.start && range.start >= region.pair.start.len() {
3956 range.start -= region.pair.start.len();
3957 if buffer.contains_str_at(range.start, ®ion.pair.start)
3958 && buffer.contains_str_at(range.end, ®ion.pair.end)
3959 {
3960 range.end += region.pair.end.len();
3961 selection.start = range.start;
3962 selection.end = range.end;
3963
3964 return selection;
3965 }
3966 }
3967 }
3968
3969 let always_treat_brackets_as_autoclosed = buffer
3970 .language_settings_at(selection.start, cx)
3971 .always_treat_brackets_as_autoclosed;
3972
3973 if !always_treat_brackets_as_autoclosed {
3974 return selection;
3975 }
3976
3977 if let Some(scope) = buffer.language_scope_at(selection.start) {
3978 for (pair, enabled) in scope.brackets() {
3979 if !enabled || !pair.close {
3980 continue;
3981 }
3982
3983 if buffer.contains_str_at(selection.start, &pair.end) {
3984 let pair_start_len = pair.start.len();
3985 if buffer.contains_str_at(
3986 selection.start.saturating_sub(pair_start_len),
3987 &pair.start,
3988 ) {
3989 selection.start -= pair_start_len;
3990 selection.end += pair.end.len();
3991
3992 return selection;
3993 }
3994 }
3995 }
3996 }
3997
3998 selection
3999 })
4000 .collect();
4001
4002 drop(buffer);
4003 self.change_selections(None, window, cx, |selections| {
4004 selections.select(new_selections)
4005 });
4006 }
4007
4008 /// Iterate the given selections, and for each one, find the smallest surrounding
4009 /// autoclose region. This uses the ordering of the selections and the autoclose
4010 /// regions to avoid repeated comparisons.
4011 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4012 &'a self,
4013 selections: impl IntoIterator<Item = Selection<D>>,
4014 buffer: &'a MultiBufferSnapshot,
4015 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4016 let mut i = 0;
4017 let mut regions = self.autoclose_regions.as_slice();
4018 selections.into_iter().map(move |selection| {
4019 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4020
4021 let mut enclosing = None;
4022 while let Some(pair_state) = regions.get(i) {
4023 if pair_state.range.end.to_offset(buffer) < range.start {
4024 regions = ®ions[i + 1..];
4025 i = 0;
4026 } else if pair_state.range.start.to_offset(buffer) > range.end {
4027 break;
4028 } else {
4029 if pair_state.selection_id == selection.id {
4030 enclosing = Some(pair_state);
4031 }
4032 i += 1;
4033 }
4034 }
4035
4036 (selection, enclosing)
4037 })
4038 }
4039
4040 /// Remove any autoclose regions that no longer contain their selection.
4041 fn invalidate_autoclose_regions(
4042 &mut self,
4043 mut selections: &[Selection<Anchor>],
4044 buffer: &MultiBufferSnapshot,
4045 ) {
4046 self.autoclose_regions.retain(|state| {
4047 let mut i = 0;
4048 while let Some(selection) = selections.get(i) {
4049 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4050 selections = &selections[1..];
4051 continue;
4052 }
4053 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4054 break;
4055 }
4056 if selection.id == state.selection_id {
4057 return true;
4058 } else {
4059 i += 1;
4060 }
4061 }
4062 false
4063 });
4064 }
4065
4066 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4067 let offset = position.to_offset(buffer);
4068 let (word_range, kind) = buffer.surrounding_word(offset, true);
4069 if offset > word_range.start && kind == Some(CharKind::Word) {
4070 Some(
4071 buffer
4072 .text_for_range(word_range.start..offset)
4073 .collect::<String>(),
4074 )
4075 } else {
4076 None
4077 }
4078 }
4079
4080 pub fn toggle_inlay_hints(
4081 &mut self,
4082 _: &ToggleInlayHints,
4083 _: &mut Window,
4084 cx: &mut Context<Self>,
4085 ) {
4086 self.refresh_inlay_hints(
4087 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4088 cx,
4089 );
4090 }
4091
4092 pub fn inlay_hints_enabled(&self) -> bool {
4093 self.inlay_hint_cache.enabled
4094 }
4095
4096 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4097 if self.semantics_provider.is_none() || !self.mode.is_full() {
4098 return;
4099 }
4100
4101 let reason_description = reason.description();
4102 let ignore_debounce = matches!(
4103 reason,
4104 InlayHintRefreshReason::SettingsChange(_)
4105 | InlayHintRefreshReason::Toggle(_)
4106 | InlayHintRefreshReason::ExcerptsRemoved(_)
4107 | InlayHintRefreshReason::ModifiersChanged(_)
4108 );
4109 let (invalidate_cache, required_languages) = match reason {
4110 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4111 match self.inlay_hint_cache.modifiers_override(enabled) {
4112 Some(enabled) => {
4113 if enabled {
4114 (InvalidationStrategy::RefreshRequested, None)
4115 } else {
4116 self.splice_inlays(
4117 &self
4118 .visible_inlay_hints(cx)
4119 .iter()
4120 .map(|inlay| inlay.id)
4121 .collect::<Vec<InlayId>>(),
4122 Vec::new(),
4123 cx,
4124 );
4125 return;
4126 }
4127 }
4128 None => return,
4129 }
4130 }
4131 InlayHintRefreshReason::Toggle(enabled) => {
4132 if self.inlay_hint_cache.toggle(enabled) {
4133 if enabled {
4134 (InvalidationStrategy::RefreshRequested, None)
4135 } else {
4136 self.splice_inlays(
4137 &self
4138 .visible_inlay_hints(cx)
4139 .iter()
4140 .map(|inlay| inlay.id)
4141 .collect::<Vec<InlayId>>(),
4142 Vec::new(),
4143 cx,
4144 );
4145 return;
4146 }
4147 } else {
4148 return;
4149 }
4150 }
4151 InlayHintRefreshReason::SettingsChange(new_settings) => {
4152 match self.inlay_hint_cache.update_settings(
4153 &self.buffer,
4154 new_settings,
4155 self.visible_inlay_hints(cx),
4156 cx,
4157 ) {
4158 ControlFlow::Break(Some(InlaySplice {
4159 to_remove,
4160 to_insert,
4161 })) => {
4162 self.splice_inlays(&to_remove, to_insert, cx);
4163 return;
4164 }
4165 ControlFlow::Break(None) => return,
4166 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4167 }
4168 }
4169 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4170 if let Some(InlaySplice {
4171 to_remove,
4172 to_insert,
4173 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4174 {
4175 self.splice_inlays(&to_remove, to_insert, cx);
4176 }
4177 self.display_map.update(cx, |display_map, _| {
4178 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4179 });
4180 return;
4181 }
4182 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4183 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4184 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4185 }
4186 InlayHintRefreshReason::RefreshRequested => {
4187 (InvalidationStrategy::RefreshRequested, None)
4188 }
4189 };
4190
4191 if let Some(InlaySplice {
4192 to_remove,
4193 to_insert,
4194 }) = self.inlay_hint_cache.spawn_hint_refresh(
4195 reason_description,
4196 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4197 invalidate_cache,
4198 ignore_debounce,
4199 cx,
4200 ) {
4201 self.splice_inlays(&to_remove, to_insert, cx);
4202 }
4203 }
4204
4205 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4206 self.display_map
4207 .read(cx)
4208 .current_inlays()
4209 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4210 .cloned()
4211 .collect()
4212 }
4213
4214 pub fn excerpts_for_inlay_hints_query(
4215 &self,
4216 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4217 cx: &mut Context<Editor>,
4218 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4219 let Some(project) = self.project.as_ref() else {
4220 return HashMap::default();
4221 };
4222 let project = project.read(cx);
4223 let multi_buffer = self.buffer().read(cx);
4224 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4225 let multi_buffer_visible_start = self
4226 .scroll_manager
4227 .anchor()
4228 .anchor
4229 .to_point(&multi_buffer_snapshot);
4230 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4231 multi_buffer_visible_start
4232 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4233 Bias::Left,
4234 );
4235 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4236 multi_buffer_snapshot
4237 .range_to_buffer_ranges(multi_buffer_visible_range)
4238 .into_iter()
4239 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4240 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4241 let buffer_file = project::File::from_dyn(buffer.file())?;
4242 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4243 let worktree_entry = buffer_worktree
4244 .read(cx)
4245 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4246 if worktree_entry.is_ignored {
4247 return None;
4248 }
4249
4250 let language = buffer.language()?;
4251 if let Some(restrict_to_languages) = restrict_to_languages {
4252 if !restrict_to_languages.contains(language) {
4253 return None;
4254 }
4255 }
4256 Some((
4257 excerpt_id,
4258 (
4259 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4260 buffer.version().clone(),
4261 excerpt_visible_range,
4262 ),
4263 ))
4264 })
4265 .collect()
4266 }
4267
4268 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4269 TextLayoutDetails {
4270 text_system: window.text_system().clone(),
4271 editor_style: self.style.clone().unwrap(),
4272 rem_size: window.rem_size(),
4273 scroll_anchor: self.scroll_manager.anchor(),
4274 visible_rows: self.visible_line_count(),
4275 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4276 }
4277 }
4278
4279 pub fn splice_inlays(
4280 &self,
4281 to_remove: &[InlayId],
4282 to_insert: Vec<Inlay>,
4283 cx: &mut Context<Self>,
4284 ) {
4285 self.display_map.update(cx, |display_map, cx| {
4286 display_map.splice_inlays(to_remove, to_insert, cx)
4287 });
4288 cx.notify();
4289 }
4290
4291 fn trigger_on_type_formatting(
4292 &self,
4293 input: String,
4294 window: &mut Window,
4295 cx: &mut Context<Self>,
4296 ) -> Option<Task<Result<()>>> {
4297 if input.len() != 1 {
4298 return None;
4299 }
4300
4301 let project = self.project.as_ref()?;
4302 let position = self.selections.newest_anchor().head();
4303 let (buffer, buffer_position) = self
4304 .buffer
4305 .read(cx)
4306 .text_anchor_for_position(position, cx)?;
4307
4308 let settings = language_settings::language_settings(
4309 buffer
4310 .read(cx)
4311 .language_at(buffer_position)
4312 .map(|l| l.name()),
4313 buffer.read(cx).file(),
4314 cx,
4315 );
4316 if !settings.use_on_type_format {
4317 return None;
4318 }
4319
4320 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4321 // hence we do LSP request & edit on host side only — add formats to host's history.
4322 let push_to_lsp_host_history = true;
4323 // If this is not the host, append its history with new edits.
4324 let push_to_client_history = project.read(cx).is_via_collab();
4325
4326 let on_type_formatting = project.update(cx, |project, cx| {
4327 project.on_type_format(
4328 buffer.clone(),
4329 buffer_position,
4330 input,
4331 push_to_lsp_host_history,
4332 cx,
4333 )
4334 });
4335 Some(cx.spawn_in(window, async move |editor, cx| {
4336 if let Some(transaction) = on_type_formatting.await? {
4337 if push_to_client_history {
4338 buffer
4339 .update(cx, |buffer, _| {
4340 buffer.push_transaction(transaction, Instant::now());
4341 buffer.finalize_last_transaction();
4342 })
4343 .ok();
4344 }
4345 editor.update(cx, |editor, cx| {
4346 editor.refresh_document_highlights(cx);
4347 })?;
4348 }
4349 Ok(())
4350 }))
4351 }
4352
4353 pub fn show_word_completions(
4354 &mut self,
4355 _: &ShowWordCompletions,
4356 window: &mut Window,
4357 cx: &mut Context<Self>,
4358 ) {
4359 self.open_completions_menu(true, None, window, cx);
4360 }
4361
4362 pub fn show_completions(
4363 &mut self,
4364 options: &ShowCompletions,
4365 window: &mut Window,
4366 cx: &mut Context<Self>,
4367 ) {
4368 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4369 }
4370
4371 fn open_completions_menu(
4372 &mut self,
4373 ignore_completion_provider: bool,
4374 trigger: Option<&str>,
4375 window: &mut Window,
4376 cx: &mut Context<Self>,
4377 ) {
4378 if self.pending_rename.is_some() {
4379 return;
4380 }
4381 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4382 return;
4383 }
4384
4385 let position = self.selections.newest_anchor().head();
4386 if position.diff_base_anchor.is_some() {
4387 return;
4388 }
4389 let (buffer, buffer_position) =
4390 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4391 output
4392 } else {
4393 return;
4394 };
4395 let buffer_snapshot = buffer.read(cx).snapshot();
4396 let show_completion_documentation = buffer_snapshot
4397 .settings_at(buffer_position, cx)
4398 .show_completion_documentation;
4399
4400 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4401
4402 let trigger_kind = match trigger {
4403 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4404 CompletionTriggerKind::TRIGGER_CHARACTER
4405 }
4406 _ => CompletionTriggerKind::INVOKED,
4407 };
4408 let completion_context = CompletionContext {
4409 trigger_character: trigger.and_then(|trigger| {
4410 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4411 Some(String::from(trigger))
4412 } else {
4413 None
4414 }
4415 }),
4416 trigger_kind,
4417 };
4418
4419 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4420 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4421 let word_to_exclude = buffer_snapshot
4422 .text_for_range(old_range.clone())
4423 .collect::<String>();
4424 (
4425 buffer_snapshot.anchor_before(old_range.start)
4426 ..buffer_snapshot.anchor_after(old_range.end),
4427 Some(word_to_exclude),
4428 )
4429 } else {
4430 (buffer_position..buffer_position, None)
4431 };
4432
4433 let completion_settings = language_settings(
4434 buffer_snapshot
4435 .language_at(buffer_position)
4436 .map(|language| language.name()),
4437 buffer_snapshot.file(),
4438 cx,
4439 )
4440 .completions;
4441
4442 // The document can be large, so stay in reasonable bounds when searching for words,
4443 // otherwise completion pop-up might be slow to appear.
4444 const WORD_LOOKUP_ROWS: u32 = 5_000;
4445 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4446 let min_word_search = buffer_snapshot.clip_point(
4447 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4448 Bias::Left,
4449 );
4450 let max_word_search = buffer_snapshot.clip_point(
4451 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4452 Bias::Right,
4453 );
4454 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4455 ..buffer_snapshot.point_to_offset(max_word_search);
4456
4457 let provider = self
4458 .completion_provider
4459 .as_ref()
4460 .filter(|_| !ignore_completion_provider);
4461 let skip_digits = query
4462 .as_ref()
4463 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4464
4465 let (mut words, provided_completions) = match provider {
4466 Some(provider) => {
4467 let completions = provider.completions(
4468 position.excerpt_id,
4469 &buffer,
4470 buffer_position,
4471 completion_context,
4472 window,
4473 cx,
4474 );
4475
4476 let words = match completion_settings.words {
4477 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4478 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4479 .background_spawn(async move {
4480 buffer_snapshot.words_in_range(WordsQuery {
4481 fuzzy_contents: None,
4482 range: word_search_range,
4483 skip_digits,
4484 })
4485 }),
4486 };
4487
4488 (words, completions)
4489 }
4490 None => (
4491 cx.background_spawn(async move {
4492 buffer_snapshot.words_in_range(WordsQuery {
4493 fuzzy_contents: None,
4494 range: word_search_range,
4495 skip_digits,
4496 })
4497 }),
4498 Task::ready(Ok(None)),
4499 ),
4500 };
4501
4502 let sort_completions = provider
4503 .as_ref()
4504 .map_or(false, |provider| provider.sort_completions());
4505
4506 let filter_completions = provider
4507 .as_ref()
4508 .map_or(true, |provider| provider.filter_completions());
4509
4510 let id = post_inc(&mut self.next_completion_id);
4511 let task = cx.spawn_in(window, async move |editor, cx| {
4512 async move {
4513 editor.update(cx, |this, _| {
4514 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4515 })?;
4516
4517 let mut completions = Vec::new();
4518 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4519 completions.extend(provided_completions);
4520 if completion_settings.words == WordsCompletionMode::Fallback {
4521 words = Task::ready(BTreeMap::default());
4522 }
4523 }
4524
4525 let mut words = words.await;
4526 if let Some(word_to_exclude) = &word_to_exclude {
4527 words.remove(word_to_exclude);
4528 }
4529 for lsp_completion in &completions {
4530 words.remove(&lsp_completion.new_text);
4531 }
4532 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4533 replace_range: old_range.clone(),
4534 new_text: word.clone(),
4535 label: CodeLabel::plain(word, None),
4536 icon_path: None,
4537 documentation: None,
4538 source: CompletionSource::BufferWord {
4539 word_range,
4540 resolved: false,
4541 },
4542 insert_text_mode: Some(InsertTextMode::AS_IS),
4543 confirm: None,
4544 }));
4545
4546 let menu = if completions.is_empty() {
4547 None
4548 } else {
4549 let mut menu = CompletionsMenu::new(
4550 id,
4551 sort_completions,
4552 show_completion_documentation,
4553 ignore_completion_provider,
4554 position,
4555 buffer.clone(),
4556 completions.into(),
4557 );
4558
4559 menu.filter(
4560 if filter_completions {
4561 query.as_deref()
4562 } else {
4563 None
4564 },
4565 cx.background_executor().clone(),
4566 )
4567 .await;
4568
4569 menu.visible().then_some(menu)
4570 };
4571
4572 editor.update_in(cx, |editor, window, cx| {
4573 match editor.context_menu.borrow().as_ref() {
4574 None => {}
4575 Some(CodeContextMenu::Completions(prev_menu)) => {
4576 if prev_menu.id > id {
4577 return;
4578 }
4579 }
4580 _ => return,
4581 }
4582
4583 if editor.focus_handle.is_focused(window) && menu.is_some() {
4584 let mut menu = menu.unwrap();
4585 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4586
4587 *editor.context_menu.borrow_mut() =
4588 Some(CodeContextMenu::Completions(menu));
4589
4590 if editor.show_edit_predictions_in_menu() {
4591 editor.update_visible_inline_completion(window, cx);
4592 } else {
4593 editor.discard_inline_completion(false, cx);
4594 }
4595
4596 cx.notify();
4597 } else if editor.completion_tasks.len() <= 1 {
4598 // If there are no more completion tasks and the last menu was
4599 // empty, we should hide it.
4600 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4601 // If it was already hidden and we don't show inline
4602 // completions in the menu, we should also show the
4603 // inline-completion when available.
4604 if was_hidden && editor.show_edit_predictions_in_menu() {
4605 editor.update_visible_inline_completion(window, cx);
4606 }
4607 }
4608 })?;
4609
4610 anyhow::Ok(())
4611 }
4612 .log_err()
4613 .await
4614 });
4615
4616 self.completion_tasks.push((id, task));
4617 }
4618
4619 #[cfg(feature = "test-support")]
4620 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4621 let menu = self.context_menu.borrow();
4622 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4623 let completions = menu.completions.borrow();
4624 Some(completions.to_vec())
4625 } else {
4626 None
4627 }
4628 }
4629
4630 pub fn confirm_completion(
4631 &mut self,
4632 action: &ConfirmCompletion,
4633 window: &mut Window,
4634 cx: &mut Context<Self>,
4635 ) -> Option<Task<Result<()>>> {
4636 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4637 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4638 }
4639
4640 pub fn confirm_completion_insert(
4641 &mut self,
4642 _: &ConfirmCompletionInsert,
4643 window: &mut Window,
4644 cx: &mut Context<Self>,
4645 ) -> Option<Task<Result<()>>> {
4646 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4647 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4648 }
4649
4650 pub fn confirm_completion_replace(
4651 &mut self,
4652 _: &ConfirmCompletionReplace,
4653 window: &mut Window,
4654 cx: &mut Context<Self>,
4655 ) -> Option<Task<Result<()>>> {
4656 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4657 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4658 }
4659
4660 pub fn compose_completion(
4661 &mut self,
4662 action: &ComposeCompletion,
4663 window: &mut Window,
4664 cx: &mut Context<Self>,
4665 ) -> Option<Task<Result<()>>> {
4666 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4667 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4668 }
4669
4670 fn do_completion(
4671 &mut self,
4672 item_ix: Option<usize>,
4673 intent: CompletionIntent,
4674 window: &mut Window,
4675 cx: &mut Context<Editor>,
4676 ) -> Option<Task<Result<()>>> {
4677 use language::ToOffset as _;
4678
4679 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4680 else {
4681 return None;
4682 };
4683
4684 let candidate_id = {
4685 let entries = completions_menu.entries.borrow();
4686 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4687 if self.show_edit_predictions_in_menu() {
4688 self.discard_inline_completion(true, cx);
4689 }
4690 mat.candidate_id
4691 };
4692
4693 let buffer_handle = completions_menu.buffer;
4694 let completion = completions_menu
4695 .completions
4696 .borrow()
4697 .get(candidate_id)?
4698 .clone();
4699 cx.stop_propagation();
4700
4701 let snippet;
4702 let new_text;
4703 if completion.is_snippet() {
4704 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4705 new_text = snippet.as_ref().unwrap().text.clone();
4706 } else {
4707 snippet = None;
4708 new_text = completion.new_text.clone();
4709 };
4710
4711 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4712 let buffer = buffer_handle.read(cx);
4713 let snapshot = self.buffer.read(cx).snapshot(cx);
4714 let replace_range_multibuffer = {
4715 let excerpt = snapshot
4716 .excerpt_containing(self.selections.newest_anchor().range())
4717 .unwrap();
4718 let multibuffer_anchor = snapshot
4719 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4720 .unwrap()
4721 ..snapshot
4722 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4723 .unwrap();
4724 multibuffer_anchor.start.to_offset(&snapshot)
4725 ..multibuffer_anchor.end.to_offset(&snapshot)
4726 };
4727 let newest_anchor = self.selections.newest_anchor();
4728 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4729 return None;
4730 }
4731
4732 let old_text = buffer
4733 .text_for_range(replace_range.clone())
4734 .collect::<String>();
4735 let lookbehind = newest_anchor
4736 .start
4737 .text_anchor
4738 .to_offset(buffer)
4739 .saturating_sub(replace_range.start);
4740 let lookahead = replace_range
4741 .end
4742 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4743 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4744 let suffix = &old_text[lookbehind.min(old_text.len())..];
4745
4746 let selections = self.selections.all::<usize>(cx);
4747 let mut edits = Vec::new();
4748 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4749
4750 for selection in &selections {
4751 let edit = if selection.id == newest_anchor.id {
4752 (replace_range_multibuffer.clone(), new_text.as_str())
4753 } else {
4754 let mut range = selection.range();
4755 let mut text = new_text.as_str();
4756
4757 // if prefix is present, don't duplicate it
4758 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4759 text = &new_text[lookbehind.min(new_text.len())..];
4760
4761 // if suffix is also present, mimic the newest cursor and replace it
4762 if selection.id != newest_anchor.id
4763 && snapshot.contains_str_at(range.end, suffix)
4764 {
4765 range.end += lookahead;
4766 }
4767 }
4768 (range, text)
4769 };
4770
4771 edits.push(edit);
4772
4773 if !self.linked_edit_ranges.is_empty() {
4774 let start_anchor = snapshot.anchor_before(selection.head());
4775 let end_anchor = snapshot.anchor_after(selection.tail());
4776 if let Some(ranges) = self
4777 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4778 {
4779 for (buffer, edits) in ranges {
4780 linked_edits
4781 .entry(buffer.clone())
4782 .or_default()
4783 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
4784 }
4785 }
4786 }
4787 }
4788
4789 cx.emit(EditorEvent::InputHandled {
4790 utf16_range_to_replace: None,
4791 text: new_text.clone().into(),
4792 });
4793
4794 self.transact(window, cx, |this, window, cx| {
4795 if let Some(mut snippet) = snippet {
4796 snippet.text = new_text.to_string();
4797 let ranges = edits
4798 .iter()
4799 .map(|(range, _)| range.clone())
4800 .collect::<Vec<_>>();
4801 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4802 } else {
4803 this.buffer.update(cx, |buffer, cx| {
4804 let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
4805 {
4806 None
4807 } else {
4808 this.autoindent_mode.clone()
4809 };
4810 buffer.edit(edits, auto_indent, cx);
4811 });
4812 }
4813 for (buffer, edits) in linked_edits {
4814 buffer.update(cx, |buffer, cx| {
4815 let snapshot = buffer.snapshot();
4816 let edits = edits
4817 .into_iter()
4818 .map(|(range, text)| {
4819 use text::ToPoint as TP;
4820 let end_point = TP::to_point(&range.end, &snapshot);
4821 let start_point = TP::to_point(&range.start, &snapshot);
4822 (start_point..end_point, text)
4823 })
4824 .sorted_by_key(|(range, _)| range.start);
4825 buffer.edit(edits, None, cx);
4826 })
4827 }
4828
4829 this.refresh_inline_completion(true, false, window, cx);
4830 });
4831
4832 let show_new_completions_on_confirm = completion
4833 .confirm
4834 .as_ref()
4835 .map_or(false, |confirm| confirm(intent, window, cx));
4836 if show_new_completions_on_confirm {
4837 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4838 }
4839
4840 let provider = self.completion_provider.as_ref()?;
4841 drop(completion);
4842 let apply_edits = provider.apply_additional_edits_for_completion(
4843 buffer_handle,
4844 completions_menu.completions.clone(),
4845 candidate_id,
4846 true,
4847 cx,
4848 );
4849
4850 let editor_settings = EditorSettings::get_global(cx);
4851 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4852 // After the code completion is finished, users often want to know what signatures are needed.
4853 // so we should automatically call signature_help
4854 self.show_signature_help(&ShowSignatureHelp, window, cx);
4855 }
4856
4857 Some(cx.foreground_executor().spawn(async move {
4858 apply_edits.await?;
4859 Ok(())
4860 }))
4861 }
4862
4863 fn prepare_code_actions_task(
4864 &mut self,
4865 action: &ToggleCodeActions,
4866 window: &mut Window,
4867 cx: &mut Context<Self>,
4868 ) -> Task<Option<(Entity<Buffer>, CodeActionContents)>> {
4869 let snapshot = self.snapshot(window, cx);
4870 let multibuffer_point = action
4871 .deployed_from_indicator
4872 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4873 .unwrap_or_else(|| self.selections.newest::<Point>(cx).head());
4874
4875 let Some((buffer, buffer_row)) = snapshot
4876 .buffer_snapshot
4877 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4878 .and_then(|(buffer_snapshot, range)| {
4879 self.buffer
4880 .read(cx)
4881 .buffer(buffer_snapshot.remote_id())
4882 .map(|buffer| (buffer, range.start.row))
4883 })
4884 else {
4885 return Task::ready(None);
4886 };
4887
4888 let (_, code_actions) = self
4889 .available_code_actions
4890 .clone()
4891 .and_then(|(location, code_actions)| {
4892 let snapshot = location.buffer.read(cx).snapshot();
4893 let point_range = location.range.to_point(&snapshot);
4894 let point_range = point_range.start.row..=point_range.end.row;
4895 if point_range.contains(&buffer_row) {
4896 Some((location, code_actions))
4897 } else {
4898 None
4899 }
4900 })
4901 .unzip();
4902
4903 let buffer_id = buffer.read(cx).remote_id();
4904 let tasks = self
4905 .tasks
4906 .get(&(buffer_id, buffer_row))
4907 .map(|t| Arc::new(t.to_owned()));
4908
4909 if tasks.is_none() && code_actions.is_none() {
4910 return Task::ready(None);
4911 }
4912
4913 self.completion_tasks.clear();
4914 self.discard_inline_completion(false, cx);
4915
4916 let task_context = tasks
4917 .as_ref()
4918 .zip(self.project.clone())
4919 .map(|(tasks, project)| {
4920 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4921 });
4922
4923 cx.spawn_in(window, async move |_, _| {
4924 let task_context = match task_context {
4925 Some(task_context) => task_context.await,
4926 None => None,
4927 };
4928 let resolved_tasks = tasks.zip(task_context).map(|(tasks, task_context)| {
4929 Rc::new(ResolvedTasks {
4930 templates: tasks.resolve(&task_context).collect(),
4931 position: snapshot
4932 .buffer_snapshot
4933 .anchor_before(Point::new(multibuffer_point.row, tasks.column)),
4934 })
4935 });
4936 Some((
4937 buffer,
4938 CodeActionContents {
4939 actions: code_actions,
4940 tasks: resolved_tasks,
4941 },
4942 ))
4943 })
4944 }
4945
4946 pub fn toggle_code_actions(
4947 &mut self,
4948 action: &ToggleCodeActions,
4949 window: &mut Window,
4950 cx: &mut Context<Self>,
4951 ) {
4952 let mut context_menu = self.context_menu.borrow_mut();
4953 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4954 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4955 // Toggle if we're selecting the same one
4956 *context_menu = None;
4957 cx.notify();
4958 return;
4959 } else {
4960 // Otherwise, clear it and start a new one
4961 *context_menu = None;
4962 cx.notify();
4963 }
4964 }
4965 drop(context_menu);
4966
4967 let deployed_from_indicator = action.deployed_from_indicator;
4968 let mut task = self.code_actions_task.take();
4969 let action = action.clone();
4970
4971 cx.spawn_in(window, async move |editor, cx| {
4972 while let Some(prev_task) = task {
4973 prev_task.await.log_err();
4974 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4975 }
4976
4977 let context_menu_task = editor.update_in(cx, |editor, window, cx| {
4978 if !editor.focus_handle.is_focused(window) {
4979 return Some(Task::ready(Ok(())));
4980 }
4981 let debugger_flag = cx.has_flag::<Debugger>();
4982 let code_actions_task = editor.prepare_code_actions_task(&action, window, cx);
4983 Some(cx.spawn_in(window, async move |editor, cx| {
4984 if let Some((buffer, code_action_contents)) = code_actions_task.await {
4985 let spawn_straight_away =
4986 code_action_contents.tasks.as_ref().map_or(false, |tasks| {
4987 tasks
4988 .templates
4989 .iter()
4990 .filter(|task| {
4991 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4992 debugger_flag
4993 } else {
4994 true
4995 }
4996 })
4997 .count()
4998 == 1
4999 }) && code_action_contents
5000 .actions
5001 .as_ref()
5002 .map_or(true, |actions| actions.is_empty());
5003 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5004 *editor.context_menu.borrow_mut() =
5005 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5006 buffer,
5007 actions: code_action_contents,
5008 selected_item: Default::default(),
5009 scroll_handle: UniformListScrollHandle::default(),
5010 deployed_from_indicator,
5011 }));
5012 if spawn_straight_away {
5013 if let Some(task) = editor.confirm_code_action(
5014 &ConfirmCodeAction {
5015 item_ix: Some(0),
5016 from_mouse_context_menu: false,
5017 },
5018 window,
5019 cx,
5020 ) {
5021 cx.notify();
5022 return task;
5023 }
5024 }
5025 cx.notify();
5026 Task::ready(Ok(()))
5027 }) {
5028 task.await
5029 } else {
5030 Ok(())
5031 }
5032 } else {
5033 Ok(())
5034 }
5035 }))
5036 })?;
5037 if let Some(task) = context_menu_task {
5038 task.await?;
5039 }
5040
5041 Ok::<_, anyhow::Error>(())
5042 })
5043 .detach_and_log_err(cx);
5044 }
5045
5046 pub fn confirm_code_action(
5047 &mut self,
5048 action: &ConfirmCodeAction,
5049 window: &mut Window,
5050 cx: &mut Context<Self>,
5051 ) -> Option<Task<Result<()>>> {
5052 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5053
5054 let (action, buffer) = if action.from_mouse_context_menu {
5055 if let Some(menu) = self.mouse_context_menu.take() {
5056 let code_action = menu.code_action?;
5057 let index = action.item_ix?;
5058 let action = code_action.actions.get(index)?;
5059 (action, code_action.buffer)
5060 } else {
5061 return None;
5062 }
5063 } else {
5064 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5065 let action_ix = action.item_ix.unwrap_or(menu.selected_item);
5066 let action = menu.actions.get(action_ix)?;
5067 let buffer = menu.buffer;
5068 (action, buffer)
5069 } else {
5070 return None;
5071 }
5072 };
5073
5074 let title = action.label();
5075 let workspace = self.workspace()?;
5076
5077 match action {
5078 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5079 match resolved_task.task_type() {
5080 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5081 workspace::tasks::schedule_resolved_task(
5082 workspace,
5083 task_source_kind,
5084 resolved_task,
5085 false,
5086 cx,
5087 );
5088
5089 Some(Task::ready(Ok(())))
5090 }),
5091 task::TaskType::Debug(debug_args) => {
5092 if debug_args.locator.is_some() {
5093 workspace.update(cx, |workspace, cx| {
5094 workspace::tasks::schedule_resolved_task(
5095 workspace,
5096 task_source_kind,
5097 resolved_task,
5098 false,
5099 cx,
5100 );
5101 });
5102
5103 return Some(Task::ready(Ok(())));
5104 }
5105
5106 if let Some(project) = self.project.as_ref() {
5107 project
5108 .update(cx, |project, cx| {
5109 project.start_debug_session(
5110 resolved_task.resolved_debug_adapter_config().unwrap(),
5111 cx,
5112 )
5113 })
5114 .detach_and_log_err(cx);
5115 Some(Task::ready(Ok(())))
5116 } else {
5117 Some(Task::ready(Ok(())))
5118 }
5119 }
5120 }
5121 }
5122 CodeActionsItem::CodeAction {
5123 excerpt_id,
5124 action,
5125 provider,
5126 } => {
5127 let apply_code_action =
5128 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5129 let workspace = workspace.downgrade();
5130 Some(cx.spawn_in(window, async move |editor, cx| {
5131 let project_transaction = apply_code_action.await?;
5132 Self::open_project_transaction(
5133 &editor,
5134 workspace,
5135 project_transaction,
5136 title,
5137 cx,
5138 )
5139 .await
5140 }))
5141 }
5142 }
5143 }
5144
5145 pub async fn open_project_transaction(
5146 this: &WeakEntity<Editor>,
5147 workspace: WeakEntity<Workspace>,
5148 transaction: ProjectTransaction,
5149 title: String,
5150 cx: &mut AsyncWindowContext,
5151 ) -> Result<()> {
5152 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5153 cx.update(|_, cx| {
5154 entries.sort_unstable_by_key(|(buffer, _)| {
5155 buffer.read(cx).file().map(|f| f.path().clone())
5156 });
5157 })?;
5158
5159 // If the project transaction's edits are all contained within this editor, then
5160 // avoid opening a new editor to display them.
5161
5162 if let Some((buffer, transaction)) = entries.first() {
5163 if entries.len() == 1 {
5164 let excerpt = this.update(cx, |editor, cx| {
5165 editor
5166 .buffer()
5167 .read(cx)
5168 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5169 })?;
5170 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5171 if excerpted_buffer == *buffer {
5172 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5173 let excerpt_range = excerpt_range.to_offset(buffer);
5174 buffer
5175 .edited_ranges_for_transaction::<usize>(transaction)
5176 .all(|range| {
5177 excerpt_range.start <= range.start
5178 && excerpt_range.end >= range.end
5179 })
5180 })?;
5181
5182 if all_edits_within_excerpt {
5183 return Ok(());
5184 }
5185 }
5186 }
5187 }
5188 } else {
5189 return Ok(());
5190 }
5191
5192 let mut ranges_to_highlight = Vec::new();
5193 let excerpt_buffer = cx.new(|cx| {
5194 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5195 for (buffer_handle, transaction) in &entries {
5196 let edited_ranges = buffer_handle
5197 .read(cx)
5198 .edited_ranges_for_transaction::<Point>(transaction)
5199 .collect::<Vec<_>>();
5200 let (ranges, _) = multibuffer.set_excerpts_for_path(
5201 PathKey::for_buffer(buffer_handle, cx),
5202 buffer_handle.clone(),
5203 edited_ranges,
5204 DEFAULT_MULTIBUFFER_CONTEXT,
5205 cx,
5206 );
5207
5208 ranges_to_highlight.extend(ranges);
5209 }
5210 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5211 multibuffer
5212 })?;
5213
5214 workspace.update_in(cx, |workspace, window, cx| {
5215 let project = workspace.project().clone();
5216 let editor =
5217 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5218 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5219 editor.update(cx, |editor, cx| {
5220 editor.highlight_background::<Self>(
5221 &ranges_to_highlight,
5222 |theme| theme.editor_highlighted_line_background,
5223 cx,
5224 );
5225 });
5226 })?;
5227
5228 Ok(())
5229 }
5230
5231 pub fn clear_code_action_providers(&mut self) {
5232 self.code_action_providers.clear();
5233 self.available_code_actions.take();
5234 }
5235
5236 pub fn add_code_action_provider(
5237 &mut self,
5238 provider: Rc<dyn CodeActionProvider>,
5239 window: &mut Window,
5240 cx: &mut Context<Self>,
5241 ) {
5242 if self
5243 .code_action_providers
5244 .iter()
5245 .any(|existing_provider| existing_provider.id() == provider.id())
5246 {
5247 return;
5248 }
5249
5250 self.code_action_providers.push(provider);
5251 self.refresh_code_actions(window, cx);
5252 }
5253
5254 pub fn remove_code_action_provider(
5255 &mut self,
5256 id: Arc<str>,
5257 window: &mut Window,
5258 cx: &mut Context<Self>,
5259 ) {
5260 self.code_action_providers
5261 .retain(|provider| provider.id() != id);
5262 self.refresh_code_actions(window, cx);
5263 }
5264
5265 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5266 let newest_selection = self.selections.newest_anchor().clone();
5267 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5268 let buffer = self.buffer.read(cx);
5269 if newest_selection.head().diff_base_anchor.is_some() {
5270 return None;
5271 }
5272 let (start_buffer, start) =
5273 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5274 let (end_buffer, end) =
5275 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5276 if start_buffer != end_buffer {
5277 return None;
5278 }
5279
5280 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5281 cx.background_executor()
5282 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5283 .await;
5284
5285 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5286 let providers = this.code_action_providers.clone();
5287 let tasks = this
5288 .code_action_providers
5289 .iter()
5290 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5291 .collect::<Vec<_>>();
5292 (providers, tasks)
5293 })?;
5294
5295 let mut actions = Vec::new();
5296 for (provider, provider_actions) in
5297 providers.into_iter().zip(future::join_all(tasks).await)
5298 {
5299 if let Some(provider_actions) = provider_actions.log_err() {
5300 actions.extend(provider_actions.into_iter().map(|action| {
5301 AvailableCodeAction {
5302 excerpt_id: newest_selection.start.excerpt_id,
5303 action,
5304 provider: provider.clone(),
5305 }
5306 }));
5307 }
5308 }
5309
5310 this.update(cx, |this, cx| {
5311 this.available_code_actions = if actions.is_empty() {
5312 None
5313 } else {
5314 Some((
5315 Location {
5316 buffer: start_buffer,
5317 range: start..end,
5318 },
5319 actions.into(),
5320 ))
5321 };
5322 cx.notify();
5323 })
5324 }));
5325 None
5326 }
5327
5328 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5329 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5330 self.show_git_blame_inline = false;
5331
5332 self.show_git_blame_inline_delay_task =
5333 Some(cx.spawn_in(window, async move |this, cx| {
5334 cx.background_executor().timer(delay).await;
5335
5336 this.update(cx, |this, cx| {
5337 this.show_git_blame_inline = true;
5338 cx.notify();
5339 })
5340 .log_err();
5341 }));
5342 }
5343 }
5344
5345 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5346 if self.pending_rename.is_some() {
5347 return None;
5348 }
5349
5350 let provider = self.semantics_provider.clone()?;
5351 let buffer = self.buffer.read(cx);
5352 let newest_selection = self.selections.newest_anchor().clone();
5353 let cursor_position = newest_selection.head();
5354 let (cursor_buffer, cursor_buffer_position) =
5355 buffer.text_anchor_for_position(cursor_position, cx)?;
5356 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5357 if cursor_buffer != tail_buffer {
5358 return None;
5359 }
5360 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5361 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5362 cx.background_executor()
5363 .timer(Duration::from_millis(debounce))
5364 .await;
5365
5366 let highlights = if let Some(highlights) = cx
5367 .update(|cx| {
5368 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5369 })
5370 .ok()
5371 .flatten()
5372 {
5373 highlights.await.log_err()
5374 } else {
5375 None
5376 };
5377
5378 if let Some(highlights) = highlights {
5379 this.update(cx, |this, cx| {
5380 if this.pending_rename.is_some() {
5381 return;
5382 }
5383
5384 let buffer_id = cursor_position.buffer_id;
5385 let buffer = this.buffer.read(cx);
5386 if !buffer
5387 .text_anchor_for_position(cursor_position, cx)
5388 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5389 {
5390 return;
5391 }
5392
5393 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5394 let mut write_ranges = Vec::new();
5395 let mut read_ranges = Vec::new();
5396 for highlight in highlights {
5397 for (excerpt_id, excerpt_range) in
5398 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5399 {
5400 let start = highlight
5401 .range
5402 .start
5403 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5404 let end = highlight
5405 .range
5406 .end
5407 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5408 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5409 continue;
5410 }
5411
5412 let range = Anchor {
5413 buffer_id,
5414 excerpt_id,
5415 text_anchor: start,
5416 diff_base_anchor: None,
5417 }..Anchor {
5418 buffer_id,
5419 excerpt_id,
5420 text_anchor: end,
5421 diff_base_anchor: None,
5422 };
5423 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5424 write_ranges.push(range);
5425 } else {
5426 read_ranges.push(range);
5427 }
5428 }
5429 }
5430
5431 this.highlight_background::<DocumentHighlightRead>(
5432 &read_ranges,
5433 |theme| theme.editor_document_highlight_read_background,
5434 cx,
5435 );
5436 this.highlight_background::<DocumentHighlightWrite>(
5437 &write_ranges,
5438 |theme| theme.editor_document_highlight_write_background,
5439 cx,
5440 );
5441 cx.notify();
5442 })
5443 .log_err();
5444 }
5445 }));
5446 None
5447 }
5448
5449 pub fn refresh_selected_text_highlights(
5450 &mut self,
5451 window: &mut Window,
5452 cx: &mut Context<Editor>,
5453 ) {
5454 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5455 return;
5456 }
5457 self.selection_highlight_task.take();
5458 if !EditorSettings::get_global(cx).selection_highlight {
5459 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5460 return;
5461 }
5462 if self.selections.count() != 1 || self.selections.line_mode {
5463 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5464 return;
5465 }
5466 let selection = self.selections.newest::<Point>(cx);
5467 if selection.is_empty() || selection.start.row != selection.end.row {
5468 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5469 return;
5470 }
5471 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5472 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5473 cx.background_executor()
5474 .timer(Duration::from_millis(debounce))
5475 .await;
5476 let Some(Some(matches_task)) = editor
5477 .update_in(cx, |editor, _, cx| {
5478 if editor.selections.count() != 1 || editor.selections.line_mode {
5479 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5480 return None;
5481 }
5482 let selection = editor.selections.newest::<Point>(cx);
5483 if selection.is_empty() || selection.start.row != selection.end.row {
5484 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5485 return None;
5486 }
5487 let buffer = editor.buffer().read(cx).snapshot(cx);
5488 let query = buffer.text_for_range(selection.range()).collect::<String>();
5489 if query.trim().is_empty() {
5490 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5491 return None;
5492 }
5493 Some(cx.background_spawn(async move {
5494 let mut ranges = Vec::new();
5495 let selection_anchors = selection.range().to_anchors(&buffer);
5496 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5497 for (search_buffer, search_range, excerpt_id) in
5498 buffer.range_to_buffer_ranges(range)
5499 {
5500 ranges.extend(
5501 project::search::SearchQuery::text(
5502 query.clone(),
5503 false,
5504 false,
5505 false,
5506 Default::default(),
5507 Default::default(),
5508 None,
5509 )
5510 .unwrap()
5511 .search(search_buffer, Some(search_range.clone()))
5512 .await
5513 .into_iter()
5514 .filter_map(
5515 |match_range| {
5516 let start = search_buffer.anchor_after(
5517 search_range.start + match_range.start,
5518 );
5519 let end = search_buffer.anchor_before(
5520 search_range.start + match_range.end,
5521 );
5522 let range = Anchor::range_in_buffer(
5523 excerpt_id,
5524 search_buffer.remote_id(),
5525 start..end,
5526 );
5527 (range != selection_anchors).then_some(range)
5528 },
5529 ),
5530 );
5531 }
5532 }
5533 ranges
5534 }))
5535 })
5536 .log_err()
5537 else {
5538 return;
5539 };
5540 let matches = matches_task.await;
5541 editor
5542 .update_in(cx, |editor, _, cx| {
5543 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5544 if !matches.is_empty() {
5545 editor.highlight_background::<SelectedTextHighlight>(
5546 &matches,
5547 |theme| theme.editor_document_highlight_bracket_background,
5548 cx,
5549 )
5550 }
5551 })
5552 .log_err();
5553 }));
5554 }
5555
5556 pub fn refresh_inline_completion(
5557 &mut self,
5558 debounce: bool,
5559 user_requested: bool,
5560 window: &mut Window,
5561 cx: &mut Context<Self>,
5562 ) -> Option<()> {
5563 let provider = self.edit_prediction_provider()?;
5564 let cursor = self.selections.newest_anchor().head();
5565 let (buffer, cursor_buffer_position) =
5566 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5567
5568 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5569 self.discard_inline_completion(false, cx);
5570 return None;
5571 }
5572
5573 if !user_requested
5574 && (!self.should_show_edit_predictions()
5575 || !self.is_focused(window)
5576 || buffer.read(cx).is_empty())
5577 {
5578 self.discard_inline_completion(false, cx);
5579 return None;
5580 }
5581
5582 self.update_visible_inline_completion(window, cx);
5583 provider.refresh(
5584 self.project.clone(),
5585 buffer,
5586 cursor_buffer_position,
5587 debounce,
5588 cx,
5589 );
5590 Some(())
5591 }
5592
5593 fn show_edit_predictions_in_menu(&self) -> bool {
5594 match self.edit_prediction_settings {
5595 EditPredictionSettings::Disabled => false,
5596 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5597 }
5598 }
5599
5600 pub fn edit_predictions_enabled(&self) -> bool {
5601 match self.edit_prediction_settings {
5602 EditPredictionSettings::Disabled => false,
5603 EditPredictionSettings::Enabled { .. } => true,
5604 }
5605 }
5606
5607 fn edit_prediction_requires_modifier(&self) -> bool {
5608 match self.edit_prediction_settings {
5609 EditPredictionSettings::Disabled => false,
5610 EditPredictionSettings::Enabled {
5611 preview_requires_modifier,
5612 ..
5613 } => preview_requires_modifier,
5614 }
5615 }
5616
5617 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5618 if self.edit_prediction_provider.is_none() {
5619 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5620 } else {
5621 let selection = self.selections.newest_anchor();
5622 let cursor = selection.head();
5623
5624 if let Some((buffer, cursor_buffer_position)) =
5625 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5626 {
5627 self.edit_prediction_settings =
5628 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5629 }
5630 }
5631 }
5632
5633 fn edit_prediction_settings_at_position(
5634 &self,
5635 buffer: &Entity<Buffer>,
5636 buffer_position: language::Anchor,
5637 cx: &App,
5638 ) -> EditPredictionSettings {
5639 if !self.mode.is_full()
5640 || !self.show_inline_completions_override.unwrap_or(true)
5641 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5642 {
5643 return EditPredictionSettings::Disabled;
5644 }
5645
5646 let buffer = buffer.read(cx);
5647
5648 let file = buffer.file();
5649
5650 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5651 return EditPredictionSettings::Disabled;
5652 };
5653
5654 let by_provider = matches!(
5655 self.menu_inline_completions_policy,
5656 MenuInlineCompletionsPolicy::ByProvider
5657 );
5658
5659 let show_in_menu = by_provider
5660 && self
5661 .edit_prediction_provider
5662 .as_ref()
5663 .map_or(false, |provider| {
5664 provider.provider.show_completions_in_menu()
5665 });
5666
5667 let preview_requires_modifier =
5668 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5669
5670 EditPredictionSettings::Enabled {
5671 show_in_menu,
5672 preview_requires_modifier,
5673 }
5674 }
5675
5676 fn should_show_edit_predictions(&self) -> bool {
5677 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5678 }
5679
5680 pub fn edit_prediction_preview_is_active(&self) -> bool {
5681 matches!(
5682 self.edit_prediction_preview,
5683 EditPredictionPreview::Active { .. }
5684 )
5685 }
5686
5687 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5688 let cursor = self.selections.newest_anchor().head();
5689 if let Some((buffer, cursor_position)) =
5690 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5691 {
5692 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5693 } else {
5694 false
5695 }
5696 }
5697
5698 fn edit_predictions_enabled_in_buffer(
5699 &self,
5700 buffer: &Entity<Buffer>,
5701 buffer_position: language::Anchor,
5702 cx: &App,
5703 ) -> bool {
5704 maybe!({
5705 if self.read_only(cx) {
5706 return Some(false);
5707 }
5708 let provider = self.edit_prediction_provider()?;
5709 if !provider.is_enabled(&buffer, buffer_position, cx) {
5710 return Some(false);
5711 }
5712 let buffer = buffer.read(cx);
5713 let Some(file) = buffer.file() else {
5714 return Some(true);
5715 };
5716 let settings = all_language_settings(Some(file), cx);
5717 Some(settings.edit_predictions_enabled_for_file(file, cx))
5718 })
5719 .unwrap_or(false)
5720 }
5721
5722 fn cycle_inline_completion(
5723 &mut self,
5724 direction: Direction,
5725 window: &mut Window,
5726 cx: &mut Context<Self>,
5727 ) -> Option<()> {
5728 let provider = self.edit_prediction_provider()?;
5729 let cursor = self.selections.newest_anchor().head();
5730 let (buffer, cursor_buffer_position) =
5731 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5732 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5733 return None;
5734 }
5735
5736 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5737 self.update_visible_inline_completion(window, cx);
5738
5739 Some(())
5740 }
5741
5742 pub fn show_inline_completion(
5743 &mut self,
5744 _: &ShowEditPrediction,
5745 window: &mut Window,
5746 cx: &mut Context<Self>,
5747 ) {
5748 if !self.has_active_inline_completion() {
5749 self.refresh_inline_completion(false, true, window, cx);
5750 return;
5751 }
5752
5753 self.update_visible_inline_completion(window, cx);
5754 }
5755
5756 pub fn display_cursor_names(
5757 &mut self,
5758 _: &DisplayCursorNames,
5759 window: &mut Window,
5760 cx: &mut Context<Self>,
5761 ) {
5762 self.show_cursor_names(window, cx);
5763 }
5764
5765 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5766 self.show_cursor_names = true;
5767 cx.notify();
5768 cx.spawn_in(window, async move |this, cx| {
5769 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5770 this.update(cx, |this, cx| {
5771 this.show_cursor_names = false;
5772 cx.notify()
5773 })
5774 .ok()
5775 })
5776 .detach();
5777 }
5778
5779 pub fn next_edit_prediction(
5780 &mut self,
5781 _: &NextEditPrediction,
5782 window: &mut Window,
5783 cx: &mut Context<Self>,
5784 ) {
5785 if self.has_active_inline_completion() {
5786 self.cycle_inline_completion(Direction::Next, window, cx);
5787 } else {
5788 let is_copilot_disabled = self
5789 .refresh_inline_completion(false, true, window, cx)
5790 .is_none();
5791 if is_copilot_disabled {
5792 cx.propagate();
5793 }
5794 }
5795 }
5796
5797 pub fn previous_edit_prediction(
5798 &mut self,
5799 _: &PreviousEditPrediction,
5800 window: &mut Window,
5801 cx: &mut Context<Self>,
5802 ) {
5803 if self.has_active_inline_completion() {
5804 self.cycle_inline_completion(Direction::Prev, window, cx);
5805 } else {
5806 let is_copilot_disabled = self
5807 .refresh_inline_completion(false, true, window, cx)
5808 .is_none();
5809 if is_copilot_disabled {
5810 cx.propagate();
5811 }
5812 }
5813 }
5814
5815 pub fn accept_edit_prediction(
5816 &mut self,
5817 _: &AcceptEditPrediction,
5818 window: &mut Window,
5819 cx: &mut Context<Self>,
5820 ) {
5821 if self.show_edit_predictions_in_menu() {
5822 self.hide_context_menu(window, cx);
5823 }
5824
5825 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5826 return;
5827 };
5828
5829 self.report_inline_completion_event(
5830 active_inline_completion.completion_id.clone(),
5831 true,
5832 cx,
5833 );
5834
5835 match &active_inline_completion.completion {
5836 InlineCompletion::Move { target, .. } => {
5837 let target = *target;
5838
5839 if let Some(position_map) = &self.last_position_map {
5840 if position_map
5841 .visible_row_range
5842 .contains(&target.to_display_point(&position_map.snapshot).row())
5843 || !self.edit_prediction_requires_modifier()
5844 {
5845 self.unfold_ranges(&[target..target], true, false, cx);
5846 // Note that this is also done in vim's handler of the Tab action.
5847 self.change_selections(
5848 Some(Autoscroll::newest()),
5849 window,
5850 cx,
5851 |selections| {
5852 selections.select_anchor_ranges([target..target]);
5853 },
5854 );
5855 self.clear_row_highlights::<EditPredictionPreview>();
5856
5857 self.edit_prediction_preview
5858 .set_previous_scroll_position(None);
5859 } else {
5860 self.edit_prediction_preview
5861 .set_previous_scroll_position(Some(
5862 position_map.snapshot.scroll_anchor,
5863 ));
5864
5865 self.highlight_rows::<EditPredictionPreview>(
5866 target..target,
5867 cx.theme().colors().editor_highlighted_line_background,
5868 true,
5869 cx,
5870 );
5871 self.request_autoscroll(Autoscroll::fit(), cx);
5872 }
5873 }
5874 }
5875 InlineCompletion::Edit { edits, .. } => {
5876 if let Some(provider) = self.edit_prediction_provider() {
5877 provider.accept(cx);
5878 }
5879
5880 let snapshot = self.buffer.read(cx).snapshot(cx);
5881 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5882
5883 self.buffer.update(cx, |buffer, cx| {
5884 buffer.edit(edits.iter().cloned(), None, cx)
5885 });
5886
5887 self.change_selections(None, window, cx, |s| {
5888 s.select_anchor_ranges([last_edit_end..last_edit_end])
5889 });
5890
5891 self.update_visible_inline_completion(window, cx);
5892 if self.active_inline_completion.is_none() {
5893 self.refresh_inline_completion(true, true, window, cx);
5894 }
5895
5896 cx.notify();
5897 }
5898 }
5899
5900 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5901 }
5902
5903 pub fn accept_partial_inline_completion(
5904 &mut self,
5905 _: &AcceptPartialEditPrediction,
5906 window: &mut Window,
5907 cx: &mut Context<Self>,
5908 ) {
5909 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5910 return;
5911 };
5912 if self.selections.count() != 1 {
5913 return;
5914 }
5915
5916 self.report_inline_completion_event(
5917 active_inline_completion.completion_id.clone(),
5918 true,
5919 cx,
5920 );
5921
5922 match &active_inline_completion.completion {
5923 InlineCompletion::Move { target, .. } => {
5924 let target = *target;
5925 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5926 selections.select_anchor_ranges([target..target]);
5927 });
5928 }
5929 InlineCompletion::Edit { edits, .. } => {
5930 // Find an insertion that starts at the cursor position.
5931 let snapshot = self.buffer.read(cx).snapshot(cx);
5932 let cursor_offset = self.selections.newest::<usize>(cx).head();
5933 let insertion = edits.iter().find_map(|(range, text)| {
5934 let range = range.to_offset(&snapshot);
5935 if range.is_empty() && range.start == cursor_offset {
5936 Some(text)
5937 } else {
5938 None
5939 }
5940 });
5941
5942 if let Some(text) = insertion {
5943 let mut partial_completion = text
5944 .chars()
5945 .by_ref()
5946 .take_while(|c| c.is_alphabetic())
5947 .collect::<String>();
5948 if partial_completion.is_empty() {
5949 partial_completion = text
5950 .chars()
5951 .by_ref()
5952 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5953 .collect::<String>();
5954 }
5955
5956 cx.emit(EditorEvent::InputHandled {
5957 utf16_range_to_replace: None,
5958 text: partial_completion.clone().into(),
5959 });
5960
5961 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5962
5963 self.refresh_inline_completion(true, true, window, cx);
5964 cx.notify();
5965 } else {
5966 self.accept_edit_prediction(&Default::default(), window, cx);
5967 }
5968 }
5969 }
5970 }
5971
5972 fn discard_inline_completion(
5973 &mut self,
5974 should_report_inline_completion_event: bool,
5975 cx: &mut Context<Self>,
5976 ) -> bool {
5977 if should_report_inline_completion_event {
5978 let completion_id = self
5979 .active_inline_completion
5980 .as_ref()
5981 .and_then(|active_completion| active_completion.completion_id.clone());
5982
5983 self.report_inline_completion_event(completion_id, false, cx);
5984 }
5985
5986 if let Some(provider) = self.edit_prediction_provider() {
5987 provider.discard(cx);
5988 }
5989
5990 self.take_active_inline_completion(cx)
5991 }
5992
5993 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5994 let Some(provider) = self.edit_prediction_provider() else {
5995 return;
5996 };
5997
5998 let Some((_, buffer, _)) = self
5999 .buffer
6000 .read(cx)
6001 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6002 else {
6003 return;
6004 };
6005
6006 let extension = buffer
6007 .read(cx)
6008 .file()
6009 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6010
6011 let event_type = match accepted {
6012 true => "Edit Prediction Accepted",
6013 false => "Edit Prediction Discarded",
6014 };
6015 telemetry::event!(
6016 event_type,
6017 provider = provider.name(),
6018 prediction_id = id,
6019 suggestion_accepted = accepted,
6020 file_extension = extension,
6021 );
6022 }
6023
6024 pub fn has_active_inline_completion(&self) -> bool {
6025 self.active_inline_completion.is_some()
6026 }
6027
6028 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6029 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6030 return false;
6031 };
6032
6033 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6034 self.clear_highlights::<InlineCompletionHighlight>(cx);
6035 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6036 true
6037 }
6038
6039 /// Returns true when we're displaying the edit prediction popover below the cursor
6040 /// like we are not previewing and the LSP autocomplete menu is visible
6041 /// or we are in `when_holding_modifier` mode.
6042 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6043 if self.edit_prediction_preview_is_active()
6044 || !self.show_edit_predictions_in_menu()
6045 || !self.edit_predictions_enabled()
6046 {
6047 return false;
6048 }
6049
6050 if self.has_visible_completions_menu() {
6051 return true;
6052 }
6053
6054 has_completion && self.edit_prediction_requires_modifier()
6055 }
6056
6057 fn handle_modifiers_changed(
6058 &mut self,
6059 modifiers: Modifiers,
6060 position_map: &PositionMap,
6061 window: &mut Window,
6062 cx: &mut Context<Self>,
6063 ) {
6064 if self.show_edit_predictions_in_menu() {
6065 self.update_edit_prediction_preview(&modifiers, window, cx);
6066 }
6067
6068 self.update_selection_mode(&modifiers, position_map, window, cx);
6069
6070 let mouse_position = window.mouse_position();
6071 if !position_map.text_hitbox.is_hovered(window) {
6072 return;
6073 }
6074
6075 self.update_hovered_link(
6076 position_map.point_for_position(mouse_position),
6077 &position_map.snapshot,
6078 modifiers,
6079 window,
6080 cx,
6081 )
6082 }
6083
6084 fn update_selection_mode(
6085 &mut self,
6086 modifiers: &Modifiers,
6087 position_map: &PositionMap,
6088 window: &mut Window,
6089 cx: &mut Context<Self>,
6090 ) {
6091 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6092 return;
6093 }
6094
6095 let mouse_position = window.mouse_position();
6096 let point_for_position = position_map.point_for_position(mouse_position);
6097 let position = point_for_position.previous_valid;
6098
6099 self.select(
6100 SelectPhase::BeginColumnar {
6101 position,
6102 reset: false,
6103 goal_column: point_for_position.exact_unclipped.column(),
6104 },
6105 window,
6106 cx,
6107 );
6108 }
6109
6110 fn update_edit_prediction_preview(
6111 &mut self,
6112 modifiers: &Modifiers,
6113 window: &mut Window,
6114 cx: &mut Context<Self>,
6115 ) {
6116 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6117 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6118 return;
6119 };
6120
6121 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6122 if matches!(
6123 self.edit_prediction_preview,
6124 EditPredictionPreview::Inactive { .. }
6125 ) {
6126 self.edit_prediction_preview = EditPredictionPreview::Active {
6127 previous_scroll_position: None,
6128 since: Instant::now(),
6129 };
6130
6131 self.update_visible_inline_completion(window, cx);
6132 cx.notify();
6133 }
6134 } else if let EditPredictionPreview::Active {
6135 previous_scroll_position,
6136 since,
6137 } = self.edit_prediction_preview
6138 {
6139 if let (Some(previous_scroll_position), Some(position_map)) =
6140 (previous_scroll_position, self.last_position_map.as_ref())
6141 {
6142 self.set_scroll_position(
6143 previous_scroll_position
6144 .scroll_position(&position_map.snapshot.display_snapshot),
6145 window,
6146 cx,
6147 );
6148 }
6149
6150 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6151 released_too_fast: since.elapsed() < Duration::from_millis(200),
6152 };
6153 self.clear_row_highlights::<EditPredictionPreview>();
6154 self.update_visible_inline_completion(window, cx);
6155 cx.notify();
6156 }
6157 }
6158
6159 fn update_visible_inline_completion(
6160 &mut self,
6161 _window: &mut Window,
6162 cx: &mut Context<Self>,
6163 ) -> Option<()> {
6164 let selection = self.selections.newest_anchor();
6165 let cursor = selection.head();
6166 let multibuffer = self.buffer.read(cx).snapshot(cx);
6167 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6168 let excerpt_id = cursor.excerpt_id;
6169
6170 let show_in_menu = self.show_edit_predictions_in_menu();
6171 let completions_menu_has_precedence = !show_in_menu
6172 && (self.context_menu.borrow().is_some()
6173 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6174
6175 if completions_menu_has_precedence
6176 || !offset_selection.is_empty()
6177 || self
6178 .active_inline_completion
6179 .as_ref()
6180 .map_or(false, |completion| {
6181 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6182 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6183 !invalidation_range.contains(&offset_selection.head())
6184 })
6185 {
6186 self.discard_inline_completion(false, cx);
6187 return None;
6188 }
6189
6190 self.take_active_inline_completion(cx);
6191 let Some(provider) = self.edit_prediction_provider() else {
6192 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6193 return None;
6194 };
6195
6196 let (buffer, cursor_buffer_position) =
6197 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6198
6199 self.edit_prediction_settings =
6200 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6201
6202 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6203
6204 if self.edit_prediction_indent_conflict {
6205 let cursor_point = cursor.to_point(&multibuffer);
6206
6207 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6208
6209 if let Some((_, indent)) = indents.iter().next() {
6210 if indent.len == cursor_point.column {
6211 self.edit_prediction_indent_conflict = false;
6212 }
6213 }
6214 }
6215
6216 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6217 let edits = inline_completion
6218 .edits
6219 .into_iter()
6220 .flat_map(|(range, new_text)| {
6221 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6222 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6223 Some((start..end, new_text))
6224 })
6225 .collect::<Vec<_>>();
6226 if edits.is_empty() {
6227 return None;
6228 }
6229
6230 let first_edit_start = edits.first().unwrap().0.start;
6231 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6232 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6233
6234 let last_edit_end = edits.last().unwrap().0.end;
6235 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6236 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6237
6238 let cursor_row = cursor.to_point(&multibuffer).row;
6239
6240 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6241
6242 let mut inlay_ids = Vec::new();
6243 let invalidation_row_range;
6244 let move_invalidation_row_range = if cursor_row < edit_start_row {
6245 Some(cursor_row..edit_end_row)
6246 } else if cursor_row > edit_end_row {
6247 Some(edit_start_row..cursor_row)
6248 } else {
6249 None
6250 };
6251 let is_move =
6252 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6253 let completion = if is_move {
6254 invalidation_row_range =
6255 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6256 let target = first_edit_start;
6257 InlineCompletion::Move { target, snapshot }
6258 } else {
6259 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6260 && !self.inline_completions_hidden_for_vim_mode;
6261
6262 if show_completions_in_buffer {
6263 if edits
6264 .iter()
6265 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6266 {
6267 let mut inlays = Vec::new();
6268 for (range, new_text) in &edits {
6269 let inlay = Inlay::inline_completion(
6270 post_inc(&mut self.next_inlay_id),
6271 range.start,
6272 new_text.as_str(),
6273 );
6274 inlay_ids.push(inlay.id);
6275 inlays.push(inlay);
6276 }
6277
6278 self.splice_inlays(&[], inlays, cx);
6279 } else {
6280 let background_color = cx.theme().status().deleted_background;
6281 self.highlight_text::<InlineCompletionHighlight>(
6282 edits.iter().map(|(range, _)| range.clone()).collect(),
6283 HighlightStyle {
6284 background_color: Some(background_color),
6285 ..Default::default()
6286 },
6287 cx,
6288 );
6289 }
6290 }
6291
6292 invalidation_row_range = edit_start_row..edit_end_row;
6293
6294 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6295 if provider.show_tab_accept_marker() {
6296 EditDisplayMode::TabAccept
6297 } else {
6298 EditDisplayMode::Inline
6299 }
6300 } else {
6301 EditDisplayMode::DiffPopover
6302 };
6303
6304 InlineCompletion::Edit {
6305 edits,
6306 edit_preview: inline_completion.edit_preview,
6307 display_mode,
6308 snapshot,
6309 }
6310 };
6311
6312 let invalidation_range = multibuffer
6313 .anchor_before(Point::new(invalidation_row_range.start, 0))
6314 ..multibuffer.anchor_after(Point::new(
6315 invalidation_row_range.end,
6316 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6317 ));
6318
6319 self.stale_inline_completion_in_menu = None;
6320 self.active_inline_completion = Some(InlineCompletionState {
6321 inlay_ids,
6322 completion,
6323 completion_id: inline_completion.id,
6324 invalidation_range,
6325 });
6326
6327 cx.notify();
6328
6329 Some(())
6330 }
6331
6332 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6333 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6334 }
6335
6336 fn render_code_actions_indicator(
6337 &self,
6338 _style: &EditorStyle,
6339 row: DisplayRow,
6340 is_active: bool,
6341 breakpoint: Option<&(Anchor, Breakpoint)>,
6342 cx: &mut Context<Self>,
6343 ) -> Option<IconButton> {
6344 let color = Color::Muted;
6345 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6346 let show_tooltip = !self.context_menu_visible();
6347
6348 if self.available_code_actions.is_some() {
6349 Some(
6350 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6351 .shape(ui::IconButtonShape::Square)
6352 .icon_size(IconSize::XSmall)
6353 .icon_color(color)
6354 .toggle_state(is_active)
6355 .when(show_tooltip, |this| {
6356 this.tooltip({
6357 let focus_handle = self.focus_handle.clone();
6358 move |window, cx| {
6359 Tooltip::for_action_in(
6360 "Toggle Code Actions",
6361 &ToggleCodeActions {
6362 deployed_from_indicator: None,
6363 },
6364 &focus_handle,
6365 window,
6366 cx,
6367 )
6368 }
6369 })
6370 })
6371 .on_click(cx.listener(move |editor, _e, window, cx| {
6372 window.focus(&editor.focus_handle(cx));
6373 editor.toggle_code_actions(
6374 &ToggleCodeActions {
6375 deployed_from_indicator: Some(row),
6376 },
6377 window,
6378 cx,
6379 );
6380 }))
6381 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6382 editor.set_breakpoint_context_menu(
6383 row,
6384 position,
6385 event.down.position,
6386 window,
6387 cx,
6388 );
6389 })),
6390 )
6391 } else {
6392 None
6393 }
6394 }
6395
6396 fn clear_tasks(&mut self) {
6397 self.tasks.clear()
6398 }
6399
6400 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6401 if self.tasks.insert(key, value).is_some() {
6402 // This case should hopefully be rare, but just in case...
6403 log::error!(
6404 "multiple different run targets found on a single line, only the last target will be rendered"
6405 )
6406 }
6407 }
6408
6409 /// Get all display points of breakpoints that will be rendered within editor
6410 ///
6411 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6412 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6413 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6414 fn active_breakpoints(
6415 &self,
6416 range: Range<DisplayRow>,
6417 window: &mut Window,
6418 cx: &mut Context<Self>,
6419 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6420 let mut breakpoint_display_points = HashMap::default();
6421
6422 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6423 return breakpoint_display_points;
6424 };
6425
6426 let snapshot = self.snapshot(window, cx);
6427
6428 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6429 let Some(project) = self.project.as_ref() else {
6430 return breakpoint_display_points;
6431 };
6432
6433 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6434 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6435
6436 for (buffer_snapshot, range, excerpt_id) in
6437 multi_buffer_snapshot.range_to_buffer_ranges(range)
6438 {
6439 let Some(buffer) = project.read_with(cx, |this, cx| {
6440 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6441 }) else {
6442 continue;
6443 };
6444 let breakpoints = breakpoint_store.read(cx).breakpoints(
6445 &buffer,
6446 Some(
6447 buffer_snapshot.anchor_before(range.start)
6448 ..buffer_snapshot.anchor_after(range.end),
6449 ),
6450 buffer_snapshot,
6451 cx,
6452 );
6453 for (anchor, breakpoint) in breakpoints {
6454 let multi_buffer_anchor =
6455 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6456 let position = multi_buffer_anchor
6457 .to_point(&multi_buffer_snapshot)
6458 .to_display_point(&snapshot);
6459
6460 breakpoint_display_points
6461 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6462 }
6463 }
6464
6465 breakpoint_display_points
6466 }
6467
6468 fn breakpoint_context_menu(
6469 &self,
6470 anchor: Anchor,
6471 window: &mut Window,
6472 cx: &mut Context<Self>,
6473 ) -> Entity<ui::ContextMenu> {
6474 let weak_editor = cx.weak_entity();
6475 let focus_handle = self.focus_handle(cx);
6476
6477 let row = self
6478 .buffer
6479 .read(cx)
6480 .snapshot(cx)
6481 .summary_for_anchor::<Point>(&anchor)
6482 .row;
6483
6484 let breakpoint = self
6485 .breakpoint_at_row(row, window, cx)
6486 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6487
6488 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6489 "Edit Log Breakpoint"
6490 } else {
6491 "Set Log Breakpoint"
6492 };
6493
6494 let condition_breakpoint_msg = if breakpoint
6495 .as_ref()
6496 .is_some_and(|bp| bp.1.condition.is_some())
6497 {
6498 "Edit Condition Breakpoint"
6499 } else {
6500 "Set Condition Breakpoint"
6501 };
6502
6503 let hit_condition_breakpoint_msg = if breakpoint
6504 .as_ref()
6505 .is_some_and(|bp| bp.1.hit_condition.is_some())
6506 {
6507 "Edit Hit Condition Breakpoint"
6508 } else {
6509 "Set Hit Condition Breakpoint"
6510 };
6511
6512 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6513 "Unset Breakpoint"
6514 } else {
6515 "Set Breakpoint"
6516 };
6517
6518 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6519 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6520
6521 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6522 BreakpointState::Enabled => Some("Disable"),
6523 BreakpointState::Disabled => Some("Enable"),
6524 });
6525
6526 let (anchor, breakpoint) =
6527 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6528
6529 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6530 menu.on_blur_subscription(Subscription::new(|| {}))
6531 .context(focus_handle)
6532 .when(run_to_cursor, |this| {
6533 let weak_editor = weak_editor.clone();
6534 this.entry("Run to cursor", None, move |window, cx| {
6535 weak_editor
6536 .update(cx, |editor, cx| {
6537 editor.change_selections(None, window, cx, |s| {
6538 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6539 });
6540 })
6541 .ok();
6542
6543 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6544 })
6545 .separator()
6546 })
6547 .when_some(toggle_state_msg, |this, msg| {
6548 this.entry(msg, None, {
6549 let weak_editor = weak_editor.clone();
6550 let breakpoint = breakpoint.clone();
6551 move |_window, cx| {
6552 weak_editor
6553 .update(cx, |this, cx| {
6554 this.edit_breakpoint_at_anchor(
6555 anchor,
6556 breakpoint.as_ref().clone(),
6557 BreakpointEditAction::InvertState,
6558 cx,
6559 );
6560 })
6561 .log_err();
6562 }
6563 })
6564 })
6565 .entry(set_breakpoint_msg, None, {
6566 let weak_editor = weak_editor.clone();
6567 let breakpoint = breakpoint.clone();
6568 move |_window, cx| {
6569 weak_editor
6570 .update(cx, |this, cx| {
6571 this.edit_breakpoint_at_anchor(
6572 anchor,
6573 breakpoint.as_ref().clone(),
6574 BreakpointEditAction::Toggle,
6575 cx,
6576 );
6577 })
6578 .log_err();
6579 }
6580 })
6581 .entry(log_breakpoint_msg, None, {
6582 let breakpoint = breakpoint.clone();
6583 let weak_editor = weak_editor.clone();
6584 move |window, cx| {
6585 weak_editor
6586 .update(cx, |this, cx| {
6587 this.add_edit_breakpoint_block(
6588 anchor,
6589 breakpoint.as_ref(),
6590 BreakpointPromptEditAction::Log,
6591 window,
6592 cx,
6593 );
6594 })
6595 .log_err();
6596 }
6597 })
6598 .entry(condition_breakpoint_msg, None, {
6599 let breakpoint = breakpoint.clone();
6600 let weak_editor = weak_editor.clone();
6601 move |window, cx| {
6602 weak_editor
6603 .update(cx, |this, cx| {
6604 this.add_edit_breakpoint_block(
6605 anchor,
6606 breakpoint.as_ref(),
6607 BreakpointPromptEditAction::Condition,
6608 window,
6609 cx,
6610 );
6611 })
6612 .log_err();
6613 }
6614 })
6615 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6616 weak_editor
6617 .update(cx, |this, cx| {
6618 this.add_edit_breakpoint_block(
6619 anchor,
6620 breakpoint.as_ref(),
6621 BreakpointPromptEditAction::HitCondition,
6622 window,
6623 cx,
6624 );
6625 })
6626 .log_err();
6627 })
6628 })
6629 }
6630
6631 fn render_breakpoint(
6632 &self,
6633 position: Anchor,
6634 row: DisplayRow,
6635 breakpoint: &Breakpoint,
6636 cx: &mut Context<Self>,
6637 ) -> IconButton {
6638 let (color, icon) = {
6639 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6640 (false, false) => ui::IconName::DebugBreakpoint,
6641 (true, false) => ui::IconName::DebugLogBreakpoint,
6642 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6643 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6644 };
6645
6646 let color = if self
6647 .gutter_breakpoint_indicator
6648 .0
6649 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6650 {
6651 Color::Hint
6652 } else {
6653 Color::Debugger
6654 };
6655
6656 (color, icon)
6657 };
6658
6659 let breakpoint = Arc::from(breakpoint.clone());
6660
6661 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6662 .icon_size(IconSize::XSmall)
6663 .size(ui::ButtonSize::None)
6664 .icon_color(color)
6665 .style(ButtonStyle::Transparent)
6666 .on_click(cx.listener({
6667 let breakpoint = breakpoint.clone();
6668
6669 move |editor, event: &ClickEvent, window, cx| {
6670 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6671 BreakpointEditAction::InvertState
6672 } else {
6673 BreakpointEditAction::Toggle
6674 };
6675
6676 window.focus(&editor.focus_handle(cx));
6677 editor.edit_breakpoint_at_anchor(
6678 position,
6679 breakpoint.as_ref().clone(),
6680 edit_action,
6681 cx,
6682 );
6683 }
6684 }))
6685 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6686 editor.set_breakpoint_context_menu(
6687 row,
6688 Some(position),
6689 event.down.position,
6690 window,
6691 cx,
6692 );
6693 }))
6694 }
6695
6696 fn build_tasks_context(
6697 project: &Entity<Project>,
6698 buffer: &Entity<Buffer>,
6699 buffer_row: u32,
6700 tasks: &Arc<RunnableTasks>,
6701 cx: &mut Context<Self>,
6702 ) -> Task<Option<task::TaskContext>> {
6703 let position = Point::new(buffer_row, tasks.column);
6704 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6705 let location = Location {
6706 buffer: buffer.clone(),
6707 range: range_start..range_start,
6708 };
6709 // Fill in the environmental variables from the tree-sitter captures
6710 let mut captured_task_variables = TaskVariables::default();
6711 for (capture_name, value) in tasks.extra_variables.clone() {
6712 captured_task_variables.insert(
6713 task::VariableName::Custom(capture_name.into()),
6714 value.clone(),
6715 );
6716 }
6717 project.update(cx, |project, cx| {
6718 project.task_store().update(cx, |task_store, cx| {
6719 task_store.task_context_for_location(captured_task_variables, location, cx)
6720 })
6721 })
6722 }
6723
6724 pub fn spawn_nearest_task(
6725 &mut self,
6726 action: &SpawnNearestTask,
6727 window: &mut Window,
6728 cx: &mut Context<Self>,
6729 ) {
6730 let Some((workspace, _)) = self.workspace.clone() else {
6731 return;
6732 };
6733 let Some(project) = self.project.clone() else {
6734 return;
6735 };
6736
6737 // Try to find a closest, enclosing node using tree-sitter that has a
6738 // task
6739 let Some((buffer, buffer_row, tasks)) = self
6740 .find_enclosing_node_task(cx)
6741 // Or find the task that's closest in row-distance.
6742 .or_else(|| self.find_closest_task(cx))
6743 else {
6744 return;
6745 };
6746
6747 let reveal_strategy = action.reveal;
6748 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6749 cx.spawn_in(window, async move |_, cx| {
6750 let context = task_context.await?;
6751 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6752
6753 let resolved = resolved_task.resolved.as_mut()?;
6754 resolved.reveal = reveal_strategy;
6755
6756 workspace
6757 .update(cx, |workspace, cx| {
6758 workspace::tasks::schedule_resolved_task(
6759 workspace,
6760 task_source_kind,
6761 resolved_task,
6762 false,
6763 cx,
6764 );
6765 })
6766 .ok()
6767 })
6768 .detach();
6769 }
6770
6771 fn find_closest_task(
6772 &mut self,
6773 cx: &mut Context<Self>,
6774 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6775 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6776
6777 let ((buffer_id, row), tasks) = self
6778 .tasks
6779 .iter()
6780 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6781
6782 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6783 let tasks = Arc::new(tasks.to_owned());
6784 Some((buffer, *row, tasks))
6785 }
6786
6787 fn find_enclosing_node_task(
6788 &mut self,
6789 cx: &mut Context<Self>,
6790 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6791 let snapshot = self.buffer.read(cx).snapshot(cx);
6792 let offset = self.selections.newest::<usize>(cx).head();
6793 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6794 let buffer_id = excerpt.buffer().remote_id();
6795
6796 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6797 let mut cursor = layer.node().walk();
6798
6799 while cursor.goto_first_child_for_byte(offset).is_some() {
6800 if cursor.node().end_byte() == offset {
6801 cursor.goto_next_sibling();
6802 }
6803 }
6804
6805 // Ascend to the smallest ancestor that contains the range and has a task.
6806 loop {
6807 let node = cursor.node();
6808 let node_range = node.byte_range();
6809 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6810
6811 // Check if this node contains our offset
6812 if node_range.start <= offset && node_range.end >= offset {
6813 // If it contains offset, check for task
6814 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6815 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6816 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6817 }
6818 }
6819
6820 if !cursor.goto_parent() {
6821 break;
6822 }
6823 }
6824 None
6825 }
6826
6827 fn render_run_indicator(
6828 &self,
6829 _style: &EditorStyle,
6830 is_active: bool,
6831 row: DisplayRow,
6832 breakpoint: Option<(Anchor, Breakpoint)>,
6833 cx: &mut Context<Self>,
6834 ) -> IconButton {
6835 let color = Color::Muted;
6836 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6837
6838 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6839 .shape(ui::IconButtonShape::Square)
6840 .icon_size(IconSize::XSmall)
6841 .icon_color(color)
6842 .toggle_state(is_active)
6843 .on_click(cx.listener(move |editor, _e, window, cx| {
6844 window.focus(&editor.focus_handle(cx));
6845 editor.toggle_code_actions(
6846 &ToggleCodeActions {
6847 deployed_from_indicator: Some(row),
6848 },
6849 window,
6850 cx,
6851 );
6852 }))
6853 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6854 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6855 }))
6856 }
6857
6858 pub fn context_menu_visible(&self) -> bool {
6859 !self.edit_prediction_preview_is_active()
6860 && self
6861 .context_menu
6862 .borrow()
6863 .as_ref()
6864 .map_or(false, |menu| menu.visible())
6865 }
6866
6867 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6868 self.context_menu
6869 .borrow()
6870 .as_ref()
6871 .map(|menu| menu.origin())
6872 }
6873
6874 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6875 self.context_menu_options = Some(options);
6876 }
6877
6878 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6879 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6880
6881 fn render_edit_prediction_popover(
6882 &mut self,
6883 text_bounds: &Bounds<Pixels>,
6884 content_origin: gpui::Point<Pixels>,
6885 editor_snapshot: &EditorSnapshot,
6886 visible_row_range: Range<DisplayRow>,
6887 scroll_top: f32,
6888 scroll_bottom: f32,
6889 line_layouts: &[LineWithInvisibles],
6890 line_height: Pixels,
6891 scroll_pixel_position: gpui::Point<Pixels>,
6892 newest_selection_head: Option<DisplayPoint>,
6893 editor_width: Pixels,
6894 style: &EditorStyle,
6895 window: &mut Window,
6896 cx: &mut App,
6897 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6898 let active_inline_completion = self.active_inline_completion.as_ref()?;
6899
6900 if self.edit_prediction_visible_in_cursor_popover(true) {
6901 return None;
6902 }
6903
6904 match &active_inline_completion.completion {
6905 InlineCompletion::Move { target, .. } => {
6906 let target_display_point = target.to_display_point(editor_snapshot);
6907
6908 if self.edit_prediction_requires_modifier() {
6909 if !self.edit_prediction_preview_is_active() {
6910 return None;
6911 }
6912
6913 self.render_edit_prediction_modifier_jump_popover(
6914 text_bounds,
6915 content_origin,
6916 visible_row_range,
6917 line_layouts,
6918 line_height,
6919 scroll_pixel_position,
6920 newest_selection_head,
6921 target_display_point,
6922 window,
6923 cx,
6924 )
6925 } else {
6926 self.render_edit_prediction_eager_jump_popover(
6927 text_bounds,
6928 content_origin,
6929 editor_snapshot,
6930 visible_row_range,
6931 scroll_top,
6932 scroll_bottom,
6933 line_height,
6934 scroll_pixel_position,
6935 target_display_point,
6936 editor_width,
6937 window,
6938 cx,
6939 )
6940 }
6941 }
6942 InlineCompletion::Edit {
6943 display_mode: EditDisplayMode::Inline,
6944 ..
6945 } => None,
6946 InlineCompletion::Edit {
6947 display_mode: EditDisplayMode::TabAccept,
6948 edits,
6949 ..
6950 } => {
6951 let range = &edits.first()?.0;
6952 let target_display_point = range.end.to_display_point(editor_snapshot);
6953
6954 self.render_edit_prediction_end_of_line_popover(
6955 "Accept",
6956 editor_snapshot,
6957 visible_row_range,
6958 target_display_point,
6959 line_height,
6960 scroll_pixel_position,
6961 content_origin,
6962 editor_width,
6963 window,
6964 cx,
6965 )
6966 }
6967 InlineCompletion::Edit {
6968 edits,
6969 edit_preview,
6970 display_mode: EditDisplayMode::DiffPopover,
6971 snapshot,
6972 } => self.render_edit_prediction_diff_popover(
6973 text_bounds,
6974 content_origin,
6975 editor_snapshot,
6976 visible_row_range,
6977 line_layouts,
6978 line_height,
6979 scroll_pixel_position,
6980 newest_selection_head,
6981 editor_width,
6982 style,
6983 edits,
6984 edit_preview,
6985 snapshot,
6986 window,
6987 cx,
6988 ),
6989 }
6990 }
6991
6992 fn render_edit_prediction_modifier_jump_popover(
6993 &mut self,
6994 text_bounds: &Bounds<Pixels>,
6995 content_origin: gpui::Point<Pixels>,
6996 visible_row_range: Range<DisplayRow>,
6997 line_layouts: &[LineWithInvisibles],
6998 line_height: Pixels,
6999 scroll_pixel_position: gpui::Point<Pixels>,
7000 newest_selection_head: Option<DisplayPoint>,
7001 target_display_point: DisplayPoint,
7002 window: &mut Window,
7003 cx: &mut App,
7004 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7005 let scrolled_content_origin =
7006 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7007
7008 const SCROLL_PADDING_Y: Pixels = px(12.);
7009
7010 if target_display_point.row() < visible_row_range.start {
7011 return self.render_edit_prediction_scroll_popover(
7012 |_| SCROLL_PADDING_Y,
7013 IconName::ArrowUp,
7014 visible_row_range,
7015 line_layouts,
7016 newest_selection_head,
7017 scrolled_content_origin,
7018 window,
7019 cx,
7020 );
7021 } else if target_display_point.row() >= visible_row_range.end {
7022 return self.render_edit_prediction_scroll_popover(
7023 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7024 IconName::ArrowDown,
7025 visible_row_range,
7026 line_layouts,
7027 newest_selection_head,
7028 scrolled_content_origin,
7029 window,
7030 cx,
7031 );
7032 }
7033
7034 const POLE_WIDTH: Pixels = px(2.);
7035
7036 let line_layout =
7037 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7038 let target_column = target_display_point.column() as usize;
7039
7040 let target_x = line_layout.x_for_index(target_column);
7041 let target_y =
7042 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7043
7044 let flag_on_right = target_x < text_bounds.size.width / 2.;
7045
7046 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7047 border_color.l += 0.001;
7048
7049 let mut element = v_flex()
7050 .items_end()
7051 .when(flag_on_right, |el| el.items_start())
7052 .child(if flag_on_right {
7053 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7054 .rounded_bl(px(0.))
7055 .rounded_tl(px(0.))
7056 .border_l_2()
7057 .border_color(border_color)
7058 } else {
7059 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7060 .rounded_br(px(0.))
7061 .rounded_tr(px(0.))
7062 .border_r_2()
7063 .border_color(border_color)
7064 })
7065 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7066 .into_any();
7067
7068 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7069
7070 let mut origin = scrolled_content_origin + point(target_x, target_y)
7071 - point(
7072 if flag_on_right {
7073 POLE_WIDTH
7074 } else {
7075 size.width - POLE_WIDTH
7076 },
7077 size.height - line_height,
7078 );
7079
7080 origin.x = origin.x.max(content_origin.x);
7081
7082 element.prepaint_at(origin, window, cx);
7083
7084 Some((element, origin))
7085 }
7086
7087 fn render_edit_prediction_scroll_popover(
7088 &mut self,
7089 to_y: impl Fn(Size<Pixels>) -> Pixels,
7090 scroll_icon: IconName,
7091 visible_row_range: Range<DisplayRow>,
7092 line_layouts: &[LineWithInvisibles],
7093 newest_selection_head: Option<DisplayPoint>,
7094 scrolled_content_origin: gpui::Point<Pixels>,
7095 window: &mut Window,
7096 cx: &mut App,
7097 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7098 let mut element = self
7099 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7100 .into_any();
7101
7102 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7103
7104 let cursor = newest_selection_head?;
7105 let cursor_row_layout =
7106 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7107 let cursor_column = cursor.column() as usize;
7108
7109 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7110
7111 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7112
7113 element.prepaint_at(origin, window, cx);
7114 Some((element, origin))
7115 }
7116
7117 fn render_edit_prediction_eager_jump_popover(
7118 &mut self,
7119 text_bounds: &Bounds<Pixels>,
7120 content_origin: gpui::Point<Pixels>,
7121 editor_snapshot: &EditorSnapshot,
7122 visible_row_range: Range<DisplayRow>,
7123 scroll_top: f32,
7124 scroll_bottom: f32,
7125 line_height: Pixels,
7126 scroll_pixel_position: gpui::Point<Pixels>,
7127 target_display_point: DisplayPoint,
7128 editor_width: Pixels,
7129 window: &mut Window,
7130 cx: &mut App,
7131 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7132 if target_display_point.row().as_f32() < scroll_top {
7133 let mut element = self
7134 .render_edit_prediction_line_popover(
7135 "Jump to Edit",
7136 Some(IconName::ArrowUp),
7137 window,
7138 cx,
7139 )?
7140 .into_any();
7141
7142 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7143 let offset = point(
7144 (text_bounds.size.width - size.width) / 2.,
7145 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7146 );
7147
7148 let origin = text_bounds.origin + offset;
7149 element.prepaint_at(origin, window, cx);
7150 Some((element, origin))
7151 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7152 let mut element = self
7153 .render_edit_prediction_line_popover(
7154 "Jump to Edit",
7155 Some(IconName::ArrowDown),
7156 window,
7157 cx,
7158 )?
7159 .into_any();
7160
7161 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7162 let offset = point(
7163 (text_bounds.size.width - size.width) / 2.,
7164 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7165 );
7166
7167 let origin = text_bounds.origin + offset;
7168 element.prepaint_at(origin, window, cx);
7169 Some((element, origin))
7170 } else {
7171 self.render_edit_prediction_end_of_line_popover(
7172 "Jump to Edit",
7173 editor_snapshot,
7174 visible_row_range,
7175 target_display_point,
7176 line_height,
7177 scroll_pixel_position,
7178 content_origin,
7179 editor_width,
7180 window,
7181 cx,
7182 )
7183 }
7184 }
7185
7186 fn render_edit_prediction_end_of_line_popover(
7187 self: &mut Editor,
7188 label: &'static str,
7189 editor_snapshot: &EditorSnapshot,
7190 visible_row_range: Range<DisplayRow>,
7191 target_display_point: DisplayPoint,
7192 line_height: Pixels,
7193 scroll_pixel_position: gpui::Point<Pixels>,
7194 content_origin: gpui::Point<Pixels>,
7195 editor_width: Pixels,
7196 window: &mut Window,
7197 cx: &mut App,
7198 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7199 let target_line_end = DisplayPoint::new(
7200 target_display_point.row(),
7201 editor_snapshot.line_len(target_display_point.row()),
7202 );
7203
7204 let mut element = self
7205 .render_edit_prediction_line_popover(label, None, window, cx)?
7206 .into_any();
7207
7208 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7209
7210 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7211
7212 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7213 let mut origin = start_point
7214 + line_origin
7215 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7216 origin.x = origin.x.max(content_origin.x);
7217
7218 let max_x = content_origin.x + editor_width - size.width;
7219
7220 if origin.x > max_x {
7221 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7222
7223 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7224 origin.y += offset;
7225 IconName::ArrowUp
7226 } else {
7227 origin.y -= offset;
7228 IconName::ArrowDown
7229 };
7230
7231 element = self
7232 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7233 .into_any();
7234
7235 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7236
7237 origin.x = content_origin.x + editor_width - size.width - px(2.);
7238 }
7239
7240 element.prepaint_at(origin, window, cx);
7241 Some((element, origin))
7242 }
7243
7244 fn render_edit_prediction_diff_popover(
7245 self: &Editor,
7246 text_bounds: &Bounds<Pixels>,
7247 content_origin: gpui::Point<Pixels>,
7248 editor_snapshot: &EditorSnapshot,
7249 visible_row_range: Range<DisplayRow>,
7250 line_layouts: &[LineWithInvisibles],
7251 line_height: Pixels,
7252 scroll_pixel_position: gpui::Point<Pixels>,
7253 newest_selection_head: Option<DisplayPoint>,
7254 editor_width: Pixels,
7255 style: &EditorStyle,
7256 edits: &Vec<(Range<Anchor>, String)>,
7257 edit_preview: &Option<language::EditPreview>,
7258 snapshot: &language::BufferSnapshot,
7259 window: &mut Window,
7260 cx: &mut App,
7261 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7262 let edit_start = edits
7263 .first()
7264 .unwrap()
7265 .0
7266 .start
7267 .to_display_point(editor_snapshot);
7268 let edit_end = edits
7269 .last()
7270 .unwrap()
7271 .0
7272 .end
7273 .to_display_point(editor_snapshot);
7274
7275 let is_visible = visible_row_range.contains(&edit_start.row())
7276 || visible_row_range.contains(&edit_end.row());
7277 if !is_visible {
7278 return None;
7279 }
7280
7281 let highlighted_edits =
7282 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7283
7284 let styled_text = highlighted_edits.to_styled_text(&style.text);
7285 let line_count = highlighted_edits.text.lines().count();
7286
7287 const BORDER_WIDTH: Pixels = px(1.);
7288
7289 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7290 let has_keybind = keybind.is_some();
7291
7292 let mut element = h_flex()
7293 .items_start()
7294 .child(
7295 h_flex()
7296 .bg(cx.theme().colors().editor_background)
7297 .border(BORDER_WIDTH)
7298 .shadow_sm()
7299 .border_color(cx.theme().colors().border)
7300 .rounded_l_lg()
7301 .when(line_count > 1, |el| el.rounded_br_lg())
7302 .pr_1()
7303 .child(styled_text),
7304 )
7305 .child(
7306 h_flex()
7307 .h(line_height + BORDER_WIDTH * 2.)
7308 .px_1p5()
7309 .gap_1()
7310 // Workaround: For some reason, there's a gap if we don't do this
7311 .ml(-BORDER_WIDTH)
7312 .shadow(smallvec![gpui::BoxShadow {
7313 color: gpui::black().opacity(0.05),
7314 offset: point(px(1.), px(1.)),
7315 blur_radius: px(2.),
7316 spread_radius: px(0.),
7317 }])
7318 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7319 .border(BORDER_WIDTH)
7320 .border_color(cx.theme().colors().border)
7321 .rounded_r_lg()
7322 .id("edit_prediction_diff_popover_keybind")
7323 .when(!has_keybind, |el| {
7324 let status_colors = cx.theme().status();
7325
7326 el.bg(status_colors.error_background)
7327 .border_color(status_colors.error.opacity(0.6))
7328 .child(Icon::new(IconName::Info).color(Color::Error))
7329 .cursor_default()
7330 .hoverable_tooltip(move |_window, cx| {
7331 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7332 })
7333 })
7334 .children(keybind),
7335 )
7336 .into_any();
7337
7338 let longest_row =
7339 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7340 let longest_line_width = if visible_row_range.contains(&longest_row) {
7341 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7342 } else {
7343 layout_line(
7344 longest_row,
7345 editor_snapshot,
7346 style,
7347 editor_width,
7348 |_| false,
7349 window,
7350 cx,
7351 )
7352 .width
7353 };
7354
7355 let viewport_bounds =
7356 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7357 right: -EditorElement::SCROLLBAR_WIDTH,
7358 ..Default::default()
7359 });
7360
7361 let x_after_longest =
7362 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7363 - scroll_pixel_position.x;
7364
7365 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7366
7367 // Fully visible if it can be displayed within the window (allow overlapping other
7368 // panes). However, this is only allowed if the popover starts within text_bounds.
7369 let can_position_to_the_right = x_after_longest < text_bounds.right()
7370 && x_after_longest + element_bounds.width < viewport_bounds.right();
7371
7372 let mut origin = if can_position_to_the_right {
7373 point(
7374 x_after_longest,
7375 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7376 - scroll_pixel_position.y,
7377 )
7378 } else {
7379 let cursor_row = newest_selection_head.map(|head| head.row());
7380 let above_edit = edit_start
7381 .row()
7382 .0
7383 .checked_sub(line_count as u32)
7384 .map(DisplayRow);
7385 let below_edit = Some(edit_end.row() + 1);
7386 let above_cursor =
7387 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7388 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7389
7390 // Place the edit popover adjacent to the edit if there is a location
7391 // available that is onscreen and does not obscure the cursor. Otherwise,
7392 // place it adjacent to the cursor.
7393 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7394 .into_iter()
7395 .flatten()
7396 .find(|&start_row| {
7397 let end_row = start_row + line_count as u32;
7398 visible_row_range.contains(&start_row)
7399 && visible_row_range.contains(&end_row)
7400 && cursor_row.map_or(true, |cursor_row| {
7401 !((start_row..end_row).contains(&cursor_row))
7402 })
7403 })?;
7404
7405 content_origin
7406 + point(
7407 -scroll_pixel_position.x,
7408 row_target.as_f32() * line_height - scroll_pixel_position.y,
7409 )
7410 };
7411
7412 origin.x -= BORDER_WIDTH;
7413
7414 window.defer_draw(element, origin, 1);
7415
7416 // Do not return an element, since it will already be drawn due to defer_draw.
7417 None
7418 }
7419
7420 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7421 px(30.)
7422 }
7423
7424 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7425 if self.read_only(cx) {
7426 cx.theme().players().read_only()
7427 } else {
7428 self.style.as_ref().unwrap().local_player
7429 }
7430 }
7431
7432 fn render_edit_prediction_accept_keybind(
7433 &self,
7434 window: &mut Window,
7435 cx: &App,
7436 ) -> Option<AnyElement> {
7437 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7438 let accept_keystroke = accept_binding.keystroke()?;
7439
7440 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7441
7442 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7443 Color::Accent
7444 } else {
7445 Color::Muted
7446 };
7447
7448 h_flex()
7449 .px_0p5()
7450 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7451 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7452 .text_size(TextSize::XSmall.rems(cx))
7453 .child(h_flex().children(ui::render_modifiers(
7454 &accept_keystroke.modifiers,
7455 PlatformStyle::platform(),
7456 Some(modifiers_color),
7457 Some(IconSize::XSmall.rems().into()),
7458 true,
7459 )))
7460 .when(is_platform_style_mac, |parent| {
7461 parent.child(accept_keystroke.key.clone())
7462 })
7463 .when(!is_platform_style_mac, |parent| {
7464 parent.child(
7465 Key::new(
7466 util::capitalize(&accept_keystroke.key),
7467 Some(Color::Default),
7468 )
7469 .size(Some(IconSize::XSmall.rems().into())),
7470 )
7471 })
7472 .into_any()
7473 .into()
7474 }
7475
7476 fn render_edit_prediction_line_popover(
7477 &self,
7478 label: impl Into<SharedString>,
7479 icon: Option<IconName>,
7480 window: &mut Window,
7481 cx: &App,
7482 ) -> Option<Stateful<Div>> {
7483 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7484
7485 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7486 let has_keybind = keybind.is_some();
7487
7488 let result = h_flex()
7489 .id("ep-line-popover")
7490 .py_0p5()
7491 .pl_1()
7492 .pr(padding_right)
7493 .gap_1()
7494 .rounded_md()
7495 .border_1()
7496 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7497 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7498 .shadow_sm()
7499 .when(!has_keybind, |el| {
7500 let status_colors = cx.theme().status();
7501
7502 el.bg(status_colors.error_background)
7503 .border_color(status_colors.error.opacity(0.6))
7504 .pl_2()
7505 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7506 .cursor_default()
7507 .hoverable_tooltip(move |_window, cx| {
7508 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7509 })
7510 })
7511 .children(keybind)
7512 .child(
7513 Label::new(label)
7514 .size(LabelSize::Small)
7515 .when(!has_keybind, |el| {
7516 el.color(cx.theme().status().error.into()).strikethrough()
7517 }),
7518 )
7519 .when(!has_keybind, |el| {
7520 el.child(
7521 h_flex().ml_1().child(
7522 Icon::new(IconName::Info)
7523 .size(IconSize::Small)
7524 .color(cx.theme().status().error.into()),
7525 ),
7526 )
7527 })
7528 .when_some(icon, |element, icon| {
7529 element.child(
7530 div()
7531 .mt(px(1.5))
7532 .child(Icon::new(icon).size(IconSize::Small)),
7533 )
7534 });
7535
7536 Some(result)
7537 }
7538
7539 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7540 let accent_color = cx.theme().colors().text_accent;
7541 let editor_bg_color = cx.theme().colors().editor_background;
7542 editor_bg_color.blend(accent_color.opacity(0.1))
7543 }
7544
7545 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7546 let accent_color = cx.theme().colors().text_accent;
7547 let editor_bg_color = cx.theme().colors().editor_background;
7548 editor_bg_color.blend(accent_color.opacity(0.6))
7549 }
7550
7551 fn render_edit_prediction_cursor_popover(
7552 &self,
7553 min_width: Pixels,
7554 max_width: Pixels,
7555 cursor_point: Point,
7556 style: &EditorStyle,
7557 accept_keystroke: Option<&gpui::Keystroke>,
7558 _window: &Window,
7559 cx: &mut Context<Editor>,
7560 ) -> Option<AnyElement> {
7561 let provider = self.edit_prediction_provider.as_ref()?;
7562
7563 if provider.provider.needs_terms_acceptance(cx) {
7564 return Some(
7565 h_flex()
7566 .min_w(min_width)
7567 .flex_1()
7568 .px_2()
7569 .py_1()
7570 .gap_3()
7571 .elevation_2(cx)
7572 .hover(|style| style.bg(cx.theme().colors().element_hover))
7573 .id("accept-terms")
7574 .cursor_pointer()
7575 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7576 .on_click(cx.listener(|this, _event, window, cx| {
7577 cx.stop_propagation();
7578 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7579 window.dispatch_action(
7580 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7581 cx,
7582 );
7583 }))
7584 .child(
7585 h_flex()
7586 .flex_1()
7587 .gap_2()
7588 .child(Icon::new(IconName::ZedPredict))
7589 .child(Label::new("Accept Terms of Service"))
7590 .child(div().w_full())
7591 .child(
7592 Icon::new(IconName::ArrowUpRight)
7593 .color(Color::Muted)
7594 .size(IconSize::Small),
7595 )
7596 .into_any_element(),
7597 )
7598 .into_any(),
7599 );
7600 }
7601
7602 let is_refreshing = provider.provider.is_refreshing(cx);
7603
7604 fn pending_completion_container() -> Div {
7605 h_flex()
7606 .h_full()
7607 .flex_1()
7608 .gap_2()
7609 .child(Icon::new(IconName::ZedPredict))
7610 }
7611
7612 let completion = match &self.active_inline_completion {
7613 Some(prediction) => {
7614 if !self.has_visible_completions_menu() {
7615 const RADIUS: Pixels = px(6.);
7616 const BORDER_WIDTH: Pixels = px(1.);
7617
7618 return Some(
7619 h_flex()
7620 .elevation_2(cx)
7621 .border(BORDER_WIDTH)
7622 .border_color(cx.theme().colors().border)
7623 .when(accept_keystroke.is_none(), |el| {
7624 el.border_color(cx.theme().status().error)
7625 })
7626 .rounded(RADIUS)
7627 .rounded_tl(px(0.))
7628 .overflow_hidden()
7629 .child(div().px_1p5().child(match &prediction.completion {
7630 InlineCompletion::Move { target, snapshot } => {
7631 use text::ToPoint as _;
7632 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7633 {
7634 Icon::new(IconName::ZedPredictDown)
7635 } else {
7636 Icon::new(IconName::ZedPredictUp)
7637 }
7638 }
7639 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7640 }))
7641 .child(
7642 h_flex()
7643 .gap_1()
7644 .py_1()
7645 .px_2()
7646 .rounded_r(RADIUS - BORDER_WIDTH)
7647 .border_l_1()
7648 .border_color(cx.theme().colors().border)
7649 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7650 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7651 el.child(
7652 Label::new("Hold")
7653 .size(LabelSize::Small)
7654 .when(accept_keystroke.is_none(), |el| {
7655 el.strikethrough()
7656 })
7657 .line_height_style(LineHeightStyle::UiLabel),
7658 )
7659 })
7660 .id("edit_prediction_cursor_popover_keybind")
7661 .when(accept_keystroke.is_none(), |el| {
7662 let status_colors = cx.theme().status();
7663
7664 el.bg(status_colors.error_background)
7665 .border_color(status_colors.error.opacity(0.6))
7666 .child(Icon::new(IconName::Info).color(Color::Error))
7667 .cursor_default()
7668 .hoverable_tooltip(move |_window, cx| {
7669 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7670 .into()
7671 })
7672 })
7673 .when_some(
7674 accept_keystroke.as_ref(),
7675 |el, accept_keystroke| {
7676 el.child(h_flex().children(ui::render_modifiers(
7677 &accept_keystroke.modifiers,
7678 PlatformStyle::platform(),
7679 Some(Color::Default),
7680 Some(IconSize::XSmall.rems().into()),
7681 false,
7682 )))
7683 },
7684 ),
7685 )
7686 .into_any(),
7687 );
7688 }
7689
7690 self.render_edit_prediction_cursor_popover_preview(
7691 prediction,
7692 cursor_point,
7693 style,
7694 cx,
7695 )?
7696 }
7697
7698 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7699 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7700 stale_completion,
7701 cursor_point,
7702 style,
7703 cx,
7704 )?,
7705
7706 None => {
7707 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7708 }
7709 },
7710
7711 None => pending_completion_container().child(Label::new("No Prediction")),
7712 };
7713
7714 let completion = if is_refreshing {
7715 completion
7716 .with_animation(
7717 "loading-completion",
7718 Animation::new(Duration::from_secs(2))
7719 .repeat()
7720 .with_easing(pulsating_between(0.4, 0.8)),
7721 |label, delta| label.opacity(delta),
7722 )
7723 .into_any_element()
7724 } else {
7725 completion.into_any_element()
7726 };
7727
7728 let has_completion = self.active_inline_completion.is_some();
7729
7730 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7731 Some(
7732 h_flex()
7733 .min_w(min_width)
7734 .max_w(max_width)
7735 .flex_1()
7736 .elevation_2(cx)
7737 .border_color(cx.theme().colors().border)
7738 .child(
7739 div()
7740 .flex_1()
7741 .py_1()
7742 .px_2()
7743 .overflow_hidden()
7744 .child(completion),
7745 )
7746 .when_some(accept_keystroke, |el, accept_keystroke| {
7747 if !accept_keystroke.modifiers.modified() {
7748 return el;
7749 }
7750
7751 el.child(
7752 h_flex()
7753 .h_full()
7754 .border_l_1()
7755 .rounded_r_lg()
7756 .border_color(cx.theme().colors().border)
7757 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7758 .gap_1()
7759 .py_1()
7760 .px_2()
7761 .child(
7762 h_flex()
7763 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7764 .when(is_platform_style_mac, |parent| parent.gap_1())
7765 .child(h_flex().children(ui::render_modifiers(
7766 &accept_keystroke.modifiers,
7767 PlatformStyle::platform(),
7768 Some(if !has_completion {
7769 Color::Muted
7770 } else {
7771 Color::Default
7772 }),
7773 None,
7774 false,
7775 ))),
7776 )
7777 .child(Label::new("Preview").into_any_element())
7778 .opacity(if has_completion { 1.0 } else { 0.4 }),
7779 )
7780 })
7781 .into_any(),
7782 )
7783 }
7784
7785 fn render_edit_prediction_cursor_popover_preview(
7786 &self,
7787 completion: &InlineCompletionState,
7788 cursor_point: Point,
7789 style: &EditorStyle,
7790 cx: &mut Context<Editor>,
7791 ) -> Option<Div> {
7792 use text::ToPoint as _;
7793
7794 fn render_relative_row_jump(
7795 prefix: impl Into<String>,
7796 current_row: u32,
7797 target_row: u32,
7798 ) -> Div {
7799 let (row_diff, arrow) = if target_row < current_row {
7800 (current_row - target_row, IconName::ArrowUp)
7801 } else {
7802 (target_row - current_row, IconName::ArrowDown)
7803 };
7804
7805 h_flex()
7806 .child(
7807 Label::new(format!("{}{}", prefix.into(), row_diff))
7808 .color(Color::Muted)
7809 .size(LabelSize::Small),
7810 )
7811 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7812 }
7813
7814 match &completion.completion {
7815 InlineCompletion::Move {
7816 target, snapshot, ..
7817 } => Some(
7818 h_flex()
7819 .px_2()
7820 .gap_2()
7821 .flex_1()
7822 .child(
7823 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7824 Icon::new(IconName::ZedPredictDown)
7825 } else {
7826 Icon::new(IconName::ZedPredictUp)
7827 },
7828 )
7829 .child(Label::new("Jump to Edit")),
7830 ),
7831
7832 InlineCompletion::Edit {
7833 edits,
7834 edit_preview,
7835 snapshot,
7836 display_mode: _,
7837 } => {
7838 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7839
7840 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7841 &snapshot,
7842 &edits,
7843 edit_preview.as_ref()?,
7844 true,
7845 cx,
7846 )
7847 .first_line_preview();
7848
7849 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7850 .with_default_highlights(&style.text, highlighted_edits.highlights);
7851
7852 let preview = h_flex()
7853 .gap_1()
7854 .min_w_16()
7855 .child(styled_text)
7856 .when(has_more_lines, |parent| parent.child("…"));
7857
7858 let left = if first_edit_row != cursor_point.row {
7859 render_relative_row_jump("", cursor_point.row, first_edit_row)
7860 .into_any_element()
7861 } else {
7862 Icon::new(IconName::ZedPredict).into_any_element()
7863 };
7864
7865 Some(
7866 h_flex()
7867 .h_full()
7868 .flex_1()
7869 .gap_2()
7870 .pr_1()
7871 .overflow_x_hidden()
7872 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7873 .child(left)
7874 .child(preview),
7875 )
7876 }
7877 }
7878 }
7879
7880 fn render_context_menu(
7881 &self,
7882 style: &EditorStyle,
7883 max_height_in_lines: u32,
7884 window: &mut Window,
7885 cx: &mut Context<Editor>,
7886 ) -> Option<AnyElement> {
7887 let menu = self.context_menu.borrow();
7888 let menu = menu.as_ref()?;
7889 if !menu.visible() {
7890 return None;
7891 };
7892 Some(menu.render(style, max_height_in_lines, window, cx))
7893 }
7894
7895 fn render_context_menu_aside(
7896 &mut self,
7897 max_size: Size<Pixels>,
7898 window: &mut Window,
7899 cx: &mut Context<Editor>,
7900 ) -> Option<AnyElement> {
7901 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7902 if menu.visible() {
7903 menu.render_aside(self, max_size, window, cx)
7904 } else {
7905 None
7906 }
7907 })
7908 }
7909
7910 fn hide_context_menu(
7911 &mut self,
7912 window: &mut Window,
7913 cx: &mut Context<Self>,
7914 ) -> Option<CodeContextMenu> {
7915 cx.notify();
7916 self.completion_tasks.clear();
7917 let context_menu = self.context_menu.borrow_mut().take();
7918 self.stale_inline_completion_in_menu.take();
7919 self.update_visible_inline_completion(window, cx);
7920 context_menu
7921 }
7922
7923 fn show_snippet_choices(
7924 &mut self,
7925 choices: &Vec<String>,
7926 selection: Range<Anchor>,
7927 cx: &mut Context<Self>,
7928 ) {
7929 if selection.start.buffer_id.is_none() {
7930 return;
7931 }
7932 let buffer_id = selection.start.buffer_id.unwrap();
7933 let buffer = self.buffer().read(cx).buffer(buffer_id);
7934 let id = post_inc(&mut self.next_completion_id);
7935
7936 if let Some(buffer) = buffer {
7937 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7938 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7939 ));
7940 }
7941 }
7942
7943 pub fn insert_snippet(
7944 &mut self,
7945 insertion_ranges: &[Range<usize>],
7946 snippet: Snippet,
7947 window: &mut Window,
7948 cx: &mut Context<Self>,
7949 ) -> Result<()> {
7950 struct Tabstop<T> {
7951 is_end_tabstop: bool,
7952 ranges: Vec<Range<T>>,
7953 choices: Option<Vec<String>>,
7954 }
7955
7956 let tabstops = self.buffer.update(cx, |buffer, cx| {
7957 let snippet_text: Arc<str> = snippet.text.clone().into();
7958 let edits = insertion_ranges
7959 .iter()
7960 .cloned()
7961 .map(|range| (range, snippet_text.clone()));
7962 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7963
7964 let snapshot = &*buffer.read(cx);
7965 let snippet = &snippet;
7966 snippet
7967 .tabstops
7968 .iter()
7969 .map(|tabstop| {
7970 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7971 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7972 });
7973 let mut tabstop_ranges = tabstop
7974 .ranges
7975 .iter()
7976 .flat_map(|tabstop_range| {
7977 let mut delta = 0_isize;
7978 insertion_ranges.iter().map(move |insertion_range| {
7979 let insertion_start = insertion_range.start as isize + delta;
7980 delta +=
7981 snippet.text.len() as isize - insertion_range.len() as isize;
7982
7983 let start = ((insertion_start + tabstop_range.start) as usize)
7984 .min(snapshot.len());
7985 let end = ((insertion_start + tabstop_range.end) as usize)
7986 .min(snapshot.len());
7987 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7988 })
7989 })
7990 .collect::<Vec<_>>();
7991 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7992
7993 Tabstop {
7994 is_end_tabstop,
7995 ranges: tabstop_ranges,
7996 choices: tabstop.choices.clone(),
7997 }
7998 })
7999 .collect::<Vec<_>>()
8000 });
8001 if let Some(tabstop) = tabstops.first() {
8002 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8003 s.select_ranges(tabstop.ranges.iter().cloned());
8004 });
8005
8006 if let Some(choices) = &tabstop.choices {
8007 if let Some(selection) = tabstop.ranges.first() {
8008 self.show_snippet_choices(choices, selection.clone(), cx)
8009 }
8010 }
8011
8012 // If we're already at the last tabstop and it's at the end of the snippet,
8013 // we're done, we don't need to keep the state around.
8014 if !tabstop.is_end_tabstop {
8015 let choices = tabstops
8016 .iter()
8017 .map(|tabstop| tabstop.choices.clone())
8018 .collect();
8019
8020 let ranges = tabstops
8021 .into_iter()
8022 .map(|tabstop| tabstop.ranges)
8023 .collect::<Vec<_>>();
8024
8025 self.snippet_stack.push(SnippetState {
8026 active_index: 0,
8027 ranges,
8028 choices,
8029 });
8030 }
8031
8032 // Check whether the just-entered snippet ends with an auto-closable bracket.
8033 if self.autoclose_regions.is_empty() {
8034 let snapshot = self.buffer.read(cx).snapshot(cx);
8035 for selection in &mut self.selections.all::<Point>(cx) {
8036 let selection_head = selection.head();
8037 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8038 continue;
8039 };
8040
8041 let mut bracket_pair = None;
8042 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8043 let prev_chars = snapshot
8044 .reversed_chars_at(selection_head)
8045 .collect::<String>();
8046 for (pair, enabled) in scope.brackets() {
8047 if enabled
8048 && pair.close
8049 && prev_chars.starts_with(pair.start.as_str())
8050 && next_chars.starts_with(pair.end.as_str())
8051 {
8052 bracket_pair = Some(pair.clone());
8053 break;
8054 }
8055 }
8056 if let Some(pair) = bracket_pair {
8057 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8058 let autoclose_enabled =
8059 self.use_autoclose && snapshot_settings.use_autoclose;
8060 if autoclose_enabled {
8061 let start = snapshot.anchor_after(selection_head);
8062 let end = snapshot.anchor_after(selection_head);
8063 self.autoclose_regions.push(AutocloseRegion {
8064 selection_id: selection.id,
8065 range: start..end,
8066 pair,
8067 });
8068 }
8069 }
8070 }
8071 }
8072 }
8073 Ok(())
8074 }
8075
8076 pub fn move_to_next_snippet_tabstop(
8077 &mut self,
8078 window: &mut Window,
8079 cx: &mut Context<Self>,
8080 ) -> bool {
8081 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8082 }
8083
8084 pub fn move_to_prev_snippet_tabstop(
8085 &mut self,
8086 window: &mut Window,
8087 cx: &mut Context<Self>,
8088 ) -> bool {
8089 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8090 }
8091
8092 pub fn move_to_snippet_tabstop(
8093 &mut self,
8094 bias: Bias,
8095 window: &mut Window,
8096 cx: &mut Context<Self>,
8097 ) -> bool {
8098 if let Some(mut snippet) = self.snippet_stack.pop() {
8099 match bias {
8100 Bias::Left => {
8101 if snippet.active_index > 0 {
8102 snippet.active_index -= 1;
8103 } else {
8104 self.snippet_stack.push(snippet);
8105 return false;
8106 }
8107 }
8108 Bias::Right => {
8109 if snippet.active_index + 1 < snippet.ranges.len() {
8110 snippet.active_index += 1;
8111 } else {
8112 self.snippet_stack.push(snippet);
8113 return false;
8114 }
8115 }
8116 }
8117 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8118 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8119 s.select_anchor_ranges(current_ranges.iter().cloned())
8120 });
8121
8122 if let Some(choices) = &snippet.choices[snippet.active_index] {
8123 if let Some(selection) = current_ranges.first() {
8124 self.show_snippet_choices(&choices, selection.clone(), cx);
8125 }
8126 }
8127
8128 // If snippet state is not at the last tabstop, push it back on the stack
8129 if snippet.active_index + 1 < snippet.ranges.len() {
8130 self.snippet_stack.push(snippet);
8131 }
8132 return true;
8133 }
8134 }
8135
8136 false
8137 }
8138
8139 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8140 self.transact(window, cx, |this, window, cx| {
8141 this.select_all(&SelectAll, window, cx);
8142 this.insert("", window, cx);
8143 });
8144 }
8145
8146 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8147 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8148 self.transact(window, cx, |this, window, cx| {
8149 this.select_autoclose_pair(window, cx);
8150 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8151 if !this.linked_edit_ranges.is_empty() {
8152 let selections = this.selections.all::<MultiBufferPoint>(cx);
8153 let snapshot = this.buffer.read(cx).snapshot(cx);
8154
8155 for selection in selections.iter() {
8156 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8157 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8158 if selection_start.buffer_id != selection_end.buffer_id {
8159 continue;
8160 }
8161 if let Some(ranges) =
8162 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8163 {
8164 for (buffer, entries) in ranges {
8165 linked_ranges.entry(buffer).or_default().extend(entries);
8166 }
8167 }
8168 }
8169 }
8170
8171 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8172 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8173 for selection in &mut selections {
8174 if selection.is_empty() {
8175 let old_head = selection.head();
8176 let mut new_head =
8177 movement::left(&display_map, old_head.to_display_point(&display_map))
8178 .to_point(&display_map);
8179 if let Some((buffer, line_buffer_range)) = display_map
8180 .buffer_snapshot
8181 .buffer_line_for_row(MultiBufferRow(old_head.row))
8182 {
8183 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8184 let indent_len = match indent_size.kind {
8185 IndentKind::Space => {
8186 buffer.settings_at(line_buffer_range.start, cx).tab_size
8187 }
8188 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8189 };
8190 if old_head.column <= indent_size.len && old_head.column > 0 {
8191 let indent_len = indent_len.get();
8192 new_head = cmp::min(
8193 new_head,
8194 MultiBufferPoint::new(
8195 old_head.row,
8196 ((old_head.column - 1) / indent_len) * indent_len,
8197 ),
8198 );
8199 }
8200 }
8201
8202 selection.set_head(new_head, SelectionGoal::None);
8203 }
8204 }
8205
8206 this.signature_help_state.set_backspace_pressed(true);
8207 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8208 s.select(selections)
8209 });
8210 this.insert("", window, cx);
8211 let empty_str: Arc<str> = Arc::from("");
8212 for (buffer, edits) in linked_ranges {
8213 let snapshot = buffer.read(cx).snapshot();
8214 use text::ToPoint as TP;
8215
8216 let edits = edits
8217 .into_iter()
8218 .map(|range| {
8219 let end_point = TP::to_point(&range.end, &snapshot);
8220 let mut start_point = TP::to_point(&range.start, &snapshot);
8221
8222 if end_point == start_point {
8223 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8224 .saturating_sub(1);
8225 start_point =
8226 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8227 };
8228
8229 (start_point..end_point, empty_str.clone())
8230 })
8231 .sorted_by_key(|(range, _)| range.start)
8232 .collect::<Vec<_>>();
8233 buffer.update(cx, |this, cx| {
8234 this.edit(edits, None, cx);
8235 })
8236 }
8237 this.refresh_inline_completion(true, false, window, cx);
8238 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8239 });
8240 }
8241
8242 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8243 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8244 self.transact(window, cx, |this, window, cx| {
8245 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8246 s.move_with(|map, selection| {
8247 if selection.is_empty() {
8248 let cursor = movement::right(map, selection.head());
8249 selection.end = cursor;
8250 selection.reversed = true;
8251 selection.goal = SelectionGoal::None;
8252 }
8253 })
8254 });
8255 this.insert("", window, cx);
8256 this.refresh_inline_completion(true, false, window, cx);
8257 });
8258 }
8259
8260 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8261 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8262 if self.move_to_prev_snippet_tabstop(window, cx) {
8263 return;
8264 }
8265 self.outdent(&Outdent, window, cx);
8266 }
8267
8268 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8269 if self.move_to_next_snippet_tabstop(window, cx) {
8270 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8271 return;
8272 }
8273 if self.read_only(cx) {
8274 return;
8275 }
8276 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8277 let mut selections = self.selections.all_adjusted(cx);
8278 let buffer = self.buffer.read(cx);
8279 let snapshot = buffer.snapshot(cx);
8280 let rows_iter = selections.iter().map(|s| s.head().row);
8281 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8282
8283 let mut edits = Vec::new();
8284 let mut prev_edited_row = 0;
8285 let mut row_delta = 0;
8286 for selection in &mut selections {
8287 if selection.start.row != prev_edited_row {
8288 row_delta = 0;
8289 }
8290 prev_edited_row = selection.end.row;
8291
8292 // If the selection is non-empty, then increase the indentation of the selected lines.
8293 if !selection.is_empty() {
8294 row_delta =
8295 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8296 continue;
8297 }
8298
8299 // If the selection is empty and the cursor is in the leading whitespace before the
8300 // suggested indentation, then auto-indent the line.
8301 let cursor = selection.head();
8302 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8303 if let Some(suggested_indent) =
8304 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8305 {
8306 if cursor.column < suggested_indent.len
8307 && cursor.column <= current_indent.len
8308 && current_indent.len <= suggested_indent.len
8309 {
8310 selection.start = Point::new(cursor.row, suggested_indent.len);
8311 selection.end = selection.start;
8312 if row_delta == 0 {
8313 edits.extend(Buffer::edit_for_indent_size_adjustment(
8314 cursor.row,
8315 current_indent,
8316 suggested_indent,
8317 ));
8318 row_delta = suggested_indent.len - current_indent.len;
8319 }
8320 continue;
8321 }
8322 }
8323
8324 // Otherwise, insert a hard or soft tab.
8325 let settings = buffer.language_settings_at(cursor, cx);
8326 let tab_size = if settings.hard_tabs {
8327 IndentSize::tab()
8328 } else {
8329 let tab_size = settings.tab_size.get();
8330 let indent_remainder = snapshot
8331 .text_for_range(Point::new(cursor.row, 0)..cursor)
8332 .flat_map(str::chars)
8333 .fold(row_delta % tab_size, |counter: u32, c| {
8334 if c == '\t' {
8335 0
8336 } else {
8337 (counter + 1) % tab_size
8338 }
8339 });
8340
8341 let chars_to_next_tab_stop = tab_size - indent_remainder;
8342 IndentSize::spaces(chars_to_next_tab_stop)
8343 };
8344 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8345 selection.end = selection.start;
8346 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8347 row_delta += tab_size.len;
8348 }
8349
8350 self.transact(window, cx, |this, window, cx| {
8351 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8352 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8353 s.select(selections)
8354 });
8355 this.refresh_inline_completion(true, false, window, cx);
8356 });
8357 }
8358
8359 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8360 if self.read_only(cx) {
8361 return;
8362 }
8363 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8364 let mut selections = self.selections.all::<Point>(cx);
8365 let mut prev_edited_row = 0;
8366 let mut row_delta = 0;
8367 let mut edits = Vec::new();
8368 let buffer = self.buffer.read(cx);
8369 let snapshot = buffer.snapshot(cx);
8370 for selection in &mut selections {
8371 if selection.start.row != prev_edited_row {
8372 row_delta = 0;
8373 }
8374 prev_edited_row = selection.end.row;
8375
8376 row_delta =
8377 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8378 }
8379
8380 self.transact(window, cx, |this, window, cx| {
8381 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8382 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8383 s.select(selections)
8384 });
8385 });
8386 }
8387
8388 fn indent_selection(
8389 buffer: &MultiBuffer,
8390 snapshot: &MultiBufferSnapshot,
8391 selection: &mut Selection<Point>,
8392 edits: &mut Vec<(Range<Point>, String)>,
8393 delta_for_start_row: u32,
8394 cx: &App,
8395 ) -> u32 {
8396 let settings = buffer.language_settings_at(selection.start, cx);
8397 let tab_size = settings.tab_size.get();
8398 let indent_kind = if settings.hard_tabs {
8399 IndentKind::Tab
8400 } else {
8401 IndentKind::Space
8402 };
8403 let mut start_row = selection.start.row;
8404 let mut end_row = selection.end.row + 1;
8405
8406 // If a selection ends at the beginning of a line, don't indent
8407 // that last line.
8408 if selection.end.column == 0 && selection.end.row > selection.start.row {
8409 end_row -= 1;
8410 }
8411
8412 // Avoid re-indenting a row that has already been indented by a
8413 // previous selection, but still update this selection's column
8414 // to reflect that indentation.
8415 if delta_for_start_row > 0 {
8416 start_row += 1;
8417 selection.start.column += delta_for_start_row;
8418 if selection.end.row == selection.start.row {
8419 selection.end.column += delta_for_start_row;
8420 }
8421 }
8422
8423 let mut delta_for_end_row = 0;
8424 let has_multiple_rows = start_row + 1 != end_row;
8425 for row in start_row..end_row {
8426 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8427 let indent_delta = match (current_indent.kind, indent_kind) {
8428 (IndentKind::Space, IndentKind::Space) => {
8429 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8430 IndentSize::spaces(columns_to_next_tab_stop)
8431 }
8432 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8433 (_, IndentKind::Tab) => IndentSize::tab(),
8434 };
8435
8436 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8437 0
8438 } else {
8439 selection.start.column
8440 };
8441 let row_start = Point::new(row, start);
8442 edits.push((
8443 row_start..row_start,
8444 indent_delta.chars().collect::<String>(),
8445 ));
8446
8447 // Update this selection's endpoints to reflect the indentation.
8448 if row == selection.start.row {
8449 selection.start.column += indent_delta.len;
8450 }
8451 if row == selection.end.row {
8452 selection.end.column += indent_delta.len;
8453 delta_for_end_row = indent_delta.len;
8454 }
8455 }
8456
8457 if selection.start.row == selection.end.row {
8458 delta_for_start_row + delta_for_end_row
8459 } else {
8460 delta_for_end_row
8461 }
8462 }
8463
8464 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8465 if self.read_only(cx) {
8466 return;
8467 }
8468 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8470 let selections = self.selections.all::<Point>(cx);
8471 let mut deletion_ranges = Vec::new();
8472 let mut last_outdent = None;
8473 {
8474 let buffer = self.buffer.read(cx);
8475 let snapshot = buffer.snapshot(cx);
8476 for selection in &selections {
8477 let settings = buffer.language_settings_at(selection.start, cx);
8478 let tab_size = settings.tab_size.get();
8479 let mut rows = selection.spanned_rows(false, &display_map);
8480
8481 // Avoid re-outdenting a row that has already been outdented by a
8482 // previous selection.
8483 if let Some(last_row) = last_outdent {
8484 if last_row == rows.start {
8485 rows.start = rows.start.next_row();
8486 }
8487 }
8488 let has_multiple_rows = rows.len() > 1;
8489 for row in rows.iter_rows() {
8490 let indent_size = snapshot.indent_size_for_line(row);
8491 if indent_size.len > 0 {
8492 let deletion_len = match indent_size.kind {
8493 IndentKind::Space => {
8494 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8495 if columns_to_prev_tab_stop == 0 {
8496 tab_size
8497 } else {
8498 columns_to_prev_tab_stop
8499 }
8500 }
8501 IndentKind::Tab => 1,
8502 };
8503 let start = if has_multiple_rows
8504 || deletion_len > selection.start.column
8505 || indent_size.len < selection.start.column
8506 {
8507 0
8508 } else {
8509 selection.start.column - deletion_len
8510 };
8511 deletion_ranges.push(
8512 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8513 );
8514 last_outdent = Some(row);
8515 }
8516 }
8517 }
8518 }
8519
8520 self.transact(window, cx, |this, window, cx| {
8521 this.buffer.update(cx, |buffer, cx| {
8522 let empty_str: Arc<str> = Arc::default();
8523 buffer.edit(
8524 deletion_ranges
8525 .into_iter()
8526 .map(|range| (range, empty_str.clone())),
8527 None,
8528 cx,
8529 );
8530 });
8531 let selections = this.selections.all::<usize>(cx);
8532 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8533 s.select(selections)
8534 });
8535 });
8536 }
8537
8538 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8539 if self.read_only(cx) {
8540 return;
8541 }
8542 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8543 let selections = self
8544 .selections
8545 .all::<usize>(cx)
8546 .into_iter()
8547 .map(|s| s.range());
8548
8549 self.transact(window, cx, |this, window, cx| {
8550 this.buffer.update(cx, |buffer, cx| {
8551 buffer.autoindent_ranges(selections, cx);
8552 });
8553 let selections = this.selections.all::<usize>(cx);
8554 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8555 s.select(selections)
8556 });
8557 });
8558 }
8559
8560 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8561 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8562 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8563 let selections = self.selections.all::<Point>(cx);
8564
8565 let mut new_cursors = Vec::new();
8566 let mut edit_ranges = Vec::new();
8567 let mut selections = selections.iter().peekable();
8568 while let Some(selection) = selections.next() {
8569 let mut rows = selection.spanned_rows(false, &display_map);
8570 let goal_display_column = selection.head().to_display_point(&display_map).column();
8571
8572 // Accumulate contiguous regions of rows that we want to delete.
8573 while let Some(next_selection) = selections.peek() {
8574 let next_rows = next_selection.spanned_rows(false, &display_map);
8575 if next_rows.start <= rows.end {
8576 rows.end = next_rows.end;
8577 selections.next().unwrap();
8578 } else {
8579 break;
8580 }
8581 }
8582
8583 let buffer = &display_map.buffer_snapshot;
8584 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8585 let edit_end;
8586 let cursor_buffer_row;
8587 if buffer.max_point().row >= rows.end.0 {
8588 // If there's a line after the range, delete the \n from the end of the row range
8589 // and position the cursor on the next line.
8590 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8591 cursor_buffer_row = rows.end;
8592 } else {
8593 // If there isn't a line after the range, delete the \n from the line before the
8594 // start of the row range and position the cursor there.
8595 edit_start = edit_start.saturating_sub(1);
8596 edit_end = buffer.len();
8597 cursor_buffer_row = rows.start.previous_row();
8598 }
8599
8600 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8601 *cursor.column_mut() =
8602 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8603
8604 new_cursors.push((
8605 selection.id,
8606 buffer.anchor_after(cursor.to_point(&display_map)),
8607 ));
8608 edit_ranges.push(edit_start..edit_end);
8609 }
8610
8611 self.transact(window, cx, |this, window, cx| {
8612 let buffer = this.buffer.update(cx, |buffer, cx| {
8613 let empty_str: Arc<str> = Arc::default();
8614 buffer.edit(
8615 edit_ranges
8616 .into_iter()
8617 .map(|range| (range, empty_str.clone())),
8618 None,
8619 cx,
8620 );
8621 buffer.snapshot(cx)
8622 });
8623 let new_selections = new_cursors
8624 .into_iter()
8625 .map(|(id, cursor)| {
8626 let cursor = cursor.to_point(&buffer);
8627 Selection {
8628 id,
8629 start: cursor,
8630 end: cursor,
8631 reversed: false,
8632 goal: SelectionGoal::None,
8633 }
8634 })
8635 .collect();
8636
8637 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8638 s.select(new_selections);
8639 });
8640 });
8641 }
8642
8643 pub fn join_lines_impl(
8644 &mut self,
8645 insert_whitespace: bool,
8646 window: &mut Window,
8647 cx: &mut Context<Self>,
8648 ) {
8649 if self.read_only(cx) {
8650 return;
8651 }
8652 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8653 for selection in self.selections.all::<Point>(cx) {
8654 let start = MultiBufferRow(selection.start.row);
8655 // Treat single line selections as if they include the next line. Otherwise this action
8656 // would do nothing for single line selections individual cursors.
8657 let end = if selection.start.row == selection.end.row {
8658 MultiBufferRow(selection.start.row + 1)
8659 } else {
8660 MultiBufferRow(selection.end.row)
8661 };
8662
8663 if let Some(last_row_range) = row_ranges.last_mut() {
8664 if start <= last_row_range.end {
8665 last_row_range.end = end;
8666 continue;
8667 }
8668 }
8669 row_ranges.push(start..end);
8670 }
8671
8672 let snapshot = self.buffer.read(cx).snapshot(cx);
8673 let mut cursor_positions = Vec::new();
8674 for row_range in &row_ranges {
8675 let anchor = snapshot.anchor_before(Point::new(
8676 row_range.end.previous_row().0,
8677 snapshot.line_len(row_range.end.previous_row()),
8678 ));
8679 cursor_positions.push(anchor..anchor);
8680 }
8681
8682 self.transact(window, cx, |this, window, cx| {
8683 for row_range in row_ranges.into_iter().rev() {
8684 for row in row_range.iter_rows().rev() {
8685 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8686 let next_line_row = row.next_row();
8687 let indent = snapshot.indent_size_for_line(next_line_row);
8688 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8689
8690 let replace =
8691 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8692 " "
8693 } else {
8694 ""
8695 };
8696
8697 this.buffer.update(cx, |buffer, cx| {
8698 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8699 });
8700 }
8701 }
8702
8703 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8704 s.select_anchor_ranges(cursor_positions)
8705 });
8706 });
8707 }
8708
8709 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8710 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8711 self.join_lines_impl(true, window, cx);
8712 }
8713
8714 pub fn sort_lines_case_sensitive(
8715 &mut self,
8716 _: &SortLinesCaseSensitive,
8717 window: &mut Window,
8718 cx: &mut Context<Self>,
8719 ) {
8720 self.manipulate_lines(window, cx, |lines| lines.sort())
8721 }
8722
8723 pub fn sort_lines_case_insensitive(
8724 &mut self,
8725 _: &SortLinesCaseInsensitive,
8726 window: &mut Window,
8727 cx: &mut Context<Self>,
8728 ) {
8729 self.manipulate_lines(window, cx, |lines| {
8730 lines.sort_by_key(|line| line.to_lowercase())
8731 })
8732 }
8733
8734 pub fn unique_lines_case_insensitive(
8735 &mut self,
8736 _: &UniqueLinesCaseInsensitive,
8737 window: &mut Window,
8738 cx: &mut Context<Self>,
8739 ) {
8740 self.manipulate_lines(window, cx, |lines| {
8741 let mut seen = HashSet::default();
8742 lines.retain(|line| seen.insert(line.to_lowercase()));
8743 })
8744 }
8745
8746 pub fn unique_lines_case_sensitive(
8747 &mut self,
8748 _: &UniqueLinesCaseSensitive,
8749 window: &mut Window,
8750 cx: &mut Context<Self>,
8751 ) {
8752 self.manipulate_lines(window, cx, |lines| {
8753 let mut seen = HashSet::default();
8754 lines.retain(|line| seen.insert(*line));
8755 })
8756 }
8757
8758 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8759 let Some(project) = self.project.clone() else {
8760 return;
8761 };
8762 self.reload(project, window, cx)
8763 .detach_and_notify_err(window, cx);
8764 }
8765
8766 pub fn restore_file(
8767 &mut self,
8768 _: &::git::RestoreFile,
8769 window: &mut Window,
8770 cx: &mut Context<Self>,
8771 ) {
8772 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8773 let mut buffer_ids = HashSet::default();
8774 let snapshot = self.buffer().read(cx).snapshot(cx);
8775 for selection in self.selections.all::<usize>(cx) {
8776 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8777 }
8778
8779 let buffer = self.buffer().read(cx);
8780 let ranges = buffer_ids
8781 .into_iter()
8782 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8783 .collect::<Vec<_>>();
8784
8785 self.restore_hunks_in_ranges(ranges, window, cx);
8786 }
8787
8788 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8789 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8790 let selections = self
8791 .selections
8792 .all(cx)
8793 .into_iter()
8794 .map(|s| s.range())
8795 .collect();
8796 self.restore_hunks_in_ranges(selections, window, cx);
8797 }
8798
8799 pub fn restore_hunks_in_ranges(
8800 &mut self,
8801 ranges: Vec<Range<Point>>,
8802 window: &mut Window,
8803 cx: &mut Context<Editor>,
8804 ) {
8805 let mut revert_changes = HashMap::default();
8806 let chunk_by = self
8807 .snapshot(window, cx)
8808 .hunks_for_ranges(ranges)
8809 .into_iter()
8810 .chunk_by(|hunk| hunk.buffer_id);
8811 for (buffer_id, hunks) in &chunk_by {
8812 let hunks = hunks.collect::<Vec<_>>();
8813 for hunk in &hunks {
8814 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8815 }
8816 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8817 }
8818 drop(chunk_by);
8819 if !revert_changes.is_empty() {
8820 self.transact(window, cx, |editor, window, cx| {
8821 editor.restore(revert_changes, window, cx);
8822 });
8823 }
8824 }
8825
8826 pub fn open_active_item_in_terminal(
8827 &mut self,
8828 _: &OpenInTerminal,
8829 window: &mut Window,
8830 cx: &mut Context<Self>,
8831 ) {
8832 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8833 let project_path = buffer.read(cx).project_path(cx)?;
8834 let project = self.project.as_ref()?.read(cx);
8835 let entry = project.entry_for_path(&project_path, cx)?;
8836 let parent = match &entry.canonical_path {
8837 Some(canonical_path) => canonical_path.to_path_buf(),
8838 None => project.absolute_path(&project_path, cx)?,
8839 }
8840 .parent()?
8841 .to_path_buf();
8842 Some(parent)
8843 }) {
8844 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8845 }
8846 }
8847
8848 fn set_breakpoint_context_menu(
8849 &mut self,
8850 display_row: DisplayRow,
8851 position: Option<Anchor>,
8852 clicked_point: gpui::Point<Pixels>,
8853 window: &mut Window,
8854 cx: &mut Context<Self>,
8855 ) {
8856 if !cx.has_flag::<Debugger>() {
8857 return;
8858 }
8859 let source = self
8860 .buffer
8861 .read(cx)
8862 .snapshot(cx)
8863 .anchor_before(Point::new(display_row.0, 0u32));
8864
8865 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8866
8867 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8868 self,
8869 source,
8870 clicked_point,
8871 None,
8872 context_menu,
8873 window,
8874 cx,
8875 );
8876 }
8877
8878 fn add_edit_breakpoint_block(
8879 &mut self,
8880 anchor: Anchor,
8881 breakpoint: &Breakpoint,
8882 edit_action: BreakpointPromptEditAction,
8883 window: &mut Window,
8884 cx: &mut Context<Self>,
8885 ) {
8886 let weak_editor = cx.weak_entity();
8887 let bp_prompt = cx.new(|cx| {
8888 BreakpointPromptEditor::new(
8889 weak_editor,
8890 anchor,
8891 breakpoint.clone(),
8892 edit_action,
8893 window,
8894 cx,
8895 )
8896 });
8897
8898 let height = bp_prompt.update(cx, |this, cx| {
8899 this.prompt
8900 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8901 });
8902 let cloned_prompt = bp_prompt.clone();
8903 let blocks = vec![BlockProperties {
8904 style: BlockStyle::Sticky,
8905 placement: BlockPlacement::Above(anchor),
8906 height: Some(height),
8907 render: Arc::new(move |cx| {
8908 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8909 cloned_prompt.clone().into_any_element()
8910 }),
8911 priority: 0,
8912 }];
8913
8914 let focus_handle = bp_prompt.focus_handle(cx);
8915 window.focus(&focus_handle);
8916
8917 let block_ids = self.insert_blocks(blocks, None, cx);
8918 bp_prompt.update(cx, |prompt, _| {
8919 prompt.add_block_ids(block_ids);
8920 });
8921 }
8922
8923 pub(crate) fn breakpoint_at_row(
8924 &self,
8925 row: u32,
8926 window: &mut Window,
8927 cx: &mut Context<Self>,
8928 ) -> Option<(Anchor, Breakpoint)> {
8929 let snapshot = self.snapshot(window, cx);
8930 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8931
8932 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
8933 }
8934
8935 pub(crate) fn breakpoint_at_anchor(
8936 &self,
8937 breakpoint_position: Anchor,
8938 snapshot: &EditorSnapshot,
8939 cx: &mut Context<Self>,
8940 ) -> Option<(Anchor, Breakpoint)> {
8941 let project = self.project.clone()?;
8942
8943 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8944 snapshot
8945 .buffer_snapshot
8946 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8947 })?;
8948
8949 let enclosing_excerpt = breakpoint_position.excerpt_id;
8950 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8951 let buffer_snapshot = buffer.read(cx).snapshot();
8952
8953 let row = buffer_snapshot
8954 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8955 .row;
8956
8957 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8958 let anchor_end = snapshot
8959 .buffer_snapshot
8960 .anchor_after(Point::new(row, line_len));
8961
8962 let bp = self
8963 .breakpoint_store
8964 .as_ref()?
8965 .read_with(cx, |breakpoint_store, cx| {
8966 breakpoint_store
8967 .breakpoints(
8968 &buffer,
8969 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8970 &buffer_snapshot,
8971 cx,
8972 )
8973 .next()
8974 .and_then(|(anchor, bp)| {
8975 let breakpoint_row = buffer_snapshot
8976 .summary_for_anchor::<text::PointUtf16>(anchor)
8977 .row;
8978
8979 if breakpoint_row == row {
8980 snapshot
8981 .buffer_snapshot
8982 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8983 .map(|anchor| (anchor, bp.clone()))
8984 } else {
8985 None
8986 }
8987 })
8988 });
8989 bp
8990 }
8991
8992 pub fn edit_log_breakpoint(
8993 &mut self,
8994 _: &EditLogBreakpoint,
8995 window: &mut Window,
8996 cx: &mut Context<Self>,
8997 ) {
8998 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
8999 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9000 message: None,
9001 state: BreakpointState::Enabled,
9002 condition: None,
9003 hit_condition: None,
9004 });
9005
9006 self.add_edit_breakpoint_block(
9007 anchor,
9008 &breakpoint,
9009 BreakpointPromptEditAction::Log,
9010 window,
9011 cx,
9012 );
9013 }
9014 }
9015
9016 fn breakpoints_at_cursors(
9017 &self,
9018 window: &mut Window,
9019 cx: &mut Context<Self>,
9020 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9021 let snapshot = self.snapshot(window, cx);
9022 let cursors = self
9023 .selections
9024 .disjoint_anchors()
9025 .into_iter()
9026 .map(|selection| {
9027 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9028
9029 let breakpoint_position = self
9030 .breakpoint_at_row(cursor_position.row, window, cx)
9031 .map(|bp| bp.0)
9032 .unwrap_or_else(|| {
9033 snapshot
9034 .display_snapshot
9035 .buffer_snapshot
9036 .anchor_after(Point::new(cursor_position.row, 0))
9037 });
9038
9039 let breakpoint = self
9040 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9041 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9042
9043 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9044 })
9045 // 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.
9046 .collect::<HashMap<Anchor, _>>();
9047
9048 cursors.into_iter().collect()
9049 }
9050
9051 pub fn enable_breakpoint(
9052 &mut self,
9053 _: &crate::actions::EnableBreakpoint,
9054 window: &mut Window,
9055 cx: &mut Context<Self>,
9056 ) {
9057 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9058 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9059 continue;
9060 };
9061 self.edit_breakpoint_at_anchor(
9062 anchor,
9063 breakpoint,
9064 BreakpointEditAction::InvertState,
9065 cx,
9066 );
9067 }
9068 }
9069
9070 pub fn disable_breakpoint(
9071 &mut self,
9072 _: &crate::actions::DisableBreakpoint,
9073 window: &mut Window,
9074 cx: &mut Context<Self>,
9075 ) {
9076 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9077 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9078 continue;
9079 };
9080 self.edit_breakpoint_at_anchor(
9081 anchor,
9082 breakpoint,
9083 BreakpointEditAction::InvertState,
9084 cx,
9085 );
9086 }
9087 }
9088
9089 pub fn toggle_breakpoint(
9090 &mut self,
9091 _: &crate::actions::ToggleBreakpoint,
9092 window: &mut Window,
9093 cx: &mut Context<Self>,
9094 ) {
9095 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9096 if let Some(breakpoint) = breakpoint {
9097 self.edit_breakpoint_at_anchor(
9098 anchor,
9099 breakpoint,
9100 BreakpointEditAction::Toggle,
9101 cx,
9102 );
9103 } else {
9104 self.edit_breakpoint_at_anchor(
9105 anchor,
9106 Breakpoint::new_standard(),
9107 BreakpointEditAction::Toggle,
9108 cx,
9109 );
9110 }
9111 }
9112 }
9113
9114 pub fn edit_breakpoint_at_anchor(
9115 &mut self,
9116 breakpoint_position: Anchor,
9117 breakpoint: Breakpoint,
9118 edit_action: BreakpointEditAction,
9119 cx: &mut Context<Self>,
9120 ) {
9121 let Some(breakpoint_store) = &self.breakpoint_store else {
9122 return;
9123 };
9124
9125 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9126 if breakpoint_position == Anchor::min() {
9127 self.buffer()
9128 .read(cx)
9129 .excerpt_buffer_ids()
9130 .into_iter()
9131 .next()
9132 } else {
9133 None
9134 }
9135 }) else {
9136 return;
9137 };
9138
9139 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9140 return;
9141 };
9142
9143 breakpoint_store.update(cx, |breakpoint_store, cx| {
9144 breakpoint_store.toggle_breakpoint(
9145 buffer,
9146 (breakpoint_position.text_anchor, breakpoint),
9147 edit_action,
9148 cx,
9149 );
9150 });
9151
9152 cx.notify();
9153 }
9154
9155 #[cfg(any(test, feature = "test-support"))]
9156 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9157 self.breakpoint_store.clone()
9158 }
9159
9160 pub fn prepare_restore_change(
9161 &self,
9162 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9163 hunk: &MultiBufferDiffHunk,
9164 cx: &mut App,
9165 ) -> Option<()> {
9166 if hunk.is_created_file() {
9167 return None;
9168 }
9169 let buffer = self.buffer.read(cx);
9170 let diff = buffer.diff_for(hunk.buffer_id)?;
9171 let buffer = buffer.buffer(hunk.buffer_id)?;
9172 let buffer = buffer.read(cx);
9173 let original_text = diff
9174 .read(cx)
9175 .base_text()
9176 .as_rope()
9177 .slice(hunk.diff_base_byte_range.clone());
9178 let buffer_snapshot = buffer.snapshot();
9179 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9180 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9181 probe
9182 .0
9183 .start
9184 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9185 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9186 }) {
9187 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9188 Some(())
9189 } else {
9190 None
9191 }
9192 }
9193
9194 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9195 self.manipulate_lines(window, cx, |lines| lines.reverse())
9196 }
9197
9198 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9199 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9200 }
9201
9202 fn manipulate_lines<Fn>(
9203 &mut self,
9204 window: &mut Window,
9205 cx: &mut Context<Self>,
9206 mut callback: Fn,
9207 ) where
9208 Fn: FnMut(&mut Vec<&str>),
9209 {
9210 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9211
9212 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9213 let buffer = self.buffer.read(cx).snapshot(cx);
9214
9215 let mut edits = Vec::new();
9216
9217 let selections = self.selections.all::<Point>(cx);
9218 let mut selections = selections.iter().peekable();
9219 let mut contiguous_row_selections = Vec::new();
9220 let mut new_selections = Vec::new();
9221 let mut added_lines = 0;
9222 let mut removed_lines = 0;
9223
9224 while let Some(selection) = selections.next() {
9225 let (start_row, end_row) = consume_contiguous_rows(
9226 &mut contiguous_row_selections,
9227 selection,
9228 &display_map,
9229 &mut selections,
9230 );
9231
9232 let start_point = Point::new(start_row.0, 0);
9233 let end_point = Point::new(
9234 end_row.previous_row().0,
9235 buffer.line_len(end_row.previous_row()),
9236 );
9237 let text = buffer
9238 .text_for_range(start_point..end_point)
9239 .collect::<String>();
9240
9241 let mut lines = text.split('\n').collect_vec();
9242
9243 let lines_before = lines.len();
9244 callback(&mut lines);
9245 let lines_after = lines.len();
9246
9247 edits.push((start_point..end_point, lines.join("\n")));
9248
9249 // Selections must change based on added and removed line count
9250 let start_row =
9251 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9252 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9253 new_selections.push(Selection {
9254 id: selection.id,
9255 start: start_row,
9256 end: end_row,
9257 goal: SelectionGoal::None,
9258 reversed: selection.reversed,
9259 });
9260
9261 if lines_after > lines_before {
9262 added_lines += lines_after - lines_before;
9263 } else if lines_before > lines_after {
9264 removed_lines += lines_before - lines_after;
9265 }
9266 }
9267
9268 self.transact(window, cx, |this, window, cx| {
9269 let buffer = this.buffer.update(cx, |buffer, cx| {
9270 buffer.edit(edits, None, cx);
9271 buffer.snapshot(cx)
9272 });
9273
9274 // Recalculate offsets on newly edited buffer
9275 let new_selections = new_selections
9276 .iter()
9277 .map(|s| {
9278 let start_point = Point::new(s.start.0, 0);
9279 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9280 Selection {
9281 id: s.id,
9282 start: buffer.point_to_offset(start_point),
9283 end: buffer.point_to_offset(end_point),
9284 goal: s.goal,
9285 reversed: s.reversed,
9286 }
9287 })
9288 .collect();
9289
9290 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9291 s.select(new_selections);
9292 });
9293
9294 this.request_autoscroll(Autoscroll::fit(), cx);
9295 });
9296 }
9297
9298 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9299 self.manipulate_text(window, cx, |text| {
9300 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9301 if has_upper_case_characters {
9302 text.to_lowercase()
9303 } else {
9304 text.to_uppercase()
9305 }
9306 })
9307 }
9308
9309 pub fn convert_to_upper_case(
9310 &mut self,
9311 _: &ConvertToUpperCase,
9312 window: &mut Window,
9313 cx: &mut Context<Self>,
9314 ) {
9315 self.manipulate_text(window, cx, |text| text.to_uppercase())
9316 }
9317
9318 pub fn convert_to_lower_case(
9319 &mut self,
9320 _: &ConvertToLowerCase,
9321 window: &mut Window,
9322 cx: &mut Context<Self>,
9323 ) {
9324 self.manipulate_text(window, cx, |text| text.to_lowercase())
9325 }
9326
9327 pub fn convert_to_title_case(
9328 &mut self,
9329 _: &ConvertToTitleCase,
9330 window: &mut Window,
9331 cx: &mut Context<Self>,
9332 ) {
9333 self.manipulate_text(window, cx, |text| {
9334 text.split('\n')
9335 .map(|line| line.to_case(Case::Title))
9336 .join("\n")
9337 })
9338 }
9339
9340 pub fn convert_to_snake_case(
9341 &mut self,
9342 _: &ConvertToSnakeCase,
9343 window: &mut Window,
9344 cx: &mut Context<Self>,
9345 ) {
9346 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9347 }
9348
9349 pub fn convert_to_kebab_case(
9350 &mut self,
9351 _: &ConvertToKebabCase,
9352 window: &mut Window,
9353 cx: &mut Context<Self>,
9354 ) {
9355 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9356 }
9357
9358 pub fn convert_to_upper_camel_case(
9359 &mut self,
9360 _: &ConvertToUpperCamelCase,
9361 window: &mut Window,
9362 cx: &mut Context<Self>,
9363 ) {
9364 self.manipulate_text(window, cx, |text| {
9365 text.split('\n')
9366 .map(|line| line.to_case(Case::UpperCamel))
9367 .join("\n")
9368 })
9369 }
9370
9371 pub fn convert_to_lower_camel_case(
9372 &mut self,
9373 _: &ConvertToLowerCamelCase,
9374 window: &mut Window,
9375 cx: &mut Context<Self>,
9376 ) {
9377 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9378 }
9379
9380 pub fn convert_to_opposite_case(
9381 &mut self,
9382 _: &ConvertToOppositeCase,
9383 window: &mut Window,
9384 cx: &mut Context<Self>,
9385 ) {
9386 self.manipulate_text(window, cx, |text| {
9387 text.chars()
9388 .fold(String::with_capacity(text.len()), |mut t, c| {
9389 if c.is_uppercase() {
9390 t.extend(c.to_lowercase());
9391 } else {
9392 t.extend(c.to_uppercase());
9393 }
9394 t
9395 })
9396 })
9397 }
9398
9399 pub fn convert_to_rot13(
9400 &mut self,
9401 _: &ConvertToRot13,
9402 window: &mut Window,
9403 cx: &mut Context<Self>,
9404 ) {
9405 self.manipulate_text(window, cx, |text| {
9406 text.chars()
9407 .map(|c| match c {
9408 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9409 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9410 _ => c,
9411 })
9412 .collect()
9413 })
9414 }
9415
9416 pub fn convert_to_rot47(
9417 &mut self,
9418 _: &ConvertToRot47,
9419 window: &mut Window,
9420 cx: &mut Context<Self>,
9421 ) {
9422 self.manipulate_text(window, cx, |text| {
9423 text.chars()
9424 .map(|c| {
9425 let code_point = c as u32;
9426 if code_point >= 33 && code_point <= 126 {
9427 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9428 }
9429 c
9430 })
9431 .collect()
9432 })
9433 }
9434
9435 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9436 where
9437 Fn: FnMut(&str) -> String,
9438 {
9439 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9440 let buffer = self.buffer.read(cx).snapshot(cx);
9441
9442 let mut new_selections = Vec::new();
9443 let mut edits = Vec::new();
9444 let mut selection_adjustment = 0i32;
9445
9446 for selection in self.selections.all::<usize>(cx) {
9447 let selection_is_empty = selection.is_empty();
9448
9449 let (start, end) = if selection_is_empty {
9450 let word_range = movement::surrounding_word(
9451 &display_map,
9452 selection.start.to_display_point(&display_map),
9453 );
9454 let start = word_range.start.to_offset(&display_map, Bias::Left);
9455 let end = word_range.end.to_offset(&display_map, Bias::Left);
9456 (start, end)
9457 } else {
9458 (selection.start, selection.end)
9459 };
9460
9461 let text = buffer.text_for_range(start..end).collect::<String>();
9462 let old_length = text.len() as i32;
9463 let text = callback(&text);
9464
9465 new_selections.push(Selection {
9466 start: (start as i32 - selection_adjustment) as usize,
9467 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9468 goal: SelectionGoal::None,
9469 ..selection
9470 });
9471
9472 selection_adjustment += old_length - text.len() as i32;
9473
9474 edits.push((start..end, text));
9475 }
9476
9477 self.transact(window, cx, |this, window, cx| {
9478 this.buffer.update(cx, |buffer, cx| {
9479 buffer.edit(edits, None, cx);
9480 });
9481
9482 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9483 s.select(new_selections);
9484 });
9485
9486 this.request_autoscroll(Autoscroll::fit(), cx);
9487 });
9488 }
9489
9490 pub fn duplicate(
9491 &mut self,
9492 upwards: bool,
9493 whole_lines: bool,
9494 window: &mut Window,
9495 cx: &mut Context<Self>,
9496 ) {
9497 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9498
9499 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9500 let buffer = &display_map.buffer_snapshot;
9501 let selections = self.selections.all::<Point>(cx);
9502
9503 let mut edits = Vec::new();
9504 let mut selections_iter = selections.iter().peekable();
9505 while let Some(selection) = selections_iter.next() {
9506 let mut rows = selection.spanned_rows(false, &display_map);
9507 // duplicate line-wise
9508 if whole_lines || selection.start == selection.end {
9509 // Avoid duplicating the same lines twice.
9510 while let Some(next_selection) = selections_iter.peek() {
9511 let next_rows = next_selection.spanned_rows(false, &display_map);
9512 if next_rows.start < rows.end {
9513 rows.end = next_rows.end;
9514 selections_iter.next().unwrap();
9515 } else {
9516 break;
9517 }
9518 }
9519
9520 // Copy the text from the selected row region and splice it either at the start
9521 // or end of the region.
9522 let start = Point::new(rows.start.0, 0);
9523 let end = Point::new(
9524 rows.end.previous_row().0,
9525 buffer.line_len(rows.end.previous_row()),
9526 );
9527 let text = buffer
9528 .text_for_range(start..end)
9529 .chain(Some("\n"))
9530 .collect::<String>();
9531 let insert_location = if upwards {
9532 Point::new(rows.end.0, 0)
9533 } else {
9534 start
9535 };
9536 edits.push((insert_location..insert_location, text));
9537 } else {
9538 // duplicate character-wise
9539 let start = selection.start;
9540 let end = selection.end;
9541 let text = buffer.text_for_range(start..end).collect::<String>();
9542 edits.push((selection.end..selection.end, text));
9543 }
9544 }
9545
9546 self.transact(window, cx, |this, _, cx| {
9547 this.buffer.update(cx, |buffer, cx| {
9548 buffer.edit(edits, None, cx);
9549 });
9550
9551 this.request_autoscroll(Autoscroll::fit(), cx);
9552 });
9553 }
9554
9555 pub fn duplicate_line_up(
9556 &mut self,
9557 _: &DuplicateLineUp,
9558 window: &mut Window,
9559 cx: &mut Context<Self>,
9560 ) {
9561 self.duplicate(true, true, window, cx);
9562 }
9563
9564 pub fn duplicate_line_down(
9565 &mut self,
9566 _: &DuplicateLineDown,
9567 window: &mut Window,
9568 cx: &mut Context<Self>,
9569 ) {
9570 self.duplicate(false, true, window, cx);
9571 }
9572
9573 pub fn duplicate_selection(
9574 &mut self,
9575 _: &DuplicateSelection,
9576 window: &mut Window,
9577 cx: &mut Context<Self>,
9578 ) {
9579 self.duplicate(false, false, window, cx);
9580 }
9581
9582 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9583 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9584
9585 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9586 let buffer = self.buffer.read(cx).snapshot(cx);
9587
9588 let mut edits = Vec::new();
9589 let mut unfold_ranges = Vec::new();
9590 let mut refold_creases = Vec::new();
9591
9592 let selections = self.selections.all::<Point>(cx);
9593 let mut selections = selections.iter().peekable();
9594 let mut contiguous_row_selections = Vec::new();
9595 let mut new_selections = Vec::new();
9596
9597 while let Some(selection) = selections.next() {
9598 // Find all the selections that span a contiguous row range
9599 let (start_row, end_row) = consume_contiguous_rows(
9600 &mut contiguous_row_selections,
9601 selection,
9602 &display_map,
9603 &mut selections,
9604 );
9605
9606 // Move the text spanned by the row range to be before the line preceding the row range
9607 if start_row.0 > 0 {
9608 let range_to_move = Point::new(
9609 start_row.previous_row().0,
9610 buffer.line_len(start_row.previous_row()),
9611 )
9612 ..Point::new(
9613 end_row.previous_row().0,
9614 buffer.line_len(end_row.previous_row()),
9615 );
9616 let insertion_point = display_map
9617 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9618 .0;
9619
9620 // Don't move lines across excerpts
9621 if buffer
9622 .excerpt_containing(insertion_point..range_to_move.end)
9623 .is_some()
9624 {
9625 let text = buffer
9626 .text_for_range(range_to_move.clone())
9627 .flat_map(|s| s.chars())
9628 .skip(1)
9629 .chain(['\n'])
9630 .collect::<String>();
9631
9632 edits.push((
9633 buffer.anchor_after(range_to_move.start)
9634 ..buffer.anchor_before(range_to_move.end),
9635 String::new(),
9636 ));
9637 let insertion_anchor = buffer.anchor_after(insertion_point);
9638 edits.push((insertion_anchor..insertion_anchor, text));
9639
9640 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9641
9642 // Move selections up
9643 new_selections.extend(contiguous_row_selections.drain(..).map(
9644 |mut selection| {
9645 selection.start.row -= row_delta;
9646 selection.end.row -= row_delta;
9647 selection
9648 },
9649 ));
9650
9651 // Move folds up
9652 unfold_ranges.push(range_to_move.clone());
9653 for fold in display_map.folds_in_range(
9654 buffer.anchor_before(range_to_move.start)
9655 ..buffer.anchor_after(range_to_move.end),
9656 ) {
9657 let mut start = fold.range.start.to_point(&buffer);
9658 let mut end = fold.range.end.to_point(&buffer);
9659 start.row -= row_delta;
9660 end.row -= row_delta;
9661 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9662 }
9663 }
9664 }
9665
9666 // If we didn't move line(s), preserve the existing selections
9667 new_selections.append(&mut contiguous_row_selections);
9668 }
9669
9670 self.transact(window, cx, |this, window, cx| {
9671 this.unfold_ranges(&unfold_ranges, true, true, cx);
9672 this.buffer.update(cx, |buffer, cx| {
9673 for (range, text) in edits {
9674 buffer.edit([(range, text)], None, cx);
9675 }
9676 });
9677 this.fold_creases(refold_creases, true, window, cx);
9678 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9679 s.select(new_selections);
9680 })
9681 });
9682 }
9683
9684 pub fn move_line_down(
9685 &mut self,
9686 _: &MoveLineDown,
9687 window: &mut Window,
9688 cx: &mut Context<Self>,
9689 ) {
9690 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9691
9692 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9693 let buffer = self.buffer.read(cx).snapshot(cx);
9694
9695 let mut edits = Vec::new();
9696 let mut unfold_ranges = Vec::new();
9697 let mut refold_creases = Vec::new();
9698
9699 let selections = self.selections.all::<Point>(cx);
9700 let mut selections = selections.iter().peekable();
9701 let mut contiguous_row_selections = Vec::new();
9702 let mut new_selections = Vec::new();
9703
9704 while let Some(selection) = selections.next() {
9705 // Find all the selections that span a contiguous row range
9706 let (start_row, end_row) = consume_contiguous_rows(
9707 &mut contiguous_row_selections,
9708 selection,
9709 &display_map,
9710 &mut selections,
9711 );
9712
9713 // Move the text spanned by the row range to be after the last line of the row range
9714 if end_row.0 <= buffer.max_point().row {
9715 let range_to_move =
9716 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9717 let insertion_point = display_map
9718 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9719 .0;
9720
9721 // Don't move lines across excerpt boundaries
9722 if buffer
9723 .excerpt_containing(range_to_move.start..insertion_point)
9724 .is_some()
9725 {
9726 let mut text = String::from("\n");
9727 text.extend(buffer.text_for_range(range_to_move.clone()));
9728 text.pop(); // Drop trailing newline
9729 edits.push((
9730 buffer.anchor_after(range_to_move.start)
9731 ..buffer.anchor_before(range_to_move.end),
9732 String::new(),
9733 ));
9734 let insertion_anchor = buffer.anchor_after(insertion_point);
9735 edits.push((insertion_anchor..insertion_anchor, text));
9736
9737 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9738
9739 // Move selections down
9740 new_selections.extend(contiguous_row_selections.drain(..).map(
9741 |mut selection| {
9742 selection.start.row += row_delta;
9743 selection.end.row += row_delta;
9744 selection
9745 },
9746 ));
9747
9748 // Move folds down
9749 unfold_ranges.push(range_to_move.clone());
9750 for fold in display_map.folds_in_range(
9751 buffer.anchor_before(range_to_move.start)
9752 ..buffer.anchor_after(range_to_move.end),
9753 ) {
9754 let mut start = fold.range.start.to_point(&buffer);
9755 let mut end = fold.range.end.to_point(&buffer);
9756 start.row += row_delta;
9757 end.row += row_delta;
9758 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9759 }
9760 }
9761 }
9762
9763 // If we didn't move line(s), preserve the existing selections
9764 new_selections.append(&mut contiguous_row_selections);
9765 }
9766
9767 self.transact(window, cx, |this, window, cx| {
9768 this.unfold_ranges(&unfold_ranges, true, true, cx);
9769 this.buffer.update(cx, |buffer, cx| {
9770 for (range, text) in edits {
9771 buffer.edit([(range, text)], None, cx);
9772 }
9773 });
9774 this.fold_creases(refold_creases, true, window, cx);
9775 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9776 s.select(new_selections)
9777 });
9778 });
9779 }
9780
9781 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9782 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9783 let text_layout_details = &self.text_layout_details(window);
9784 self.transact(window, cx, |this, window, cx| {
9785 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9786 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9787 s.move_with(|display_map, selection| {
9788 if !selection.is_empty() {
9789 return;
9790 }
9791
9792 let mut head = selection.head();
9793 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9794 if head.column() == display_map.line_len(head.row()) {
9795 transpose_offset = display_map
9796 .buffer_snapshot
9797 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9798 }
9799
9800 if transpose_offset == 0 {
9801 return;
9802 }
9803
9804 *head.column_mut() += 1;
9805 head = display_map.clip_point(head, Bias::Right);
9806 let goal = SelectionGoal::HorizontalPosition(
9807 display_map
9808 .x_for_display_point(head, text_layout_details)
9809 .into(),
9810 );
9811 selection.collapse_to(head, goal);
9812
9813 let transpose_start = display_map
9814 .buffer_snapshot
9815 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9816 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9817 let transpose_end = display_map
9818 .buffer_snapshot
9819 .clip_offset(transpose_offset + 1, Bias::Right);
9820 if let Some(ch) =
9821 display_map.buffer_snapshot.chars_at(transpose_start).next()
9822 {
9823 edits.push((transpose_start..transpose_offset, String::new()));
9824 edits.push((transpose_end..transpose_end, ch.to_string()));
9825 }
9826 }
9827 });
9828 edits
9829 });
9830 this.buffer
9831 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9832 let selections = this.selections.all::<usize>(cx);
9833 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9834 s.select(selections);
9835 });
9836 });
9837 }
9838
9839 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9840 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9841 self.rewrap_impl(RewrapOptions::default(), cx)
9842 }
9843
9844 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9845 let buffer = self.buffer.read(cx).snapshot(cx);
9846 let selections = self.selections.all::<Point>(cx);
9847 let mut selections = selections.iter().peekable();
9848
9849 let mut edits = Vec::new();
9850 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9851
9852 while let Some(selection) = selections.next() {
9853 let mut start_row = selection.start.row;
9854 let mut end_row = selection.end.row;
9855
9856 // Skip selections that overlap with a range that has already been rewrapped.
9857 let selection_range = start_row..end_row;
9858 if rewrapped_row_ranges
9859 .iter()
9860 .any(|range| range.overlaps(&selection_range))
9861 {
9862 continue;
9863 }
9864
9865 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9866
9867 // Since not all lines in the selection may be at the same indent
9868 // level, choose the indent size that is the most common between all
9869 // of the lines.
9870 //
9871 // If there is a tie, we use the deepest indent.
9872 let (indent_size, indent_end) = {
9873 let mut indent_size_occurrences = HashMap::default();
9874 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9875
9876 for row in start_row..=end_row {
9877 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9878 rows_by_indent_size.entry(indent).or_default().push(row);
9879 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9880 }
9881
9882 let indent_size = indent_size_occurrences
9883 .into_iter()
9884 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9885 .map(|(indent, _)| indent)
9886 .unwrap_or_default();
9887 let row = rows_by_indent_size[&indent_size][0];
9888 let indent_end = Point::new(row, indent_size.len);
9889
9890 (indent_size, indent_end)
9891 };
9892
9893 let mut line_prefix = indent_size.chars().collect::<String>();
9894
9895 let mut inside_comment = false;
9896 if let Some(comment_prefix) =
9897 buffer
9898 .language_scope_at(selection.head())
9899 .and_then(|language| {
9900 language
9901 .line_comment_prefixes()
9902 .iter()
9903 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9904 .cloned()
9905 })
9906 {
9907 line_prefix.push_str(&comment_prefix);
9908 inside_comment = true;
9909 }
9910
9911 let language_settings = buffer.language_settings_at(selection.head(), cx);
9912 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9913 RewrapBehavior::InComments => inside_comment,
9914 RewrapBehavior::InSelections => !selection.is_empty(),
9915 RewrapBehavior::Anywhere => true,
9916 };
9917
9918 let should_rewrap = options.override_language_settings
9919 || allow_rewrap_based_on_language
9920 || self.hard_wrap.is_some();
9921 if !should_rewrap {
9922 continue;
9923 }
9924
9925 if selection.is_empty() {
9926 'expand_upwards: while start_row > 0 {
9927 let prev_row = start_row - 1;
9928 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9929 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9930 {
9931 start_row = prev_row;
9932 } else {
9933 break 'expand_upwards;
9934 }
9935 }
9936
9937 'expand_downwards: while end_row < buffer.max_point().row {
9938 let next_row = end_row + 1;
9939 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9940 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9941 {
9942 end_row = next_row;
9943 } else {
9944 break 'expand_downwards;
9945 }
9946 }
9947 }
9948
9949 let start = Point::new(start_row, 0);
9950 let start_offset = start.to_offset(&buffer);
9951 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9952 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9953 let Some(lines_without_prefixes) = selection_text
9954 .lines()
9955 .map(|line| {
9956 line.strip_prefix(&line_prefix)
9957 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9958 .ok_or_else(|| {
9959 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9960 })
9961 })
9962 .collect::<Result<Vec<_>, _>>()
9963 .log_err()
9964 else {
9965 continue;
9966 };
9967
9968 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9969 buffer
9970 .language_settings_at(Point::new(start_row, 0), cx)
9971 .preferred_line_length as usize
9972 });
9973 let wrapped_text = wrap_with_prefix(
9974 line_prefix,
9975 lines_without_prefixes.join("\n"),
9976 wrap_column,
9977 tab_size,
9978 options.preserve_existing_whitespace,
9979 );
9980
9981 // TODO: should always use char-based diff while still supporting cursor behavior that
9982 // matches vim.
9983 let mut diff_options = DiffOptions::default();
9984 if options.override_language_settings {
9985 diff_options.max_word_diff_len = 0;
9986 diff_options.max_word_diff_line_count = 0;
9987 } else {
9988 diff_options.max_word_diff_len = usize::MAX;
9989 diff_options.max_word_diff_line_count = usize::MAX;
9990 }
9991
9992 for (old_range, new_text) in
9993 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9994 {
9995 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9996 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9997 edits.push((edit_start..edit_end, new_text));
9998 }
9999
10000 rewrapped_row_ranges.push(start_row..=end_row);
10001 }
10002
10003 self.buffer
10004 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10005 }
10006
10007 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10008 let mut text = String::new();
10009 let buffer = self.buffer.read(cx).snapshot(cx);
10010 let mut selections = self.selections.all::<Point>(cx);
10011 let mut clipboard_selections = Vec::with_capacity(selections.len());
10012 {
10013 let max_point = buffer.max_point();
10014 let mut is_first = true;
10015 for selection in &mut selections {
10016 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10017 if is_entire_line {
10018 selection.start = Point::new(selection.start.row, 0);
10019 if !selection.is_empty() && selection.end.column == 0 {
10020 selection.end = cmp::min(max_point, selection.end);
10021 } else {
10022 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10023 }
10024 selection.goal = SelectionGoal::None;
10025 }
10026 if is_first {
10027 is_first = false;
10028 } else {
10029 text += "\n";
10030 }
10031 let mut len = 0;
10032 for chunk in buffer.text_for_range(selection.start..selection.end) {
10033 text.push_str(chunk);
10034 len += chunk.len();
10035 }
10036 clipboard_selections.push(ClipboardSelection {
10037 len,
10038 is_entire_line,
10039 first_line_indent: buffer
10040 .indent_size_for_line(MultiBufferRow(selection.start.row))
10041 .len,
10042 });
10043 }
10044 }
10045
10046 self.transact(window, cx, |this, window, cx| {
10047 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10048 s.select(selections);
10049 });
10050 this.insert("", window, cx);
10051 });
10052 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10053 }
10054
10055 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10056 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10057 let item = self.cut_common(window, cx);
10058 cx.write_to_clipboard(item);
10059 }
10060
10061 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10062 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10063 self.change_selections(None, window, cx, |s| {
10064 s.move_with(|snapshot, sel| {
10065 if sel.is_empty() {
10066 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10067 }
10068 });
10069 });
10070 let item = self.cut_common(window, cx);
10071 cx.set_global(KillRing(item))
10072 }
10073
10074 pub fn kill_ring_yank(
10075 &mut self,
10076 _: &KillRingYank,
10077 window: &mut Window,
10078 cx: &mut Context<Self>,
10079 ) {
10080 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10081 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10082 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10083 (kill_ring.text().to_string(), kill_ring.metadata_json())
10084 } else {
10085 return;
10086 }
10087 } else {
10088 return;
10089 };
10090 self.do_paste(&text, metadata, false, window, cx);
10091 }
10092
10093 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10094 self.do_copy(true, cx);
10095 }
10096
10097 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10098 self.do_copy(false, cx);
10099 }
10100
10101 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10102 let selections = self.selections.all::<Point>(cx);
10103 let buffer = self.buffer.read(cx).read(cx);
10104 let mut text = String::new();
10105
10106 let mut clipboard_selections = Vec::with_capacity(selections.len());
10107 {
10108 let max_point = buffer.max_point();
10109 let mut is_first = true;
10110 for selection in &selections {
10111 let mut start = selection.start;
10112 let mut end = selection.end;
10113 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10114 if is_entire_line {
10115 start = Point::new(start.row, 0);
10116 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10117 }
10118
10119 let mut trimmed_selections = Vec::new();
10120 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10121 let row = MultiBufferRow(start.row);
10122 let first_indent = buffer.indent_size_for_line(row);
10123 if first_indent.len == 0 || start.column > first_indent.len {
10124 trimmed_selections.push(start..end);
10125 } else {
10126 trimmed_selections.push(
10127 Point::new(row.0, first_indent.len)
10128 ..Point::new(row.0, buffer.line_len(row)),
10129 );
10130 for row in start.row + 1..=end.row {
10131 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10132 if row_indent_size.len >= first_indent.len {
10133 trimmed_selections.push(
10134 Point::new(row, first_indent.len)
10135 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10136 );
10137 } else {
10138 trimmed_selections.clear();
10139 trimmed_selections.push(start..end);
10140 break;
10141 }
10142 }
10143 }
10144 } else {
10145 trimmed_selections.push(start..end);
10146 }
10147
10148 for trimmed_range in trimmed_selections {
10149 if is_first {
10150 is_first = false;
10151 } else {
10152 text += "\n";
10153 }
10154 let mut len = 0;
10155 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10156 text.push_str(chunk);
10157 len += chunk.len();
10158 }
10159 clipboard_selections.push(ClipboardSelection {
10160 len,
10161 is_entire_line,
10162 first_line_indent: buffer
10163 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10164 .len,
10165 });
10166 }
10167 }
10168 }
10169
10170 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10171 text,
10172 clipboard_selections,
10173 ));
10174 }
10175
10176 pub fn do_paste(
10177 &mut self,
10178 text: &String,
10179 clipboard_selections: Option<Vec<ClipboardSelection>>,
10180 handle_entire_lines: bool,
10181 window: &mut Window,
10182 cx: &mut Context<Self>,
10183 ) {
10184 if self.read_only(cx) {
10185 return;
10186 }
10187
10188 let clipboard_text = Cow::Borrowed(text);
10189
10190 self.transact(window, cx, |this, window, cx| {
10191 if let Some(mut clipboard_selections) = clipboard_selections {
10192 let old_selections = this.selections.all::<usize>(cx);
10193 let all_selections_were_entire_line =
10194 clipboard_selections.iter().all(|s| s.is_entire_line);
10195 let first_selection_indent_column =
10196 clipboard_selections.first().map(|s| s.first_line_indent);
10197 if clipboard_selections.len() != old_selections.len() {
10198 clipboard_selections.drain(..);
10199 }
10200 let cursor_offset = this.selections.last::<usize>(cx).head();
10201 let mut auto_indent_on_paste = true;
10202
10203 this.buffer.update(cx, |buffer, cx| {
10204 let snapshot = buffer.read(cx);
10205 auto_indent_on_paste = snapshot
10206 .language_settings_at(cursor_offset, cx)
10207 .auto_indent_on_paste;
10208
10209 let mut start_offset = 0;
10210 let mut edits = Vec::new();
10211 let mut original_indent_columns = Vec::new();
10212 for (ix, selection) in old_selections.iter().enumerate() {
10213 let to_insert;
10214 let entire_line;
10215 let original_indent_column;
10216 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10217 let end_offset = start_offset + clipboard_selection.len;
10218 to_insert = &clipboard_text[start_offset..end_offset];
10219 entire_line = clipboard_selection.is_entire_line;
10220 start_offset = end_offset + 1;
10221 original_indent_column = Some(clipboard_selection.first_line_indent);
10222 } else {
10223 to_insert = clipboard_text.as_str();
10224 entire_line = all_selections_were_entire_line;
10225 original_indent_column = first_selection_indent_column
10226 }
10227
10228 // If the corresponding selection was empty when this slice of the
10229 // clipboard text was written, then the entire line containing the
10230 // selection was copied. If this selection is also currently empty,
10231 // then paste the line before the current line of the buffer.
10232 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10233 let column = selection.start.to_point(&snapshot).column as usize;
10234 let line_start = selection.start - column;
10235 line_start..line_start
10236 } else {
10237 selection.range()
10238 };
10239
10240 edits.push((range, to_insert));
10241 original_indent_columns.push(original_indent_column);
10242 }
10243 drop(snapshot);
10244
10245 buffer.edit(
10246 edits,
10247 if auto_indent_on_paste {
10248 Some(AutoindentMode::Block {
10249 original_indent_columns,
10250 })
10251 } else {
10252 None
10253 },
10254 cx,
10255 );
10256 });
10257
10258 let selections = this.selections.all::<usize>(cx);
10259 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10260 s.select(selections)
10261 });
10262 } else {
10263 this.insert(&clipboard_text, window, cx);
10264 }
10265 });
10266 }
10267
10268 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10269 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10270 if let Some(item) = cx.read_from_clipboard() {
10271 let entries = item.entries();
10272
10273 match entries.first() {
10274 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10275 // of all the pasted entries.
10276 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10277 .do_paste(
10278 clipboard_string.text(),
10279 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10280 true,
10281 window,
10282 cx,
10283 ),
10284 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10285 }
10286 }
10287 }
10288
10289 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10290 if self.read_only(cx) {
10291 return;
10292 }
10293
10294 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10295
10296 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10297 if let Some((selections, _)) =
10298 self.selection_history.transaction(transaction_id).cloned()
10299 {
10300 self.change_selections(None, window, cx, |s| {
10301 s.select_anchors(selections.to_vec());
10302 });
10303 } else {
10304 log::error!(
10305 "No entry in selection_history found for undo. \
10306 This may correspond to a bug where undo does not update the selection. \
10307 If this is occurring, please add details to \
10308 https://github.com/zed-industries/zed/issues/22692"
10309 );
10310 }
10311 self.request_autoscroll(Autoscroll::fit(), cx);
10312 self.unmark_text(window, cx);
10313 self.refresh_inline_completion(true, false, window, cx);
10314 cx.emit(EditorEvent::Edited { transaction_id });
10315 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10316 }
10317 }
10318
10319 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10320 if self.read_only(cx) {
10321 return;
10322 }
10323
10324 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10325
10326 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10327 if let Some((_, Some(selections))) =
10328 self.selection_history.transaction(transaction_id).cloned()
10329 {
10330 self.change_selections(None, window, cx, |s| {
10331 s.select_anchors(selections.to_vec());
10332 });
10333 } else {
10334 log::error!(
10335 "No entry in selection_history found for redo. \
10336 This may correspond to a bug where undo does not update the selection. \
10337 If this is occurring, please add details to \
10338 https://github.com/zed-industries/zed/issues/22692"
10339 );
10340 }
10341 self.request_autoscroll(Autoscroll::fit(), cx);
10342 self.unmark_text(window, cx);
10343 self.refresh_inline_completion(true, false, window, cx);
10344 cx.emit(EditorEvent::Edited { transaction_id });
10345 }
10346 }
10347
10348 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10349 self.buffer
10350 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10351 }
10352
10353 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10354 self.buffer
10355 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10356 }
10357
10358 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10359 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10360 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10361 s.move_with(|map, selection| {
10362 let cursor = if selection.is_empty() {
10363 movement::left(map, selection.start)
10364 } else {
10365 selection.start
10366 };
10367 selection.collapse_to(cursor, SelectionGoal::None);
10368 });
10369 })
10370 }
10371
10372 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10373 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10374 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10375 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10376 })
10377 }
10378
10379 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10380 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10381 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10382 s.move_with(|map, selection| {
10383 let cursor = if selection.is_empty() {
10384 movement::right(map, selection.end)
10385 } else {
10386 selection.end
10387 };
10388 selection.collapse_to(cursor, SelectionGoal::None)
10389 });
10390 })
10391 }
10392
10393 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10394 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10395 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10396 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10397 })
10398 }
10399
10400 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10401 if self.take_rename(true, window, cx).is_some() {
10402 return;
10403 }
10404
10405 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10406 cx.propagate();
10407 return;
10408 }
10409
10410 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10411
10412 let text_layout_details = &self.text_layout_details(window);
10413 let selection_count = self.selections.count();
10414 let first_selection = self.selections.first_anchor();
10415
10416 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10417 s.move_with(|map, selection| {
10418 if !selection.is_empty() {
10419 selection.goal = SelectionGoal::None;
10420 }
10421 let (cursor, goal) = movement::up(
10422 map,
10423 selection.start,
10424 selection.goal,
10425 false,
10426 text_layout_details,
10427 );
10428 selection.collapse_to(cursor, goal);
10429 });
10430 });
10431
10432 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10433 {
10434 cx.propagate();
10435 }
10436 }
10437
10438 pub fn move_up_by_lines(
10439 &mut self,
10440 action: &MoveUpByLines,
10441 window: &mut Window,
10442 cx: &mut Context<Self>,
10443 ) {
10444 if self.take_rename(true, window, cx).is_some() {
10445 return;
10446 }
10447
10448 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10449 cx.propagate();
10450 return;
10451 }
10452
10453 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10454
10455 let text_layout_details = &self.text_layout_details(window);
10456
10457 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10458 s.move_with(|map, selection| {
10459 if !selection.is_empty() {
10460 selection.goal = SelectionGoal::None;
10461 }
10462 let (cursor, goal) = movement::up_by_rows(
10463 map,
10464 selection.start,
10465 action.lines,
10466 selection.goal,
10467 false,
10468 text_layout_details,
10469 );
10470 selection.collapse_to(cursor, goal);
10471 });
10472 })
10473 }
10474
10475 pub fn move_down_by_lines(
10476 &mut self,
10477 action: &MoveDownByLines,
10478 window: &mut Window,
10479 cx: &mut Context<Self>,
10480 ) {
10481 if self.take_rename(true, window, cx).is_some() {
10482 return;
10483 }
10484
10485 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10486 cx.propagate();
10487 return;
10488 }
10489
10490 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10491
10492 let text_layout_details = &self.text_layout_details(window);
10493
10494 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10495 s.move_with(|map, selection| {
10496 if !selection.is_empty() {
10497 selection.goal = SelectionGoal::None;
10498 }
10499 let (cursor, goal) = movement::down_by_rows(
10500 map,
10501 selection.start,
10502 action.lines,
10503 selection.goal,
10504 false,
10505 text_layout_details,
10506 );
10507 selection.collapse_to(cursor, goal);
10508 });
10509 })
10510 }
10511
10512 pub fn select_down_by_lines(
10513 &mut self,
10514 action: &SelectDownByLines,
10515 window: &mut Window,
10516 cx: &mut Context<Self>,
10517 ) {
10518 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10519 let text_layout_details = &self.text_layout_details(window);
10520 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10521 s.move_heads_with(|map, head, goal| {
10522 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10523 })
10524 })
10525 }
10526
10527 pub fn select_up_by_lines(
10528 &mut self,
10529 action: &SelectUpByLines,
10530 window: &mut Window,
10531 cx: &mut Context<Self>,
10532 ) {
10533 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10534 let text_layout_details = &self.text_layout_details(window);
10535 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10536 s.move_heads_with(|map, head, goal| {
10537 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10538 })
10539 })
10540 }
10541
10542 pub fn select_page_up(
10543 &mut self,
10544 _: &SelectPageUp,
10545 window: &mut Window,
10546 cx: &mut Context<Self>,
10547 ) {
10548 let Some(row_count) = self.visible_row_count() else {
10549 return;
10550 };
10551
10552 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10553
10554 let text_layout_details = &self.text_layout_details(window);
10555
10556 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10557 s.move_heads_with(|map, head, goal| {
10558 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10559 })
10560 })
10561 }
10562
10563 pub fn move_page_up(
10564 &mut self,
10565 action: &MovePageUp,
10566 window: &mut Window,
10567 cx: &mut Context<Self>,
10568 ) {
10569 if self.take_rename(true, window, cx).is_some() {
10570 return;
10571 }
10572
10573 if self
10574 .context_menu
10575 .borrow_mut()
10576 .as_mut()
10577 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10578 .unwrap_or(false)
10579 {
10580 return;
10581 }
10582
10583 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10584 cx.propagate();
10585 return;
10586 }
10587
10588 let Some(row_count) = self.visible_row_count() else {
10589 return;
10590 };
10591
10592 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10593
10594 let autoscroll = if action.center_cursor {
10595 Autoscroll::center()
10596 } else {
10597 Autoscroll::fit()
10598 };
10599
10600 let text_layout_details = &self.text_layout_details(window);
10601
10602 self.change_selections(Some(autoscroll), window, cx, |s| {
10603 s.move_with(|map, selection| {
10604 if !selection.is_empty() {
10605 selection.goal = SelectionGoal::None;
10606 }
10607 let (cursor, goal) = movement::up_by_rows(
10608 map,
10609 selection.end,
10610 row_count,
10611 selection.goal,
10612 false,
10613 text_layout_details,
10614 );
10615 selection.collapse_to(cursor, goal);
10616 });
10617 });
10618 }
10619
10620 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10621 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10622 let text_layout_details = &self.text_layout_details(window);
10623 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10624 s.move_heads_with(|map, head, goal| {
10625 movement::up(map, head, goal, false, text_layout_details)
10626 })
10627 })
10628 }
10629
10630 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10631 self.take_rename(true, window, cx);
10632
10633 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10634 cx.propagate();
10635 return;
10636 }
10637
10638 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10639
10640 let text_layout_details = &self.text_layout_details(window);
10641 let selection_count = self.selections.count();
10642 let first_selection = self.selections.first_anchor();
10643
10644 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10645 s.move_with(|map, selection| {
10646 if !selection.is_empty() {
10647 selection.goal = SelectionGoal::None;
10648 }
10649 let (cursor, goal) = movement::down(
10650 map,
10651 selection.end,
10652 selection.goal,
10653 false,
10654 text_layout_details,
10655 );
10656 selection.collapse_to(cursor, goal);
10657 });
10658 });
10659
10660 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10661 {
10662 cx.propagate();
10663 }
10664 }
10665
10666 pub fn select_page_down(
10667 &mut self,
10668 _: &SelectPageDown,
10669 window: &mut Window,
10670 cx: &mut Context<Self>,
10671 ) {
10672 let Some(row_count) = self.visible_row_count() else {
10673 return;
10674 };
10675
10676 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10677
10678 let text_layout_details = &self.text_layout_details(window);
10679
10680 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10681 s.move_heads_with(|map, head, goal| {
10682 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10683 })
10684 })
10685 }
10686
10687 pub fn move_page_down(
10688 &mut self,
10689 action: &MovePageDown,
10690 window: &mut Window,
10691 cx: &mut Context<Self>,
10692 ) {
10693 if self.take_rename(true, window, cx).is_some() {
10694 return;
10695 }
10696
10697 if self
10698 .context_menu
10699 .borrow_mut()
10700 .as_mut()
10701 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10702 .unwrap_or(false)
10703 {
10704 return;
10705 }
10706
10707 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10708 cx.propagate();
10709 return;
10710 }
10711
10712 let Some(row_count) = self.visible_row_count() else {
10713 return;
10714 };
10715
10716 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10717
10718 let autoscroll = if action.center_cursor {
10719 Autoscroll::center()
10720 } else {
10721 Autoscroll::fit()
10722 };
10723
10724 let text_layout_details = &self.text_layout_details(window);
10725 self.change_selections(Some(autoscroll), window, cx, |s| {
10726 s.move_with(|map, selection| {
10727 if !selection.is_empty() {
10728 selection.goal = SelectionGoal::None;
10729 }
10730 let (cursor, goal) = movement::down_by_rows(
10731 map,
10732 selection.end,
10733 row_count,
10734 selection.goal,
10735 false,
10736 text_layout_details,
10737 );
10738 selection.collapse_to(cursor, goal);
10739 });
10740 });
10741 }
10742
10743 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10744 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10745 let text_layout_details = &self.text_layout_details(window);
10746 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10747 s.move_heads_with(|map, head, goal| {
10748 movement::down(map, head, goal, false, text_layout_details)
10749 })
10750 });
10751 }
10752
10753 pub fn context_menu_first(
10754 &mut self,
10755 _: &ContextMenuFirst,
10756 _window: &mut Window,
10757 cx: &mut Context<Self>,
10758 ) {
10759 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10760 context_menu.select_first(self.completion_provider.as_deref(), cx);
10761 }
10762 }
10763
10764 pub fn context_menu_prev(
10765 &mut self,
10766 _: &ContextMenuPrevious,
10767 _window: &mut Window,
10768 cx: &mut Context<Self>,
10769 ) {
10770 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10771 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10772 }
10773 }
10774
10775 pub fn context_menu_next(
10776 &mut self,
10777 _: &ContextMenuNext,
10778 _window: &mut Window,
10779 cx: &mut Context<Self>,
10780 ) {
10781 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10782 context_menu.select_next(self.completion_provider.as_deref(), cx);
10783 }
10784 }
10785
10786 pub fn context_menu_last(
10787 &mut self,
10788 _: &ContextMenuLast,
10789 _window: &mut Window,
10790 cx: &mut Context<Self>,
10791 ) {
10792 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10793 context_menu.select_last(self.completion_provider.as_deref(), cx);
10794 }
10795 }
10796
10797 pub fn move_to_previous_word_start(
10798 &mut self,
10799 _: &MoveToPreviousWordStart,
10800 window: &mut Window,
10801 cx: &mut Context<Self>,
10802 ) {
10803 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10804 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10805 s.move_cursors_with(|map, head, _| {
10806 (
10807 movement::previous_word_start(map, head),
10808 SelectionGoal::None,
10809 )
10810 });
10811 })
10812 }
10813
10814 pub fn move_to_previous_subword_start(
10815 &mut self,
10816 _: &MoveToPreviousSubwordStart,
10817 window: &mut Window,
10818 cx: &mut Context<Self>,
10819 ) {
10820 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10821 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10822 s.move_cursors_with(|map, head, _| {
10823 (
10824 movement::previous_subword_start(map, head),
10825 SelectionGoal::None,
10826 )
10827 });
10828 })
10829 }
10830
10831 pub fn select_to_previous_word_start(
10832 &mut self,
10833 _: &SelectToPreviousWordStart,
10834 window: &mut Window,
10835 cx: &mut Context<Self>,
10836 ) {
10837 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10838 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10839 s.move_heads_with(|map, head, _| {
10840 (
10841 movement::previous_word_start(map, head),
10842 SelectionGoal::None,
10843 )
10844 });
10845 })
10846 }
10847
10848 pub fn select_to_previous_subword_start(
10849 &mut self,
10850 _: &SelectToPreviousSubwordStart,
10851 window: &mut Window,
10852 cx: &mut Context<Self>,
10853 ) {
10854 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10855 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10856 s.move_heads_with(|map, head, _| {
10857 (
10858 movement::previous_subword_start(map, head),
10859 SelectionGoal::None,
10860 )
10861 });
10862 })
10863 }
10864
10865 pub fn delete_to_previous_word_start(
10866 &mut self,
10867 action: &DeleteToPreviousWordStart,
10868 window: &mut Window,
10869 cx: &mut Context<Self>,
10870 ) {
10871 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10872 self.transact(window, cx, |this, window, cx| {
10873 this.select_autoclose_pair(window, cx);
10874 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10875 s.move_with(|map, selection| {
10876 if selection.is_empty() {
10877 let cursor = if action.ignore_newlines {
10878 movement::previous_word_start(map, selection.head())
10879 } else {
10880 movement::previous_word_start_or_newline(map, selection.head())
10881 };
10882 selection.set_head(cursor, SelectionGoal::None);
10883 }
10884 });
10885 });
10886 this.insert("", window, cx);
10887 });
10888 }
10889
10890 pub fn delete_to_previous_subword_start(
10891 &mut self,
10892 _: &DeleteToPreviousSubwordStart,
10893 window: &mut Window,
10894 cx: &mut Context<Self>,
10895 ) {
10896 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10897 self.transact(window, cx, |this, window, cx| {
10898 this.select_autoclose_pair(window, cx);
10899 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10900 s.move_with(|map, selection| {
10901 if selection.is_empty() {
10902 let cursor = movement::previous_subword_start(map, selection.head());
10903 selection.set_head(cursor, SelectionGoal::None);
10904 }
10905 });
10906 });
10907 this.insert("", window, cx);
10908 });
10909 }
10910
10911 pub fn move_to_next_word_end(
10912 &mut self,
10913 _: &MoveToNextWordEnd,
10914 window: &mut Window,
10915 cx: &mut Context<Self>,
10916 ) {
10917 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10918 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10919 s.move_cursors_with(|map, head, _| {
10920 (movement::next_word_end(map, head), SelectionGoal::None)
10921 });
10922 })
10923 }
10924
10925 pub fn move_to_next_subword_end(
10926 &mut self,
10927 _: &MoveToNextSubwordEnd,
10928 window: &mut Window,
10929 cx: &mut Context<Self>,
10930 ) {
10931 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10932 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10933 s.move_cursors_with(|map, head, _| {
10934 (movement::next_subword_end(map, head), SelectionGoal::None)
10935 });
10936 })
10937 }
10938
10939 pub fn select_to_next_word_end(
10940 &mut self,
10941 _: &SelectToNextWordEnd,
10942 window: &mut Window,
10943 cx: &mut Context<Self>,
10944 ) {
10945 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10946 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10947 s.move_heads_with(|map, head, _| {
10948 (movement::next_word_end(map, head), SelectionGoal::None)
10949 });
10950 })
10951 }
10952
10953 pub fn select_to_next_subword_end(
10954 &mut self,
10955 _: &SelectToNextSubwordEnd,
10956 window: &mut Window,
10957 cx: &mut Context<Self>,
10958 ) {
10959 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10960 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10961 s.move_heads_with(|map, head, _| {
10962 (movement::next_subword_end(map, head), SelectionGoal::None)
10963 });
10964 })
10965 }
10966
10967 pub fn delete_to_next_word_end(
10968 &mut self,
10969 action: &DeleteToNextWordEnd,
10970 window: &mut Window,
10971 cx: &mut Context<Self>,
10972 ) {
10973 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10974 self.transact(window, cx, |this, window, cx| {
10975 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10976 s.move_with(|map, selection| {
10977 if selection.is_empty() {
10978 let cursor = if action.ignore_newlines {
10979 movement::next_word_end(map, selection.head())
10980 } else {
10981 movement::next_word_end_or_newline(map, selection.head())
10982 };
10983 selection.set_head(cursor, SelectionGoal::None);
10984 }
10985 });
10986 });
10987 this.insert("", window, cx);
10988 });
10989 }
10990
10991 pub fn delete_to_next_subword_end(
10992 &mut self,
10993 _: &DeleteToNextSubwordEnd,
10994 window: &mut Window,
10995 cx: &mut Context<Self>,
10996 ) {
10997 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10998 self.transact(window, cx, |this, window, cx| {
10999 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11000 s.move_with(|map, selection| {
11001 if selection.is_empty() {
11002 let cursor = movement::next_subword_end(map, selection.head());
11003 selection.set_head(cursor, SelectionGoal::None);
11004 }
11005 });
11006 });
11007 this.insert("", window, cx);
11008 });
11009 }
11010
11011 pub fn move_to_beginning_of_line(
11012 &mut self,
11013 action: &MoveToBeginningOfLine,
11014 window: &mut Window,
11015 cx: &mut Context<Self>,
11016 ) {
11017 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11018 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11019 s.move_cursors_with(|map, head, _| {
11020 (
11021 movement::indented_line_beginning(
11022 map,
11023 head,
11024 action.stop_at_soft_wraps,
11025 action.stop_at_indent,
11026 ),
11027 SelectionGoal::None,
11028 )
11029 });
11030 })
11031 }
11032
11033 pub fn select_to_beginning_of_line(
11034 &mut self,
11035 action: &SelectToBeginningOfLine,
11036 window: &mut Window,
11037 cx: &mut Context<Self>,
11038 ) {
11039 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11040 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11041 s.move_heads_with(|map, head, _| {
11042 (
11043 movement::indented_line_beginning(
11044 map,
11045 head,
11046 action.stop_at_soft_wraps,
11047 action.stop_at_indent,
11048 ),
11049 SelectionGoal::None,
11050 )
11051 });
11052 });
11053 }
11054
11055 pub fn delete_to_beginning_of_line(
11056 &mut self,
11057 action: &DeleteToBeginningOfLine,
11058 window: &mut Window,
11059 cx: &mut Context<Self>,
11060 ) {
11061 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11062 self.transact(window, cx, |this, window, cx| {
11063 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11064 s.move_with(|_, selection| {
11065 selection.reversed = true;
11066 });
11067 });
11068
11069 this.select_to_beginning_of_line(
11070 &SelectToBeginningOfLine {
11071 stop_at_soft_wraps: false,
11072 stop_at_indent: action.stop_at_indent,
11073 },
11074 window,
11075 cx,
11076 );
11077 this.backspace(&Backspace, window, cx);
11078 });
11079 }
11080
11081 pub fn move_to_end_of_line(
11082 &mut self,
11083 action: &MoveToEndOfLine,
11084 window: &mut Window,
11085 cx: &mut Context<Self>,
11086 ) {
11087 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11088 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11089 s.move_cursors_with(|map, head, _| {
11090 (
11091 movement::line_end(map, head, action.stop_at_soft_wraps),
11092 SelectionGoal::None,
11093 )
11094 });
11095 })
11096 }
11097
11098 pub fn select_to_end_of_line(
11099 &mut self,
11100 action: &SelectToEndOfLine,
11101 window: &mut Window,
11102 cx: &mut Context<Self>,
11103 ) {
11104 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11105 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11106 s.move_heads_with(|map, head, _| {
11107 (
11108 movement::line_end(map, head, action.stop_at_soft_wraps),
11109 SelectionGoal::None,
11110 )
11111 });
11112 })
11113 }
11114
11115 pub fn delete_to_end_of_line(
11116 &mut self,
11117 _: &DeleteToEndOfLine,
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.select_to_end_of_line(
11124 &SelectToEndOfLine {
11125 stop_at_soft_wraps: false,
11126 },
11127 window,
11128 cx,
11129 );
11130 this.delete(&Delete, window, cx);
11131 });
11132 }
11133
11134 pub fn cut_to_end_of_line(
11135 &mut self,
11136 _: &CutToEndOfLine,
11137 window: &mut Window,
11138 cx: &mut Context<Self>,
11139 ) {
11140 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11141 self.transact(window, cx, |this, window, cx| {
11142 this.select_to_end_of_line(
11143 &SelectToEndOfLine {
11144 stop_at_soft_wraps: false,
11145 },
11146 window,
11147 cx,
11148 );
11149 this.cut(&Cut, window, cx);
11150 });
11151 }
11152
11153 pub fn move_to_start_of_paragraph(
11154 &mut self,
11155 _: &MoveToStartOfParagraph,
11156 window: &mut Window,
11157 cx: &mut Context<Self>,
11158 ) {
11159 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11160 cx.propagate();
11161 return;
11162 }
11163 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11164 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11165 s.move_with(|map, selection| {
11166 selection.collapse_to(
11167 movement::start_of_paragraph(map, selection.head(), 1),
11168 SelectionGoal::None,
11169 )
11170 });
11171 })
11172 }
11173
11174 pub fn move_to_end_of_paragraph(
11175 &mut self,
11176 _: &MoveToEndOfParagraph,
11177 window: &mut Window,
11178 cx: &mut Context<Self>,
11179 ) {
11180 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11181 cx.propagate();
11182 return;
11183 }
11184 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11185 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11186 s.move_with(|map, selection| {
11187 selection.collapse_to(
11188 movement::end_of_paragraph(map, selection.head(), 1),
11189 SelectionGoal::None,
11190 )
11191 });
11192 })
11193 }
11194
11195 pub fn select_to_start_of_paragraph(
11196 &mut self,
11197 _: &SelectToStartOfParagraph,
11198 window: &mut Window,
11199 cx: &mut Context<Self>,
11200 ) {
11201 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11202 cx.propagate();
11203 return;
11204 }
11205 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11206 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11207 s.move_heads_with(|map, head, _| {
11208 (
11209 movement::start_of_paragraph(map, head, 1),
11210 SelectionGoal::None,
11211 )
11212 });
11213 })
11214 }
11215
11216 pub fn select_to_end_of_paragraph(
11217 &mut self,
11218 _: &SelectToEndOfParagraph,
11219 window: &mut Window,
11220 cx: &mut Context<Self>,
11221 ) {
11222 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11223 cx.propagate();
11224 return;
11225 }
11226 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11227 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11228 s.move_heads_with(|map, head, _| {
11229 (
11230 movement::end_of_paragraph(map, head, 1),
11231 SelectionGoal::None,
11232 )
11233 });
11234 })
11235 }
11236
11237 pub fn move_to_start_of_excerpt(
11238 &mut self,
11239 _: &MoveToStartOfExcerpt,
11240 window: &mut Window,
11241 cx: &mut Context<Self>,
11242 ) {
11243 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11244 cx.propagate();
11245 return;
11246 }
11247 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11248 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11249 s.move_with(|map, selection| {
11250 selection.collapse_to(
11251 movement::start_of_excerpt(
11252 map,
11253 selection.head(),
11254 workspace::searchable::Direction::Prev,
11255 ),
11256 SelectionGoal::None,
11257 )
11258 });
11259 })
11260 }
11261
11262 pub fn move_to_start_of_next_excerpt(
11263 &mut self,
11264 _: &MoveToStartOfNextExcerpt,
11265 window: &mut Window,
11266 cx: &mut Context<Self>,
11267 ) {
11268 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11269 cx.propagate();
11270 return;
11271 }
11272
11273 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11274 s.move_with(|map, selection| {
11275 selection.collapse_to(
11276 movement::start_of_excerpt(
11277 map,
11278 selection.head(),
11279 workspace::searchable::Direction::Next,
11280 ),
11281 SelectionGoal::None,
11282 )
11283 });
11284 })
11285 }
11286
11287 pub fn move_to_end_of_excerpt(
11288 &mut self,
11289 _: &MoveToEndOfExcerpt,
11290 window: &mut Window,
11291 cx: &mut Context<Self>,
11292 ) {
11293 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11294 cx.propagate();
11295 return;
11296 }
11297 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11298 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11299 s.move_with(|map, selection| {
11300 selection.collapse_to(
11301 movement::end_of_excerpt(
11302 map,
11303 selection.head(),
11304 workspace::searchable::Direction::Next,
11305 ),
11306 SelectionGoal::None,
11307 )
11308 });
11309 })
11310 }
11311
11312 pub fn move_to_end_of_previous_excerpt(
11313 &mut self,
11314 _: &MoveToEndOfPreviousExcerpt,
11315 window: &mut Window,
11316 cx: &mut Context<Self>,
11317 ) {
11318 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11319 cx.propagate();
11320 return;
11321 }
11322 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11323 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11324 s.move_with(|map, selection| {
11325 selection.collapse_to(
11326 movement::end_of_excerpt(
11327 map,
11328 selection.head(),
11329 workspace::searchable::Direction::Prev,
11330 ),
11331 SelectionGoal::None,
11332 )
11333 });
11334 })
11335 }
11336
11337 pub fn select_to_start_of_excerpt(
11338 &mut self,
11339 _: &SelectToStartOfExcerpt,
11340 window: &mut Window,
11341 cx: &mut Context<Self>,
11342 ) {
11343 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11344 cx.propagate();
11345 return;
11346 }
11347 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11348 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11349 s.move_heads_with(|map, head, _| {
11350 (
11351 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11352 SelectionGoal::None,
11353 )
11354 });
11355 })
11356 }
11357
11358 pub fn select_to_start_of_next_excerpt(
11359 &mut self,
11360 _: &SelectToStartOfNextExcerpt,
11361 window: &mut Window,
11362 cx: &mut Context<Self>,
11363 ) {
11364 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11365 cx.propagate();
11366 return;
11367 }
11368 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11369 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11370 s.move_heads_with(|map, head, _| {
11371 (
11372 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11373 SelectionGoal::None,
11374 )
11375 });
11376 })
11377 }
11378
11379 pub fn select_to_end_of_excerpt(
11380 &mut self,
11381 _: &SelectToEndOfExcerpt,
11382 window: &mut Window,
11383 cx: &mut Context<Self>,
11384 ) {
11385 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11386 cx.propagate();
11387 return;
11388 }
11389 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11390 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11391 s.move_heads_with(|map, head, _| {
11392 (
11393 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11394 SelectionGoal::None,
11395 )
11396 });
11397 })
11398 }
11399
11400 pub fn select_to_end_of_previous_excerpt(
11401 &mut self,
11402 _: &SelectToEndOfPreviousExcerpt,
11403 window: &mut Window,
11404 cx: &mut Context<Self>,
11405 ) {
11406 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11407 cx.propagate();
11408 return;
11409 }
11410 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11411 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11412 s.move_heads_with(|map, head, _| {
11413 (
11414 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11415 SelectionGoal::None,
11416 )
11417 });
11418 })
11419 }
11420
11421 pub fn move_to_beginning(
11422 &mut self,
11423 _: &MoveToBeginning,
11424 window: &mut Window,
11425 cx: &mut Context<Self>,
11426 ) {
11427 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11428 cx.propagate();
11429 return;
11430 }
11431 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11432 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11433 s.select_ranges(vec![0..0]);
11434 });
11435 }
11436
11437 pub fn select_to_beginning(
11438 &mut self,
11439 _: &SelectToBeginning,
11440 window: &mut Window,
11441 cx: &mut Context<Self>,
11442 ) {
11443 let mut selection = self.selections.last::<Point>(cx);
11444 selection.set_head(Point::zero(), SelectionGoal::None);
11445 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11446 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11447 s.select(vec![selection]);
11448 });
11449 }
11450
11451 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11452 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11453 cx.propagate();
11454 return;
11455 }
11456 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11457 let cursor = self.buffer.read(cx).read(cx).len();
11458 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11459 s.select_ranges(vec![cursor..cursor])
11460 });
11461 }
11462
11463 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11464 self.nav_history = nav_history;
11465 }
11466
11467 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11468 self.nav_history.as_ref()
11469 }
11470
11471 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11472 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11473 }
11474
11475 fn push_to_nav_history(
11476 &mut self,
11477 cursor_anchor: Anchor,
11478 new_position: Option<Point>,
11479 is_deactivate: bool,
11480 cx: &mut Context<Self>,
11481 ) {
11482 if let Some(nav_history) = self.nav_history.as_mut() {
11483 let buffer = self.buffer.read(cx).read(cx);
11484 let cursor_position = cursor_anchor.to_point(&buffer);
11485 let scroll_state = self.scroll_manager.anchor();
11486 let scroll_top_row = scroll_state.top_row(&buffer);
11487 drop(buffer);
11488
11489 if let Some(new_position) = new_position {
11490 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11491 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11492 return;
11493 }
11494 }
11495
11496 nav_history.push(
11497 Some(NavigationData {
11498 cursor_anchor,
11499 cursor_position,
11500 scroll_anchor: scroll_state,
11501 scroll_top_row,
11502 }),
11503 cx,
11504 );
11505 cx.emit(EditorEvent::PushedToNavHistory {
11506 anchor: cursor_anchor,
11507 is_deactivate,
11508 })
11509 }
11510 }
11511
11512 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11513 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11514 let buffer = self.buffer.read(cx).snapshot(cx);
11515 let mut selection = self.selections.first::<usize>(cx);
11516 selection.set_head(buffer.len(), SelectionGoal::None);
11517 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11518 s.select(vec![selection]);
11519 });
11520 }
11521
11522 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11523 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11524 let end = self.buffer.read(cx).read(cx).len();
11525 self.change_selections(None, window, cx, |s| {
11526 s.select_ranges(vec![0..end]);
11527 });
11528 }
11529
11530 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11531 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11532 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11533 let mut selections = self.selections.all::<Point>(cx);
11534 let max_point = display_map.buffer_snapshot.max_point();
11535 for selection in &mut selections {
11536 let rows = selection.spanned_rows(true, &display_map);
11537 selection.start = Point::new(rows.start.0, 0);
11538 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11539 selection.reversed = false;
11540 }
11541 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11542 s.select(selections);
11543 });
11544 }
11545
11546 pub fn split_selection_into_lines(
11547 &mut self,
11548 _: &SplitSelectionIntoLines,
11549 window: &mut Window,
11550 cx: &mut Context<Self>,
11551 ) {
11552 let selections = self
11553 .selections
11554 .all::<Point>(cx)
11555 .into_iter()
11556 .map(|selection| selection.start..selection.end)
11557 .collect::<Vec<_>>();
11558 self.unfold_ranges(&selections, true, true, cx);
11559
11560 let mut new_selection_ranges = Vec::new();
11561 {
11562 let buffer = self.buffer.read(cx).read(cx);
11563 for selection in selections {
11564 for row in selection.start.row..selection.end.row {
11565 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11566 new_selection_ranges.push(cursor..cursor);
11567 }
11568
11569 let is_multiline_selection = selection.start.row != selection.end.row;
11570 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11571 // so this action feels more ergonomic when paired with other selection operations
11572 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11573 if !should_skip_last {
11574 new_selection_ranges.push(selection.end..selection.end);
11575 }
11576 }
11577 }
11578 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11579 s.select_ranges(new_selection_ranges);
11580 });
11581 }
11582
11583 pub fn add_selection_above(
11584 &mut self,
11585 _: &AddSelectionAbove,
11586 window: &mut Window,
11587 cx: &mut Context<Self>,
11588 ) {
11589 self.add_selection(true, window, cx);
11590 }
11591
11592 pub fn add_selection_below(
11593 &mut self,
11594 _: &AddSelectionBelow,
11595 window: &mut Window,
11596 cx: &mut Context<Self>,
11597 ) {
11598 self.add_selection(false, window, cx);
11599 }
11600
11601 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11602 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11603
11604 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11605 let mut selections = self.selections.all::<Point>(cx);
11606 let text_layout_details = self.text_layout_details(window);
11607 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11608 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11609 let range = oldest_selection.display_range(&display_map).sorted();
11610
11611 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11612 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11613 let positions = start_x.min(end_x)..start_x.max(end_x);
11614
11615 selections.clear();
11616 let mut stack = Vec::new();
11617 for row in range.start.row().0..=range.end.row().0 {
11618 if let Some(selection) = self.selections.build_columnar_selection(
11619 &display_map,
11620 DisplayRow(row),
11621 &positions,
11622 oldest_selection.reversed,
11623 &text_layout_details,
11624 ) {
11625 stack.push(selection.id);
11626 selections.push(selection);
11627 }
11628 }
11629
11630 if above {
11631 stack.reverse();
11632 }
11633
11634 AddSelectionsState { above, stack }
11635 });
11636
11637 let last_added_selection = *state.stack.last().unwrap();
11638 let mut new_selections = Vec::new();
11639 if above == state.above {
11640 let end_row = if above {
11641 DisplayRow(0)
11642 } else {
11643 display_map.max_point().row()
11644 };
11645
11646 'outer: for selection in selections {
11647 if selection.id == last_added_selection {
11648 let range = selection.display_range(&display_map).sorted();
11649 debug_assert_eq!(range.start.row(), range.end.row());
11650 let mut row = range.start.row();
11651 let positions =
11652 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11653 px(start)..px(end)
11654 } else {
11655 let start_x =
11656 display_map.x_for_display_point(range.start, &text_layout_details);
11657 let end_x =
11658 display_map.x_for_display_point(range.end, &text_layout_details);
11659 start_x.min(end_x)..start_x.max(end_x)
11660 };
11661
11662 while row != end_row {
11663 if above {
11664 row.0 -= 1;
11665 } else {
11666 row.0 += 1;
11667 }
11668
11669 if let Some(new_selection) = self.selections.build_columnar_selection(
11670 &display_map,
11671 row,
11672 &positions,
11673 selection.reversed,
11674 &text_layout_details,
11675 ) {
11676 state.stack.push(new_selection.id);
11677 if above {
11678 new_selections.push(new_selection);
11679 new_selections.push(selection);
11680 } else {
11681 new_selections.push(selection);
11682 new_selections.push(new_selection);
11683 }
11684
11685 continue 'outer;
11686 }
11687 }
11688 }
11689
11690 new_selections.push(selection);
11691 }
11692 } else {
11693 new_selections = selections;
11694 new_selections.retain(|s| s.id != last_added_selection);
11695 state.stack.pop();
11696 }
11697
11698 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11699 s.select(new_selections);
11700 });
11701 if state.stack.len() > 1 {
11702 self.add_selections_state = Some(state);
11703 }
11704 }
11705
11706 pub fn select_next_match_internal(
11707 &mut self,
11708 display_map: &DisplaySnapshot,
11709 replace_newest: bool,
11710 autoscroll: Option<Autoscroll>,
11711 window: &mut Window,
11712 cx: &mut Context<Self>,
11713 ) -> Result<()> {
11714 fn select_next_match_ranges(
11715 this: &mut Editor,
11716 range: Range<usize>,
11717 replace_newest: bool,
11718 auto_scroll: Option<Autoscroll>,
11719 window: &mut Window,
11720 cx: &mut Context<Editor>,
11721 ) {
11722 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11723 this.change_selections(auto_scroll, window, cx, |s| {
11724 if replace_newest {
11725 s.delete(s.newest_anchor().id);
11726 }
11727 s.insert_range(range.clone());
11728 });
11729 }
11730
11731 let buffer = &display_map.buffer_snapshot;
11732 let mut selections = self.selections.all::<usize>(cx);
11733 if let Some(mut select_next_state) = self.select_next_state.take() {
11734 let query = &select_next_state.query;
11735 if !select_next_state.done {
11736 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11737 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11738 let mut next_selected_range = None;
11739
11740 let bytes_after_last_selection =
11741 buffer.bytes_in_range(last_selection.end..buffer.len());
11742 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11743 let query_matches = query
11744 .stream_find_iter(bytes_after_last_selection)
11745 .map(|result| (last_selection.end, result))
11746 .chain(
11747 query
11748 .stream_find_iter(bytes_before_first_selection)
11749 .map(|result| (0, result)),
11750 );
11751
11752 for (start_offset, query_match) in query_matches {
11753 let query_match = query_match.unwrap(); // can only fail due to I/O
11754 let offset_range =
11755 start_offset + query_match.start()..start_offset + query_match.end();
11756 let display_range = offset_range.start.to_display_point(display_map)
11757 ..offset_range.end.to_display_point(display_map);
11758
11759 if !select_next_state.wordwise
11760 || (!movement::is_inside_word(display_map, display_range.start)
11761 && !movement::is_inside_word(display_map, display_range.end))
11762 {
11763 // TODO: This is n^2, because we might check all the selections
11764 if !selections
11765 .iter()
11766 .any(|selection| selection.range().overlaps(&offset_range))
11767 {
11768 next_selected_range = Some(offset_range);
11769 break;
11770 }
11771 }
11772 }
11773
11774 if let Some(next_selected_range) = next_selected_range {
11775 select_next_match_ranges(
11776 self,
11777 next_selected_range,
11778 replace_newest,
11779 autoscroll,
11780 window,
11781 cx,
11782 );
11783 } else {
11784 select_next_state.done = true;
11785 }
11786 }
11787
11788 self.select_next_state = Some(select_next_state);
11789 } else {
11790 let mut only_carets = true;
11791 let mut same_text_selected = true;
11792 let mut selected_text = None;
11793
11794 let mut selections_iter = selections.iter().peekable();
11795 while let Some(selection) = selections_iter.next() {
11796 if selection.start != selection.end {
11797 only_carets = false;
11798 }
11799
11800 if same_text_selected {
11801 if selected_text.is_none() {
11802 selected_text =
11803 Some(buffer.text_for_range(selection.range()).collect::<String>());
11804 }
11805
11806 if let Some(next_selection) = selections_iter.peek() {
11807 if next_selection.range().len() == selection.range().len() {
11808 let next_selected_text = buffer
11809 .text_for_range(next_selection.range())
11810 .collect::<String>();
11811 if Some(next_selected_text) != selected_text {
11812 same_text_selected = false;
11813 selected_text = None;
11814 }
11815 } else {
11816 same_text_selected = false;
11817 selected_text = None;
11818 }
11819 }
11820 }
11821 }
11822
11823 if only_carets {
11824 for selection in &mut selections {
11825 let word_range = movement::surrounding_word(
11826 display_map,
11827 selection.start.to_display_point(display_map),
11828 );
11829 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11830 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11831 selection.goal = SelectionGoal::None;
11832 selection.reversed = false;
11833 select_next_match_ranges(
11834 self,
11835 selection.start..selection.end,
11836 replace_newest,
11837 autoscroll,
11838 window,
11839 cx,
11840 );
11841 }
11842
11843 if selections.len() == 1 {
11844 let selection = selections
11845 .last()
11846 .expect("ensured that there's only one selection");
11847 let query = buffer
11848 .text_for_range(selection.start..selection.end)
11849 .collect::<String>();
11850 let is_empty = query.is_empty();
11851 let select_state = SelectNextState {
11852 query: AhoCorasick::new(&[query])?,
11853 wordwise: true,
11854 done: is_empty,
11855 };
11856 self.select_next_state = Some(select_state);
11857 } else {
11858 self.select_next_state = None;
11859 }
11860 } else if let Some(selected_text) = selected_text {
11861 self.select_next_state = Some(SelectNextState {
11862 query: AhoCorasick::new(&[selected_text])?,
11863 wordwise: false,
11864 done: false,
11865 });
11866 self.select_next_match_internal(
11867 display_map,
11868 replace_newest,
11869 autoscroll,
11870 window,
11871 cx,
11872 )?;
11873 }
11874 }
11875 Ok(())
11876 }
11877
11878 pub fn select_all_matches(
11879 &mut self,
11880 _action: &SelectAllMatches,
11881 window: &mut Window,
11882 cx: &mut Context<Self>,
11883 ) -> Result<()> {
11884 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11885
11886 self.push_to_selection_history();
11887 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11888
11889 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11890 let Some(select_next_state) = self.select_next_state.as_mut() else {
11891 return Ok(());
11892 };
11893 if select_next_state.done {
11894 return Ok(());
11895 }
11896
11897 let mut new_selections = Vec::new();
11898
11899 let reversed = self.selections.oldest::<usize>(cx).reversed;
11900 let buffer = &display_map.buffer_snapshot;
11901 let query_matches = select_next_state
11902 .query
11903 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11904
11905 for query_match in query_matches.into_iter() {
11906 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11907 let offset_range = if reversed {
11908 query_match.end()..query_match.start()
11909 } else {
11910 query_match.start()..query_match.end()
11911 };
11912 let display_range = offset_range.start.to_display_point(&display_map)
11913 ..offset_range.end.to_display_point(&display_map);
11914
11915 if !select_next_state.wordwise
11916 || (!movement::is_inside_word(&display_map, display_range.start)
11917 && !movement::is_inside_word(&display_map, display_range.end))
11918 {
11919 new_selections.push(offset_range.start..offset_range.end);
11920 }
11921 }
11922
11923 select_next_state.done = true;
11924 self.unfold_ranges(&new_selections.clone(), false, false, cx);
11925 self.change_selections(None, window, cx, |selections| {
11926 selections.select_ranges(new_selections)
11927 });
11928
11929 Ok(())
11930 }
11931
11932 pub fn select_next(
11933 &mut self,
11934 action: &SelectNext,
11935 window: &mut Window,
11936 cx: &mut Context<Self>,
11937 ) -> Result<()> {
11938 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11939 self.push_to_selection_history();
11940 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11941 self.select_next_match_internal(
11942 &display_map,
11943 action.replace_newest,
11944 Some(Autoscroll::newest()),
11945 window,
11946 cx,
11947 )?;
11948 Ok(())
11949 }
11950
11951 pub fn select_previous(
11952 &mut self,
11953 action: &SelectPrevious,
11954 window: &mut Window,
11955 cx: &mut Context<Self>,
11956 ) -> Result<()> {
11957 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11958 self.push_to_selection_history();
11959 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11960 let buffer = &display_map.buffer_snapshot;
11961 let mut selections = self.selections.all::<usize>(cx);
11962 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11963 let query = &select_prev_state.query;
11964 if !select_prev_state.done {
11965 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11966 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11967 let mut next_selected_range = None;
11968 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11969 let bytes_before_last_selection =
11970 buffer.reversed_bytes_in_range(0..last_selection.start);
11971 let bytes_after_first_selection =
11972 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11973 let query_matches = query
11974 .stream_find_iter(bytes_before_last_selection)
11975 .map(|result| (last_selection.start, result))
11976 .chain(
11977 query
11978 .stream_find_iter(bytes_after_first_selection)
11979 .map(|result| (buffer.len(), result)),
11980 );
11981 for (end_offset, query_match) in query_matches {
11982 let query_match = query_match.unwrap(); // can only fail due to I/O
11983 let offset_range =
11984 end_offset - query_match.end()..end_offset - query_match.start();
11985 let display_range = offset_range.start.to_display_point(&display_map)
11986 ..offset_range.end.to_display_point(&display_map);
11987
11988 if !select_prev_state.wordwise
11989 || (!movement::is_inside_word(&display_map, display_range.start)
11990 && !movement::is_inside_word(&display_map, display_range.end))
11991 {
11992 next_selected_range = Some(offset_range);
11993 break;
11994 }
11995 }
11996
11997 if let Some(next_selected_range) = next_selected_range {
11998 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11999 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12000 if action.replace_newest {
12001 s.delete(s.newest_anchor().id);
12002 }
12003 s.insert_range(next_selected_range);
12004 });
12005 } else {
12006 select_prev_state.done = true;
12007 }
12008 }
12009
12010 self.select_prev_state = Some(select_prev_state);
12011 } else {
12012 let mut only_carets = true;
12013 let mut same_text_selected = true;
12014 let mut selected_text = None;
12015
12016 let mut selections_iter = selections.iter().peekable();
12017 while let Some(selection) = selections_iter.next() {
12018 if selection.start != selection.end {
12019 only_carets = false;
12020 }
12021
12022 if same_text_selected {
12023 if selected_text.is_none() {
12024 selected_text =
12025 Some(buffer.text_for_range(selection.range()).collect::<String>());
12026 }
12027
12028 if let Some(next_selection) = selections_iter.peek() {
12029 if next_selection.range().len() == selection.range().len() {
12030 let next_selected_text = buffer
12031 .text_for_range(next_selection.range())
12032 .collect::<String>();
12033 if Some(next_selected_text) != selected_text {
12034 same_text_selected = false;
12035 selected_text = None;
12036 }
12037 } else {
12038 same_text_selected = false;
12039 selected_text = None;
12040 }
12041 }
12042 }
12043 }
12044
12045 if only_carets {
12046 for selection in &mut selections {
12047 let word_range = movement::surrounding_word(
12048 &display_map,
12049 selection.start.to_display_point(&display_map),
12050 );
12051 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12052 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12053 selection.goal = SelectionGoal::None;
12054 selection.reversed = false;
12055 }
12056 if selections.len() == 1 {
12057 let selection = selections
12058 .last()
12059 .expect("ensured that there's only one selection");
12060 let query = buffer
12061 .text_for_range(selection.start..selection.end)
12062 .collect::<String>();
12063 let is_empty = query.is_empty();
12064 let select_state = SelectNextState {
12065 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12066 wordwise: true,
12067 done: is_empty,
12068 };
12069 self.select_prev_state = Some(select_state);
12070 } else {
12071 self.select_prev_state = None;
12072 }
12073
12074 self.unfold_ranges(
12075 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12076 false,
12077 true,
12078 cx,
12079 );
12080 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12081 s.select(selections);
12082 });
12083 } else if let Some(selected_text) = selected_text {
12084 self.select_prev_state = Some(SelectNextState {
12085 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12086 wordwise: false,
12087 done: false,
12088 });
12089 self.select_previous(action, window, cx)?;
12090 }
12091 }
12092 Ok(())
12093 }
12094
12095 pub fn find_next_match(
12096 &mut self,
12097 _: &FindNextMatch,
12098 window: &mut Window,
12099 cx: &mut Context<Self>,
12100 ) -> Result<()> {
12101 let selections = self.selections.disjoint_anchors();
12102 match selections.first() {
12103 Some(first) if selections.len() >= 2 => {
12104 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12105 s.select_ranges([first.range()]);
12106 });
12107 }
12108 _ => self.select_next(
12109 &SelectNext {
12110 replace_newest: true,
12111 },
12112 window,
12113 cx,
12114 )?,
12115 }
12116 Ok(())
12117 }
12118
12119 pub fn find_previous_match(
12120 &mut self,
12121 _: &FindPreviousMatch,
12122 window: &mut Window,
12123 cx: &mut Context<Self>,
12124 ) -> Result<()> {
12125 let selections = self.selections.disjoint_anchors();
12126 match selections.last() {
12127 Some(last) if selections.len() >= 2 => {
12128 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12129 s.select_ranges([last.range()]);
12130 });
12131 }
12132 _ => self.select_previous(
12133 &SelectPrevious {
12134 replace_newest: true,
12135 },
12136 window,
12137 cx,
12138 )?,
12139 }
12140 Ok(())
12141 }
12142
12143 pub fn toggle_comments(
12144 &mut self,
12145 action: &ToggleComments,
12146 window: &mut Window,
12147 cx: &mut Context<Self>,
12148 ) {
12149 if self.read_only(cx) {
12150 return;
12151 }
12152 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12153 let text_layout_details = &self.text_layout_details(window);
12154 self.transact(window, cx, |this, window, cx| {
12155 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12156 let mut edits = Vec::new();
12157 let mut selection_edit_ranges = Vec::new();
12158 let mut last_toggled_row = None;
12159 let snapshot = this.buffer.read(cx).read(cx);
12160 let empty_str: Arc<str> = Arc::default();
12161 let mut suffixes_inserted = Vec::new();
12162 let ignore_indent = action.ignore_indent;
12163
12164 fn comment_prefix_range(
12165 snapshot: &MultiBufferSnapshot,
12166 row: MultiBufferRow,
12167 comment_prefix: &str,
12168 comment_prefix_whitespace: &str,
12169 ignore_indent: bool,
12170 ) -> Range<Point> {
12171 let indent_size = if ignore_indent {
12172 0
12173 } else {
12174 snapshot.indent_size_for_line(row).len
12175 };
12176
12177 let start = Point::new(row.0, indent_size);
12178
12179 let mut line_bytes = snapshot
12180 .bytes_in_range(start..snapshot.max_point())
12181 .flatten()
12182 .copied();
12183
12184 // If this line currently begins with the line comment prefix, then record
12185 // the range containing the prefix.
12186 if line_bytes
12187 .by_ref()
12188 .take(comment_prefix.len())
12189 .eq(comment_prefix.bytes())
12190 {
12191 // Include any whitespace that matches the comment prefix.
12192 let matching_whitespace_len = line_bytes
12193 .zip(comment_prefix_whitespace.bytes())
12194 .take_while(|(a, b)| a == b)
12195 .count() as u32;
12196 let end = Point::new(
12197 start.row,
12198 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12199 );
12200 start..end
12201 } else {
12202 start..start
12203 }
12204 }
12205
12206 fn comment_suffix_range(
12207 snapshot: &MultiBufferSnapshot,
12208 row: MultiBufferRow,
12209 comment_suffix: &str,
12210 comment_suffix_has_leading_space: bool,
12211 ) -> Range<Point> {
12212 let end = Point::new(row.0, snapshot.line_len(row));
12213 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12214
12215 let mut line_end_bytes = snapshot
12216 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12217 .flatten()
12218 .copied();
12219
12220 let leading_space_len = if suffix_start_column > 0
12221 && line_end_bytes.next() == Some(b' ')
12222 && comment_suffix_has_leading_space
12223 {
12224 1
12225 } else {
12226 0
12227 };
12228
12229 // If this line currently begins with the line comment prefix, then record
12230 // the range containing the prefix.
12231 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12232 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12233 start..end
12234 } else {
12235 end..end
12236 }
12237 }
12238
12239 // TODO: Handle selections that cross excerpts
12240 for selection in &mut selections {
12241 let start_column = snapshot
12242 .indent_size_for_line(MultiBufferRow(selection.start.row))
12243 .len;
12244 let language = if let Some(language) =
12245 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12246 {
12247 language
12248 } else {
12249 continue;
12250 };
12251
12252 selection_edit_ranges.clear();
12253
12254 // If multiple selections contain a given row, avoid processing that
12255 // row more than once.
12256 let mut start_row = MultiBufferRow(selection.start.row);
12257 if last_toggled_row == Some(start_row) {
12258 start_row = start_row.next_row();
12259 }
12260 let end_row =
12261 if selection.end.row > selection.start.row && selection.end.column == 0 {
12262 MultiBufferRow(selection.end.row - 1)
12263 } else {
12264 MultiBufferRow(selection.end.row)
12265 };
12266 last_toggled_row = Some(end_row);
12267
12268 if start_row > end_row {
12269 continue;
12270 }
12271
12272 // If the language has line comments, toggle those.
12273 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12274
12275 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12276 if ignore_indent {
12277 full_comment_prefixes = full_comment_prefixes
12278 .into_iter()
12279 .map(|s| Arc::from(s.trim_end()))
12280 .collect();
12281 }
12282
12283 if !full_comment_prefixes.is_empty() {
12284 let first_prefix = full_comment_prefixes
12285 .first()
12286 .expect("prefixes is non-empty");
12287 let prefix_trimmed_lengths = full_comment_prefixes
12288 .iter()
12289 .map(|p| p.trim_end_matches(' ').len())
12290 .collect::<SmallVec<[usize; 4]>>();
12291
12292 let mut all_selection_lines_are_comments = true;
12293
12294 for row in start_row.0..=end_row.0 {
12295 let row = MultiBufferRow(row);
12296 if start_row < end_row && snapshot.is_line_blank(row) {
12297 continue;
12298 }
12299
12300 let prefix_range = full_comment_prefixes
12301 .iter()
12302 .zip(prefix_trimmed_lengths.iter().copied())
12303 .map(|(prefix, trimmed_prefix_len)| {
12304 comment_prefix_range(
12305 snapshot.deref(),
12306 row,
12307 &prefix[..trimmed_prefix_len],
12308 &prefix[trimmed_prefix_len..],
12309 ignore_indent,
12310 )
12311 })
12312 .max_by_key(|range| range.end.column - range.start.column)
12313 .expect("prefixes is non-empty");
12314
12315 if prefix_range.is_empty() {
12316 all_selection_lines_are_comments = false;
12317 }
12318
12319 selection_edit_ranges.push(prefix_range);
12320 }
12321
12322 if all_selection_lines_are_comments {
12323 edits.extend(
12324 selection_edit_ranges
12325 .iter()
12326 .cloned()
12327 .map(|range| (range, empty_str.clone())),
12328 );
12329 } else {
12330 let min_column = selection_edit_ranges
12331 .iter()
12332 .map(|range| range.start.column)
12333 .min()
12334 .unwrap_or(0);
12335 edits.extend(selection_edit_ranges.iter().map(|range| {
12336 let position = Point::new(range.start.row, min_column);
12337 (position..position, first_prefix.clone())
12338 }));
12339 }
12340 } else if let Some((full_comment_prefix, comment_suffix)) =
12341 language.block_comment_delimiters()
12342 {
12343 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12344 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12345 let prefix_range = comment_prefix_range(
12346 snapshot.deref(),
12347 start_row,
12348 comment_prefix,
12349 comment_prefix_whitespace,
12350 ignore_indent,
12351 );
12352 let suffix_range = comment_suffix_range(
12353 snapshot.deref(),
12354 end_row,
12355 comment_suffix.trim_start_matches(' '),
12356 comment_suffix.starts_with(' '),
12357 );
12358
12359 if prefix_range.is_empty() || suffix_range.is_empty() {
12360 edits.push((
12361 prefix_range.start..prefix_range.start,
12362 full_comment_prefix.clone(),
12363 ));
12364 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12365 suffixes_inserted.push((end_row, comment_suffix.len()));
12366 } else {
12367 edits.push((prefix_range, empty_str.clone()));
12368 edits.push((suffix_range, empty_str.clone()));
12369 }
12370 } else {
12371 continue;
12372 }
12373 }
12374
12375 drop(snapshot);
12376 this.buffer.update(cx, |buffer, cx| {
12377 buffer.edit(edits, None, cx);
12378 });
12379
12380 // Adjust selections so that they end before any comment suffixes that
12381 // were inserted.
12382 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12383 let mut selections = this.selections.all::<Point>(cx);
12384 let snapshot = this.buffer.read(cx).read(cx);
12385 for selection in &mut selections {
12386 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12387 match row.cmp(&MultiBufferRow(selection.end.row)) {
12388 Ordering::Less => {
12389 suffixes_inserted.next();
12390 continue;
12391 }
12392 Ordering::Greater => break,
12393 Ordering::Equal => {
12394 if selection.end.column == snapshot.line_len(row) {
12395 if selection.is_empty() {
12396 selection.start.column -= suffix_len as u32;
12397 }
12398 selection.end.column -= suffix_len as u32;
12399 }
12400 break;
12401 }
12402 }
12403 }
12404 }
12405
12406 drop(snapshot);
12407 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12408 s.select(selections)
12409 });
12410
12411 let selections = this.selections.all::<Point>(cx);
12412 let selections_on_single_row = selections.windows(2).all(|selections| {
12413 selections[0].start.row == selections[1].start.row
12414 && selections[0].end.row == selections[1].end.row
12415 && selections[0].start.row == selections[0].end.row
12416 });
12417 let selections_selecting = selections
12418 .iter()
12419 .any(|selection| selection.start != selection.end);
12420 let advance_downwards = action.advance_downwards
12421 && selections_on_single_row
12422 && !selections_selecting
12423 && !matches!(this.mode, EditorMode::SingleLine { .. });
12424
12425 if advance_downwards {
12426 let snapshot = this.buffer.read(cx).snapshot(cx);
12427
12428 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12429 s.move_cursors_with(|display_snapshot, display_point, _| {
12430 let mut point = display_point.to_point(display_snapshot);
12431 point.row += 1;
12432 point = snapshot.clip_point(point, Bias::Left);
12433 let display_point = point.to_display_point(display_snapshot);
12434 let goal = SelectionGoal::HorizontalPosition(
12435 display_snapshot
12436 .x_for_display_point(display_point, text_layout_details)
12437 .into(),
12438 );
12439 (display_point, goal)
12440 })
12441 });
12442 }
12443 });
12444 }
12445
12446 pub fn select_enclosing_symbol(
12447 &mut self,
12448 _: &SelectEnclosingSymbol,
12449 window: &mut Window,
12450 cx: &mut Context<Self>,
12451 ) {
12452 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12453
12454 let buffer = self.buffer.read(cx).snapshot(cx);
12455 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12456
12457 fn update_selection(
12458 selection: &Selection<usize>,
12459 buffer_snap: &MultiBufferSnapshot,
12460 ) -> Option<Selection<usize>> {
12461 let cursor = selection.head();
12462 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12463 for symbol in symbols.iter().rev() {
12464 let start = symbol.range.start.to_offset(buffer_snap);
12465 let end = symbol.range.end.to_offset(buffer_snap);
12466 let new_range = start..end;
12467 if start < selection.start || end > selection.end {
12468 return Some(Selection {
12469 id: selection.id,
12470 start: new_range.start,
12471 end: new_range.end,
12472 goal: SelectionGoal::None,
12473 reversed: selection.reversed,
12474 });
12475 }
12476 }
12477 None
12478 }
12479
12480 let mut selected_larger_symbol = false;
12481 let new_selections = old_selections
12482 .iter()
12483 .map(|selection| match update_selection(selection, &buffer) {
12484 Some(new_selection) => {
12485 if new_selection.range() != selection.range() {
12486 selected_larger_symbol = true;
12487 }
12488 new_selection
12489 }
12490 None => selection.clone(),
12491 })
12492 .collect::<Vec<_>>();
12493
12494 if selected_larger_symbol {
12495 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12496 s.select(new_selections);
12497 });
12498 }
12499 }
12500
12501 pub fn select_larger_syntax_node(
12502 &mut self,
12503 _: &SelectLargerSyntaxNode,
12504 window: &mut Window,
12505 cx: &mut Context<Self>,
12506 ) {
12507 let Some(visible_row_count) = self.visible_row_count() else {
12508 return;
12509 };
12510 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12511 if old_selections.is_empty() {
12512 return;
12513 }
12514
12515 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12516
12517 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12518 let buffer = self.buffer.read(cx).snapshot(cx);
12519
12520 let mut selected_larger_node = false;
12521 let mut new_selections = old_selections
12522 .iter()
12523 .map(|selection| {
12524 let old_range = selection.start..selection.end;
12525
12526 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12527 // manually select word at selection
12528 if ["string_content", "inline"].contains(&node.kind()) {
12529 let word_range = {
12530 let display_point = buffer
12531 .offset_to_point(old_range.start)
12532 .to_display_point(&display_map);
12533 let Range { start, end } =
12534 movement::surrounding_word(&display_map, display_point);
12535 start.to_point(&display_map).to_offset(&buffer)
12536 ..end.to_point(&display_map).to_offset(&buffer)
12537 };
12538 // ignore if word is already selected
12539 if !word_range.is_empty() && old_range != word_range {
12540 let last_word_range = {
12541 let display_point = buffer
12542 .offset_to_point(old_range.end)
12543 .to_display_point(&display_map);
12544 let Range { start, end } =
12545 movement::surrounding_word(&display_map, display_point);
12546 start.to_point(&display_map).to_offset(&buffer)
12547 ..end.to_point(&display_map).to_offset(&buffer)
12548 };
12549 // only select word if start and end point belongs to same word
12550 if word_range == last_word_range {
12551 selected_larger_node = true;
12552 return Selection {
12553 id: selection.id,
12554 start: word_range.start,
12555 end: word_range.end,
12556 goal: SelectionGoal::None,
12557 reversed: selection.reversed,
12558 };
12559 }
12560 }
12561 }
12562 }
12563
12564 let mut new_range = old_range.clone();
12565 let mut new_node = None;
12566 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12567 {
12568 new_node = Some(node);
12569 new_range = match containing_range {
12570 MultiOrSingleBufferOffsetRange::Single(_) => break,
12571 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12572 };
12573 if !display_map.intersects_fold(new_range.start)
12574 && !display_map.intersects_fold(new_range.end)
12575 {
12576 break;
12577 }
12578 }
12579
12580 if let Some(node) = new_node {
12581 // Log the ancestor, to support using this action as a way to explore TreeSitter
12582 // nodes. Parent and grandparent are also logged because this operation will not
12583 // visit nodes that have the same range as their parent.
12584 log::info!("Node: {node:?}");
12585 let parent = node.parent();
12586 log::info!("Parent: {parent:?}");
12587 let grandparent = parent.and_then(|x| x.parent());
12588 log::info!("Grandparent: {grandparent:?}");
12589 }
12590
12591 selected_larger_node |= new_range != old_range;
12592 Selection {
12593 id: selection.id,
12594 start: new_range.start,
12595 end: new_range.end,
12596 goal: SelectionGoal::None,
12597 reversed: selection.reversed,
12598 }
12599 })
12600 .collect::<Vec<_>>();
12601
12602 if !selected_larger_node {
12603 return; // don't put this call in the history
12604 }
12605
12606 // scroll based on transformation done to the last selection created by the user
12607 let (last_old, last_new) = old_selections
12608 .last()
12609 .zip(new_selections.last().cloned())
12610 .expect("old_selections isn't empty");
12611
12612 // revert selection
12613 let is_selection_reversed = {
12614 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12615 new_selections.last_mut().expect("checked above").reversed =
12616 should_newest_selection_be_reversed;
12617 should_newest_selection_be_reversed
12618 };
12619
12620 if selected_larger_node {
12621 self.select_syntax_node_history.disable_clearing = true;
12622 self.change_selections(None, window, cx, |s| {
12623 s.select(new_selections.clone());
12624 });
12625 self.select_syntax_node_history.disable_clearing = false;
12626 }
12627
12628 let start_row = last_new.start.to_display_point(&display_map).row().0;
12629 let end_row = last_new.end.to_display_point(&display_map).row().0;
12630 let selection_height = end_row - start_row + 1;
12631 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12632
12633 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12634 let scroll_behavior = if fits_on_the_screen {
12635 self.request_autoscroll(Autoscroll::fit(), cx);
12636 SelectSyntaxNodeScrollBehavior::FitSelection
12637 } else if is_selection_reversed {
12638 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12639 SelectSyntaxNodeScrollBehavior::CursorTop
12640 } else {
12641 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12642 SelectSyntaxNodeScrollBehavior::CursorBottom
12643 };
12644
12645 self.select_syntax_node_history.push((
12646 old_selections,
12647 scroll_behavior,
12648 is_selection_reversed,
12649 ));
12650 }
12651
12652 pub fn select_smaller_syntax_node(
12653 &mut self,
12654 _: &SelectSmallerSyntaxNode,
12655 window: &mut Window,
12656 cx: &mut Context<Self>,
12657 ) {
12658 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12659
12660 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12661 self.select_syntax_node_history.pop()
12662 {
12663 if let Some(selection) = selections.last_mut() {
12664 selection.reversed = is_selection_reversed;
12665 }
12666
12667 self.select_syntax_node_history.disable_clearing = true;
12668 self.change_selections(None, window, cx, |s| {
12669 s.select(selections.to_vec());
12670 });
12671 self.select_syntax_node_history.disable_clearing = false;
12672
12673 match scroll_behavior {
12674 SelectSyntaxNodeScrollBehavior::CursorTop => {
12675 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12676 }
12677 SelectSyntaxNodeScrollBehavior::FitSelection => {
12678 self.request_autoscroll(Autoscroll::fit(), cx);
12679 }
12680 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12681 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12682 }
12683 }
12684 }
12685 }
12686
12687 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12688 if !EditorSettings::get_global(cx).gutter.runnables {
12689 self.clear_tasks();
12690 return Task::ready(());
12691 }
12692 let project = self.project.as_ref().map(Entity::downgrade);
12693 let task_sources = self.lsp_task_sources(cx);
12694 cx.spawn_in(window, async move |editor, cx| {
12695 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12696 let Some(project) = project.and_then(|p| p.upgrade()) else {
12697 return;
12698 };
12699 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12700 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12701 }) else {
12702 return;
12703 };
12704
12705 let hide_runnables = project
12706 .update(cx, |project, cx| {
12707 // Do not display any test indicators in non-dev server remote projects.
12708 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12709 })
12710 .unwrap_or(true);
12711 if hide_runnables {
12712 return;
12713 }
12714 let new_rows =
12715 cx.background_spawn({
12716 let snapshot = display_snapshot.clone();
12717 async move {
12718 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12719 }
12720 })
12721 .await;
12722 let Ok(lsp_tasks) =
12723 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12724 else {
12725 return;
12726 };
12727 let lsp_tasks = lsp_tasks.await;
12728
12729 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12730 lsp_tasks
12731 .into_iter()
12732 .flat_map(|(kind, tasks)| {
12733 tasks.into_iter().filter_map(move |(location, task)| {
12734 Some((kind.clone(), location?, task))
12735 })
12736 })
12737 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12738 let buffer = location.target.buffer;
12739 let buffer_snapshot = buffer.read(cx).snapshot();
12740 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12741 |(excerpt_id, snapshot, _)| {
12742 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12743 display_snapshot
12744 .buffer_snapshot
12745 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12746 } else {
12747 None
12748 }
12749 },
12750 );
12751 if let Some(offset) = offset {
12752 let task_buffer_range =
12753 location.target.range.to_point(&buffer_snapshot);
12754 let context_buffer_range =
12755 task_buffer_range.to_offset(&buffer_snapshot);
12756 let context_range = BufferOffset(context_buffer_range.start)
12757 ..BufferOffset(context_buffer_range.end);
12758
12759 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12760 .or_insert_with(|| RunnableTasks {
12761 templates: Vec::new(),
12762 offset,
12763 column: task_buffer_range.start.column,
12764 extra_variables: HashMap::default(),
12765 context_range,
12766 })
12767 .templates
12768 .push((kind, task.original_task().clone()));
12769 }
12770
12771 acc
12772 })
12773 }) else {
12774 return;
12775 };
12776
12777 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12778 editor
12779 .update(cx, |editor, _| {
12780 editor.clear_tasks();
12781 for (key, mut value) in rows {
12782 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12783 value.templates.extend(lsp_tasks.templates);
12784 }
12785
12786 editor.insert_tasks(key, value);
12787 }
12788 for (key, value) in lsp_tasks_by_rows {
12789 editor.insert_tasks(key, value);
12790 }
12791 })
12792 .ok();
12793 })
12794 }
12795 fn fetch_runnable_ranges(
12796 snapshot: &DisplaySnapshot,
12797 range: Range<Anchor>,
12798 ) -> Vec<language::RunnableRange> {
12799 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12800 }
12801
12802 fn runnable_rows(
12803 project: Entity<Project>,
12804 snapshot: DisplaySnapshot,
12805 runnable_ranges: Vec<RunnableRange>,
12806 mut cx: AsyncWindowContext,
12807 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12808 runnable_ranges
12809 .into_iter()
12810 .filter_map(|mut runnable| {
12811 let tasks = cx
12812 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12813 .ok()?;
12814 if tasks.is_empty() {
12815 return None;
12816 }
12817
12818 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12819
12820 let row = snapshot
12821 .buffer_snapshot
12822 .buffer_line_for_row(MultiBufferRow(point.row))?
12823 .1
12824 .start
12825 .row;
12826
12827 let context_range =
12828 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12829 Some((
12830 (runnable.buffer_id, row),
12831 RunnableTasks {
12832 templates: tasks,
12833 offset: snapshot
12834 .buffer_snapshot
12835 .anchor_before(runnable.run_range.start),
12836 context_range,
12837 column: point.column,
12838 extra_variables: runnable.extra_captures,
12839 },
12840 ))
12841 })
12842 .collect()
12843 }
12844
12845 fn templates_with_tags(
12846 project: &Entity<Project>,
12847 runnable: &mut Runnable,
12848 cx: &mut App,
12849 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12850 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12851 let (worktree_id, file) = project
12852 .buffer_for_id(runnable.buffer, cx)
12853 .and_then(|buffer| buffer.read(cx).file())
12854 .map(|file| (file.worktree_id(cx), file.clone()))
12855 .unzip();
12856
12857 (
12858 project.task_store().read(cx).task_inventory().cloned(),
12859 worktree_id,
12860 file,
12861 )
12862 });
12863
12864 let mut templates_with_tags = mem::take(&mut runnable.tags)
12865 .into_iter()
12866 .flat_map(|RunnableTag(tag)| {
12867 inventory
12868 .as_ref()
12869 .into_iter()
12870 .flat_map(|inventory| {
12871 inventory.read(cx).list_tasks(
12872 file.clone(),
12873 Some(runnable.language.clone()),
12874 worktree_id,
12875 cx,
12876 )
12877 })
12878 .filter(move |(_, template)| {
12879 template.tags.iter().any(|source_tag| source_tag == &tag)
12880 })
12881 })
12882 .sorted_by_key(|(kind, _)| kind.to_owned())
12883 .collect::<Vec<_>>();
12884 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12885 // Strongest source wins; if we have worktree tag binding, prefer that to
12886 // global and language bindings;
12887 // if we have a global binding, prefer that to language binding.
12888 let first_mismatch = templates_with_tags
12889 .iter()
12890 .position(|(tag_source, _)| tag_source != leading_tag_source);
12891 if let Some(index) = first_mismatch {
12892 templates_with_tags.truncate(index);
12893 }
12894 }
12895
12896 templates_with_tags
12897 }
12898
12899 pub fn move_to_enclosing_bracket(
12900 &mut self,
12901 _: &MoveToEnclosingBracket,
12902 window: &mut Window,
12903 cx: &mut Context<Self>,
12904 ) {
12905 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12906 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12907 s.move_offsets_with(|snapshot, selection| {
12908 let Some(enclosing_bracket_ranges) =
12909 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12910 else {
12911 return;
12912 };
12913
12914 let mut best_length = usize::MAX;
12915 let mut best_inside = false;
12916 let mut best_in_bracket_range = false;
12917 let mut best_destination = None;
12918 for (open, close) in enclosing_bracket_ranges {
12919 let close = close.to_inclusive();
12920 let length = close.end() - open.start;
12921 let inside = selection.start >= open.end && selection.end <= *close.start();
12922 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12923 || close.contains(&selection.head());
12924
12925 // If best is next to a bracket and current isn't, skip
12926 if !in_bracket_range && best_in_bracket_range {
12927 continue;
12928 }
12929
12930 // Prefer smaller lengths unless best is inside and current isn't
12931 if length > best_length && (best_inside || !inside) {
12932 continue;
12933 }
12934
12935 best_length = length;
12936 best_inside = inside;
12937 best_in_bracket_range = in_bracket_range;
12938 best_destination = Some(
12939 if close.contains(&selection.start) && close.contains(&selection.end) {
12940 if inside { open.end } else { open.start }
12941 } else if inside {
12942 *close.start()
12943 } else {
12944 *close.end()
12945 },
12946 );
12947 }
12948
12949 if let Some(destination) = best_destination {
12950 selection.collapse_to(destination, SelectionGoal::None);
12951 }
12952 })
12953 });
12954 }
12955
12956 pub fn undo_selection(
12957 &mut self,
12958 _: &UndoSelection,
12959 window: &mut Window,
12960 cx: &mut Context<Self>,
12961 ) {
12962 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12963 self.end_selection(window, cx);
12964 self.selection_history.mode = SelectionHistoryMode::Undoing;
12965 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12966 self.change_selections(None, window, cx, |s| {
12967 s.select_anchors(entry.selections.to_vec())
12968 });
12969 self.select_next_state = entry.select_next_state;
12970 self.select_prev_state = entry.select_prev_state;
12971 self.add_selections_state = entry.add_selections_state;
12972 self.request_autoscroll(Autoscroll::newest(), cx);
12973 }
12974 self.selection_history.mode = SelectionHistoryMode::Normal;
12975 }
12976
12977 pub fn redo_selection(
12978 &mut self,
12979 _: &RedoSelection,
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::Redoing;
12986 if let Some(entry) = self.selection_history.redo_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 expand_excerpts(
12999 &mut self,
13000 action: &ExpandExcerpts,
13001 _: &mut Window,
13002 cx: &mut Context<Self>,
13003 ) {
13004 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13005 }
13006
13007 pub fn expand_excerpts_down(
13008 &mut self,
13009 action: &ExpandExcerptsDown,
13010 _: &mut Window,
13011 cx: &mut Context<Self>,
13012 ) {
13013 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13014 }
13015
13016 pub fn expand_excerpts_up(
13017 &mut self,
13018 action: &ExpandExcerptsUp,
13019 _: &mut Window,
13020 cx: &mut Context<Self>,
13021 ) {
13022 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13023 }
13024
13025 pub fn expand_excerpts_for_direction(
13026 &mut self,
13027 lines: u32,
13028 direction: ExpandExcerptDirection,
13029
13030 cx: &mut Context<Self>,
13031 ) {
13032 let selections = self.selections.disjoint_anchors();
13033
13034 let lines = if lines == 0 {
13035 EditorSettings::get_global(cx).expand_excerpt_lines
13036 } else {
13037 lines
13038 };
13039
13040 self.buffer.update(cx, |buffer, cx| {
13041 let snapshot = buffer.snapshot(cx);
13042 let mut excerpt_ids = selections
13043 .iter()
13044 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13045 .collect::<Vec<_>>();
13046 excerpt_ids.sort();
13047 excerpt_ids.dedup();
13048 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13049 })
13050 }
13051
13052 pub fn expand_excerpt(
13053 &mut self,
13054 excerpt: ExcerptId,
13055 direction: ExpandExcerptDirection,
13056 window: &mut Window,
13057 cx: &mut Context<Self>,
13058 ) {
13059 let current_scroll_position = self.scroll_position(cx);
13060 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13061 let mut should_scroll_up = false;
13062
13063 if direction == ExpandExcerptDirection::Down {
13064 let multi_buffer = self.buffer.read(cx);
13065 let snapshot = multi_buffer.snapshot(cx);
13066 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13067 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13068 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13069 let buffer_snapshot = buffer.read(cx).snapshot();
13070 let excerpt_end_row =
13071 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13072 let last_row = buffer_snapshot.max_point().row;
13073 let lines_below = last_row.saturating_sub(excerpt_end_row);
13074 should_scroll_up = lines_below >= lines_to_expand;
13075 }
13076 }
13077 }
13078 }
13079
13080 self.buffer.update(cx, |buffer, cx| {
13081 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13082 });
13083
13084 if should_scroll_up {
13085 let new_scroll_position =
13086 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13087 self.set_scroll_position(new_scroll_position, window, cx);
13088 }
13089 }
13090
13091 pub fn go_to_singleton_buffer_point(
13092 &mut self,
13093 point: Point,
13094 window: &mut Window,
13095 cx: &mut Context<Self>,
13096 ) {
13097 self.go_to_singleton_buffer_range(point..point, window, cx);
13098 }
13099
13100 pub fn go_to_singleton_buffer_range(
13101 &mut self,
13102 range: Range<Point>,
13103 window: &mut Window,
13104 cx: &mut Context<Self>,
13105 ) {
13106 let multibuffer = self.buffer().read(cx);
13107 let Some(buffer) = multibuffer.as_singleton() else {
13108 return;
13109 };
13110 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13111 return;
13112 };
13113 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13114 return;
13115 };
13116 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13117 s.select_anchor_ranges([start..end])
13118 });
13119 }
13120
13121 pub fn go_to_diagnostic(
13122 &mut self,
13123 _: &GoToDiagnostic,
13124 window: &mut Window,
13125 cx: &mut Context<Self>,
13126 ) {
13127 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13128 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13129 }
13130
13131 pub fn go_to_prev_diagnostic(
13132 &mut self,
13133 _: &GoToPreviousDiagnostic,
13134 window: &mut Window,
13135 cx: &mut Context<Self>,
13136 ) {
13137 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13138 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13139 }
13140
13141 pub fn go_to_diagnostic_impl(
13142 &mut self,
13143 direction: Direction,
13144 window: &mut Window,
13145 cx: &mut Context<Self>,
13146 ) {
13147 let buffer = self.buffer.read(cx).snapshot(cx);
13148 let selection = self.selections.newest::<usize>(cx);
13149
13150 let mut active_group_id = None;
13151 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13152 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13153 active_group_id = Some(active_group.group_id);
13154 }
13155 }
13156
13157 fn filtered(
13158 snapshot: EditorSnapshot,
13159 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13160 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13161 diagnostics
13162 .filter(|entry| entry.range.start != entry.range.end)
13163 .filter(|entry| !entry.diagnostic.is_unnecessary)
13164 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13165 }
13166
13167 let snapshot = self.snapshot(window, cx);
13168 let before = filtered(
13169 snapshot.clone(),
13170 buffer
13171 .diagnostics_in_range(0..selection.start)
13172 .filter(|entry| entry.range.start <= selection.start),
13173 );
13174 let after = filtered(
13175 snapshot,
13176 buffer
13177 .diagnostics_in_range(selection.start..buffer.len())
13178 .filter(|entry| entry.range.start >= selection.start),
13179 );
13180
13181 let mut found: Option<DiagnosticEntry<usize>> = None;
13182 if direction == Direction::Prev {
13183 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13184 {
13185 for diagnostic in prev_diagnostics.into_iter().rev() {
13186 if diagnostic.range.start != selection.start
13187 || active_group_id
13188 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13189 {
13190 found = Some(diagnostic);
13191 break 'outer;
13192 }
13193 }
13194 }
13195 } else {
13196 for diagnostic in after.chain(before) {
13197 if diagnostic.range.start != selection.start
13198 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13199 {
13200 found = Some(diagnostic);
13201 break;
13202 }
13203 }
13204 }
13205 let Some(next_diagnostic) = found else {
13206 return;
13207 };
13208
13209 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13210 return;
13211 };
13212 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13213 s.select_ranges(vec![
13214 next_diagnostic.range.start..next_diagnostic.range.start,
13215 ])
13216 });
13217 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13218 self.refresh_inline_completion(false, true, window, cx);
13219 }
13220
13221 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13222 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13223 let snapshot = self.snapshot(window, cx);
13224 let selection = self.selections.newest::<Point>(cx);
13225 self.go_to_hunk_before_or_after_position(
13226 &snapshot,
13227 selection.head(),
13228 Direction::Next,
13229 window,
13230 cx,
13231 );
13232 }
13233
13234 pub fn go_to_hunk_before_or_after_position(
13235 &mut self,
13236 snapshot: &EditorSnapshot,
13237 position: Point,
13238 direction: Direction,
13239 window: &mut Window,
13240 cx: &mut Context<Editor>,
13241 ) {
13242 let row = if direction == Direction::Next {
13243 self.hunk_after_position(snapshot, position)
13244 .map(|hunk| hunk.row_range.start)
13245 } else {
13246 self.hunk_before_position(snapshot, position)
13247 };
13248
13249 if let Some(row) = row {
13250 let destination = Point::new(row.0, 0);
13251 let autoscroll = Autoscroll::center();
13252
13253 self.unfold_ranges(&[destination..destination], false, false, cx);
13254 self.change_selections(Some(autoscroll), window, cx, |s| {
13255 s.select_ranges([destination..destination]);
13256 });
13257 }
13258 }
13259
13260 fn hunk_after_position(
13261 &mut self,
13262 snapshot: &EditorSnapshot,
13263 position: Point,
13264 ) -> Option<MultiBufferDiffHunk> {
13265 snapshot
13266 .buffer_snapshot
13267 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13268 .find(|hunk| hunk.row_range.start.0 > position.row)
13269 .or_else(|| {
13270 snapshot
13271 .buffer_snapshot
13272 .diff_hunks_in_range(Point::zero()..position)
13273 .find(|hunk| hunk.row_range.end.0 < position.row)
13274 })
13275 }
13276
13277 fn go_to_prev_hunk(
13278 &mut self,
13279 _: &GoToPreviousHunk,
13280 window: &mut Window,
13281 cx: &mut Context<Self>,
13282 ) {
13283 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13284 let snapshot = self.snapshot(window, cx);
13285 let selection = self.selections.newest::<Point>(cx);
13286 self.go_to_hunk_before_or_after_position(
13287 &snapshot,
13288 selection.head(),
13289 Direction::Prev,
13290 window,
13291 cx,
13292 );
13293 }
13294
13295 fn hunk_before_position(
13296 &mut self,
13297 snapshot: &EditorSnapshot,
13298 position: Point,
13299 ) -> Option<MultiBufferRow> {
13300 snapshot
13301 .buffer_snapshot
13302 .diff_hunk_before(position)
13303 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13304 }
13305
13306 fn go_to_line<T: 'static>(
13307 &mut self,
13308 position: Anchor,
13309 highlight_color: Option<Hsla>,
13310 window: &mut Window,
13311 cx: &mut Context<Self>,
13312 ) {
13313 let snapshot = self.snapshot(window, cx).display_snapshot;
13314 let position = position.to_point(&snapshot.buffer_snapshot);
13315 let start = snapshot
13316 .buffer_snapshot
13317 .clip_point(Point::new(position.row, 0), Bias::Left);
13318 let end = start + Point::new(1, 0);
13319 let start = snapshot.buffer_snapshot.anchor_before(start);
13320 let end = snapshot.buffer_snapshot.anchor_before(end);
13321
13322 self.highlight_rows::<T>(
13323 start..end,
13324 highlight_color
13325 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13326 false,
13327 cx,
13328 );
13329 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13330 }
13331
13332 pub fn go_to_definition(
13333 &mut self,
13334 _: &GoToDefinition,
13335 window: &mut Window,
13336 cx: &mut Context<Self>,
13337 ) -> Task<Result<Navigated>> {
13338 let definition =
13339 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13340 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13341 cx.spawn_in(window, async move |editor, cx| {
13342 if definition.await? == Navigated::Yes {
13343 return Ok(Navigated::Yes);
13344 }
13345 match fallback_strategy {
13346 GoToDefinitionFallback::None => Ok(Navigated::No),
13347 GoToDefinitionFallback::FindAllReferences => {
13348 match editor.update_in(cx, |editor, window, cx| {
13349 editor.find_all_references(&FindAllReferences, window, cx)
13350 })? {
13351 Some(references) => references.await,
13352 None => Ok(Navigated::No),
13353 }
13354 }
13355 }
13356 })
13357 }
13358
13359 pub fn go_to_declaration(
13360 &mut self,
13361 _: &GoToDeclaration,
13362 window: &mut Window,
13363 cx: &mut Context<Self>,
13364 ) -> Task<Result<Navigated>> {
13365 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13366 }
13367
13368 pub fn go_to_declaration_split(
13369 &mut self,
13370 _: &GoToDeclaration,
13371 window: &mut Window,
13372 cx: &mut Context<Self>,
13373 ) -> Task<Result<Navigated>> {
13374 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13375 }
13376
13377 pub fn go_to_implementation(
13378 &mut self,
13379 _: &GoToImplementation,
13380 window: &mut Window,
13381 cx: &mut Context<Self>,
13382 ) -> Task<Result<Navigated>> {
13383 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13384 }
13385
13386 pub fn go_to_implementation_split(
13387 &mut self,
13388 _: &GoToImplementationSplit,
13389 window: &mut Window,
13390 cx: &mut Context<Self>,
13391 ) -> Task<Result<Navigated>> {
13392 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13393 }
13394
13395 pub fn go_to_type_definition(
13396 &mut self,
13397 _: &GoToTypeDefinition,
13398 window: &mut Window,
13399 cx: &mut Context<Self>,
13400 ) -> Task<Result<Navigated>> {
13401 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13402 }
13403
13404 pub fn go_to_definition_split(
13405 &mut self,
13406 _: &GoToDefinitionSplit,
13407 window: &mut Window,
13408 cx: &mut Context<Self>,
13409 ) -> Task<Result<Navigated>> {
13410 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13411 }
13412
13413 pub fn go_to_type_definition_split(
13414 &mut self,
13415 _: &GoToTypeDefinitionSplit,
13416 window: &mut Window,
13417 cx: &mut Context<Self>,
13418 ) -> Task<Result<Navigated>> {
13419 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13420 }
13421
13422 fn go_to_definition_of_kind(
13423 &mut self,
13424 kind: GotoDefinitionKind,
13425 split: bool,
13426 window: &mut Window,
13427 cx: &mut Context<Self>,
13428 ) -> Task<Result<Navigated>> {
13429 let Some(provider) = self.semantics_provider.clone() else {
13430 return Task::ready(Ok(Navigated::No));
13431 };
13432 let head = self.selections.newest::<usize>(cx).head();
13433 let buffer = self.buffer.read(cx);
13434 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13435 text_anchor
13436 } else {
13437 return Task::ready(Ok(Navigated::No));
13438 };
13439
13440 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13441 return Task::ready(Ok(Navigated::No));
13442 };
13443
13444 cx.spawn_in(window, async move |editor, cx| {
13445 let definitions = definitions.await?;
13446 let navigated = editor
13447 .update_in(cx, |editor, window, cx| {
13448 editor.navigate_to_hover_links(
13449 Some(kind),
13450 definitions
13451 .into_iter()
13452 .filter(|location| {
13453 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13454 })
13455 .map(HoverLink::Text)
13456 .collect::<Vec<_>>(),
13457 split,
13458 window,
13459 cx,
13460 )
13461 })?
13462 .await?;
13463 anyhow::Ok(navigated)
13464 })
13465 }
13466
13467 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13468 let selection = self.selections.newest_anchor();
13469 let head = selection.head();
13470 let tail = selection.tail();
13471
13472 let Some((buffer, start_position)) =
13473 self.buffer.read(cx).text_anchor_for_position(head, cx)
13474 else {
13475 return;
13476 };
13477
13478 let end_position = if head != tail {
13479 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13480 return;
13481 };
13482 Some(pos)
13483 } else {
13484 None
13485 };
13486
13487 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13488 let url = if let Some(end_pos) = end_position {
13489 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13490 } else {
13491 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13492 };
13493
13494 if let Some(url) = url {
13495 editor.update(cx, |_, cx| {
13496 cx.open_url(&url);
13497 })
13498 } else {
13499 Ok(())
13500 }
13501 });
13502
13503 url_finder.detach();
13504 }
13505
13506 pub fn open_selected_filename(
13507 &mut self,
13508 _: &OpenSelectedFilename,
13509 window: &mut Window,
13510 cx: &mut Context<Self>,
13511 ) {
13512 let Some(workspace) = self.workspace() else {
13513 return;
13514 };
13515
13516 let position = self.selections.newest_anchor().head();
13517
13518 let Some((buffer, buffer_position)) =
13519 self.buffer.read(cx).text_anchor_for_position(position, cx)
13520 else {
13521 return;
13522 };
13523
13524 let project = self.project.clone();
13525
13526 cx.spawn_in(window, async move |_, cx| {
13527 let result = find_file(&buffer, project, buffer_position, cx).await;
13528
13529 if let Some((_, path)) = result {
13530 workspace
13531 .update_in(cx, |workspace, window, cx| {
13532 workspace.open_resolved_path(path, window, cx)
13533 })?
13534 .await?;
13535 }
13536 anyhow::Ok(())
13537 })
13538 .detach();
13539 }
13540
13541 pub(crate) fn navigate_to_hover_links(
13542 &mut self,
13543 kind: Option<GotoDefinitionKind>,
13544 mut definitions: Vec<HoverLink>,
13545 split: bool,
13546 window: &mut Window,
13547 cx: &mut Context<Editor>,
13548 ) -> Task<Result<Navigated>> {
13549 // If there is one definition, just open it directly
13550 if definitions.len() == 1 {
13551 let definition = definitions.pop().unwrap();
13552
13553 enum TargetTaskResult {
13554 Location(Option<Location>),
13555 AlreadyNavigated,
13556 }
13557
13558 let target_task = match definition {
13559 HoverLink::Text(link) => {
13560 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13561 }
13562 HoverLink::InlayHint(lsp_location, server_id) => {
13563 let computation =
13564 self.compute_target_location(lsp_location, server_id, window, cx);
13565 cx.background_spawn(async move {
13566 let location = computation.await?;
13567 Ok(TargetTaskResult::Location(location))
13568 })
13569 }
13570 HoverLink::Url(url) => {
13571 cx.open_url(&url);
13572 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13573 }
13574 HoverLink::File(path) => {
13575 if let Some(workspace) = self.workspace() {
13576 cx.spawn_in(window, async move |_, cx| {
13577 workspace
13578 .update_in(cx, |workspace, window, cx| {
13579 workspace.open_resolved_path(path, window, cx)
13580 })?
13581 .await
13582 .map(|_| TargetTaskResult::AlreadyNavigated)
13583 })
13584 } else {
13585 Task::ready(Ok(TargetTaskResult::Location(None)))
13586 }
13587 }
13588 };
13589 cx.spawn_in(window, async move |editor, cx| {
13590 let target = match target_task.await.context("target resolution task")? {
13591 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13592 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13593 TargetTaskResult::Location(Some(target)) => target,
13594 };
13595
13596 editor.update_in(cx, |editor, window, cx| {
13597 let Some(workspace) = editor.workspace() else {
13598 return Navigated::No;
13599 };
13600 let pane = workspace.read(cx).active_pane().clone();
13601
13602 let range = target.range.to_point(target.buffer.read(cx));
13603 let range = editor.range_for_match(&range);
13604 let range = collapse_multiline_range(range);
13605
13606 if !split
13607 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13608 {
13609 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13610 } else {
13611 window.defer(cx, move |window, cx| {
13612 let target_editor: Entity<Self> =
13613 workspace.update(cx, |workspace, cx| {
13614 let pane = if split {
13615 workspace.adjacent_pane(window, cx)
13616 } else {
13617 workspace.active_pane().clone()
13618 };
13619
13620 workspace.open_project_item(
13621 pane,
13622 target.buffer.clone(),
13623 true,
13624 true,
13625 window,
13626 cx,
13627 )
13628 });
13629 target_editor.update(cx, |target_editor, cx| {
13630 // When selecting a definition in a different buffer, disable the nav history
13631 // to avoid creating a history entry at the previous cursor location.
13632 pane.update(cx, |pane, _| pane.disable_history());
13633 target_editor.go_to_singleton_buffer_range(range, window, cx);
13634 pane.update(cx, |pane, _| pane.enable_history());
13635 });
13636 });
13637 }
13638 Navigated::Yes
13639 })
13640 })
13641 } else if !definitions.is_empty() {
13642 cx.spawn_in(window, async move |editor, cx| {
13643 let (title, location_tasks, workspace) = editor
13644 .update_in(cx, |editor, window, cx| {
13645 let tab_kind = match kind {
13646 Some(GotoDefinitionKind::Implementation) => "Implementations",
13647 _ => "Definitions",
13648 };
13649 let title = definitions
13650 .iter()
13651 .find_map(|definition| match definition {
13652 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13653 let buffer = origin.buffer.read(cx);
13654 format!(
13655 "{} for {}",
13656 tab_kind,
13657 buffer
13658 .text_for_range(origin.range.clone())
13659 .collect::<String>()
13660 )
13661 }),
13662 HoverLink::InlayHint(_, _) => None,
13663 HoverLink::Url(_) => None,
13664 HoverLink::File(_) => None,
13665 })
13666 .unwrap_or(tab_kind.to_string());
13667 let location_tasks = definitions
13668 .into_iter()
13669 .map(|definition| match definition {
13670 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13671 HoverLink::InlayHint(lsp_location, server_id) => editor
13672 .compute_target_location(lsp_location, server_id, window, cx),
13673 HoverLink::Url(_) => Task::ready(Ok(None)),
13674 HoverLink::File(_) => Task::ready(Ok(None)),
13675 })
13676 .collect::<Vec<_>>();
13677 (title, location_tasks, editor.workspace().clone())
13678 })
13679 .context("location tasks preparation")?;
13680
13681 let locations = future::join_all(location_tasks)
13682 .await
13683 .into_iter()
13684 .filter_map(|location| location.transpose())
13685 .collect::<Result<_>>()
13686 .context("location tasks")?;
13687
13688 let Some(workspace) = workspace else {
13689 return Ok(Navigated::No);
13690 };
13691 let opened = workspace
13692 .update_in(cx, |workspace, window, cx| {
13693 Self::open_locations_in_multibuffer(
13694 workspace,
13695 locations,
13696 title,
13697 split,
13698 MultibufferSelectionMode::First,
13699 window,
13700 cx,
13701 )
13702 })
13703 .ok();
13704
13705 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13706 })
13707 } else {
13708 Task::ready(Ok(Navigated::No))
13709 }
13710 }
13711
13712 fn compute_target_location(
13713 &self,
13714 lsp_location: lsp::Location,
13715 server_id: LanguageServerId,
13716 window: &mut Window,
13717 cx: &mut Context<Self>,
13718 ) -> Task<anyhow::Result<Option<Location>>> {
13719 let Some(project) = self.project.clone() else {
13720 return Task::ready(Ok(None));
13721 };
13722
13723 cx.spawn_in(window, async move |editor, cx| {
13724 let location_task = editor.update(cx, |_, cx| {
13725 project.update(cx, |project, cx| {
13726 let language_server_name = project
13727 .language_server_statuses(cx)
13728 .find(|(id, _)| server_id == *id)
13729 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13730 language_server_name.map(|language_server_name| {
13731 project.open_local_buffer_via_lsp(
13732 lsp_location.uri.clone(),
13733 server_id,
13734 language_server_name,
13735 cx,
13736 )
13737 })
13738 })
13739 })?;
13740 let location = match location_task {
13741 Some(task) => Some({
13742 let target_buffer_handle = task.await.context("open local buffer")?;
13743 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13744 let target_start = target_buffer
13745 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13746 let target_end = target_buffer
13747 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13748 target_buffer.anchor_after(target_start)
13749 ..target_buffer.anchor_before(target_end)
13750 })?;
13751 Location {
13752 buffer: target_buffer_handle,
13753 range,
13754 }
13755 }),
13756 None => None,
13757 };
13758 Ok(location)
13759 })
13760 }
13761
13762 pub fn find_all_references(
13763 &mut self,
13764 _: &FindAllReferences,
13765 window: &mut Window,
13766 cx: &mut Context<Self>,
13767 ) -> Option<Task<Result<Navigated>>> {
13768 let selection = self.selections.newest::<usize>(cx);
13769 let multi_buffer = self.buffer.read(cx);
13770 let head = selection.head();
13771
13772 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13773 let head_anchor = multi_buffer_snapshot.anchor_at(
13774 head,
13775 if head < selection.tail() {
13776 Bias::Right
13777 } else {
13778 Bias::Left
13779 },
13780 );
13781
13782 match self
13783 .find_all_references_task_sources
13784 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13785 {
13786 Ok(_) => {
13787 log::info!(
13788 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13789 );
13790 return None;
13791 }
13792 Err(i) => {
13793 self.find_all_references_task_sources.insert(i, head_anchor);
13794 }
13795 }
13796
13797 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13798 let workspace = self.workspace()?;
13799 let project = workspace.read(cx).project().clone();
13800 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13801 Some(cx.spawn_in(window, async move |editor, cx| {
13802 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13803 if let Ok(i) = editor
13804 .find_all_references_task_sources
13805 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13806 {
13807 editor.find_all_references_task_sources.remove(i);
13808 }
13809 });
13810
13811 let locations = references.await?;
13812 if locations.is_empty() {
13813 return anyhow::Ok(Navigated::No);
13814 }
13815
13816 workspace.update_in(cx, |workspace, window, cx| {
13817 let title = locations
13818 .first()
13819 .as_ref()
13820 .map(|location| {
13821 let buffer = location.buffer.read(cx);
13822 format!(
13823 "References to `{}`",
13824 buffer
13825 .text_for_range(location.range.clone())
13826 .collect::<String>()
13827 )
13828 })
13829 .unwrap();
13830 Self::open_locations_in_multibuffer(
13831 workspace,
13832 locations,
13833 title,
13834 false,
13835 MultibufferSelectionMode::First,
13836 window,
13837 cx,
13838 );
13839 Navigated::Yes
13840 })
13841 }))
13842 }
13843
13844 /// Opens a multibuffer with the given project locations in it
13845 pub fn open_locations_in_multibuffer(
13846 workspace: &mut Workspace,
13847 mut locations: Vec<Location>,
13848 title: String,
13849 split: bool,
13850 multibuffer_selection_mode: MultibufferSelectionMode,
13851 window: &mut Window,
13852 cx: &mut Context<Workspace>,
13853 ) {
13854 // If there are multiple definitions, open them in a multibuffer
13855 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13856 let mut locations = locations.into_iter().peekable();
13857 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13858 let capability = workspace.project().read(cx).capability();
13859
13860 let excerpt_buffer = cx.new(|cx| {
13861 let mut multibuffer = MultiBuffer::new(capability);
13862 while let Some(location) = locations.next() {
13863 let buffer = location.buffer.read(cx);
13864 let mut ranges_for_buffer = Vec::new();
13865 let range = location.range.to_point(buffer);
13866 ranges_for_buffer.push(range.clone());
13867
13868 while let Some(next_location) = locations.peek() {
13869 if next_location.buffer == location.buffer {
13870 ranges_for_buffer.push(next_location.range.to_point(buffer));
13871 locations.next();
13872 } else {
13873 break;
13874 }
13875 }
13876
13877 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13878 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13879 PathKey::for_buffer(&location.buffer, cx),
13880 location.buffer.clone(),
13881 ranges_for_buffer,
13882 DEFAULT_MULTIBUFFER_CONTEXT,
13883 cx,
13884 );
13885 ranges.extend(new_ranges)
13886 }
13887
13888 multibuffer.with_title(title)
13889 });
13890
13891 let editor = cx.new(|cx| {
13892 Editor::for_multibuffer(
13893 excerpt_buffer,
13894 Some(workspace.project().clone()),
13895 window,
13896 cx,
13897 )
13898 });
13899 editor.update(cx, |editor, cx| {
13900 match multibuffer_selection_mode {
13901 MultibufferSelectionMode::First => {
13902 if let Some(first_range) = ranges.first() {
13903 editor.change_selections(None, window, cx, |selections| {
13904 selections.clear_disjoint();
13905 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13906 });
13907 }
13908 editor.highlight_background::<Self>(
13909 &ranges,
13910 |theme| theme.editor_highlighted_line_background,
13911 cx,
13912 );
13913 }
13914 MultibufferSelectionMode::All => {
13915 editor.change_selections(None, window, cx, |selections| {
13916 selections.clear_disjoint();
13917 selections.select_anchor_ranges(ranges);
13918 });
13919 }
13920 }
13921 editor.register_buffers_with_language_servers(cx);
13922 });
13923
13924 let item = Box::new(editor);
13925 let item_id = item.item_id();
13926
13927 if split {
13928 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13929 } else {
13930 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13931 let (preview_item_id, preview_item_idx) =
13932 workspace.active_pane().update(cx, |pane, _| {
13933 (pane.preview_item_id(), pane.preview_item_idx())
13934 });
13935
13936 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13937
13938 if let Some(preview_item_id) = preview_item_id {
13939 workspace.active_pane().update(cx, |pane, cx| {
13940 pane.remove_item(preview_item_id, false, false, window, cx);
13941 });
13942 }
13943 } else {
13944 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13945 }
13946 }
13947 workspace.active_pane().update(cx, |pane, cx| {
13948 pane.set_preview_item_id(Some(item_id), cx);
13949 });
13950 }
13951
13952 pub fn rename(
13953 &mut self,
13954 _: &Rename,
13955 window: &mut Window,
13956 cx: &mut Context<Self>,
13957 ) -> Option<Task<Result<()>>> {
13958 use language::ToOffset as _;
13959
13960 let provider = self.semantics_provider.clone()?;
13961 let selection = self.selections.newest_anchor().clone();
13962 let (cursor_buffer, cursor_buffer_position) = self
13963 .buffer
13964 .read(cx)
13965 .text_anchor_for_position(selection.head(), cx)?;
13966 let (tail_buffer, cursor_buffer_position_end) = self
13967 .buffer
13968 .read(cx)
13969 .text_anchor_for_position(selection.tail(), cx)?;
13970 if tail_buffer != cursor_buffer {
13971 return None;
13972 }
13973
13974 let snapshot = cursor_buffer.read(cx).snapshot();
13975 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13976 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13977 let prepare_rename = provider
13978 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13979 .unwrap_or_else(|| Task::ready(Ok(None)));
13980 drop(snapshot);
13981
13982 Some(cx.spawn_in(window, async move |this, cx| {
13983 let rename_range = if let Some(range) = prepare_rename.await? {
13984 Some(range)
13985 } else {
13986 this.update(cx, |this, cx| {
13987 let buffer = this.buffer.read(cx).snapshot(cx);
13988 let mut buffer_highlights = this
13989 .document_highlights_for_position(selection.head(), &buffer)
13990 .filter(|highlight| {
13991 highlight.start.excerpt_id == selection.head().excerpt_id
13992 && highlight.end.excerpt_id == selection.head().excerpt_id
13993 });
13994 buffer_highlights
13995 .next()
13996 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13997 })?
13998 };
13999 if let Some(rename_range) = rename_range {
14000 this.update_in(cx, |this, window, cx| {
14001 let snapshot = cursor_buffer.read(cx).snapshot();
14002 let rename_buffer_range = rename_range.to_offset(&snapshot);
14003 let cursor_offset_in_rename_range =
14004 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14005 let cursor_offset_in_rename_range_end =
14006 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14007
14008 this.take_rename(false, window, cx);
14009 let buffer = this.buffer.read(cx).read(cx);
14010 let cursor_offset = selection.head().to_offset(&buffer);
14011 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14012 let rename_end = rename_start + rename_buffer_range.len();
14013 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14014 let mut old_highlight_id = None;
14015 let old_name: Arc<str> = buffer
14016 .chunks(rename_start..rename_end, true)
14017 .map(|chunk| {
14018 if old_highlight_id.is_none() {
14019 old_highlight_id = chunk.syntax_highlight_id;
14020 }
14021 chunk.text
14022 })
14023 .collect::<String>()
14024 .into();
14025
14026 drop(buffer);
14027
14028 // Position the selection in the rename editor so that it matches the current selection.
14029 this.show_local_selections = false;
14030 let rename_editor = cx.new(|cx| {
14031 let mut editor = Editor::single_line(window, cx);
14032 editor.buffer.update(cx, |buffer, cx| {
14033 buffer.edit([(0..0, old_name.clone())], None, cx)
14034 });
14035 let rename_selection_range = match cursor_offset_in_rename_range
14036 .cmp(&cursor_offset_in_rename_range_end)
14037 {
14038 Ordering::Equal => {
14039 editor.select_all(&SelectAll, window, cx);
14040 return editor;
14041 }
14042 Ordering::Less => {
14043 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14044 }
14045 Ordering::Greater => {
14046 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14047 }
14048 };
14049 if rename_selection_range.end > old_name.len() {
14050 editor.select_all(&SelectAll, window, cx);
14051 } else {
14052 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14053 s.select_ranges([rename_selection_range]);
14054 });
14055 }
14056 editor
14057 });
14058 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14059 if e == &EditorEvent::Focused {
14060 cx.emit(EditorEvent::FocusedIn)
14061 }
14062 })
14063 .detach();
14064
14065 let write_highlights =
14066 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14067 let read_highlights =
14068 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14069 let ranges = write_highlights
14070 .iter()
14071 .flat_map(|(_, ranges)| ranges.iter())
14072 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14073 .cloned()
14074 .collect();
14075
14076 this.highlight_text::<Rename>(
14077 ranges,
14078 HighlightStyle {
14079 fade_out: Some(0.6),
14080 ..Default::default()
14081 },
14082 cx,
14083 );
14084 let rename_focus_handle = rename_editor.focus_handle(cx);
14085 window.focus(&rename_focus_handle);
14086 let block_id = this.insert_blocks(
14087 [BlockProperties {
14088 style: BlockStyle::Flex,
14089 placement: BlockPlacement::Below(range.start),
14090 height: Some(1),
14091 render: Arc::new({
14092 let rename_editor = rename_editor.clone();
14093 move |cx: &mut BlockContext| {
14094 let mut text_style = cx.editor_style.text.clone();
14095 if let Some(highlight_style) = old_highlight_id
14096 .and_then(|h| h.style(&cx.editor_style.syntax))
14097 {
14098 text_style = text_style.highlight(highlight_style);
14099 }
14100 div()
14101 .block_mouse_down()
14102 .pl(cx.anchor_x)
14103 .child(EditorElement::new(
14104 &rename_editor,
14105 EditorStyle {
14106 background: cx.theme().system().transparent,
14107 local_player: cx.editor_style.local_player,
14108 text: text_style,
14109 scrollbar_width: cx.editor_style.scrollbar_width,
14110 syntax: cx.editor_style.syntax.clone(),
14111 status: cx.editor_style.status.clone(),
14112 inlay_hints_style: HighlightStyle {
14113 font_weight: Some(FontWeight::BOLD),
14114 ..make_inlay_hints_style(cx.app)
14115 },
14116 inline_completion_styles: make_suggestion_styles(
14117 cx.app,
14118 ),
14119 ..EditorStyle::default()
14120 },
14121 ))
14122 .into_any_element()
14123 }
14124 }),
14125 priority: 0,
14126 }],
14127 Some(Autoscroll::fit()),
14128 cx,
14129 )[0];
14130 this.pending_rename = Some(RenameState {
14131 range,
14132 old_name,
14133 editor: rename_editor,
14134 block_id,
14135 });
14136 })?;
14137 }
14138
14139 Ok(())
14140 }))
14141 }
14142
14143 pub fn confirm_rename(
14144 &mut self,
14145 _: &ConfirmRename,
14146 window: &mut Window,
14147 cx: &mut Context<Self>,
14148 ) -> Option<Task<Result<()>>> {
14149 let rename = self.take_rename(false, window, cx)?;
14150 let workspace = self.workspace()?.downgrade();
14151 let (buffer, start) = self
14152 .buffer
14153 .read(cx)
14154 .text_anchor_for_position(rename.range.start, cx)?;
14155 let (end_buffer, _) = self
14156 .buffer
14157 .read(cx)
14158 .text_anchor_for_position(rename.range.end, cx)?;
14159 if buffer != end_buffer {
14160 return None;
14161 }
14162
14163 let old_name = rename.old_name;
14164 let new_name = rename.editor.read(cx).text(cx);
14165
14166 let rename = self.semantics_provider.as_ref()?.perform_rename(
14167 &buffer,
14168 start,
14169 new_name.clone(),
14170 cx,
14171 )?;
14172
14173 Some(cx.spawn_in(window, async move |editor, cx| {
14174 let project_transaction = rename.await?;
14175 Self::open_project_transaction(
14176 &editor,
14177 workspace,
14178 project_transaction,
14179 format!("Rename: {} → {}", old_name, new_name),
14180 cx,
14181 )
14182 .await?;
14183
14184 editor.update(cx, |editor, cx| {
14185 editor.refresh_document_highlights(cx);
14186 })?;
14187 Ok(())
14188 }))
14189 }
14190
14191 fn take_rename(
14192 &mut self,
14193 moving_cursor: bool,
14194 window: &mut Window,
14195 cx: &mut Context<Self>,
14196 ) -> Option<RenameState> {
14197 let rename = self.pending_rename.take()?;
14198 if rename.editor.focus_handle(cx).is_focused(window) {
14199 window.focus(&self.focus_handle);
14200 }
14201
14202 self.remove_blocks(
14203 [rename.block_id].into_iter().collect(),
14204 Some(Autoscroll::fit()),
14205 cx,
14206 );
14207 self.clear_highlights::<Rename>(cx);
14208 self.show_local_selections = true;
14209
14210 if moving_cursor {
14211 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14212 editor.selections.newest::<usize>(cx).head()
14213 });
14214
14215 // Update the selection to match the position of the selection inside
14216 // the rename editor.
14217 let snapshot = self.buffer.read(cx).read(cx);
14218 let rename_range = rename.range.to_offset(&snapshot);
14219 let cursor_in_editor = snapshot
14220 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14221 .min(rename_range.end);
14222 drop(snapshot);
14223
14224 self.change_selections(None, window, cx, |s| {
14225 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14226 });
14227 } else {
14228 self.refresh_document_highlights(cx);
14229 }
14230
14231 Some(rename)
14232 }
14233
14234 pub fn pending_rename(&self) -> Option<&RenameState> {
14235 self.pending_rename.as_ref()
14236 }
14237
14238 fn format(
14239 &mut self,
14240 _: &Format,
14241 window: &mut Window,
14242 cx: &mut Context<Self>,
14243 ) -> Option<Task<Result<()>>> {
14244 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14245
14246 let project = match &self.project {
14247 Some(project) => project.clone(),
14248 None => return None,
14249 };
14250
14251 Some(self.perform_format(
14252 project,
14253 FormatTrigger::Manual,
14254 FormatTarget::Buffers,
14255 window,
14256 cx,
14257 ))
14258 }
14259
14260 fn format_selections(
14261 &mut self,
14262 _: &FormatSelections,
14263 window: &mut Window,
14264 cx: &mut Context<Self>,
14265 ) -> Option<Task<Result<()>>> {
14266 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14267
14268 let project = match &self.project {
14269 Some(project) => project.clone(),
14270 None => return None,
14271 };
14272
14273 let ranges = self
14274 .selections
14275 .all_adjusted(cx)
14276 .into_iter()
14277 .map(|selection| selection.range())
14278 .collect_vec();
14279
14280 Some(self.perform_format(
14281 project,
14282 FormatTrigger::Manual,
14283 FormatTarget::Ranges(ranges),
14284 window,
14285 cx,
14286 ))
14287 }
14288
14289 fn perform_format(
14290 &mut self,
14291 project: Entity<Project>,
14292 trigger: FormatTrigger,
14293 target: FormatTarget,
14294 window: &mut Window,
14295 cx: &mut Context<Self>,
14296 ) -> Task<Result<()>> {
14297 let buffer = self.buffer.clone();
14298 let (buffers, target) = match target {
14299 FormatTarget::Buffers => {
14300 let mut buffers = buffer.read(cx).all_buffers();
14301 if trigger == FormatTrigger::Save {
14302 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14303 }
14304 (buffers, LspFormatTarget::Buffers)
14305 }
14306 FormatTarget::Ranges(selection_ranges) => {
14307 let multi_buffer = buffer.read(cx);
14308 let snapshot = multi_buffer.read(cx);
14309 let mut buffers = HashSet::default();
14310 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14311 BTreeMap::new();
14312 for selection_range in selection_ranges {
14313 for (buffer, buffer_range, _) in
14314 snapshot.range_to_buffer_ranges(selection_range)
14315 {
14316 let buffer_id = buffer.remote_id();
14317 let start = buffer.anchor_before(buffer_range.start);
14318 let end = buffer.anchor_after(buffer_range.end);
14319 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14320 buffer_id_to_ranges
14321 .entry(buffer_id)
14322 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14323 .or_insert_with(|| vec![start..end]);
14324 }
14325 }
14326 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14327 }
14328 };
14329
14330 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14331 let selections_prev = transaction_id_prev
14332 .and_then(|transaction_id_prev| {
14333 // default to selections as they were after the last edit, if we have them,
14334 // instead of how they are now.
14335 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14336 // will take you back to where you made the last edit, instead of staying where you scrolled
14337 self.selection_history
14338 .transaction(transaction_id_prev)
14339 .map(|t| t.0.clone())
14340 })
14341 .unwrap_or_else(|| {
14342 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14343 self.selections.disjoint_anchors()
14344 });
14345
14346 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14347 let format = project.update(cx, |project, cx| {
14348 project.format(buffers, target, true, trigger, cx)
14349 });
14350
14351 cx.spawn_in(window, async move |editor, cx| {
14352 let transaction = futures::select_biased! {
14353 transaction = format.log_err().fuse() => transaction,
14354 () = timeout => {
14355 log::warn!("timed out waiting for formatting");
14356 None
14357 }
14358 };
14359
14360 buffer
14361 .update(cx, |buffer, cx| {
14362 if let Some(transaction) = transaction {
14363 if !buffer.is_singleton() {
14364 buffer.push_transaction(&transaction.0, cx);
14365 }
14366 }
14367 cx.notify();
14368 })
14369 .ok();
14370
14371 if let Some(transaction_id_now) =
14372 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14373 {
14374 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14375 if has_new_transaction {
14376 _ = editor.update(cx, |editor, _| {
14377 editor
14378 .selection_history
14379 .insert_transaction(transaction_id_now, selections_prev);
14380 });
14381 }
14382 }
14383
14384 Ok(())
14385 })
14386 }
14387
14388 fn organize_imports(
14389 &mut self,
14390 _: &OrganizeImports,
14391 window: &mut Window,
14392 cx: &mut Context<Self>,
14393 ) -> Option<Task<Result<()>>> {
14394 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14395 let project = match &self.project {
14396 Some(project) => project.clone(),
14397 None => return None,
14398 };
14399 Some(self.perform_code_action_kind(
14400 project,
14401 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14402 window,
14403 cx,
14404 ))
14405 }
14406
14407 fn perform_code_action_kind(
14408 &mut self,
14409 project: Entity<Project>,
14410 kind: CodeActionKind,
14411 window: &mut Window,
14412 cx: &mut Context<Self>,
14413 ) -> Task<Result<()>> {
14414 let buffer = self.buffer.clone();
14415 let buffers = buffer.read(cx).all_buffers();
14416 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14417 let apply_action = project.update(cx, |project, cx| {
14418 project.apply_code_action_kind(buffers, kind, true, cx)
14419 });
14420 cx.spawn_in(window, async move |_, cx| {
14421 let transaction = futures::select_biased! {
14422 () = timeout => {
14423 log::warn!("timed out waiting for executing code action");
14424 None
14425 }
14426 transaction = apply_action.log_err().fuse() => transaction,
14427 };
14428 buffer
14429 .update(cx, |buffer, cx| {
14430 // check if we need this
14431 if let Some(transaction) = transaction {
14432 if !buffer.is_singleton() {
14433 buffer.push_transaction(&transaction.0, cx);
14434 }
14435 }
14436 cx.notify();
14437 })
14438 .ok();
14439 Ok(())
14440 })
14441 }
14442
14443 fn restart_language_server(
14444 &mut self,
14445 _: &RestartLanguageServer,
14446 _: &mut Window,
14447 cx: &mut Context<Self>,
14448 ) {
14449 if let Some(project) = self.project.clone() {
14450 self.buffer.update(cx, |multi_buffer, cx| {
14451 project.update(cx, |project, cx| {
14452 project.restart_language_servers_for_buffers(
14453 multi_buffer.all_buffers().into_iter().collect(),
14454 cx,
14455 );
14456 });
14457 })
14458 }
14459 }
14460
14461 fn stop_language_server(
14462 &mut self,
14463 _: &StopLanguageServer,
14464 _: &mut Window,
14465 cx: &mut Context<Self>,
14466 ) {
14467 if let Some(project) = self.project.clone() {
14468 self.buffer.update(cx, |multi_buffer, cx| {
14469 project.update(cx, |project, cx| {
14470 project.stop_language_servers_for_buffers(
14471 multi_buffer.all_buffers().into_iter().collect(),
14472 cx,
14473 );
14474 cx.emit(project::Event::RefreshInlayHints);
14475 });
14476 });
14477 }
14478 }
14479
14480 fn cancel_language_server_work(
14481 workspace: &mut Workspace,
14482 _: &actions::CancelLanguageServerWork,
14483 _: &mut Window,
14484 cx: &mut Context<Workspace>,
14485 ) {
14486 let project = workspace.project();
14487 let buffers = workspace
14488 .active_item(cx)
14489 .and_then(|item| item.act_as::<Editor>(cx))
14490 .map_or(HashSet::default(), |editor| {
14491 editor.read(cx).buffer.read(cx).all_buffers()
14492 });
14493 project.update(cx, |project, cx| {
14494 project.cancel_language_server_work_for_buffers(buffers, cx);
14495 });
14496 }
14497
14498 fn show_character_palette(
14499 &mut self,
14500 _: &ShowCharacterPalette,
14501 window: &mut Window,
14502 _: &mut Context<Self>,
14503 ) {
14504 window.show_character_palette();
14505 }
14506
14507 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14508 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14509 let buffer = self.buffer.read(cx).snapshot(cx);
14510 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14511 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14512 let is_valid = buffer
14513 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14514 .any(|entry| {
14515 entry.diagnostic.is_primary
14516 && !entry.range.is_empty()
14517 && entry.range.start == primary_range_start
14518 && entry.diagnostic.message == active_diagnostics.active_message
14519 });
14520
14521 if !is_valid {
14522 self.dismiss_diagnostics(cx);
14523 }
14524 }
14525 }
14526
14527 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14528 match &self.active_diagnostics {
14529 ActiveDiagnostic::Group(group) => Some(group),
14530 _ => None,
14531 }
14532 }
14533
14534 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14535 self.dismiss_diagnostics(cx);
14536 self.active_diagnostics = ActiveDiagnostic::All;
14537 }
14538
14539 fn activate_diagnostics(
14540 &mut self,
14541 buffer_id: BufferId,
14542 diagnostic: DiagnosticEntry<usize>,
14543 window: &mut Window,
14544 cx: &mut Context<Self>,
14545 ) {
14546 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14547 return;
14548 }
14549 self.dismiss_diagnostics(cx);
14550 let snapshot = self.snapshot(window, cx);
14551 let Some(diagnostic_renderer) = cx
14552 .try_global::<GlobalDiagnosticRenderer>()
14553 .map(|g| g.0.clone())
14554 else {
14555 return;
14556 };
14557 let buffer = self.buffer.read(cx).snapshot(cx);
14558
14559 let diagnostic_group = buffer
14560 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14561 .collect::<Vec<_>>();
14562
14563 let blocks = diagnostic_renderer.render_group(
14564 diagnostic_group,
14565 buffer_id,
14566 snapshot,
14567 cx.weak_entity(),
14568 cx,
14569 );
14570
14571 let blocks = self.display_map.update(cx, |display_map, cx| {
14572 display_map.insert_blocks(blocks, cx).into_iter().collect()
14573 });
14574 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14575 active_range: buffer.anchor_before(diagnostic.range.start)
14576 ..buffer.anchor_after(diagnostic.range.end),
14577 active_message: diagnostic.diagnostic.message.clone(),
14578 group_id: diagnostic.diagnostic.group_id,
14579 blocks,
14580 });
14581 cx.notify();
14582 }
14583
14584 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14585 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14586 return;
14587 };
14588
14589 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14590 if let ActiveDiagnostic::Group(group) = prev {
14591 self.display_map.update(cx, |display_map, cx| {
14592 display_map.remove_blocks(group.blocks, cx);
14593 });
14594 cx.notify();
14595 }
14596 }
14597
14598 /// Disable inline diagnostics rendering for this editor.
14599 pub fn disable_inline_diagnostics(&mut self) {
14600 self.inline_diagnostics_enabled = false;
14601 self.inline_diagnostics_update = Task::ready(());
14602 self.inline_diagnostics.clear();
14603 }
14604
14605 pub fn inline_diagnostics_enabled(&self) -> bool {
14606 self.inline_diagnostics_enabled
14607 }
14608
14609 pub fn show_inline_diagnostics(&self) -> bool {
14610 self.show_inline_diagnostics
14611 }
14612
14613 pub fn toggle_inline_diagnostics(
14614 &mut self,
14615 _: &ToggleInlineDiagnostics,
14616 window: &mut Window,
14617 cx: &mut Context<Editor>,
14618 ) {
14619 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14620 self.refresh_inline_diagnostics(false, window, cx);
14621 }
14622
14623 fn refresh_inline_diagnostics(
14624 &mut self,
14625 debounce: bool,
14626 window: &mut Window,
14627 cx: &mut Context<Self>,
14628 ) {
14629 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14630 self.inline_diagnostics_update = Task::ready(());
14631 self.inline_diagnostics.clear();
14632 return;
14633 }
14634
14635 let debounce_ms = ProjectSettings::get_global(cx)
14636 .diagnostics
14637 .inline
14638 .update_debounce_ms;
14639 let debounce = if debounce && debounce_ms > 0 {
14640 Some(Duration::from_millis(debounce_ms))
14641 } else {
14642 None
14643 };
14644 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14645 let editor = editor.upgrade().unwrap();
14646
14647 if let Some(debounce) = debounce {
14648 cx.background_executor().timer(debounce).await;
14649 }
14650 let Some(snapshot) = editor
14651 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14652 .ok()
14653 else {
14654 return;
14655 };
14656
14657 let new_inline_diagnostics = cx
14658 .background_spawn(async move {
14659 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14660 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14661 let message = diagnostic_entry
14662 .diagnostic
14663 .message
14664 .split_once('\n')
14665 .map(|(line, _)| line)
14666 .map(SharedString::new)
14667 .unwrap_or_else(|| {
14668 SharedString::from(diagnostic_entry.diagnostic.message)
14669 });
14670 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14671 let (Ok(i) | Err(i)) = inline_diagnostics
14672 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14673 inline_diagnostics.insert(
14674 i,
14675 (
14676 start_anchor,
14677 InlineDiagnostic {
14678 message,
14679 group_id: diagnostic_entry.diagnostic.group_id,
14680 start: diagnostic_entry.range.start.to_point(&snapshot),
14681 is_primary: diagnostic_entry.diagnostic.is_primary,
14682 severity: diagnostic_entry.diagnostic.severity,
14683 },
14684 ),
14685 );
14686 }
14687 inline_diagnostics
14688 })
14689 .await;
14690
14691 editor
14692 .update(cx, |editor, cx| {
14693 editor.inline_diagnostics = new_inline_diagnostics;
14694 cx.notify();
14695 })
14696 .ok();
14697 });
14698 }
14699
14700 pub fn set_selections_from_remote(
14701 &mut self,
14702 selections: Vec<Selection<Anchor>>,
14703 pending_selection: Option<Selection<Anchor>>,
14704 window: &mut Window,
14705 cx: &mut Context<Self>,
14706 ) {
14707 let old_cursor_position = self.selections.newest_anchor().head();
14708 self.selections.change_with(cx, |s| {
14709 s.select_anchors(selections);
14710 if let Some(pending_selection) = pending_selection {
14711 s.set_pending(pending_selection, SelectMode::Character);
14712 } else {
14713 s.clear_pending();
14714 }
14715 });
14716 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14717 }
14718
14719 fn push_to_selection_history(&mut self) {
14720 self.selection_history.push(SelectionHistoryEntry {
14721 selections: self.selections.disjoint_anchors(),
14722 select_next_state: self.select_next_state.clone(),
14723 select_prev_state: self.select_prev_state.clone(),
14724 add_selections_state: self.add_selections_state.clone(),
14725 });
14726 }
14727
14728 pub fn transact(
14729 &mut self,
14730 window: &mut Window,
14731 cx: &mut Context<Self>,
14732 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14733 ) -> Option<TransactionId> {
14734 self.start_transaction_at(Instant::now(), window, cx);
14735 update(self, window, cx);
14736 self.end_transaction_at(Instant::now(), cx)
14737 }
14738
14739 pub fn start_transaction_at(
14740 &mut self,
14741 now: Instant,
14742 window: &mut Window,
14743 cx: &mut Context<Self>,
14744 ) {
14745 self.end_selection(window, cx);
14746 if let Some(tx_id) = self
14747 .buffer
14748 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14749 {
14750 self.selection_history
14751 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14752 cx.emit(EditorEvent::TransactionBegun {
14753 transaction_id: tx_id,
14754 })
14755 }
14756 }
14757
14758 pub fn end_transaction_at(
14759 &mut self,
14760 now: Instant,
14761 cx: &mut Context<Self>,
14762 ) -> Option<TransactionId> {
14763 if let Some(transaction_id) = self
14764 .buffer
14765 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14766 {
14767 if let Some((_, end_selections)) =
14768 self.selection_history.transaction_mut(transaction_id)
14769 {
14770 *end_selections = Some(self.selections.disjoint_anchors());
14771 } else {
14772 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14773 }
14774
14775 cx.emit(EditorEvent::Edited { transaction_id });
14776 Some(transaction_id)
14777 } else {
14778 None
14779 }
14780 }
14781
14782 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14783 if self.selection_mark_mode {
14784 self.change_selections(None, window, cx, |s| {
14785 s.move_with(|_, sel| {
14786 sel.collapse_to(sel.head(), SelectionGoal::None);
14787 });
14788 })
14789 }
14790 self.selection_mark_mode = true;
14791 cx.notify();
14792 }
14793
14794 pub fn swap_selection_ends(
14795 &mut self,
14796 _: &actions::SwapSelectionEnds,
14797 window: &mut Window,
14798 cx: &mut Context<Self>,
14799 ) {
14800 self.change_selections(None, window, cx, |s| {
14801 s.move_with(|_, sel| {
14802 if sel.start != sel.end {
14803 sel.reversed = !sel.reversed
14804 }
14805 });
14806 });
14807 self.request_autoscroll(Autoscroll::newest(), cx);
14808 cx.notify();
14809 }
14810
14811 pub fn toggle_fold(
14812 &mut self,
14813 _: &actions::ToggleFold,
14814 window: &mut Window,
14815 cx: &mut Context<Self>,
14816 ) {
14817 if self.is_singleton(cx) {
14818 let selection = self.selections.newest::<Point>(cx);
14819
14820 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14821 let range = if selection.is_empty() {
14822 let point = selection.head().to_display_point(&display_map);
14823 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14824 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14825 .to_point(&display_map);
14826 start..end
14827 } else {
14828 selection.range()
14829 };
14830 if display_map.folds_in_range(range).next().is_some() {
14831 self.unfold_lines(&Default::default(), window, cx)
14832 } else {
14833 self.fold(&Default::default(), window, cx)
14834 }
14835 } else {
14836 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14837 let buffer_ids: HashSet<_> = self
14838 .selections
14839 .disjoint_anchor_ranges()
14840 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14841 .collect();
14842
14843 let should_unfold = buffer_ids
14844 .iter()
14845 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14846
14847 for buffer_id in buffer_ids {
14848 if should_unfold {
14849 self.unfold_buffer(buffer_id, cx);
14850 } else {
14851 self.fold_buffer(buffer_id, cx);
14852 }
14853 }
14854 }
14855 }
14856
14857 pub fn toggle_fold_recursive(
14858 &mut self,
14859 _: &actions::ToggleFoldRecursive,
14860 window: &mut Window,
14861 cx: &mut Context<Self>,
14862 ) {
14863 let selection = self.selections.newest::<Point>(cx);
14864
14865 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14866 let range = if selection.is_empty() {
14867 let point = selection.head().to_display_point(&display_map);
14868 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14869 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14870 .to_point(&display_map);
14871 start..end
14872 } else {
14873 selection.range()
14874 };
14875 if display_map.folds_in_range(range).next().is_some() {
14876 self.unfold_recursive(&Default::default(), window, cx)
14877 } else {
14878 self.fold_recursive(&Default::default(), window, cx)
14879 }
14880 }
14881
14882 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14883 if self.is_singleton(cx) {
14884 let mut to_fold = Vec::new();
14885 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14886 let selections = self.selections.all_adjusted(cx);
14887
14888 for selection in selections {
14889 let range = selection.range().sorted();
14890 let buffer_start_row = range.start.row;
14891
14892 if range.start.row != range.end.row {
14893 let mut found = false;
14894 let mut row = range.start.row;
14895 while row <= range.end.row {
14896 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14897 {
14898 found = true;
14899 row = crease.range().end.row + 1;
14900 to_fold.push(crease);
14901 } else {
14902 row += 1
14903 }
14904 }
14905 if found {
14906 continue;
14907 }
14908 }
14909
14910 for row in (0..=range.start.row).rev() {
14911 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14912 if crease.range().end.row >= buffer_start_row {
14913 to_fold.push(crease);
14914 if row <= range.start.row {
14915 break;
14916 }
14917 }
14918 }
14919 }
14920 }
14921
14922 self.fold_creases(to_fold, true, window, cx);
14923 } else {
14924 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14925 let buffer_ids = self
14926 .selections
14927 .disjoint_anchor_ranges()
14928 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14929 .collect::<HashSet<_>>();
14930 for buffer_id in buffer_ids {
14931 self.fold_buffer(buffer_id, cx);
14932 }
14933 }
14934 }
14935
14936 fn fold_at_level(
14937 &mut self,
14938 fold_at: &FoldAtLevel,
14939 window: &mut Window,
14940 cx: &mut Context<Self>,
14941 ) {
14942 if !self.buffer.read(cx).is_singleton() {
14943 return;
14944 }
14945
14946 let fold_at_level = fold_at.0;
14947 let snapshot = self.buffer.read(cx).snapshot(cx);
14948 let mut to_fold = Vec::new();
14949 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14950
14951 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14952 while start_row < end_row {
14953 match self
14954 .snapshot(window, cx)
14955 .crease_for_buffer_row(MultiBufferRow(start_row))
14956 {
14957 Some(crease) => {
14958 let nested_start_row = crease.range().start.row + 1;
14959 let nested_end_row = crease.range().end.row;
14960
14961 if current_level < fold_at_level {
14962 stack.push((nested_start_row, nested_end_row, current_level + 1));
14963 } else if current_level == fold_at_level {
14964 to_fold.push(crease);
14965 }
14966
14967 start_row = nested_end_row + 1;
14968 }
14969 None => start_row += 1,
14970 }
14971 }
14972 }
14973
14974 self.fold_creases(to_fold, true, window, cx);
14975 }
14976
14977 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14978 if self.buffer.read(cx).is_singleton() {
14979 let mut fold_ranges = Vec::new();
14980 let snapshot = self.buffer.read(cx).snapshot(cx);
14981
14982 for row in 0..snapshot.max_row().0 {
14983 if let Some(foldable_range) = self
14984 .snapshot(window, cx)
14985 .crease_for_buffer_row(MultiBufferRow(row))
14986 {
14987 fold_ranges.push(foldable_range);
14988 }
14989 }
14990
14991 self.fold_creases(fold_ranges, true, window, cx);
14992 } else {
14993 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14994 editor
14995 .update_in(cx, |editor, _, cx| {
14996 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14997 editor.fold_buffer(buffer_id, cx);
14998 }
14999 })
15000 .ok();
15001 });
15002 }
15003 }
15004
15005 pub fn fold_function_bodies(
15006 &mut self,
15007 _: &actions::FoldFunctionBodies,
15008 window: &mut Window,
15009 cx: &mut Context<Self>,
15010 ) {
15011 let snapshot = self.buffer.read(cx).snapshot(cx);
15012
15013 let ranges = snapshot
15014 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15015 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15016 .collect::<Vec<_>>();
15017
15018 let creases = ranges
15019 .into_iter()
15020 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15021 .collect();
15022
15023 self.fold_creases(creases, true, window, cx);
15024 }
15025
15026 pub fn fold_recursive(
15027 &mut self,
15028 _: &actions::FoldRecursive,
15029 window: &mut Window,
15030 cx: &mut Context<Self>,
15031 ) {
15032 let mut to_fold = Vec::new();
15033 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15034 let selections = self.selections.all_adjusted(cx);
15035
15036 for selection in selections {
15037 let range = selection.range().sorted();
15038 let buffer_start_row = range.start.row;
15039
15040 if range.start.row != range.end.row {
15041 let mut found = false;
15042 for row in range.start.row..=range.end.row {
15043 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15044 found = true;
15045 to_fold.push(crease);
15046 }
15047 }
15048 if found {
15049 continue;
15050 }
15051 }
15052
15053 for row in (0..=range.start.row).rev() {
15054 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15055 if crease.range().end.row >= buffer_start_row {
15056 to_fold.push(crease);
15057 } else {
15058 break;
15059 }
15060 }
15061 }
15062 }
15063
15064 self.fold_creases(to_fold, true, window, cx);
15065 }
15066
15067 pub fn fold_at(
15068 &mut self,
15069 buffer_row: MultiBufferRow,
15070 window: &mut Window,
15071 cx: &mut Context<Self>,
15072 ) {
15073 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15074
15075 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15076 let autoscroll = self
15077 .selections
15078 .all::<Point>(cx)
15079 .iter()
15080 .any(|selection| crease.range().overlaps(&selection.range()));
15081
15082 self.fold_creases(vec![crease], autoscroll, window, cx);
15083 }
15084 }
15085
15086 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15087 if self.is_singleton(cx) {
15088 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15089 let buffer = &display_map.buffer_snapshot;
15090 let selections = self.selections.all::<Point>(cx);
15091 let ranges = selections
15092 .iter()
15093 .map(|s| {
15094 let range = s.display_range(&display_map).sorted();
15095 let mut start = range.start.to_point(&display_map);
15096 let mut end = range.end.to_point(&display_map);
15097 start.column = 0;
15098 end.column = buffer.line_len(MultiBufferRow(end.row));
15099 start..end
15100 })
15101 .collect::<Vec<_>>();
15102
15103 self.unfold_ranges(&ranges, true, true, cx);
15104 } else {
15105 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15106 let buffer_ids = self
15107 .selections
15108 .disjoint_anchor_ranges()
15109 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15110 .collect::<HashSet<_>>();
15111 for buffer_id in buffer_ids {
15112 self.unfold_buffer(buffer_id, cx);
15113 }
15114 }
15115 }
15116
15117 pub fn unfold_recursive(
15118 &mut self,
15119 _: &UnfoldRecursive,
15120 _window: &mut Window,
15121 cx: &mut Context<Self>,
15122 ) {
15123 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15124 let selections = self.selections.all::<Point>(cx);
15125 let ranges = selections
15126 .iter()
15127 .map(|s| {
15128 let mut range = s.display_range(&display_map).sorted();
15129 *range.start.column_mut() = 0;
15130 *range.end.column_mut() = display_map.line_len(range.end.row());
15131 let start = range.start.to_point(&display_map);
15132 let end = range.end.to_point(&display_map);
15133 start..end
15134 })
15135 .collect::<Vec<_>>();
15136
15137 self.unfold_ranges(&ranges, true, true, cx);
15138 }
15139
15140 pub fn unfold_at(
15141 &mut self,
15142 buffer_row: MultiBufferRow,
15143 _window: &mut Window,
15144 cx: &mut Context<Self>,
15145 ) {
15146 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15147
15148 let intersection_range = Point::new(buffer_row.0, 0)
15149 ..Point::new(
15150 buffer_row.0,
15151 display_map.buffer_snapshot.line_len(buffer_row),
15152 );
15153
15154 let autoscroll = self
15155 .selections
15156 .all::<Point>(cx)
15157 .iter()
15158 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15159
15160 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15161 }
15162
15163 pub fn unfold_all(
15164 &mut self,
15165 _: &actions::UnfoldAll,
15166 _window: &mut Window,
15167 cx: &mut Context<Self>,
15168 ) {
15169 if self.buffer.read(cx).is_singleton() {
15170 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15171 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15172 } else {
15173 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15174 editor
15175 .update(cx, |editor, cx| {
15176 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15177 editor.unfold_buffer(buffer_id, cx);
15178 }
15179 })
15180 .ok();
15181 });
15182 }
15183 }
15184
15185 pub fn fold_selected_ranges(
15186 &mut self,
15187 _: &FoldSelectedRanges,
15188 window: &mut Window,
15189 cx: &mut Context<Self>,
15190 ) {
15191 let selections = self.selections.all_adjusted(cx);
15192 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15193 let ranges = selections
15194 .into_iter()
15195 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15196 .collect::<Vec<_>>();
15197 self.fold_creases(ranges, true, window, cx);
15198 }
15199
15200 pub fn fold_ranges<T: ToOffset + Clone>(
15201 &mut self,
15202 ranges: Vec<Range<T>>,
15203 auto_scroll: bool,
15204 window: &mut Window,
15205 cx: &mut Context<Self>,
15206 ) {
15207 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15208 let ranges = ranges
15209 .into_iter()
15210 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15211 .collect::<Vec<_>>();
15212 self.fold_creases(ranges, auto_scroll, window, cx);
15213 }
15214
15215 pub fn fold_creases<T: ToOffset + Clone>(
15216 &mut self,
15217 creases: Vec<Crease<T>>,
15218 auto_scroll: bool,
15219 _window: &mut Window,
15220 cx: &mut Context<Self>,
15221 ) {
15222 if creases.is_empty() {
15223 return;
15224 }
15225
15226 let mut buffers_affected = HashSet::default();
15227 let multi_buffer = self.buffer().read(cx);
15228 for crease in &creases {
15229 if let Some((_, buffer, _)) =
15230 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15231 {
15232 buffers_affected.insert(buffer.read(cx).remote_id());
15233 };
15234 }
15235
15236 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15237
15238 if auto_scroll {
15239 self.request_autoscroll(Autoscroll::fit(), cx);
15240 }
15241
15242 cx.notify();
15243
15244 self.scrollbar_marker_state.dirty = true;
15245 self.folds_did_change(cx);
15246 }
15247
15248 /// Removes any folds whose ranges intersect any of the given ranges.
15249 pub fn unfold_ranges<T: ToOffset + Clone>(
15250 &mut self,
15251 ranges: &[Range<T>],
15252 inclusive: bool,
15253 auto_scroll: bool,
15254 cx: &mut Context<Self>,
15255 ) {
15256 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15257 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15258 });
15259 self.folds_did_change(cx);
15260 }
15261
15262 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15263 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15264 return;
15265 }
15266 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15267 self.display_map.update(cx, |display_map, cx| {
15268 display_map.fold_buffers([buffer_id], cx)
15269 });
15270 cx.emit(EditorEvent::BufferFoldToggled {
15271 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15272 folded: true,
15273 });
15274 cx.notify();
15275 }
15276
15277 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15278 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15279 return;
15280 }
15281 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15282 self.display_map.update(cx, |display_map, cx| {
15283 display_map.unfold_buffers([buffer_id], cx);
15284 });
15285 cx.emit(EditorEvent::BufferFoldToggled {
15286 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15287 folded: false,
15288 });
15289 cx.notify();
15290 }
15291
15292 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15293 self.display_map.read(cx).is_buffer_folded(buffer)
15294 }
15295
15296 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15297 self.display_map.read(cx).folded_buffers()
15298 }
15299
15300 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15301 self.display_map.update(cx, |display_map, cx| {
15302 display_map.disable_header_for_buffer(buffer_id, cx);
15303 });
15304 cx.notify();
15305 }
15306
15307 /// Removes any folds with the given ranges.
15308 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15309 &mut self,
15310 ranges: &[Range<T>],
15311 type_id: TypeId,
15312 auto_scroll: bool,
15313 cx: &mut Context<Self>,
15314 ) {
15315 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15316 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15317 });
15318 self.folds_did_change(cx);
15319 }
15320
15321 fn remove_folds_with<T: ToOffset + Clone>(
15322 &mut self,
15323 ranges: &[Range<T>],
15324 auto_scroll: bool,
15325 cx: &mut Context<Self>,
15326 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15327 ) {
15328 if ranges.is_empty() {
15329 return;
15330 }
15331
15332 let mut buffers_affected = HashSet::default();
15333 let multi_buffer = self.buffer().read(cx);
15334 for range in ranges {
15335 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15336 buffers_affected.insert(buffer.read(cx).remote_id());
15337 };
15338 }
15339
15340 self.display_map.update(cx, update);
15341
15342 if auto_scroll {
15343 self.request_autoscroll(Autoscroll::fit(), cx);
15344 }
15345
15346 cx.notify();
15347 self.scrollbar_marker_state.dirty = true;
15348 self.active_indent_guides_state.dirty = true;
15349 }
15350
15351 pub fn update_fold_widths(
15352 &mut self,
15353 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15354 cx: &mut Context<Self>,
15355 ) -> bool {
15356 self.display_map
15357 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15358 }
15359
15360 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15361 self.display_map.read(cx).fold_placeholder.clone()
15362 }
15363
15364 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15365 self.buffer.update(cx, |buffer, cx| {
15366 buffer.set_all_diff_hunks_expanded(cx);
15367 });
15368 }
15369
15370 pub fn expand_all_diff_hunks(
15371 &mut self,
15372 _: &ExpandAllDiffHunks,
15373 _window: &mut Window,
15374 cx: &mut Context<Self>,
15375 ) {
15376 self.buffer.update(cx, |buffer, cx| {
15377 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15378 });
15379 }
15380
15381 pub fn toggle_selected_diff_hunks(
15382 &mut self,
15383 _: &ToggleSelectedDiffHunks,
15384 _window: &mut Window,
15385 cx: &mut Context<Self>,
15386 ) {
15387 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15388 self.toggle_diff_hunks_in_ranges(ranges, cx);
15389 }
15390
15391 pub fn diff_hunks_in_ranges<'a>(
15392 &'a self,
15393 ranges: &'a [Range<Anchor>],
15394 buffer: &'a MultiBufferSnapshot,
15395 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15396 ranges.iter().flat_map(move |range| {
15397 let end_excerpt_id = range.end.excerpt_id;
15398 let range = range.to_point(buffer);
15399 let mut peek_end = range.end;
15400 if range.end.row < buffer.max_row().0 {
15401 peek_end = Point::new(range.end.row + 1, 0);
15402 }
15403 buffer
15404 .diff_hunks_in_range(range.start..peek_end)
15405 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15406 })
15407 }
15408
15409 pub fn has_stageable_diff_hunks_in_ranges(
15410 &self,
15411 ranges: &[Range<Anchor>],
15412 snapshot: &MultiBufferSnapshot,
15413 ) -> bool {
15414 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15415 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15416 }
15417
15418 pub fn toggle_staged_selected_diff_hunks(
15419 &mut self,
15420 _: &::git::ToggleStaged,
15421 _: &mut Window,
15422 cx: &mut Context<Self>,
15423 ) {
15424 let snapshot = self.buffer.read(cx).snapshot(cx);
15425 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15426 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15427 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15428 }
15429
15430 pub fn set_render_diff_hunk_controls(
15431 &mut self,
15432 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15433 cx: &mut Context<Self>,
15434 ) {
15435 self.render_diff_hunk_controls = render_diff_hunk_controls;
15436 cx.notify();
15437 }
15438
15439 pub fn stage_and_next(
15440 &mut self,
15441 _: &::git::StageAndNext,
15442 window: &mut Window,
15443 cx: &mut Context<Self>,
15444 ) {
15445 self.do_stage_or_unstage_and_next(true, window, cx);
15446 }
15447
15448 pub fn unstage_and_next(
15449 &mut self,
15450 _: &::git::UnstageAndNext,
15451 window: &mut Window,
15452 cx: &mut Context<Self>,
15453 ) {
15454 self.do_stage_or_unstage_and_next(false, window, cx);
15455 }
15456
15457 pub fn stage_or_unstage_diff_hunks(
15458 &mut self,
15459 stage: bool,
15460 ranges: Vec<Range<Anchor>>,
15461 cx: &mut Context<Self>,
15462 ) {
15463 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15464 cx.spawn(async move |this, cx| {
15465 task.await?;
15466 this.update(cx, |this, cx| {
15467 let snapshot = this.buffer.read(cx).snapshot(cx);
15468 let chunk_by = this
15469 .diff_hunks_in_ranges(&ranges, &snapshot)
15470 .chunk_by(|hunk| hunk.buffer_id);
15471 for (buffer_id, hunks) in &chunk_by {
15472 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15473 }
15474 })
15475 })
15476 .detach_and_log_err(cx);
15477 }
15478
15479 fn save_buffers_for_ranges_if_needed(
15480 &mut self,
15481 ranges: &[Range<Anchor>],
15482 cx: &mut Context<Editor>,
15483 ) -> Task<Result<()>> {
15484 let multibuffer = self.buffer.read(cx);
15485 let snapshot = multibuffer.read(cx);
15486 let buffer_ids: HashSet<_> = ranges
15487 .iter()
15488 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15489 .collect();
15490 drop(snapshot);
15491
15492 let mut buffers = HashSet::default();
15493 for buffer_id in buffer_ids {
15494 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15495 let buffer = buffer_entity.read(cx);
15496 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15497 {
15498 buffers.insert(buffer_entity);
15499 }
15500 }
15501 }
15502
15503 if let Some(project) = &self.project {
15504 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15505 } else {
15506 Task::ready(Ok(()))
15507 }
15508 }
15509
15510 fn do_stage_or_unstage_and_next(
15511 &mut self,
15512 stage: bool,
15513 window: &mut Window,
15514 cx: &mut Context<Self>,
15515 ) {
15516 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15517
15518 if ranges.iter().any(|range| range.start != range.end) {
15519 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15520 return;
15521 }
15522
15523 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15524 let snapshot = self.snapshot(window, cx);
15525 let position = self.selections.newest::<Point>(cx).head();
15526 let mut row = snapshot
15527 .buffer_snapshot
15528 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15529 .find(|hunk| hunk.row_range.start.0 > position.row)
15530 .map(|hunk| hunk.row_range.start);
15531
15532 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15533 // Outside of the project diff editor, wrap around to the beginning.
15534 if !all_diff_hunks_expanded {
15535 row = row.or_else(|| {
15536 snapshot
15537 .buffer_snapshot
15538 .diff_hunks_in_range(Point::zero()..position)
15539 .find(|hunk| hunk.row_range.end.0 < position.row)
15540 .map(|hunk| hunk.row_range.start)
15541 });
15542 }
15543
15544 if let Some(row) = row {
15545 let destination = Point::new(row.0, 0);
15546 let autoscroll = Autoscroll::center();
15547
15548 self.unfold_ranges(&[destination..destination], false, false, cx);
15549 self.change_selections(Some(autoscroll), window, cx, |s| {
15550 s.select_ranges([destination..destination]);
15551 });
15552 }
15553 }
15554
15555 fn do_stage_or_unstage(
15556 &self,
15557 stage: bool,
15558 buffer_id: BufferId,
15559 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15560 cx: &mut App,
15561 ) -> Option<()> {
15562 let project = self.project.as_ref()?;
15563 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15564 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15565 let buffer_snapshot = buffer.read(cx).snapshot();
15566 let file_exists = buffer_snapshot
15567 .file()
15568 .is_some_and(|file| file.disk_state().exists());
15569 diff.update(cx, |diff, cx| {
15570 diff.stage_or_unstage_hunks(
15571 stage,
15572 &hunks
15573 .map(|hunk| buffer_diff::DiffHunk {
15574 buffer_range: hunk.buffer_range,
15575 diff_base_byte_range: hunk.diff_base_byte_range,
15576 secondary_status: hunk.secondary_status,
15577 range: Point::zero()..Point::zero(), // unused
15578 })
15579 .collect::<Vec<_>>(),
15580 &buffer_snapshot,
15581 file_exists,
15582 cx,
15583 )
15584 });
15585 None
15586 }
15587
15588 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15589 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15590 self.buffer
15591 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15592 }
15593
15594 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15595 self.buffer.update(cx, |buffer, cx| {
15596 let ranges = vec![Anchor::min()..Anchor::max()];
15597 if !buffer.all_diff_hunks_expanded()
15598 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15599 {
15600 buffer.collapse_diff_hunks(ranges, cx);
15601 true
15602 } else {
15603 false
15604 }
15605 })
15606 }
15607
15608 fn toggle_diff_hunks_in_ranges(
15609 &mut self,
15610 ranges: Vec<Range<Anchor>>,
15611 cx: &mut Context<Editor>,
15612 ) {
15613 self.buffer.update(cx, |buffer, cx| {
15614 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15615 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15616 })
15617 }
15618
15619 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15620 self.buffer.update(cx, |buffer, cx| {
15621 let snapshot = buffer.snapshot(cx);
15622 let excerpt_id = range.end.excerpt_id;
15623 let point_range = range.to_point(&snapshot);
15624 let expand = !buffer.single_hunk_is_expanded(range, cx);
15625 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15626 })
15627 }
15628
15629 pub(crate) fn apply_all_diff_hunks(
15630 &mut self,
15631 _: &ApplyAllDiffHunks,
15632 window: &mut Window,
15633 cx: &mut Context<Self>,
15634 ) {
15635 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15636
15637 let buffers = self.buffer.read(cx).all_buffers();
15638 for branch_buffer in buffers {
15639 branch_buffer.update(cx, |branch_buffer, cx| {
15640 branch_buffer.merge_into_base(Vec::new(), cx);
15641 });
15642 }
15643
15644 if let Some(project) = self.project.clone() {
15645 self.save(true, project, window, cx).detach_and_log_err(cx);
15646 }
15647 }
15648
15649 pub(crate) fn apply_selected_diff_hunks(
15650 &mut self,
15651 _: &ApplyDiffHunk,
15652 window: &mut Window,
15653 cx: &mut Context<Self>,
15654 ) {
15655 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15656 let snapshot = self.snapshot(window, cx);
15657 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15658 let mut ranges_by_buffer = HashMap::default();
15659 self.transact(window, cx, |editor, _window, cx| {
15660 for hunk in hunks {
15661 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15662 ranges_by_buffer
15663 .entry(buffer.clone())
15664 .or_insert_with(Vec::new)
15665 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15666 }
15667 }
15668
15669 for (buffer, ranges) in ranges_by_buffer {
15670 buffer.update(cx, |buffer, cx| {
15671 buffer.merge_into_base(ranges, cx);
15672 });
15673 }
15674 });
15675
15676 if let Some(project) = self.project.clone() {
15677 self.save(true, project, window, cx).detach_and_log_err(cx);
15678 }
15679 }
15680
15681 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15682 if hovered != self.gutter_hovered {
15683 self.gutter_hovered = hovered;
15684 cx.notify();
15685 }
15686 }
15687
15688 pub fn insert_blocks(
15689 &mut self,
15690 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15691 autoscroll: Option<Autoscroll>,
15692 cx: &mut Context<Self>,
15693 ) -> Vec<CustomBlockId> {
15694 let blocks = self
15695 .display_map
15696 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15697 if let Some(autoscroll) = autoscroll {
15698 self.request_autoscroll(autoscroll, cx);
15699 }
15700 cx.notify();
15701 blocks
15702 }
15703
15704 pub fn resize_blocks(
15705 &mut self,
15706 heights: HashMap<CustomBlockId, u32>,
15707 autoscroll: Option<Autoscroll>,
15708 cx: &mut Context<Self>,
15709 ) {
15710 self.display_map
15711 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15712 if let Some(autoscroll) = autoscroll {
15713 self.request_autoscroll(autoscroll, cx);
15714 }
15715 cx.notify();
15716 }
15717
15718 pub fn replace_blocks(
15719 &mut self,
15720 renderers: HashMap<CustomBlockId, RenderBlock>,
15721 autoscroll: Option<Autoscroll>,
15722 cx: &mut Context<Self>,
15723 ) {
15724 self.display_map
15725 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15726 if let Some(autoscroll) = autoscroll {
15727 self.request_autoscroll(autoscroll, cx);
15728 }
15729 cx.notify();
15730 }
15731
15732 pub fn remove_blocks(
15733 &mut self,
15734 block_ids: HashSet<CustomBlockId>,
15735 autoscroll: Option<Autoscroll>,
15736 cx: &mut Context<Self>,
15737 ) {
15738 self.display_map.update(cx, |display_map, cx| {
15739 display_map.remove_blocks(block_ids, cx)
15740 });
15741 if let Some(autoscroll) = autoscroll {
15742 self.request_autoscroll(autoscroll, cx);
15743 }
15744 cx.notify();
15745 }
15746
15747 pub fn row_for_block(
15748 &self,
15749 block_id: CustomBlockId,
15750 cx: &mut Context<Self>,
15751 ) -> Option<DisplayRow> {
15752 self.display_map
15753 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15754 }
15755
15756 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15757 self.focused_block = Some(focused_block);
15758 }
15759
15760 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15761 self.focused_block.take()
15762 }
15763
15764 pub fn insert_creases(
15765 &mut self,
15766 creases: impl IntoIterator<Item = Crease<Anchor>>,
15767 cx: &mut Context<Self>,
15768 ) -> Vec<CreaseId> {
15769 self.display_map
15770 .update(cx, |map, cx| map.insert_creases(creases, cx))
15771 }
15772
15773 pub fn remove_creases(
15774 &mut self,
15775 ids: impl IntoIterator<Item = CreaseId>,
15776 cx: &mut Context<Self>,
15777 ) {
15778 self.display_map
15779 .update(cx, |map, cx| map.remove_creases(ids, cx));
15780 }
15781
15782 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15783 self.display_map
15784 .update(cx, |map, cx| map.snapshot(cx))
15785 .longest_row()
15786 }
15787
15788 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15789 self.display_map
15790 .update(cx, |map, cx| map.snapshot(cx))
15791 .max_point()
15792 }
15793
15794 pub fn text(&self, cx: &App) -> String {
15795 self.buffer.read(cx).read(cx).text()
15796 }
15797
15798 pub fn is_empty(&self, cx: &App) -> bool {
15799 self.buffer.read(cx).read(cx).is_empty()
15800 }
15801
15802 pub fn text_option(&self, cx: &App) -> Option<String> {
15803 let text = self.text(cx);
15804 let text = text.trim();
15805
15806 if text.is_empty() {
15807 return None;
15808 }
15809
15810 Some(text.to_string())
15811 }
15812
15813 pub fn set_text(
15814 &mut self,
15815 text: impl Into<Arc<str>>,
15816 window: &mut Window,
15817 cx: &mut Context<Self>,
15818 ) {
15819 self.transact(window, cx, |this, _, cx| {
15820 this.buffer
15821 .read(cx)
15822 .as_singleton()
15823 .expect("you can only call set_text on editors for singleton buffers")
15824 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15825 });
15826 }
15827
15828 pub fn display_text(&self, cx: &mut App) -> String {
15829 self.display_map
15830 .update(cx, |map, cx| map.snapshot(cx))
15831 .text()
15832 }
15833
15834 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15835 let mut wrap_guides = smallvec::smallvec![];
15836
15837 if self.show_wrap_guides == Some(false) {
15838 return wrap_guides;
15839 }
15840
15841 let settings = self.buffer.read(cx).language_settings(cx);
15842 if settings.show_wrap_guides {
15843 match self.soft_wrap_mode(cx) {
15844 SoftWrap::Column(soft_wrap) => {
15845 wrap_guides.push((soft_wrap as usize, true));
15846 }
15847 SoftWrap::Bounded(soft_wrap) => {
15848 wrap_guides.push((soft_wrap as usize, true));
15849 }
15850 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15851 }
15852 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15853 }
15854
15855 wrap_guides
15856 }
15857
15858 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15859 let settings = self.buffer.read(cx).language_settings(cx);
15860 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15861 match mode {
15862 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15863 SoftWrap::None
15864 }
15865 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15866 language_settings::SoftWrap::PreferredLineLength => {
15867 SoftWrap::Column(settings.preferred_line_length)
15868 }
15869 language_settings::SoftWrap::Bounded => {
15870 SoftWrap::Bounded(settings.preferred_line_length)
15871 }
15872 }
15873 }
15874
15875 pub fn set_soft_wrap_mode(
15876 &mut self,
15877 mode: language_settings::SoftWrap,
15878
15879 cx: &mut Context<Self>,
15880 ) {
15881 self.soft_wrap_mode_override = Some(mode);
15882 cx.notify();
15883 }
15884
15885 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15886 self.hard_wrap = hard_wrap;
15887 cx.notify();
15888 }
15889
15890 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15891 self.text_style_refinement = Some(style);
15892 }
15893
15894 /// called by the Element so we know what style we were most recently rendered with.
15895 pub(crate) fn set_style(
15896 &mut self,
15897 style: EditorStyle,
15898 window: &mut Window,
15899 cx: &mut Context<Self>,
15900 ) {
15901 let rem_size = window.rem_size();
15902 self.display_map.update(cx, |map, cx| {
15903 map.set_font(
15904 style.text.font(),
15905 style.text.font_size.to_pixels(rem_size),
15906 cx,
15907 )
15908 });
15909 self.style = Some(style);
15910 }
15911
15912 pub fn style(&self) -> Option<&EditorStyle> {
15913 self.style.as_ref()
15914 }
15915
15916 // Called by the element. This method is not designed to be called outside of the editor
15917 // element's layout code because it does not notify when rewrapping is computed synchronously.
15918 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15919 self.display_map
15920 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15921 }
15922
15923 pub fn set_soft_wrap(&mut self) {
15924 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15925 }
15926
15927 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15928 if self.soft_wrap_mode_override.is_some() {
15929 self.soft_wrap_mode_override.take();
15930 } else {
15931 let soft_wrap = match self.soft_wrap_mode(cx) {
15932 SoftWrap::GitDiff => return,
15933 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15934 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15935 language_settings::SoftWrap::None
15936 }
15937 };
15938 self.soft_wrap_mode_override = Some(soft_wrap);
15939 }
15940 cx.notify();
15941 }
15942
15943 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15944 let Some(workspace) = self.workspace() else {
15945 return;
15946 };
15947 let fs = workspace.read(cx).app_state().fs.clone();
15948 let current_show = TabBarSettings::get_global(cx).show;
15949 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15950 setting.show = Some(!current_show);
15951 });
15952 }
15953
15954 pub fn toggle_indent_guides(
15955 &mut self,
15956 _: &ToggleIndentGuides,
15957 _: &mut Window,
15958 cx: &mut Context<Self>,
15959 ) {
15960 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15961 self.buffer
15962 .read(cx)
15963 .language_settings(cx)
15964 .indent_guides
15965 .enabled
15966 });
15967 self.show_indent_guides = Some(!currently_enabled);
15968 cx.notify();
15969 }
15970
15971 fn should_show_indent_guides(&self) -> Option<bool> {
15972 self.show_indent_guides
15973 }
15974
15975 pub fn toggle_line_numbers(
15976 &mut self,
15977 _: &ToggleLineNumbers,
15978 _: &mut Window,
15979 cx: &mut Context<Self>,
15980 ) {
15981 let mut editor_settings = EditorSettings::get_global(cx).clone();
15982 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15983 EditorSettings::override_global(editor_settings, cx);
15984 }
15985
15986 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15987 if let Some(show_line_numbers) = self.show_line_numbers {
15988 return show_line_numbers;
15989 }
15990 EditorSettings::get_global(cx).gutter.line_numbers
15991 }
15992
15993 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15994 self.use_relative_line_numbers
15995 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15996 }
15997
15998 pub fn toggle_relative_line_numbers(
15999 &mut self,
16000 _: &ToggleRelativeLineNumbers,
16001 _: &mut Window,
16002 cx: &mut Context<Self>,
16003 ) {
16004 let is_relative = self.should_use_relative_line_numbers(cx);
16005 self.set_relative_line_number(Some(!is_relative), cx)
16006 }
16007
16008 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16009 self.use_relative_line_numbers = is_relative;
16010 cx.notify();
16011 }
16012
16013 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16014 self.show_gutter = show_gutter;
16015 cx.notify();
16016 }
16017
16018 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16019 self.show_scrollbars = show_scrollbars;
16020 cx.notify();
16021 }
16022
16023 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16024 self.show_line_numbers = Some(show_line_numbers);
16025 cx.notify();
16026 }
16027
16028 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16029 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16030 cx.notify();
16031 }
16032
16033 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16034 self.show_code_actions = Some(show_code_actions);
16035 cx.notify();
16036 }
16037
16038 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16039 self.show_runnables = Some(show_runnables);
16040 cx.notify();
16041 }
16042
16043 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16044 self.show_breakpoints = Some(show_breakpoints);
16045 cx.notify();
16046 }
16047
16048 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16049 if self.display_map.read(cx).masked != masked {
16050 self.display_map.update(cx, |map, _| map.masked = masked);
16051 }
16052 cx.notify()
16053 }
16054
16055 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16056 self.show_wrap_guides = Some(show_wrap_guides);
16057 cx.notify();
16058 }
16059
16060 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16061 self.show_indent_guides = Some(show_indent_guides);
16062 cx.notify();
16063 }
16064
16065 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16066 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16067 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16068 if let Some(dir) = file.abs_path(cx).parent() {
16069 return Some(dir.to_owned());
16070 }
16071 }
16072
16073 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16074 return Some(project_path.path.to_path_buf());
16075 }
16076 }
16077
16078 None
16079 }
16080
16081 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16082 self.active_excerpt(cx)?
16083 .1
16084 .read(cx)
16085 .file()
16086 .and_then(|f| f.as_local())
16087 }
16088
16089 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16090 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16091 let buffer = buffer.read(cx);
16092 if let Some(project_path) = buffer.project_path(cx) {
16093 let project = self.project.as_ref()?.read(cx);
16094 project.absolute_path(&project_path, cx)
16095 } else {
16096 buffer
16097 .file()
16098 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16099 }
16100 })
16101 }
16102
16103 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16104 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16105 let project_path = buffer.read(cx).project_path(cx)?;
16106 let project = self.project.as_ref()?.read(cx);
16107 let entry = project.entry_for_path(&project_path, cx)?;
16108 let path = entry.path.to_path_buf();
16109 Some(path)
16110 })
16111 }
16112
16113 pub fn reveal_in_finder(
16114 &mut self,
16115 _: &RevealInFileManager,
16116 _window: &mut Window,
16117 cx: &mut Context<Self>,
16118 ) {
16119 if let Some(target) = self.target_file(cx) {
16120 cx.reveal_path(&target.abs_path(cx));
16121 }
16122 }
16123
16124 pub fn copy_path(
16125 &mut self,
16126 _: &zed_actions::workspace::CopyPath,
16127 _window: &mut Window,
16128 cx: &mut Context<Self>,
16129 ) {
16130 if let Some(path) = self.target_file_abs_path(cx) {
16131 if let Some(path) = path.to_str() {
16132 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16133 }
16134 }
16135 }
16136
16137 pub fn copy_relative_path(
16138 &mut self,
16139 _: &zed_actions::workspace::CopyRelativePath,
16140 _window: &mut Window,
16141 cx: &mut Context<Self>,
16142 ) {
16143 if let Some(path) = self.target_file_path(cx) {
16144 if let Some(path) = path.to_str() {
16145 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16146 }
16147 }
16148 }
16149
16150 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16151 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16152 buffer.read(cx).project_path(cx)
16153 } else {
16154 None
16155 }
16156 }
16157
16158 // Returns true if the editor handled a go-to-line request
16159 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16160 maybe!({
16161 let breakpoint_store = self.breakpoint_store.as_ref()?;
16162
16163 let Some((_, _, active_position)) =
16164 breakpoint_store.read(cx).active_position().cloned()
16165 else {
16166 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16167 return None;
16168 };
16169
16170 let snapshot = self
16171 .project
16172 .as_ref()?
16173 .read(cx)
16174 .buffer_for_id(active_position.buffer_id?, cx)?
16175 .read(cx)
16176 .snapshot();
16177
16178 let mut handled = false;
16179 for (id, ExcerptRange { context, .. }) in self
16180 .buffer
16181 .read(cx)
16182 .excerpts_for_buffer(active_position.buffer_id?, cx)
16183 {
16184 if context.start.cmp(&active_position, &snapshot).is_ge()
16185 || context.end.cmp(&active_position, &snapshot).is_lt()
16186 {
16187 continue;
16188 }
16189 let snapshot = self.buffer.read(cx).snapshot(cx);
16190 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16191
16192 handled = true;
16193 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16194 self.go_to_line::<DebugCurrentRowHighlight>(
16195 multibuffer_anchor,
16196 Some(cx.theme().colors().editor_debugger_active_line_background),
16197 window,
16198 cx,
16199 );
16200
16201 cx.notify();
16202 }
16203 handled.then_some(())
16204 })
16205 .is_some()
16206 }
16207
16208 pub fn copy_file_name_without_extension(
16209 &mut self,
16210 _: &CopyFileNameWithoutExtension,
16211 _: &mut Window,
16212 cx: &mut Context<Self>,
16213 ) {
16214 if let Some(file) = self.target_file(cx) {
16215 if let Some(file_stem) = file.path().file_stem() {
16216 if let Some(name) = file_stem.to_str() {
16217 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16218 }
16219 }
16220 }
16221 }
16222
16223 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16224 if let Some(file) = self.target_file(cx) {
16225 if let Some(file_name) = file.path().file_name() {
16226 if let Some(name) = file_name.to_str() {
16227 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16228 }
16229 }
16230 }
16231 }
16232
16233 pub fn toggle_git_blame(
16234 &mut self,
16235 _: &::git::Blame,
16236 window: &mut Window,
16237 cx: &mut Context<Self>,
16238 ) {
16239 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16240
16241 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16242 self.start_git_blame(true, window, cx);
16243 }
16244
16245 cx.notify();
16246 }
16247
16248 pub fn toggle_git_blame_inline(
16249 &mut self,
16250 _: &ToggleGitBlameInline,
16251 window: &mut Window,
16252 cx: &mut Context<Self>,
16253 ) {
16254 self.toggle_git_blame_inline_internal(true, window, cx);
16255 cx.notify();
16256 }
16257
16258 pub fn open_git_blame_commit(
16259 &mut self,
16260 _: &OpenGitBlameCommit,
16261 window: &mut Window,
16262 cx: &mut Context<Self>,
16263 ) {
16264 self.open_git_blame_commit_internal(window, cx);
16265 }
16266
16267 fn open_git_blame_commit_internal(
16268 &mut self,
16269 window: &mut Window,
16270 cx: &mut Context<Self>,
16271 ) -> Option<()> {
16272 let blame = self.blame.as_ref()?;
16273 let snapshot = self.snapshot(window, cx);
16274 let cursor = self.selections.newest::<Point>(cx).head();
16275 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16276 let blame_entry = blame
16277 .update(cx, |blame, cx| {
16278 blame
16279 .blame_for_rows(
16280 &[RowInfo {
16281 buffer_id: Some(buffer.remote_id()),
16282 buffer_row: Some(point.row),
16283 ..Default::default()
16284 }],
16285 cx,
16286 )
16287 .next()
16288 })
16289 .flatten()?;
16290 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16291 let repo = blame.read(cx).repository(cx)?;
16292 let workspace = self.workspace()?.downgrade();
16293 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16294 None
16295 }
16296
16297 pub fn git_blame_inline_enabled(&self) -> bool {
16298 self.git_blame_inline_enabled
16299 }
16300
16301 pub fn toggle_selection_menu(
16302 &mut self,
16303 _: &ToggleSelectionMenu,
16304 _: &mut Window,
16305 cx: &mut Context<Self>,
16306 ) {
16307 self.show_selection_menu = self
16308 .show_selection_menu
16309 .map(|show_selections_menu| !show_selections_menu)
16310 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16311
16312 cx.notify();
16313 }
16314
16315 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16316 self.show_selection_menu
16317 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16318 }
16319
16320 fn start_git_blame(
16321 &mut self,
16322 user_triggered: bool,
16323 window: &mut Window,
16324 cx: &mut Context<Self>,
16325 ) {
16326 if let Some(project) = self.project.as_ref() {
16327 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16328 return;
16329 };
16330
16331 if buffer.read(cx).file().is_none() {
16332 return;
16333 }
16334
16335 let focused = self.focus_handle(cx).contains_focused(window, cx);
16336
16337 let project = project.clone();
16338 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16339 self.blame_subscription =
16340 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16341 self.blame = Some(blame);
16342 }
16343 }
16344
16345 fn toggle_git_blame_inline_internal(
16346 &mut self,
16347 user_triggered: bool,
16348 window: &mut Window,
16349 cx: &mut Context<Self>,
16350 ) {
16351 if self.git_blame_inline_enabled {
16352 self.git_blame_inline_enabled = false;
16353 self.show_git_blame_inline = false;
16354 self.show_git_blame_inline_delay_task.take();
16355 } else {
16356 self.git_blame_inline_enabled = true;
16357 self.start_git_blame_inline(user_triggered, window, cx);
16358 }
16359
16360 cx.notify();
16361 }
16362
16363 fn start_git_blame_inline(
16364 &mut self,
16365 user_triggered: bool,
16366 window: &mut Window,
16367 cx: &mut Context<Self>,
16368 ) {
16369 self.start_git_blame(user_triggered, window, cx);
16370
16371 if ProjectSettings::get_global(cx)
16372 .git
16373 .inline_blame_delay()
16374 .is_some()
16375 {
16376 self.start_inline_blame_timer(window, cx);
16377 } else {
16378 self.show_git_blame_inline = true
16379 }
16380 }
16381
16382 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16383 self.blame.as_ref()
16384 }
16385
16386 pub fn show_git_blame_gutter(&self) -> bool {
16387 self.show_git_blame_gutter
16388 }
16389
16390 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16391 self.show_git_blame_gutter && self.has_blame_entries(cx)
16392 }
16393
16394 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16395 self.show_git_blame_inline
16396 && (self.focus_handle.is_focused(window)
16397 || self
16398 .git_blame_inline_tooltip
16399 .as_ref()
16400 .and_then(|t| t.upgrade())
16401 .is_some())
16402 && !self.newest_selection_head_on_empty_line(cx)
16403 && self.has_blame_entries(cx)
16404 }
16405
16406 fn has_blame_entries(&self, cx: &App) -> bool {
16407 self.blame()
16408 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16409 }
16410
16411 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16412 let cursor_anchor = self.selections.newest_anchor().head();
16413
16414 let snapshot = self.buffer.read(cx).snapshot(cx);
16415 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16416
16417 snapshot.line_len(buffer_row) == 0
16418 }
16419
16420 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16421 let buffer_and_selection = maybe!({
16422 let selection = self.selections.newest::<Point>(cx);
16423 let selection_range = selection.range();
16424
16425 let multi_buffer = self.buffer().read(cx);
16426 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16427 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16428
16429 let (buffer, range, _) = if selection.reversed {
16430 buffer_ranges.first()
16431 } else {
16432 buffer_ranges.last()
16433 }?;
16434
16435 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16436 ..text::ToPoint::to_point(&range.end, &buffer).row;
16437 Some((
16438 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16439 selection,
16440 ))
16441 });
16442
16443 let Some((buffer, selection)) = buffer_and_selection else {
16444 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16445 };
16446
16447 let Some(project) = self.project.as_ref() else {
16448 return Task::ready(Err(anyhow!("editor does not have project")));
16449 };
16450
16451 project.update(cx, |project, cx| {
16452 project.get_permalink_to_line(&buffer, selection, cx)
16453 })
16454 }
16455
16456 pub fn copy_permalink_to_line(
16457 &mut self,
16458 _: &CopyPermalinkToLine,
16459 window: &mut Window,
16460 cx: &mut Context<Self>,
16461 ) {
16462 let permalink_task = self.get_permalink_to_line(cx);
16463 let workspace = self.workspace();
16464
16465 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16466 Ok(permalink) => {
16467 cx.update(|_, cx| {
16468 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16469 })
16470 .ok();
16471 }
16472 Err(err) => {
16473 let message = format!("Failed to copy permalink: {err}");
16474
16475 Err::<(), anyhow::Error>(err).log_err();
16476
16477 if let Some(workspace) = workspace {
16478 workspace
16479 .update_in(cx, |workspace, _, cx| {
16480 struct CopyPermalinkToLine;
16481
16482 workspace.show_toast(
16483 Toast::new(
16484 NotificationId::unique::<CopyPermalinkToLine>(),
16485 message,
16486 ),
16487 cx,
16488 )
16489 })
16490 .ok();
16491 }
16492 }
16493 })
16494 .detach();
16495 }
16496
16497 pub fn copy_file_location(
16498 &mut self,
16499 _: &CopyFileLocation,
16500 _: &mut Window,
16501 cx: &mut Context<Self>,
16502 ) {
16503 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16504 if let Some(file) = self.target_file(cx) {
16505 if let Some(path) = file.path().to_str() {
16506 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16507 }
16508 }
16509 }
16510
16511 pub fn open_permalink_to_line(
16512 &mut self,
16513 _: &OpenPermalinkToLine,
16514 window: &mut Window,
16515 cx: &mut Context<Self>,
16516 ) {
16517 let permalink_task = self.get_permalink_to_line(cx);
16518 let workspace = self.workspace();
16519
16520 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16521 Ok(permalink) => {
16522 cx.update(|_, cx| {
16523 cx.open_url(permalink.as_ref());
16524 })
16525 .ok();
16526 }
16527 Err(err) => {
16528 let message = format!("Failed to open permalink: {err}");
16529
16530 Err::<(), anyhow::Error>(err).log_err();
16531
16532 if let Some(workspace) = workspace {
16533 workspace
16534 .update(cx, |workspace, cx| {
16535 struct OpenPermalinkToLine;
16536
16537 workspace.show_toast(
16538 Toast::new(
16539 NotificationId::unique::<OpenPermalinkToLine>(),
16540 message,
16541 ),
16542 cx,
16543 )
16544 })
16545 .ok();
16546 }
16547 }
16548 })
16549 .detach();
16550 }
16551
16552 pub fn insert_uuid_v4(
16553 &mut self,
16554 _: &InsertUuidV4,
16555 window: &mut Window,
16556 cx: &mut Context<Self>,
16557 ) {
16558 self.insert_uuid(UuidVersion::V4, window, cx);
16559 }
16560
16561 pub fn insert_uuid_v7(
16562 &mut self,
16563 _: &InsertUuidV7,
16564 window: &mut Window,
16565 cx: &mut Context<Self>,
16566 ) {
16567 self.insert_uuid(UuidVersion::V7, window, cx);
16568 }
16569
16570 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16571 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16572 self.transact(window, cx, |this, window, cx| {
16573 let edits = this
16574 .selections
16575 .all::<Point>(cx)
16576 .into_iter()
16577 .map(|selection| {
16578 let uuid = match version {
16579 UuidVersion::V4 => uuid::Uuid::new_v4(),
16580 UuidVersion::V7 => uuid::Uuid::now_v7(),
16581 };
16582
16583 (selection.range(), uuid.to_string())
16584 });
16585 this.edit(edits, cx);
16586 this.refresh_inline_completion(true, false, window, cx);
16587 });
16588 }
16589
16590 pub fn open_selections_in_multibuffer(
16591 &mut self,
16592 _: &OpenSelectionsInMultibuffer,
16593 window: &mut Window,
16594 cx: &mut Context<Self>,
16595 ) {
16596 let multibuffer = self.buffer.read(cx);
16597
16598 let Some(buffer) = multibuffer.as_singleton() else {
16599 return;
16600 };
16601
16602 let Some(workspace) = self.workspace() else {
16603 return;
16604 };
16605
16606 let locations = self
16607 .selections
16608 .disjoint_anchors()
16609 .iter()
16610 .map(|range| Location {
16611 buffer: buffer.clone(),
16612 range: range.start.text_anchor..range.end.text_anchor,
16613 })
16614 .collect::<Vec<_>>();
16615
16616 let title = multibuffer.title(cx).to_string();
16617
16618 cx.spawn_in(window, async move |_, cx| {
16619 workspace.update_in(cx, |workspace, window, cx| {
16620 Self::open_locations_in_multibuffer(
16621 workspace,
16622 locations,
16623 format!("Selections for '{title}'"),
16624 false,
16625 MultibufferSelectionMode::All,
16626 window,
16627 cx,
16628 );
16629 })
16630 })
16631 .detach();
16632 }
16633
16634 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16635 /// last highlight added will be used.
16636 ///
16637 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16638 pub fn highlight_rows<T: 'static>(
16639 &mut self,
16640 range: Range<Anchor>,
16641 color: Hsla,
16642 should_autoscroll: bool,
16643 cx: &mut Context<Self>,
16644 ) {
16645 let snapshot = self.buffer().read(cx).snapshot(cx);
16646 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16647 let ix = row_highlights.binary_search_by(|highlight| {
16648 Ordering::Equal
16649 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16650 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16651 });
16652
16653 if let Err(mut ix) = ix {
16654 let index = post_inc(&mut self.highlight_order);
16655
16656 // If this range intersects with the preceding highlight, then merge it with
16657 // the preceding highlight. Otherwise insert a new highlight.
16658 let mut merged = false;
16659 if ix > 0 {
16660 let prev_highlight = &mut row_highlights[ix - 1];
16661 if prev_highlight
16662 .range
16663 .end
16664 .cmp(&range.start, &snapshot)
16665 .is_ge()
16666 {
16667 ix -= 1;
16668 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16669 prev_highlight.range.end = range.end;
16670 }
16671 merged = true;
16672 prev_highlight.index = index;
16673 prev_highlight.color = color;
16674 prev_highlight.should_autoscroll = should_autoscroll;
16675 }
16676 }
16677
16678 if !merged {
16679 row_highlights.insert(
16680 ix,
16681 RowHighlight {
16682 range: range.clone(),
16683 index,
16684 color,
16685 should_autoscroll,
16686 },
16687 );
16688 }
16689
16690 // If any of the following highlights intersect with this one, merge them.
16691 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16692 let highlight = &row_highlights[ix];
16693 if next_highlight
16694 .range
16695 .start
16696 .cmp(&highlight.range.end, &snapshot)
16697 .is_le()
16698 {
16699 if next_highlight
16700 .range
16701 .end
16702 .cmp(&highlight.range.end, &snapshot)
16703 .is_gt()
16704 {
16705 row_highlights[ix].range.end = next_highlight.range.end;
16706 }
16707 row_highlights.remove(ix + 1);
16708 } else {
16709 break;
16710 }
16711 }
16712 }
16713 }
16714
16715 /// Remove any highlighted row ranges of the given type that intersect the
16716 /// given ranges.
16717 pub fn remove_highlighted_rows<T: 'static>(
16718 &mut self,
16719 ranges_to_remove: Vec<Range<Anchor>>,
16720 cx: &mut Context<Self>,
16721 ) {
16722 let snapshot = self.buffer().read(cx).snapshot(cx);
16723 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16724 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16725 row_highlights.retain(|highlight| {
16726 while let Some(range_to_remove) = ranges_to_remove.peek() {
16727 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16728 Ordering::Less | Ordering::Equal => {
16729 ranges_to_remove.next();
16730 }
16731 Ordering::Greater => {
16732 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16733 Ordering::Less | Ordering::Equal => {
16734 return false;
16735 }
16736 Ordering::Greater => break,
16737 }
16738 }
16739 }
16740 }
16741
16742 true
16743 })
16744 }
16745
16746 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16747 pub fn clear_row_highlights<T: 'static>(&mut self) {
16748 self.highlighted_rows.remove(&TypeId::of::<T>());
16749 }
16750
16751 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16752 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16753 self.highlighted_rows
16754 .get(&TypeId::of::<T>())
16755 .map_or(&[] as &[_], |vec| vec.as_slice())
16756 .iter()
16757 .map(|highlight| (highlight.range.clone(), highlight.color))
16758 }
16759
16760 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16761 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16762 /// Allows to ignore certain kinds of highlights.
16763 pub fn highlighted_display_rows(
16764 &self,
16765 window: &mut Window,
16766 cx: &mut App,
16767 ) -> BTreeMap<DisplayRow, LineHighlight> {
16768 let snapshot = self.snapshot(window, cx);
16769 let mut used_highlight_orders = HashMap::default();
16770 self.highlighted_rows
16771 .iter()
16772 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16773 .fold(
16774 BTreeMap::<DisplayRow, LineHighlight>::new(),
16775 |mut unique_rows, highlight| {
16776 let start = highlight.range.start.to_display_point(&snapshot);
16777 let end = highlight.range.end.to_display_point(&snapshot);
16778 let start_row = start.row().0;
16779 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16780 && end.column() == 0
16781 {
16782 end.row().0.saturating_sub(1)
16783 } else {
16784 end.row().0
16785 };
16786 for row in start_row..=end_row {
16787 let used_index =
16788 used_highlight_orders.entry(row).or_insert(highlight.index);
16789 if highlight.index >= *used_index {
16790 *used_index = highlight.index;
16791 unique_rows.insert(DisplayRow(row), highlight.color.into());
16792 }
16793 }
16794 unique_rows
16795 },
16796 )
16797 }
16798
16799 pub fn highlighted_display_row_for_autoscroll(
16800 &self,
16801 snapshot: &DisplaySnapshot,
16802 ) -> Option<DisplayRow> {
16803 self.highlighted_rows
16804 .values()
16805 .flat_map(|highlighted_rows| highlighted_rows.iter())
16806 .filter_map(|highlight| {
16807 if highlight.should_autoscroll {
16808 Some(highlight.range.start.to_display_point(snapshot).row())
16809 } else {
16810 None
16811 }
16812 })
16813 .min()
16814 }
16815
16816 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16817 self.highlight_background::<SearchWithinRange>(
16818 ranges,
16819 |colors| colors.editor_document_highlight_read_background,
16820 cx,
16821 )
16822 }
16823
16824 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16825 self.breadcrumb_header = Some(new_header);
16826 }
16827
16828 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16829 self.clear_background_highlights::<SearchWithinRange>(cx);
16830 }
16831
16832 pub fn highlight_background<T: 'static>(
16833 &mut self,
16834 ranges: &[Range<Anchor>],
16835 color_fetcher: fn(&ThemeColors) -> Hsla,
16836 cx: &mut Context<Self>,
16837 ) {
16838 self.background_highlights
16839 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16840 self.scrollbar_marker_state.dirty = true;
16841 cx.notify();
16842 }
16843
16844 pub fn clear_background_highlights<T: 'static>(
16845 &mut self,
16846 cx: &mut Context<Self>,
16847 ) -> Option<BackgroundHighlight> {
16848 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16849 if !text_highlights.1.is_empty() {
16850 self.scrollbar_marker_state.dirty = true;
16851 cx.notify();
16852 }
16853 Some(text_highlights)
16854 }
16855
16856 pub fn highlight_gutter<T: 'static>(
16857 &mut self,
16858 ranges: &[Range<Anchor>],
16859 color_fetcher: fn(&App) -> Hsla,
16860 cx: &mut Context<Self>,
16861 ) {
16862 self.gutter_highlights
16863 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16864 cx.notify();
16865 }
16866
16867 pub fn clear_gutter_highlights<T: 'static>(
16868 &mut self,
16869 cx: &mut Context<Self>,
16870 ) -> Option<GutterHighlight> {
16871 cx.notify();
16872 self.gutter_highlights.remove(&TypeId::of::<T>())
16873 }
16874
16875 #[cfg(feature = "test-support")]
16876 pub fn all_text_background_highlights(
16877 &self,
16878 window: &mut Window,
16879 cx: &mut Context<Self>,
16880 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16881 let snapshot = self.snapshot(window, cx);
16882 let buffer = &snapshot.buffer_snapshot;
16883 let start = buffer.anchor_before(0);
16884 let end = buffer.anchor_after(buffer.len());
16885 let theme = cx.theme().colors();
16886 self.background_highlights_in_range(start..end, &snapshot, theme)
16887 }
16888
16889 #[cfg(feature = "test-support")]
16890 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16891 let snapshot = self.buffer().read(cx).snapshot(cx);
16892
16893 let highlights = self
16894 .background_highlights
16895 .get(&TypeId::of::<items::BufferSearchHighlights>());
16896
16897 if let Some((_color, ranges)) = highlights {
16898 ranges
16899 .iter()
16900 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16901 .collect_vec()
16902 } else {
16903 vec![]
16904 }
16905 }
16906
16907 fn document_highlights_for_position<'a>(
16908 &'a self,
16909 position: Anchor,
16910 buffer: &'a MultiBufferSnapshot,
16911 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16912 let read_highlights = self
16913 .background_highlights
16914 .get(&TypeId::of::<DocumentHighlightRead>())
16915 .map(|h| &h.1);
16916 let write_highlights = self
16917 .background_highlights
16918 .get(&TypeId::of::<DocumentHighlightWrite>())
16919 .map(|h| &h.1);
16920 let left_position = position.bias_left(buffer);
16921 let right_position = position.bias_right(buffer);
16922 read_highlights
16923 .into_iter()
16924 .chain(write_highlights)
16925 .flat_map(move |ranges| {
16926 let start_ix = match ranges.binary_search_by(|probe| {
16927 let cmp = probe.end.cmp(&left_position, buffer);
16928 if cmp.is_ge() {
16929 Ordering::Greater
16930 } else {
16931 Ordering::Less
16932 }
16933 }) {
16934 Ok(i) | Err(i) => i,
16935 };
16936
16937 ranges[start_ix..]
16938 .iter()
16939 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16940 })
16941 }
16942
16943 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16944 self.background_highlights
16945 .get(&TypeId::of::<T>())
16946 .map_or(false, |(_, highlights)| !highlights.is_empty())
16947 }
16948
16949 pub fn background_highlights_in_range(
16950 &self,
16951 search_range: Range<Anchor>,
16952 display_snapshot: &DisplaySnapshot,
16953 theme: &ThemeColors,
16954 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16955 let mut results = Vec::new();
16956 for (color_fetcher, ranges) in self.background_highlights.values() {
16957 let color = color_fetcher(theme);
16958 let start_ix = match ranges.binary_search_by(|probe| {
16959 let cmp = probe
16960 .end
16961 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16962 if cmp.is_gt() {
16963 Ordering::Greater
16964 } else {
16965 Ordering::Less
16966 }
16967 }) {
16968 Ok(i) | Err(i) => i,
16969 };
16970 for range in &ranges[start_ix..] {
16971 if range
16972 .start
16973 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16974 .is_ge()
16975 {
16976 break;
16977 }
16978
16979 let start = range.start.to_display_point(display_snapshot);
16980 let end = range.end.to_display_point(display_snapshot);
16981 results.push((start..end, color))
16982 }
16983 }
16984 results
16985 }
16986
16987 pub fn background_highlight_row_ranges<T: 'static>(
16988 &self,
16989 search_range: Range<Anchor>,
16990 display_snapshot: &DisplaySnapshot,
16991 count: usize,
16992 ) -> Vec<RangeInclusive<DisplayPoint>> {
16993 let mut results = Vec::new();
16994 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16995 return vec![];
16996 };
16997
16998 let start_ix = match ranges.binary_search_by(|probe| {
16999 let cmp = probe
17000 .end
17001 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17002 if cmp.is_gt() {
17003 Ordering::Greater
17004 } else {
17005 Ordering::Less
17006 }
17007 }) {
17008 Ok(i) | Err(i) => i,
17009 };
17010 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17011 if let (Some(start_display), Some(end_display)) = (start, end) {
17012 results.push(
17013 start_display.to_display_point(display_snapshot)
17014 ..=end_display.to_display_point(display_snapshot),
17015 );
17016 }
17017 };
17018 let mut start_row: Option<Point> = None;
17019 let mut end_row: Option<Point> = None;
17020 if ranges.len() > count {
17021 return Vec::new();
17022 }
17023 for range in &ranges[start_ix..] {
17024 if range
17025 .start
17026 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17027 .is_ge()
17028 {
17029 break;
17030 }
17031 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17032 if let Some(current_row) = &end_row {
17033 if end.row == current_row.row {
17034 continue;
17035 }
17036 }
17037 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17038 if start_row.is_none() {
17039 assert_eq!(end_row, None);
17040 start_row = Some(start);
17041 end_row = Some(end);
17042 continue;
17043 }
17044 if let Some(current_end) = end_row.as_mut() {
17045 if start.row > current_end.row + 1 {
17046 push_region(start_row, end_row);
17047 start_row = Some(start);
17048 end_row = Some(end);
17049 } else {
17050 // Merge two hunks.
17051 *current_end = end;
17052 }
17053 } else {
17054 unreachable!();
17055 }
17056 }
17057 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17058 push_region(start_row, end_row);
17059 results
17060 }
17061
17062 pub fn gutter_highlights_in_range(
17063 &self,
17064 search_range: Range<Anchor>,
17065 display_snapshot: &DisplaySnapshot,
17066 cx: &App,
17067 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17068 let mut results = Vec::new();
17069 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17070 let color = color_fetcher(cx);
17071 let start_ix = match ranges.binary_search_by(|probe| {
17072 let cmp = probe
17073 .end
17074 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17075 if cmp.is_gt() {
17076 Ordering::Greater
17077 } else {
17078 Ordering::Less
17079 }
17080 }) {
17081 Ok(i) | Err(i) => i,
17082 };
17083 for range in &ranges[start_ix..] {
17084 if range
17085 .start
17086 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17087 .is_ge()
17088 {
17089 break;
17090 }
17091
17092 let start = range.start.to_display_point(display_snapshot);
17093 let end = range.end.to_display_point(display_snapshot);
17094 results.push((start..end, color))
17095 }
17096 }
17097 results
17098 }
17099
17100 /// Get the text ranges corresponding to the redaction query
17101 pub fn redacted_ranges(
17102 &self,
17103 search_range: Range<Anchor>,
17104 display_snapshot: &DisplaySnapshot,
17105 cx: &App,
17106 ) -> Vec<Range<DisplayPoint>> {
17107 display_snapshot
17108 .buffer_snapshot
17109 .redacted_ranges(search_range, |file| {
17110 if let Some(file) = file {
17111 file.is_private()
17112 && EditorSettings::get(
17113 Some(SettingsLocation {
17114 worktree_id: file.worktree_id(cx),
17115 path: file.path().as_ref(),
17116 }),
17117 cx,
17118 )
17119 .redact_private_values
17120 } else {
17121 false
17122 }
17123 })
17124 .map(|range| {
17125 range.start.to_display_point(display_snapshot)
17126 ..range.end.to_display_point(display_snapshot)
17127 })
17128 .collect()
17129 }
17130
17131 pub fn highlight_text<T: 'static>(
17132 &mut self,
17133 ranges: Vec<Range<Anchor>>,
17134 style: HighlightStyle,
17135 cx: &mut Context<Self>,
17136 ) {
17137 self.display_map.update(cx, |map, _| {
17138 map.highlight_text(TypeId::of::<T>(), ranges, style)
17139 });
17140 cx.notify();
17141 }
17142
17143 pub(crate) fn highlight_inlays<T: 'static>(
17144 &mut self,
17145 highlights: Vec<InlayHighlight>,
17146 style: HighlightStyle,
17147 cx: &mut Context<Self>,
17148 ) {
17149 self.display_map.update(cx, |map, _| {
17150 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17151 });
17152 cx.notify();
17153 }
17154
17155 pub fn text_highlights<'a, T: 'static>(
17156 &'a self,
17157 cx: &'a App,
17158 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17159 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17160 }
17161
17162 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17163 let cleared = self
17164 .display_map
17165 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17166 if cleared {
17167 cx.notify();
17168 }
17169 }
17170
17171 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17172 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17173 && self.focus_handle.is_focused(window)
17174 }
17175
17176 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17177 self.show_cursor_when_unfocused = is_enabled;
17178 cx.notify();
17179 }
17180
17181 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17182 cx.notify();
17183 }
17184
17185 fn on_buffer_event(
17186 &mut self,
17187 multibuffer: &Entity<MultiBuffer>,
17188 event: &multi_buffer::Event,
17189 window: &mut Window,
17190 cx: &mut Context<Self>,
17191 ) {
17192 match event {
17193 multi_buffer::Event::Edited {
17194 singleton_buffer_edited,
17195 edited_buffer: buffer_edited,
17196 } => {
17197 self.scrollbar_marker_state.dirty = true;
17198 self.active_indent_guides_state.dirty = true;
17199 self.refresh_active_diagnostics(cx);
17200 self.refresh_code_actions(window, cx);
17201 if self.has_active_inline_completion() {
17202 self.update_visible_inline_completion(window, cx);
17203 }
17204 if let Some(buffer) = buffer_edited {
17205 let buffer_id = buffer.read(cx).remote_id();
17206 if !self.registered_buffers.contains_key(&buffer_id) {
17207 if let Some(project) = self.project.as_ref() {
17208 project.update(cx, |project, cx| {
17209 self.registered_buffers.insert(
17210 buffer_id,
17211 project.register_buffer_with_language_servers(&buffer, cx),
17212 );
17213 })
17214 }
17215 }
17216 }
17217 cx.emit(EditorEvent::BufferEdited);
17218 cx.emit(SearchEvent::MatchesInvalidated);
17219 if *singleton_buffer_edited {
17220 if let Some(project) = &self.project {
17221 #[allow(clippy::mutable_key_type)]
17222 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17223 multibuffer
17224 .all_buffers()
17225 .into_iter()
17226 .filter_map(|buffer| {
17227 buffer.update(cx, |buffer, cx| {
17228 let language = buffer.language()?;
17229 let should_discard = project.update(cx, |project, cx| {
17230 project.is_local()
17231 && !project.has_language_servers_for(buffer, cx)
17232 });
17233 should_discard.not().then_some(language.clone())
17234 })
17235 })
17236 .collect::<HashSet<_>>()
17237 });
17238 if !languages_affected.is_empty() {
17239 self.refresh_inlay_hints(
17240 InlayHintRefreshReason::BufferEdited(languages_affected),
17241 cx,
17242 );
17243 }
17244 }
17245 }
17246
17247 let Some(project) = &self.project else { return };
17248 let (telemetry, is_via_ssh) = {
17249 let project = project.read(cx);
17250 let telemetry = project.client().telemetry().clone();
17251 let is_via_ssh = project.is_via_ssh();
17252 (telemetry, is_via_ssh)
17253 };
17254 refresh_linked_ranges(self, window, cx);
17255 telemetry.log_edit_event("editor", is_via_ssh);
17256 }
17257 multi_buffer::Event::ExcerptsAdded {
17258 buffer,
17259 predecessor,
17260 excerpts,
17261 } => {
17262 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17263 let buffer_id = buffer.read(cx).remote_id();
17264 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17265 if let Some(project) = &self.project {
17266 get_uncommitted_diff_for_buffer(
17267 project,
17268 [buffer.clone()],
17269 self.buffer.clone(),
17270 cx,
17271 )
17272 .detach();
17273 }
17274 }
17275 cx.emit(EditorEvent::ExcerptsAdded {
17276 buffer: buffer.clone(),
17277 predecessor: *predecessor,
17278 excerpts: excerpts.clone(),
17279 });
17280 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17281 }
17282 multi_buffer::Event::ExcerptsRemoved { ids } => {
17283 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17284 let buffer = self.buffer.read(cx);
17285 self.registered_buffers
17286 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17287 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17288 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17289 }
17290 multi_buffer::Event::ExcerptsEdited {
17291 excerpt_ids,
17292 buffer_ids,
17293 } => {
17294 self.display_map.update(cx, |map, cx| {
17295 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17296 });
17297 cx.emit(EditorEvent::ExcerptsEdited {
17298 ids: excerpt_ids.clone(),
17299 })
17300 }
17301 multi_buffer::Event::ExcerptsExpanded { ids } => {
17302 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17303 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17304 }
17305 multi_buffer::Event::Reparsed(buffer_id) => {
17306 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17307 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17308
17309 cx.emit(EditorEvent::Reparsed(*buffer_id));
17310 }
17311 multi_buffer::Event::DiffHunksToggled => {
17312 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17313 }
17314 multi_buffer::Event::LanguageChanged(buffer_id) => {
17315 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17316 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17317 cx.emit(EditorEvent::Reparsed(*buffer_id));
17318 cx.notify();
17319 }
17320 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17321 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17322 multi_buffer::Event::FileHandleChanged
17323 | multi_buffer::Event::Reloaded
17324 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17325 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17326 multi_buffer::Event::DiagnosticsUpdated => {
17327 self.refresh_active_diagnostics(cx);
17328 self.refresh_inline_diagnostics(true, window, cx);
17329 self.scrollbar_marker_state.dirty = true;
17330 cx.notify();
17331 }
17332 _ => {}
17333 };
17334 }
17335
17336 fn on_display_map_changed(
17337 &mut self,
17338 _: Entity<DisplayMap>,
17339 _: &mut Window,
17340 cx: &mut Context<Self>,
17341 ) {
17342 cx.notify();
17343 }
17344
17345 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17346 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17347 self.update_edit_prediction_settings(cx);
17348 self.refresh_inline_completion(true, false, window, cx);
17349 self.refresh_inlay_hints(
17350 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17351 self.selections.newest_anchor().head(),
17352 &self.buffer.read(cx).snapshot(cx),
17353 cx,
17354 )),
17355 cx,
17356 );
17357
17358 let old_cursor_shape = self.cursor_shape;
17359
17360 {
17361 let editor_settings = EditorSettings::get_global(cx);
17362 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17363 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17364 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17365 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17366 }
17367
17368 if old_cursor_shape != self.cursor_shape {
17369 cx.emit(EditorEvent::CursorShapeChanged);
17370 }
17371
17372 let project_settings = ProjectSettings::get_global(cx);
17373 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17374
17375 if self.mode.is_full() {
17376 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17377 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17378 if self.show_inline_diagnostics != show_inline_diagnostics {
17379 self.show_inline_diagnostics = show_inline_diagnostics;
17380 self.refresh_inline_diagnostics(false, window, cx);
17381 }
17382
17383 if self.git_blame_inline_enabled != inline_blame_enabled {
17384 self.toggle_git_blame_inline_internal(false, window, cx);
17385 }
17386 }
17387
17388 cx.notify();
17389 }
17390
17391 pub fn set_searchable(&mut self, searchable: bool) {
17392 self.searchable = searchable;
17393 }
17394
17395 pub fn searchable(&self) -> bool {
17396 self.searchable
17397 }
17398
17399 fn open_proposed_changes_editor(
17400 &mut self,
17401 _: &OpenProposedChangesEditor,
17402 window: &mut Window,
17403 cx: &mut Context<Self>,
17404 ) {
17405 let Some(workspace) = self.workspace() else {
17406 cx.propagate();
17407 return;
17408 };
17409
17410 let selections = self.selections.all::<usize>(cx);
17411 let multi_buffer = self.buffer.read(cx);
17412 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17413 let mut new_selections_by_buffer = HashMap::default();
17414 for selection in selections {
17415 for (buffer, range, _) in
17416 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17417 {
17418 let mut range = range.to_point(buffer);
17419 range.start.column = 0;
17420 range.end.column = buffer.line_len(range.end.row);
17421 new_selections_by_buffer
17422 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17423 .or_insert(Vec::new())
17424 .push(range)
17425 }
17426 }
17427
17428 let proposed_changes_buffers = new_selections_by_buffer
17429 .into_iter()
17430 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17431 .collect::<Vec<_>>();
17432 let proposed_changes_editor = cx.new(|cx| {
17433 ProposedChangesEditor::new(
17434 "Proposed changes",
17435 proposed_changes_buffers,
17436 self.project.clone(),
17437 window,
17438 cx,
17439 )
17440 });
17441
17442 window.defer(cx, move |window, cx| {
17443 workspace.update(cx, |workspace, cx| {
17444 workspace.active_pane().update(cx, |pane, cx| {
17445 pane.add_item(
17446 Box::new(proposed_changes_editor),
17447 true,
17448 true,
17449 None,
17450 window,
17451 cx,
17452 );
17453 });
17454 });
17455 });
17456 }
17457
17458 pub fn open_excerpts_in_split(
17459 &mut self,
17460 _: &OpenExcerptsSplit,
17461 window: &mut Window,
17462 cx: &mut Context<Self>,
17463 ) {
17464 self.open_excerpts_common(None, true, window, cx)
17465 }
17466
17467 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17468 self.open_excerpts_common(None, false, window, cx)
17469 }
17470
17471 fn open_excerpts_common(
17472 &mut self,
17473 jump_data: Option<JumpData>,
17474 split: bool,
17475 window: &mut Window,
17476 cx: &mut Context<Self>,
17477 ) {
17478 let Some(workspace) = self.workspace() else {
17479 cx.propagate();
17480 return;
17481 };
17482
17483 if self.buffer.read(cx).is_singleton() {
17484 cx.propagate();
17485 return;
17486 }
17487
17488 let mut new_selections_by_buffer = HashMap::default();
17489 match &jump_data {
17490 Some(JumpData::MultiBufferPoint {
17491 excerpt_id,
17492 position,
17493 anchor,
17494 line_offset_from_top,
17495 }) => {
17496 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17497 if let Some(buffer) = multi_buffer_snapshot
17498 .buffer_id_for_excerpt(*excerpt_id)
17499 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17500 {
17501 let buffer_snapshot = buffer.read(cx).snapshot();
17502 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17503 language::ToPoint::to_point(anchor, &buffer_snapshot)
17504 } else {
17505 buffer_snapshot.clip_point(*position, Bias::Left)
17506 };
17507 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17508 new_selections_by_buffer.insert(
17509 buffer,
17510 (
17511 vec![jump_to_offset..jump_to_offset],
17512 Some(*line_offset_from_top),
17513 ),
17514 );
17515 }
17516 }
17517 Some(JumpData::MultiBufferRow {
17518 row,
17519 line_offset_from_top,
17520 }) => {
17521 let point = MultiBufferPoint::new(row.0, 0);
17522 if let Some((buffer, buffer_point, _)) =
17523 self.buffer.read(cx).point_to_buffer_point(point, cx)
17524 {
17525 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17526 new_selections_by_buffer
17527 .entry(buffer)
17528 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17529 .0
17530 .push(buffer_offset..buffer_offset)
17531 }
17532 }
17533 None => {
17534 let selections = self.selections.all::<usize>(cx);
17535 let multi_buffer = self.buffer.read(cx);
17536 for selection in selections {
17537 for (snapshot, range, _, anchor) in multi_buffer
17538 .snapshot(cx)
17539 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17540 {
17541 if let Some(anchor) = anchor {
17542 // selection is in a deleted hunk
17543 let Some(buffer_id) = anchor.buffer_id else {
17544 continue;
17545 };
17546 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17547 continue;
17548 };
17549 let offset = text::ToOffset::to_offset(
17550 &anchor.text_anchor,
17551 &buffer_handle.read(cx).snapshot(),
17552 );
17553 let range = offset..offset;
17554 new_selections_by_buffer
17555 .entry(buffer_handle)
17556 .or_insert((Vec::new(), None))
17557 .0
17558 .push(range)
17559 } else {
17560 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17561 else {
17562 continue;
17563 };
17564 new_selections_by_buffer
17565 .entry(buffer_handle)
17566 .or_insert((Vec::new(), None))
17567 .0
17568 .push(range)
17569 }
17570 }
17571 }
17572 }
17573 }
17574
17575 new_selections_by_buffer
17576 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17577
17578 if new_selections_by_buffer.is_empty() {
17579 return;
17580 }
17581
17582 // We defer the pane interaction because we ourselves are a workspace item
17583 // and activating a new item causes the pane to call a method on us reentrantly,
17584 // which panics if we're on the stack.
17585 window.defer(cx, move |window, cx| {
17586 workspace.update(cx, |workspace, cx| {
17587 let pane = if split {
17588 workspace.adjacent_pane(window, cx)
17589 } else {
17590 workspace.active_pane().clone()
17591 };
17592
17593 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17594 let editor = buffer
17595 .read(cx)
17596 .file()
17597 .is_none()
17598 .then(|| {
17599 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17600 // so `workspace.open_project_item` will never find them, always opening a new editor.
17601 // Instead, we try to activate the existing editor in the pane first.
17602 let (editor, pane_item_index) =
17603 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17604 let editor = item.downcast::<Editor>()?;
17605 let singleton_buffer =
17606 editor.read(cx).buffer().read(cx).as_singleton()?;
17607 if singleton_buffer == buffer {
17608 Some((editor, i))
17609 } else {
17610 None
17611 }
17612 })?;
17613 pane.update(cx, |pane, cx| {
17614 pane.activate_item(pane_item_index, true, true, window, cx)
17615 });
17616 Some(editor)
17617 })
17618 .flatten()
17619 .unwrap_or_else(|| {
17620 workspace.open_project_item::<Self>(
17621 pane.clone(),
17622 buffer,
17623 true,
17624 true,
17625 window,
17626 cx,
17627 )
17628 });
17629
17630 editor.update(cx, |editor, cx| {
17631 let autoscroll = match scroll_offset {
17632 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17633 None => Autoscroll::newest(),
17634 };
17635 let nav_history = editor.nav_history.take();
17636 editor.change_selections(Some(autoscroll), window, cx, |s| {
17637 s.select_ranges(ranges);
17638 });
17639 editor.nav_history = nav_history;
17640 });
17641 }
17642 })
17643 });
17644 }
17645
17646 // For now, don't allow opening excerpts in buffers that aren't backed by
17647 // regular project files.
17648 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17649 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17650 }
17651
17652 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17653 let snapshot = self.buffer.read(cx).read(cx);
17654 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17655 Some(
17656 ranges
17657 .iter()
17658 .map(move |range| {
17659 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17660 })
17661 .collect(),
17662 )
17663 }
17664
17665 fn selection_replacement_ranges(
17666 &self,
17667 range: Range<OffsetUtf16>,
17668 cx: &mut App,
17669 ) -> Vec<Range<OffsetUtf16>> {
17670 let selections = self.selections.all::<OffsetUtf16>(cx);
17671 let newest_selection = selections
17672 .iter()
17673 .max_by_key(|selection| selection.id)
17674 .unwrap();
17675 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17676 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17677 let snapshot = self.buffer.read(cx).read(cx);
17678 selections
17679 .into_iter()
17680 .map(|mut selection| {
17681 selection.start.0 =
17682 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17683 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17684 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17685 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17686 })
17687 .collect()
17688 }
17689
17690 fn report_editor_event(
17691 &self,
17692 event_type: &'static str,
17693 file_extension: Option<String>,
17694 cx: &App,
17695 ) {
17696 if cfg!(any(test, feature = "test-support")) {
17697 return;
17698 }
17699
17700 let Some(project) = &self.project else { return };
17701
17702 // If None, we are in a file without an extension
17703 let file = self
17704 .buffer
17705 .read(cx)
17706 .as_singleton()
17707 .and_then(|b| b.read(cx).file());
17708 let file_extension = file_extension.or(file
17709 .as_ref()
17710 .and_then(|file| Path::new(file.file_name(cx)).extension())
17711 .and_then(|e| e.to_str())
17712 .map(|a| a.to_string()));
17713
17714 let vim_mode = cx
17715 .global::<SettingsStore>()
17716 .raw_user_settings()
17717 .get("vim_mode")
17718 == Some(&serde_json::Value::Bool(true));
17719
17720 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17721 let copilot_enabled = edit_predictions_provider
17722 == language::language_settings::EditPredictionProvider::Copilot;
17723 let copilot_enabled_for_language = self
17724 .buffer
17725 .read(cx)
17726 .language_settings(cx)
17727 .show_edit_predictions;
17728
17729 let project = project.read(cx);
17730 telemetry::event!(
17731 event_type,
17732 file_extension,
17733 vim_mode,
17734 copilot_enabled,
17735 copilot_enabled_for_language,
17736 edit_predictions_provider,
17737 is_via_ssh = project.is_via_ssh(),
17738 );
17739 }
17740
17741 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17742 /// with each line being an array of {text, highlight} objects.
17743 fn copy_highlight_json(
17744 &mut self,
17745 _: &CopyHighlightJson,
17746 window: &mut Window,
17747 cx: &mut Context<Self>,
17748 ) {
17749 #[derive(Serialize)]
17750 struct Chunk<'a> {
17751 text: String,
17752 highlight: Option<&'a str>,
17753 }
17754
17755 let snapshot = self.buffer.read(cx).snapshot(cx);
17756 let range = self
17757 .selected_text_range(false, window, cx)
17758 .and_then(|selection| {
17759 if selection.range.is_empty() {
17760 None
17761 } else {
17762 Some(selection.range)
17763 }
17764 })
17765 .unwrap_or_else(|| 0..snapshot.len());
17766
17767 let chunks = snapshot.chunks(range, true);
17768 let mut lines = Vec::new();
17769 let mut line: VecDeque<Chunk> = VecDeque::new();
17770
17771 let Some(style) = self.style.as_ref() else {
17772 return;
17773 };
17774
17775 for chunk in chunks {
17776 let highlight = chunk
17777 .syntax_highlight_id
17778 .and_then(|id| id.name(&style.syntax));
17779 let mut chunk_lines = chunk.text.split('\n').peekable();
17780 while let Some(text) = chunk_lines.next() {
17781 let mut merged_with_last_token = false;
17782 if let Some(last_token) = line.back_mut() {
17783 if last_token.highlight == highlight {
17784 last_token.text.push_str(text);
17785 merged_with_last_token = true;
17786 }
17787 }
17788
17789 if !merged_with_last_token {
17790 line.push_back(Chunk {
17791 text: text.into(),
17792 highlight,
17793 });
17794 }
17795
17796 if chunk_lines.peek().is_some() {
17797 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17798 line.pop_front();
17799 }
17800 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17801 line.pop_back();
17802 }
17803
17804 lines.push(mem::take(&mut line));
17805 }
17806 }
17807 }
17808
17809 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17810 return;
17811 };
17812 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17813 }
17814
17815 pub fn open_context_menu(
17816 &mut self,
17817 _: &OpenContextMenu,
17818 window: &mut Window,
17819 cx: &mut Context<Self>,
17820 ) {
17821 self.request_autoscroll(Autoscroll::newest(), cx);
17822 let position = self.selections.newest_display(cx).start;
17823 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17824 }
17825
17826 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17827 &self.inlay_hint_cache
17828 }
17829
17830 pub fn replay_insert_event(
17831 &mut self,
17832 text: &str,
17833 relative_utf16_range: Option<Range<isize>>,
17834 window: &mut Window,
17835 cx: &mut Context<Self>,
17836 ) {
17837 if !self.input_enabled {
17838 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17839 return;
17840 }
17841 if let Some(relative_utf16_range) = relative_utf16_range {
17842 let selections = self.selections.all::<OffsetUtf16>(cx);
17843 self.change_selections(None, window, cx, |s| {
17844 let new_ranges = selections.into_iter().map(|range| {
17845 let start = OffsetUtf16(
17846 range
17847 .head()
17848 .0
17849 .saturating_add_signed(relative_utf16_range.start),
17850 );
17851 let end = OffsetUtf16(
17852 range
17853 .head()
17854 .0
17855 .saturating_add_signed(relative_utf16_range.end),
17856 );
17857 start..end
17858 });
17859 s.select_ranges(new_ranges);
17860 });
17861 }
17862
17863 self.handle_input(text, window, cx);
17864 }
17865
17866 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17867 let Some(provider) = self.semantics_provider.as_ref() else {
17868 return false;
17869 };
17870
17871 let mut supports = false;
17872 self.buffer().update(cx, |this, cx| {
17873 this.for_each_buffer(|buffer| {
17874 supports |= provider.supports_inlay_hints(buffer, cx);
17875 });
17876 });
17877
17878 supports
17879 }
17880
17881 pub fn is_focused(&self, window: &Window) -> bool {
17882 self.focus_handle.is_focused(window)
17883 }
17884
17885 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17886 cx.emit(EditorEvent::Focused);
17887
17888 if let Some(descendant) = self
17889 .last_focused_descendant
17890 .take()
17891 .and_then(|descendant| descendant.upgrade())
17892 {
17893 window.focus(&descendant);
17894 } else {
17895 if let Some(blame) = self.blame.as_ref() {
17896 blame.update(cx, GitBlame::focus)
17897 }
17898
17899 self.blink_manager.update(cx, BlinkManager::enable);
17900 self.show_cursor_names(window, cx);
17901 self.buffer.update(cx, |buffer, cx| {
17902 buffer.finalize_last_transaction(cx);
17903 if self.leader_peer_id.is_none() {
17904 buffer.set_active_selections(
17905 &self.selections.disjoint_anchors(),
17906 self.selections.line_mode,
17907 self.cursor_shape,
17908 cx,
17909 );
17910 }
17911 });
17912 }
17913 }
17914
17915 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17916 cx.emit(EditorEvent::FocusedIn)
17917 }
17918
17919 fn handle_focus_out(
17920 &mut self,
17921 event: FocusOutEvent,
17922 _window: &mut Window,
17923 cx: &mut Context<Self>,
17924 ) {
17925 if event.blurred != self.focus_handle {
17926 self.last_focused_descendant = Some(event.blurred);
17927 }
17928 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17929 }
17930
17931 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17932 self.blink_manager.update(cx, BlinkManager::disable);
17933 self.buffer
17934 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17935
17936 if let Some(blame) = self.blame.as_ref() {
17937 blame.update(cx, GitBlame::blur)
17938 }
17939 if !self.hover_state.focused(window, cx) {
17940 hide_hover(self, cx);
17941 }
17942 if !self
17943 .context_menu
17944 .borrow()
17945 .as_ref()
17946 .is_some_and(|context_menu| context_menu.focused(window, cx))
17947 {
17948 self.hide_context_menu(window, cx);
17949 }
17950 self.discard_inline_completion(false, cx);
17951 cx.emit(EditorEvent::Blurred);
17952 cx.notify();
17953 }
17954
17955 pub fn register_action<A: Action>(
17956 &mut self,
17957 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17958 ) -> Subscription {
17959 let id = self.next_editor_action_id.post_inc();
17960 let listener = Arc::new(listener);
17961 self.editor_actions.borrow_mut().insert(
17962 id,
17963 Box::new(move |window, _| {
17964 let listener = listener.clone();
17965 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17966 let action = action.downcast_ref().unwrap();
17967 if phase == DispatchPhase::Bubble {
17968 listener(action, window, cx)
17969 }
17970 })
17971 }),
17972 );
17973
17974 let editor_actions = self.editor_actions.clone();
17975 Subscription::new(move || {
17976 editor_actions.borrow_mut().remove(&id);
17977 })
17978 }
17979
17980 pub fn file_header_size(&self) -> u32 {
17981 FILE_HEADER_HEIGHT
17982 }
17983
17984 pub fn restore(
17985 &mut self,
17986 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17987 window: &mut Window,
17988 cx: &mut Context<Self>,
17989 ) {
17990 let workspace = self.workspace();
17991 let project = self.project.as_ref();
17992 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17993 let mut tasks = Vec::new();
17994 for (buffer_id, changes) in revert_changes {
17995 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17996 buffer.update(cx, |buffer, cx| {
17997 buffer.edit(
17998 changes
17999 .into_iter()
18000 .map(|(range, text)| (range, text.to_string())),
18001 None,
18002 cx,
18003 );
18004 });
18005
18006 if let Some(project) =
18007 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18008 {
18009 project.update(cx, |project, cx| {
18010 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18011 })
18012 }
18013 }
18014 }
18015 tasks
18016 });
18017 cx.spawn_in(window, async move |_, cx| {
18018 for (buffer, task) in save_tasks {
18019 let result = task.await;
18020 if result.is_err() {
18021 let Some(path) = buffer
18022 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18023 .ok()
18024 else {
18025 continue;
18026 };
18027 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18028 let Some(task) = cx
18029 .update_window_entity(&workspace, |workspace, window, cx| {
18030 workspace
18031 .open_path_preview(path, None, false, false, false, window, cx)
18032 })
18033 .ok()
18034 else {
18035 continue;
18036 };
18037 task.await.log_err();
18038 }
18039 }
18040 }
18041 })
18042 .detach();
18043 self.change_selections(None, window, cx, |selections| selections.refresh());
18044 }
18045
18046 pub fn to_pixel_point(
18047 &self,
18048 source: multi_buffer::Anchor,
18049 editor_snapshot: &EditorSnapshot,
18050 window: &mut Window,
18051 ) -> Option<gpui::Point<Pixels>> {
18052 let source_point = source.to_display_point(editor_snapshot);
18053 self.display_to_pixel_point(source_point, editor_snapshot, window)
18054 }
18055
18056 pub fn display_to_pixel_point(
18057 &self,
18058 source: DisplayPoint,
18059 editor_snapshot: &EditorSnapshot,
18060 window: &mut Window,
18061 ) -> Option<gpui::Point<Pixels>> {
18062 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18063 let text_layout_details = self.text_layout_details(window);
18064 let scroll_top = text_layout_details
18065 .scroll_anchor
18066 .scroll_position(editor_snapshot)
18067 .y;
18068
18069 if source.row().as_f32() < scroll_top.floor() {
18070 return None;
18071 }
18072 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18073 let source_y = line_height * (source.row().as_f32() - scroll_top);
18074 Some(gpui::Point::new(source_x, source_y))
18075 }
18076
18077 pub fn has_visible_completions_menu(&self) -> bool {
18078 !self.edit_prediction_preview_is_active()
18079 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18080 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18081 })
18082 }
18083
18084 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18085 self.addons
18086 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18087 }
18088
18089 pub fn unregister_addon<T: Addon>(&mut self) {
18090 self.addons.remove(&std::any::TypeId::of::<T>());
18091 }
18092
18093 pub fn addon<T: Addon>(&self) -> Option<&T> {
18094 let type_id = std::any::TypeId::of::<T>();
18095 self.addons
18096 .get(&type_id)
18097 .and_then(|item| item.to_any().downcast_ref::<T>())
18098 }
18099
18100 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18101 let text_layout_details = self.text_layout_details(window);
18102 let style = &text_layout_details.editor_style;
18103 let font_id = window.text_system().resolve_font(&style.text.font());
18104 let font_size = style.text.font_size.to_pixels(window.rem_size());
18105 let line_height = style.text.line_height_in_pixels(window.rem_size());
18106 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18107
18108 gpui::Size::new(em_width, line_height)
18109 }
18110
18111 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18112 self.load_diff_task.clone()
18113 }
18114
18115 fn read_metadata_from_db(
18116 &mut self,
18117 item_id: u64,
18118 workspace_id: WorkspaceId,
18119 window: &mut Window,
18120 cx: &mut Context<Editor>,
18121 ) {
18122 if self.is_singleton(cx)
18123 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18124 {
18125 let buffer_snapshot = OnceCell::new();
18126
18127 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18128 if !folds.is_empty() {
18129 let snapshot =
18130 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18131 self.fold_ranges(
18132 folds
18133 .into_iter()
18134 .map(|(start, end)| {
18135 snapshot.clip_offset(start, Bias::Left)
18136 ..snapshot.clip_offset(end, Bias::Right)
18137 })
18138 .collect(),
18139 false,
18140 window,
18141 cx,
18142 );
18143 }
18144 }
18145
18146 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18147 if !selections.is_empty() {
18148 let snapshot =
18149 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18150 self.change_selections(None, window, cx, |s| {
18151 s.select_ranges(selections.into_iter().map(|(start, end)| {
18152 snapshot.clip_offset(start, Bias::Left)
18153 ..snapshot.clip_offset(end, Bias::Right)
18154 }));
18155 });
18156 }
18157 };
18158 }
18159
18160 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18161 }
18162}
18163
18164// Consider user intent and default settings
18165fn choose_completion_range(
18166 completion: &Completion,
18167 intent: CompletionIntent,
18168 buffer: &Entity<Buffer>,
18169 cx: &mut Context<Editor>,
18170) -> Range<usize> {
18171 fn should_replace(
18172 completion: &Completion,
18173 insert_range: &Range<text::Anchor>,
18174 intent: CompletionIntent,
18175 completion_mode_setting: LspInsertMode,
18176 buffer: &Buffer,
18177 ) -> bool {
18178 // specific actions take precedence over settings
18179 match intent {
18180 CompletionIntent::CompleteWithInsert => return false,
18181 CompletionIntent::CompleteWithReplace => return true,
18182 CompletionIntent::Complete | CompletionIntent::Compose => {}
18183 }
18184
18185 match completion_mode_setting {
18186 LspInsertMode::Insert => false,
18187 LspInsertMode::Replace => true,
18188 LspInsertMode::ReplaceSubsequence => {
18189 let mut text_to_replace = buffer.chars_for_range(
18190 buffer.anchor_before(completion.replace_range.start)
18191 ..buffer.anchor_after(completion.replace_range.end),
18192 );
18193 let mut completion_text = completion.new_text.chars();
18194
18195 // is `text_to_replace` a subsequence of `completion_text`
18196 text_to_replace
18197 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18198 }
18199 LspInsertMode::ReplaceSuffix => {
18200 let range_after_cursor = insert_range.end..completion.replace_range.end;
18201
18202 let text_after_cursor = buffer
18203 .text_for_range(
18204 buffer.anchor_before(range_after_cursor.start)
18205 ..buffer.anchor_after(range_after_cursor.end),
18206 )
18207 .collect::<String>();
18208 completion.new_text.ends_with(&text_after_cursor)
18209 }
18210 }
18211 }
18212
18213 let buffer = buffer.read(cx);
18214
18215 if let CompletionSource::Lsp {
18216 insert_range: Some(insert_range),
18217 ..
18218 } = &completion.source
18219 {
18220 let completion_mode_setting =
18221 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18222 .completions
18223 .lsp_insert_mode;
18224
18225 if !should_replace(
18226 completion,
18227 &insert_range,
18228 intent,
18229 completion_mode_setting,
18230 buffer,
18231 ) {
18232 return insert_range.to_offset(buffer);
18233 }
18234 }
18235
18236 completion.replace_range.to_offset(buffer)
18237}
18238
18239fn insert_extra_newline_brackets(
18240 buffer: &MultiBufferSnapshot,
18241 range: Range<usize>,
18242 language: &language::LanguageScope,
18243) -> bool {
18244 let leading_whitespace_len = buffer
18245 .reversed_chars_at(range.start)
18246 .take_while(|c| c.is_whitespace() && *c != '\n')
18247 .map(|c| c.len_utf8())
18248 .sum::<usize>();
18249 let trailing_whitespace_len = buffer
18250 .chars_at(range.end)
18251 .take_while(|c| c.is_whitespace() && *c != '\n')
18252 .map(|c| c.len_utf8())
18253 .sum::<usize>();
18254 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18255
18256 language.brackets().any(|(pair, enabled)| {
18257 let pair_start = pair.start.trim_end();
18258 let pair_end = pair.end.trim_start();
18259
18260 enabled
18261 && pair.newline
18262 && buffer.contains_str_at(range.end, pair_end)
18263 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18264 })
18265}
18266
18267fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18268 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18269 [(buffer, range, _)] => (*buffer, range.clone()),
18270 _ => return false,
18271 };
18272 let pair = {
18273 let mut result: Option<BracketMatch> = None;
18274
18275 for pair in buffer
18276 .all_bracket_ranges(range.clone())
18277 .filter(move |pair| {
18278 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18279 })
18280 {
18281 let len = pair.close_range.end - pair.open_range.start;
18282
18283 if let Some(existing) = &result {
18284 let existing_len = existing.close_range.end - existing.open_range.start;
18285 if len > existing_len {
18286 continue;
18287 }
18288 }
18289
18290 result = Some(pair);
18291 }
18292
18293 result
18294 };
18295 let Some(pair) = pair else {
18296 return false;
18297 };
18298 pair.newline_only
18299 && buffer
18300 .chars_for_range(pair.open_range.end..range.start)
18301 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18302 .all(|c| c.is_whitespace() && c != '\n')
18303}
18304
18305fn get_uncommitted_diff_for_buffer(
18306 project: &Entity<Project>,
18307 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18308 buffer: Entity<MultiBuffer>,
18309 cx: &mut App,
18310) -> Task<()> {
18311 let mut tasks = Vec::new();
18312 project.update(cx, |project, cx| {
18313 for buffer in buffers {
18314 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18315 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18316 }
18317 }
18318 });
18319 cx.spawn(async move |cx| {
18320 let diffs = future::join_all(tasks).await;
18321 buffer
18322 .update(cx, |buffer, cx| {
18323 for diff in diffs.into_iter().flatten() {
18324 buffer.add_diff(diff, cx);
18325 }
18326 })
18327 .ok();
18328 })
18329}
18330
18331fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18332 let tab_size = tab_size.get() as usize;
18333 let mut width = offset;
18334
18335 for ch in text.chars() {
18336 width += if ch == '\t' {
18337 tab_size - (width % tab_size)
18338 } else {
18339 1
18340 };
18341 }
18342
18343 width - offset
18344}
18345
18346#[cfg(test)]
18347mod tests {
18348 use super::*;
18349
18350 #[test]
18351 fn test_string_size_with_expanded_tabs() {
18352 let nz = |val| NonZeroU32::new(val).unwrap();
18353 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18354 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18355 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18356 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18357 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18358 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18359 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18360 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18361 }
18362}
18363
18364/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18365struct WordBreakingTokenizer<'a> {
18366 input: &'a str,
18367}
18368
18369impl<'a> WordBreakingTokenizer<'a> {
18370 fn new(input: &'a str) -> Self {
18371 Self { input }
18372 }
18373}
18374
18375fn is_char_ideographic(ch: char) -> bool {
18376 use unicode_script::Script::*;
18377 use unicode_script::UnicodeScript;
18378 matches!(ch.script(), Han | Tangut | Yi)
18379}
18380
18381fn is_grapheme_ideographic(text: &str) -> bool {
18382 text.chars().any(is_char_ideographic)
18383}
18384
18385fn is_grapheme_whitespace(text: &str) -> bool {
18386 text.chars().any(|x| x.is_whitespace())
18387}
18388
18389fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18390 text.chars().next().map_or(false, |ch| {
18391 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18392 })
18393}
18394
18395#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18396enum WordBreakToken<'a> {
18397 Word { token: &'a str, grapheme_len: usize },
18398 InlineWhitespace { token: &'a str, grapheme_len: usize },
18399 Newline,
18400}
18401
18402impl<'a> Iterator for WordBreakingTokenizer<'a> {
18403 /// Yields a span, the count of graphemes in the token, and whether it was
18404 /// whitespace. Note that it also breaks at word boundaries.
18405 type Item = WordBreakToken<'a>;
18406
18407 fn next(&mut self) -> Option<Self::Item> {
18408 use unicode_segmentation::UnicodeSegmentation;
18409 if self.input.is_empty() {
18410 return None;
18411 }
18412
18413 let mut iter = self.input.graphemes(true).peekable();
18414 let mut offset = 0;
18415 let mut grapheme_len = 0;
18416 if let Some(first_grapheme) = iter.next() {
18417 let is_newline = first_grapheme == "\n";
18418 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18419 offset += first_grapheme.len();
18420 grapheme_len += 1;
18421 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18422 if let Some(grapheme) = iter.peek().copied() {
18423 if should_stay_with_preceding_ideograph(grapheme) {
18424 offset += grapheme.len();
18425 grapheme_len += 1;
18426 }
18427 }
18428 } else {
18429 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18430 let mut next_word_bound = words.peek().copied();
18431 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18432 next_word_bound = words.next();
18433 }
18434 while let Some(grapheme) = iter.peek().copied() {
18435 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18436 break;
18437 };
18438 if is_grapheme_whitespace(grapheme) != is_whitespace
18439 || (grapheme == "\n") != is_newline
18440 {
18441 break;
18442 };
18443 offset += grapheme.len();
18444 grapheme_len += 1;
18445 iter.next();
18446 }
18447 }
18448 let token = &self.input[..offset];
18449 self.input = &self.input[offset..];
18450 if token == "\n" {
18451 Some(WordBreakToken::Newline)
18452 } else if is_whitespace {
18453 Some(WordBreakToken::InlineWhitespace {
18454 token,
18455 grapheme_len,
18456 })
18457 } else {
18458 Some(WordBreakToken::Word {
18459 token,
18460 grapheme_len,
18461 })
18462 }
18463 } else {
18464 None
18465 }
18466 }
18467}
18468
18469#[test]
18470fn test_word_breaking_tokenizer() {
18471 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18472 ("", &[]),
18473 (" ", &[whitespace(" ", 2)]),
18474 ("Ʒ", &[word("Ʒ", 1)]),
18475 ("Ǽ", &[word("Ǽ", 1)]),
18476 ("⋑", &[word("⋑", 1)]),
18477 ("⋑⋑", &[word("⋑⋑", 2)]),
18478 (
18479 "原理,进而",
18480 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18481 ),
18482 (
18483 "hello world",
18484 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18485 ),
18486 (
18487 "hello, world",
18488 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18489 ),
18490 (
18491 " hello world",
18492 &[
18493 whitespace(" ", 2),
18494 word("hello", 5),
18495 whitespace(" ", 1),
18496 word("world", 5),
18497 ],
18498 ),
18499 (
18500 "这是什么 \n 钢笔",
18501 &[
18502 word("这", 1),
18503 word("是", 1),
18504 word("什", 1),
18505 word("么", 1),
18506 whitespace(" ", 1),
18507 newline(),
18508 whitespace(" ", 1),
18509 word("钢", 1),
18510 word("笔", 1),
18511 ],
18512 ),
18513 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18514 ];
18515
18516 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18517 WordBreakToken::Word {
18518 token,
18519 grapheme_len,
18520 }
18521 }
18522
18523 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18524 WordBreakToken::InlineWhitespace {
18525 token,
18526 grapheme_len,
18527 }
18528 }
18529
18530 fn newline() -> WordBreakToken<'static> {
18531 WordBreakToken::Newline
18532 }
18533
18534 for (input, result) in tests {
18535 assert_eq!(
18536 WordBreakingTokenizer::new(input)
18537 .collect::<Vec<_>>()
18538 .as_slice(),
18539 *result,
18540 );
18541 }
18542}
18543
18544fn wrap_with_prefix(
18545 line_prefix: String,
18546 unwrapped_text: String,
18547 wrap_column: usize,
18548 tab_size: NonZeroU32,
18549 preserve_existing_whitespace: bool,
18550) -> String {
18551 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18552 let mut wrapped_text = String::new();
18553 let mut current_line = line_prefix.clone();
18554
18555 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18556 let mut current_line_len = line_prefix_len;
18557 let mut in_whitespace = false;
18558 for token in tokenizer {
18559 let have_preceding_whitespace = in_whitespace;
18560 match token {
18561 WordBreakToken::Word {
18562 token,
18563 grapheme_len,
18564 } => {
18565 in_whitespace = false;
18566 if current_line_len + grapheme_len > wrap_column
18567 && current_line_len != line_prefix_len
18568 {
18569 wrapped_text.push_str(current_line.trim_end());
18570 wrapped_text.push('\n');
18571 current_line.truncate(line_prefix.len());
18572 current_line_len = line_prefix_len;
18573 }
18574 current_line.push_str(token);
18575 current_line_len += grapheme_len;
18576 }
18577 WordBreakToken::InlineWhitespace {
18578 mut token,
18579 mut grapheme_len,
18580 } => {
18581 in_whitespace = true;
18582 if have_preceding_whitespace && !preserve_existing_whitespace {
18583 continue;
18584 }
18585 if !preserve_existing_whitespace {
18586 token = " ";
18587 grapheme_len = 1;
18588 }
18589 if current_line_len + grapheme_len > wrap_column {
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 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18595 current_line.push_str(token);
18596 current_line_len += grapheme_len;
18597 }
18598 }
18599 WordBreakToken::Newline => {
18600 in_whitespace = true;
18601 if preserve_existing_whitespace {
18602 wrapped_text.push_str(current_line.trim_end());
18603 wrapped_text.push('\n');
18604 current_line.truncate(line_prefix.len());
18605 current_line_len = line_prefix_len;
18606 } else if have_preceding_whitespace {
18607 continue;
18608 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18609 {
18610 wrapped_text.push_str(current_line.trim_end());
18611 wrapped_text.push('\n');
18612 current_line.truncate(line_prefix.len());
18613 current_line_len = line_prefix_len;
18614 } else if current_line_len != line_prefix_len {
18615 current_line.push(' ');
18616 current_line_len += 1;
18617 }
18618 }
18619 }
18620 }
18621
18622 if !current_line.is_empty() {
18623 wrapped_text.push_str(¤t_line);
18624 }
18625 wrapped_text
18626}
18627
18628#[test]
18629fn test_wrap_with_prefix() {
18630 assert_eq!(
18631 wrap_with_prefix(
18632 "# ".to_string(),
18633 "abcdefg".to_string(),
18634 4,
18635 NonZeroU32::new(4).unwrap(),
18636 false,
18637 ),
18638 "# abcdefg"
18639 );
18640 assert_eq!(
18641 wrap_with_prefix(
18642 "".to_string(),
18643 "\thello world".to_string(),
18644 8,
18645 NonZeroU32::new(4).unwrap(),
18646 false,
18647 ),
18648 "hello\nworld"
18649 );
18650 assert_eq!(
18651 wrap_with_prefix(
18652 "// ".to_string(),
18653 "xx \nyy zz aa bb cc".to_string(),
18654 12,
18655 NonZeroU32::new(4).unwrap(),
18656 false,
18657 ),
18658 "// xx yy zz\n// aa bb cc"
18659 );
18660 assert_eq!(
18661 wrap_with_prefix(
18662 String::new(),
18663 "这是什么 \n 钢笔".to_string(),
18664 3,
18665 NonZeroU32::new(4).unwrap(),
18666 false,
18667 ),
18668 "这是什\n么 钢\n笔"
18669 );
18670}
18671
18672pub trait CollaborationHub {
18673 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18674 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18675 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18676}
18677
18678impl CollaborationHub for Entity<Project> {
18679 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18680 self.read(cx).collaborators()
18681 }
18682
18683 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18684 self.read(cx).user_store().read(cx).participant_indices()
18685 }
18686
18687 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18688 let this = self.read(cx);
18689 let user_ids = this.collaborators().values().map(|c| c.user_id);
18690 this.user_store().read_with(cx, |user_store, cx| {
18691 user_store.participant_names(user_ids, cx)
18692 })
18693 }
18694}
18695
18696pub trait SemanticsProvider {
18697 fn hover(
18698 &self,
18699 buffer: &Entity<Buffer>,
18700 position: text::Anchor,
18701 cx: &mut App,
18702 ) -> Option<Task<Vec<project::Hover>>>;
18703
18704 fn inlay_hints(
18705 &self,
18706 buffer_handle: Entity<Buffer>,
18707 range: Range<text::Anchor>,
18708 cx: &mut App,
18709 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18710
18711 fn resolve_inlay_hint(
18712 &self,
18713 hint: InlayHint,
18714 buffer_handle: Entity<Buffer>,
18715 server_id: LanguageServerId,
18716 cx: &mut App,
18717 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18718
18719 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18720
18721 fn document_highlights(
18722 &self,
18723 buffer: &Entity<Buffer>,
18724 position: text::Anchor,
18725 cx: &mut App,
18726 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18727
18728 fn definitions(
18729 &self,
18730 buffer: &Entity<Buffer>,
18731 position: text::Anchor,
18732 kind: GotoDefinitionKind,
18733 cx: &mut App,
18734 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18735
18736 fn range_for_rename(
18737 &self,
18738 buffer: &Entity<Buffer>,
18739 position: text::Anchor,
18740 cx: &mut App,
18741 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18742
18743 fn perform_rename(
18744 &self,
18745 buffer: &Entity<Buffer>,
18746 position: text::Anchor,
18747 new_name: String,
18748 cx: &mut App,
18749 ) -> Option<Task<Result<ProjectTransaction>>>;
18750}
18751
18752pub trait CompletionProvider {
18753 fn completions(
18754 &self,
18755 excerpt_id: ExcerptId,
18756 buffer: &Entity<Buffer>,
18757 buffer_position: text::Anchor,
18758 trigger: CompletionContext,
18759 window: &mut Window,
18760 cx: &mut Context<Editor>,
18761 ) -> Task<Result<Option<Vec<Completion>>>>;
18762
18763 fn resolve_completions(
18764 &self,
18765 buffer: Entity<Buffer>,
18766 completion_indices: Vec<usize>,
18767 completions: Rc<RefCell<Box<[Completion]>>>,
18768 cx: &mut Context<Editor>,
18769 ) -> Task<Result<bool>>;
18770
18771 fn apply_additional_edits_for_completion(
18772 &self,
18773 _buffer: Entity<Buffer>,
18774 _completions: Rc<RefCell<Box<[Completion]>>>,
18775 _completion_index: usize,
18776 _push_to_history: bool,
18777 _cx: &mut Context<Editor>,
18778 ) -> Task<Result<Option<language::Transaction>>> {
18779 Task::ready(Ok(None))
18780 }
18781
18782 fn is_completion_trigger(
18783 &self,
18784 buffer: &Entity<Buffer>,
18785 position: language::Anchor,
18786 text: &str,
18787 trigger_in_words: bool,
18788 cx: &mut Context<Editor>,
18789 ) -> bool;
18790
18791 fn sort_completions(&self) -> bool {
18792 true
18793 }
18794
18795 fn filter_completions(&self) -> bool {
18796 true
18797 }
18798}
18799
18800pub trait CodeActionProvider {
18801 fn id(&self) -> Arc<str>;
18802
18803 fn code_actions(
18804 &self,
18805 buffer: &Entity<Buffer>,
18806 range: Range<text::Anchor>,
18807 window: &mut Window,
18808 cx: &mut App,
18809 ) -> Task<Result<Vec<CodeAction>>>;
18810
18811 fn apply_code_action(
18812 &self,
18813 buffer_handle: Entity<Buffer>,
18814 action: CodeAction,
18815 excerpt_id: ExcerptId,
18816 push_to_history: bool,
18817 window: &mut Window,
18818 cx: &mut App,
18819 ) -> Task<Result<ProjectTransaction>>;
18820}
18821
18822impl CodeActionProvider for Entity<Project> {
18823 fn id(&self) -> Arc<str> {
18824 "project".into()
18825 }
18826
18827 fn code_actions(
18828 &self,
18829 buffer: &Entity<Buffer>,
18830 range: Range<text::Anchor>,
18831 _window: &mut Window,
18832 cx: &mut App,
18833 ) -> Task<Result<Vec<CodeAction>>> {
18834 self.update(cx, |project, cx| {
18835 let code_lens = project.code_lens(buffer, range.clone(), cx);
18836 let code_actions = project.code_actions(buffer, range, None, cx);
18837 cx.background_spawn(async move {
18838 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18839 Ok(code_lens
18840 .context("code lens fetch")?
18841 .into_iter()
18842 .chain(code_actions.context("code action fetch")?)
18843 .collect())
18844 })
18845 })
18846 }
18847
18848 fn apply_code_action(
18849 &self,
18850 buffer_handle: Entity<Buffer>,
18851 action: CodeAction,
18852 _excerpt_id: ExcerptId,
18853 push_to_history: bool,
18854 _window: &mut Window,
18855 cx: &mut App,
18856 ) -> Task<Result<ProjectTransaction>> {
18857 self.update(cx, |project, cx| {
18858 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18859 })
18860 }
18861}
18862
18863fn snippet_completions(
18864 project: &Project,
18865 buffer: &Entity<Buffer>,
18866 buffer_position: text::Anchor,
18867 cx: &mut App,
18868) -> Task<Result<Vec<Completion>>> {
18869 let languages = buffer.read(cx).languages_at(buffer_position);
18870 let snippet_store = project.snippets().read(cx);
18871
18872 let scopes: Vec<_> = languages
18873 .iter()
18874 .filter_map(|language| {
18875 let language_name = language.lsp_id();
18876 let snippets = snippet_store.snippets_for(Some(language_name), cx);
18877
18878 if snippets.is_empty() {
18879 None
18880 } else {
18881 Some((language.default_scope(), snippets))
18882 }
18883 })
18884 .collect();
18885
18886 if scopes.is_empty() {
18887 return Task::ready(Ok(vec![]));
18888 }
18889
18890 let snapshot = buffer.read(cx).text_snapshot();
18891 let chars: String = snapshot
18892 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18893 .collect();
18894 let executor = cx.background_executor().clone();
18895
18896 cx.background_spawn(async move {
18897 let mut all_results: Vec<Completion> = Vec::new();
18898 for (scope, snippets) in scopes.into_iter() {
18899 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18900 let mut last_word = chars
18901 .chars()
18902 .take_while(|c| classifier.is_word(*c))
18903 .collect::<String>();
18904 last_word = last_word.chars().rev().collect();
18905
18906 if last_word.is_empty() {
18907 return Ok(vec![]);
18908 }
18909
18910 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18911 let to_lsp = |point: &text::Anchor| {
18912 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18913 point_to_lsp(end)
18914 };
18915 let lsp_end = to_lsp(&buffer_position);
18916
18917 let candidates = snippets
18918 .iter()
18919 .enumerate()
18920 .flat_map(|(ix, snippet)| {
18921 snippet
18922 .prefix
18923 .iter()
18924 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18925 })
18926 .collect::<Vec<StringMatchCandidate>>();
18927
18928 let mut matches = fuzzy::match_strings(
18929 &candidates,
18930 &last_word,
18931 last_word.chars().any(|c| c.is_uppercase()),
18932 100,
18933 &Default::default(),
18934 executor.clone(),
18935 )
18936 .await;
18937
18938 // Remove all candidates where the query's start does not match the start of any word in the candidate
18939 if let Some(query_start) = last_word.chars().next() {
18940 matches.retain(|string_match| {
18941 split_words(&string_match.string).any(|word| {
18942 // Check that the first codepoint of the word as lowercase matches the first
18943 // codepoint of the query as lowercase
18944 word.chars()
18945 .flat_map(|codepoint| codepoint.to_lowercase())
18946 .zip(query_start.to_lowercase())
18947 .all(|(word_cp, query_cp)| word_cp == query_cp)
18948 })
18949 });
18950 }
18951
18952 let matched_strings = matches
18953 .into_iter()
18954 .map(|m| m.string)
18955 .collect::<HashSet<_>>();
18956
18957 let mut result: Vec<Completion> = snippets
18958 .iter()
18959 .filter_map(|snippet| {
18960 let matching_prefix = snippet
18961 .prefix
18962 .iter()
18963 .find(|prefix| matched_strings.contains(*prefix))?;
18964 let start = as_offset - last_word.len();
18965 let start = snapshot.anchor_before(start);
18966 let range = start..buffer_position;
18967 let lsp_start = to_lsp(&start);
18968 let lsp_range = lsp::Range {
18969 start: lsp_start,
18970 end: lsp_end,
18971 };
18972 Some(Completion {
18973 replace_range: range,
18974 new_text: snippet.body.clone(),
18975 source: CompletionSource::Lsp {
18976 insert_range: None,
18977 server_id: LanguageServerId(usize::MAX),
18978 resolved: true,
18979 lsp_completion: Box::new(lsp::CompletionItem {
18980 label: snippet.prefix.first().unwrap().clone(),
18981 kind: Some(CompletionItemKind::SNIPPET),
18982 label_details: snippet.description.as_ref().map(|description| {
18983 lsp::CompletionItemLabelDetails {
18984 detail: Some(description.clone()),
18985 description: None,
18986 }
18987 }),
18988 insert_text_format: Some(InsertTextFormat::SNIPPET),
18989 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18990 lsp::InsertReplaceEdit {
18991 new_text: snippet.body.clone(),
18992 insert: lsp_range,
18993 replace: lsp_range,
18994 },
18995 )),
18996 filter_text: Some(snippet.body.clone()),
18997 sort_text: Some(char::MAX.to_string()),
18998 ..lsp::CompletionItem::default()
18999 }),
19000 lsp_defaults: None,
19001 },
19002 label: CodeLabel {
19003 text: matching_prefix.clone(),
19004 runs: Vec::new(),
19005 filter_range: 0..matching_prefix.len(),
19006 },
19007 icon_path: None,
19008 documentation: snippet.description.clone().map(|description| {
19009 CompletionDocumentation::SingleLine(description.into())
19010 }),
19011 insert_text_mode: None,
19012 confirm: None,
19013 })
19014 })
19015 .collect();
19016
19017 all_results.append(&mut result);
19018 }
19019
19020 Ok(all_results)
19021 })
19022}
19023
19024impl CompletionProvider for Entity<Project> {
19025 fn completions(
19026 &self,
19027 _excerpt_id: ExcerptId,
19028 buffer: &Entity<Buffer>,
19029 buffer_position: text::Anchor,
19030 options: CompletionContext,
19031 _window: &mut Window,
19032 cx: &mut Context<Editor>,
19033 ) -> Task<Result<Option<Vec<Completion>>>> {
19034 self.update(cx, |project, cx| {
19035 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19036 let project_completions = project.completions(buffer, buffer_position, options, cx);
19037 cx.background_spawn(async move {
19038 let snippets_completions = snippets.await?;
19039 match project_completions.await? {
19040 Some(mut completions) => {
19041 completions.extend(snippets_completions);
19042 Ok(Some(completions))
19043 }
19044 None => {
19045 if snippets_completions.is_empty() {
19046 Ok(None)
19047 } else {
19048 Ok(Some(snippets_completions))
19049 }
19050 }
19051 }
19052 })
19053 })
19054 }
19055
19056 fn resolve_completions(
19057 &self,
19058 buffer: Entity<Buffer>,
19059 completion_indices: Vec<usize>,
19060 completions: Rc<RefCell<Box<[Completion]>>>,
19061 cx: &mut Context<Editor>,
19062 ) -> Task<Result<bool>> {
19063 self.update(cx, |project, cx| {
19064 project.lsp_store().update(cx, |lsp_store, cx| {
19065 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19066 })
19067 })
19068 }
19069
19070 fn apply_additional_edits_for_completion(
19071 &self,
19072 buffer: Entity<Buffer>,
19073 completions: Rc<RefCell<Box<[Completion]>>>,
19074 completion_index: usize,
19075 push_to_history: bool,
19076 cx: &mut Context<Editor>,
19077 ) -> Task<Result<Option<language::Transaction>>> {
19078 self.update(cx, |project, cx| {
19079 project.lsp_store().update(cx, |lsp_store, cx| {
19080 lsp_store.apply_additional_edits_for_completion(
19081 buffer,
19082 completions,
19083 completion_index,
19084 push_to_history,
19085 cx,
19086 )
19087 })
19088 })
19089 }
19090
19091 fn is_completion_trigger(
19092 &self,
19093 buffer: &Entity<Buffer>,
19094 position: language::Anchor,
19095 text: &str,
19096 trigger_in_words: bool,
19097 cx: &mut Context<Editor>,
19098 ) -> bool {
19099 let mut chars = text.chars();
19100 let char = if let Some(char) = chars.next() {
19101 char
19102 } else {
19103 return false;
19104 };
19105 if chars.next().is_some() {
19106 return false;
19107 }
19108
19109 let buffer = buffer.read(cx);
19110 let snapshot = buffer.snapshot();
19111 if !snapshot.settings_at(position, cx).show_completions_on_input {
19112 return false;
19113 }
19114 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19115 if trigger_in_words && classifier.is_word(char) {
19116 return true;
19117 }
19118
19119 buffer.completion_triggers().contains(text)
19120 }
19121}
19122
19123impl SemanticsProvider for Entity<Project> {
19124 fn hover(
19125 &self,
19126 buffer: &Entity<Buffer>,
19127 position: text::Anchor,
19128 cx: &mut App,
19129 ) -> Option<Task<Vec<project::Hover>>> {
19130 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19131 }
19132
19133 fn document_highlights(
19134 &self,
19135 buffer: &Entity<Buffer>,
19136 position: text::Anchor,
19137 cx: &mut App,
19138 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19139 Some(self.update(cx, |project, cx| {
19140 project.document_highlights(buffer, position, cx)
19141 }))
19142 }
19143
19144 fn definitions(
19145 &self,
19146 buffer: &Entity<Buffer>,
19147 position: text::Anchor,
19148 kind: GotoDefinitionKind,
19149 cx: &mut App,
19150 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19151 Some(self.update(cx, |project, cx| match kind {
19152 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19153 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19154 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19155 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19156 }))
19157 }
19158
19159 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19160 // TODO: make this work for remote projects
19161 self.update(cx, |this, cx| {
19162 buffer.update(cx, |buffer, cx| {
19163 this.any_language_server_supports_inlay_hints(buffer, cx)
19164 })
19165 })
19166 }
19167
19168 fn inlay_hints(
19169 &self,
19170 buffer_handle: Entity<Buffer>,
19171 range: Range<text::Anchor>,
19172 cx: &mut App,
19173 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19174 Some(self.update(cx, |project, cx| {
19175 project.inlay_hints(buffer_handle, range, cx)
19176 }))
19177 }
19178
19179 fn resolve_inlay_hint(
19180 &self,
19181 hint: InlayHint,
19182 buffer_handle: Entity<Buffer>,
19183 server_id: LanguageServerId,
19184 cx: &mut App,
19185 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19186 Some(self.update(cx, |project, cx| {
19187 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19188 }))
19189 }
19190
19191 fn range_for_rename(
19192 &self,
19193 buffer: &Entity<Buffer>,
19194 position: text::Anchor,
19195 cx: &mut App,
19196 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19197 Some(self.update(cx, |project, cx| {
19198 let buffer = buffer.clone();
19199 let task = project.prepare_rename(buffer.clone(), position, cx);
19200 cx.spawn(async move |_, cx| {
19201 Ok(match task.await? {
19202 PrepareRenameResponse::Success(range) => Some(range),
19203 PrepareRenameResponse::InvalidPosition => None,
19204 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19205 // Fallback on using TreeSitter info to determine identifier range
19206 buffer.update(cx, |buffer, _| {
19207 let snapshot = buffer.snapshot();
19208 let (range, kind) = snapshot.surrounding_word(position);
19209 if kind != Some(CharKind::Word) {
19210 return None;
19211 }
19212 Some(
19213 snapshot.anchor_before(range.start)
19214 ..snapshot.anchor_after(range.end),
19215 )
19216 })?
19217 }
19218 })
19219 })
19220 }))
19221 }
19222
19223 fn perform_rename(
19224 &self,
19225 buffer: &Entity<Buffer>,
19226 position: text::Anchor,
19227 new_name: String,
19228 cx: &mut App,
19229 ) -> Option<Task<Result<ProjectTransaction>>> {
19230 Some(self.update(cx, |project, cx| {
19231 project.perform_rename(buffer.clone(), position, new_name, cx)
19232 }))
19233 }
19234}
19235
19236fn inlay_hint_settings(
19237 location: Anchor,
19238 snapshot: &MultiBufferSnapshot,
19239 cx: &mut Context<Editor>,
19240) -> InlayHintSettings {
19241 let file = snapshot.file_at(location);
19242 let language = snapshot.language_at(location).map(|l| l.name());
19243 language_settings(language, file, cx).inlay_hints
19244}
19245
19246fn consume_contiguous_rows(
19247 contiguous_row_selections: &mut Vec<Selection<Point>>,
19248 selection: &Selection<Point>,
19249 display_map: &DisplaySnapshot,
19250 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19251) -> (MultiBufferRow, MultiBufferRow) {
19252 contiguous_row_selections.push(selection.clone());
19253 let start_row = MultiBufferRow(selection.start.row);
19254 let mut end_row = ending_row(selection, display_map);
19255
19256 while let Some(next_selection) = selections.peek() {
19257 if next_selection.start.row <= end_row.0 {
19258 end_row = ending_row(next_selection, display_map);
19259 contiguous_row_selections.push(selections.next().unwrap().clone());
19260 } else {
19261 break;
19262 }
19263 }
19264 (start_row, end_row)
19265}
19266
19267fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19268 if next_selection.end.column > 0 || next_selection.is_empty() {
19269 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19270 } else {
19271 MultiBufferRow(next_selection.end.row)
19272 }
19273}
19274
19275impl EditorSnapshot {
19276 pub fn remote_selections_in_range<'a>(
19277 &'a self,
19278 range: &'a Range<Anchor>,
19279 collaboration_hub: &dyn CollaborationHub,
19280 cx: &'a App,
19281 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19282 let participant_names = collaboration_hub.user_names(cx);
19283 let participant_indices = collaboration_hub.user_participant_indices(cx);
19284 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19285 let collaborators_by_replica_id = collaborators_by_peer_id
19286 .iter()
19287 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19288 .collect::<HashMap<_, _>>();
19289 self.buffer_snapshot
19290 .selections_in_range(range, false)
19291 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19292 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19293 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19294 let user_name = participant_names.get(&collaborator.user_id).cloned();
19295 Some(RemoteSelection {
19296 replica_id,
19297 selection,
19298 cursor_shape,
19299 line_mode,
19300 participant_index,
19301 peer_id: collaborator.peer_id,
19302 user_name,
19303 })
19304 })
19305 }
19306
19307 pub fn hunks_for_ranges(
19308 &self,
19309 ranges: impl IntoIterator<Item = Range<Point>>,
19310 ) -> Vec<MultiBufferDiffHunk> {
19311 let mut hunks = Vec::new();
19312 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19313 HashMap::default();
19314 for query_range in ranges {
19315 let query_rows =
19316 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19317 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19318 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19319 ) {
19320 // Include deleted hunks that are adjacent to the query range, because
19321 // otherwise they would be missed.
19322 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19323 if hunk.status().is_deleted() {
19324 intersects_range |= hunk.row_range.start == query_rows.end;
19325 intersects_range |= hunk.row_range.end == query_rows.start;
19326 }
19327 if intersects_range {
19328 if !processed_buffer_rows
19329 .entry(hunk.buffer_id)
19330 .or_default()
19331 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19332 {
19333 continue;
19334 }
19335 hunks.push(hunk);
19336 }
19337 }
19338 }
19339
19340 hunks
19341 }
19342
19343 fn display_diff_hunks_for_rows<'a>(
19344 &'a self,
19345 display_rows: Range<DisplayRow>,
19346 folded_buffers: &'a HashSet<BufferId>,
19347 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19348 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19349 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19350
19351 self.buffer_snapshot
19352 .diff_hunks_in_range(buffer_start..buffer_end)
19353 .filter_map(|hunk| {
19354 if folded_buffers.contains(&hunk.buffer_id) {
19355 return None;
19356 }
19357
19358 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19359 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19360
19361 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19362 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19363
19364 let display_hunk = if hunk_display_start.column() != 0 {
19365 DisplayDiffHunk::Folded {
19366 display_row: hunk_display_start.row(),
19367 }
19368 } else {
19369 let mut end_row = hunk_display_end.row();
19370 if hunk_display_end.column() > 0 {
19371 end_row.0 += 1;
19372 }
19373 let is_created_file = hunk.is_created_file();
19374 DisplayDiffHunk::Unfolded {
19375 status: hunk.status(),
19376 diff_base_byte_range: hunk.diff_base_byte_range,
19377 display_row_range: hunk_display_start.row()..end_row,
19378 multi_buffer_range: Anchor::range_in_buffer(
19379 hunk.excerpt_id,
19380 hunk.buffer_id,
19381 hunk.buffer_range,
19382 ),
19383 is_created_file,
19384 }
19385 };
19386
19387 Some(display_hunk)
19388 })
19389 }
19390
19391 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19392 self.display_snapshot.buffer_snapshot.language_at(position)
19393 }
19394
19395 pub fn is_focused(&self) -> bool {
19396 self.is_focused
19397 }
19398
19399 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19400 self.placeholder_text.as_ref()
19401 }
19402
19403 pub fn scroll_position(&self) -> gpui::Point<f32> {
19404 self.scroll_anchor.scroll_position(&self.display_snapshot)
19405 }
19406
19407 fn gutter_dimensions(
19408 &self,
19409 font_id: FontId,
19410 font_size: Pixels,
19411 max_line_number_width: Pixels,
19412 cx: &App,
19413 ) -> Option<GutterDimensions> {
19414 if !self.show_gutter {
19415 return None;
19416 }
19417
19418 let descent = cx.text_system().descent(font_id, font_size);
19419 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19420 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19421
19422 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19423 matches!(
19424 ProjectSettings::get_global(cx).git.git_gutter,
19425 Some(GitGutterSetting::TrackedFiles)
19426 )
19427 });
19428 let gutter_settings = EditorSettings::get_global(cx).gutter;
19429 let show_line_numbers = self
19430 .show_line_numbers
19431 .unwrap_or(gutter_settings.line_numbers);
19432 let line_gutter_width = if show_line_numbers {
19433 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19434 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19435 max_line_number_width.max(min_width_for_number_on_gutter)
19436 } else {
19437 0.0.into()
19438 };
19439
19440 let show_code_actions = self
19441 .show_code_actions
19442 .unwrap_or(gutter_settings.code_actions);
19443
19444 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19445 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19446
19447 let git_blame_entries_width =
19448 self.git_blame_gutter_max_author_length
19449 .map(|max_author_length| {
19450 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19451 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19452
19453 /// The number of characters to dedicate to gaps and margins.
19454 const SPACING_WIDTH: usize = 4;
19455
19456 let max_char_count = max_author_length.min(renderer.max_author_length())
19457 + ::git::SHORT_SHA_LENGTH
19458 + MAX_RELATIVE_TIMESTAMP.len()
19459 + SPACING_WIDTH;
19460
19461 em_advance * max_char_count
19462 });
19463
19464 let is_singleton = self.buffer_snapshot.is_singleton();
19465
19466 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19467 left_padding += if !is_singleton {
19468 em_width * 4.0
19469 } else if show_code_actions || show_runnables || show_breakpoints {
19470 em_width * 3.0
19471 } else if show_git_gutter && show_line_numbers {
19472 em_width * 2.0
19473 } else if show_git_gutter || show_line_numbers {
19474 em_width
19475 } else {
19476 px(0.)
19477 };
19478
19479 let shows_folds = is_singleton && gutter_settings.folds;
19480
19481 let right_padding = if shows_folds && show_line_numbers {
19482 em_width * 4.0
19483 } else if shows_folds || (!is_singleton && show_line_numbers) {
19484 em_width * 3.0
19485 } else if show_line_numbers {
19486 em_width
19487 } else {
19488 px(0.)
19489 };
19490
19491 Some(GutterDimensions {
19492 left_padding,
19493 right_padding,
19494 width: line_gutter_width + left_padding + right_padding,
19495 margin: -descent,
19496 git_blame_entries_width,
19497 })
19498 }
19499
19500 pub fn render_crease_toggle(
19501 &self,
19502 buffer_row: MultiBufferRow,
19503 row_contains_cursor: bool,
19504 editor: Entity<Editor>,
19505 window: &mut Window,
19506 cx: &mut App,
19507 ) -> Option<AnyElement> {
19508 let folded = self.is_line_folded(buffer_row);
19509 let mut is_foldable = false;
19510
19511 if let Some(crease) = self
19512 .crease_snapshot
19513 .query_row(buffer_row, &self.buffer_snapshot)
19514 {
19515 is_foldable = true;
19516 match crease {
19517 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19518 if let Some(render_toggle) = render_toggle {
19519 let toggle_callback =
19520 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19521 if folded {
19522 editor.update(cx, |editor, cx| {
19523 editor.fold_at(buffer_row, window, cx)
19524 });
19525 } else {
19526 editor.update(cx, |editor, cx| {
19527 editor.unfold_at(buffer_row, window, cx)
19528 });
19529 }
19530 });
19531 return Some((render_toggle)(
19532 buffer_row,
19533 folded,
19534 toggle_callback,
19535 window,
19536 cx,
19537 ));
19538 }
19539 }
19540 }
19541 }
19542
19543 is_foldable |= self.starts_indent(buffer_row);
19544
19545 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19546 Some(
19547 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19548 .toggle_state(folded)
19549 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19550 if folded {
19551 this.unfold_at(buffer_row, window, cx);
19552 } else {
19553 this.fold_at(buffer_row, window, cx);
19554 }
19555 }))
19556 .into_any_element(),
19557 )
19558 } else {
19559 None
19560 }
19561 }
19562
19563 pub fn render_crease_trailer(
19564 &self,
19565 buffer_row: MultiBufferRow,
19566 window: &mut Window,
19567 cx: &mut App,
19568 ) -> Option<AnyElement> {
19569 let folded = self.is_line_folded(buffer_row);
19570 if let Crease::Inline { render_trailer, .. } = self
19571 .crease_snapshot
19572 .query_row(buffer_row, &self.buffer_snapshot)?
19573 {
19574 let render_trailer = render_trailer.as_ref()?;
19575 Some(render_trailer(buffer_row, folded, window, cx))
19576 } else {
19577 None
19578 }
19579 }
19580}
19581
19582impl Deref for EditorSnapshot {
19583 type Target = DisplaySnapshot;
19584
19585 fn deref(&self) -> &Self::Target {
19586 &self.display_snapshot
19587 }
19588}
19589
19590#[derive(Clone, Debug, PartialEq, Eq)]
19591pub enum EditorEvent {
19592 InputIgnored {
19593 text: Arc<str>,
19594 },
19595 InputHandled {
19596 utf16_range_to_replace: Option<Range<isize>>,
19597 text: Arc<str>,
19598 },
19599 ExcerptsAdded {
19600 buffer: Entity<Buffer>,
19601 predecessor: ExcerptId,
19602 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19603 },
19604 ExcerptsRemoved {
19605 ids: Vec<ExcerptId>,
19606 },
19607 BufferFoldToggled {
19608 ids: Vec<ExcerptId>,
19609 folded: bool,
19610 },
19611 ExcerptsEdited {
19612 ids: Vec<ExcerptId>,
19613 },
19614 ExcerptsExpanded {
19615 ids: Vec<ExcerptId>,
19616 },
19617 BufferEdited,
19618 Edited {
19619 transaction_id: clock::Lamport,
19620 },
19621 Reparsed(BufferId),
19622 Focused,
19623 FocusedIn,
19624 Blurred,
19625 DirtyChanged,
19626 Saved,
19627 TitleChanged,
19628 DiffBaseChanged,
19629 SelectionsChanged {
19630 local: bool,
19631 },
19632 ScrollPositionChanged {
19633 local: bool,
19634 autoscroll: bool,
19635 },
19636 Closed,
19637 TransactionUndone {
19638 transaction_id: clock::Lamport,
19639 },
19640 TransactionBegun {
19641 transaction_id: clock::Lamport,
19642 },
19643 Reloaded,
19644 CursorShapeChanged,
19645 PushedToNavHistory {
19646 anchor: Anchor,
19647 is_deactivate: bool,
19648 },
19649}
19650
19651impl EventEmitter<EditorEvent> for Editor {}
19652
19653impl Focusable for Editor {
19654 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19655 self.focus_handle.clone()
19656 }
19657}
19658
19659impl Render for Editor {
19660 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19661 let settings = ThemeSettings::get_global(cx);
19662
19663 let mut text_style = match self.mode {
19664 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19665 color: cx.theme().colors().editor_foreground,
19666 font_family: settings.ui_font.family.clone(),
19667 font_features: settings.ui_font.features.clone(),
19668 font_fallbacks: settings.ui_font.fallbacks.clone(),
19669 font_size: rems(0.875).into(),
19670 font_weight: settings.ui_font.weight,
19671 line_height: relative(settings.buffer_line_height.value()),
19672 ..Default::default()
19673 },
19674 EditorMode::Full { .. } => TextStyle {
19675 color: cx.theme().colors().editor_foreground,
19676 font_family: settings.buffer_font.family.clone(),
19677 font_features: settings.buffer_font.features.clone(),
19678 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19679 font_size: settings.buffer_font_size(cx).into(),
19680 font_weight: settings.buffer_font.weight,
19681 line_height: relative(settings.buffer_line_height.value()),
19682 ..Default::default()
19683 },
19684 };
19685 if let Some(text_style_refinement) = &self.text_style_refinement {
19686 text_style.refine(text_style_refinement)
19687 }
19688
19689 let background = match self.mode {
19690 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19691 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19692 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19693 };
19694
19695 EditorElement::new(
19696 &cx.entity(),
19697 EditorStyle {
19698 background,
19699 local_player: cx.theme().players().local(),
19700 text: text_style,
19701 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19702 syntax: cx.theme().syntax().clone(),
19703 status: cx.theme().status().clone(),
19704 inlay_hints_style: make_inlay_hints_style(cx),
19705 inline_completion_styles: make_suggestion_styles(cx),
19706 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19707 },
19708 )
19709 }
19710}
19711
19712impl EntityInputHandler for Editor {
19713 fn text_for_range(
19714 &mut self,
19715 range_utf16: Range<usize>,
19716 adjusted_range: &mut Option<Range<usize>>,
19717 _: &mut Window,
19718 cx: &mut Context<Self>,
19719 ) -> Option<String> {
19720 let snapshot = self.buffer.read(cx).read(cx);
19721 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19722 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19723 if (start.0..end.0) != range_utf16 {
19724 adjusted_range.replace(start.0..end.0);
19725 }
19726 Some(snapshot.text_for_range(start..end).collect())
19727 }
19728
19729 fn selected_text_range(
19730 &mut self,
19731 ignore_disabled_input: bool,
19732 _: &mut Window,
19733 cx: &mut Context<Self>,
19734 ) -> Option<UTF16Selection> {
19735 // Prevent the IME menu from appearing when holding down an alphabetic key
19736 // while input is disabled.
19737 if !ignore_disabled_input && !self.input_enabled {
19738 return None;
19739 }
19740
19741 let selection = self.selections.newest::<OffsetUtf16>(cx);
19742 let range = selection.range();
19743
19744 Some(UTF16Selection {
19745 range: range.start.0..range.end.0,
19746 reversed: selection.reversed,
19747 })
19748 }
19749
19750 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19751 let snapshot = self.buffer.read(cx).read(cx);
19752 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19753 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19754 }
19755
19756 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19757 self.clear_highlights::<InputComposition>(cx);
19758 self.ime_transaction.take();
19759 }
19760
19761 fn replace_text_in_range(
19762 &mut self,
19763 range_utf16: Option<Range<usize>>,
19764 text: &str,
19765 window: &mut Window,
19766 cx: &mut Context<Self>,
19767 ) {
19768 if !self.input_enabled {
19769 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19770 return;
19771 }
19772
19773 self.transact(window, cx, |this, window, cx| {
19774 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19775 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19776 Some(this.selection_replacement_ranges(range_utf16, cx))
19777 } else {
19778 this.marked_text_ranges(cx)
19779 };
19780
19781 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19782 let newest_selection_id = this.selections.newest_anchor().id;
19783 this.selections
19784 .all::<OffsetUtf16>(cx)
19785 .iter()
19786 .zip(ranges_to_replace.iter())
19787 .find_map(|(selection, range)| {
19788 if selection.id == newest_selection_id {
19789 Some(
19790 (range.start.0 as isize - selection.head().0 as isize)
19791 ..(range.end.0 as isize - selection.head().0 as isize),
19792 )
19793 } else {
19794 None
19795 }
19796 })
19797 });
19798
19799 cx.emit(EditorEvent::InputHandled {
19800 utf16_range_to_replace: range_to_replace,
19801 text: text.into(),
19802 });
19803
19804 if let Some(new_selected_ranges) = new_selected_ranges {
19805 this.change_selections(None, window, cx, |selections| {
19806 selections.select_ranges(new_selected_ranges)
19807 });
19808 this.backspace(&Default::default(), window, cx);
19809 }
19810
19811 this.handle_input(text, window, cx);
19812 });
19813
19814 if let Some(transaction) = self.ime_transaction {
19815 self.buffer.update(cx, |buffer, cx| {
19816 buffer.group_until_transaction(transaction, cx);
19817 });
19818 }
19819
19820 self.unmark_text(window, cx);
19821 }
19822
19823 fn replace_and_mark_text_in_range(
19824 &mut self,
19825 range_utf16: Option<Range<usize>>,
19826 text: &str,
19827 new_selected_range_utf16: Option<Range<usize>>,
19828 window: &mut Window,
19829 cx: &mut Context<Self>,
19830 ) {
19831 if !self.input_enabled {
19832 return;
19833 }
19834
19835 let transaction = self.transact(window, cx, |this, window, cx| {
19836 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19837 let snapshot = this.buffer.read(cx).read(cx);
19838 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19839 for marked_range in &mut marked_ranges {
19840 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19841 marked_range.start.0 += relative_range_utf16.start;
19842 marked_range.start =
19843 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19844 marked_range.end =
19845 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19846 }
19847 }
19848 Some(marked_ranges)
19849 } else if let Some(range_utf16) = range_utf16 {
19850 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19851 Some(this.selection_replacement_ranges(range_utf16, cx))
19852 } else {
19853 None
19854 };
19855
19856 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19857 let newest_selection_id = this.selections.newest_anchor().id;
19858 this.selections
19859 .all::<OffsetUtf16>(cx)
19860 .iter()
19861 .zip(ranges_to_replace.iter())
19862 .find_map(|(selection, range)| {
19863 if selection.id == newest_selection_id {
19864 Some(
19865 (range.start.0 as isize - selection.head().0 as isize)
19866 ..(range.end.0 as isize - selection.head().0 as isize),
19867 )
19868 } else {
19869 None
19870 }
19871 })
19872 });
19873
19874 cx.emit(EditorEvent::InputHandled {
19875 utf16_range_to_replace: range_to_replace,
19876 text: text.into(),
19877 });
19878
19879 if let Some(ranges) = ranges_to_replace {
19880 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19881 }
19882
19883 let marked_ranges = {
19884 let snapshot = this.buffer.read(cx).read(cx);
19885 this.selections
19886 .disjoint_anchors()
19887 .iter()
19888 .map(|selection| {
19889 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19890 })
19891 .collect::<Vec<_>>()
19892 };
19893
19894 if text.is_empty() {
19895 this.unmark_text(window, cx);
19896 } else {
19897 this.highlight_text::<InputComposition>(
19898 marked_ranges.clone(),
19899 HighlightStyle {
19900 underline: Some(UnderlineStyle {
19901 thickness: px(1.),
19902 color: None,
19903 wavy: false,
19904 }),
19905 ..Default::default()
19906 },
19907 cx,
19908 );
19909 }
19910
19911 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19912 let use_autoclose = this.use_autoclose;
19913 let use_auto_surround = this.use_auto_surround;
19914 this.set_use_autoclose(false);
19915 this.set_use_auto_surround(false);
19916 this.handle_input(text, window, cx);
19917 this.set_use_autoclose(use_autoclose);
19918 this.set_use_auto_surround(use_auto_surround);
19919
19920 if let Some(new_selected_range) = new_selected_range_utf16 {
19921 let snapshot = this.buffer.read(cx).read(cx);
19922 let new_selected_ranges = marked_ranges
19923 .into_iter()
19924 .map(|marked_range| {
19925 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19926 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19927 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19928 snapshot.clip_offset_utf16(new_start, Bias::Left)
19929 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19930 })
19931 .collect::<Vec<_>>();
19932
19933 drop(snapshot);
19934 this.change_selections(None, window, cx, |selections| {
19935 selections.select_ranges(new_selected_ranges)
19936 });
19937 }
19938 });
19939
19940 self.ime_transaction = self.ime_transaction.or(transaction);
19941 if let Some(transaction) = self.ime_transaction {
19942 self.buffer.update(cx, |buffer, cx| {
19943 buffer.group_until_transaction(transaction, cx);
19944 });
19945 }
19946
19947 if self.text_highlights::<InputComposition>(cx).is_none() {
19948 self.ime_transaction.take();
19949 }
19950 }
19951
19952 fn bounds_for_range(
19953 &mut self,
19954 range_utf16: Range<usize>,
19955 element_bounds: gpui::Bounds<Pixels>,
19956 window: &mut Window,
19957 cx: &mut Context<Self>,
19958 ) -> Option<gpui::Bounds<Pixels>> {
19959 let text_layout_details = self.text_layout_details(window);
19960 let gpui::Size {
19961 width: em_width,
19962 height: line_height,
19963 } = self.character_size(window);
19964
19965 let snapshot = self.snapshot(window, cx);
19966 let scroll_position = snapshot.scroll_position();
19967 let scroll_left = scroll_position.x * em_width;
19968
19969 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19970 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19971 + self.gutter_dimensions.width
19972 + self.gutter_dimensions.margin;
19973 let y = line_height * (start.row().as_f32() - scroll_position.y);
19974
19975 Some(Bounds {
19976 origin: element_bounds.origin + point(x, y),
19977 size: size(em_width, line_height),
19978 })
19979 }
19980
19981 fn character_index_for_point(
19982 &mut self,
19983 point: gpui::Point<Pixels>,
19984 _window: &mut Window,
19985 _cx: &mut Context<Self>,
19986 ) -> Option<usize> {
19987 let position_map = self.last_position_map.as_ref()?;
19988 if !position_map.text_hitbox.contains(&point) {
19989 return None;
19990 }
19991 let display_point = position_map.point_for_position(point).previous_valid;
19992 let anchor = position_map
19993 .snapshot
19994 .display_point_to_anchor(display_point, Bias::Left);
19995 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19996 Some(utf16_offset.0)
19997 }
19998}
19999
20000trait SelectionExt {
20001 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20002 fn spanned_rows(
20003 &self,
20004 include_end_if_at_line_start: bool,
20005 map: &DisplaySnapshot,
20006 ) -> Range<MultiBufferRow>;
20007}
20008
20009impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20010 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20011 let start = self
20012 .start
20013 .to_point(&map.buffer_snapshot)
20014 .to_display_point(map);
20015 let end = self
20016 .end
20017 .to_point(&map.buffer_snapshot)
20018 .to_display_point(map);
20019 if self.reversed {
20020 end..start
20021 } else {
20022 start..end
20023 }
20024 }
20025
20026 fn spanned_rows(
20027 &self,
20028 include_end_if_at_line_start: bool,
20029 map: &DisplaySnapshot,
20030 ) -> Range<MultiBufferRow> {
20031 let start = self.start.to_point(&map.buffer_snapshot);
20032 let mut end = self.end.to_point(&map.buffer_snapshot);
20033 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20034 end.row -= 1;
20035 }
20036
20037 let buffer_start = map.prev_line_boundary(start).0;
20038 let buffer_end = map.next_line_boundary(end).0;
20039 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20040 }
20041}
20042
20043impl<T: InvalidationRegion> InvalidationStack<T> {
20044 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20045 where
20046 S: Clone + ToOffset,
20047 {
20048 while let Some(region) = self.last() {
20049 let all_selections_inside_invalidation_ranges =
20050 if selections.len() == region.ranges().len() {
20051 selections
20052 .iter()
20053 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20054 .all(|(selection, invalidation_range)| {
20055 let head = selection.head().to_offset(buffer);
20056 invalidation_range.start <= head && invalidation_range.end >= head
20057 })
20058 } else {
20059 false
20060 };
20061
20062 if all_selections_inside_invalidation_ranges {
20063 break;
20064 } else {
20065 self.pop();
20066 }
20067 }
20068 }
20069}
20070
20071impl<T> Default for InvalidationStack<T> {
20072 fn default() -> Self {
20073 Self(Default::default())
20074 }
20075}
20076
20077impl<T> Deref for InvalidationStack<T> {
20078 type Target = Vec<T>;
20079
20080 fn deref(&self) -> &Self::Target {
20081 &self.0
20082 }
20083}
20084
20085impl<T> DerefMut for InvalidationStack<T> {
20086 fn deref_mut(&mut self) -> &mut Self::Target {
20087 &mut self.0
20088 }
20089}
20090
20091impl InvalidationRegion for SnippetState {
20092 fn ranges(&self) -> &[Range<Anchor>] {
20093 &self.ranges[self.active_index]
20094 }
20095}
20096
20097fn inline_completion_edit_text(
20098 current_snapshot: &BufferSnapshot,
20099 edits: &[(Range<Anchor>, String)],
20100 edit_preview: &EditPreview,
20101 include_deletions: bool,
20102 cx: &App,
20103) -> HighlightedText {
20104 let edits = edits
20105 .iter()
20106 .map(|(anchor, text)| {
20107 (
20108 anchor.start.text_anchor..anchor.end.text_anchor,
20109 text.clone(),
20110 )
20111 })
20112 .collect::<Vec<_>>();
20113
20114 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20115}
20116
20117pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20118 match severity {
20119 DiagnosticSeverity::ERROR => colors.error,
20120 DiagnosticSeverity::WARNING => colors.warning,
20121 DiagnosticSeverity::INFORMATION => colors.info,
20122 DiagnosticSeverity::HINT => colors.info,
20123 _ => colors.ignored,
20124 }
20125}
20126
20127pub fn styled_runs_for_code_label<'a>(
20128 label: &'a CodeLabel,
20129 syntax_theme: &'a theme::SyntaxTheme,
20130) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20131 let fade_out = HighlightStyle {
20132 fade_out: Some(0.35),
20133 ..Default::default()
20134 };
20135
20136 let mut prev_end = label.filter_range.end;
20137 label
20138 .runs
20139 .iter()
20140 .enumerate()
20141 .flat_map(move |(ix, (range, highlight_id))| {
20142 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20143 style
20144 } else {
20145 return Default::default();
20146 };
20147 let mut muted_style = style;
20148 muted_style.highlight(fade_out);
20149
20150 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20151 if range.start >= label.filter_range.end {
20152 if range.start > prev_end {
20153 runs.push((prev_end..range.start, fade_out));
20154 }
20155 runs.push((range.clone(), muted_style));
20156 } else if range.end <= label.filter_range.end {
20157 runs.push((range.clone(), style));
20158 } else {
20159 runs.push((range.start..label.filter_range.end, style));
20160 runs.push((label.filter_range.end..range.end, muted_style));
20161 }
20162 prev_end = cmp::max(prev_end, range.end);
20163
20164 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20165 runs.push((prev_end..label.text.len(), fade_out));
20166 }
20167
20168 runs
20169 })
20170}
20171
20172pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20173 let mut prev_index = 0;
20174 let mut prev_codepoint: Option<char> = None;
20175 text.char_indices()
20176 .chain([(text.len(), '\0')])
20177 .filter_map(move |(index, codepoint)| {
20178 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20179 let is_boundary = index == text.len()
20180 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20181 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20182 if is_boundary {
20183 let chunk = &text[prev_index..index];
20184 prev_index = index;
20185 Some(chunk)
20186 } else {
20187 None
20188 }
20189 })
20190}
20191
20192pub trait RangeToAnchorExt: Sized {
20193 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20194
20195 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20196 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20197 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20198 }
20199}
20200
20201impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20202 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20203 let start_offset = self.start.to_offset(snapshot);
20204 let end_offset = self.end.to_offset(snapshot);
20205 if start_offset == end_offset {
20206 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20207 } else {
20208 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20209 }
20210 }
20211}
20212
20213pub trait RowExt {
20214 fn as_f32(&self) -> f32;
20215
20216 fn next_row(&self) -> Self;
20217
20218 fn previous_row(&self) -> Self;
20219
20220 fn minus(&self, other: Self) -> u32;
20221}
20222
20223impl RowExt for DisplayRow {
20224 fn as_f32(&self) -> f32 {
20225 self.0 as f32
20226 }
20227
20228 fn next_row(&self) -> Self {
20229 Self(self.0 + 1)
20230 }
20231
20232 fn previous_row(&self) -> Self {
20233 Self(self.0.saturating_sub(1))
20234 }
20235
20236 fn minus(&self, other: Self) -> u32 {
20237 self.0 - other.0
20238 }
20239}
20240
20241impl RowExt for MultiBufferRow {
20242 fn as_f32(&self) -> f32 {
20243 self.0 as f32
20244 }
20245
20246 fn next_row(&self) -> Self {
20247 Self(self.0 + 1)
20248 }
20249
20250 fn previous_row(&self) -> Self {
20251 Self(self.0.saturating_sub(1))
20252 }
20253
20254 fn minus(&self, other: Self) -> u32 {
20255 self.0 - other.0
20256 }
20257}
20258
20259trait RowRangeExt {
20260 type Row;
20261
20262 fn len(&self) -> usize;
20263
20264 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20265}
20266
20267impl RowRangeExt for Range<MultiBufferRow> {
20268 type Row = MultiBufferRow;
20269
20270 fn len(&self) -> usize {
20271 (self.end.0 - self.start.0) as usize
20272 }
20273
20274 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20275 (self.start.0..self.end.0).map(MultiBufferRow)
20276 }
20277}
20278
20279impl RowRangeExt for Range<DisplayRow> {
20280 type Row = DisplayRow;
20281
20282 fn len(&self) -> usize {
20283 (self.end.0 - self.start.0) as usize
20284 }
20285
20286 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20287 (self.start.0..self.end.0).map(DisplayRow)
20288 }
20289}
20290
20291/// If select range has more than one line, we
20292/// just point the cursor to range.start.
20293fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20294 if range.start.row == range.end.row {
20295 range
20296 } else {
20297 range.start..range.start
20298 }
20299}
20300pub struct KillRing(ClipboardItem);
20301impl Global for KillRing {}
20302
20303const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20304
20305enum BreakpointPromptEditAction {
20306 Log,
20307 Condition,
20308 HitCondition,
20309}
20310
20311struct BreakpointPromptEditor {
20312 pub(crate) prompt: Entity<Editor>,
20313 editor: WeakEntity<Editor>,
20314 breakpoint_anchor: Anchor,
20315 breakpoint: Breakpoint,
20316 edit_action: BreakpointPromptEditAction,
20317 block_ids: HashSet<CustomBlockId>,
20318 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20319 _subscriptions: Vec<Subscription>,
20320}
20321
20322impl BreakpointPromptEditor {
20323 const MAX_LINES: u8 = 4;
20324
20325 fn new(
20326 editor: WeakEntity<Editor>,
20327 breakpoint_anchor: Anchor,
20328 breakpoint: Breakpoint,
20329 edit_action: BreakpointPromptEditAction,
20330 window: &mut Window,
20331 cx: &mut Context<Self>,
20332 ) -> Self {
20333 let base_text = match edit_action {
20334 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20335 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20336 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20337 }
20338 .map(|msg| msg.to_string())
20339 .unwrap_or_default();
20340
20341 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20342 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20343
20344 let prompt = cx.new(|cx| {
20345 let mut prompt = Editor::new(
20346 EditorMode::AutoHeight {
20347 max_lines: Self::MAX_LINES as usize,
20348 },
20349 buffer,
20350 None,
20351 window,
20352 cx,
20353 );
20354 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20355 prompt.set_show_cursor_when_unfocused(false, cx);
20356 prompt.set_placeholder_text(
20357 match edit_action {
20358 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20359 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20360 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20361 },
20362 cx,
20363 );
20364
20365 prompt
20366 });
20367
20368 Self {
20369 prompt,
20370 editor,
20371 breakpoint_anchor,
20372 breakpoint,
20373 edit_action,
20374 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20375 block_ids: Default::default(),
20376 _subscriptions: vec![],
20377 }
20378 }
20379
20380 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20381 self.block_ids.extend(block_ids)
20382 }
20383
20384 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20385 if let Some(editor) = self.editor.upgrade() {
20386 let message = self
20387 .prompt
20388 .read(cx)
20389 .buffer
20390 .read(cx)
20391 .as_singleton()
20392 .expect("A multi buffer in breakpoint prompt isn't possible")
20393 .read(cx)
20394 .as_rope()
20395 .to_string();
20396
20397 editor.update(cx, |editor, cx| {
20398 editor.edit_breakpoint_at_anchor(
20399 self.breakpoint_anchor,
20400 self.breakpoint.clone(),
20401 match self.edit_action {
20402 BreakpointPromptEditAction::Log => {
20403 BreakpointEditAction::EditLogMessage(message.into())
20404 }
20405 BreakpointPromptEditAction::Condition => {
20406 BreakpointEditAction::EditCondition(message.into())
20407 }
20408 BreakpointPromptEditAction::HitCondition => {
20409 BreakpointEditAction::EditHitCondition(message.into())
20410 }
20411 },
20412 cx,
20413 );
20414
20415 editor.remove_blocks(self.block_ids.clone(), None, cx);
20416 cx.focus_self(window);
20417 });
20418 }
20419 }
20420
20421 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20422 self.editor
20423 .update(cx, |editor, cx| {
20424 editor.remove_blocks(self.block_ids.clone(), None, cx);
20425 window.focus(&editor.focus_handle);
20426 })
20427 .log_err();
20428 }
20429
20430 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20431 let settings = ThemeSettings::get_global(cx);
20432 let text_style = TextStyle {
20433 color: if self.prompt.read(cx).read_only(cx) {
20434 cx.theme().colors().text_disabled
20435 } else {
20436 cx.theme().colors().text
20437 },
20438 font_family: settings.buffer_font.family.clone(),
20439 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20440 font_size: settings.buffer_font_size(cx).into(),
20441 font_weight: settings.buffer_font.weight,
20442 line_height: relative(settings.buffer_line_height.value()),
20443 ..Default::default()
20444 };
20445 EditorElement::new(
20446 &self.prompt,
20447 EditorStyle {
20448 background: cx.theme().colors().editor_background,
20449 local_player: cx.theme().players().local(),
20450 text: text_style,
20451 ..Default::default()
20452 },
20453 )
20454 }
20455}
20456
20457impl Render for BreakpointPromptEditor {
20458 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20459 let gutter_dimensions = *self.gutter_dimensions.lock();
20460 h_flex()
20461 .key_context("Editor")
20462 .bg(cx.theme().colors().editor_background)
20463 .border_y_1()
20464 .border_color(cx.theme().status().info_border)
20465 .size_full()
20466 .py(window.line_height() / 2.5)
20467 .on_action(cx.listener(Self::confirm))
20468 .on_action(cx.listener(Self::cancel))
20469 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20470 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20471 }
20472}
20473
20474impl Focusable for BreakpointPromptEditor {
20475 fn focus_handle(&self, cx: &App) -> FocusHandle {
20476 self.prompt.focus_handle(cx)
20477 }
20478}
20479
20480fn all_edits_insertions_or_deletions(
20481 edits: &Vec<(Range<Anchor>, String)>,
20482 snapshot: &MultiBufferSnapshot,
20483) -> bool {
20484 let mut all_insertions = true;
20485 let mut all_deletions = true;
20486
20487 for (range, new_text) in edits.iter() {
20488 let range_is_empty = range.to_offset(&snapshot).is_empty();
20489 let text_is_empty = new_text.is_empty();
20490
20491 if range_is_empty != text_is_empty {
20492 if range_is_empty {
20493 all_deletions = false;
20494 } else {
20495 all_insertions = false;
20496 }
20497 } else {
20498 return false;
20499 }
20500
20501 if !all_insertions && !all_deletions {
20502 return false;
20503 }
20504 }
20505 all_insertions || all_deletions
20506}
20507
20508struct MissingEditPredictionKeybindingTooltip;
20509
20510impl Render for MissingEditPredictionKeybindingTooltip {
20511 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20512 ui::tooltip_container(window, cx, |container, _, cx| {
20513 container
20514 .flex_shrink_0()
20515 .max_w_80()
20516 .min_h(rems_from_px(124.))
20517 .justify_between()
20518 .child(
20519 v_flex()
20520 .flex_1()
20521 .text_ui_sm(cx)
20522 .child(Label::new("Conflict with Accept Keybinding"))
20523 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20524 )
20525 .child(
20526 h_flex()
20527 .pb_1()
20528 .gap_1()
20529 .items_end()
20530 .w_full()
20531 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20532 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20533 }))
20534 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20535 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20536 })),
20537 )
20538 })
20539 }
20540}
20541
20542#[derive(Debug, Clone, Copy, PartialEq)]
20543pub struct LineHighlight {
20544 pub background: Background,
20545 pub border: Option<gpui::Hsla>,
20546}
20547
20548impl From<Hsla> for LineHighlight {
20549 fn from(hsla: Hsla) -> Self {
20550 Self {
20551 background: hsla.into(),
20552 border: None,
20553 }
20554 }
20555}
20556
20557impl From<Background> for LineHighlight {
20558 fn from(background: Background) -> Self {
20559 Self {
20560 background,
20561 border: None,
20562 }
20563 }
20564}
20565
20566fn render_diff_hunk_controls(
20567 row: u32,
20568 status: &DiffHunkStatus,
20569 hunk_range: Range<Anchor>,
20570 is_created_file: bool,
20571 line_height: Pixels,
20572 editor: &Entity<Editor>,
20573 _window: &mut Window,
20574 cx: &mut App,
20575) -> AnyElement {
20576 h_flex()
20577 .h(line_height)
20578 .mr_1()
20579 .gap_1()
20580 .px_0p5()
20581 .pb_1()
20582 .border_x_1()
20583 .border_b_1()
20584 .border_color(cx.theme().colors().border_variant)
20585 .rounded_b_lg()
20586 .bg(cx.theme().colors().editor_background)
20587 .gap_1()
20588 .occlude()
20589 .shadow_md()
20590 .child(if status.has_secondary_hunk() {
20591 Button::new(("stage", row as u64), "Stage")
20592 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20593 .tooltip({
20594 let focus_handle = editor.focus_handle(cx);
20595 move |window, cx| {
20596 Tooltip::for_action_in(
20597 "Stage Hunk",
20598 &::git::ToggleStaged,
20599 &focus_handle,
20600 window,
20601 cx,
20602 )
20603 }
20604 })
20605 .on_click({
20606 let editor = editor.clone();
20607 move |_event, _window, cx| {
20608 editor.update(cx, |editor, cx| {
20609 editor.stage_or_unstage_diff_hunks(
20610 true,
20611 vec![hunk_range.start..hunk_range.start],
20612 cx,
20613 );
20614 });
20615 }
20616 })
20617 } else {
20618 Button::new(("unstage", row as u64), "Unstage")
20619 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20620 .tooltip({
20621 let focus_handle = editor.focus_handle(cx);
20622 move |window, cx| {
20623 Tooltip::for_action_in(
20624 "Unstage Hunk",
20625 &::git::ToggleStaged,
20626 &focus_handle,
20627 window,
20628 cx,
20629 )
20630 }
20631 })
20632 .on_click({
20633 let editor = editor.clone();
20634 move |_event, _window, cx| {
20635 editor.update(cx, |editor, cx| {
20636 editor.stage_or_unstage_diff_hunks(
20637 false,
20638 vec![hunk_range.start..hunk_range.start],
20639 cx,
20640 );
20641 });
20642 }
20643 })
20644 })
20645 .child(
20646 Button::new(("restore", row as u64), "Restore")
20647 .tooltip({
20648 let focus_handle = editor.focus_handle(cx);
20649 move |window, cx| {
20650 Tooltip::for_action_in(
20651 "Restore Hunk",
20652 &::git::Restore,
20653 &focus_handle,
20654 window,
20655 cx,
20656 )
20657 }
20658 })
20659 .on_click({
20660 let editor = editor.clone();
20661 move |_event, window, cx| {
20662 editor.update(cx, |editor, cx| {
20663 let snapshot = editor.snapshot(window, cx);
20664 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20665 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20666 });
20667 }
20668 })
20669 .disabled(is_created_file),
20670 )
20671 .when(
20672 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20673 |el| {
20674 el.child(
20675 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20676 .shape(IconButtonShape::Square)
20677 .icon_size(IconSize::Small)
20678 // .disabled(!has_multiple_hunks)
20679 .tooltip({
20680 let focus_handle = editor.focus_handle(cx);
20681 move |window, cx| {
20682 Tooltip::for_action_in(
20683 "Next Hunk",
20684 &GoToHunk,
20685 &focus_handle,
20686 window,
20687 cx,
20688 )
20689 }
20690 })
20691 .on_click({
20692 let editor = editor.clone();
20693 move |_event, window, cx| {
20694 editor.update(cx, |editor, cx| {
20695 let snapshot = editor.snapshot(window, cx);
20696 let position =
20697 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20698 editor.go_to_hunk_before_or_after_position(
20699 &snapshot,
20700 position,
20701 Direction::Next,
20702 window,
20703 cx,
20704 );
20705 editor.expand_selected_diff_hunks(cx);
20706 });
20707 }
20708 }),
20709 )
20710 .child(
20711 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20712 .shape(IconButtonShape::Square)
20713 .icon_size(IconSize::Small)
20714 // .disabled(!has_multiple_hunks)
20715 .tooltip({
20716 let focus_handle = editor.focus_handle(cx);
20717 move |window, cx| {
20718 Tooltip::for_action_in(
20719 "Previous Hunk",
20720 &GoToPreviousHunk,
20721 &focus_handle,
20722 window,
20723 cx,
20724 )
20725 }
20726 })
20727 .on_click({
20728 let editor = editor.clone();
20729 move |_event, window, cx| {
20730 editor.update(cx, |editor, cx| {
20731 let snapshot = editor.snapshot(window, cx);
20732 let point =
20733 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20734 editor.go_to_hunk_before_or_after_position(
20735 &snapshot,
20736 point,
20737 Direction::Prev,
20738 window,
20739 cx,
20740 );
20741 editor.expand_selected_diff_hunks(cx);
20742 });
20743 }
20744 }),
20745 )
20746 },
20747 )
20748 .into_any_element()
20749}