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;
26mod 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, StyledText, Subscription, Task, TextStyle,
92 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
93 WeakFocusHandle, Window, div, impl_actions, point, prelude::*, pulsating_between, px, relative,
94 size,
95};
96use highlight_matching_bracket::refresh_matching_bracket_highlights;
97use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
98pub use hover_popover::hover_markdown_style;
99use hover_popover::{HoverState, hide_hover};
100use indent_guides::ActiveIndentGuidesState;
101use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
102pub use inline_completion::Direction;
103use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
104pub use items::MAX_TAB_TITLE_LEN;
105use itertools::Itertools;
106use language::{
107 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
108 CursorShape, Diagnostic, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
109 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
110 TransactionId, TreeSitterOptions, WordsQuery,
111 language_settings::{
112 self, InlayHintSettings, RewrapBehavior, WordsCompletionMode, all_language_settings,
113 language_settings,
114 },
115 point_from_lsp, text_diff_with_options,
116};
117use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
118use linked_editing_ranges::refresh_linked_ranges;
119use mouse_context_menu::MouseContextMenu;
120use persistence::DB;
121use project::{
122 ProjectPath,
123 debugger::breakpoint_store::{
124 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
125 },
126};
127
128pub use git::blame::BlameRenderer;
129pub use proposed_changes_editor::{
130 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
131};
132use smallvec::smallvec;
133use std::{cell::OnceCell, iter::Peekable};
134use task::{ResolvedTask, TaskTemplate, TaskVariables};
135
136pub use lsp::CompletionContext;
137use lsp::{
138 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
139 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
140};
141
142use language::BufferSnapshot;
143use movement::TextLayoutDetails;
144pub use multi_buffer::{
145 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
146 ToOffset, ToPoint,
147};
148use multi_buffer::{
149 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
150 MultiOrSingleBufferOffsetRange, PathKey, 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 struct SearchWithinRange;
359
360trait InvalidationRegion {
361 fn ranges(&self) -> &[Range<Anchor>];
362}
363
364#[derive(Clone, Debug, PartialEq)]
365pub enum SelectPhase {
366 Begin {
367 position: DisplayPoint,
368 add: bool,
369 click_count: usize,
370 },
371 BeginColumnar {
372 position: DisplayPoint,
373 reset: bool,
374 goal_column: u32,
375 },
376 Extend {
377 position: DisplayPoint,
378 click_count: usize,
379 },
380 Update {
381 position: DisplayPoint,
382 goal_column: u32,
383 scroll_delta: gpui::Point<f32>,
384 },
385 End,
386}
387
388#[derive(Clone, Debug)]
389pub enum SelectMode {
390 Character,
391 Word(Range<Anchor>),
392 Line(Range<Anchor>),
393 All,
394}
395
396#[derive(Copy, Clone, PartialEq, Eq, Debug)]
397pub enum EditorMode {
398 SingleLine { auto_width: bool },
399 AutoHeight { max_lines: usize },
400 Full,
401}
402
403#[derive(Copy, Clone, Debug)]
404pub enum SoftWrap {
405 /// Prefer not to wrap at all.
406 ///
407 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
408 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
409 GitDiff,
410 /// Prefer a single line generally, unless an overly long line is encountered.
411 None,
412 /// Soft wrap lines that exceed the editor width.
413 EditorWidth,
414 /// Soft wrap lines at the preferred line length.
415 Column(u32),
416 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
417 Bounded(u32),
418}
419
420#[derive(Clone)]
421pub struct EditorStyle {
422 pub background: Hsla,
423 pub local_player: PlayerColor,
424 pub text: TextStyle,
425 pub scrollbar_width: Pixels,
426 pub syntax: Arc<SyntaxTheme>,
427 pub status: StatusColors,
428 pub inlay_hints_style: HighlightStyle,
429 pub inline_completion_styles: InlineCompletionStyles,
430 pub unnecessary_code_fade: f32,
431}
432
433impl Default for EditorStyle {
434 fn default() -> Self {
435 Self {
436 background: Hsla::default(),
437 local_player: PlayerColor::default(),
438 text: TextStyle::default(),
439 scrollbar_width: Pixels::default(),
440 syntax: Default::default(),
441 // HACK: Status colors don't have a real default.
442 // We should look into removing the status colors from the editor
443 // style and retrieve them directly from the theme.
444 status: StatusColors::dark(),
445 inlay_hints_style: HighlightStyle::default(),
446 inline_completion_styles: InlineCompletionStyles {
447 insertion: HighlightStyle::default(),
448 whitespace: HighlightStyle::default(),
449 },
450 unnecessary_code_fade: Default::default(),
451 }
452 }
453}
454
455pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
456 let show_background = language_settings::language_settings(None, None, cx)
457 .inlay_hints
458 .show_background;
459
460 HighlightStyle {
461 color: Some(cx.theme().status().hint),
462 background_color: show_background.then(|| cx.theme().status().hint_background),
463 ..HighlightStyle::default()
464 }
465}
466
467pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
468 InlineCompletionStyles {
469 insertion: HighlightStyle {
470 color: Some(cx.theme().status().predictive),
471 ..HighlightStyle::default()
472 },
473 whitespace: HighlightStyle {
474 background_color: Some(cx.theme().status().created_background),
475 ..HighlightStyle::default()
476 },
477 }
478}
479
480type CompletionId = usize;
481
482pub(crate) enum EditDisplayMode {
483 TabAccept,
484 DiffPopover,
485 Inline,
486}
487
488enum InlineCompletion {
489 Edit {
490 edits: Vec<(Range<Anchor>, String)>,
491 edit_preview: Option<EditPreview>,
492 display_mode: EditDisplayMode,
493 snapshot: BufferSnapshot,
494 },
495 Move {
496 target: Anchor,
497 snapshot: BufferSnapshot,
498 },
499}
500
501struct InlineCompletionState {
502 inlay_ids: Vec<InlayId>,
503 completion: InlineCompletion,
504 completion_id: Option<SharedString>,
505 invalidation_range: Range<Anchor>,
506}
507
508enum EditPredictionSettings {
509 Disabled,
510 Enabled {
511 show_in_menu: bool,
512 preview_requires_modifier: bool,
513 },
514}
515
516enum InlineCompletionHighlight {}
517
518#[derive(Debug, Clone)]
519struct InlineDiagnostic {
520 message: SharedString,
521 group_id: usize,
522 is_primary: bool,
523 start: Point,
524 severity: DiagnosticSeverity,
525}
526
527pub enum MenuInlineCompletionsPolicy {
528 Never,
529 ByProvider,
530}
531
532pub enum EditPredictionPreview {
533 /// Modifier is not pressed
534 Inactive { released_too_fast: bool },
535 /// Modifier pressed
536 Active {
537 since: Instant,
538 previous_scroll_position: Option<ScrollAnchor>,
539 },
540}
541
542impl EditPredictionPreview {
543 pub fn released_too_fast(&self) -> bool {
544 match self {
545 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
546 EditPredictionPreview::Active { .. } => false,
547 }
548 }
549
550 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
551 if let EditPredictionPreview::Active {
552 previous_scroll_position,
553 ..
554 } = self
555 {
556 *previous_scroll_position = scroll_position;
557 }
558 }
559}
560
561pub struct ContextMenuOptions {
562 pub min_entries_visible: usize,
563 pub max_entries_visible: usize,
564 pub placement: Option<ContextMenuPlacement>,
565}
566
567#[derive(Debug, Clone, PartialEq, Eq)]
568pub enum ContextMenuPlacement {
569 Above,
570 Below,
571}
572
573#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
574struct EditorActionId(usize);
575
576impl EditorActionId {
577 pub fn post_inc(&mut self) -> Self {
578 let answer = self.0;
579
580 *self = Self(answer + 1);
581
582 Self(answer)
583 }
584}
585
586// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
587// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
588
589type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
590type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
591
592#[derive(Default)]
593struct ScrollbarMarkerState {
594 scrollbar_size: Size<Pixels>,
595 dirty: bool,
596 markers: Arc<[PaintQuad]>,
597 pending_refresh: Option<Task<Result<()>>>,
598}
599
600impl ScrollbarMarkerState {
601 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
602 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
603 }
604}
605
606#[derive(Clone, Debug)]
607struct RunnableTasks {
608 templates: Vec<(TaskSourceKind, TaskTemplate)>,
609 offset: multi_buffer::Anchor,
610 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
611 column: u32,
612 // Values of all named captures, including those starting with '_'
613 extra_variables: HashMap<String, String>,
614 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
615 context_range: Range<BufferOffset>,
616}
617
618impl RunnableTasks {
619 fn resolve<'a>(
620 &'a self,
621 cx: &'a task::TaskContext,
622 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
623 self.templates.iter().filter_map(|(kind, template)| {
624 template
625 .resolve_task(&kind.to_id_base(), cx)
626 .map(|task| (kind.clone(), task))
627 })
628 }
629}
630
631#[derive(Clone)]
632struct ResolvedTasks {
633 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
634 position: Anchor,
635}
636
637#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
638struct BufferOffset(usize);
639
640// Addons allow storing per-editor state in other crates (e.g. Vim)
641pub trait Addon: 'static {
642 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
643
644 fn render_buffer_header_controls(
645 &self,
646 _: &ExcerptInfo,
647 _: &Window,
648 _: &App,
649 ) -> Option<AnyElement> {
650 None
651 }
652
653 fn to_any(&self) -> &dyn std::any::Any;
654}
655
656/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
657///
658/// See the [module level documentation](self) for more information.
659pub struct Editor {
660 focus_handle: FocusHandle,
661 last_focused_descendant: Option<WeakFocusHandle>,
662 /// The text buffer being edited
663 buffer: Entity<MultiBuffer>,
664 /// Map of how text in the buffer should be displayed.
665 /// Handles soft wraps, folds, fake inlay text insertions, etc.
666 pub display_map: Entity<DisplayMap>,
667 pub selections: SelectionsCollection,
668 pub scroll_manager: ScrollManager,
669 /// When inline assist editors are linked, they all render cursors because
670 /// typing enters text into each of them, even the ones that aren't focused.
671 pub(crate) show_cursor_when_unfocused: bool,
672 columnar_selection_tail: Option<Anchor>,
673 add_selections_state: Option<AddSelectionsState>,
674 select_next_state: Option<SelectNextState>,
675 select_prev_state: Option<SelectNextState>,
676 selection_history: SelectionHistory,
677 autoclose_regions: Vec<AutocloseRegion>,
678 snippet_stack: InvalidationStack<SnippetState>,
679 select_syntax_node_history: SelectSyntaxNodeHistory,
680 ime_transaction: Option<TransactionId>,
681 active_diagnostics: Option<ActiveDiagnosticGroup>,
682 show_inline_diagnostics: bool,
683 inline_diagnostics_update: Task<()>,
684 inline_diagnostics_enabled: bool,
685 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
686 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
687 hard_wrap: Option<usize>,
688
689 // TODO: make this a access method
690 pub project: Option<Entity<Project>>,
691 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
692 completion_provider: Option<Box<dyn CompletionProvider>>,
693 collaboration_hub: Option<Box<dyn CollaborationHub>>,
694 blink_manager: Entity<BlinkManager>,
695 show_cursor_names: bool,
696 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
697 pub show_local_selections: bool,
698 mode: EditorMode,
699 show_breadcrumbs: bool,
700 show_gutter: bool,
701 show_scrollbars: bool,
702 show_line_numbers: Option<bool>,
703 use_relative_line_numbers: Option<bool>,
704 show_git_diff_gutter: Option<bool>,
705 show_code_actions: Option<bool>,
706 show_runnables: Option<bool>,
707 show_breakpoints: Option<bool>,
708 show_wrap_guides: Option<bool>,
709 show_indent_guides: Option<bool>,
710 placeholder_text: Option<Arc<str>>,
711 highlight_order: usize,
712 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
713 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
714 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
715 scrollbar_marker_state: ScrollbarMarkerState,
716 active_indent_guides_state: ActiveIndentGuidesState,
717 nav_history: Option<ItemNavHistory>,
718 context_menu: RefCell<Option<CodeContextMenu>>,
719 context_menu_options: Option<ContextMenuOptions>,
720 mouse_context_menu: Option<MouseContextMenu>,
721 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
722 signature_help_state: SignatureHelpState,
723 auto_signature_help: Option<bool>,
724 find_all_references_task_sources: Vec<Anchor>,
725 next_completion_id: CompletionId,
726 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
727 code_actions_task: Option<Task<Result<()>>>,
728 selection_highlight_task: Option<Task<()>>,
729 document_highlights_task: Option<Task<()>>,
730 linked_editing_range_task: Option<Task<Option<()>>>,
731 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
732 pending_rename: Option<RenameState>,
733 searchable: bool,
734 cursor_shape: CursorShape,
735 current_line_highlight: Option<CurrentLineHighlight>,
736 collapse_matches: bool,
737 autoindent_mode: Option<AutoindentMode>,
738 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
739 input_enabled: bool,
740 use_modal_editing: bool,
741 read_only: bool,
742 leader_peer_id: Option<PeerId>,
743 remote_id: Option<ViewId>,
744 hover_state: HoverState,
745 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
746 gutter_hovered: bool,
747 hovered_link_state: Option<HoveredLinkState>,
748 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
749 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
750 active_inline_completion: Option<InlineCompletionState>,
751 /// Used to prevent flickering as the user types while the menu is open
752 stale_inline_completion_in_menu: Option<InlineCompletionState>,
753 edit_prediction_settings: EditPredictionSettings,
754 inline_completions_hidden_for_vim_mode: bool,
755 show_inline_completions_override: Option<bool>,
756 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
757 edit_prediction_preview: EditPredictionPreview,
758 edit_prediction_indent_conflict: bool,
759 edit_prediction_requires_modifier_in_indent_conflict: bool,
760 inlay_hint_cache: InlayHintCache,
761 next_inlay_id: usize,
762 _subscriptions: Vec<Subscription>,
763 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
764 gutter_dimensions: GutterDimensions,
765 style: Option<EditorStyle>,
766 text_style_refinement: Option<TextStyleRefinement>,
767 next_editor_action_id: EditorActionId,
768 editor_actions:
769 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
770 use_autoclose: bool,
771 use_auto_surround: bool,
772 auto_replace_emoji_shortcode: bool,
773 jsx_tag_auto_close_enabled_in_any_buffer: bool,
774 show_git_blame_gutter: bool,
775 show_git_blame_inline: bool,
776 show_git_blame_inline_delay_task: Option<Task<()>>,
777 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
778 git_blame_inline_enabled: bool,
779 render_diff_hunk_controls: RenderDiffHunkControlsFn,
780 serialize_dirty_buffers: bool,
781 show_selection_menu: Option<bool>,
782 blame: Option<Entity<GitBlame>>,
783 blame_subscription: Option<Subscription>,
784 custom_context_menu: Option<
785 Box<
786 dyn 'static
787 + Fn(
788 &mut Self,
789 DisplayPoint,
790 &mut Window,
791 &mut Context<Self>,
792 ) -> Option<Entity<ui::ContextMenu>>,
793 >,
794 >,
795 last_bounds: Option<Bounds<Pixels>>,
796 last_position_map: Option<Rc<PositionMap>>,
797 expect_bounds_change: Option<Bounds<Pixels>>,
798 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
799 tasks_update_task: Option<Task<()>>,
800 breakpoint_store: Option<Entity<BreakpointStore>>,
801 /// Allow's a user to create a breakpoint by selecting this indicator
802 /// It should be None while a user is not hovering over the gutter
803 /// Otherwise it represents the point that the breakpoint will be shown
804 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
805 in_project_search: bool,
806 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
807 breadcrumb_header: Option<String>,
808 focused_block: Option<FocusedBlock>,
809 next_scroll_position: NextScrollCursorCenterTopBottom,
810 addons: HashMap<TypeId, Box<dyn Addon>>,
811 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
812 load_diff_task: Option<Shared<Task<()>>>,
813 selection_mark_mode: bool,
814 toggle_fold_multiple_buffers: Task<()>,
815 _scroll_cursor_center_top_bottom_task: Task<()>,
816 serialize_selections: Task<()>,
817 serialize_folds: Task<()>,
818 mouse_cursor_hidden: bool,
819 hide_mouse_mode: HideMouseMode,
820}
821
822#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
823enum NextScrollCursorCenterTopBottom {
824 #[default]
825 Center,
826 Top,
827 Bottom,
828}
829
830impl NextScrollCursorCenterTopBottom {
831 fn next(&self) -> Self {
832 match self {
833 Self::Center => Self::Top,
834 Self::Top => Self::Bottom,
835 Self::Bottom => Self::Center,
836 }
837 }
838}
839
840#[derive(Clone)]
841pub struct EditorSnapshot {
842 pub mode: EditorMode,
843 show_gutter: bool,
844 show_line_numbers: Option<bool>,
845 show_git_diff_gutter: Option<bool>,
846 show_code_actions: Option<bool>,
847 show_runnables: Option<bool>,
848 show_breakpoints: Option<bool>,
849 git_blame_gutter_max_author_length: Option<usize>,
850 pub display_snapshot: DisplaySnapshot,
851 pub placeholder_text: Option<Arc<str>>,
852 is_focused: bool,
853 scroll_anchor: ScrollAnchor,
854 ongoing_scroll: OngoingScroll,
855 current_line_highlight: CurrentLineHighlight,
856 gutter_hovered: bool,
857}
858
859#[derive(Default, Debug, Clone, Copy)]
860pub struct GutterDimensions {
861 pub left_padding: Pixels,
862 pub right_padding: Pixels,
863 pub width: Pixels,
864 pub margin: Pixels,
865 pub git_blame_entries_width: Option<Pixels>,
866}
867
868impl GutterDimensions {
869 /// The full width of the space taken up by the gutter.
870 pub fn full_width(&self) -> Pixels {
871 self.margin + self.width
872 }
873
874 /// The width of the space reserved for the fold indicators,
875 /// use alongside 'justify_end' and `gutter_width` to
876 /// right align content with the line numbers
877 pub fn fold_area_width(&self) -> Pixels {
878 self.margin + self.right_padding
879 }
880}
881
882#[derive(Debug)]
883pub struct RemoteSelection {
884 pub replica_id: ReplicaId,
885 pub selection: Selection<Anchor>,
886 pub cursor_shape: CursorShape,
887 pub peer_id: PeerId,
888 pub line_mode: bool,
889 pub participant_index: Option<ParticipantIndex>,
890 pub user_name: Option<SharedString>,
891}
892
893#[derive(Clone, Debug)]
894struct SelectionHistoryEntry {
895 selections: Arc<[Selection<Anchor>]>,
896 select_next_state: Option<SelectNextState>,
897 select_prev_state: Option<SelectNextState>,
898 add_selections_state: Option<AddSelectionsState>,
899}
900
901enum SelectionHistoryMode {
902 Normal,
903 Undoing,
904 Redoing,
905}
906
907#[derive(Clone, PartialEq, Eq, Hash)]
908struct HoveredCursor {
909 replica_id: u16,
910 selection_id: usize,
911}
912
913impl Default for SelectionHistoryMode {
914 fn default() -> Self {
915 Self::Normal
916 }
917}
918
919#[derive(Default)]
920struct SelectionHistory {
921 #[allow(clippy::type_complexity)]
922 selections_by_transaction:
923 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
924 mode: SelectionHistoryMode,
925 undo_stack: VecDeque<SelectionHistoryEntry>,
926 redo_stack: VecDeque<SelectionHistoryEntry>,
927}
928
929impl SelectionHistory {
930 fn insert_transaction(
931 &mut self,
932 transaction_id: TransactionId,
933 selections: Arc<[Selection<Anchor>]>,
934 ) {
935 self.selections_by_transaction
936 .insert(transaction_id, (selections, None));
937 }
938
939 #[allow(clippy::type_complexity)]
940 fn transaction(
941 &self,
942 transaction_id: TransactionId,
943 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
944 self.selections_by_transaction.get(&transaction_id)
945 }
946
947 #[allow(clippy::type_complexity)]
948 fn transaction_mut(
949 &mut self,
950 transaction_id: TransactionId,
951 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
952 self.selections_by_transaction.get_mut(&transaction_id)
953 }
954
955 fn push(&mut self, entry: SelectionHistoryEntry) {
956 if !entry.selections.is_empty() {
957 match self.mode {
958 SelectionHistoryMode::Normal => {
959 self.push_undo(entry);
960 self.redo_stack.clear();
961 }
962 SelectionHistoryMode::Undoing => self.push_redo(entry),
963 SelectionHistoryMode::Redoing => self.push_undo(entry),
964 }
965 }
966 }
967
968 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
969 if self
970 .undo_stack
971 .back()
972 .map_or(true, |e| e.selections != entry.selections)
973 {
974 self.undo_stack.push_back(entry);
975 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
976 self.undo_stack.pop_front();
977 }
978 }
979 }
980
981 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
982 if self
983 .redo_stack
984 .back()
985 .map_or(true, |e| e.selections != entry.selections)
986 {
987 self.redo_stack.push_back(entry);
988 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
989 self.redo_stack.pop_front();
990 }
991 }
992 }
993}
994
995struct RowHighlight {
996 index: usize,
997 range: Range<Anchor>,
998 color: Hsla,
999 should_autoscroll: bool,
1000}
1001
1002#[derive(Clone, Debug)]
1003struct AddSelectionsState {
1004 above: bool,
1005 stack: Vec<usize>,
1006}
1007
1008#[derive(Clone)]
1009struct SelectNextState {
1010 query: AhoCorasick,
1011 wordwise: bool,
1012 done: bool,
1013}
1014
1015impl std::fmt::Debug for SelectNextState {
1016 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1017 f.debug_struct(std::any::type_name::<Self>())
1018 .field("wordwise", &self.wordwise)
1019 .field("done", &self.done)
1020 .finish()
1021 }
1022}
1023
1024#[derive(Debug)]
1025struct AutocloseRegion {
1026 selection_id: usize,
1027 range: Range<Anchor>,
1028 pair: BracketPair,
1029}
1030
1031#[derive(Debug)]
1032struct SnippetState {
1033 ranges: Vec<Vec<Range<Anchor>>>,
1034 active_index: usize,
1035 choices: Vec<Option<Vec<String>>>,
1036}
1037
1038#[doc(hidden)]
1039pub struct RenameState {
1040 pub range: Range<Anchor>,
1041 pub old_name: Arc<str>,
1042 pub editor: Entity<Editor>,
1043 block_id: CustomBlockId,
1044}
1045
1046struct InvalidationStack<T>(Vec<T>);
1047
1048struct RegisteredInlineCompletionProvider {
1049 provider: Arc<dyn InlineCompletionProviderHandle>,
1050 _subscription: Subscription,
1051}
1052
1053#[derive(Debug, PartialEq, Eq)]
1054struct ActiveDiagnosticGroup {
1055 primary_range: Range<Anchor>,
1056 primary_message: String,
1057 group_id: usize,
1058 blocks: HashMap<CustomBlockId, Diagnostic>,
1059 is_valid: bool,
1060}
1061
1062#[derive(Serialize, Deserialize, Clone, Debug)]
1063pub struct ClipboardSelection {
1064 /// The number of bytes in this selection.
1065 pub len: usize,
1066 /// Whether this was a full-line selection.
1067 pub is_entire_line: bool,
1068 /// The indentation of the first line when this content was originally copied.
1069 pub first_line_indent: u32,
1070}
1071
1072// selections, scroll behavior, was newest selection reversed
1073type SelectSyntaxNodeHistoryState = (
1074 Box<[Selection<usize>]>,
1075 SelectSyntaxNodeScrollBehavior,
1076 bool,
1077);
1078
1079#[derive(Default)]
1080struct SelectSyntaxNodeHistory {
1081 stack: Vec<SelectSyntaxNodeHistoryState>,
1082 // disable temporarily to allow changing selections without losing the stack
1083 pub disable_clearing: bool,
1084}
1085
1086impl SelectSyntaxNodeHistory {
1087 pub fn try_clear(&mut self) {
1088 if !self.disable_clearing {
1089 self.stack.clear();
1090 }
1091 }
1092
1093 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1094 self.stack.push(selection);
1095 }
1096
1097 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1098 self.stack.pop()
1099 }
1100}
1101
1102enum SelectSyntaxNodeScrollBehavior {
1103 CursorTop,
1104 FitSelection,
1105 CursorBottom,
1106}
1107
1108#[derive(Debug)]
1109pub(crate) struct NavigationData {
1110 cursor_anchor: Anchor,
1111 cursor_position: Point,
1112 scroll_anchor: ScrollAnchor,
1113 scroll_top_row: u32,
1114}
1115
1116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1117pub enum GotoDefinitionKind {
1118 Symbol,
1119 Declaration,
1120 Type,
1121 Implementation,
1122}
1123
1124#[derive(Debug, Clone)]
1125enum InlayHintRefreshReason {
1126 ModifiersChanged(bool),
1127 Toggle(bool),
1128 SettingsChange(InlayHintSettings),
1129 NewLinesShown,
1130 BufferEdited(HashSet<Arc<Language>>),
1131 RefreshRequested,
1132 ExcerptsRemoved(Vec<ExcerptId>),
1133}
1134
1135impl InlayHintRefreshReason {
1136 fn description(&self) -> &'static str {
1137 match self {
1138 Self::ModifiersChanged(_) => "modifiers changed",
1139 Self::Toggle(_) => "toggle",
1140 Self::SettingsChange(_) => "settings change",
1141 Self::NewLinesShown => "new lines shown",
1142 Self::BufferEdited(_) => "buffer edited",
1143 Self::RefreshRequested => "refresh requested",
1144 Self::ExcerptsRemoved(_) => "excerpts removed",
1145 }
1146 }
1147}
1148
1149pub enum FormatTarget {
1150 Buffers,
1151 Ranges(Vec<Range<MultiBufferPoint>>),
1152}
1153
1154pub(crate) struct FocusedBlock {
1155 id: BlockId,
1156 focus_handle: WeakFocusHandle,
1157}
1158
1159#[derive(Clone)]
1160enum JumpData {
1161 MultiBufferRow {
1162 row: MultiBufferRow,
1163 line_offset_from_top: u32,
1164 },
1165 MultiBufferPoint {
1166 excerpt_id: ExcerptId,
1167 position: Point,
1168 anchor: text::Anchor,
1169 line_offset_from_top: u32,
1170 },
1171}
1172
1173pub enum MultibufferSelectionMode {
1174 First,
1175 All,
1176}
1177
1178#[derive(Clone, Copy, Debug, Default)]
1179pub struct RewrapOptions {
1180 pub override_language_settings: bool,
1181 pub preserve_existing_whitespace: bool,
1182}
1183
1184impl Editor {
1185 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1186 let buffer = cx.new(|cx| Buffer::local("", cx));
1187 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1188 Self::new(
1189 EditorMode::SingleLine { auto_width: false },
1190 buffer,
1191 None,
1192 window,
1193 cx,
1194 )
1195 }
1196
1197 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1198 let buffer = cx.new(|cx| Buffer::local("", cx));
1199 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1200 Self::new(EditorMode::Full, buffer, None, window, cx)
1201 }
1202
1203 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1204 let buffer = cx.new(|cx| Buffer::local("", cx));
1205 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1206 Self::new(
1207 EditorMode::SingleLine { auto_width: true },
1208 buffer,
1209 None,
1210 window,
1211 cx,
1212 )
1213 }
1214
1215 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1216 let buffer = cx.new(|cx| Buffer::local("", cx));
1217 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1218 Self::new(
1219 EditorMode::AutoHeight { max_lines },
1220 buffer,
1221 None,
1222 window,
1223 cx,
1224 )
1225 }
1226
1227 pub fn for_buffer(
1228 buffer: Entity<Buffer>,
1229 project: Option<Entity<Project>>,
1230 window: &mut Window,
1231 cx: &mut Context<Self>,
1232 ) -> Self {
1233 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1234 Self::new(EditorMode::Full, buffer, project, window, cx)
1235 }
1236
1237 pub fn for_multibuffer(
1238 buffer: Entity<MultiBuffer>,
1239 project: Option<Entity<Project>>,
1240 window: &mut Window,
1241 cx: &mut Context<Self>,
1242 ) -> Self {
1243 Self::new(EditorMode::Full, buffer, project, window, cx)
1244 }
1245
1246 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1247 let mut clone = Self::new(
1248 self.mode,
1249 self.buffer.clone(),
1250 self.project.clone(),
1251 window,
1252 cx,
1253 );
1254 self.display_map.update(cx, |display_map, cx| {
1255 let snapshot = display_map.snapshot(cx);
1256 clone.display_map.update(cx, |display_map, cx| {
1257 display_map.set_state(&snapshot, cx);
1258 });
1259 });
1260 clone.folds_did_change(cx);
1261 clone.selections.clone_state(&self.selections);
1262 clone.scroll_manager.clone_state(&self.scroll_manager);
1263 clone.searchable = self.searchable;
1264 clone
1265 }
1266
1267 pub fn new(
1268 mode: EditorMode,
1269 buffer: Entity<MultiBuffer>,
1270 project: Option<Entity<Project>>,
1271 window: &mut Window,
1272 cx: &mut Context<Self>,
1273 ) -> Self {
1274 let style = window.text_style();
1275 let font_size = style.font_size.to_pixels(window.rem_size());
1276 let editor = cx.entity().downgrade();
1277 let fold_placeholder = FoldPlaceholder {
1278 constrain_width: true,
1279 render: Arc::new(move |fold_id, fold_range, cx| {
1280 let editor = editor.clone();
1281 div()
1282 .id(fold_id)
1283 .bg(cx.theme().colors().ghost_element_background)
1284 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1285 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1286 .rounded_xs()
1287 .size_full()
1288 .cursor_pointer()
1289 .child("⋯")
1290 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1291 .on_click(move |_, _window, cx| {
1292 editor
1293 .update(cx, |editor, cx| {
1294 editor.unfold_ranges(
1295 &[fold_range.start..fold_range.end],
1296 true,
1297 false,
1298 cx,
1299 );
1300 cx.stop_propagation();
1301 })
1302 .ok();
1303 })
1304 .into_any()
1305 }),
1306 merge_adjacent: true,
1307 ..Default::default()
1308 };
1309 let display_map = cx.new(|cx| {
1310 DisplayMap::new(
1311 buffer.clone(),
1312 style.font(),
1313 font_size,
1314 None,
1315 FILE_HEADER_HEIGHT,
1316 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1317 fold_placeholder,
1318 cx,
1319 )
1320 });
1321
1322 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1323
1324 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1325
1326 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1327 .then(|| language_settings::SoftWrap::None);
1328
1329 let mut project_subscriptions = Vec::new();
1330 if mode == EditorMode::Full {
1331 if let Some(project) = project.as_ref() {
1332 project_subscriptions.push(cx.subscribe_in(
1333 project,
1334 window,
1335 |editor, _, event, window, cx| match event {
1336 project::Event::RefreshCodeLens => {
1337 // we always query lens with actions, without storing them, always refreshing them
1338 }
1339 project::Event::RefreshInlayHints => {
1340 editor
1341 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1342 }
1343 project::Event::SnippetEdit(id, snippet_edits) => {
1344 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1345 let focus_handle = editor.focus_handle(cx);
1346 if focus_handle.is_focused(window) {
1347 let snapshot = buffer.read(cx).snapshot();
1348 for (range, snippet) in snippet_edits {
1349 let editor_range =
1350 language::range_from_lsp(*range).to_offset(&snapshot);
1351 editor
1352 .insert_snippet(
1353 &[editor_range],
1354 snippet.clone(),
1355 window,
1356 cx,
1357 )
1358 .ok();
1359 }
1360 }
1361 }
1362 }
1363 _ => {}
1364 },
1365 ));
1366 if let Some(task_inventory) = project
1367 .read(cx)
1368 .task_store()
1369 .read(cx)
1370 .task_inventory()
1371 .cloned()
1372 {
1373 project_subscriptions.push(cx.observe_in(
1374 &task_inventory,
1375 window,
1376 |editor, _, window, cx| {
1377 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1378 },
1379 ));
1380 };
1381
1382 project_subscriptions.push(cx.subscribe_in(
1383 &project.read(cx).breakpoint_store(),
1384 window,
1385 |editor, _, event, window, cx| match event {
1386 BreakpointStoreEvent::ActiveDebugLineChanged => {
1387 if editor.go_to_active_debug_line(window, cx) {
1388 cx.stop_propagation();
1389 }
1390 }
1391 _ => {}
1392 },
1393 ));
1394 }
1395 }
1396
1397 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1398
1399 let inlay_hint_settings =
1400 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1401 let focus_handle = cx.focus_handle();
1402 cx.on_focus(&focus_handle, window, Self::handle_focus)
1403 .detach();
1404 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1405 .detach();
1406 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1407 .detach();
1408 cx.on_blur(&focus_handle, window, Self::handle_blur)
1409 .detach();
1410
1411 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1412 Some(false)
1413 } else {
1414 None
1415 };
1416
1417 let breakpoint_store = match (mode, project.as_ref()) {
1418 (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
1419 _ => None,
1420 };
1421
1422 let mut code_action_providers = Vec::new();
1423 let mut load_uncommitted_diff = None;
1424 if let Some(project) = project.clone() {
1425 load_uncommitted_diff = Some(
1426 get_uncommitted_diff_for_buffer(
1427 &project,
1428 buffer.read(cx).all_buffers(),
1429 buffer.clone(),
1430 cx,
1431 )
1432 .shared(),
1433 );
1434 code_action_providers.push(Rc::new(project) as Rc<_>);
1435 }
1436
1437 let mut this = Self {
1438 focus_handle,
1439 show_cursor_when_unfocused: false,
1440 last_focused_descendant: None,
1441 buffer: buffer.clone(),
1442 display_map: display_map.clone(),
1443 selections,
1444 scroll_manager: ScrollManager::new(cx),
1445 columnar_selection_tail: None,
1446 add_selections_state: None,
1447 select_next_state: None,
1448 select_prev_state: None,
1449 selection_history: Default::default(),
1450 autoclose_regions: Default::default(),
1451 snippet_stack: Default::default(),
1452 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1453 ime_transaction: Default::default(),
1454 active_diagnostics: None,
1455 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1456 inline_diagnostics_update: Task::ready(()),
1457 inline_diagnostics: Vec::new(),
1458 soft_wrap_mode_override,
1459 hard_wrap: None,
1460 completion_provider: project.clone().map(|project| Box::new(project) as _),
1461 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1462 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1463 project,
1464 blink_manager: blink_manager.clone(),
1465 show_local_selections: true,
1466 show_scrollbars: true,
1467 mode,
1468 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1469 show_gutter: mode == EditorMode::Full,
1470 show_line_numbers: None,
1471 use_relative_line_numbers: None,
1472 show_git_diff_gutter: None,
1473 show_code_actions: None,
1474 show_runnables: None,
1475 show_breakpoints: None,
1476 show_wrap_guides: None,
1477 show_indent_guides,
1478 placeholder_text: None,
1479 highlight_order: 0,
1480 highlighted_rows: HashMap::default(),
1481 background_highlights: Default::default(),
1482 gutter_highlights: TreeMap::default(),
1483 scrollbar_marker_state: ScrollbarMarkerState::default(),
1484 active_indent_guides_state: ActiveIndentGuidesState::default(),
1485 nav_history: None,
1486 context_menu: RefCell::new(None),
1487 context_menu_options: None,
1488 mouse_context_menu: None,
1489 completion_tasks: Default::default(),
1490 signature_help_state: SignatureHelpState::default(),
1491 auto_signature_help: None,
1492 find_all_references_task_sources: Vec::new(),
1493 next_completion_id: 0,
1494 next_inlay_id: 0,
1495 code_action_providers,
1496 available_code_actions: Default::default(),
1497 code_actions_task: Default::default(),
1498 selection_highlight_task: Default::default(),
1499 document_highlights_task: Default::default(),
1500 linked_editing_range_task: Default::default(),
1501 pending_rename: Default::default(),
1502 searchable: true,
1503 cursor_shape: EditorSettings::get_global(cx)
1504 .cursor_shape
1505 .unwrap_or_default(),
1506 current_line_highlight: None,
1507 autoindent_mode: Some(AutoindentMode::EachLine),
1508 collapse_matches: false,
1509 workspace: None,
1510 input_enabled: true,
1511 use_modal_editing: mode == EditorMode::Full,
1512 read_only: false,
1513 use_autoclose: true,
1514 use_auto_surround: true,
1515 auto_replace_emoji_shortcode: false,
1516 jsx_tag_auto_close_enabled_in_any_buffer: false,
1517 leader_peer_id: None,
1518 remote_id: None,
1519 hover_state: Default::default(),
1520 pending_mouse_down: None,
1521 hovered_link_state: Default::default(),
1522 edit_prediction_provider: None,
1523 active_inline_completion: None,
1524 stale_inline_completion_in_menu: None,
1525 edit_prediction_preview: EditPredictionPreview::Inactive {
1526 released_too_fast: false,
1527 },
1528 inline_diagnostics_enabled: mode == EditorMode::Full,
1529 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1530
1531 gutter_hovered: false,
1532 pixel_position_of_newest_cursor: None,
1533 last_bounds: None,
1534 last_position_map: None,
1535 expect_bounds_change: None,
1536 gutter_dimensions: GutterDimensions::default(),
1537 style: None,
1538 show_cursor_names: false,
1539 hovered_cursors: Default::default(),
1540 next_editor_action_id: EditorActionId::default(),
1541 editor_actions: Rc::default(),
1542 inline_completions_hidden_for_vim_mode: false,
1543 show_inline_completions_override: None,
1544 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1545 edit_prediction_settings: EditPredictionSettings::Disabled,
1546 edit_prediction_indent_conflict: false,
1547 edit_prediction_requires_modifier_in_indent_conflict: true,
1548 custom_context_menu: None,
1549 show_git_blame_gutter: false,
1550 show_git_blame_inline: false,
1551 show_selection_menu: None,
1552 show_git_blame_inline_delay_task: None,
1553 git_blame_inline_tooltip: None,
1554 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1555 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1556 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1557 .session
1558 .restore_unsaved_buffers,
1559 blame: None,
1560 blame_subscription: None,
1561 tasks: Default::default(),
1562
1563 breakpoint_store,
1564 gutter_breakpoint_indicator: (None, None),
1565 _subscriptions: vec![
1566 cx.observe(&buffer, Self::on_buffer_changed),
1567 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1568 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1569 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1570 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1571 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1572 cx.observe_window_activation(window, |editor, window, cx| {
1573 let active = window.is_window_active();
1574 editor.blink_manager.update(cx, |blink_manager, cx| {
1575 if active {
1576 blink_manager.enable(cx);
1577 } else {
1578 blink_manager.disable(cx);
1579 }
1580 });
1581 }),
1582 ],
1583 tasks_update_task: None,
1584 linked_edit_ranges: Default::default(),
1585 in_project_search: false,
1586 previous_search_ranges: None,
1587 breadcrumb_header: None,
1588 focused_block: None,
1589 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1590 addons: HashMap::default(),
1591 registered_buffers: HashMap::default(),
1592 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1593 selection_mark_mode: false,
1594 toggle_fold_multiple_buffers: Task::ready(()),
1595 serialize_selections: Task::ready(()),
1596 serialize_folds: Task::ready(()),
1597 text_style_refinement: None,
1598 load_diff_task: load_uncommitted_diff,
1599 mouse_cursor_hidden: false,
1600 hide_mouse_mode: EditorSettings::get_global(cx)
1601 .hide_mouse
1602 .unwrap_or_default(),
1603 };
1604 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1605 this._subscriptions
1606 .push(cx.observe(breakpoints, |_, _, cx| {
1607 cx.notify();
1608 }));
1609 }
1610 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1611 this._subscriptions.extend(project_subscriptions);
1612
1613 this._subscriptions.push(cx.subscribe_in(
1614 &cx.entity(),
1615 window,
1616 |editor, _, e: &EditorEvent, window, cx| {
1617 if let EditorEvent::SelectionsChanged { local } = e {
1618 if *local {
1619 let new_anchor = editor.scroll_manager.anchor();
1620 let snapshot = editor.snapshot(window, cx);
1621 editor.update_restoration_data(cx, move |data| {
1622 data.scroll_position = (
1623 new_anchor.top_row(&snapshot.buffer_snapshot),
1624 new_anchor.offset,
1625 );
1626 });
1627 }
1628 }
1629 },
1630 ));
1631
1632 this.end_selection(window, cx);
1633 this.scroll_manager.show_scrollbars(window, cx);
1634 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1635
1636 if mode == EditorMode::Full {
1637 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1638 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1639
1640 if this.git_blame_inline_enabled {
1641 this.git_blame_inline_enabled = true;
1642 this.start_git_blame_inline(false, window, cx);
1643 }
1644
1645 this.go_to_active_debug_line(window, cx);
1646
1647 if let Some(buffer) = buffer.read(cx).as_singleton() {
1648 if let Some(project) = this.project.as_ref() {
1649 let handle = project.update(cx, |project, cx| {
1650 project.register_buffer_with_language_servers(&buffer, cx)
1651 });
1652 this.registered_buffers
1653 .insert(buffer.read(cx).remote_id(), handle);
1654 }
1655 }
1656 }
1657
1658 this.report_editor_event("Editor Opened", None, cx);
1659 this
1660 }
1661
1662 pub fn deploy_mouse_context_menu(
1663 &mut self,
1664 position: gpui::Point<Pixels>,
1665 context_menu: Entity<ContextMenu>,
1666 window: &mut Window,
1667 cx: &mut Context<Self>,
1668 ) {
1669 self.mouse_context_menu = Some(MouseContextMenu::new(
1670 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1671 context_menu,
1672 window,
1673 cx,
1674 ));
1675 }
1676
1677 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1678 self.mouse_context_menu
1679 .as_ref()
1680 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1681 }
1682
1683 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1684 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1685 }
1686
1687 fn key_context_internal(
1688 &self,
1689 has_active_edit_prediction: bool,
1690 window: &Window,
1691 cx: &App,
1692 ) -> KeyContext {
1693 let mut key_context = KeyContext::new_with_defaults();
1694 key_context.add("Editor");
1695 let mode = match self.mode {
1696 EditorMode::SingleLine { .. } => "single_line",
1697 EditorMode::AutoHeight { .. } => "auto_height",
1698 EditorMode::Full => "full",
1699 };
1700
1701 if EditorSettings::jupyter_enabled(cx) {
1702 key_context.add("jupyter");
1703 }
1704
1705 key_context.set("mode", mode);
1706 if self.pending_rename.is_some() {
1707 key_context.add("renaming");
1708 }
1709
1710 match self.context_menu.borrow().as_ref() {
1711 Some(CodeContextMenu::Completions(_)) => {
1712 key_context.add("menu");
1713 key_context.add("showing_completions");
1714 }
1715 Some(CodeContextMenu::CodeActions(_)) => {
1716 key_context.add("menu");
1717 key_context.add("showing_code_actions")
1718 }
1719 None => {}
1720 }
1721
1722 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1723 if !self.focus_handle(cx).contains_focused(window, cx)
1724 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1725 {
1726 for addon in self.addons.values() {
1727 addon.extend_key_context(&mut key_context, cx)
1728 }
1729 }
1730
1731 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1732 if let Some(extension) = singleton_buffer
1733 .read(cx)
1734 .file()
1735 .and_then(|file| file.path().extension()?.to_str())
1736 {
1737 key_context.set("extension", extension.to_string());
1738 }
1739 } else {
1740 key_context.add("multibuffer");
1741 }
1742
1743 if has_active_edit_prediction {
1744 if self.edit_prediction_in_conflict() {
1745 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1746 } else {
1747 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1748 key_context.add("copilot_suggestion");
1749 }
1750 }
1751
1752 if self.selection_mark_mode {
1753 key_context.add("selection_mode");
1754 }
1755
1756 key_context
1757 }
1758
1759 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1760 self.mouse_cursor_hidden = match origin {
1761 HideMouseCursorOrigin::TypingAction => {
1762 matches!(
1763 self.hide_mouse_mode,
1764 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1765 )
1766 }
1767 HideMouseCursorOrigin::MovementAction => {
1768 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1769 }
1770 };
1771 }
1772
1773 pub fn edit_prediction_in_conflict(&self) -> bool {
1774 if !self.show_edit_predictions_in_menu() {
1775 return false;
1776 }
1777
1778 let showing_completions = self
1779 .context_menu
1780 .borrow()
1781 .as_ref()
1782 .map_or(false, |context| {
1783 matches!(context, CodeContextMenu::Completions(_))
1784 });
1785
1786 showing_completions
1787 || self.edit_prediction_requires_modifier()
1788 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1789 // bindings to insert tab characters.
1790 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1791 }
1792
1793 pub fn accept_edit_prediction_keybind(
1794 &self,
1795 window: &Window,
1796 cx: &App,
1797 ) -> AcceptEditPredictionBinding {
1798 let key_context = self.key_context_internal(true, window, cx);
1799 let in_conflict = self.edit_prediction_in_conflict();
1800
1801 AcceptEditPredictionBinding(
1802 window
1803 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1804 .into_iter()
1805 .filter(|binding| {
1806 !in_conflict
1807 || binding
1808 .keystrokes()
1809 .first()
1810 .map_or(false, |keystroke| keystroke.modifiers.modified())
1811 })
1812 .rev()
1813 .min_by_key(|binding| {
1814 binding
1815 .keystrokes()
1816 .first()
1817 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1818 }),
1819 )
1820 }
1821
1822 pub fn new_file(
1823 workspace: &mut Workspace,
1824 _: &workspace::NewFile,
1825 window: &mut Window,
1826 cx: &mut Context<Workspace>,
1827 ) {
1828 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1829 "Failed to create buffer",
1830 window,
1831 cx,
1832 |e, _, _| match e.error_code() {
1833 ErrorCode::RemoteUpgradeRequired => Some(format!(
1834 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1835 e.error_tag("required").unwrap_or("the latest version")
1836 )),
1837 _ => None,
1838 },
1839 );
1840 }
1841
1842 pub fn new_in_workspace(
1843 workspace: &mut Workspace,
1844 window: &mut Window,
1845 cx: &mut Context<Workspace>,
1846 ) -> Task<Result<Entity<Editor>>> {
1847 let project = workspace.project().clone();
1848 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1849
1850 cx.spawn_in(window, async move |workspace, cx| {
1851 let buffer = create.await?;
1852 workspace.update_in(cx, |workspace, window, cx| {
1853 let editor =
1854 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1855 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1856 editor
1857 })
1858 })
1859 }
1860
1861 fn new_file_vertical(
1862 workspace: &mut Workspace,
1863 _: &workspace::NewFileSplitVertical,
1864 window: &mut Window,
1865 cx: &mut Context<Workspace>,
1866 ) {
1867 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1868 }
1869
1870 fn new_file_horizontal(
1871 workspace: &mut Workspace,
1872 _: &workspace::NewFileSplitHorizontal,
1873 window: &mut Window,
1874 cx: &mut Context<Workspace>,
1875 ) {
1876 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1877 }
1878
1879 fn new_file_in_direction(
1880 workspace: &mut Workspace,
1881 direction: SplitDirection,
1882 window: &mut Window,
1883 cx: &mut Context<Workspace>,
1884 ) {
1885 let project = workspace.project().clone();
1886 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1887
1888 cx.spawn_in(window, async move |workspace, cx| {
1889 let buffer = create.await?;
1890 workspace.update_in(cx, move |workspace, window, cx| {
1891 workspace.split_item(
1892 direction,
1893 Box::new(
1894 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1895 ),
1896 window,
1897 cx,
1898 )
1899 })?;
1900 anyhow::Ok(())
1901 })
1902 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1903 match e.error_code() {
1904 ErrorCode::RemoteUpgradeRequired => Some(format!(
1905 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1906 e.error_tag("required").unwrap_or("the latest version")
1907 )),
1908 _ => None,
1909 }
1910 });
1911 }
1912
1913 pub fn leader_peer_id(&self) -> Option<PeerId> {
1914 self.leader_peer_id
1915 }
1916
1917 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1918 &self.buffer
1919 }
1920
1921 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1922 self.workspace.as_ref()?.0.upgrade()
1923 }
1924
1925 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1926 self.buffer().read(cx).title(cx)
1927 }
1928
1929 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1930 let git_blame_gutter_max_author_length = self
1931 .render_git_blame_gutter(cx)
1932 .then(|| {
1933 if let Some(blame) = self.blame.as_ref() {
1934 let max_author_length =
1935 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1936 Some(max_author_length)
1937 } else {
1938 None
1939 }
1940 })
1941 .flatten();
1942
1943 EditorSnapshot {
1944 mode: self.mode,
1945 show_gutter: self.show_gutter,
1946 show_line_numbers: self.show_line_numbers,
1947 show_git_diff_gutter: self.show_git_diff_gutter,
1948 show_code_actions: self.show_code_actions,
1949 show_runnables: self.show_runnables,
1950 show_breakpoints: self.show_breakpoints,
1951 git_blame_gutter_max_author_length,
1952 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1953 scroll_anchor: self.scroll_manager.anchor(),
1954 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1955 placeholder_text: self.placeholder_text.clone(),
1956 is_focused: self.focus_handle.is_focused(window),
1957 current_line_highlight: self
1958 .current_line_highlight
1959 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1960 gutter_hovered: self.gutter_hovered,
1961 }
1962 }
1963
1964 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1965 self.buffer.read(cx).language_at(point, cx)
1966 }
1967
1968 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1969 self.buffer.read(cx).read(cx).file_at(point).cloned()
1970 }
1971
1972 pub fn active_excerpt(
1973 &self,
1974 cx: &App,
1975 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1976 self.buffer
1977 .read(cx)
1978 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1979 }
1980
1981 pub fn mode(&self) -> EditorMode {
1982 self.mode
1983 }
1984
1985 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1986 self.collaboration_hub.as_deref()
1987 }
1988
1989 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1990 self.collaboration_hub = Some(hub);
1991 }
1992
1993 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1994 self.in_project_search = in_project_search;
1995 }
1996
1997 pub fn set_custom_context_menu(
1998 &mut self,
1999 f: impl 'static
2000 + Fn(
2001 &mut Self,
2002 DisplayPoint,
2003 &mut Window,
2004 &mut Context<Self>,
2005 ) -> Option<Entity<ui::ContextMenu>>,
2006 ) {
2007 self.custom_context_menu = Some(Box::new(f))
2008 }
2009
2010 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2011 self.completion_provider = provider;
2012 }
2013
2014 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2015 self.semantics_provider.clone()
2016 }
2017
2018 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2019 self.semantics_provider = provider;
2020 }
2021
2022 pub fn set_edit_prediction_provider<T>(
2023 &mut self,
2024 provider: Option<Entity<T>>,
2025 window: &mut Window,
2026 cx: &mut Context<Self>,
2027 ) where
2028 T: EditPredictionProvider,
2029 {
2030 self.edit_prediction_provider =
2031 provider.map(|provider| RegisteredInlineCompletionProvider {
2032 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2033 if this.focus_handle.is_focused(window) {
2034 this.update_visible_inline_completion(window, cx);
2035 }
2036 }),
2037 provider: Arc::new(provider),
2038 });
2039 self.update_edit_prediction_settings(cx);
2040 self.refresh_inline_completion(false, false, window, cx);
2041 }
2042
2043 pub fn placeholder_text(&self) -> Option<&str> {
2044 self.placeholder_text.as_deref()
2045 }
2046
2047 pub fn set_placeholder_text(
2048 &mut self,
2049 placeholder_text: impl Into<Arc<str>>,
2050 cx: &mut Context<Self>,
2051 ) {
2052 let placeholder_text = Some(placeholder_text.into());
2053 if self.placeholder_text != placeholder_text {
2054 self.placeholder_text = placeholder_text;
2055 cx.notify();
2056 }
2057 }
2058
2059 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2060 self.cursor_shape = cursor_shape;
2061
2062 // Disrupt blink for immediate user feedback that the cursor shape has changed
2063 self.blink_manager.update(cx, BlinkManager::show_cursor);
2064
2065 cx.notify();
2066 }
2067
2068 pub fn set_current_line_highlight(
2069 &mut self,
2070 current_line_highlight: Option<CurrentLineHighlight>,
2071 ) {
2072 self.current_line_highlight = current_line_highlight;
2073 }
2074
2075 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2076 self.collapse_matches = collapse_matches;
2077 }
2078
2079 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2080 let buffers = self.buffer.read(cx).all_buffers();
2081 let Some(project) = self.project.as_ref() else {
2082 return;
2083 };
2084 project.update(cx, |project, cx| {
2085 for buffer in buffers {
2086 self.registered_buffers
2087 .entry(buffer.read(cx).remote_id())
2088 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2089 }
2090 })
2091 }
2092
2093 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2094 if self.collapse_matches {
2095 return range.start..range.start;
2096 }
2097 range.clone()
2098 }
2099
2100 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2101 if self.display_map.read(cx).clip_at_line_ends != clip {
2102 self.display_map
2103 .update(cx, |map, _| map.clip_at_line_ends = clip);
2104 }
2105 }
2106
2107 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2108 self.input_enabled = input_enabled;
2109 }
2110
2111 pub fn set_inline_completions_hidden_for_vim_mode(
2112 &mut self,
2113 hidden: bool,
2114 window: &mut Window,
2115 cx: &mut Context<Self>,
2116 ) {
2117 if hidden != self.inline_completions_hidden_for_vim_mode {
2118 self.inline_completions_hidden_for_vim_mode = hidden;
2119 if hidden {
2120 self.update_visible_inline_completion(window, cx);
2121 } else {
2122 self.refresh_inline_completion(true, false, window, cx);
2123 }
2124 }
2125 }
2126
2127 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2128 self.menu_inline_completions_policy = value;
2129 }
2130
2131 pub fn set_autoindent(&mut self, autoindent: bool) {
2132 if autoindent {
2133 self.autoindent_mode = Some(AutoindentMode::EachLine);
2134 } else {
2135 self.autoindent_mode = None;
2136 }
2137 }
2138
2139 pub fn read_only(&self, cx: &App) -> bool {
2140 self.read_only || self.buffer.read(cx).read_only()
2141 }
2142
2143 pub fn set_read_only(&mut self, read_only: bool) {
2144 self.read_only = read_only;
2145 }
2146
2147 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2148 self.use_autoclose = autoclose;
2149 }
2150
2151 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2152 self.use_auto_surround = auto_surround;
2153 }
2154
2155 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2156 self.auto_replace_emoji_shortcode = auto_replace;
2157 }
2158
2159 pub fn toggle_edit_predictions(
2160 &mut self,
2161 _: &ToggleEditPrediction,
2162 window: &mut Window,
2163 cx: &mut Context<Self>,
2164 ) {
2165 if self.show_inline_completions_override.is_some() {
2166 self.set_show_edit_predictions(None, window, cx);
2167 } else {
2168 let show_edit_predictions = !self.edit_predictions_enabled();
2169 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2170 }
2171 }
2172
2173 pub fn set_show_edit_predictions(
2174 &mut self,
2175 show_edit_predictions: Option<bool>,
2176 window: &mut Window,
2177 cx: &mut Context<Self>,
2178 ) {
2179 self.show_inline_completions_override = show_edit_predictions;
2180 self.update_edit_prediction_settings(cx);
2181
2182 if let Some(false) = show_edit_predictions {
2183 self.discard_inline_completion(false, cx);
2184 } else {
2185 self.refresh_inline_completion(false, true, window, cx);
2186 }
2187 }
2188
2189 fn inline_completions_disabled_in_scope(
2190 &self,
2191 buffer: &Entity<Buffer>,
2192 buffer_position: language::Anchor,
2193 cx: &App,
2194 ) -> bool {
2195 let snapshot = buffer.read(cx).snapshot();
2196 let settings = snapshot.settings_at(buffer_position, cx);
2197
2198 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2199 return false;
2200 };
2201
2202 scope.override_name().map_or(false, |scope_name| {
2203 settings
2204 .edit_predictions_disabled_in
2205 .iter()
2206 .any(|s| s == scope_name)
2207 })
2208 }
2209
2210 pub fn set_use_modal_editing(&mut self, to: bool) {
2211 self.use_modal_editing = to;
2212 }
2213
2214 pub fn use_modal_editing(&self) -> bool {
2215 self.use_modal_editing
2216 }
2217
2218 fn selections_did_change(
2219 &mut self,
2220 local: bool,
2221 old_cursor_position: &Anchor,
2222 show_completions: bool,
2223 window: &mut Window,
2224 cx: &mut Context<Self>,
2225 ) {
2226 window.invalidate_character_coordinates();
2227
2228 // Copy selections to primary selection buffer
2229 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2230 if local {
2231 let selections = self.selections.all::<usize>(cx);
2232 let buffer_handle = self.buffer.read(cx).read(cx);
2233
2234 let mut text = String::new();
2235 for (index, selection) in selections.iter().enumerate() {
2236 let text_for_selection = buffer_handle
2237 .text_for_range(selection.start..selection.end)
2238 .collect::<String>();
2239
2240 text.push_str(&text_for_selection);
2241 if index != selections.len() - 1 {
2242 text.push('\n');
2243 }
2244 }
2245
2246 if !text.is_empty() {
2247 cx.write_to_primary(ClipboardItem::new_string(text));
2248 }
2249 }
2250
2251 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2252 self.buffer.update(cx, |buffer, cx| {
2253 buffer.set_active_selections(
2254 &self.selections.disjoint_anchors(),
2255 self.selections.line_mode,
2256 self.cursor_shape,
2257 cx,
2258 )
2259 });
2260 }
2261 let display_map = self
2262 .display_map
2263 .update(cx, |display_map, cx| display_map.snapshot(cx));
2264 let buffer = &display_map.buffer_snapshot;
2265 self.add_selections_state = None;
2266 self.select_next_state = None;
2267 self.select_prev_state = None;
2268 self.select_syntax_node_history.try_clear();
2269 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2270 self.snippet_stack
2271 .invalidate(&self.selections.disjoint_anchors(), buffer);
2272 self.take_rename(false, window, cx);
2273
2274 let new_cursor_position = self.selections.newest_anchor().head();
2275
2276 self.push_to_nav_history(
2277 *old_cursor_position,
2278 Some(new_cursor_position.to_point(buffer)),
2279 false,
2280 cx,
2281 );
2282
2283 if local {
2284 let new_cursor_position = self.selections.newest_anchor().head();
2285 let mut context_menu = self.context_menu.borrow_mut();
2286 let completion_menu = match context_menu.as_ref() {
2287 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2288 _ => {
2289 *context_menu = None;
2290 None
2291 }
2292 };
2293 if let Some(buffer_id) = new_cursor_position.buffer_id {
2294 if !self.registered_buffers.contains_key(&buffer_id) {
2295 if let Some(project) = self.project.as_ref() {
2296 project.update(cx, |project, cx| {
2297 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2298 return;
2299 };
2300 self.registered_buffers.insert(
2301 buffer_id,
2302 project.register_buffer_with_language_servers(&buffer, cx),
2303 );
2304 })
2305 }
2306 }
2307 }
2308
2309 if let Some(completion_menu) = completion_menu {
2310 let cursor_position = new_cursor_position.to_offset(buffer);
2311 let (word_range, kind) =
2312 buffer.surrounding_word(completion_menu.initial_position, true);
2313 if kind == Some(CharKind::Word)
2314 && word_range.to_inclusive().contains(&cursor_position)
2315 {
2316 let mut completion_menu = completion_menu.clone();
2317 drop(context_menu);
2318
2319 let query = Self::completion_query(buffer, cursor_position);
2320 cx.spawn(async move |this, cx| {
2321 completion_menu
2322 .filter(query.as_deref(), cx.background_executor().clone())
2323 .await;
2324
2325 this.update(cx, |this, cx| {
2326 let mut context_menu = this.context_menu.borrow_mut();
2327 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2328 else {
2329 return;
2330 };
2331
2332 if menu.id > completion_menu.id {
2333 return;
2334 }
2335
2336 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2337 drop(context_menu);
2338 cx.notify();
2339 })
2340 })
2341 .detach();
2342
2343 if show_completions {
2344 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2345 }
2346 } else {
2347 drop(context_menu);
2348 self.hide_context_menu(window, cx);
2349 }
2350 } else {
2351 drop(context_menu);
2352 }
2353
2354 hide_hover(self, cx);
2355
2356 if old_cursor_position.to_display_point(&display_map).row()
2357 != new_cursor_position.to_display_point(&display_map).row()
2358 {
2359 self.available_code_actions.take();
2360 }
2361 self.refresh_code_actions(window, cx);
2362 self.refresh_document_highlights(cx);
2363 self.refresh_selected_text_highlights(window, cx);
2364 refresh_matching_bracket_highlights(self, window, cx);
2365 self.update_visible_inline_completion(window, cx);
2366 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2367 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2368 if self.git_blame_inline_enabled {
2369 self.start_inline_blame_timer(window, cx);
2370 }
2371 }
2372
2373 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2374 cx.emit(EditorEvent::SelectionsChanged { local });
2375
2376 let selections = &self.selections.disjoint;
2377 if selections.len() == 1 {
2378 cx.emit(SearchEvent::ActiveMatchChanged)
2379 }
2380 if local {
2381 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2382 let inmemory_selections = selections
2383 .iter()
2384 .map(|s| {
2385 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2386 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2387 })
2388 .collect();
2389 self.update_restoration_data(cx, |data| {
2390 data.selections = inmemory_selections;
2391 });
2392
2393 if WorkspaceSettings::get(None, cx).restore_on_startup
2394 != RestoreOnStartupBehavior::None
2395 {
2396 if let Some(workspace_id) =
2397 self.workspace.as_ref().and_then(|workspace| workspace.1)
2398 {
2399 let snapshot = self.buffer().read(cx).snapshot(cx);
2400 let selections = selections.clone();
2401 let background_executor = cx.background_executor().clone();
2402 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2403 self.serialize_selections = cx.background_spawn(async move {
2404 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2405 let db_selections = selections
2406 .iter()
2407 .map(|selection| {
2408 (
2409 selection.start.to_offset(&snapshot),
2410 selection.end.to_offset(&snapshot),
2411 )
2412 })
2413 .collect();
2414
2415 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2416 .await
2417 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2418 .log_err();
2419 });
2420 }
2421 }
2422 }
2423 }
2424
2425 cx.notify();
2426 }
2427
2428 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2429 use text::ToOffset as _;
2430 use text::ToPoint as _;
2431
2432 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2433 return;
2434 }
2435
2436 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2437 return;
2438 };
2439
2440 let snapshot = singleton.read(cx).snapshot();
2441 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2442 let display_snapshot = display_map.snapshot(cx);
2443
2444 display_snapshot
2445 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2446 .map(|fold| {
2447 fold.range.start.text_anchor.to_point(&snapshot)
2448 ..fold.range.end.text_anchor.to_point(&snapshot)
2449 })
2450 .collect()
2451 });
2452 self.update_restoration_data(cx, |data| {
2453 data.folds = inmemory_folds;
2454 });
2455
2456 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2457 return;
2458 };
2459 let background_executor = cx.background_executor().clone();
2460 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2461 let db_folds = self.display_map.update(cx, |display_map, cx| {
2462 display_map
2463 .snapshot(cx)
2464 .folds_in_range(0..snapshot.len())
2465 .map(|fold| {
2466 (
2467 fold.range.start.text_anchor.to_offset(&snapshot),
2468 fold.range.end.text_anchor.to_offset(&snapshot),
2469 )
2470 })
2471 .collect()
2472 });
2473 self.serialize_folds = cx.background_spawn(async move {
2474 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2475 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2476 .await
2477 .with_context(|| {
2478 format!(
2479 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2480 )
2481 })
2482 .log_err();
2483 });
2484 }
2485
2486 pub fn sync_selections(
2487 &mut self,
2488 other: Entity<Editor>,
2489 cx: &mut Context<Self>,
2490 ) -> gpui::Subscription {
2491 let other_selections = other.read(cx).selections.disjoint.to_vec();
2492 self.selections.change_with(cx, |selections| {
2493 selections.select_anchors(other_selections);
2494 });
2495
2496 let other_subscription =
2497 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2498 EditorEvent::SelectionsChanged { local: true } => {
2499 let other_selections = other.read(cx).selections.disjoint.to_vec();
2500 if other_selections.is_empty() {
2501 return;
2502 }
2503 this.selections.change_with(cx, |selections| {
2504 selections.select_anchors(other_selections);
2505 });
2506 }
2507 _ => {}
2508 });
2509
2510 let this_subscription =
2511 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2512 EditorEvent::SelectionsChanged { local: true } => {
2513 let these_selections = this.selections.disjoint.to_vec();
2514 if these_selections.is_empty() {
2515 return;
2516 }
2517 other.update(cx, |other_editor, cx| {
2518 other_editor.selections.change_with(cx, |selections| {
2519 selections.select_anchors(these_selections);
2520 })
2521 });
2522 }
2523 _ => {}
2524 });
2525
2526 Subscription::join(other_subscription, this_subscription)
2527 }
2528
2529 pub fn change_selections<R>(
2530 &mut self,
2531 autoscroll: Option<Autoscroll>,
2532 window: &mut Window,
2533 cx: &mut Context<Self>,
2534 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2535 ) -> R {
2536 self.change_selections_inner(autoscroll, true, window, cx, change)
2537 }
2538
2539 fn change_selections_inner<R>(
2540 &mut self,
2541 autoscroll: Option<Autoscroll>,
2542 request_completions: bool,
2543 window: &mut Window,
2544 cx: &mut Context<Self>,
2545 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2546 ) -> R {
2547 let old_cursor_position = self.selections.newest_anchor().head();
2548 self.push_to_selection_history();
2549
2550 let (changed, result) = self.selections.change_with(cx, change);
2551
2552 if changed {
2553 if let Some(autoscroll) = autoscroll {
2554 self.request_autoscroll(autoscroll, cx);
2555 }
2556 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2557
2558 if self.should_open_signature_help_automatically(
2559 &old_cursor_position,
2560 self.signature_help_state.backspace_pressed(),
2561 cx,
2562 ) {
2563 self.show_signature_help(&ShowSignatureHelp, window, cx);
2564 }
2565 self.signature_help_state.set_backspace_pressed(false);
2566 }
2567
2568 result
2569 }
2570
2571 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2572 where
2573 I: IntoIterator<Item = (Range<S>, T)>,
2574 S: ToOffset,
2575 T: Into<Arc<str>>,
2576 {
2577 if self.read_only(cx) {
2578 return;
2579 }
2580
2581 self.buffer
2582 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2583 }
2584
2585 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2586 where
2587 I: IntoIterator<Item = (Range<S>, T)>,
2588 S: ToOffset,
2589 T: Into<Arc<str>>,
2590 {
2591 if self.read_only(cx) {
2592 return;
2593 }
2594
2595 self.buffer.update(cx, |buffer, cx| {
2596 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2597 });
2598 }
2599
2600 pub fn edit_with_block_indent<I, S, T>(
2601 &mut self,
2602 edits: I,
2603 original_indent_columns: Vec<Option<u32>>,
2604 cx: &mut Context<Self>,
2605 ) where
2606 I: IntoIterator<Item = (Range<S>, T)>,
2607 S: ToOffset,
2608 T: Into<Arc<str>>,
2609 {
2610 if self.read_only(cx) {
2611 return;
2612 }
2613
2614 self.buffer.update(cx, |buffer, cx| {
2615 buffer.edit(
2616 edits,
2617 Some(AutoindentMode::Block {
2618 original_indent_columns,
2619 }),
2620 cx,
2621 )
2622 });
2623 }
2624
2625 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2626 self.hide_context_menu(window, cx);
2627
2628 match phase {
2629 SelectPhase::Begin {
2630 position,
2631 add,
2632 click_count,
2633 } => self.begin_selection(position, add, click_count, window, cx),
2634 SelectPhase::BeginColumnar {
2635 position,
2636 goal_column,
2637 reset,
2638 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2639 SelectPhase::Extend {
2640 position,
2641 click_count,
2642 } => self.extend_selection(position, click_count, window, cx),
2643 SelectPhase::Update {
2644 position,
2645 goal_column,
2646 scroll_delta,
2647 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2648 SelectPhase::End => self.end_selection(window, cx),
2649 }
2650 }
2651
2652 fn extend_selection(
2653 &mut self,
2654 position: DisplayPoint,
2655 click_count: usize,
2656 window: &mut Window,
2657 cx: &mut Context<Self>,
2658 ) {
2659 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2660 let tail = self.selections.newest::<usize>(cx).tail();
2661 self.begin_selection(position, false, click_count, window, cx);
2662
2663 let position = position.to_offset(&display_map, Bias::Left);
2664 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2665
2666 let mut pending_selection = self
2667 .selections
2668 .pending_anchor()
2669 .expect("extend_selection not called with pending selection");
2670 if position >= tail {
2671 pending_selection.start = tail_anchor;
2672 } else {
2673 pending_selection.end = tail_anchor;
2674 pending_selection.reversed = true;
2675 }
2676
2677 let mut pending_mode = self.selections.pending_mode().unwrap();
2678 match &mut pending_mode {
2679 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2680 _ => {}
2681 }
2682
2683 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2684 s.set_pending(pending_selection, pending_mode)
2685 });
2686 }
2687
2688 fn begin_selection(
2689 &mut self,
2690 position: DisplayPoint,
2691 add: bool,
2692 click_count: usize,
2693 window: &mut Window,
2694 cx: &mut Context<Self>,
2695 ) {
2696 if !self.focus_handle.is_focused(window) {
2697 self.last_focused_descendant = None;
2698 window.focus(&self.focus_handle);
2699 }
2700
2701 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2702 let buffer = &display_map.buffer_snapshot;
2703 let newest_selection = self.selections.newest_anchor().clone();
2704 let position = display_map.clip_point(position, Bias::Left);
2705
2706 let start;
2707 let end;
2708 let mode;
2709 let mut auto_scroll;
2710 match click_count {
2711 1 => {
2712 start = buffer.anchor_before(position.to_point(&display_map));
2713 end = start;
2714 mode = SelectMode::Character;
2715 auto_scroll = true;
2716 }
2717 2 => {
2718 let range = movement::surrounding_word(&display_map, position);
2719 start = buffer.anchor_before(range.start.to_point(&display_map));
2720 end = buffer.anchor_before(range.end.to_point(&display_map));
2721 mode = SelectMode::Word(start..end);
2722 auto_scroll = true;
2723 }
2724 3 => {
2725 let position = display_map
2726 .clip_point(position, Bias::Left)
2727 .to_point(&display_map);
2728 let line_start = display_map.prev_line_boundary(position).0;
2729 let next_line_start = buffer.clip_point(
2730 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2731 Bias::Left,
2732 );
2733 start = buffer.anchor_before(line_start);
2734 end = buffer.anchor_before(next_line_start);
2735 mode = SelectMode::Line(start..end);
2736 auto_scroll = true;
2737 }
2738 _ => {
2739 start = buffer.anchor_before(0);
2740 end = buffer.anchor_before(buffer.len());
2741 mode = SelectMode::All;
2742 auto_scroll = false;
2743 }
2744 }
2745 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2746
2747 let point_to_delete: Option<usize> = {
2748 let selected_points: Vec<Selection<Point>> =
2749 self.selections.disjoint_in_range(start..end, cx);
2750
2751 if !add || click_count > 1 {
2752 None
2753 } else if !selected_points.is_empty() {
2754 Some(selected_points[0].id)
2755 } else {
2756 let clicked_point_already_selected =
2757 self.selections.disjoint.iter().find(|selection| {
2758 selection.start.to_point(buffer) == start.to_point(buffer)
2759 || selection.end.to_point(buffer) == end.to_point(buffer)
2760 });
2761
2762 clicked_point_already_selected.map(|selection| selection.id)
2763 }
2764 };
2765
2766 let selections_count = self.selections.count();
2767
2768 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2769 if let Some(point_to_delete) = point_to_delete {
2770 s.delete(point_to_delete);
2771
2772 if selections_count == 1 {
2773 s.set_pending_anchor_range(start..end, mode);
2774 }
2775 } else {
2776 if !add {
2777 s.clear_disjoint();
2778 } else if click_count > 1 {
2779 s.delete(newest_selection.id)
2780 }
2781
2782 s.set_pending_anchor_range(start..end, mode);
2783 }
2784 });
2785 }
2786
2787 fn begin_columnar_selection(
2788 &mut self,
2789 position: DisplayPoint,
2790 goal_column: u32,
2791 reset: bool,
2792 window: &mut Window,
2793 cx: &mut Context<Self>,
2794 ) {
2795 if !self.focus_handle.is_focused(window) {
2796 self.last_focused_descendant = None;
2797 window.focus(&self.focus_handle);
2798 }
2799
2800 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2801
2802 if reset {
2803 let pointer_position = display_map
2804 .buffer_snapshot
2805 .anchor_before(position.to_point(&display_map));
2806
2807 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2808 s.clear_disjoint();
2809 s.set_pending_anchor_range(
2810 pointer_position..pointer_position,
2811 SelectMode::Character,
2812 );
2813 });
2814 }
2815
2816 let tail = self.selections.newest::<Point>(cx).tail();
2817 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2818
2819 if !reset {
2820 self.select_columns(
2821 tail.to_display_point(&display_map),
2822 position,
2823 goal_column,
2824 &display_map,
2825 window,
2826 cx,
2827 );
2828 }
2829 }
2830
2831 fn update_selection(
2832 &mut self,
2833 position: DisplayPoint,
2834 goal_column: u32,
2835 scroll_delta: gpui::Point<f32>,
2836 window: &mut Window,
2837 cx: &mut Context<Self>,
2838 ) {
2839 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2840
2841 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2842 let tail = tail.to_display_point(&display_map);
2843 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2844 } else if let Some(mut pending) = self.selections.pending_anchor() {
2845 let buffer = self.buffer.read(cx).snapshot(cx);
2846 let head;
2847 let tail;
2848 let mode = self.selections.pending_mode().unwrap();
2849 match &mode {
2850 SelectMode::Character => {
2851 head = position.to_point(&display_map);
2852 tail = pending.tail().to_point(&buffer);
2853 }
2854 SelectMode::Word(original_range) => {
2855 let original_display_range = original_range.start.to_display_point(&display_map)
2856 ..original_range.end.to_display_point(&display_map);
2857 let original_buffer_range = original_display_range.start.to_point(&display_map)
2858 ..original_display_range.end.to_point(&display_map);
2859 if movement::is_inside_word(&display_map, position)
2860 || original_display_range.contains(&position)
2861 {
2862 let word_range = movement::surrounding_word(&display_map, position);
2863 if word_range.start < original_display_range.start {
2864 head = word_range.start.to_point(&display_map);
2865 } else {
2866 head = word_range.end.to_point(&display_map);
2867 }
2868 } else {
2869 head = position.to_point(&display_map);
2870 }
2871
2872 if head <= original_buffer_range.start {
2873 tail = original_buffer_range.end;
2874 } else {
2875 tail = original_buffer_range.start;
2876 }
2877 }
2878 SelectMode::Line(original_range) => {
2879 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2880
2881 let position = display_map
2882 .clip_point(position, Bias::Left)
2883 .to_point(&display_map);
2884 let line_start = display_map.prev_line_boundary(position).0;
2885 let next_line_start = buffer.clip_point(
2886 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2887 Bias::Left,
2888 );
2889
2890 if line_start < original_range.start {
2891 head = line_start
2892 } else {
2893 head = next_line_start
2894 }
2895
2896 if head <= original_range.start {
2897 tail = original_range.end;
2898 } else {
2899 tail = original_range.start;
2900 }
2901 }
2902 SelectMode::All => {
2903 return;
2904 }
2905 };
2906
2907 if head < tail {
2908 pending.start = buffer.anchor_before(head);
2909 pending.end = buffer.anchor_before(tail);
2910 pending.reversed = true;
2911 } else {
2912 pending.start = buffer.anchor_before(tail);
2913 pending.end = buffer.anchor_before(head);
2914 pending.reversed = false;
2915 }
2916
2917 self.change_selections(None, window, cx, |s| {
2918 s.set_pending(pending, mode);
2919 });
2920 } else {
2921 log::error!("update_selection dispatched with no pending selection");
2922 return;
2923 }
2924
2925 self.apply_scroll_delta(scroll_delta, window, cx);
2926 cx.notify();
2927 }
2928
2929 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2930 self.columnar_selection_tail.take();
2931 if self.selections.pending_anchor().is_some() {
2932 let selections = self.selections.all::<usize>(cx);
2933 self.change_selections(None, window, cx, |s| {
2934 s.select(selections);
2935 s.clear_pending();
2936 });
2937 }
2938 }
2939
2940 fn select_columns(
2941 &mut self,
2942 tail: DisplayPoint,
2943 head: DisplayPoint,
2944 goal_column: u32,
2945 display_map: &DisplaySnapshot,
2946 window: &mut Window,
2947 cx: &mut Context<Self>,
2948 ) {
2949 let start_row = cmp::min(tail.row(), head.row());
2950 let end_row = cmp::max(tail.row(), head.row());
2951 let start_column = cmp::min(tail.column(), goal_column);
2952 let end_column = cmp::max(tail.column(), goal_column);
2953 let reversed = start_column < tail.column();
2954
2955 let selection_ranges = (start_row.0..=end_row.0)
2956 .map(DisplayRow)
2957 .filter_map(|row| {
2958 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2959 let start = display_map
2960 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2961 .to_point(display_map);
2962 let end = display_map
2963 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2964 .to_point(display_map);
2965 if reversed {
2966 Some(end..start)
2967 } else {
2968 Some(start..end)
2969 }
2970 } else {
2971 None
2972 }
2973 })
2974 .collect::<Vec<_>>();
2975
2976 self.change_selections(None, window, cx, |s| {
2977 s.select_ranges(selection_ranges);
2978 });
2979 cx.notify();
2980 }
2981
2982 pub fn has_pending_nonempty_selection(&self) -> bool {
2983 let pending_nonempty_selection = match self.selections.pending_anchor() {
2984 Some(Selection { start, end, .. }) => start != end,
2985 None => false,
2986 };
2987
2988 pending_nonempty_selection
2989 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2990 }
2991
2992 pub fn has_pending_selection(&self) -> bool {
2993 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2994 }
2995
2996 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2997 self.selection_mark_mode = false;
2998
2999 if self.clear_expanded_diff_hunks(cx) {
3000 cx.notify();
3001 return;
3002 }
3003 if self.dismiss_menus_and_popups(true, window, cx) {
3004 return;
3005 }
3006
3007 if self.mode == EditorMode::Full
3008 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3009 {
3010 return;
3011 }
3012
3013 cx.propagate();
3014 }
3015
3016 pub fn dismiss_menus_and_popups(
3017 &mut self,
3018 is_user_requested: bool,
3019 window: &mut Window,
3020 cx: &mut Context<Self>,
3021 ) -> bool {
3022 if self.take_rename(false, window, cx).is_some() {
3023 return true;
3024 }
3025
3026 if hide_hover(self, cx) {
3027 return true;
3028 }
3029
3030 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3031 return true;
3032 }
3033
3034 if self.hide_context_menu(window, cx).is_some() {
3035 return true;
3036 }
3037
3038 if self.mouse_context_menu.take().is_some() {
3039 return true;
3040 }
3041
3042 if is_user_requested && self.discard_inline_completion(true, cx) {
3043 return true;
3044 }
3045
3046 if self.snippet_stack.pop().is_some() {
3047 return true;
3048 }
3049
3050 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3051 self.dismiss_diagnostics(cx);
3052 return true;
3053 }
3054
3055 false
3056 }
3057
3058 fn linked_editing_ranges_for(
3059 &self,
3060 selection: Range<text::Anchor>,
3061 cx: &App,
3062 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3063 if self.linked_edit_ranges.is_empty() {
3064 return None;
3065 }
3066 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3067 selection.end.buffer_id.and_then(|end_buffer_id| {
3068 if selection.start.buffer_id != Some(end_buffer_id) {
3069 return None;
3070 }
3071 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3072 let snapshot = buffer.read(cx).snapshot();
3073 self.linked_edit_ranges
3074 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3075 .map(|ranges| (ranges, snapshot, buffer))
3076 })?;
3077 use text::ToOffset as TO;
3078 // find offset from the start of current range to current cursor position
3079 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3080
3081 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3082 let start_difference = start_offset - start_byte_offset;
3083 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3084 let end_difference = end_offset - start_byte_offset;
3085 // Current range has associated linked ranges.
3086 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3087 for range in linked_ranges.iter() {
3088 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3089 let end_offset = start_offset + end_difference;
3090 let start_offset = start_offset + start_difference;
3091 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3092 continue;
3093 }
3094 if self.selections.disjoint_anchor_ranges().any(|s| {
3095 if s.start.buffer_id != selection.start.buffer_id
3096 || s.end.buffer_id != selection.end.buffer_id
3097 {
3098 return false;
3099 }
3100 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3101 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3102 }) {
3103 continue;
3104 }
3105 let start = buffer_snapshot.anchor_after(start_offset);
3106 let end = buffer_snapshot.anchor_after(end_offset);
3107 linked_edits
3108 .entry(buffer.clone())
3109 .or_default()
3110 .push(start..end);
3111 }
3112 Some(linked_edits)
3113 }
3114
3115 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3116 let text: Arc<str> = text.into();
3117
3118 if self.read_only(cx) {
3119 return;
3120 }
3121
3122 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3123
3124 let selections = self.selections.all_adjusted(cx);
3125 let mut bracket_inserted = false;
3126 let mut edits = Vec::new();
3127 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3128 let mut new_selections = Vec::with_capacity(selections.len());
3129 let mut new_autoclose_regions = Vec::new();
3130 let snapshot = self.buffer.read(cx).read(cx);
3131
3132 for (selection, autoclose_region) in
3133 self.selections_with_autoclose_regions(selections, &snapshot)
3134 {
3135 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3136 // Determine if the inserted text matches the opening or closing
3137 // bracket of any of this language's bracket pairs.
3138 let mut bracket_pair = None;
3139 let mut is_bracket_pair_start = false;
3140 let mut is_bracket_pair_end = false;
3141 if !text.is_empty() {
3142 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3143 // and they are removing the character that triggered IME popup.
3144 for (pair, enabled) in scope.brackets() {
3145 if !pair.close && !pair.surround {
3146 continue;
3147 }
3148
3149 if enabled && pair.start.ends_with(text.as_ref()) {
3150 let prefix_len = pair.start.len() - text.len();
3151 let preceding_text_matches_prefix = prefix_len == 0
3152 || (selection.start.column >= (prefix_len as u32)
3153 && snapshot.contains_str_at(
3154 Point::new(
3155 selection.start.row,
3156 selection.start.column - (prefix_len as u32),
3157 ),
3158 &pair.start[..prefix_len],
3159 ));
3160 if preceding_text_matches_prefix {
3161 bracket_pair = Some(pair.clone());
3162 is_bracket_pair_start = true;
3163 break;
3164 }
3165 }
3166 if pair.end.as_str() == text.as_ref() {
3167 bracket_pair = Some(pair.clone());
3168 is_bracket_pair_end = true;
3169 break;
3170 }
3171 }
3172 }
3173
3174 if let Some(bracket_pair) = bracket_pair {
3175 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3176 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3177 let auto_surround =
3178 self.use_auto_surround && snapshot_settings.use_auto_surround;
3179 if selection.is_empty() {
3180 if is_bracket_pair_start {
3181 // If the inserted text is a suffix of an opening bracket and the
3182 // selection is preceded by the rest of the opening bracket, then
3183 // insert the closing bracket.
3184 let following_text_allows_autoclose = snapshot
3185 .chars_at(selection.start)
3186 .next()
3187 .map_or(true, |c| scope.should_autoclose_before(c));
3188
3189 let preceding_text_allows_autoclose = selection.start.column == 0
3190 || snapshot.reversed_chars_at(selection.start).next().map_or(
3191 true,
3192 |c| {
3193 bracket_pair.start != bracket_pair.end
3194 || !snapshot
3195 .char_classifier_at(selection.start)
3196 .is_word(c)
3197 },
3198 );
3199
3200 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3201 && bracket_pair.start.len() == 1
3202 {
3203 let target = bracket_pair.start.chars().next().unwrap();
3204 let current_line_count = snapshot
3205 .reversed_chars_at(selection.start)
3206 .take_while(|&c| c != '\n')
3207 .filter(|&c| c == target)
3208 .count();
3209 current_line_count % 2 == 1
3210 } else {
3211 false
3212 };
3213
3214 if autoclose
3215 && bracket_pair.close
3216 && following_text_allows_autoclose
3217 && preceding_text_allows_autoclose
3218 && !is_closing_quote
3219 {
3220 let anchor = snapshot.anchor_before(selection.end);
3221 new_selections.push((selection.map(|_| anchor), text.len()));
3222 new_autoclose_regions.push((
3223 anchor,
3224 text.len(),
3225 selection.id,
3226 bracket_pair.clone(),
3227 ));
3228 edits.push((
3229 selection.range(),
3230 format!("{}{}", text, bracket_pair.end).into(),
3231 ));
3232 bracket_inserted = true;
3233 continue;
3234 }
3235 }
3236
3237 if let Some(region) = autoclose_region {
3238 // If the selection is followed by an auto-inserted closing bracket,
3239 // then don't insert that closing bracket again; just move the selection
3240 // past the closing bracket.
3241 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3242 && text.as_ref() == region.pair.end.as_str();
3243 if should_skip {
3244 let anchor = snapshot.anchor_after(selection.end);
3245 new_selections
3246 .push((selection.map(|_| anchor), region.pair.end.len()));
3247 continue;
3248 }
3249 }
3250
3251 let always_treat_brackets_as_autoclosed = snapshot
3252 .language_settings_at(selection.start, cx)
3253 .always_treat_brackets_as_autoclosed;
3254 if always_treat_brackets_as_autoclosed
3255 && is_bracket_pair_end
3256 && snapshot.contains_str_at(selection.end, text.as_ref())
3257 {
3258 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3259 // and the inserted text is a closing bracket and the selection is followed
3260 // by the closing bracket then move the selection past the closing bracket.
3261 let anchor = snapshot.anchor_after(selection.end);
3262 new_selections.push((selection.map(|_| anchor), text.len()));
3263 continue;
3264 }
3265 }
3266 // If an opening bracket is 1 character long and is typed while
3267 // text is selected, then surround that text with the bracket pair.
3268 else if auto_surround
3269 && bracket_pair.surround
3270 && is_bracket_pair_start
3271 && bracket_pair.start.chars().count() == 1
3272 {
3273 edits.push((selection.start..selection.start, text.clone()));
3274 edits.push((
3275 selection.end..selection.end,
3276 bracket_pair.end.as_str().into(),
3277 ));
3278 bracket_inserted = true;
3279 new_selections.push((
3280 Selection {
3281 id: selection.id,
3282 start: snapshot.anchor_after(selection.start),
3283 end: snapshot.anchor_before(selection.end),
3284 reversed: selection.reversed,
3285 goal: selection.goal,
3286 },
3287 0,
3288 ));
3289 continue;
3290 }
3291 }
3292 }
3293
3294 if self.auto_replace_emoji_shortcode
3295 && selection.is_empty()
3296 && text.as_ref().ends_with(':')
3297 {
3298 if let Some(possible_emoji_short_code) =
3299 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3300 {
3301 if !possible_emoji_short_code.is_empty() {
3302 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3303 let emoji_shortcode_start = Point::new(
3304 selection.start.row,
3305 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3306 );
3307
3308 // Remove shortcode from buffer
3309 edits.push((
3310 emoji_shortcode_start..selection.start,
3311 "".to_string().into(),
3312 ));
3313 new_selections.push((
3314 Selection {
3315 id: selection.id,
3316 start: snapshot.anchor_after(emoji_shortcode_start),
3317 end: snapshot.anchor_before(selection.start),
3318 reversed: selection.reversed,
3319 goal: selection.goal,
3320 },
3321 0,
3322 ));
3323
3324 // Insert emoji
3325 let selection_start_anchor = snapshot.anchor_after(selection.start);
3326 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3327 edits.push((selection.start..selection.end, emoji.to_string().into()));
3328
3329 continue;
3330 }
3331 }
3332 }
3333 }
3334
3335 // If not handling any auto-close operation, then just replace the selected
3336 // text with the given input and move the selection to the end of the
3337 // newly inserted text.
3338 let anchor = snapshot.anchor_after(selection.end);
3339 if !self.linked_edit_ranges.is_empty() {
3340 let start_anchor = snapshot.anchor_before(selection.start);
3341
3342 let is_word_char = text.chars().next().map_or(true, |char| {
3343 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3344 classifier.is_word(char)
3345 });
3346
3347 if is_word_char {
3348 if let Some(ranges) = self
3349 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3350 {
3351 for (buffer, edits) in ranges {
3352 linked_edits
3353 .entry(buffer.clone())
3354 .or_default()
3355 .extend(edits.into_iter().map(|range| (range, text.clone())));
3356 }
3357 }
3358 }
3359 }
3360
3361 new_selections.push((selection.map(|_| anchor), 0));
3362 edits.push((selection.start..selection.end, text.clone()));
3363 }
3364
3365 drop(snapshot);
3366
3367 self.transact(window, cx, |this, window, cx| {
3368 let initial_buffer_versions =
3369 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3370
3371 this.buffer.update(cx, |buffer, cx| {
3372 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3373 });
3374 for (buffer, edits) in linked_edits {
3375 buffer.update(cx, |buffer, cx| {
3376 let snapshot = buffer.snapshot();
3377 let edits = edits
3378 .into_iter()
3379 .map(|(range, text)| {
3380 use text::ToPoint as TP;
3381 let end_point = TP::to_point(&range.end, &snapshot);
3382 let start_point = TP::to_point(&range.start, &snapshot);
3383 (start_point..end_point, text)
3384 })
3385 .sorted_by_key(|(range, _)| range.start);
3386 buffer.edit(edits, None, cx);
3387 })
3388 }
3389 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3390 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3391 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3392 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3393 .zip(new_selection_deltas)
3394 .map(|(selection, delta)| Selection {
3395 id: selection.id,
3396 start: selection.start + delta,
3397 end: selection.end + delta,
3398 reversed: selection.reversed,
3399 goal: SelectionGoal::None,
3400 })
3401 .collect::<Vec<_>>();
3402
3403 let mut i = 0;
3404 for (position, delta, selection_id, pair) in new_autoclose_regions {
3405 let position = position.to_offset(&map.buffer_snapshot) + delta;
3406 let start = map.buffer_snapshot.anchor_before(position);
3407 let end = map.buffer_snapshot.anchor_after(position);
3408 while let Some(existing_state) = this.autoclose_regions.get(i) {
3409 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3410 Ordering::Less => i += 1,
3411 Ordering::Greater => break,
3412 Ordering::Equal => {
3413 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3414 Ordering::Less => i += 1,
3415 Ordering::Equal => break,
3416 Ordering::Greater => break,
3417 }
3418 }
3419 }
3420 }
3421 this.autoclose_regions.insert(
3422 i,
3423 AutocloseRegion {
3424 selection_id,
3425 range: start..end,
3426 pair,
3427 },
3428 );
3429 }
3430
3431 let had_active_inline_completion = this.has_active_inline_completion();
3432 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3433 s.select(new_selections)
3434 });
3435
3436 if !bracket_inserted {
3437 if let Some(on_type_format_task) =
3438 this.trigger_on_type_formatting(text.to_string(), window, cx)
3439 {
3440 on_type_format_task.detach_and_log_err(cx);
3441 }
3442 }
3443
3444 let editor_settings = EditorSettings::get_global(cx);
3445 if bracket_inserted
3446 && (editor_settings.auto_signature_help
3447 || editor_settings.show_signature_help_after_edits)
3448 {
3449 this.show_signature_help(&ShowSignatureHelp, window, cx);
3450 }
3451
3452 let trigger_in_words =
3453 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3454 if this.hard_wrap.is_some() {
3455 let latest: Range<Point> = this.selections.newest(cx).range();
3456 if latest.is_empty()
3457 && this
3458 .buffer()
3459 .read(cx)
3460 .snapshot(cx)
3461 .line_len(MultiBufferRow(latest.start.row))
3462 == latest.start.column
3463 {
3464 this.rewrap_impl(
3465 RewrapOptions {
3466 override_language_settings: true,
3467 preserve_existing_whitespace: true,
3468 },
3469 cx,
3470 )
3471 }
3472 }
3473 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3474 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3475 this.refresh_inline_completion(true, false, window, cx);
3476 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3477 });
3478 }
3479
3480 fn find_possible_emoji_shortcode_at_position(
3481 snapshot: &MultiBufferSnapshot,
3482 position: Point,
3483 ) -> Option<String> {
3484 let mut chars = Vec::new();
3485 let mut found_colon = false;
3486 for char in snapshot.reversed_chars_at(position).take(100) {
3487 // Found a possible emoji shortcode in the middle of the buffer
3488 if found_colon {
3489 if char.is_whitespace() {
3490 chars.reverse();
3491 return Some(chars.iter().collect());
3492 }
3493 // If the previous character is not a whitespace, we are in the middle of a word
3494 // and we only want to complete the shortcode if the word is made up of other emojis
3495 let mut containing_word = String::new();
3496 for ch in snapshot
3497 .reversed_chars_at(position)
3498 .skip(chars.len() + 1)
3499 .take(100)
3500 {
3501 if ch.is_whitespace() {
3502 break;
3503 }
3504 containing_word.push(ch);
3505 }
3506 let containing_word = containing_word.chars().rev().collect::<String>();
3507 if util::word_consists_of_emojis(containing_word.as_str()) {
3508 chars.reverse();
3509 return Some(chars.iter().collect());
3510 }
3511 }
3512
3513 if char.is_whitespace() || !char.is_ascii() {
3514 return None;
3515 }
3516 if char == ':' {
3517 found_colon = true;
3518 } else {
3519 chars.push(char);
3520 }
3521 }
3522 // Found a possible emoji shortcode at the beginning of the buffer
3523 chars.reverse();
3524 Some(chars.iter().collect())
3525 }
3526
3527 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3528 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3529 self.transact(window, cx, |this, window, cx| {
3530 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3531 let selections = this.selections.all::<usize>(cx);
3532 let multi_buffer = this.buffer.read(cx);
3533 let buffer = multi_buffer.snapshot(cx);
3534 selections
3535 .iter()
3536 .map(|selection| {
3537 let start_point = selection.start.to_point(&buffer);
3538 let mut indent =
3539 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3540 indent.len = cmp::min(indent.len, start_point.column);
3541 let start = selection.start;
3542 let end = selection.end;
3543 let selection_is_empty = start == end;
3544 let language_scope = buffer.language_scope_at(start);
3545 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3546 &language_scope
3547 {
3548 let insert_extra_newline =
3549 insert_extra_newline_brackets(&buffer, start..end, language)
3550 || insert_extra_newline_tree_sitter(&buffer, start..end);
3551
3552 // Comment extension on newline is allowed only for cursor selections
3553 let comment_delimiter = maybe!({
3554 if !selection_is_empty {
3555 return None;
3556 }
3557
3558 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3559 return None;
3560 }
3561
3562 let delimiters = language.line_comment_prefixes();
3563 let max_len_of_delimiter =
3564 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3565 let (snapshot, range) =
3566 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3567
3568 let mut index_of_first_non_whitespace = 0;
3569 let comment_candidate = snapshot
3570 .chars_for_range(range)
3571 .skip_while(|c| {
3572 let should_skip = c.is_whitespace();
3573 if should_skip {
3574 index_of_first_non_whitespace += 1;
3575 }
3576 should_skip
3577 })
3578 .take(max_len_of_delimiter)
3579 .collect::<String>();
3580 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3581 comment_candidate.starts_with(comment_prefix.as_ref())
3582 })?;
3583 let cursor_is_placed_after_comment_marker =
3584 index_of_first_non_whitespace + comment_prefix.len()
3585 <= start_point.column as usize;
3586 if cursor_is_placed_after_comment_marker {
3587 Some(comment_prefix.clone())
3588 } else {
3589 None
3590 }
3591 });
3592 (comment_delimiter, insert_extra_newline)
3593 } else {
3594 (None, false)
3595 };
3596
3597 let capacity_for_delimiter = comment_delimiter
3598 .as_deref()
3599 .map(str::len)
3600 .unwrap_or_default();
3601 let mut new_text =
3602 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3603 new_text.push('\n');
3604 new_text.extend(indent.chars());
3605 if let Some(delimiter) = &comment_delimiter {
3606 new_text.push_str(delimiter);
3607 }
3608 if insert_extra_newline {
3609 new_text = new_text.repeat(2);
3610 }
3611
3612 let anchor = buffer.anchor_after(end);
3613 let new_selection = selection.map(|_| anchor);
3614 (
3615 (start..end, new_text),
3616 (insert_extra_newline, new_selection),
3617 )
3618 })
3619 .unzip()
3620 };
3621
3622 this.edit_with_autoindent(edits, cx);
3623 let buffer = this.buffer.read(cx).snapshot(cx);
3624 let new_selections = selection_fixup_info
3625 .into_iter()
3626 .map(|(extra_newline_inserted, new_selection)| {
3627 let mut cursor = new_selection.end.to_point(&buffer);
3628 if extra_newline_inserted {
3629 cursor.row -= 1;
3630 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3631 }
3632 new_selection.map(|_| cursor)
3633 })
3634 .collect();
3635
3636 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3637 s.select(new_selections)
3638 });
3639 this.refresh_inline_completion(true, false, window, cx);
3640 });
3641 }
3642
3643 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3644 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3645
3646 let buffer = self.buffer.read(cx);
3647 let snapshot = buffer.snapshot(cx);
3648
3649 let mut edits = Vec::new();
3650 let mut rows = Vec::new();
3651
3652 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3653 let cursor = selection.head();
3654 let row = cursor.row;
3655
3656 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3657
3658 let newline = "\n".to_string();
3659 edits.push((start_of_line..start_of_line, newline));
3660
3661 rows.push(row + rows_inserted as u32);
3662 }
3663
3664 self.transact(window, cx, |editor, window, cx| {
3665 editor.edit(edits, cx);
3666
3667 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3668 let mut index = 0;
3669 s.move_cursors_with(|map, _, _| {
3670 let row = rows[index];
3671 index += 1;
3672
3673 let point = Point::new(row, 0);
3674 let boundary = map.next_line_boundary(point).1;
3675 let clipped = map.clip_point(boundary, Bias::Left);
3676
3677 (clipped, SelectionGoal::None)
3678 });
3679 });
3680
3681 let mut indent_edits = Vec::new();
3682 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3683 for row in rows {
3684 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3685 for (row, indent) in indents {
3686 if indent.len == 0 {
3687 continue;
3688 }
3689
3690 let text = match indent.kind {
3691 IndentKind::Space => " ".repeat(indent.len as usize),
3692 IndentKind::Tab => "\t".repeat(indent.len as usize),
3693 };
3694 let point = Point::new(row.0, 0);
3695 indent_edits.push((point..point, text));
3696 }
3697 }
3698 editor.edit(indent_edits, cx);
3699 });
3700 }
3701
3702 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3703 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3704
3705 let buffer = self.buffer.read(cx);
3706 let snapshot = buffer.snapshot(cx);
3707
3708 let mut edits = Vec::new();
3709 let mut rows = Vec::new();
3710 let mut rows_inserted = 0;
3711
3712 for selection in self.selections.all_adjusted(cx) {
3713 let cursor = selection.head();
3714 let row = cursor.row;
3715
3716 let point = Point::new(row + 1, 0);
3717 let start_of_line = snapshot.clip_point(point, Bias::Left);
3718
3719 let newline = "\n".to_string();
3720 edits.push((start_of_line..start_of_line, newline));
3721
3722 rows_inserted += 1;
3723 rows.push(row + rows_inserted);
3724 }
3725
3726 self.transact(window, cx, |editor, window, cx| {
3727 editor.edit(edits, cx);
3728
3729 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3730 let mut index = 0;
3731 s.move_cursors_with(|map, _, _| {
3732 let row = rows[index];
3733 index += 1;
3734
3735 let point = Point::new(row, 0);
3736 let boundary = map.next_line_boundary(point).1;
3737 let clipped = map.clip_point(boundary, Bias::Left);
3738
3739 (clipped, SelectionGoal::None)
3740 });
3741 });
3742
3743 let mut indent_edits = Vec::new();
3744 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3745 for row in rows {
3746 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3747 for (row, indent) in indents {
3748 if indent.len == 0 {
3749 continue;
3750 }
3751
3752 let text = match indent.kind {
3753 IndentKind::Space => " ".repeat(indent.len as usize),
3754 IndentKind::Tab => "\t".repeat(indent.len as usize),
3755 };
3756 let point = Point::new(row.0, 0);
3757 indent_edits.push((point..point, text));
3758 }
3759 }
3760 editor.edit(indent_edits, cx);
3761 });
3762 }
3763
3764 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3765 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3766 original_indent_columns: Vec::new(),
3767 });
3768 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3769 }
3770
3771 fn insert_with_autoindent_mode(
3772 &mut self,
3773 text: &str,
3774 autoindent_mode: Option<AutoindentMode>,
3775 window: &mut Window,
3776 cx: &mut Context<Self>,
3777 ) {
3778 if self.read_only(cx) {
3779 return;
3780 }
3781
3782 let text: Arc<str> = text.into();
3783 self.transact(window, cx, |this, window, cx| {
3784 let old_selections = this.selections.all_adjusted(cx);
3785 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3786 let anchors = {
3787 let snapshot = buffer.read(cx);
3788 old_selections
3789 .iter()
3790 .map(|s| {
3791 let anchor = snapshot.anchor_after(s.head());
3792 s.map(|_| anchor)
3793 })
3794 .collect::<Vec<_>>()
3795 };
3796 buffer.edit(
3797 old_selections
3798 .iter()
3799 .map(|s| (s.start..s.end, text.clone())),
3800 autoindent_mode,
3801 cx,
3802 );
3803 anchors
3804 });
3805
3806 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3807 s.select_anchors(selection_anchors);
3808 });
3809
3810 cx.notify();
3811 });
3812 }
3813
3814 fn trigger_completion_on_input(
3815 &mut self,
3816 text: &str,
3817 trigger_in_words: bool,
3818 window: &mut Window,
3819 cx: &mut Context<Self>,
3820 ) {
3821 let ignore_completion_provider = self
3822 .context_menu
3823 .borrow()
3824 .as_ref()
3825 .map(|menu| match menu {
3826 CodeContextMenu::Completions(completions_menu) => {
3827 completions_menu.ignore_completion_provider
3828 }
3829 CodeContextMenu::CodeActions(_) => false,
3830 })
3831 .unwrap_or(false);
3832
3833 if ignore_completion_provider {
3834 self.show_word_completions(&ShowWordCompletions, window, cx);
3835 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3836 self.show_completions(
3837 &ShowCompletions {
3838 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3839 },
3840 window,
3841 cx,
3842 );
3843 } else {
3844 self.hide_context_menu(window, cx);
3845 }
3846 }
3847
3848 fn is_completion_trigger(
3849 &self,
3850 text: &str,
3851 trigger_in_words: bool,
3852 cx: &mut Context<Self>,
3853 ) -> bool {
3854 let position = self.selections.newest_anchor().head();
3855 let multibuffer = self.buffer.read(cx);
3856 let Some(buffer) = position
3857 .buffer_id
3858 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3859 else {
3860 return false;
3861 };
3862
3863 if let Some(completion_provider) = &self.completion_provider {
3864 completion_provider.is_completion_trigger(
3865 &buffer,
3866 position.text_anchor,
3867 text,
3868 trigger_in_words,
3869 cx,
3870 )
3871 } else {
3872 false
3873 }
3874 }
3875
3876 /// If any empty selections is touching the start of its innermost containing autoclose
3877 /// region, expand it to select the brackets.
3878 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3879 let selections = self.selections.all::<usize>(cx);
3880 let buffer = self.buffer.read(cx).read(cx);
3881 let new_selections = self
3882 .selections_with_autoclose_regions(selections, &buffer)
3883 .map(|(mut selection, region)| {
3884 if !selection.is_empty() {
3885 return selection;
3886 }
3887
3888 if let Some(region) = region {
3889 let mut range = region.range.to_offset(&buffer);
3890 if selection.start == range.start && range.start >= region.pair.start.len() {
3891 range.start -= region.pair.start.len();
3892 if buffer.contains_str_at(range.start, ®ion.pair.start)
3893 && buffer.contains_str_at(range.end, ®ion.pair.end)
3894 {
3895 range.end += region.pair.end.len();
3896 selection.start = range.start;
3897 selection.end = range.end;
3898
3899 return selection;
3900 }
3901 }
3902 }
3903
3904 let always_treat_brackets_as_autoclosed = buffer
3905 .language_settings_at(selection.start, cx)
3906 .always_treat_brackets_as_autoclosed;
3907
3908 if !always_treat_brackets_as_autoclosed {
3909 return selection;
3910 }
3911
3912 if let Some(scope) = buffer.language_scope_at(selection.start) {
3913 for (pair, enabled) in scope.brackets() {
3914 if !enabled || !pair.close {
3915 continue;
3916 }
3917
3918 if buffer.contains_str_at(selection.start, &pair.end) {
3919 let pair_start_len = pair.start.len();
3920 if buffer.contains_str_at(
3921 selection.start.saturating_sub(pair_start_len),
3922 &pair.start,
3923 ) {
3924 selection.start -= pair_start_len;
3925 selection.end += pair.end.len();
3926
3927 return selection;
3928 }
3929 }
3930 }
3931 }
3932
3933 selection
3934 })
3935 .collect();
3936
3937 drop(buffer);
3938 self.change_selections(None, window, cx, |selections| {
3939 selections.select(new_selections)
3940 });
3941 }
3942
3943 /// Iterate the given selections, and for each one, find the smallest surrounding
3944 /// autoclose region. This uses the ordering of the selections and the autoclose
3945 /// regions to avoid repeated comparisons.
3946 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3947 &'a self,
3948 selections: impl IntoIterator<Item = Selection<D>>,
3949 buffer: &'a MultiBufferSnapshot,
3950 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3951 let mut i = 0;
3952 let mut regions = self.autoclose_regions.as_slice();
3953 selections.into_iter().map(move |selection| {
3954 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3955
3956 let mut enclosing = None;
3957 while let Some(pair_state) = regions.get(i) {
3958 if pair_state.range.end.to_offset(buffer) < range.start {
3959 regions = ®ions[i + 1..];
3960 i = 0;
3961 } else if pair_state.range.start.to_offset(buffer) > range.end {
3962 break;
3963 } else {
3964 if pair_state.selection_id == selection.id {
3965 enclosing = Some(pair_state);
3966 }
3967 i += 1;
3968 }
3969 }
3970
3971 (selection, enclosing)
3972 })
3973 }
3974
3975 /// Remove any autoclose regions that no longer contain their selection.
3976 fn invalidate_autoclose_regions(
3977 &mut self,
3978 mut selections: &[Selection<Anchor>],
3979 buffer: &MultiBufferSnapshot,
3980 ) {
3981 self.autoclose_regions.retain(|state| {
3982 let mut i = 0;
3983 while let Some(selection) = selections.get(i) {
3984 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3985 selections = &selections[1..];
3986 continue;
3987 }
3988 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3989 break;
3990 }
3991 if selection.id == state.selection_id {
3992 return true;
3993 } else {
3994 i += 1;
3995 }
3996 }
3997 false
3998 });
3999 }
4000
4001 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4002 let offset = position.to_offset(buffer);
4003 let (word_range, kind) = buffer.surrounding_word(offset, true);
4004 if offset > word_range.start && kind == Some(CharKind::Word) {
4005 Some(
4006 buffer
4007 .text_for_range(word_range.start..offset)
4008 .collect::<String>(),
4009 )
4010 } else {
4011 None
4012 }
4013 }
4014
4015 pub fn toggle_inlay_hints(
4016 &mut self,
4017 _: &ToggleInlayHints,
4018 _: &mut Window,
4019 cx: &mut Context<Self>,
4020 ) {
4021 self.refresh_inlay_hints(
4022 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4023 cx,
4024 );
4025 }
4026
4027 pub fn inlay_hints_enabled(&self) -> bool {
4028 self.inlay_hint_cache.enabled
4029 }
4030
4031 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4032 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4033 return;
4034 }
4035
4036 let reason_description = reason.description();
4037 let ignore_debounce = matches!(
4038 reason,
4039 InlayHintRefreshReason::SettingsChange(_)
4040 | InlayHintRefreshReason::Toggle(_)
4041 | InlayHintRefreshReason::ExcerptsRemoved(_)
4042 | InlayHintRefreshReason::ModifiersChanged(_)
4043 );
4044 let (invalidate_cache, required_languages) = match reason {
4045 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4046 match self.inlay_hint_cache.modifiers_override(enabled) {
4047 Some(enabled) => {
4048 if enabled {
4049 (InvalidationStrategy::RefreshRequested, None)
4050 } else {
4051 self.splice_inlays(
4052 &self
4053 .visible_inlay_hints(cx)
4054 .iter()
4055 .map(|inlay| inlay.id)
4056 .collect::<Vec<InlayId>>(),
4057 Vec::new(),
4058 cx,
4059 );
4060 return;
4061 }
4062 }
4063 None => return,
4064 }
4065 }
4066 InlayHintRefreshReason::Toggle(enabled) => {
4067 if self.inlay_hint_cache.toggle(enabled) {
4068 if enabled {
4069 (InvalidationStrategy::RefreshRequested, None)
4070 } else {
4071 self.splice_inlays(
4072 &self
4073 .visible_inlay_hints(cx)
4074 .iter()
4075 .map(|inlay| inlay.id)
4076 .collect::<Vec<InlayId>>(),
4077 Vec::new(),
4078 cx,
4079 );
4080 return;
4081 }
4082 } else {
4083 return;
4084 }
4085 }
4086 InlayHintRefreshReason::SettingsChange(new_settings) => {
4087 match self.inlay_hint_cache.update_settings(
4088 &self.buffer,
4089 new_settings,
4090 self.visible_inlay_hints(cx),
4091 cx,
4092 ) {
4093 ControlFlow::Break(Some(InlaySplice {
4094 to_remove,
4095 to_insert,
4096 })) => {
4097 self.splice_inlays(&to_remove, to_insert, cx);
4098 return;
4099 }
4100 ControlFlow::Break(None) => return,
4101 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4102 }
4103 }
4104 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4105 if let Some(InlaySplice {
4106 to_remove,
4107 to_insert,
4108 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4109 {
4110 self.splice_inlays(&to_remove, to_insert, cx);
4111 }
4112 return;
4113 }
4114 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4115 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4116 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4117 }
4118 InlayHintRefreshReason::RefreshRequested => {
4119 (InvalidationStrategy::RefreshRequested, None)
4120 }
4121 };
4122
4123 if let Some(InlaySplice {
4124 to_remove,
4125 to_insert,
4126 }) = self.inlay_hint_cache.spawn_hint_refresh(
4127 reason_description,
4128 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4129 invalidate_cache,
4130 ignore_debounce,
4131 cx,
4132 ) {
4133 self.splice_inlays(&to_remove, to_insert, cx);
4134 }
4135 }
4136
4137 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4138 self.display_map
4139 .read(cx)
4140 .current_inlays()
4141 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4142 .cloned()
4143 .collect()
4144 }
4145
4146 pub fn excerpts_for_inlay_hints_query(
4147 &self,
4148 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4149 cx: &mut Context<Editor>,
4150 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4151 let Some(project) = self.project.as_ref() else {
4152 return HashMap::default();
4153 };
4154 let project = project.read(cx);
4155 let multi_buffer = self.buffer().read(cx);
4156 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4157 let multi_buffer_visible_start = self
4158 .scroll_manager
4159 .anchor()
4160 .anchor
4161 .to_point(&multi_buffer_snapshot);
4162 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4163 multi_buffer_visible_start
4164 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4165 Bias::Left,
4166 );
4167 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4168 multi_buffer_snapshot
4169 .range_to_buffer_ranges(multi_buffer_visible_range)
4170 .into_iter()
4171 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4172 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4173 let buffer_file = project::File::from_dyn(buffer.file())?;
4174 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4175 let worktree_entry = buffer_worktree
4176 .read(cx)
4177 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4178 if worktree_entry.is_ignored {
4179 return None;
4180 }
4181
4182 let language = buffer.language()?;
4183 if let Some(restrict_to_languages) = restrict_to_languages {
4184 if !restrict_to_languages.contains(language) {
4185 return None;
4186 }
4187 }
4188 Some((
4189 excerpt_id,
4190 (
4191 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4192 buffer.version().clone(),
4193 excerpt_visible_range,
4194 ),
4195 ))
4196 })
4197 .collect()
4198 }
4199
4200 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4201 TextLayoutDetails {
4202 text_system: window.text_system().clone(),
4203 editor_style: self.style.clone().unwrap(),
4204 rem_size: window.rem_size(),
4205 scroll_anchor: self.scroll_manager.anchor(),
4206 visible_rows: self.visible_line_count(),
4207 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4208 }
4209 }
4210
4211 pub fn splice_inlays(
4212 &self,
4213 to_remove: &[InlayId],
4214 to_insert: Vec<Inlay>,
4215 cx: &mut Context<Self>,
4216 ) {
4217 self.display_map.update(cx, |display_map, cx| {
4218 display_map.splice_inlays(to_remove, to_insert, cx)
4219 });
4220 cx.notify();
4221 }
4222
4223 fn trigger_on_type_formatting(
4224 &self,
4225 input: String,
4226 window: &mut Window,
4227 cx: &mut Context<Self>,
4228 ) -> Option<Task<Result<()>>> {
4229 if input.len() != 1 {
4230 return None;
4231 }
4232
4233 let project = self.project.as_ref()?;
4234 let position = self.selections.newest_anchor().head();
4235 let (buffer, buffer_position) = self
4236 .buffer
4237 .read(cx)
4238 .text_anchor_for_position(position, cx)?;
4239
4240 let settings = language_settings::language_settings(
4241 buffer
4242 .read(cx)
4243 .language_at(buffer_position)
4244 .map(|l| l.name()),
4245 buffer.read(cx).file(),
4246 cx,
4247 );
4248 if !settings.use_on_type_format {
4249 return None;
4250 }
4251
4252 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4253 // hence we do LSP request & edit on host side only — add formats to host's history.
4254 let push_to_lsp_host_history = true;
4255 // If this is not the host, append its history with new edits.
4256 let push_to_client_history = project.read(cx).is_via_collab();
4257
4258 let on_type_formatting = project.update(cx, |project, cx| {
4259 project.on_type_format(
4260 buffer.clone(),
4261 buffer_position,
4262 input,
4263 push_to_lsp_host_history,
4264 cx,
4265 )
4266 });
4267 Some(cx.spawn_in(window, async move |editor, cx| {
4268 if let Some(transaction) = on_type_formatting.await? {
4269 if push_to_client_history {
4270 buffer
4271 .update(cx, |buffer, _| {
4272 buffer.push_transaction(transaction, Instant::now());
4273 })
4274 .ok();
4275 }
4276 editor.update(cx, |editor, cx| {
4277 editor.refresh_document_highlights(cx);
4278 })?;
4279 }
4280 Ok(())
4281 }))
4282 }
4283
4284 pub fn show_word_completions(
4285 &mut self,
4286 _: &ShowWordCompletions,
4287 window: &mut Window,
4288 cx: &mut Context<Self>,
4289 ) {
4290 self.open_completions_menu(true, None, window, cx);
4291 }
4292
4293 pub fn show_completions(
4294 &mut self,
4295 options: &ShowCompletions,
4296 window: &mut Window,
4297 cx: &mut Context<Self>,
4298 ) {
4299 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4300 }
4301
4302 fn open_completions_menu(
4303 &mut self,
4304 ignore_completion_provider: bool,
4305 trigger: Option<&str>,
4306 window: &mut Window,
4307 cx: &mut Context<Self>,
4308 ) {
4309 if self.pending_rename.is_some() {
4310 return;
4311 }
4312 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4313 return;
4314 }
4315
4316 let position = self.selections.newest_anchor().head();
4317 if position.diff_base_anchor.is_some() {
4318 return;
4319 }
4320 let (buffer, buffer_position) =
4321 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4322 output
4323 } else {
4324 return;
4325 };
4326 let buffer_snapshot = buffer.read(cx).snapshot();
4327 let show_completion_documentation = buffer_snapshot
4328 .settings_at(buffer_position, cx)
4329 .show_completion_documentation;
4330
4331 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4332
4333 let trigger_kind = match trigger {
4334 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4335 CompletionTriggerKind::TRIGGER_CHARACTER
4336 }
4337 _ => CompletionTriggerKind::INVOKED,
4338 };
4339 let completion_context = CompletionContext {
4340 trigger_character: trigger.and_then(|trigger| {
4341 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4342 Some(String::from(trigger))
4343 } else {
4344 None
4345 }
4346 }),
4347 trigger_kind,
4348 };
4349
4350 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4351 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4352 let word_to_exclude = buffer_snapshot
4353 .text_for_range(old_range.clone())
4354 .collect::<String>();
4355 (
4356 buffer_snapshot.anchor_before(old_range.start)
4357 ..buffer_snapshot.anchor_after(old_range.end),
4358 Some(word_to_exclude),
4359 )
4360 } else {
4361 (buffer_position..buffer_position, None)
4362 };
4363
4364 let completion_settings = language_settings(
4365 buffer_snapshot
4366 .language_at(buffer_position)
4367 .map(|language| language.name()),
4368 buffer_snapshot.file(),
4369 cx,
4370 )
4371 .completions;
4372
4373 // The document can be large, so stay in reasonable bounds when searching for words,
4374 // otherwise completion pop-up might be slow to appear.
4375 const WORD_LOOKUP_ROWS: u32 = 5_000;
4376 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4377 let min_word_search = buffer_snapshot.clip_point(
4378 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4379 Bias::Left,
4380 );
4381 let max_word_search = buffer_snapshot.clip_point(
4382 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4383 Bias::Right,
4384 );
4385 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4386 ..buffer_snapshot.point_to_offset(max_word_search);
4387
4388 let provider = self
4389 .completion_provider
4390 .as_ref()
4391 .filter(|_| !ignore_completion_provider);
4392 let skip_digits = query
4393 .as_ref()
4394 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4395
4396 let (mut words, provided_completions) = match provider {
4397 Some(provider) => {
4398 let completions = provider.completions(
4399 position.excerpt_id,
4400 &buffer,
4401 buffer_position,
4402 completion_context,
4403 window,
4404 cx,
4405 );
4406
4407 let words = match completion_settings.words {
4408 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4409 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4410 .background_spawn(async move {
4411 buffer_snapshot.words_in_range(WordsQuery {
4412 fuzzy_contents: None,
4413 range: word_search_range,
4414 skip_digits,
4415 })
4416 }),
4417 };
4418
4419 (words, completions)
4420 }
4421 None => (
4422 cx.background_spawn(async move {
4423 buffer_snapshot.words_in_range(WordsQuery {
4424 fuzzy_contents: None,
4425 range: word_search_range,
4426 skip_digits,
4427 })
4428 }),
4429 Task::ready(Ok(None)),
4430 ),
4431 };
4432
4433 let sort_completions = provider
4434 .as_ref()
4435 .map_or(false, |provider| provider.sort_completions());
4436
4437 let filter_completions = provider
4438 .as_ref()
4439 .map_or(true, |provider| provider.filter_completions());
4440
4441 let id = post_inc(&mut self.next_completion_id);
4442 let task = cx.spawn_in(window, async move |editor, cx| {
4443 async move {
4444 editor.update(cx, |this, _| {
4445 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4446 })?;
4447
4448 let mut completions = Vec::new();
4449 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4450 completions.extend(provided_completions);
4451 if completion_settings.words == WordsCompletionMode::Fallback {
4452 words = Task::ready(BTreeMap::default());
4453 }
4454 }
4455
4456 let mut words = words.await;
4457 if let Some(word_to_exclude) = &word_to_exclude {
4458 words.remove(word_to_exclude);
4459 }
4460 for lsp_completion in &completions {
4461 words.remove(&lsp_completion.new_text);
4462 }
4463 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4464 old_range: old_range.clone(),
4465 new_text: word.clone(),
4466 label: CodeLabel::plain(word, None),
4467 icon_path: None,
4468 documentation: None,
4469 source: CompletionSource::BufferWord {
4470 word_range,
4471 resolved: false,
4472 },
4473 insert_text_mode: Some(InsertTextMode::AS_IS),
4474 confirm: None,
4475 }));
4476
4477 let menu = if completions.is_empty() {
4478 None
4479 } else {
4480 let mut menu = CompletionsMenu::new(
4481 id,
4482 sort_completions,
4483 show_completion_documentation,
4484 ignore_completion_provider,
4485 position,
4486 buffer.clone(),
4487 completions.into(),
4488 );
4489
4490 menu.filter(
4491 if filter_completions {
4492 query.as_deref()
4493 } else {
4494 None
4495 },
4496 cx.background_executor().clone(),
4497 )
4498 .await;
4499
4500 menu.visible().then_some(menu)
4501 };
4502
4503 editor.update_in(cx, |editor, window, cx| {
4504 match editor.context_menu.borrow().as_ref() {
4505 None => {}
4506 Some(CodeContextMenu::Completions(prev_menu)) => {
4507 if prev_menu.id > id {
4508 return;
4509 }
4510 }
4511 _ => return,
4512 }
4513
4514 if editor.focus_handle.is_focused(window) && menu.is_some() {
4515 let mut menu = menu.unwrap();
4516 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4517
4518 *editor.context_menu.borrow_mut() =
4519 Some(CodeContextMenu::Completions(menu));
4520
4521 if editor.show_edit_predictions_in_menu() {
4522 editor.update_visible_inline_completion(window, cx);
4523 } else {
4524 editor.discard_inline_completion(false, cx);
4525 }
4526
4527 cx.notify();
4528 } else if editor.completion_tasks.len() <= 1 {
4529 // If there are no more completion tasks and the last menu was
4530 // empty, we should hide it.
4531 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4532 // If it was already hidden and we don't show inline
4533 // completions in the menu, we should also show the
4534 // inline-completion when available.
4535 if was_hidden && editor.show_edit_predictions_in_menu() {
4536 editor.update_visible_inline_completion(window, cx);
4537 }
4538 }
4539 })?;
4540
4541 anyhow::Ok(())
4542 }
4543 .log_err()
4544 .await
4545 });
4546
4547 self.completion_tasks.push((id, task));
4548 }
4549
4550 #[cfg(feature = "test-support")]
4551 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4552 let menu = self.context_menu.borrow();
4553 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4554 let completions = menu.completions.borrow();
4555 Some(completions.to_vec())
4556 } else {
4557 None
4558 }
4559 }
4560
4561 pub fn confirm_completion(
4562 &mut self,
4563 action: &ConfirmCompletion,
4564 window: &mut Window,
4565 cx: &mut Context<Self>,
4566 ) -> Option<Task<Result<()>>> {
4567 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4568 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4569 }
4570
4571 pub fn compose_completion(
4572 &mut self,
4573 action: &ComposeCompletion,
4574 window: &mut Window,
4575 cx: &mut Context<Self>,
4576 ) -> Option<Task<Result<()>>> {
4577 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4578 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4579 }
4580
4581 fn do_completion(
4582 &mut self,
4583 item_ix: Option<usize>,
4584 intent: CompletionIntent,
4585 window: &mut Window,
4586 cx: &mut Context<Editor>,
4587 ) -> Option<Task<Result<()>>> {
4588 use language::ToOffset as _;
4589
4590 let completions_menu =
4591 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4592 menu
4593 } else {
4594 return None;
4595 };
4596
4597 let candidate_id = {
4598 let entries = completions_menu.entries.borrow();
4599 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4600 if self.show_edit_predictions_in_menu() {
4601 self.discard_inline_completion(true, cx);
4602 }
4603 mat.candidate_id
4604 };
4605
4606 let buffer_handle = completions_menu.buffer;
4607 let completion = completions_menu
4608 .completions
4609 .borrow()
4610 .get(candidate_id)?
4611 .clone();
4612 cx.stop_propagation();
4613
4614 let snippet;
4615 let new_text;
4616 if completion.is_snippet() {
4617 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4618 new_text = snippet.as_ref().unwrap().text.clone();
4619 } else {
4620 snippet = None;
4621 new_text = completion.new_text.clone();
4622 };
4623 let selections = self.selections.all::<usize>(cx);
4624 let buffer = buffer_handle.read(cx);
4625 let old_range = completion.old_range.to_offset(buffer);
4626 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4627
4628 let newest_selection = self.selections.newest_anchor();
4629 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4630 return None;
4631 }
4632
4633 let lookbehind = newest_selection
4634 .start
4635 .text_anchor
4636 .to_offset(buffer)
4637 .saturating_sub(old_range.start);
4638 let lookahead = old_range
4639 .end
4640 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4641 let mut common_prefix_len = 0;
4642 for (a, b) in old_text.chars().zip(new_text.chars()) {
4643 if a == b {
4644 common_prefix_len += a.len_utf8();
4645 } else {
4646 break;
4647 }
4648 }
4649
4650 let snapshot = self.buffer.read(cx).snapshot(cx);
4651 let mut range_to_replace: Option<Range<usize>> = None;
4652 let mut ranges = Vec::new();
4653 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4654 for selection in &selections {
4655 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4656 let start = selection.start.saturating_sub(lookbehind);
4657 let end = selection.end + lookahead;
4658 if selection.id == newest_selection.id {
4659 range_to_replace = Some(start + common_prefix_len..end);
4660 }
4661 ranges.push(start + common_prefix_len..end);
4662 } else {
4663 common_prefix_len = 0;
4664 ranges.clear();
4665 ranges.extend(selections.iter().map(|s| {
4666 if s.id == newest_selection.id {
4667 range_to_replace = Some(old_range.clone());
4668 old_range.clone()
4669 } else {
4670 s.start..s.end
4671 }
4672 }));
4673 break;
4674 }
4675 if !self.linked_edit_ranges.is_empty() {
4676 let start_anchor = snapshot.anchor_before(selection.head());
4677 let end_anchor = snapshot.anchor_after(selection.tail());
4678 if let Some(ranges) = self
4679 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4680 {
4681 for (buffer, edits) in ranges {
4682 linked_edits.entry(buffer.clone()).or_default().extend(
4683 edits
4684 .into_iter()
4685 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4686 );
4687 }
4688 }
4689 }
4690 }
4691 let text = &new_text[common_prefix_len..];
4692
4693 let utf16_range_to_replace = range_to_replace.map(|range| {
4694 let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
4695 let selection_start_utf16 = newest_selection.start.0 as isize;
4696
4697 range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4698 ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4699 });
4700 cx.emit(EditorEvent::InputHandled {
4701 utf16_range_to_replace,
4702 text: text.into(),
4703 });
4704
4705 self.transact(window, cx, |this, window, cx| {
4706 if let Some(mut snippet) = snippet {
4707 snippet.text = text.to_string();
4708 for tabstop in snippet
4709 .tabstops
4710 .iter_mut()
4711 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4712 {
4713 tabstop.start -= common_prefix_len as isize;
4714 tabstop.end -= common_prefix_len as isize;
4715 }
4716
4717 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4718 } else {
4719 this.buffer.update(cx, |buffer, cx| {
4720 let edits = ranges.iter().map(|range| (range.clone(), text));
4721 let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
4722 {
4723 None
4724 } else {
4725 this.autoindent_mode.clone()
4726 };
4727 buffer.edit(edits, auto_indent, cx);
4728 });
4729 }
4730 for (buffer, edits) in linked_edits {
4731 buffer.update(cx, |buffer, cx| {
4732 let snapshot = buffer.snapshot();
4733 let edits = edits
4734 .into_iter()
4735 .map(|(range, text)| {
4736 use text::ToPoint as TP;
4737 let end_point = TP::to_point(&range.end, &snapshot);
4738 let start_point = TP::to_point(&range.start, &snapshot);
4739 (start_point..end_point, text)
4740 })
4741 .sorted_by_key(|(range, _)| range.start);
4742 buffer.edit(edits, None, cx);
4743 })
4744 }
4745
4746 this.refresh_inline_completion(true, false, window, cx);
4747 });
4748
4749 let show_new_completions_on_confirm = completion
4750 .confirm
4751 .as_ref()
4752 .map_or(false, |confirm| confirm(intent, window, cx));
4753 if show_new_completions_on_confirm {
4754 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4755 }
4756
4757 let provider = self.completion_provider.as_ref()?;
4758 drop(completion);
4759 let apply_edits = provider.apply_additional_edits_for_completion(
4760 buffer_handle,
4761 completions_menu.completions.clone(),
4762 candidate_id,
4763 true,
4764 cx,
4765 );
4766
4767 let editor_settings = EditorSettings::get_global(cx);
4768 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4769 // After the code completion is finished, users often want to know what signatures are needed.
4770 // so we should automatically call signature_help
4771 self.show_signature_help(&ShowSignatureHelp, window, cx);
4772 }
4773
4774 Some(cx.foreground_executor().spawn(async move {
4775 apply_edits.await?;
4776 Ok(())
4777 }))
4778 }
4779
4780 pub fn toggle_code_actions(
4781 &mut self,
4782 action: &ToggleCodeActions,
4783 window: &mut Window,
4784 cx: &mut Context<Self>,
4785 ) {
4786 let mut context_menu = self.context_menu.borrow_mut();
4787 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4788 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4789 // Toggle if we're selecting the same one
4790 *context_menu = None;
4791 cx.notify();
4792 return;
4793 } else {
4794 // Otherwise, clear it and start a new one
4795 *context_menu = None;
4796 cx.notify();
4797 }
4798 }
4799 drop(context_menu);
4800 let snapshot = self.snapshot(window, cx);
4801 let deployed_from_indicator = action.deployed_from_indicator;
4802 let mut task = self.code_actions_task.take();
4803 let action = action.clone();
4804 cx.spawn_in(window, async move |editor, cx| {
4805 while let Some(prev_task) = task {
4806 prev_task.await.log_err();
4807 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4808 }
4809
4810 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4811 if editor.focus_handle.is_focused(window) {
4812 let multibuffer_point = action
4813 .deployed_from_indicator
4814 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4815 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4816 let (buffer, buffer_row) = snapshot
4817 .buffer_snapshot
4818 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4819 .and_then(|(buffer_snapshot, range)| {
4820 editor
4821 .buffer
4822 .read(cx)
4823 .buffer(buffer_snapshot.remote_id())
4824 .map(|buffer| (buffer, range.start.row))
4825 })?;
4826 let (_, code_actions) = editor
4827 .available_code_actions
4828 .clone()
4829 .and_then(|(location, code_actions)| {
4830 let snapshot = location.buffer.read(cx).snapshot();
4831 let point_range = location.range.to_point(&snapshot);
4832 let point_range = point_range.start.row..=point_range.end.row;
4833 if point_range.contains(&buffer_row) {
4834 Some((location, code_actions))
4835 } else {
4836 None
4837 }
4838 })
4839 .unzip();
4840 let buffer_id = buffer.read(cx).remote_id();
4841 let tasks = editor
4842 .tasks
4843 .get(&(buffer_id, buffer_row))
4844 .map(|t| Arc::new(t.to_owned()));
4845 if tasks.is_none() && code_actions.is_none() {
4846 return None;
4847 }
4848
4849 editor.completion_tasks.clear();
4850 editor.discard_inline_completion(false, cx);
4851 let task_context =
4852 tasks
4853 .as_ref()
4854 .zip(editor.project.clone())
4855 .map(|(tasks, project)| {
4856 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4857 });
4858
4859 let debugger_flag = cx.has_flag::<Debugger>();
4860
4861 Some(cx.spawn_in(window, async move |editor, cx| {
4862 let task_context = match task_context {
4863 Some(task_context) => task_context.await,
4864 None => None,
4865 };
4866 let resolved_tasks =
4867 tasks.zip(task_context).map(|(tasks, task_context)| {
4868 Rc::new(ResolvedTasks {
4869 templates: tasks.resolve(&task_context).collect(),
4870 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4871 multibuffer_point.row,
4872 tasks.column,
4873 )),
4874 })
4875 });
4876 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
4877 tasks
4878 .templates
4879 .iter()
4880 .filter(|task| {
4881 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4882 debugger_flag
4883 } else {
4884 true
4885 }
4886 })
4887 .count()
4888 == 1
4889 }) && code_actions
4890 .as_ref()
4891 .map_or(true, |actions| actions.is_empty());
4892 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4893 *editor.context_menu.borrow_mut() =
4894 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4895 buffer,
4896 actions: CodeActionContents {
4897 tasks: resolved_tasks,
4898 actions: code_actions,
4899 },
4900 selected_item: Default::default(),
4901 scroll_handle: UniformListScrollHandle::default(),
4902 deployed_from_indicator,
4903 }));
4904 if spawn_straight_away {
4905 if let Some(task) = editor.confirm_code_action(
4906 &ConfirmCodeAction { item_ix: Some(0) },
4907 window,
4908 cx,
4909 ) {
4910 cx.notify();
4911 return task;
4912 }
4913 }
4914 cx.notify();
4915 Task::ready(Ok(()))
4916 }) {
4917 task.await
4918 } else {
4919 Ok(())
4920 }
4921 }))
4922 } else {
4923 Some(Task::ready(Ok(())))
4924 }
4925 })?;
4926 if let Some(task) = spawned_test_task {
4927 task.await?;
4928 }
4929
4930 Ok::<_, anyhow::Error>(())
4931 })
4932 .detach_and_log_err(cx);
4933 }
4934
4935 pub fn confirm_code_action(
4936 &mut self,
4937 action: &ConfirmCodeAction,
4938 window: &mut Window,
4939 cx: &mut Context<Self>,
4940 ) -> Option<Task<Result<()>>> {
4941 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4942
4943 let actions_menu =
4944 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4945 menu
4946 } else {
4947 return None;
4948 };
4949
4950 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4951 let action = actions_menu.actions.get(action_ix)?;
4952 let title = action.label();
4953 let buffer = actions_menu.buffer;
4954 let workspace = self.workspace()?;
4955
4956 match action {
4957 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4958 match resolved_task.task_type() {
4959 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
4960 workspace::tasks::schedule_resolved_task(
4961 workspace,
4962 task_source_kind,
4963 resolved_task,
4964 false,
4965 cx,
4966 );
4967
4968 Some(Task::ready(Ok(())))
4969 }),
4970 task::TaskType::Debug(debug_args) => {
4971 if debug_args.locator.is_some() {
4972 workspace.update(cx, |workspace, cx| {
4973 workspace::tasks::schedule_resolved_task(
4974 workspace,
4975 task_source_kind,
4976 resolved_task,
4977 false,
4978 cx,
4979 );
4980 });
4981
4982 return Some(Task::ready(Ok(())));
4983 }
4984
4985 if let Some(project) = self.project.as_ref() {
4986 project
4987 .update(cx, |project, cx| {
4988 project.start_debug_session(
4989 resolved_task.resolved_debug_adapter_config().unwrap(),
4990 cx,
4991 )
4992 })
4993 .detach_and_log_err(cx);
4994 Some(Task::ready(Ok(())))
4995 } else {
4996 Some(Task::ready(Ok(())))
4997 }
4998 }
4999 }
5000 }
5001 CodeActionsItem::CodeAction {
5002 excerpt_id,
5003 action,
5004 provider,
5005 } => {
5006 let apply_code_action =
5007 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5008 let workspace = workspace.downgrade();
5009 Some(cx.spawn_in(window, async move |editor, cx| {
5010 let project_transaction = apply_code_action.await?;
5011 Self::open_project_transaction(
5012 &editor,
5013 workspace,
5014 project_transaction,
5015 title,
5016 cx,
5017 )
5018 .await
5019 }))
5020 }
5021 }
5022 }
5023
5024 pub async fn open_project_transaction(
5025 this: &WeakEntity<Editor>,
5026 workspace: WeakEntity<Workspace>,
5027 transaction: ProjectTransaction,
5028 title: String,
5029 cx: &mut AsyncWindowContext,
5030 ) -> Result<()> {
5031 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5032 cx.update(|_, cx| {
5033 entries.sort_unstable_by_key(|(buffer, _)| {
5034 buffer.read(cx).file().map(|f| f.path().clone())
5035 });
5036 })?;
5037
5038 // If the project transaction's edits are all contained within this editor, then
5039 // avoid opening a new editor to display them.
5040
5041 if let Some((buffer, transaction)) = entries.first() {
5042 if entries.len() == 1 {
5043 let excerpt = this.update(cx, |editor, cx| {
5044 editor
5045 .buffer()
5046 .read(cx)
5047 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5048 })?;
5049 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5050 if excerpted_buffer == *buffer {
5051 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5052 let excerpt_range = excerpt_range.to_offset(buffer);
5053 buffer
5054 .edited_ranges_for_transaction::<usize>(transaction)
5055 .all(|range| {
5056 excerpt_range.start <= range.start
5057 && excerpt_range.end >= range.end
5058 })
5059 })?;
5060
5061 if all_edits_within_excerpt {
5062 return Ok(());
5063 }
5064 }
5065 }
5066 }
5067 } else {
5068 return Ok(());
5069 }
5070
5071 let mut ranges_to_highlight = Vec::new();
5072 let excerpt_buffer = cx.new(|cx| {
5073 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5074 for (buffer_handle, transaction) in &entries {
5075 let edited_ranges = buffer_handle
5076 .read(cx)
5077 .edited_ranges_for_transaction::<Point>(transaction)
5078 .collect::<Vec<_>>();
5079 let (ranges, _) = multibuffer.set_excerpts_for_path(
5080 PathKey::for_buffer(buffer_handle, cx),
5081 buffer_handle.clone(),
5082 edited_ranges,
5083 DEFAULT_MULTIBUFFER_CONTEXT,
5084 cx,
5085 );
5086
5087 ranges_to_highlight.extend(ranges);
5088 }
5089 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5090 multibuffer
5091 })?;
5092
5093 workspace.update_in(cx, |workspace, window, cx| {
5094 let project = workspace.project().clone();
5095 let editor =
5096 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5097 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5098 editor.update(cx, |editor, cx| {
5099 editor.highlight_background::<Self>(
5100 &ranges_to_highlight,
5101 |theme| theme.editor_highlighted_line_background,
5102 cx,
5103 );
5104 });
5105 })?;
5106
5107 Ok(())
5108 }
5109
5110 pub fn clear_code_action_providers(&mut self) {
5111 self.code_action_providers.clear();
5112 self.available_code_actions.take();
5113 }
5114
5115 pub fn add_code_action_provider(
5116 &mut self,
5117 provider: Rc<dyn CodeActionProvider>,
5118 window: &mut Window,
5119 cx: &mut Context<Self>,
5120 ) {
5121 if self
5122 .code_action_providers
5123 .iter()
5124 .any(|existing_provider| existing_provider.id() == provider.id())
5125 {
5126 return;
5127 }
5128
5129 self.code_action_providers.push(provider);
5130 self.refresh_code_actions(window, cx);
5131 }
5132
5133 pub fn remove_code_action_provider(
5134 &mut self,
5135 id: Arc<str>,
5136 window: &mut Window,
5137 cx: &mut Context<Self>,
5138 ) {
5139 self.code_action_providers
5140 .retain(|provider| provider.id() != id);
5141 self.refresh_code_actions(window, cx);
5142 }
5143
5144 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5145 let buffer = self.buffer.read(cx);
5146 let newest_selection = self.selections.newest_anchor().clone();
5147 if newest_selection.head().diff_base_anchor.is_some() {
5148 return None;
5149 }
5150 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5151 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5152 if start_buffer != end_buffer {
5153 return None;
5154 }
5155
5156 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5157 cx.background_executor()
5158 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5159 .await;
5160
5161 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5162 let providers = this.code_action_providers.clone();
5163 let tasks = this
5164 .code_action_providers
5165 .iter()
5166 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5167 .collect::<Vec<_>>();
5168 (providers, tasks)
5169 })?;
5170
5171 let mut actions = Vec::new();
5172 for (provider, provider_actions) in
5173 providers.into_iter().zip(future::join_all(tasks).await)
5174 {
5175 if let Some(provider_actions) = provider_actions.log_err() {
5176 actions.extend(provider_actions.into_iter().map(|action| {
5177 AvailableCodeAction {
5178 excerpt_id: newest_selection.start.excerpt_id,
5179 action,
5180 provider: provider.clone(),
5181 }
5182 }));
5183 }
5184 }
5185
5186 this.update(cx, |this, cx| {
5187 this.available_code_actions = if actions.is_empty() {
5188 None
5189 } else {
5190 Some((
5191 Location {
5192 buffer: start_buffer,
5193 range: start..end,
5194 },
5195 actions.into(),
5196 ))
5197 };
5198 cx.notify();
5199 })
5200 }));
5201 None
5202 }
5203
5204 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5205 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5206 self.show_git_blame_inline = false;
5207
5208 self.show_git_blame_inline_delay_task =
5209 Some(cx.spawn_in(window, async move |this, cx| {
5210 cx.background_executor().timer(delay).await;
5211
5212 this.update(cx, |this, cx| {
5213 this.show_git_blame_inline = true;
5214 cx.notify();
5215 })
5216 .log_err();
5217 }));
5218 }
5219 }
5220
5221 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5222 if self.pending_rename.is_some() {
5223 return None;
5224 }
5225
5226 let provider = self.semantics_provider.clone()?;
5227 let buffer = self.buffer.read(cx);
5228 let newest_selection = self.selections.newest_anchor().clone();
5229 let cursor_position = newest_selection.head();
5230 let (cursor_buffer, cursor_buffer_position) =
5231 buffer.text_anchor_for_position(cursor_position, cx)?;
5232 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5233 if cursor_buffer != tail_buffer {
5234 return None;
5235 }
5236 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5237 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5238 cx.background_executor()
5239 .timer(Duration::from_millis(debounce))
5240 .await;
5241
5242 let highlights = if let Some(highlights) = cx
5243 .update(|cx| {
5244 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5245 })
5246 .ok()
5247 .flatten()
5248 {
5249 highlights.await.log_err()
5250 } else {
5251 None
5252 };
5253
5254 if let Some(highlights) = highlights {
5255 this.update(cx, |this, cx| {
5256 if this.pending_rename.is_some() {
5257 return;
5258 }
5259
5260 let buffer_id = cursor_position.buffer_id;
5261 let buffer = this.buffer.read(cx);
5262 if !buffer
5263 .text_anchor_for_position(cursor_position, cx)
5264 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5265 {
5266 return;
5267 }
5268
5269 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5270 let mut write_ranges = Vec::new();
5271 let mut read_ranges = Vec::new();
5272 for highlight in highlights {
5273 for (excerpt_id, excerpt_range) in
5274 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5275 {
5276 let start = highlight
5277 .range
5278 .start
5279 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5280 let end = highlight
5281 .range
5282 .end
5283 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5284 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5285 continue;
5286 }
5287
5288 let range = Anchor {
5289 buffer_id,
5290 excerpt_id,
5291 text_anchor: start,
5292 diff_base_anchor: None,
5293 }..Anchor {
5294 buffer_id,
5295 excerpt_id,
5296 text_anchor: end,
5297 diff_base_anchor: None,
5298 };
5299 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5300 write_ranges.push(range);
5301 } else {
5302 read_ranges.push(range);
5303 }
5304 }
5305 }
5306
5307 this.highlight_background::<DocumentHighlightRead>(
5308 &read_ranges,
5309 |theme| theme.editor_document_highlight_read_background,
5310 cx,
5311 );
5312 this.highlight_background::<DocumentHighlightWrite>(
5313 &write_ranges,
5314 |theme| theme.editor_document_highlight_write_background,
5315 cx,
5316 );
5317 cx.notify();
5318 })
5319 .log_err();
5320 }
5321 }));
5322 None
5323 }
5324
5325 pub fn refresh_selected_text_highlights(
5326 &mut self,
5327 window: &mut Window,
5328 cx: &mut Context<Editor>,
5329 ) {
5330 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5331 return;
5332 }
5333 self.selection_highlight_task.take();
5334 if !EditorSettings::get_global(cx).selection_highlight {
5335 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5336 return;
5337 }
5338 if self.selections.count() != 1 || self.selections.line_mode {
5339 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5340 return;
5341 }
5342 let selection = self.selections.newest::<Point>(cx);
5343 if selection.is_empty() || selection.start.row != selection.end.row {
5344 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5345 return;
5346 }
5347 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5348 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5349 cx.background_executor()
5350 .timer(Duration::from_millis(debounce))
5351 .await;
5352 let Some(Some(matches_task)) = editor
5353 .update_in(cx, |editor, _, cx| {
5354 if editor.selections.count() != 1 || editor.selections.line_mode {
5355 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5356 return None;
5357 }
5358 let selection = editor.selections.newest::<Point>(cx);
5359 if selection.is_empty() || selection.start.row != selection.end.row {
5360 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5361 return None;
5362 }
5363 let buffer = editor.buffer().read(cx).snapshot(cx);
5364 let query = buffer.text_for_range(selection.range()).collect::<String>();
5365 if query.trim().is_empty() {
5366 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5367 return None;
5368 }
5369 Some(cx.background_spawn(async move {
5370 let mut ranges = Vec::new();
5371 let selection_anchors = selection.range().to_anchors(&buffer);
5372 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5373 for (search_buffer, search_range, excerpt_id) in
5374 buffer.range_to_buffer_ranges(range)
5375 {
5376 ranges.extend(
5377 project::search::SearchQuery::text(
5378 query.clone(),
5379 false,
5380 false,
5381 false,
5382 Default::default(),
5383 Default::default(),
5384 None,
5385 )
5386 .unwrap()
5387 .search(search_buffer, Some(search_range.clone()))
5388 .await
5389 .into_iter()
5390 .filter_map(
5391 |match_range| {
5392 let start = search_buffer.anchor_after(
5393 search_range.start + match_range.start,
5394 );
5395 let end = search_buffer.anchor_before(
5396 search_range.start + match_range.end,
5397 );
5398 let range = Anchor::range_in_buffer(
5399 excerpt_id,
5400 search_buffer.remote_id(),
5401 start..end,
5402 );
5403 (range != selection_anchors).then_some(range)
5404 },
5405 ),
5406 );
5407 }
5408 }
5409 ranges
5410 }))
5411 })
5412 .log_err()
5413 else {
5414 return;
5415 };
5416 let matches = matches_task.await;
5417 editor
5418 .update_in(cx, |editor, _, cx| {
5419 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5420 if !matches.is_empty() {
5421 editor.highlight_background::<SelectedTextHighlight>(
5422 &matches,
5423 |theme| theme.editor_document_highlight_bracket_background,
5424 cx,
5425 )
5426 }
5427 })
5428 .log_err();
5429 }));
5430 }
5431
5432 pub fn refresh_inline_completion(
5433 &mut self,
5434 debounce: bool,
5435 user_requested: bool,
5436 window: &mut Window,
5437 cx: &mut Context<Self>,
5438 ) -> Option<()> {
5439 let provider = self.edit_prediction_provider()?;
5440 let cursor = self.selections.newest_anchor().head();
5441 let (buffer, cursor_buffer_position) =
5442 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5443
5444 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5445 self.discard_inline_completion(false, cx);
5446 return None;
5447 }
5448
5449 if !user_requested
5450 && (!self.should_show_edit_predictions()
5451 || !self.is_focused(window)
5452 || buffer.read(cx).is_empty())
5453 {
5454 self.discard_inline_completion(false, cx);
5455 return None;
5456 }
5457
5458 self.update_visible_inline_completion(window, cx);
5459 provider.refresh(
5460 self.project.clone(),
5461 buffer,
5462 cursor_buffer_position,
5463 debounce,
5464 cx,
5465 );
5466 Some(())
5467 }
5468
5469 fn show_edit_predictions_in_menu(&self) -> bool {
5470 match self.edit_prediction_settings {
5471 EditPredictionSettings::Disabled => false,
5472 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5473 }
5474 }
5475
5476 pub fn edit_predictions_enabled(&self) -> bool {
5477 match self.edit_prediction_settings {
5478 EditPredictionSettings::Disabled => false,
5479 EditPredictionSettings::Enabled { .. } => true,
5480 }
5481 }
5482
5483 fn edit_prediction_requires_modifier(&self) -> bool {
5484 match self.edit_prediction_settings {
5485 EditPredictionSettings::Disabled => false,
5486 EditPredictionSettings::Enabled {
5487 preview_requires_modifier,
5488 ..
5489 } => preview_requires_modifier,
5490 }
5491 }
5492
5493 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5494 if self.edit_prediction_provider.is_none() {
5495 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5496 } else {
5497 let selection = self.selections.newest_anchor();
5498 let cursor = selection.head();
5499
5500 if let Some((buffer, cursor_buffer_position)) =
5501 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5502 {
5503 self.edit_prediction_settings =
5504 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5505 }
5506 }
5507 }
5508
5509 fn edit_prediction_settings_at_position(
5510 &self,
5511 buffer: &Entity<Buffer>,
5512 buffer_position: language::Anchor,
5513 cx: &App,
5514 ) -> EditPredictionSettings {
5515 if self.mode != EditorMode::Full
5516 || !self.show_inline_completions_override.unwrap_or(true)
5517 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5518 {
5519 return EditPredictionSettings::Disabled;
5520 }
5521
5522 let buffer = buffer.read(cx);
5523
5524 let file = buffer.file();
5525
5526 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5527 return EditPredictionSettings::Disabled;
5528 };
5529
5530 let by_provider = matches!(
5531 self.menu_inline_completions_policy,
5532 MenuInlineCompletionsPolicy::ByProvider
5533 );
5534
5535 let show_in_menu = by_provider
5536 && self
5537 .edit_prediction_provider
5538 .as_ref()
5539 .map_or(false, |provider| {
5540 provider.provider.show_completions_in_menu()
5541 });
5542
5543 let preview_requires_modifier =
5544 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5545
5546 EditPredictionSettings::Enabled {
5547 show_in_menu,
5548 preview_requires_modifier,
5549 }
5550 }
5551
5552 fn should_show_edit_predictions(&self) -> bool {
5553 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5554 }
5555
5556 pub fn edit_prediction_preview_is_active(&self) -> bool {
5557 matches!(
5558 self.edit_prediction_preview,
5559 EditPredictionPreview::Active { .. }
5560 )
5561 }
5562
5563 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5564 let cursor = self.selections.newest_anchor().head();
5565 if let Some((buffer, cursor_position)) =
5566 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5567 {
5568 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5569 } else {
5570 false
5571 }
5572 }
5573
5574 fn edit_predictions_enabled_in_buffer(
5575 &self,
5576 buffer: &Entity<Buffer>,
5577 buffer_position: language::Anchor,
5578 cx: &App,
5579 ) -> bool {
5580 maybe!({
5581 if self.read_only(cx) {
5582 return Some(false);
5583 }
5584 let provider = self.edit_prediction_provider()?;
5585 if !provider.is_enabled(&buffer, buffer_position, cx) {
5586 return Some(false);
5587 }
5588 let buffer = buffer.read(cx);
5589 let Some(file) = buffer.file() else {
5590 return Some(true);
5591 };
5592 let settings = all_language_settings(Some(file), cx);
5593 Some(settings.edit_predictions_enabled_for_file(file, cx))
5594 })
5595 .unwrap_or(false)
5596 }
5597
5598 fn cycle_inline_completion(
5599 &mut self,
5600 direction: Direction,
5601 window: &mut Window,
5602 cx: &mut Context<Self>,
5603 ) -> Option<()> {
5604 let provider = self.edit_prediction_provider()?;
5605 let cursor = self.selections.newest_anchor().head();
5606 let (buffer, cursor_buffer_position) =
5607 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5608 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5609 return None;
5610 }
5611
5612 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5613 self.update_visible_inline_completion(window, cx);
5614
5615 Some(())
5616 }
5617
5618 pub fn show_inline_completion(
5619 &mut self,
5620 _: &ShowEditPrediction,
5621 window: &mut Window,
5622 cx: &mut Context<Self>,
5623 ) {
5624 if !self.has_active_inline_completion() {
5625 self.refresh_inline_completion(false, true, window, cx);
5626 return;
5627 }
5628
5629 self.update_visible_inline_completion(window, cx);
5630 }
5631
5632 pub fn display_cursor_names(
5633 &mut self,
5634 _: &DisplayCursorNames,
5635 window: &mut Window,
5636 cx: &mut Context<Self>,
5637 ) {
5638 self.show_cursor_names(window, cx);
5639 }
5640
5641 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5642 self.show_cursor_names = true;
5643 cx.notify();
5644 cx.spawn_in(window, async move |this, cx| {
5645 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5646 this.update(cx, |this, cx| {
5647 this.show_cursor_names = false;
5648 cx.notify()
5649 })
5650 .ok()
5651 })
5652 .detach();
5653 }
5654
5655 pub fn next_edit_prediction(
5656 &mut self,
5657 _: &NextEditPrediction,
5658 window: &mut Window,
5659 cx: &mut Context<Self>,
5660 ) {
5661 if self.has_active_inline_completion() {
5662 self.cycle_inline_completion(Direction::Next, window, cx);
5663 } else {
5664 let is_copilot_disabled = self
5665 .refresh_inline_completion(false, true, window, cx)
5666 .is_none();
5667 if is_copilot_disabled {
5668 cx.propagate();
5669 }
5670 }
5671 }
5672
5673 pub fn previous_edit_prediction(
5674 &mut self,
5675 _: &PreviousEditPrediction,
5676 window: &mut Window,
5677 cx: &mut Context<Self>,
5678 ) {
5679 if self.has_active_inline_completion() {
5680 self.cycle_inline_completion(Direction::Prev, window, cx);
5681 } else {
5682 let is_copilot_disabled = self
5683 .refresh_inline_completion(false, true, window, cx)
5684 .is_none();
5685 if is_copilot_disabled {
5686 cx.propagate();
5687 }
5688 }
5689 }
5690
5691 pub fn accept_edit_prediction(
5692 &mut self,
5693 _: &AcceptEditPrediction,
5694 window: &mut Window,
5695 cx: &mut Context<Self>,
5696 ) {
5697 if self.show_edit_predictions_in_menu() {
5698 self.hide_context_menu(window, cx);
5699 }
5700
5701 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5702 return;
5703 };
5704
5705 self.report_inline_completion_event(
5706 active_inline_completion.completion_id.clone(),
5707 true,
5708 cx,
5709 );
5710
5711 match &active_inline_completion.completion {
5712 InlineCompletion::Move { target, .. } => {
5713 let target = *target;
5714
5715 if let Some(position_map) = &self.last_position_map {
5716 if position_map
5717 .visible_row_range
5718 .contains(&target.to_display_point(&position_map.snapshot).row())
5719 || !self.edit_prediction_requires_modifier()
5720 {
5721 self.unfold_ranges(&[target..target], true, false, cx);
5722 // Note that this is also done in vim's handler of the Tab action.
5723 self.change_selections(
5724 Some(Autoscroll::newest()),
5725 window,
5726 cx,
5727 |selections| {
5728 selections.select_anchor_ranges([target..target]);
5729 },
5730 );
5731 self.clear_row_highlights::<EditPredictionPreview>();
5732
5733 self.edit_prediction_preview
5734 .set_previous_scroll_position(None);
5735 } else {
5736 self.edit_prediction_preview
5737 .set_previous_scroll_position(Some(
5738 position_map.snapshot.scroll_anchor,
5739 ));
5740
5741 self.highlight_rows::<EditPredictionPreview>(
5742 target..target,
5743 cx.theme().colors().editor_highlighted_line_background,
5744 true,
5745 cx,
5746 );
5747 self.request_autoscroll(Autoscroll::fit(), cx);
5748 }
5749 }
5750 }
5751 InlineCompletion::Edit { edits, .. } => {
5752 if let Some(provider) = self.edit_prediction_provider() {
5753 provider.accept(cx);
5754 }
5755
5756 let snapshot = self.buffer.read(cx).snapshot(cx);
5757 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5758
5759 self.buffer.update(cx, |buffer, cx| {
5760 buffer.edit(edits.iter().cloned(), None, cx)
5761 });
5762
5763 self.change_selections(None, window, cx, |s| {
5764 s.select_anchor_ranges([last_edit_end..last_edit_end])
5765 });
5766
5767 self.update_visible_inline_completion(window, cx);
5768 if self.active_inline_completion.is_none() {
5769 self.refresh_inline_completion(true, true, window, cx);
5770 }
5771
5772 cx.notify();
5773 }
5774 }
5775
5776 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5777 }
5778
5779 pub fn accept_partial_inline_completion(
5780 &mut self,
5781 _: &AcceptPartialEditPrediction,
5782 window: &mut Window,
5783 cx: &mut Context<Self>,
5784 ) {
5785 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5786 return;
5787 };
5788 if self.selections.count() != 1 {
5789 return;
5790 }
5791
5792 self.report_inline_completion_event(
5793 active_inline_completion.completion_id.clone(),
5794 true,
5795 cx,
5796 );
5797
5798 match &active_inline_completion.completion {
5799 InlineCompletion::Move { target, .. } => {
5800 let target = *target;
5801 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5802 selections.select_anchor_ranges([target..target]);
5803 });
5804 }
5805 InlineCompletion::Edit { edits, .. } => {
5806 // Find an insertion that starts at the cursor position.
5807 let snapshot = self.buffer.read(cx).snapshot(cx);
5808 let cursor_offset = self.selections.newest::<usize>(cx).head();
5809 let insertion = edits.iter().find_map(|(range, text)| {
5810 let range = range.to_offset(&snapshot);
5811 if range.is_empty() && range.start == cursor_offset {
5812 Some(text)
5813 } else {
5814 None
5815 }
5816 });
5817
5818 if let Some(text) = insertion {
5819 let mut partial_completion = text
5820 .chars()
5821 .by_ref()
5822 .take_while(|c| c.is_alphabetic())
5823 .collect::<String>();
5824 if partial_completion.is_empty() {
5825 partial_completion = text
5826 .chars()
5827 .by_ref()
5828 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5829 .collect::<String>();
5830 }
5831
5832 cx.emit(EditorEvent::InputHandled {
5833 utf16_range_to_replace: None,
5834 text: partial_completion.clone().into(),
5835 });
5836
5837 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5838
5839 self.refresh_inline_completion(true, true, window, cx);
5840 cx.notify();
5841 } else {
5842 self.accept_edit_prediction(&Default::default(), window, cx);
5843 }
5844 }
5845 }
5846 }
5847
5848 fn discard_inline_completion(
5849 &mut self,
5850 should_report_inline_completion_event: bool,
5851 cx: &mut Context<Self>,
5852 ) -> bool {
5853 if should_report_inline_completion_event {
5854 let completion_id = self
5855 .active_inline_completion
5856 .as_ref()
5857 .and_then(|active_completion| active_completion.completion_id.clone());
5858
5859 self.report_inline_completion_event(completion_id, false, cx);
5860 }
5861
5862 if let Some(provider) = self.edit_prediction_provider() {
5863 provider.discard(cx);
5864 }
5865
5866 self.take_active_inline_completion(cx)
5867 }
5868
5869 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5870 let Some(provider) = self.edit_prediction_provider() else {
5871 return;
5872 };
5873
5874 let Some((_, buffer, _)) = self
5875 .buffer
5876 .read(cx)
5877 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5878 else {
5879 return;
5880 };
5881
5882 let extension = buffer
5883 .read(cx)
5884 .file()
5885 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5886
5887 let event_type = match accepted {
5888 true => "Edit Prediction Accepted",
5889 false => "Edit Prediction Discarded",
5890 };
5891 telemetry::event!(
5892 event_type,
5893 provider = provider.name(),
5894 prediction_id = id,
5895 suggestion_accepted = accepted,
5896 file_extension = extension,
5897 );
5898 }
5899
5900 pub fn has_active_inline_completion(&self) -> bool {
5901 self.active_inline_completion.is_some()
5902 }
5903
5904 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5905 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5906 return false;
5907 };
5908
5909 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5910 self.clear_highlights::<InlineCompletionHighlight>(cx);
5911 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5912 true
5913 }
5914
5915 /// Returns true when we're displaying the edit prediction popover below the cursor
5916 /// like we are not previewing and the LSP autocomplete menu is visible
5917 /// or we are in `when_holding_modifier` mode.
5918 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5919 if self.edit_prediction_preview_is_active()
5920 || !self.show_edit_predictions_in_menu()
5921 || !self.edit_predictions_enabled()
5922 {
5923 return false;
5924 }
5925
5926 if self.has_visible_completions_menu() {
5927 return true;
5928 }
5929
5930 has_completion && self.edit_prediction_requires_modifier()
5931 }
5932
5933 fn handle_modifiers_changed(
5934 &mut self,
5935 modifiers: Modifiers,
5936 position_map: &PositionMap,
5937 window: &mut Window,
5938 cx: &mut Context<Self>,
5939 ) {
5940 if self.show_edit_predictions_in_menu() {
5941 self.update_edit_prediction_preview(&modifiers, window, cx);
5942 }
5943
5944 self.update_selection_mode(&modifiers, position_map, window, cx);
5945
5946 let mouse_position = window.mouse_position();
5947 if !position_map.text_hitbox.is_hovered(window) {
5948 return;
5949 }
5950
5951 self.update_hovered_link(
5952 position_map.point_for_position(mouse_position),
5953 &position_map.snapshot,
5954 modifiers,
5955 window,
5956 cx,
5957 )
5958 }
5959
5960 fn update_selection_mode(
5961 &mut self,
5962 modifiers: &Modifiers,
5963 position_map: &PositionMap,
5964 window: &mut Window,
5965 cx: &mut Context<Self>,
5966 ) {
5967 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5968 return;
5969 }
5970
5971 let mouse_position = window.mouse_position();
5972 let point_for_position = position_map.point_for_position(mouse_position);
5973 let position = point_for_position.previous_valid;
5974
5975 self.select(
5976 SelectPhase::BeginColumnar {
5977 position,
5978 reset: false,
5979 goal_column: point_for_position.exact_unclipped.column(),
5980 },
5981 window,
5982 cx,
5983 );
5984 }
5985
5986 fn update_edit_prediction_preview(
5987 &mut self,
5988 modifiers: &Modifiers,
5989 window: &mut Window,
5990 cx: &mut Context<Self>,
5991 ) {
5992 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5993 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5994 return;
5995 };
5996
5997 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5998 if matches!(
5999 self.edit_prediction_preview,
6000 EditPredictionPreview::Inactive { .. }
6001 ) {
6002 self.edit_prediction_preview = EditPredictionPreview::Active {
6003 previous_scroll_position: None,
6004 since: Instant::now(),
6005 };
6006
6007 self.update_visible_inline_completion(window, cx);
6008 cx.notify();
6009 }
6010 } else if let EditPredictionPreview::Active {
6011 previous_scroll_position,
6012 since,
6013 } = self.edit_prediction_preview
6014 {
6015 if let (Some(previous_scroll_position), Some(position_map)) =
6016 (previous_scroll_position, self.last_position_map.as_ref())
6017 {
6018 self.set_scroll_position(
6019 previous_scroll_position
6020 .scroll_position(&position_map.snapshot.display_snapshot),
6021 window,
6022 cx,
6023 );
6024 }
6025
6026 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6027 released_too_fast: since.elapsed() < Duration::from_millis(200),
6028 };
6029 self.clear_row_highlights::<EditPredictionPreview>();
6030 self.update_visible_inline_completion(window, cx);
6031 cx.notify();
6032 }
6033 }
6034
6035 fn update_visible_inline_completion(
6036 &mut self,
6037 _window: &mut Window,
6038 cx: &mut Context<Self>,
6039 ) -> Option<()> {
6040 let selection = self.selections.newest_anchor();
6041 let cursor = selection.head();
6042 let multibuffer = self.buffer.read(cx).snapshot(cx);
6043 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6044 let excerpt_id = cursor.excerpt_id;
6045
6046 let show_in_menu = self.show_edit_predictions_in_menu();
6047 let completions_menu_has_precedence = !show_in_menu
6048 && (self.context_menu.borrow().is_some()
6049 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6050
6051 if completions_menu_has_precedence
6052 || !offset_selection.is_empty()
6053 || self
6054 .active_inline_completion
6055 .as_ref()
6056 .map_or(false, |completion| {
6057 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6058 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6059 !invalidation_range.contains(&offset_selection.head())
6060 })
6061 {
6062 self.discard_inline_completion(false, cx);
6063 return None;
6064 }
6065
6066 self.take_active_inline_completion(cx);
6067 let Some(provider) = self.edit_prediction_provider() else {
6068 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6069 return None;
6070 };
6071
6072 let (buffer, cursor_buffer_position) =
6073 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6074
6075 self.edit_prediction_settings =
6076 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6077
6078 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6079
6080 if self.edit_prediction_indent_conflict {
6081 let cursor_point = cursor.to_point(&multibuffer);
6082
6083 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6084
6085 if let Some((_, indent)) = indents.iter().next() {
6086 if indent.len == cursor_point.column {
6087 self.edit_prediction_indent_conflict = false;
6088 }
6089 }
6090 }
6091
6092 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6093 let edits = inline_completion
6094 .edits
6095 .into_iter()
6096 .flat_map(|(range, new_text)| {
6097 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6098 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6099 Some((start..end, new_text))
6100 })
6101 .collect::<Vec<_>>();
6102 if edits.is_empty() {
6103 return None;
6104 }
6105
6106 let first_edit_start = edits.first().unwrap().0.start;
6107 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6108 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6109
6110 let last_edit_end = edits.last().unwrap().0.end;
6111 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6112 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6113
6114 let cursor_row = cursor.to_point(&multibuffer).row;
6115
6116 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6117
6118 let mut inlay_ids = Vec::new();
6119 let invalidation_row_range;
6120 let move_invalidation_row_range = if cursor_row < edit_start_row {
6121 Some(cursor_row..edit_end_row)
6122 } else if cursor_row > edit_end_row {
6123 Some(edit_start_row..cursor_row)
6124 } else {
6125 None
6126 };
6127 let is_move =
6128 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6129 let completion = if is_move {
6130 invalidation_row_range =
6131 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6132 let target = first_edit_start;
6133 InlineCompletion::Move { target, snapshot }
6134 } else {
6135 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6136 && !self.inline_completions_hidden_for_vim_mode;
6137
6138 if show_completions_in_buffer {
6139 if edits
6140 .iter()
6141 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6142 {
6143 let mut inlays = Vec::new();
6144 for (range, new_text) in &edits {
6145 let inlay = Inlay::inline_completion(
6146 post_inc(&mut self.next_inlay_id),
6147 range.start,
6148 new_text.as_str(),
6149 );
6150 inlay_ids.push(inlay.id);
6151 inlays.push(inlay);
6152 }
6153
6154 self.splice_inlays(&[], inlays, cx);
6155 } else {
6156 let background_color = cx.theme().status().deleted_background;
6157 self.highlight_text::<InlineCompletionHighlight>(
6158 edits.iter().map(|(range, _)| range.clone()).collect(),
6159 HighlightStyle {
6160 background_color: Some(background_color),
6161 ..Default::default()
6162 },
6163 cx,
6164 );
6165 }
6166 }
6167
6168 invalidation_row_range = edit_start_row..edit_end_row;
6169
6170 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6171 if provider.show_tab_accept_marker() {
6172 EditDisplayMode::TabAccept
6173 } else {
6174 EditDisplayMode::Inline
6175 }
6176 } else {
6177 EditDisplayMode::DiffPopover
6178 };
6179
6180 InlineCompletion::Edit {
6181 edits,
6182 edit_preview: inline_completion.edit_preview,
6183 display_mode,
6184 snapshot,
6185 }
6186 };
6187
6188 let invalidation_range = multibuffer
6189 .anchor_before(Point::new(invalidation_row_range.start, 0))
6190 ..multibuffer.anchor_after(Point::new(
6191 invalidation_row_range.end,
6192 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6193 ));
6194
6195 self.stale_inline_completion_in_menu = None;
6196 self.active_inline_completion = Some(InlineCompletionState {
6197 inlay_ids,
6198 completion,
6199 completion_id: inline_completion.id,
6200 invalidation_range,
6201 });
6202
6203 cx.notify();
6204
6205 Some(())
6206 }
6207
6208 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6209 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6210 }
6211
6212 fn render_code_actions_indicator(
6213 &self,
6214 _style: &EditorStyle,
6215 row: DisplayRow,
6216 is_active: bool,
6217 breakpoint: Option<&(Anchor, Breakpoint)>,
6218 cx: &mut Context<Self>,
6219 ) -> Option<IconButton> {
6220 let color = Color::Muted;
6221 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6222 let show_tooltip = !self.context_menu_visible();
6223
6224 if self.available_code_actions.is_some() {
6225 Some(
6226 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6227 .shape(ui::IconButtonShape::Square)
6228 .icon_size(IconSize::XSmall)
6229 .icon_color(color)
6230 .toggle_state(is_active)
6231 .when(show_tooltip, |this| {
6232 this.tooltip({
6233 let focus_handle = self.focus_handle.clone();
6234 move |window, cx| {
6235 Tooltip::for_action_in(
6236 "Toggle Code Actions",
6237 &ToggleCodeActions {
6238 deployed_from_indicator: None,
6239 },
6240 &focus_handle,
6241 window,
6242 cx,
6243 )
6244 }
6245 })
6246 })
6247 .on_click(cx.listener(move |editor, _e, window, cx| {
6248 window.focus(&editor.focus_handle(cx));
6249 editor.toggle_code_actions(
6250 &ToggleCodeActions {
6251 deployed_from_indicator: Some(row),
6252 },
6253 window,
6254 cx,
6255 );
6256 }))
6257 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6258 editor.set_breakpoint_context_menu(
6259 row,
6260 position,
6261 event.down.position,
6262 window,
6263 cx,
6264 );
6265 })),
6266 )
6267 } else {
6268 None
6269 }
6270 }
6271
6272 fn clear_tasks(&mut self) {
6273 self.tasks.clear()
6274 }
6275
6276 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6277 if self.tasks.insert(key, value).is_some() {
6278 // This case should hopefully be rare, but just in case...
6279 log::error!(
6280 "multiple different run targets found on a single line, only the last target will be rendered"
6281 )
6282 }
6283 }
6284
6285 /// Get all display points of breakpoints that will be rendered within editor
6286 ///
6287 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6288 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6289 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6290 fn active_breakpoints(
6291 &self,
6292 range: Range<DisplayRow>,
6293 window: &mut Window,
6294 cx: &mut Context<Self>,
6295 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6296 let mut breakpoint_display_points = HashMap::default();
6297
6298 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6299 return breakpoint_display_points;
6300 };
6301
6302 let snapshot = self.snapshot(window, cx);
6303
6304 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6305 let Some(project) = self.project.as_ref() else {
6306 return breakpoint_display_points;
6307 };
6308
6309 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6310 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6311
6312 for (buffer_snapshot, range, excerpt_id) in
6313 multi_buffer_snapshot.range_to_buffer_ranges(range)
6314 {
6315 let Some(buffer) = project.read_with(cx, |this, cx| {
6316 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6317 }) else {
6318 continue;
6319 };
6320 let breakpoints = breakpoint_store.read(cx).breakpoints(
6321 &buffer,
6322 Some(
6323 buffer_snapshot.anchor_before(range.start)
6324 ..buffer_snapshot.anchor_after(range.end),
6325 ),
6326 buffer_snapshot,
6327 cx,
6328 );
6329 for (anchor, breakpoint) in breakpoints {
6330 let multi_buffer_anchor =
6331 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6332 let position = multi_buffer_anchor
6333 .to_point(&multi_buffer_snapshot)
6334 .to_display_point(&snapshot);
6335
6336 breakpoint_display_points
6337 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6338 }
6339 }
6340
6341 breakpoint_display_points
6342 }
6343
6344 fn breakpoint_context_menu(
6345 &self,
6346 anchor: Anchor,
6347 window: &mut Window,
6348 cx: &mut Context<Self>,
6349 ) -> Entity<ui::ContextMenu> {
6350 let weak_editor = cx.weak_entity();
6351 let focus_handle = self.focus_handle(cx);
6352
6353 let row = self
6354 .buffer
6355 .read(cx)
6356 .snapshot(cx)
6357 .summary_for_anchor::<Point>(&anchor)
6358 .row;
6359
6360 let breakpoint = self
6361 .breakpoint_at_row(row, window, cx)
6362 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6363
6364 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6365 "Edit Log Breakpoint"
6366 } else {
6367 "Set Log Breakpoint"
6368 };
6369
6370 let condition_breakpoint_msg = if breakpoint
6371 .as_ref()
6372 .is_some_and(|bp| bp.1.condition.is_some())
6373 {
6374 "Edit Condition Breakpoint"
6375 } else {
6376 "Set Condition Breakpoint"
6377 };
6378
6379 let hit_condition_breakpoint_msg = if breakpoint
6380 .as_ref()
6381 .is_some_and(|bp| bp.1.hit_condition.is_some())
6382 {
6383 "Edit Hit Condition Breakpoint"
6384 } else {
6385 "Set Hit Condition Breakpoint"
6386 };
6387
6388 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6389 "Unset Breakpoint"
6390 } else {
6391 "Set Breakpoint"
6392 };
6393
6394 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6395 BreakpointState::Enabled => Some("Disable"),
6396 BreakpointState::Disabled => Some("Enable"),
6397 });
6398
6399 let (anchor, breakpoint) =
6400 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6401
6402 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6403 menu.on_blur_subscription(Subscription::new(|| {}))
6404 .context(focus_handle)
6405 .when_some(toggle_state_msg, |this, msg| {
6406 this.entry(msg, None, {
6407 let weak_editor = weak_editor.clone();
6408 let breakpoint = breakpoint.clone();
6409 move |_window, cx| {
6410 weak_editor
6411 .update(cx, |this, cx| {
6412 this.edit_breakpoint_at_anchor(
6413 anchor,
6414 breakpoint.as_ref().clone(),
6415 BreakpointEditAction::InvertState,
6416 cx,
6417 );
6418 })
6419 .log_err();
6420 }
6421 })
6422 })
6423 .entry(set_breakpoint_msg, None, {
6424 let weak_editor = weak_editor.clone();
6425 let breakpoint = breakpoint.clone();
6426 move |_window, cx| {
6427 weak_editor
6428 .update(cx, |this, cx| {
6429 this.edit_breakpoint_at_anchor(
6430 anchor,
6431 breakpoint.as_ref().clone(),
6432 BreakpointEditAction::Toggle,
6433 cx,
6434 );
6435 })
6436 .log_err();
6437 }
6438 })
6439 .entry(log_breakpoint_msg, None, {
6440 let breakpoint = breakpoint.clone();
6441 let weak_editor = weak_editor.clone();
6442 move |window, cx| {
6443 weak_editor
6444 .update(cx, |this, cx| {
6445 this.add_edit_breakpoint_block(
6446 anchor,
6447 breakpoint.as_ref(),
6448 BreakpointPromptEditAction::Log,
6449 window,
6450 cx,
6451 );
6452 })
6453 .log_err();
6454 }
6455 })
6456 .entry(condition_breakpoint_msg, None, {
6457 let breakpoint = breakpoint.clone();
6458 let weak_editor = weak_editor.clone();
6459 move |window, cx| {
6460 weak_editor
6461 .update(cx, |this, cx| {
6462 this.add_edit_breakpoint_block(
6463 anchor,
6464 breakpoint.as_ref(),
6465 BreakpointPromptEditAction::Condition,
6466 window,
6467 cx,
6468 );
6469 })
6470 .log_err();
6471 }
6472 })
6473 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6474 weak_editor
6475 .update(cx, |this, cx| {
6476 this.add_edit_breakpoint_block(
6477 anchor,
6478 breakpoint.as_ref(),
6479 BreakpointPromptEditAction::HitCondition,
6480 window,
6481 cx,
6482 );
6483 })
6484 .log_err();
6485 })
6486 })
6487 }
6488
6489 fn render_breakpoint(
6490 &self,
6491 position: Anchor,
6492 row: DisplayRow,
6493 breakpoint: &Breakpoint,
6494 cx: &mut Context<Self>,
6495 ) -> IconButton {
6496 let (color, icon) = {
6497 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6498 (false, false) => ui::IconName::DebugBreakpoint,
6499 (true, false) => ui::IconName::DebugLogBreakpoint,
6500 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6501 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6502 };
6503
6504 let color = if self
6505 .gutter_breakpoint_indicator
6506 .0
6507 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6508 {
6509 Color::Hint
6510 } else {
6511 Color::Debugger
6512 };
6513
6514 (color, icon)
6515 };
6516
6517 let breakpoint = Arc::from(breakpoint.clone());
6518
6519 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6520 .icon_size(IconSize::XSmall)
6521 .size(ui::ButtonSize::None)
6522 .icon_color(color)
6523 .style(ButtonStyle::Transparent)
6524 .on_click(cx.listener({
6525 let breakpoint = breakpoint.clone();
6526
6527 move |editor, event: &ClickEvent, window, cx| {
6528 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6529 BreakpointEditAction::InvertState
6530 } else {
6531 BreakpointEditAction::Toggle
6532 };
6533
6534 window.focus(&editor.focus_handle(cx));
6535 editor.edit_breakpoint_at_anchor(
6536 position,
6537 breakpoint.as_ref().clone(),
6538 edit_action,
6539 cx,
6540 );
6541 }
6542 }))
6543 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6544 editor.set_breakpoint_context_menu(
6545 row,
6546 Some(position),
6547 event.down.position,
6548 window,
6549 cx,
6550 );
6551 }))
6552 }
6553
6554 fn build_tasks_context(
6555 project: &Entity<Project>,
6556 buffer: &Entity<Buffer>,
6557 buffer_row: u32,
6558 tasks: &Arc<RunnableTasks>,
6559 cx: &mut Context<Self>,
6560 ) -> Task<Option<task::TaskContext>> {
6561 let position = Point::new(buffer_row, tasks.column);
6562 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6563 let location = Location {
6564 buffer: buffer.clone(),
6565 range: range_start..range_start,
6566 };
6567 // Fill in the environmental variables from the tree-sitter captures
6568 let mut captured_task_variables = TaskVariables::default();
6569 for (capture_name, value) in tasks.extra_variables.clone() {
6570 captured_task_variables.insert(
6571 task::VariableName::Custom(capture_name.into()),
6572 value.clone(),
6573 );
6574 }
6575 project.update(cx, |project, cx| {
6576 project.task_store().update(cx, |task_store, cx| {
6577 task_store.task_context_for_location(captured_task_variables, location, cx)
6578 })
6579 })
6580 }
6581
6582 pub fn spawn_nearest_task(
6583 &mut self,
6584 action: &SpawnNearestTask,
6585 window: &mut Window,
6586 cx: &mut Context<Self>,
6587 ) {
6588 let Some((workspace, _)) = self.workspace.clone() else {
6589 return;
6590 };
6591 let Some(project) = self.project.clone() else {
6592 return;
6593 };
6594
6595 // Try to find a closest, enclosing node using tree-sitter that has a
6596 // task
6597 let Some((buffer, buffer_row, tasks)) = self
6598 .find_enclosing_node_task(cx)
6599 // Or find the task that's closest in row-distance.
6600 .or_else(|| self.find_closest_task(cx))
6601 else {
6602 return;
6603 };
6604
6605 let reveal_strategy = action.reveal;
6606 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6607 cx.spawn_in(window, async move |_, cx| {
6608 let context = task_context.await?;
6609 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6610
6611 let resolved = resolved_task.resolved.as_mut()?;
6612 resolved.reveal = reveal_strategy;
6613
6614 workspace
6615 .update(cx, |workspace, cx| {
6616 workspace::tasks::schedule_resolved_task(
6617 workspace,
6618 task_source_kind,
6619 resolved_task,
6620 false,
6621 cx,
6622 );
6623 })
6624 .ok()
6625 })
6626 .detach();
6627 }
6628
6629 fn find_closest_task(
6630 &mut self,
6631 cx: &mut Context<Self>,
6632 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6633 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6634
6635 let ((buffer_id, row), tasks) = self
6636 .tasks
6637 .iter()
6638 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6639
6640 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6641 let tasks = Arc::new(tasks.to_owned());
6642 Some((buffer, *row, tasks))
6643 }
6644
6645 fn find_enclosing_node_task(
6646 &mut self,
6647 cx: &mut Context<Self>,
6648 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6649 let snapshot = self.buffer.read(cx).snapshot(cx);
6650 let offset = self.selections.newest::<usize>(cx).head();
6651 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6652 let buffer_id = excerpt.buffer().remote_id();
6653
6654 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6655 let mut cursor = layer.node().walk();
6656
6657 while cursor.goto_first_child_for_byte(offset).is_some() {
6658 if cursor.node().end_byte() == offset {
6659 cursor.goto_next_sibling();
6660 }
6661 }
6662
6663 // Ascend to the smallest ancestor that contains the range and has a task.
6664 loop {
6665 let node = cursor.node();
6666 let node_range = node.byte_range();
6667 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6668
6669 // Check if this node contains our offset
6670 if node_range.start <= offset && node_range.end >= offset {
6671 // If it contains offset, check for task
6672 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6673 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6674 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6675 }
6676 }
6677
6678 if !cursor.goto_parent() {
6679 break;
6680 }
6681 }
6682 None
6683 }
6684
6685 fn render_run_indicator(
6686 &self,
6687 _style: &EditorStyle,
6688 is_active: bool,
6689 row: DisplayRow,
6690 breakpoint: Option<(Anchor, Breakpoint)>,
6691 cx: &mut Context<Self>,
6692 ) -> IconButton {
6693 let color = Color::Muted;
6694 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6695
6696 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6697 .shape(ui::IconButtonShape::Square)
6698 .icon_size(IconSize::XSmall)
6699 .icon_color(color)
6700 .toggle_state(is_active)
6701 .on_click(cx.listener(move |editor, _e, window, cx| {
6702 window.focus(&editor.focus_handle(cx));
6703 editor.toggle_code_actions(
6704 &ToggleCodeActions {
6705 deployed_from_indicator: Some(row),
6706 },
6707 window,
6708 cx,
6709 );
6710 }))
6711 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6712 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6713 }))
6714 }
6715
6716 pub fn context_menu_visible(&self) -> bool {
6717 !self.edit_prediction_preview_is_active()
6718 && self
6719 .context_menu
6720 .borrow()
6721 .as_ref()
6722 .map_or(false, |menu| menu.visible())
6723 }
6724
6725 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6726 self.context_menu
6727 .borrow()
6728 .as_ref()
6729 .map(|menu| menu.origin())
6730 }
6731
6732 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6733 self.context_menu_options = Some(options);
6734 }
6735
6736 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6737 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6738
6739 fn render_edit_prediction_popover(
6740 &mut self,
6741 text_bounds: &Bounds<Pixels>,
6742 content_origin: gpui::Point<Pixels>,
6743 editor_snapshot: &EditorSnapshot,
6744 visible_row_range: Range<DisplayRow>,
6745 scroll_top: f32,
6746 scroll_bottom: f32,
6747 line_layouts: &[LineWithInvisibles],
6748 line_height: Pixels,
6749 scroll_pixel_position: gpui::Point<Pixels>,
6750 newest_selection_head: Option<DisplayPoint>,
6751 editor_width: Pixels,
6752 style: &EditorStyle,
6753 window: &mut Window,
6754 cx: &mut App,
6755 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6756 let active_inline_completion = self.active_inline_completion.as_ref()?;
6757
6758 if self.edit_prediction_visible_in_cursor_popover(true) {
6759 return None;
6760 }
6761
6762 match &active_inline_completion.completion {
6763 InlineCompletion::Move { target, .. } => {
6764 let target_display_point = target.to_display_point(editor_snapshot);
6765
6766 if self.edit_prediction_requires_modifier() {
6767 if !self.edit_prediction_preview_is_active() {
6768 return None;
6769 }
6770
6771 self.render_edit_prediction_modifier_jump_popover(
6772 text_bounds,
6773 content_origin,
6774 visible_row_range,
6775 line_layouts,
6776 line_height,
6777 scroll_pixel_position,
6778 newest_selection_head,
6779 target_display_point,
6780 window,
6781 cx,
6782 )
6783 } else {
6784 self.render_edit_prediction_eager_jump_popover(
6785 text_bounds,
6786 content_origin,
6787 editor_snapshot,
6788 visible_row_range,
6789 scroll_top,
6790 scroll_bottom,
6791 line_height,
6792 scroll_pixel_position,
6793 target_display_point,
6794 editor_width,
6795 window,
6796 cx,
6797 )
6798 }
6799 }
6800 InlineCompletion::Edit {
6801 display_mode: EditDisplayMode::Inline,
6802 ..
6803 } => None,
6804 InlineCompletion::Edit {
6805 display_mode: EditDisplayMode::TabAccept,
6806 edits,
6807 ..
6808 } => {
6809 let range = &edits.first()?.0;
6810 let target_display_point = range.end.to_display_point(editor_snapshot);
6811
6812 self.render_edit_prediction_end_of_line_popover(
6813 "Accept",
6814 editor_snapshot,
6815 visible_row_range,
6816 target_display_point,
6817 line_height,
6818 scroll_pixel_position,
6819 content_origin,
6820 editor_width,
6821 window,
6822 cx,
6823 )
6824 }
6825 InlineCompletion::Edit {
6826 edits,
6827 edit_preview,
6828 display_mode: EditDisplayMode::DiffPopover,
6829 snapshot,
6830 } => self.render_edit_prediction_diff_popover(
6831 text_bounds,
6832 content_origin,
6833 editor_snapshot,
6834 visible_row_range,
6835 line_layouts,
6836 line_height,
6837 scroll_pixel_position,
6838 newest_selection_head,
6839 editor_width,
6840 style,
6841 edits,
6842 edit_preview,
6843 snapshot,
6844 window,
6845 cx,
6846 ),
6847 }
6848 }
6849
6850 fn render_edit_prediction_modifier_jump_popover(
6851 &mut self,
6852 text_bounds: &Bounds<Pixels>,
6853 content_origin: gpui::Point<Pixels>,
6854 visible_row_range: Range<DisplayRow>,
6855 line_layouts: &[LineWithInvisibles],
6856 line_height: Pixels,
6857 scroll_pixel_position: gpui::Point<Pixels>,
6858 newest_selection_head: Option<DisplayPoint>,
6859 target_display_point: DisplayPoint,
6860 window: &mut Window,
6861 cx: &mut App,
6862 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6863 let scrolled_content_origin =
6864 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6865
6866 const SCROLL_PADDING_Y: Pixels = px(12.);
6867
6868 if target_display_point.row() < visible_row_range.start {
6869 return self.render_edit_prediction_scroll_popover(
6870 |_| SCROLL_PADDING_Y,
6871 IconName::ArrowUp,
6872 visible_row_range,
6873 line_layouts,
6874 newest_selection_head,
6875 scrolled_content_origin,
6876 window,
6877 cx,
6878 );
6879 } else if target_display_point.row() >= visible_row_range.end {
6880 return self.render_edit_prediction_scroll_popover(
6881 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6882 IconName::ArrowDown,
6883 visible_row_range,
6884 line_layouts,
6885 newest_selection_head,
6886 scrolled_content_origin,
6887 window,
6888 cx,
6889 );
6890 }
6891
6892 const POLE_WIDTH: Pixels = px(2.);
6893
6894 let line_layout =
6895 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6896 let target_column = target_display_point.column() as usize;
6897
6898 let target_x = line_layout.x_for_index(target_column);
6899 let target_y =
6900 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6901
6902 let flag_on_right = target_x < text_bounds.size.width / 2.;
6903
6904 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6905 border_color.l += 0.001;
6906
6907 let mut element = v_flex()
6908 .items_end()
6909 .when(flag_on_right, |el| el.items_start())
6910 .child(if flag_on_right {
6911 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6912 .rounded_bl(px(0.))
6913 .rounded_tl(px(0.))
6914 .border_l_2()
6915 .border_color(border_color)
6916 } else {
6917 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6918 .rounded_br(px(0.))
6919 .rounded_tr(px(0.))
6920 .border_r_2()
6921 .border_color(border_color)
6922 })
6923 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6924 .into_any();
6925
6926 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6927
6928 let mut origin = scrolled_content_origin + point(target_x, target_y)
6929 - point(
6930 if flag_on_right {
6931 POLE_WIDTH
6932 } else {
6933 size.width - POLE_WIDTH
6934 },
6935 size.height - line_height,
6936 );
6937
6938 origin.x = origin.x.max(content_origin.x);
6939
6940 element.prepaint_at(origin, window, cx);
6941
6942 Some((element, origin))
6943 }
6944
6945 fn render_edit_prediction_scroll_popover(
6946 &mut self,
6947 to_y: impl Fn(Size<Pixels>) -> Pixels,
6948 scroll_icon: IconName,
6949 visible_row_range: Range<DisplayRow>,
6950 line_layouts: &[LineWithInvisibles],
6951 newest_selection_head: Option<DisplayPoint>,
6952 scrolled_content_origin: gpui::Point<Pixels>,
6953 window: &mut Window,
6954 cx: &mut App,
6955 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6956 let mut element = self
6957 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6958 .into_any();
6959
6960 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6961
6962 let cursor = newest_selection_head?;
6963 let cursor_row_layout =
6964 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6965 let cursor_column = cursor.column() as usize;
6966
6967 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6968
6969 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6970
6971 element.prepaint_at(origin, window, cx);
6972 Some((element, origin))
6973 }
6974
6975 fn render_edit_prediction_eager_jump_popover(
6976 &mut self,
6977 text_bounds: &Bounds<Pixels>,
6978 content_origin: gpui::Point<Pixels>,
6979 editor_snapshot: &EditorSnapshot,
6980 visible_row_range: Range<DisplayRow>,
6981 scroll_top: f32,
6982 scroll_bottom: f32,
6983 line_height: Pixels,
6984 scroll_pixel_position: gpui::Point<Pixels>,
6985 target_display_point: DisplayPoint,
6986 editor_width: Pixels,
6987 window: &mut Window,
6988 cx: &mut App,
6989 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6990 if target_display_point.row().as_f32() < scroll_top {
6991 let mut element = self
6992 .render_edit_prediction_line_popover(
6993 "Jump to Edit",
6994 Some(IconName::ArrowUp),
6995 window,
6996 cx,
6997 )?
6998 .into_any();
6999
7000 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7001 let offset = point(
7002 (text_bounds.size.width - size.width) / 2.,
7003 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7004 );
7005
7006 let origin = text_bounds.origin + offset;
7007 element.prepaint_at(origin, window, cx);
7008 Some((element, origin))
7009 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7010 let mut element = self
7011 .render_edit_prediction_line_popover(
7012 "Jump to Edit",
7013 Some(IconName::ArrowDown),
7014 window,
7015 cx,
7016 )?
7017 .into_any();
7018
7019 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7020 let offset = point(
7021 (text_bounds.size.width - size.width) / 2.,
7022 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7023 );
7024
7025 let origin = text_bounds.origin + offset;
7026 element.prepaint_at(origin, window, cx);
7027 Some((element, origin))
7028 } else {
7029 self.render_edit_prediction_end_of_line_popover(
7030 "Jump to Edit",
7031 editor_snapshot,
7032 visible_row_range,
7033 target_display_point,
7034 line_height,
7035 scroll_pixel_position,
7036 content_origin,
7037 editor_width,
7038 window,
7039 cx,
7040 )
7041 }
7042 }
7043
7044 fn render_edit_prediction_end_of_line_popover(
7045 self: &mut Editor,
7046 label: &'static str,
7047 editor_snapshot: &EditorSnapshot,
7048 visible_row_range: Range<DisplayRow>,
7049 target_display_point: DisplayPoint,
7050 line_height: Pixels,
7051 scroll_pixel_position: gpui::Point<Pixels>,
7052 content_origin: gpui::Point<Pixels>,
7053 editor_width: Pixels,
7054 window: &mut Window,
7055 cx: &mut App,
7056 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7057 let target_line_end = DisplayPoint::new(
7058 target_display_point.row(),
7059 editor_snapshot.line_len(target_display_point.row()),
7060 );
7061
7062 let mut element = self
7063 .render_edit_prediction_line_popover(label, None, window, cx)?
7064 .into_any();
7065
7066 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7067
7068 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7069
7070 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7071 let mut origin = start_point
7072 + line_origin
7073 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7074 origin.x = origin.x.max(content_origin.x);
7075
7076 let max_x = content_origin.x + editor_width - size.width;
7077
7078 if origin.x > max_x {
7079 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7080
7081 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7082 origin.y += offset;
7083 IconName::ArrowUp
7084 } else {
7085 origin.y -= offset;
7086 IconName::ArrowDown
7087 };
7088
7089 element = self
7090 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7091 .into_any();
7092
7093 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7094
7095 origin.x = content_origin.x + editor_width - size.width - px(2.);
7096 }
7097
7098 element.prepaint_at(origin, window, cx);
7099 Some((element, origin))
7100 }
7101
7102 fn render_edit_prediction_diff_popover(
7103 self: &Editor,
7104 text_bounds: &Bounds<Pixels>,
7105 content_origin: gpui::Point<Pixels>,
7106 editor_snapshot: &EditorSnapshot,
7107 visible_row_range: Range<DisplayRow>,
7108 line_layouts: &[LineWithInvisibles],
7109 line_height: Pixels,
7110 scroll_pixel_position: gpui::Point<Pixels>,
7111 newest_selection_head: Option<DisplayPoint>,
7112 editor_width: Pixels,
7113 style: &EditorStyle,
7114 edits: &Vec<(Range<Anchor>, String)>,
7115 edit_preview: &Option<language::EditPreview>,
7116 snapshot: &language::BufferSnapshot,
7117 window: &mut Window,
7118 cx: &mut App,
7119 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7120 let edit_start = edits
7121 .first()
7122 .unwrap()
7123 .0
7124 .start
7125 .to_display_point(editor_snapshot);
7126 let edit_end = edits
7127 .last()
7128 .unwrap()
7129 .0
7130 .end
7131 .to_display_point(editor_snapshot);
7132
7133 let is_visible = visible_row_range.contains(&edit_start.row())
7134 || visible_row_range.contains(&edit_end.row());
7135 if !is_visible {
7136 return None;
7137 }
7138
7139 let highlighted_edits =
7140 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7141
7142 let styled_text = highlighted_edits.to_styled_text(&style.text);
7143 let line_count = highlighted_edits.text.lines().count();
7144
7145 const BORDER_WIDTH: Pixels = px(1.);
7146
7147 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7148 let has_keybind = keybind.is_some();
7149
7150 let mut element = h_flex()
7151 .items_start()
7152 .child(
7153 h_flex()
7154 .bg(cx.theme().colors().editor_background)
7155 .border(BORDER_WIDTH)
7156 .shadow_sm()
7157 .border_color(cx.theme().colors().border)
7158 .rounded_l_lg()
7159 .when(line_count > 1, |el| el.rounded_br_lg())
7160 .pr_1()
7161 .child(styled_text),
7162 )
7163 .child(
7164 h_flex()
7165 .h(line_height + BORDER_WIDTH * 2.)
7166 .px_1p5()
7167 .gap_1()
7168 // Workaround: For some reason, there's a gap if we don't do this
7169 .ml(-BORDER_WIDTH)
7170 .shadow(smallvec![gpui::BoxShadow {
7171 color: gpui::black().opacity(0.05),
7172 offset: point(px(1.), px(1.)),
7173 blur_radius: px(2.),
7174 spread_radius: px(0.),
7175 }])
7176 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7177 .border(BORDER_WIDTH)
7178 .border_color(cx.theme().colors().border)
7179 .rounded_r_lg()
7180 .id("edit_prediction_diff_popover_keybind")
7181 .when(!has_keybind, |el| {
7182 let status_colors = cx.theme().status();
7183
7184 el.bg(status_colors.error_background)
7185 .border_color(status_colors.error.opacity(0.6))
7186 .child(Icon::new(IconName::Info).color(Color::Error))
7187 .cursor_default()
7188 .hoverable_tooltip(move |_window, cx| {
7189 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7190 })
7191 })
7192 .children(keybind),
7193 )
7194 .into_any();
7195
7196 let longest_row =
7197 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7198 let longest_line_width = if visible_row_range.contains(&longest_row) {
7199 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7200 } else {
7201 layout_line(
7202 longest_row,
7203 editor_snapshot,
7204 style,
7205 editor_width,
7206 |_| false,
7207 window,
7208 cx,
7209 )
7210 .width
7211 };
7212
7213 let viewport_bounds =
7214 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7215 right: -EditorElement::SCROLLBAR_WIDTH,
7216 ..Default::default()
7217 });
7218
7219 let x_after_longest =
7220 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7221 - scroll_pixel_position.x;
7222
7223 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7224
7225 // Fully visible if it can be displayed within the window (allow overlapping other
7226 // panes). However, this is only allowed if the popover starts within text_bounds.
7227 let can_position_to_the_right = x_after_longest < text_bounds.right()
7228 && x_after_longest + element_bounds.width < viewport_bounds.right();
7229
7230 let mut origin = if can_position_to_the_right {
7231 point(
7232 x_after_longest,
7233 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7234 - scroll_pixel_position.y,
7235 )
7236 } else {
7237 let cursor_row = newest_selection_head.map(|head| head.row());
7238 let above_edit = edit_start
7239 .row()
7240 .0
7241 .checked_sub(line_count as u32)
7242 .map(DisplayRow);
7243 let below_edit = Some(edit_end.row() + 1);
7244 let above_cursor =
7245 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7246 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7247
7248 // Place the edit popover adjacent to the edit if there is a location
7249 // available that is onscreen and does not obscure the cursor. Otherwise,
7250 // place it adjacent to the cursor.
7251 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7252 .into_iter()
7253 .flatten()
7254 .find(|&start_row| {
7255 let end_row = start_row + line_count as u32;
7256 visible_row_range.contains(&start_row)
7257 && visible_row_range.contains(&end_row)
7258 && cursor_row.map_or(true, |cursor_row| {
7259 !((start_row..end_row).contains(&cursor_row))
7260 })
7261 })?;
7262
7263 content_origin
7264 + point(
7265 -scroll_pixel_position.x,
7266 row_target.as_f32() * line_height - scroll_pixel_position.y,
7267 )
7268 };
7269
7270 origin.x -= BORDER_WIDTH;
7271
7272 window.defer_draw(element, origin, 1);
7273
7274 // Do not return an element, since it will already be drawn due to defer_draw.
7275 None
7276 }
7277
7278 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7279 px(30.)
7280 }
7281
7282 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7283 if self.read_only(cx) {
7284 cx.theme().players().read_only()
7285 } else {
7286 self.style.as_ref().unwrap().local_player
7287 }
7288 }
7289
7290 fn render_edit_prediction_accept_keybind(
7291 &self,
7292 window: &mut Window,
7293 cx: &App,
7294 ) -> Option<AnyElement> {
7295 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7296 let accept_keystroke = accept_binding.keystroke()?;
7297
7298 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7299
7300 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7301 Color::Accent
7302 } else {
7303 Color::Muted
7304 };
7305
7306 h_flex()
7307 .px_0p5()
7308 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7309 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7310 .text_size(TextSize::XSmall.rems(cx))
7311 .child(h_flex().children(ui::render_modifiers(
7312 &accept_keystroke.modifiers,
7313 PlatformStyle::platform(),
7314 Some(modifiers_color),
7315 Some(IconSize::XSmall.rems().into()),
7316 true,
7317 )))
7318 .when(is_platform_style_mac, |parent| {
7319 parent.child(accept_keystroke.key.clone())
7320 })
7321 .when(!is_platform_style_mac, |parent| {
7322 parent.child(
7323 Key::new(
7324 util::capitalize(&accept_keystroke.key),
7325 Some(Color::Default),
7326 )
7327 .size(Some(IconSize::XSmall.rems().into())),
7328 )
7329 })
7330 .into_any()
7331 .into()
7332 }
7333
7334 fn render_edit_prediction_line_popover(
7335 &self,
7336 label: impl Into<SharedString>,
7337 icon: Option<IconName>,
7338 window: &mut Window,
7339 cx: &App,
7340 ) -> Option<Stateful<Div>> {
7341 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7342
7343 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7344 let has_keybind = keybind.is_some();
7345
7346 let result = h_flex()
7347 .id("ep-line-popover")
7348 .py_0p5()
7349 .pl_1()
7350 .pr(padding_right)
7351 .gap_1()
7352 .rounded_md()
7353 .border_1()
7354 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7355 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7356 .shadow_sm()
7357 .when(!has_keybind, |el| {
7358 let status_colors = cx.theme().status();
7359
7360 el.bg(status_colors.error_background)
7361 .border_color(status_colors.error.opacity(0.6))
7362 .pl_2()
7363 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7364 .cursor_default()
7365 .hoverable_tooltip(move |_window, cx| {
7366 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7367 })
7368 })
7369 .children(keybind)
7370 .child(
7371 Label::new(label)
7372 .size(LabelSize::Small)
7373 .when(!has_keybind, |el| {
7374 el.color(cx.theme().status().error.into()).strikethrough()
7375 }),
7376 )
7377 .when(!has_keybind, |el| {
7378 el.child(
7379 h_flex().ml_1().child(
7380 Icon::new(IconName::Info)
7381 .size(IconSize::Small)
7382 .color(cx.theme().status().error.into()),
7383 ),
7384 )
7385 })
7386 .when_some(icon, |element, icon| {
7387 element.child(
7388 div()
7389 .mt(px(1.5))
7390 .child(Icon::new(icon).size(IconSize::Small)),
7391 )
7392 });
7393
7394 Some(result)
7395 }
7396
7397 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7398 let accent_color = cx.theme().colors().text_accent;
7399 let editor_bg_color = cx.theme().colors().editor_background;
7400 editor_bg_color.blend(accent_color.opacity(0.1))
7401 }
7402
7403 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7404 let accent_color = cx.theme().colors().text_accent;
7405 let editor_bg_color = cx.theme().colors().editor_background;
7406 editor_bg_color.blend(accent_color.opacity(0.6))
7407 }
7408
7409 fn render_edit_prediction_cursor_popover(
7410 &self,
7411 min_width: Pixels,
7412 max_width: Pixels,
7413 cursor_point: Point,
7414 style: &EditorStyle,
7415 accept_keystroke: Option<&gpui::Keystroke>,
7416 _window: &Window,
7417 cx: &mut Context<Editor>,
7418 ) -> Option<AnyElement> {
7419 let provider = self.edit_prediction_provider.as_ref()?;
7420
7421 if provider.provider.needs_terms_acceptance(cx) {
7422 return Some(
7423 h_flex()
7424 .min_w(min_width)
7425 .flex_1()
7426 .px_2()
7427 .py_1()
7428 .gap_3()
7429 .elevation_2(cx)
7430 .hover(|style| style.bg(cx.theme().colors().element_hover))
7431 .id("accept-terms")
7432 .cursor_pointer()
7433 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7434 .on_click(cx.listener(|this, _event, window, cx| {
7435 cx.stop_propagation();
7436 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7437 window.dispatch_action(
7438 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7439 cx,
7440 );
7441 }))
7442 .child(
7443 h_flex()
7444 .flex_1()
7445 .gap_2()
7446 .child(Icon::new(IconName::ZedPredict))
7447 .child(Label::new("Accept Terms of Service"))
7448 .child(div().w_full())
7449 .child(
7450 Icon::new(IconName::ArrowUpRight)
7451 .color(Color::Muted)
7452 .size(IconSize::Small),
7453 )
7454 .into_any_element(),
7455 )
7456 .into_any(),
7457 );
7458 }
7459
7460 let is_refreshing = provider.provider.is_refreshing(cx);
7461
7462 fn pending_completion_container() -> Div {
7463 h_flex()
7464 .h_full()
7465 .flex_1()
7466 .gap_2()
7467 .child(Icon::new(IconName::ZedPredict))
7468 }
7469
7470 let completion = match &self.active_inline_completion {
7471 Some(prediction) => {
7472 if !self.has_visible_completions_menu() {
7473 const RADIUS: Pixels = px(6.);
7474 const BORDER_WIDTH: Pixels = px(1.);
7475
7476 return Some(
7477 h_flex()
7478 .elevation_2(cx)
7479 .border(BORDER_WIDTH)
7480 .border_color(cx.theme().colors().border)
7481 .when(accept_keystroke.is_none(), |el| {
7482 el.border_color(cx.theme().status().error)
7483 })
7484 .rounded(RADIUS)
7485 .rounded_tl(px(0.))
7486 .overflow_hidden()
7487 .child(div().px_1p5().child(match &prediction.completion {
7488 InlineCompletion::Move { target, snapshot } => {
7489 use text::ToPoint as _;
7490 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7491 {
7492 Icon::new(IconName::ZedPredictDown)
7493 } else {
7494 Icon::new(IconName::ZedPredictUp)
7495 }
7496 }
7497 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7498 }))
7499 .child(
7500 h_flex()
7501 .gap_1()
7502 .py_1()
7503 .px_2()
7504 .rounded_r(RADIUS - BORDER_WIDTH)
7505 .border_l_1()
7506 .border_color(cx.theme().colors().border)
7507 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7508 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7509 el.child(
7510 Label::new("Hold")
7511 .size(LabelSize::Small)
7512 .when(accept_keystroke.is_none(), |el| {
7513 el.strikethrough()
7514 })
7515 .line_height_style(LineHeightStyle::UiLabel),
7516 )
7517 })
7518 .id("edit_prediction_cursor_popover_keybind")
7519 .when(accept_keystroke.is_none(), |el| {
7520 let status_colors = cx.theme().status();
7521
7522 el.bg(status_colors.error_background)
7523 .border_color(status_colors.error.opacity(0.6))
7524 .child(Icon::new(IconName::Info).color(Color::Error))
7525 .cursor_default()
7526 .hoverable_tooltip(move |_window, cx| {
7527 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7528 .into()
7529 })
7530 })
7531 .when_some(
7532 accept_keystroke.as_ref(),
7533 |el, accept_keystroke| {
7534 el.child(h_flex().children(ui::render_modifiers(
7535 &accept_keystroke.modifiers,
7536 PlatformStyle::platform(),
7537 Some(Color::Default),
7538 Some(IconSize::XSmall.rems().into()),
7539 false,
7540 )))
7541 },
7542 ),
7543 )
7544 .into_any(),
7545 );
7546 }
7547
7548 self.render_edit_prediction_cursor_popover_preview(
7549 prediction,
7550 cursor_point,
7551 style,
7552 cx,
7553 )?
7554 }
7555
7556 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7557 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7558 stale_completion,
7559 cursor_point,
7560 style,
7561 cx,
7562 )?,
7563
7564 None => {
7565 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7566 }
7567 },
7568
7569 None => pending_completion_container().child(Label::new("No Prediction")),
7570 };
7571
7572 let completion = if is_refreshing {
7573 completion
7574 .with_animation(
7575 "loading-completion",
7576 Animation::new(Duration::from_secs(2))
7577 .repeat()
7578 .with_easing(pulsating_between(0.4, 0.8)),
7579 |label, delta| label.opacity(delta),
7580 )
7581 .into_any_element()
7582 } else {
7583 completion.into_any_element()
7584 };
7585
7586 let has_completion = self.active_inline_completion.is_some();
7587
7588 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7589 Some(
7590 h_flex()
7591 .min_w(min_width)
7592 .max_w(max_width)
7593 .flex_1()
7594 .elevation_2(cx)
7595 .border_color(cx.theme().colors().border)
7596 .child(
7597 div()
7598 .flex_1()
7599 .py_1()
7600 .px_2()
7601 .overflow_hidden()
7602 .child(completion),
7603 )
7604 .when_some(accept_keystroke, |el, accept_keystroke| {
7605 if !accept_keystroke.modifiers.modified() {
7606 return el;
7607 }
7608
7609 el.child(
7610 h_flex()
7611 .h_full()
7612 .border_l_1()
7613 .rounded_r_lg()
7614 .border_color(cx.theme().colors().border)
7615 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7616 .gap_1()
7617 .py_1()
7618 .px_2()
7619 .child(
7620 h_flex()
7621 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7622 .when(is_platform_style_mac, |parent| parent.gap_1())
7623 .child(h_flex().children(ui::render_modifiers(
7624 &accept_keystroke.modifiers,
7625 PlatformStyle::platform(),
7626 Some(if !has_completion {
7627 Color::Muted
7628 } else {
7629 Color::Default
7630 }),
7631 None,
7632 false,
7633 ))),
7634 )
7635 .child(Label::new("Preview").into_any_element())
7636 .opacity(if has_completion { 1.0 } else { 0.4 }),
7637 )
7638 })
7639 .into_any(),
7640 )
7641 }
7642
7643 fn render_edit_prediction_cursor_popover_preview(
7644 &self,
7645 completion: &InlineCompletionState,
7646 cursor_point: Point,
7647 style: &EditorStyle,
7648 cx: &mut Context<Editor>,
7649 ) -> Option<Div> {
7650 use text::ToPoint as _;
7651
7652 fn render_relative_row_jump(
7653 prefix: impl Into<String>,
7654 current_row: u32,
7655 target_row: u32,
7656 ) -> Div {
7657 let (row_diff, arrow) = if target_row < current_row {
7658 (current_row - target_row, IconName::ArrowUp)
7659 } else {
7660 (target_row - current_row, IconName::ArrowDown)
7661 };
7662
7663 h_flex()
7664 .child(
7665 Label::new(format!("{}{}", prefix.into(), row_diff))
7666 .color(Color::Muted)
7667 .size(LabelSize::Small),
7668 )
7669 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7670 }
7671
7672 match &completion.completion {
7673 InlineCompletion::Move {
7674 target, snapshot, ..
7675 } => Some(
7676 h_flex()
7677 .px_2()
7678 .gap_2()
7679 .flex_1()
7680 .child(
7681 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7682 Icon::new(IconName::ZedPredictDown)
7683 } else {
7684 Icon::new(IconName::ZedPredictUp)
7685 },
7686 )
7687 .child(Label::new("Jump to Edit")),
7688 ),
7689
7690 InlineCompletion::Edit {
7691 edits,
7692 edit_preview,
7693 snapshot,
7694 display_mode: _,
7695 } => {
7696 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7697
7698 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7699 &snapshot,
7700 &edits,
7701 edit_preview.as_ref()?,
7702 true,
7703 cx,
7704 )
7705 .first_line_preview();
7706
7707 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7708 .with_default_highlights(&style.text, highlighted_edits.highlights);
7709
7710 let preview = h_flex()
7711 .gap_1()
7712 .min_w_16()
7713 .child(styled_text)
7714 .when(has_more_lines, |parent| parent.child("…"));
7715
7716 let left = if first_edit_row != cursor_point.row {
7717 render_relative_row_jump("", cursor_point.row, first_edit_row)
7718 .into_any_element()
7719 } else {
7720 Icon::new(IconName::ZedPredict).into_any_element()
7721 };
7722
7723 Some(
7724 h_flex()
7725 .h_full()
7726 .flex_1()
7727 .gap_2()
7728 .pr_1()
7729 .overflow_x_hidden()
7730 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7731 .child(left)
7732 .child(preview),
7733 )
7734 }
7735 }
7736 }
7737
7738 fn render_context_menu(
7739 &self,
7740 style: &EditorStyle,
7741 max_height_in_lines: u32,
7742 window: &mut Window,
7743 cx: &mut Context<Editor>,
7744 ) -> Option<AnyElement> {
7745 let menu = self.context_menu.borrow();
7746 let menu = menu.as_ref()?;
7747 if !menu.visible() {
7748 return None;
7749 };
7750 Some(menu.render(style, max_height_in_lines, window, cx))
7751 }
7752
7753 fn render_context_menu_aside(
7754 &mut self,
7755 max_size: Size<Pixels>,
7756 window: &mut Window,
7757 cx: &mut Context<Editor>,
7758 ) -> Option<AnyElement> {
7759 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7760 if menu.visible() {
7761 menu.render_aside(self, max_size, window, cx)
7762 } else {
7763 None
7764 }
7765 })
7766 }
7767
7768 fn hide_context_menu(
7769 &mut self,
7770 window: &mut Window,
7771 cx: &mut Context<Self>,
7772 ) -> Option<CodeContextMenu> {
7773 cx.notify();
7774 self.completion_tasks.clear();
7775 let context_menu = self.context_menu.borrow_mut().take();
7776 self.stale_inline_completion_in_menu.take();
7777 self.update_visible_inline_completion(window, cx);
7778 context_menu
7779 }
7780
7781 fn show_snippet_choices(
7782 &mut self,
7783 choices: &Vec<String>,
7784 selection: Range<Anchor>,
7785 cx: &mut Context<Self>,
7786 ) {
7787 if selection.start.buffer_id.is_none() {
7788 return;
7789 }
7790 let buffer_id = selection.start.buffer_id.unwrap();
7791 let buffer = self.buffer().read(cx).buffer(buffer_id);
7792 let id = post_inc(&mut self.next_completion_id);
7793
7794 if let Some(buffer) = buffer {
7795 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7796 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7797 ));
7798 }
7799 }
7800
7801 pub fn insert_snippet(
7802 &mut self,
7803 insertion_ranges: &[Range<usize>],
7804 snippet: Snippet,
7805 window: &mut Window,
7806 cx: &mut Context<Self>,
7807 ) -> Result<()> {
7808 struct Tabstop<T> {
7809 is_end_tabstop: bool,
7810 ranges: Vec<Range<T>>,
7811 choices: Option<Vec<String>>,
7812 }
7813
7814 let tabstops = self.buffer.update(cx, |buffer, cx| {
7815 let snippet_text: Arc<str> = snippet.text.clone().into();
7816 let edits = insertion_ranges
7817 .iter()
7818 .cloned()
7819 .map(|range| (range, snippet_text.clone()));
7820 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7821
7822 let snapshot = &*buffer.read(cx);
7823 let snippet = &snippet;
7824 snippet
7825 .tabstops
7826 .iter()
7827 .map(|tabstop| {
7828 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7829 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7830 });
7831 let mut tabstop_ranges = tabstop
7832 .ranges
7833 .iter()
7834 .flat_map(|tabstop_range| {
7835 let mut delta = 0_isize;
7836 insertion_ranges.iter().map(move |insertion_range| {
7837 let insertion_start = insertion_range.start as isize + delta;
7838 delta +=
7839 snippet.text.len() as isize - insertion_range.len() as isize;
7840
7841 let start = ((insertion_start + tabstop_range.start) as usize)
7842 .min(snapshot.len());
7843 let end = ((insertion_start + tabstop_range.end) as usize)
7844 .min(snapshot.len());
7845 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7846 })
7847 })
7848 .collect::<Vec<_>>();
7849 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7850
7851 Tabstop {
7852 is_end_tabstop,
7853 ranges: tabstop_ranges,
7854 choices: tabstop.choices.clone(),
7855 }
7856 })
7857 .collect::<Vec<_>>()
7858 });
7859 if let Some(tabstop) = tabstops.first() {
7860 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7861 s.select_ranges(tabstop.ranges.iter().cloned());
7862 });
7863
7864 if let Some(choices) = &tabstop.choices {
7865 if let Some(selection) = tabstop.ranges.first() {
7866 self.show_snippet_choices(choices, selection.clone(), cx)
7867 }
7868 }
7869
7870 // If we're already at the last tabstop and it's at the end of the snippet,
7871 // we're done, we don't need to keep the state around.
7872 if !tabstop.is_end_tabstop {
7873 let choices = tabstops
7874 .iter()
7875 .map(|tabstop| tabstop.choices.clone())
7876 .collect();
7877
7878 let ranges = tabstops
7879 .into_iter()
7880 .map(|tabstop| tabstop.ranges)
7881 .collect::<Vec<_>>();
7882
7883 self.snippet_stack.push(SnippetState {
7884 active_index: 0,
7885 ranges,
7886 choices,
7887 });
7888 }
7889
7890 // Check whether the just-entered snippet ends with an auto-closable bracket.
7891 if self.autoclose_regions.is_empty() {
7892 let snapshot = self.buffer.read(cx).snapshot(cx);
7893 for selection in &mut self.selections.all::<Point>(cx) {
7894 let selection_head = selection.head();
7895 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7896 continue;
7897 };
7898
7899 let mut bracket_pair = None;
7900 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7901 let prev_chars = snapshot
7902 .reversed_chars_at(selection_head)
7903 .collect::<String>();
7904 for (pair, enabled) in scope.brackets() {
7905 if enabled
7906 && pair.close
7907 && prev_chars.starts_with(pair.start.as_str())
7908 && next_chars.starts_with(pair.end.as_str())
7909 {
7910 bracket_pair = Some(pair.clone());
7911 break;
7912 }
7913 }
7914 if let Some(pair) = bracket_pair {
7915 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
7916 let autoclose_enabled =
7917 self.use_autoclose && snapshot_settings.use_autoclose;
7918 if autoclose_enabled {
7919 let start = snapshot.anchor_after(selection_head);
7920 let end = snapshot.anchor_after(selection_head);
7921 self.autoclose_regions.push(AutocloseRegion {
7922 selection_id: selection.id,
7923 range: start..end,
7924 pair,
7925 });
7926 }
7927 }
7928 }
7929 }
7930 }
7931 Ok(())
7932 }
7933
7934 pub fn move_to_next_snippet_tabstop(
7935 &mut self,
7936 window: &mut Window,
7937 cx: &mut Context<Self>,
7938 ) -> bool {
7939 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7940 }
7941
7942 pub fn move_to_prev_snippet_tabstop(
7943 &mut self,
7944 window: &mut Window,
7945 cx: &mut Context<Self>,
7946 ) -> bool {
7947 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7948 }
7949
7950 pub fn move_to_snippet_tabstop(
7951 &mut self,
7952 bias: Bias,
7953 window: &mut Window,
7954 cx: &mut Context<Self>,
7955 ) -> bool {
7956 if let Some(mut snippet) = self.snippet_stack.pop() {
7957 match bias {
7958 Bias::Left => {
7959 if snippet.active_index > 0 {
7960 snippet.active_index -= 1;
7961 } else {
7962 self.snippet_stack.push(snippet);
7963 return false;
7964 }
7965 }
7966 Bias::Right => {
7967 if snippet.active_index + 1 < snippet.ranges.len() {
7968 snippet.active_index += 1;
7969 } else {
7970 self.snippet_stack.push(snippet);
7971 return false;
7972 }
7973 }
7974 }
7975 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7976 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7977 s.select_anchor_ranges(current_ranges.iter().cloned())
7978 });
7979
7980 if let Some(choices) = &snippet.choices[snippet.active_index] {
7981 if let Some(selection) = current_ranges.first() {
7982 self.show_snippet_choices(&choices, selection.clone(), cx);
7983 }
7984 }
7985
7986 // If snippet state is not at the last tabstop, push it back on the stack
7987 if snippet.active_index + 1 < snippet.ranges.len() {
7988 self.snippet_stack.push(snippet);
7989 }
7990 return true;
7991 }
7992 }
7993
7994 false
7995 }
7996
7997 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7998 self.transact(window, cx, |this, window, cx| {
7999 this.select_all(&SelectAll, window, cx);
8000 this.insert("", window, cx);
8001 });
8002 }
8003
8004 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8005 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8006 self.transact(window, cx, |this, window, cx| {
8007 this.select_autoclose_pair(window, cx);
8008 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8009 if !this.linked_edit_ranges.is_empty() {
8010 let selections = this.selections.all::<MultiBufferPoint>(cx);
8011 let snapshot = this.buffer.read(cx).snapshot(cx);
8012
8013 for selection in selections.iter() {
8014 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8015 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8016 if selection_start.buffer_id != selection_end.buffer_id {
8017 continue;
8018 }
8019 if let Some(ranges) =
8020 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8021 {
8022 for (buffer, entries) in ranges {
8023 linked_ranges.entry(buffer).or_default().extend(entries);
8024 }
8025 }
8026 }
8027 }
8028
8029 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8030 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8031 for selection in &mut selections {
8032 if selection.is_empty() {
8033 let old_head = selection.head();
8034 let mut new_head =
8035 movement::left(&display_map, old_head.to_display_point(&display_map))
8036 .to_point(&display_map);
8037 if let Some((buffer, line_buffer_range)) = display_map
8038 .buffer_snapshot
8039 .buffer_line_for_row(MultiBufferRow(old_head.row))
8040 {
8041 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8042 let indent_len = match indent_size.kind {
8043 IndentKind::Space => {
8044 buffer.settings_at(line_buffer_range.start, cx).tab_size
8045 }
8046 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8047 };
8048 if old_head.column <= indent_size.len && old_head.column > 0 {
8049 let indent_len = indent_len.get();
8050 new_head = cmp::min(
8051 new_head,
8052 MultiBufferPoint::new(
8053 old_head.row,
8054 ((old_head.column - 1) / indent_len) * indent_len,
8055 ),
8056 );
8057 }
8058 }
8059
8060 selection.set_head(new_head, SelectionGoal::None);
8061 }
8062 }
8063
8064 this.signature_help_state.set_backspace_pressed(true);
8065 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8066 s.select(selections)
8067 });
8068 this.insert("", window, cx);
8069 let empty_str: Arc<str> = Arc::from("");
8070 for (buffer, edits) in linked_ranges {
8071 let snapshot = buffer.read(cx).snapshot();
8072 use text::ToPoint as TP;
8073
8074 let edits = edits
8075 .into_iter()
8076 .map(|range| {
8077 let end_point = TP::to_point(&range.end, &snapshot);
8078 let mut start_point = TP::to_point(&range.start, &snapshot);
8079
8080 if end_point == start_point {
8081 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8082 .saturating_sub(1);
8083 start_point =
8084 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8085 };
8086
8087 (start_point..end_point, empty_str.clone())
8088 })
8089 .sorted_by_key(|(range, _)| range.start)
8090 .collect::<Vec<_>>();
8091 buffer.update(cx, |this, cx| {
8092 this.edit(edits, None, cx);
8093 })
8094 }
8095 this.refresh_inline_completion(true, false, window, cx);
8096 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8097 });
8098 }
8099
8100 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8101 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8102 self.transact(window, cx, |this, window, cx| {
8103 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8104 s.move_with(|map, selection| {
8105 if selection.is_empty() {
8106 let cursor = movement::right(map, selection.head());
8107 selection.end = cursor;
8108 selection.reversed = true;
8109 selection.goal = SelectionGoal::None;
8110 }
8111 })
8112 });
8113 this.insert("", window, cx);
8114 this.refresh_inline_completion(true, false, window, cx);
8115 });
8116 }
8117
8118 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8119 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8120 if self.move_to_prev_snippet_tabstop(window, cx) {
8121 return;
8122 }
8123 self.outdent(&Outdent, window, cx);
8124 }
8125
8126 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8127 if self.move_to_next_snippet_tabstop(window, cx) {
8128 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8129 return;
8130 }
8131 if self.read_only(cx) {
8132 return;
8133 }
8134 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8135 let mut selections = self.selections.all_adjusted(cx);
8136 let buffer = self.buffer.read(cx);
8137 let snapshot = buffer.snapshot(cx);
8138 let rows_iter = selections.iter().map(|s| s.head().row);
8139 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8140
8141 let mut edits = Vec::new();
8142 let mut prev_edited_row = 0;
8143 let mut row_delta = 0;
8144 for selection in &mut selections {
8145 if selection.start.row != prev_edited_row {
8146 row_delta = 0;
8147 }
8148 prev_edited_row = selection.end.row;
8149
8150 // If the selection is non-empty, then increase the indentation of the selected lines.
8151 if !selection.is_empty() {
8152 row_delta =
8153 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8154 continue;
8155 }
8156
8157 // If the selection is empty and the cursor is in the leading whitespace before the
8158 // suggested indentation, then auto-indent the line.
8159 let cursor = selection.head();
8160 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8161 if let Some(suggested_indent) =
8162 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8163 {
8164 if cursor.column < suggested_indent.len
8165 && cursor.column <= current_indent.len
8166 && current_indent.len <= suggested_indent.len
8167 {
8168 selection.start = Point::new(cursor.row, suggested_indent.len);
8169 selection.end = selection.start;
8170 if row_delta == 0 {
8171 edits.extend(Buffer::edit_for_indent_size_adjustment(
8172 cursor.row,
8173 current_indent,
8174 suggested_indent,
8175 ));
8176 row_delta = suggested_indent.len - current_indent.len;
8177 }
8178 continue;
8179 }
8180 }
8181
8182 // Otherwise, insert a hard or soft tab.
8183 let settings = buffer.language_settings_at(cursor, cx);
8184 let tab_size = if settings.hard_tabs {
8185 IndentSize::tab()
8186 } else {
8187 let tab_size = settings.tab_size.get();
8188 let char_column = snapshot
8189 .text_for_range(Point::new(cursor.row, 0)..cursor)
8190 .flat_map(str::chars)
8191 .count()
8192 + row_delta as usize;
8193 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
8194 IndentSize::spaces(chars_to_next_tab_stop)
8195 };
8196 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8197 selection.end = selection.start;
8198 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8199 row_delta += tab_size.len;
8200 }
8201
8202 self.transact(window, cx, |this, window, cx| {
8203 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8204 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8205 s.select(selections)
8206 });
8207 this.refresh_inline_completion(true, false, window, cx);
8208 });
8209 }
8210
8211 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8212 if self.read_only(cx) {
8213 return;
8214 }
8215 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8216 let mut selections = self.selections.all::<Point>(cx);
8217 let mut prev_edited_row = 0;
8218 let mut row_delta = 0;
8219 let mut edits = Vec::new();
8220 let buffer = self.buffer.read(cx);
8221 let snapshot = buffer.snapshot(cx);
8222 for selection in &mut selections {
8223 if selection.start.row != prev_edited_row {
8224 row_delta = 0;
8225 }
8226 prev_edited_row = selection.end.row;
8227
8228 row_delta =
8229 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8230 }
8231
8232 self.transact(window, cx, |this, window, cx| {
8233 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8234 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8235 s.select(selections)
8236 });
8237 });
8238 }
8239
8240 fn indent_selection(
8241 buffer: &MultiBuffer,
8242 snapshot: &MultiBufferSnapshot,
8243 selection: &mut Selection<Point>,
8244 edits: &mut Vec<(Range<Point>, String)>,
8245 delta_for_start_row: u32,
8246 cx: &App,
8247 ) -> u32 {
8248 let settings = buffer.language_settings_at(selection.start, cx);
8249 let tab_size = settings.tab_size.get();
8250 let indent_kind = if settings.hard_tabs {
8251 IndentKind::Tab
8252 } else {
8253 IndentKind::Space
8254 };
8255 let mut start_row = selection.start.row;
8256 let mut end_row = selection.end.row + 1;
8257
8258 // If a selection ends at the beginning of a line, don't indent
8259 // that last line.
8260 if selection.end.column == 0 && selection.end.row > selection.start.row {
8261 end_row -= 1;
8262 }
8263
8264 // Avoid re-indenting a row that has already been indented by a
8265 // previous selection, but still update this selection's column
8266 // to reflect that indentation.
8267 if delta_for_start_row > 0 {
8268 start_row += 1;
8269 selection.start.column += delta_for_start_row;
8270 if selection.end.row == selection.start.row {
8271 selection.end.column += delta_for_start_row;
8272 }
8273 }
8274
8275 let mut delta_for_end_row = 0;
8276 let has_multiple_rows = start_row + 1 != end_row;
8277 for row in start_row..end_row {
8278 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8279 let indent_delta = match (current_indent.kind, indent_kind) {
8280 (IndentKind::Space, IndentKind::Space) => {
8281 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8282 IndentSize::spaces(columns_to_next_tab_stop)
8283 }
8284 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8285 (_, IndentKind::Tab) => IndentSize::tab(),
8286 };
8287
8288 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8289 0
8290 } else {
8291 selection.start.column
8292 };
8293 let row_start = Point::new(row, start);
8294 edits.push((
8295 row_start..row_start,
8296 indent_delta.chars().collect::<String>(),
8297 ));
8298
8299 // Update this selection's endpoints to reflect the indentation.
8300 if row == selection.start.row {
8301 selection.start.column += indent_delta.len;
8302 }
8303 if row == selection.end.row {
8304 selection.end.column += indent_delta.len;
8305 delta_for_end_row = indent_delta.len;
8306 }
8307 }
8308
8309 if selection.start.row == selection.end.row {
8310 delta_for_start_row + delta_for_end_row
8311 } else {
8312 delta_for_end_row
8313 }
8314 }
8315
8316 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8317 if self.read_only(cx) {
8318 return;
8319 }
8320 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8322 let selections = self.selections.all::<Point>(cx);
8323 let mut deletion_ranges = Vec::new();
8324 let mut last_outdent = None;
8325 {
8326 let buffer = self.buffer.read(cx);
8327 let snapshot = buffer.snapshot(cx);
8328 for selection in &selections {
8329 let settings = buffer.language_settings_at(selection.start, cx);
8330 let tab_size = settings.tab_size.get();
8331 let mut rows = selection.spanned_rows(false, &display_map);
8332
8333 // Avoid re-outdenting a row that has already been outdented by a
8334 // previous selection.
8335 if let Some(last_row) = last_outdent {
8336 if last_row == rows.start {
8337 rows.start = rows.start.next_row();
8338 }
8339 }
8340 let has_multiple_rows = rows.len() > 1;
8341 for row in rows.iter_rows() {
8342 let indent_size = snapshot.indent_size_for_line(row);
8343 if indent_size.len > 0 {
8344 let deletion_len = match indent_size.kind {
8345 IndentKind::Space => {
8346 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8347 if columns_to_prev_tab_stop == 0 {
8348 tab_size
8349 } else {
8350 columns_to_prev_tab_stop
8351 }
8352 }
8353 IndentKind::Tab => 1,
8354 };
8355 let start = if has_multiple_rows
8356 || deletion_len > selection.start.column
8357 || indent_size.len < selection.start.column
8358 {
8359 0
8360 } else {
8361 selection.start.column - deletion_len
8362 };
8363 deletion_ranges.push(
8364 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8365 );
8366 last_outdent = Some(row);
8367 }
8368 }
8369 }
8370 }
8371
8372 self.transact(window, cx, |this, window, cx| {
8373 this.buffer.update(cx, |buffer, cx| {
8374 let empty_str: Arc<str> = Arc::default();
8375 buffer.edit(
8376 deletion_ranges
8377 .into_iter()
8378 .map(|range| (range, empty_str.clone())),
8379 None,
8380 cx,
8381 );
8382 });
8383 let selections = this.selections.all::<usize>(cx);
8384 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8385 s.select(selections)
8386 });
8387 });
8388 }
8389
8390 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8391 if self.read_only(cx) {
8392 return;
8393 }
8394 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8395 let selections = self
8396 .selections
8397 .all::<usize>(cx)
8398 .into_iter()
8399 .map(|s| s.range());
8400
8401 self.transact(window, cx, |this, window, cx| {
8402 this.buffer.update(cx, |buffer, cx| {
8403 buffer.autoindent_ranges(selections, cx);
8404 });
8405 let selections = this.selections.all::<usize>(cx);
8406 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8407 s.select(selections)
8408 });
8409 });
8410 }
8411
8412 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8413 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8414 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8415 let selections = self.selections.all::<Point>(cx);
8416
8417 let mut new_cursors = Vec::new();
8418 let mut edit_ranges = Vec::new();
8419 let mut selections = selections.iter().peekable();
8420 while let Some(selection) = selections.next() {
8421 let mut rows = selection.spanned_rows(false, &display_map);
8422 let goal_display_column = selection.head().to_display_point(&display_map).column();
8423
8424 // Accumulate contiguous regions of rows that we want to delete.
8425 while let Some(next_selection) = selections.peek() {
8426 let next_rows = next_selection.spanned_rows(false, &display_map);
8427 if next_rows.start <= rows.end {
8428 rows.end = next_rows.end;
8429 selections.next().unwrap();
8430 } else {
8431 break;
8432 }
8433 }
8434
8435 let buffer = &display_map.buffer_snapshot;
8436 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8437 let edit_end;
8438 let cursor_buffer_row;
8439 if buffer.max_point().row >= rows.end.0 {
8440 // If there's a line after the range, delete the \n from the end of the row range
8441 // and position the cursor on the next line.
8442 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8443 cursor_buffer_row = rows.end;
8444 } else {
8445 // If there isn't a line after the range, delete the \n from the line before the
8446 // start of the row range and position the cursor there.
8447 edit_start = edit_start.saturating_sub(1);
8448 edit_end = buffer.len();
8449 cursor_buffer_row = rows.start.previous_row();
8450 }
8451
8452 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8453 *cursor.column_mut() =
8454 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8455
8456 new_cursors.push((
8457 selection.id,
8458 buffer.anchor_after(cursor.to_point(&display_map)),
8459 ));
8460 edit_ranges.push(edit_start..edit_end);
8461 }
8462
8463 self.transact(window, cx, |this, window, cx| {
8464 let buffer = this.buffer.update(cx, |buffer, cx| {
8465 let empty_str: Arc<str> = Arc::default();
8466 buffer.edit(
8467 edit_ranges
8468 .into_iter()
8469 .map(|range| (range, empty_str.clone())),
8470 None,
8471 cx,
8472 );
8473 buffer.snapshot(cx)
8474 });
8475 let new_selections = new_cursors
8476 .into_iter()
8477 .map(|(id, cursor)| {
8478 let cursor = cursor.to_point(&buffer);
8479 Selection {
8480 id,
8481 start: cursor,
8482 end: cursor,
8483 reversed: false,
8484 goal: SelectionGoal::None,
8485 }
8486 })
8487 .collect();
8488
8489 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8490 s.select(new_selections);
8491 });
8492 });
8493 }
8494
8495 pub fn join_lines_impl(
8496 &mut self,
8497 insert_whitespace: bool,
8498 window: &mut Window,
8499 cx: &mut Context<Self>,
8500 ) {
8501 if self.read_only(cx) {
8502 return;
8503 }
8504 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8505 for selection in self.selections.all::<Point>(cx) {
8506 let start = MultiBufferRow(selection.start.row);
8507 // Treat single line selections as if they include the next line. Otherwise this action
8508 // would do nothing for single line selections individual cursors.
8509 let end = if selection.start.row == selection.end.row {
8510 MultiBufferRow(selection.start.row + 1)
8511 } else {
8512 MultiBufferRow(selection.end.row)
8513 };
8514
8515 if let Some(last_row_range) = row_ranges.last_mut() {
8516 if start <= last_row_range.end {
8517 last_row_range.end = end;
8518 continue;
8519 }
8520 }
8521 row_ranges.push(start..end);
8522 }
8523
8524 let snapshot = self.buffer.read(cx).snapshot(cx);
8525 let mut cursor_positions = Vec::new();
8526 for row_range in &row_ranges {
8527 let anchor = snapshot.anchor_before(Point::new(
8528 row_range.end.previous_row().0,
8529 snapshot.line_len(row_range.end.previous_row()),
8530 ));
8531 cursor_positions.push(anchor..anchor);
8532 }
8533
8534 self.transact(window, cx, |this, window, cx| {
8535 for row_range in row_ranges.into_iter().rev() {
8536 for row in row_range.iter_rows().rev() {
8537 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8538 let next_line_row = row.next_row();
8539 let indent = snapshot.indent_size_for_line(next_line_row);
8540 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8541
8542 let replace =
8543 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8544 " "
8545 } else {
8546 ""
8547 };
8548
8549 this.buffer.update(cx, |buffer, cx| {
8550 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8551 });
8552 }
8553 }
8554
8555 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8556 s.select_anchor_ranges(cursor_positions)
8557 });
8558 });
8559 }
8560
8561 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8562 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8563 self.join_lines_impl(true, window, cx);
8564 }
8565
8566 pub fn sort_lines_case_sensitive(
8567 &mut self,
8568 _: &SortLinesCaseSensitive,
8569 window: &mut Window,
8570 cx: &mut Context<Self>,
8571 ) {
8572 self.manipulate_lines(window, cx, |lines| lines.sort())
8573 }
8574
8575 pub fn sort_lines_case_insensitive(
8576 &mut self,
8577 _: &SortLinesCaseInsensitive,
8578 window: &mut Window,
8579 cx: &mut Context<Self>,
8580 ) {
8581 self.manipulate_lines(window, cx, |lines| {
8582 lines.sort_by_key(|line| line.to_lowercase())
8583 })
8584 }
8585
8586 pub fn unique_lines_case_insensitive(
8587 &mut self,
8588 _: &UniqueLinesCaseInsensitive,
8589 window: &mut Window,
8590 cx: &mut Context<Self>,
8591 ) {
8592 self.manipulate_lines(window, cx, |lines| {
8593 let mut seen = HashSet::default();
8594 lines.retain(|line| seen.insert(line.to_lowercase()));
8595 })
8596 }
8597
8598 pub fn unique_lines_case_sensitive(
8599 &mut self,
8600 _: &UniqueLinesCaseSensitive,
8601 window: &mut Window,
8602 cx: &mut Context<Self>,
8603 ) {
8604 self.manipulate_lines(window, cx, |lines| {
8605 let mut seen = HashSet::default();
8606 lines.retain(|line| seen.insert(*line));
8607 })
8608 }
8609
8610 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8611 let Some(project) = self.project.clone() else {
8612 return;
8613 };
8614 self.reload(project, window, cx)
8615 .detach_and_notify_err(window, cx);
8616 }
8617
8618 pub fn restore_file(
8619 &mut self,
8620 _: &::git::RestoreFile,
8621 window: &mut Window,
8622 cx: &mut Context<Self>,
8623 ) {
8624 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8625 let mut buffer_ids = HashSet::default();
8626 let snapshot = self.buffer().read(cx).snapshot(cx);
8627 for selection in self.selections.all::<usize>(cx) {
8628 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8629 }
8630
8631 let buffer = self.buffer().read(cx);
8632 let ranges = buffer_ids
8633 .into_iter()
8634 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8635 .collect::<Vec<_>>();
8636
8637 self.restore_hunks_in_ranges(ranges, window, cx);
8638 }
8639
8640 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8641 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8642 let selections = self
8643 .selections
8644 .all(cx)
8645 .into_iter()
8646 .map(|s| s.range())
8647 .collect();
8648 self.restore_hunks_in_ranges(selections, window, cx);
8649 }
8650
8651 pub fn restore_hunks_in_ranges(
8652 &mut self,
8653 ranges: Vec<Range<Point>>,
8654 window: &mut Window,
8655 cx: &mut Context<Editor>,
8656 ) {
8657 let mut revert_changes = HashMap::default();
8658 let chunk_by = self
8659 .snapshot(window, cx)
8660 .hunks_for_ranges(ranges)
8661 .into_iter()
8662 .chunk_by(|hunk| hunk.buffer_id);
8663 for (buffer_id, hunks) in &chunk_by {
8664 let hunks = hunks.collect::<Vec<_>>();
8665 for hunk in &hunks {
8666 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8667 }
8668 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8669 }
8670 drop(chunk_by);
8671 if !revert_changes.is_empty() {
8672 self.transact(window, cx, |editor, window, cx| {
8673 editor.restore(revert_changes, window, cx);
8674 });
8675 }
8676 }
8677
8678 pub fn open_active_item_in_terminal(
8679 &mut self,
8680 _: &OpenInTerminal,
8681 window: &mut Window,
8682 cx: &mut Context<Self>,
8683 ) {
8684 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8685 let project_path = buffer.read(cx).project_path(cx)?;
8686 let project = self.project.as_ref()?.read(cx);
8687 let entry = project.entry_for_path(&project_path, cx)?;
8688 let parent = match &entry.canonical_path {
8689 Some(canonical_path) => canonical_path.to_path_buf(),
8690 None => project.absolute_path(&project_path, cx)?,
8691 }
8692 .parent()?
8693 .to_path_buf();
8694 Some(parent)
8695 }) {
8696 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8697 }
8698 }
8699
8700 fn set_breakpoint_context_menu(
8701 &mut self,
8702 display_row: DisplayRow,
8703 position: Option<Anchor>,
8704 clicked_point: gpui::Point<Pixels>,
8705 window: &mut Window,
8706 cx: &mut Context<Self>,
8707 ) {
8708 if !cx.has_flag::<Debugger>() {
8709 return;
8710 }
8711 let source = self
8712 .buffer
8713 .read(cx)
8714 .snapshot(cx)
8715 .anchor_before(Point::new(display_row.0, 0u32));
8716
8717 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8718
8719 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8720 self,
8721 source,
8722 clicked_point,
8723 context_menu,
8724 window,
8725 cx,
8726 );
8727 }
8728
8729 fn add_edit_breakpoint_block(
8730 &mut self,
8731 anchor: Anchor,
8732 breakpoint: &Breakpoint,
8733 edit_action: BreakpointPromptEditAction,
8734 window: &mut Window,
8735 cx: &mut Context<Self>,
8736 ) {
8737 let weak_editor = cx.weak_entity();
8738 let bp_prompt = cx.new(|cx| {
8739 BreakpointPromptEditor::new(
8740 weak_editor,
8741 anchor,
8742 breakpoint.clone(),
8743 edit_action,
8744 window,
8745 cx,
8746 )
8747 });
8748
8749 let height = bp_prompt.update(cx, |this, cx| {
8750 this.prompt
8751 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8752 });
8753 let cloned_prompt = bp_prompt.clone();
8754 let blocks = vec![BlockProperties {
8755 style: BlockStyle::Sticky,
8756 placement: BlockPlacement::Above(anchor),
8757 height: Some(height),
8758 render: Arc::new(move |cx| {
8759 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8760 cloned_prompt.clone().into_any_element()
8761 }),
8762 priority: 0,
8763 }];
8764
8765 let focus_handle = bp_prompt.focus_handle(cx);
8766 window.focus(&focus_handle);
8767
8768 let block_ids = self.insert_blocks(blocks, None, cx);
8769 bp_prompt.update(cx, |prompt, _| {
8770 prompt.add_block_ids(block_ids);
8771 });
8772 }
8773
8774 fn breakpoint_at_cursor_head(
8775 &self,
8776 window: &mut Window,
8777 cx: &mut Context<Self>,
8778 ) -> Option<(Anchor, Breakpoint)> {
8779 let cursor_position: Point = self.selections.newest(cx).head();
8780 self.breakpoint_at_row(cursor_position.row, window, cx)
8781 }
8782
8783 pub(crate) fn breakpoint_at_row(
8784 &self,
8785 row: u32,
8786 window: &mut Window,
8787 cx: &mut Context<Self>,
8788 ) -> Option<(Anchor, Breakpoint)> {
8789 let snapshot = self.snapshot(window, cx);
8790 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8791
8792 let project = self.project.clone()?;
8793
8794 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8795 snapshot
8796 .buffer_snapshot
8797 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8798 })?;
8799
8800 let enclosing_excerpt = breakpoint_position.excerpt_id;
8801 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8802 let buffer_snapshot = buffer.read(cx).snapshot();
8803
8804 let row = buffer_snapshot
8805 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8806 .row;
8807
8808 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8809 let anchor_end = snapshot
8810 .buffer_snapshot
8811 .anchor_after(Point::new(row, line_len));
8812
8813 let bp = self
8814 .breakpoint_store
8815 .as_ref()?
8816 .read_with(cx, |breakpoint_store, cx| {
8817 breakpoint_store
8818 .breakpoints(
8819 &buffer,
8820 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8821 &buffer_snapshot,
8822 cx,
8823 )
8824 .next()
8825 .and_then(|(anchor, bp)| {
8826 let breakpoint_row = buffer_snapshot
8827 .summary_for_anchor::<text::PointUtf16>(anchor)
8828 .row;
8829
8830 if breakpoint_row == row {
8831 snapshot
8832 .buffer_snapshot
8833 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8834 .map(|anchor| (anchor, bp.clone()))
8835 } else {
8836 None
8837 }
8838 })
8839 });
8840 bp
8841 }
8842
8843 pub fn edit_log_breakpoint(
8844 &mut self,
8845 _: &EditLogBreakpoint,
8846 window: &mut Window,
8847 cx: &mut Context<Self>,
8848 ) {
8849 let (anchor, bp) = self
8850 .breakpoint_at_cursor_head(window, cx)
8851 .unwrap_or_else(|| {
8852 let cursor_position: Point = self.selections.newest(cx).head();
8853
8854 let breakpoint_position = self
8855 .snapshot(window, cx)
8856 .display_snapshot
8857 .buffer_snapshot
8858 .anchor_after(Point::new(cursor_position.row, 0));
8859
8860 (
8861 breakpoint_position,
8862 Breakpoint {
8863 message: None,
8864 state: BreakpointState::Enabled,
8865 condition: None,
8866 hit_condition: None,
8867 },
8868 )
8869 });
8870
8871 self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
8872 }
8873
8874 pub fn enable_breakpoint(
8875 &mut self,
8876 _: &crate::actions::EnableBreakpoint,
8877 window: &mut Window,
8878 cx: &mut Context<Self>,
8879 ) {
8880 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8881 if breakpoint.is_disabled() {
8882 self.edit_breakpoint_at_anchor(
8883 anchor,
8884 breakpoint,
8885 BreakpointEditAction::InvertState,
8886 cx,
8887 );
8888 }
8889 }
8890 }
8891
8892 pub fn disable_breakpoint(
8893 &mut self,
8894 _: &crate::actions::DisableBreakpoint,
8895 window: &mut Window,
8896 cx: &mut Context<Self>,
8897 ) {
8898 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8899 if breakpoint.is_enabled() {
8900 self.edit_breakpoint_at_anchor(
8901 anchor,
8902 breakpoint,
8903 BreakpointEditAction::InvertState,
8904 cx,
8905 );
8906 }
8907 }
8908 }
8909
8910 pub fn toggle_breakpoint(
8911 &mut self,
8912 _: &crate::actions::ToggleBreakpoint,
8913 window: &mut Window,
8914 cx: &mut Context<Self>,
8915 ) {
8916 let edit_action = BreakpointEditAction::Toggle;
8917
8918 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8919 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8920 } else {
8921 let cursor_position: Point = self.selections.newest(cx).head();
8922
8923 let breakpoint_position = self
8924 .snapshot(window, cx)
8925 .display_snapshot
8926 .buffer_snapshot
8927 .anchor_after(Point::new(cursor_position.row, 0));
8928
8929 self.edit_breakpoint_at_anchor(
8930 breakpoint_position,
8931 Breakpoint::new_standard(),
8932 edit_action,
8933 cx,
8934 );
8935 }
8936 }
8937
8938 pub fn edit_breakpoint_at_anchor(
8939 &mut self,
8940 breakpoint_position: Anchor,
8941 breakpoint: Breakpoint,
8942 edit_action: BreakpointEditAction,
8943 cx: &mut Context<Self>,
8944 ) {
8945 let Some(breakpoint_store) = &self.breakpoint_store else {
8946 return;
8947 };
8948
8949 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8950 if breakpoint_position == Anchor::min() {
8951 self.buffer()
8952 .read(cx)
8953 .excerpt_buffer_ids()
8954 .into_iter()
8955 .next()
8956 } else {
8957 None
8958 }
8959 }) else {
8960 return;
8961 };
8962
8963 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8964 return;
8965 };
8966
8967 breakpoint_store.update(cx, |breakpoint_store, cx| {
8968 breakpoint_store.toggle_breakpoint(
8969 buffer,
8970 (breakpoint_position.text_anchor, breakpoint),
8971 edit_action,
8972 cx,
8973 );
8974 });
8975
8976 cx.notify();
8977 }
8978
8979 #[cfg(any(test, feature = "test-support"))]
8980 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8981 self.breakpoint_store.clone()
8982 }
8983
8984 pub fn prepare_restore_change(
8985 &self,
8986 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8987 hunk: &MultiBufferDiffHunk,
8988 cx: &mut App,
8989 ) -> Option<()> {
8990 if hunk.is_created_file() {
8991 return None;
8992 }
8993 let buffer = self.buffer.read(cx);
8994 let diff = buffer.diff_for(hunk.buffer_id)?;
8995 let buffer = buffer.buffer(hunk.buffer_id)?;
8996 let buffer = buffer.read(cx);
8997 let original_text = diff
8998 .read(cx)
8999 .base_text()
9000 .as_rope()
9001 .slice(hunk.diff_base_byte_range.clone());
9002 let buffer_snapshot = buffer.snapshot();
9003 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9004 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9005 probe
9006 .0
9007 .start
9008 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9009 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9010 }) {
9011 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9012 Some(())
9013 } else {
9014 None
9015 }
9016 }
9017
9018 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9019 self.manipulate_lines(window, cx, |lines| lines.reverse())
9020 }
9021
9022 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9023 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9024 }
9025
9026 fn manipulate_lines<Fn>(
9027 &mut self,
9028 window: &mut Window,
9029 cx: &mut Context<Self>,
9030 mut callback: Fn,
9031 ) where
9032 Fn: FnMut(&mut Vec<&str>),
9033 {
9034 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9035
9036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9037 let buffer = self.buffer.read(cx).snapshot(cx);
9038
9039 let mut edits = Vec::new();
9040
9041 let selections = self.selections.all::<Point>(cx);
9042 let mut selections = selections.iter().peekable();
9043 let mut contiguous_row_selections = Vec::new();
9044 let mut new_selections = Vec::new();
9045 let mut added_lines = 0;
9046 let mut removed_lines = 0;
9047
9048 while let Some(selection) = selections.next() {
9049 let (start_row, end_row) = consume_contiguous_rows(
9050 &mut contiguous_row_selections,
9051 selection,
9052 &display_map,
9053 &mut selections,
9054 );
9055
9056 let start_point = Point::new(start_row.0, 0);
9057 let end_point = Point::new(
9058 end_row.previous_row().0,
9059 buffer.line_len(end_row.previous_row()),
9060 );
9061 let text = buffer
9062 .text_for_range(start_point..end_point)
9063 .collect::<String>();
9064
9065 let mut lines = text.split('\n').collect_vec();
9066
9067 let lines_before = lines.len();
9068 callback(&mut lines);
9069 let lines_after = lines.len();
9070
9071 edits.push((start_point..end_point, lines.join("\n")));
9072
9073 // Selections must change based on added and removed line count
9074 let start_row =
9075 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9076 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9077 new_selections.push(Selection {
9078 id: selection.id,
9079 start: start_row,
9080 end: end_row,
9081 goal: SelectionGoal::None,
9082 reversed: selection.reversed,
9083 });
9084
9085 if lines_after > lines_before {
9086 added_lines += lines_after - lines_before;
9087 } else if lines_before > lines_after {
9088 removed_lines += lines_before - lines_after;
9089 }
9090 }
9091
9092 self.transact(window, cx, |this, window, cx| {
9093 let buffer = this.buffer.update(cx, |buffer, cx| {
9094 buffer.edit(edits, None, cx);
9095 buffer.snapshot(cx)
9096 });
9097
9098 // Recalculate offsets on newly edited buffer
9099 let new_selections = new_selections
9100 .iter()
9101 .map(|s| {
9102 let start_point = Point::new(s.start.0, 0);
9103 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9104 Selection {
9105 id: s.id,
9106 start: buffer.point_to_offset(start_point),
9107 end: buffer.point_to_offset(end_point),
9108 goal: s.goal,
9109 reversed: s.reversed,
9110 }
9111 })
9112 .collect();
9113
9114 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9115 s.select(new_selections);
9116 });
9117
9118 this.request_autoscroll(Autoscroll::fit(), cx);
9119 });
9120 }
9121
9122 pub fn convert_to_upper_case(
9123 &mut self,
9124 _: &ConvertToUpperCase,
9125 window: &mut Window,
9126 cx: &mut Context<Self>,
9127 ) {
9128 self.manipulate_text(window, cx, |text| text.to_uppercase())
9129 }
9130
9131 pub fn convert_to_lower_case(
9132 &mut self,
9133 _: &ConvertToLowerCase,
9134 window: &mut Window,
9135 cx: &mut Context<Self>,
9136 ) {
9137 self.manipulate_text(window, cx, |text| text.to_lowercase())
9138 }
9139
9140 pub fn convert_to_title_case(
9141 &mut self,
9142 _: &ConvertToTitleCase,
9143 window: &mut Window,
9144 cx: &mut Context<Self>,
9145 ) {
9146 self.manipulate_text(window, cx, |text| {
9147 text.split('\n')
9148 .map(|line| line.to_case(Case::Title))
9149 .join("\n")
9150 })
9151 }
9152
9153 pub fn convert_to_snake_case(
9154 &mut self,
9155 _: &ConvertToSnakeCase,
9156 window: &mut Window,
9157 cx: &mut Context<Self>,
9158 ) {
9159 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9160 }
9161
9162 pub fn convert_to_kebab_case(
9163 &mut self,
9164 _: &ConvertToKebabCase,
9165 window: &mut Window,
9166 cx: &mut Context<Self>,
9167 ) {
9168 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9169 }
9170
9171 pub fn convert_to_upper_camel_case(
9172 &mut self,
9173 _: &ConvertToUpperCamelCase,
9174 window: &mut Window,
9175 cx: &mut Context<Self>,
9176 ) {
9177 self.manipulate_text(window, cx, |text| {
9178 text.split('\n')
9179 .map(|line| line.to_case(Case::UpperCamel))
9180 .join("\n")
9181 })
9182 }
9183
9184 pub fn convert_to_lower_camel_case(
9185 &mut self,
9186 _: &ConvertToLowerCamelCase,
9187 window: &mut Window,
9188 cx: &mut Context<Self>,
9189 ) {
9190 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9191 }
9192
9193 pub fn convert_to_opposite_case(
9194 &mut self,
9195 _: &ConvertToOppositeCase,
9196 window: &mut Window,
9197 cx: &mut Context<Self>,
9198 ) {
9199 self.manipulate_text(window, cx, |text| {
9200 text.chars()
9201 .fold(String::with_capacity(text.len()), |mut t, c| {
9202 if c.is_uppercase() {
9203 t.extend(c.to_lowercase());
9204 } else {
9205 t.extend(c.to_uppercase());
9206 }
9207 t
9208 })
9209 })
9210 }
9211
9212 pub fn convert_to_rot13(
9213 &mut self,
9214 _: &ConvertToRot13,
9215 window: &mut Window,
9216 cx: &mut Context<Self>,
9217 ) {
9218 self.manipulate_text(window, cx, |text| {
9219 text.chars()
9220 .map(|c| match c {
9221 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9222 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9223 _ => c,
9224 })
9225 .collect()
9226 })
9227 }
9228
9229 pub fn convert_to_rot47(
9230 &mut self,
9231 _: &ConvertToRot47,
9232 window: &mut Window,
9233 cx: &mut Context<Self>,
9234 ) {
9235 self.manipulate_text(window, cx, |text| {
9236 text.chars()
9237 .map(|c| {
9238 let code_point = c as u32;
9239 if code_point >= 33 && code_point <= 126 {
9240 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9241 }
9242 c
9243 })
9244 .collect()
9245 })
9246 }
9247
9248 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9249 where
9250 Fn: FnMut(&str) -> String,
9251 {
9252 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9253 let buffer = self.buffer.read(cx).snapshot(cx);
9254
9255 let mut new_selections = Vec::new();
9256 let mut edits = Vec::new();
9257 let mut selection_adjustment = 0i32;
9258
9259 for selection in self.selections.all::<usize>(cx) {
9260 let selection_is_empty = selection.is_empty();
9261
9262 let (start, end) = if selection_is_empty {
9263 let word_range = movement::surrounding_word(
9264 &display_map,
9265 selection.start.to_display_point(&display_map),
9266 );
9267 let start = word_range.start.to_offset(&display_map, Bias::Left);
9268 let end = word_range.end.to_offset(&display_map, Bias::Left);
9269 (start, end)
9270 } else {
9271 (selection.start, selection.end)
9272 };
9273
9274 let text = buffer.text_for_range(start..end).collect::<String>();
9275 let old_length = text.len() as i32;
9276 let text = callback(&text);
9277
9278 new_selections.push(Selection {
9279 start: (start as i32 - selection_adjustment) as usize,
9280 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9281 goal: SelectionGoal::None,
9282 ..selection
9283 });
9284
9285 selection_adjustment += old_length - text.len() as i32;
9286
9287 edits.push((start..end, text));
9288 }
9289
9290 self.transact(window, cx, |this, window, cx| {
9291 this.buffer.update(cx, |buffer, cx| {
9292 buffer.edit(edits, None, cx);
9293 });
9294
9295 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9296 s.select(new_selections);
9297 });
9298
9299 this.request_autoscroll(Autoscroll::fit(), cx);
9300 });
9301 }
9302
9303 pub fn duplicate(
9304 &mut self,
9305 upwards: bool,
9306 whole_lines: bool,
9307 window: &mut Window,
9308 cx: &mut Context<Self>,
9309 ) {
9310 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9311
9312 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9313 let buffer = &display_map.buffer_snapshot;
9314 let selections = self.selections.all::<Point>(cx);
9315
9316 let mut edits = Vec::new();
9317 let mut selections_iter = selections.iter().peekable();
9318 while let Some(selection) = selections_iter.next() {
9319 let mut rows = selection.spanned_rows(false, &display_map);
9320 // duplicate line-wise
9321 if whole_lines || selection.start == selection.end {
9322 // Avoid duplicating the same lines twice.
9323 while let Some(next_selection) = selections_iter.peek() {
9324 let next_rows = next_selection.spanned_rows(false, &display_map);
9325 if next_rows.start < rows.end {
9326 rows.end = next_rows.end;
9327 selections_iter.next().unwrap();
9328 } else {
9329 break;
9330 }
9331 }
9332
9333 // Copy the text from the selected row region and splice it either at the start
9334 // or end of the region.
9335 let start = Point::new(rows.start.0, 0);
9336 let end = Point::new(
9337 rows.end.previous_row().0,
9338 buffer.line_len(rows.end.previous_row()),
9339 );
9340 let text = buffer
9341 .text_for_range(start..end)
9342 .chain(Some("\n"))
9343 .collect::<String>();
9344 let insert_location = if upwards {
9345 Point::new(rows.end.0, 0)
9346 } else {
9347 start
9348 };
9349 edits.push((insert_location..insert_location, text));
9350 } else {
9351 // duplicate character-wise
9352 let start = selection.start;
9353 let end = selection.end;
9354 let text = buffer.text_for_range(start..end).collect::<String>();
9355 edits.push((selection.end..selection.end, text));
9356 }
9357 }
9358
9359 self.transact(window, cx, |this, _, cx| {
9360 this.buffer.update(cx, |buffer, cx| {
9361 buffer.edit(edits, None, cx);
9362 });
9363
9364 this.request_autoscroll(Autoscroll::fit(), cx);
9365 });
9366 }
9367
9368 pub fn duplicate_line_up(
9369 &mut self,
9370 _: &DuplicateLineUp,
9371 window: &mut Window,
9372 cx: &mut Context<Self>,
9373 ) {
9374 self.duplicate(true, true, window, cx);
9375 }
9376
9377 pub fn duplicate_line_down(
9378 &mut self,
9379 _: &DuplicateLineDown,
9380 window: &mut Window,
9381 cx: &mut Context<Self>,
9382 ) {
9383 self.duplicate(false, true, window, cx);
9384 }
9385
9386 pub fn duplicate_selection(
9387 &mut self,
9388 _: &DuplicateSelection,
9389 window: &mut Window,
9390 cx: &mut Context<Self>,
9391 ) {
9392 self.duplicate(false, false, window, cx);
9393 }
9394
9395 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9396 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9397
9398 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9399 let buffer = self.buffer.read(cx).snapshot(cx);
9400
9401 let mut edits = Vec::new();
9402 let mut unfold_ranges = Vec::new();
9403 let mut refold_creases = Vec::new();
9404
9405 let selections = self.selections.all::<Point>(cx);
9406 let mut selections = selections.iter().peekable();
9407 let mut contiguous_row_selections = Vec::new();
9408 let mut new_selections = Vec::new();
9409
9410 while let Some(selection) = selections.next() {
9411 // Find all the selections that span a contiguous row range
9412 let (start_row, end_row) = consume_contiguous_rows(
9413 &mut contiguous_row_selections,
9414 selection,
9415 &display_map,
9416 &mut selections,
9417 );
9418
9419 // Move the text spanned by the row range to be before the line preceding the row range
9420 if start_row.0 > 0 {
9421 let range_to_move = Point::new(
9422 start_row.previous_row().0,
9423 buffer.line_len(start_row.previous_row()),
9424 )
9425 ..Point::new(
9426 end_row.previous_row().0,
9427 buffer.line_len(end_row.previous_row()),
9428 );
9429 let insertion_point = display_map
9430 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9431 .0;
9432
9433 // Don't move lines across excerpts
9434 if buffer
9435 .excerpt_containing(insertion_point..range_to_move.end)
9436 .is_some()
9437 {
9438 let text = buffer
9439 .text_for_range(range_to_move.clone())
9440 .flat_map(|s| s.chars())
9441 .skip(1)
9442 .chain(['\n'])
9443 .collect::<String>();
9444
9445 edits.push((
9446 buffer.anchor_after(range_to_move.start)
9447 ..buffer.anchor_before(range_to_move.end),
9448 String::new(),
9449 ));
9450 let insertion_anchor = buffer.anchor_after(insertion_point);
9451 edits.push((insertion_anchor..insertion_anchor, text));
9452
9453 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9454
9455 // Move selections up
9456 new_selections.extend(contiguous_row_selections.drain(..).map(
9457 |mut selection| {
9458 selection.start.row -= row_delta;
9459 selection.end.row -= row_delta;
9460 selection
9461 },
9462 ));
9463
9464 // Move folds up
9465 unfold_ranges.push(range_to_move.clone());
9466 for fold in display_map.folds_in_range(
9467 buffer.anchor_before(range_to_move.start)
9468 ..buffer.anchor_after(range_to_move.end),
9469 ) {
9470 let mut start = fold.range.start.to_point(&buffer);
9471 let mut end = fold.range.end.to_point(&buffer);
9472 start.row -= row_delta;
9473 end.row -= row_delta;
9474 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9475 }
9476 }
9477 }
9478
9479 // If we didn't move line(s), preserve the existing selections
9480 new_selections.append(&mut contiguous_row_selections);
9481 }
9482
9483 self.transact(window, cx, |this, window, cx| {
9484 this.unfold_ranges(&unfold_ranges, true, true, cx);
9485 this.buffer.update(cx, |buffer, cx| {
9486 for (range, text) in edits {
9487 buffer.edit([(range, text)], None, cx);
9488 }
9489 });
9490 this.fold_creases(refold_creases, true, window, cx);
9491 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9492 s.select(new_selections);
9493 })
9494 });
9495 }
9496
9497 pub fn move_line_down(
9498 &mut self,
9499 _: &MoveLineDown,
9500 window: &mut Window,
9501 cx: &mut Context<Self>,
9502 ) {
9503 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9504
9505 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9506 let buffer = self.buffer.read(cx).snapshot(cx);
9507
9508 let mut edits = Vec::new();
9509 let mut unfold_ranges = Vec::new();
9510 let mut refold_creases = Vec::new();
9511
9512 let selections = self.selections.all::<Point>(cx);
9513 let mut selections = selections.iter().peekable();
9514 let mut contiguous_row_selections = Vec::new();
9515 let mut new_selections = Vec::new();
9516
9517 while let Some(selection) = selections.next() {
9518 // Find all the selections that span a contiguous row range
9519 let (start_row, end_row) = consume_contiguous_rows(
9520 &mut contiguous_row_selections,
9521 selection,
9522 &display_map,
9523 &mut selections,
9524 );
9525
9526 // Move the text spanned by the row range to be after the last line of the row range
9527 if end_row.0 <= buffer.max_point().row {
9528 let range_to_move =
9529 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9530 let insertion_point = display_map
9531 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9532 .0;
9533
9534 // Don't move lines across excerpt boundaries
9535 if buffer
9536 .excerpt_containing(range_to_move.start..insertion_point)
9537 .is_some()
9538 {
9539 let mut text = String::from("\n");
9540 text.extend(buffer.text_for_range(range_to_move.clone()));
9541 text.pop(); // Drop trailing newline
9542 edits.push((
9543 buffer.anchor_after(range_to_move.start)
9544 ..buffer.anchor_before(range_to_move.end),
9545 String::new(),
9546 ));
9547 let insertion_anchor = buffer.anchor_after(insertion_point);
9548 edits.push((insertion_anchor..insertion_anchor, text));
9549
9550 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9551
9552 // Move selections down
9553 new_selections.extend(contiguous_row_selections.drain(..).map(
9554 |mut selection| {
9555 selection.start.row += row_delta;
9556 selection.end.row += row_delta;
9557 selection
9558 },
9559 ));
9560
9561 // Move folds down
9562 unfold_ranges.push(range_to_move.clone());
9563 for fold in display_map.folds_in_range(
9564 buffer.anchor_before(range_to_move.start)
9565 ..buffer.anchor_after(range_to_move.end),
9566 ) {
9567 let mut start = fold.range.start.to_point(&buffer);
9568 let mut end = fold.range.end.to_point(&buffer);
9569 start.row += row_delta;
9570 end.row += row_delta;
9571 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9572 }
9573 }
9574 }
9575
9576 // If we didn't move line(s), preserve the existing selections
9577 new_selections.append(&mut contiguous_row_selections);
9578 }
9579
9580 self.transact(window, cx, |this, window, cx| {
9581 this.unfold_ranges(&unfold_ranges, true, true, cx);
9582 this.buffer.update(cx, |buffer, cx| {
9583 for (range, text) in edits {
9584 buffer.edit([(range, text)], None, cx);
9585 }
9586 });
9587 this.fold_creases(refold_creases, true, window, cx);
9588 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9589 s.select(new_selections)
9590 });
9591 });
9592 }
9593
9594 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9595 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9596 let text_layout_details = &self.text_layout_details(window);
9597 self.transact(window, cx, |this, window, cx| {
9598 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9599 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9600 s.move_with(|display_map, selection| {
9601 if !selection.is_empty() {
9602 return;
9603 }
9604
9605 let mut head = selection.head();
9606 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9607 if head.column() == display_map.line_len(head.row()) {
9608 transpose_offset = display_map
9609 .buffer_snapshot
9610 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9611 }
9612
9613 if transpose_offset == 0 {
9614 return;
9615 }
9616
9617 *head.column_mut() += 1;
9618 head = display_map.clip_point(head, Bias::Right);
9619 let goal = SelectionGoal::HorizontalPosition(
9620 display_map
9621 .x_for_display_point(head, text_layout_details)
9622 .into(),
9623 );
9624 selection.collapse_to(head, goal);
9625
9626 let transpose_start = display_map
9627 .buffer_snapshot
9628 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9629 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9630 let transpose_end = display_map
9631 .buffer_snapshot
9632 .clip_offset(transpose_offset + 1, Bias::Right);
9633 if let Some(ch) =
9634 display_map.buffer_snapshot.chars_at(transpose_start).next()
9635 {
9636 edits.push((transpose_start..transpose_offset, String::new()));
9637 edits.push((transpose_end..transpose_end, ch.to_string()));
9638 }
9639 }
9640 });
9641 edits
9642 });
9643 this.buffer
9644 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9645 let selections = this.selections.all::<usize>(cx);
9646 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9647 s.select(selections);
9648 });
9649 });
9650 }
9651
9652 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9653 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9654 self.rewrap_impl(RewrapOptions::default(), cx)
9655 }
9656
9657 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9658 let buffer = self.buffer.read(cx).snapshot(cx);
9659 let selections = self.selections.all::<Point>(cx);
9660 let mut selections = selections.iter().peekable();
9661
9662 let mut edits = Vec::new();
9663 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9664
9665 while let Some(selection) = selections.next() {
9666 let mut start_row = selection.start.row;
9667 let mut end_row = selection.end.row;
9668
9669 // Skip selections that overlap with a range that has already been rewrapped.
9670 let selection_range = start_row..end_row;
9671 if rewrapped_row_ranges
9672 .iter()
9673 .any(|range| range.overlaps(&selection_range))
9674 {
9675 continue;
9676 }
9677
9678 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9679
9680 // Since not all lines in the selection may be at the same indent
9681 // level, choose the indent size that is the most common between all
9682 // of the lines.
9683 //
9684 // If there is a tie, we use the deepest indent.
9685 let (indent_size, indent_end) = {
9686 let mut indent_size_occurrences = HashMap::default();
9687 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9688
9689 for row in start_row..=end_row {
9690 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9691 rows_by_indent_size.entry(indent).or_default().push(row);
9692 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9693 }
9694
9695 let indent_size = indent_size_occurrences
9696 .into_iter()
9697 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9698 .map(|(indent, _)| indent)
9699 .unwrap_or_default();
9700 let row = rows_by_indent_size[&indent_size][0];
9701 let indent_end = Point::new(row, indent_size.len);
9702
9703 (indent_size, indent_end)
9704 };
9705
9706 let mut line_prefix = indent_size.chars().collect::<String>();
9707
9708 let mut inside_comment = false;
9709 if let Some(comment_prefix) =
9710 buffer
9711 .language_scope_at(selection.head())
9712 .and_then(|language| {
9713 language
9714 .line_comment_prefixes()
9715 .iter()
9716 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9717 .cloned()
9718 })
9719 {
9720 line_prefix.push_str(&comment_prefix);
9721 inside_comment = true;
9722 }
9723
9724 let language_settings = buffer.language_settings_at(selection.head(), cx);
9725 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9726 RewrapBehavior::InComments => inside_comment,
9727 RewrapBehavior::InSelections => !selection.is_empty(),
9728 RewrapBehavior::Anywhere => true,
9729 };
9730
9731 let should_rewrap = options.override_language_settings
9732 || allow_rewrap_based_on_language
9733 || self.hard_wrap.is_some();
9734 if !should_rewrap {
9735 continue;
9736 }
9737
9738 if selection.is_empty() {
9739 'expand_upwards: while start_row > 0 {
9740 let prev_row = start_row - 1;
9741 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9742 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9743 {
9744 start_row = prev_row;
9745 } else {
9746 break 'expand_upwards;
9747 }
9748 }
9749
9750 'expand_downwards: while end_row < buffer.max_point().row {
9751 let next_row = end_row + 1;
9752 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9753 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9754 {
9755 end_row = next_row;
9756 } else {
9757 break 'expand_downwards;
9758 }
9759 }
9760 }
9761
9762 let start = Point::new(start_row, 0);
9763 let start_offset = start.to_offset(&buffer);
9764 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9765 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9766 let Some(lines_without_prefixes) = selection_text
9767 .lines()
9768 .map(|line| {
9769 line.strip_prefix(&line_prefix)
9770 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9771 .ok_or_else(|| {
9772 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9773 })
9774 })
9775 .collect::<Result<Vec<_>, _>>()
9776 .log_err()
9777 else {
9778 continue;
9779 };
9780
9781 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9782 buffer
9783 .language_settings_at(Point::new(start_row, 0), cx)
9784 .preferred_line_length as usize
9785 });
9786 let wrapped_text = wrap_with_prefix(
9787 line_prefix,
9788 lines_without_prefixes.join("\n"),
9789 wrap_column,
9790 tab_size,
9791 options.preserve_existing_whitespace,
9792 );
9793
9794 // TODO: should always use char-based diff while still supporting cursor behavior that
9795 // matches vim.
9796 let mut diff_options = DiffOptions::default();
9797 if options.override_language_settings {
9798 diff_options.max_word_diff_len = 0;
9799 diff_options.max_word_diff_line_count = 0;
9800 } else {
9801 diff_options.max_word_diff_len = usize::MAX;
9802 diff_options.max_word_diff_line_count = usize::MAX;
9803 }
9804
9805 for (old_range, new_text) in
9806 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9807 {
9808 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9809 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9810 edits.push((edit_start..edit_end, new_text));
9811 }
9812
9813 rewrapped_row_ranges.push(start_row..=end_row);
9814 }
9815
9816 self.buffer
9817 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9818 }
9819
9820 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9821 let mut text = String::new();
9822 let buffer = self.buffer.read(cx).snapshot(cx);
9823 let mut selections = self.selections.all::<Point>(cx);
9824 let mut clipboard_selections = Vec::with_capacity(selections.len());
9825 {
9826 let max_point = buffer.max_point();
9827 let mut is_first = true;
9828 for selection in &mut selections {
9829 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9830 if is_entire_line {
9831 selection.start = Point::new(selection.start.row, 0);
9832 if !selection.is_empty() && selection.end.column == 0 {
9833 selection.end = cmp::min(max_point, selection.end);
9834 } else {
9835 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9836 }
9837 selection.goal = SelectionGoal::None;
9838 }
9839 if is_first {
9840 is_first = false;
9841 } else {
9842 text += "\n";
9843 }
9844 let mut len = 0;
9845 for chunk in buffer.text_for_range(selection.start..selection.end) {
9846 text.push_str(chunk);
9847 len += chunk.len();
9848 }
9849 clipboard_selections.push(ClipboardSelection {
9850 len,
9851 is_entire_line,
9852 first_line_indent: buffer
9853 .indent_size_for_line(MultiBufferRow(selection.start.row))
9854 .len,
9855 });
9856 }
9857 }
9858
9859 self.transact(window, cx, |this, window, cx| {
9860 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9861 s.select(selections);
9862 });
9863 this.insert("", window, cx);
9864 });
9865 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9866 }
9867
9868 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9869 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9870 let item = self.cut_common(window, cx);
9871 cx.write_to_clipboard(item);
9872 }
9873
9874 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9875 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9876 self.change_selections(None, window, cx, |s| {
9877 s.move_with(|snapshot, sel| {
9878 if sel.is_empty() {
9879 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9880 }
9881 });
9882 });
9883 let item = self.cut_common(window, cx);
9884 cx.set_global(KillRing(item))
9885 }
9886
9887 pub fn kill_ring_yank(
9888 &mut self,
9889 _: &KillRingYank,
9890 window: &mut Window,
9891 cx: &mut Context<Self>,
9892 ) {
9893 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9894 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9895 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9896 (kill_ring.text().to_string(), kill_ring.metadata_json())
9897 } else {
9898 return;
9899 }
9900 } else {
9901 return;
9902 };
9903 self.do_paste(&text, metadata, false, window, cx);
9904 }
9905
9906 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9907 self.do_copy(true, cx);
9908 }
9909
9910 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9911 self.do_copy(false, cx);
9912 }
9913
9914 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9915 let selections = self.selections.all::<Point>(cx);
9916 let buffer = self.buffer.read(cx).read(cx);
9917 let mut text = String::new();
9918
9919 let mut clipboard_selections = Vec::with_capacity(selections.len());
9920 {
9921 let max_point = buffer.max_point();
9922 let mut is_first = true;
9923 for selection in &selections {
9924 let mut start = selection.start;
9925 let mut end = selection.end;
9926 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9927 if is_entire_line {
9928 start = Point::new(start.row, 0);
9929 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9930 }
9931
9932 let mut trimmed_selections = Vec::new();
9933 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9934 let row = MultiBufferRow(start.row);
9935 let first_indent = buffer.indent_size_for_line(row);
9936 if first_indent.len == 0 || start.column > first_indent.len {
9937 trimmed_selections.push(start..end);
9938 } else {
9939 trimmed_selections.push(
9940 Point::new(row.0, first_indent.len)
9941 ..Point::new(row.0, buffer.line_len(row)),
9942 );
9943 for row in start.row + 1..=end.row {
9944 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
9945 if row_indent_size.len >= first_indent.len {
9946 trimmed_selections.push(
9947 Point::new(row, first_indent.len)
9948 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
9949 );
9950 } else {
9951 trimmed_selections.clear();
9952 trimmed_selections.push(start..end);
9953 break;
9954 }
9955 }
9956 }
9957 } else {
9958 trimmed_selections.push(start..end);
9959 }
9960
9961 for trimmed_range in trimmed_selections {
9962 if is_first {
9963 is_first = false;
9964 } else {
9965 text += "\n";
9966 }
9967 let mut len = 0;
9968 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
9969 text.push_str(chunk);
9970 len += chunk.len();
9971 }
9972 clipboard_selections.push(ClipboardSelection {
9973 len,
9974 is_entire_line,
9975 first_line_indent: buffer
9976 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
9977 .len,
9978 });
9979 }
9980 }
9981 }
9982
9983 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9984 text,
9985 clipboard_selections,
9986 ));
9987 }
9988
9989 pub fn do_paste(
9990 &mut self,
9991 text: &String,
9992 clipboard_selections: Option<Vec<ClipboardSelection>>,
9993 handle_entire_lines: bool,
9994 window: &mut Window,
9995 cx: &mut Context<Self>,
9996 ) {
9997 if self.read_only(cx) {
9998 return;
9999 }
10000
10001 let clipboard_text = Cow::Borrowed(text);
10002
10003 self.transact(window, cx, |this, window, cx| {
10004 if let Some(mut clipboard_selections) = clipboard_selections {
10005 let old_selections = this.selections.all::<usize>(cx);
10006 let all_selections_were_entire_line =
10007 clipboard_selections.iter().all(|s| s.is_entire_line);
10008 let first_selection_indent_column =
10009 clipboard_selections.first().map(|s| s.first_line_indent);
10010 if clipboard_selections.len() != old_selections.len() {
10011 clipboard_selections.drain(..);
10012 }
10013 let cursor_offset = this.selections.last::<usize>(cx).head();
10014 let mut auto_indent_on_paste = true;
10015
10016 this.buffer.update(cx, |buffer, cx| {
10017 let snapshot = buffer.read(cx);
10018 auto_indent_on_paste = snapshot
10019 .language_settings_at(cursor_offset, cx)
10020 .auto_indent_on_paste;
10021
10022 let mut start_offset = 0;
10023 let mut edits = Vec::new();
10024 let mut original_indent_columns = Vec::new();
10025 for (ix, selection) in old_selections.iter().enumerate() {
10026 let to_insert;
10027 let entire_line;
10028 let original_indent_column;
10029 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10030 let end_offset = start_offset + clipboard_selection.len;
10031 to_insert = &clipboard_text[start_offset..end_offset];
10032 entire_line = clipboard_selection.is_entire_line;
10033 start_offset = end_offset + 1;
10034 original_indent_column = Some(clipboard_selection.first_line_indent);
10035 } else {
10036 to_insert = clipboard_text.as_str();
10037 entire_line = all_selections_were_entire_line;
10038 original_indent_column = first_selection_indent_column
10039 }
10040
10041 // If the corresponding selection was empty when this slice of the
10042 // clipboard text was written, then the entire line containing the
10043 // selection was copied. If this selection is also currently empty,
10044 // then paste the line before the current line of the buffer.
10045 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10046 let column = selection.start.to_point(&snapshot).column as usize;
10047 let line_start = selection.start - column;
10048 line_start..line_start
10049 } else {
10050 selection.range()
10051 };
10052
10053 edits.push((range, to_insert));
10054 original_indent_columns.push(original_indent_column);
10055 }
10056 drop(snapshot);
10057
10058 buffer.edit(
10059 edits,
10060 if auto_indent_on_paste {
10061 Some(AutoindentMode::Block {
10062 original_indent_columns,
10063 })
10064 } else {
10065 None
10066 },
10067 cx,
10068 );
10069 });
10070
10071 let selections = this.selections.all::<usize>(cx);
10072 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10073 s.select(selections)
10074 });
10075 } else {
10076 this.insert(&clipboard_text, window, cx);
10077 }
10078 });
10079 }
10080
10081 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10082 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10083 if let Some(item) = cx.read_from_clipboard() {
10084 let entries = item.entries();
10085
10086 match entries.first() {
10087 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10088 // of all the pasted entries.
10089 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10090 .do_paste(
10091 clipboard_string.text(),
10092 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10093 true,
10094 window,
10095 cx,
10096 ),
10097 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10098 }
10099 }
10100 }
10101
10102 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10103 if self.read_only(cx) {
10104 return;
10105 }
10106
10107 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10108
10109 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10110 if let Some((selections, _)) =
10111 self.selection_history.transaction(transaction_id).cloned()
10112 {
10113 self.change_selections(None, window, cx, |s| {
10114 s.select_anchors(selections.to_vec());
10115 });
10116 } else {
10117 log::error!(
10118 "No entry in selection_history found for undo. \
10119 This may correspond to a bug where undo does not update the selection. \
10120 If this is occurring, please add details to \
10121 https://github.com/zed-industries/zed/issues/22692"
10122 );
10123 }
10124 self.request_autoscroll(Autoscroll::fit(), cx);
10125 self.unmark_text(window, cx);
10126 self.refresh_inline_completion(true, false, window, cx);
10127 cx.emit(EditorEvent::Edited { transaction_id });
10128 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10129 }
10130 }
10131
10132 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10133 if self.read_only(cx) {
10134 return;
10135 }
10136
10137 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10138
10139 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10140 if let Some((_, Some(selections))) =
10141 self.selection_history.transaction(transaction_id).cloned()
10142 {
10143 self.change_selections(None, window, cx, |s| {
10144 s.select_anchors(selections.to_vec());
10145 });
10146 } else {
10147 log::error!(
10148 "No entry in selection_history found for redo. \
10149 This may correspond to a bug where undo does not update the selection. \
10150 If this is occurring, please add details to \
10151 https://github.com/zed-industries/zed/issues/22692"
10152 );
10153 }
10154 self.request_autoscroll(Autoscroll::fit(), cx);
10155 self.unmark_text(window, cx);
10156 self.refresh_inline_completion(true, false, window, cx);
10157 cx.emit(EditorEvent::Edited { transaction_id });
10158 }
10159 }
10160
10161 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10162 self.buffer
10163 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10164 }
10165
10166 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10167 self.buffer
10168 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10169 }
10170
10171 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10172 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10173 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10174 s.move_with(|map, selection| {
10175 let cursor = if selection.is_empty() {
10176 movement::left(map, selection.start)
10177 } else {
10178 selection.start
10179 };
10180 selection.collapse_to(cursor, SelectionGoal::None);
10181 });
10182 })
10183 }
10184
10185 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10186 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10187 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10188 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10189 })
10190 }
10191
10192 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10193 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10194 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10195 s.move_with(|map, selection| {
10196 let cursor = if selection.is_empty() {
10197 movement::right(map, selection.end)
10198 } else {
10199 selection.end
10200 };
10201 selection.collapse_to(cursor, SelectionGoal::None)
10202 });
10203 })
10204 }
10205
10206 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10207 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10208 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10209 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10210 })
10211 }
10212
10213 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10214 if self.take_rename(true, window, cx).is_some() {
10215 return;
10216 }
10217
10218 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10219 cx.propagate();
10220 return;
10221 }
10222
10223 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10224
10225 let text_layout_details = &self.text_layout_details(window);
10226 let selection_count = self.selections.count();
10227 let first_selection = self.selections.first_anchor();
10228
10229 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10230 s.move_with(|map, selection| {
10231 if !selection.is_empty() {
10232 selection.goal = SelectionGoal::None;
10233 }
10234 let (cursor, goal) = movement::up(
10235 map,
10236 selection.start,
10237 selection.goal,
10238 false,
10239 text_layout_details,
10240 );
10241 selection.collapse_to(cursor, goal);
10242 });
10243 });
10244
10245 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10246 {
10247 cx.propagate();
10248 }
10249 }
10250
10251 pub fn move_up_by_lines(
10252 &mut self,
10253 action: &MoveUpByLines,
10254 window: &mut Window,
10255 cx: &mut Context<Self>,
10256 ) {
10257 if self.take_rename(true, window, cx).is_some() {
10258 return;
10259 }
10260
10261 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10262 cx.propagate();
10263 return;
10264 }
10265
10266 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10267
10268 let text_layout_details = &self.text_layout_details(window);
10269
10270 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10271 s.move_with(|map, selection| {
10272 if !selection.is_empty() {
10273 selection.goal = SelectionGoal::None;
10274 }
10275 let (cursor, goal) = movement::up_by_rows(
10276 map,
10277 selection.start,
10278 action.lines,
10279 selection.goal,
10280 false,
10281 text_layout_details,
10282 );
10283 selection.collapse_to(cursor, goal);
10284 });
10285 })
10286 }
10287
10288 pub fn move_down_by_lines(
10289 &mut self,
10290 action: &MoveDownByLines,
10291 window: &mut Window,
10292 cx: &mut Context<Self>,
10293 ) {
10294 if self.take_rename(true, window, cx).is_some() {
10295 return;
10296 }
10297
10298 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10299 cx.propagate();
10300 return;
10301 }
10302
10303 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10304
10305 let text_layout_details = &self.text_layout_details(window);
10306
10307 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10308 s.move_with(|map, selection| {
10309 if !selection.is_empty() {
10310 selection.goal = SelectionGoal::None;
10311 }
10312 let (cursor, goal) = movement::down_by_rows(
10313 map,
10314 selection.start,
10315 action.lines,
10316 selection.goal,
10317 false,
10318 text_layout_details,
10319 );
10320 selection.collapse_to(cursor, goal);
10321 });
10322 })
10323 }
10324
10325 pub fn select_down_by_lines(
10326 &mut self,
10327 action: &SelectDownByLines,
10328 window: &mut Window,
10329 cx: &mut Context<Self>,
10330 ) {
10331 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10332 let text_layout_details = &self.text_layout_details(window);
10333 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10334 s.move_heads_with(|map, head, goal| {
10335 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10336 })
10337 })
10338 }
10339
10340 pub fn select_up_by_lines(
10341 &mut self,
10342 action: &SelectUpByLines,
10343 window: &mut Window,
10344 cx: &mut Context<Self>,
10345 ) {
10346 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10347 let text_layout_details = &self.text_layout_details(window);
10348 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10349 s.move_heads_with(|map, head, goal| {
10350 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10351 })
10352 })
10353 }
10354
10355 pub fn select_page_up(
10356 &mut self,
10357 _: &SelectPageUp,
10358 window: &mut Window,
10359 cx: &mut Context<Self>,
10360 ) {
10361 let Some(row_count) = self.visible_row_count() else {
10362 return;
10363 };
10364
10365 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10366
10367 let text_layout_details = &self.text_layout_details(window);
10368
10369 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10370 s.move_heads_with(|map, head, goal| {
10371 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10372 })
10373 })
10374 }
10375
10376 pub fn move_page_up(
10377 &mut self,
10378 action: &MovePageUp,
10379 window: &mut Window,
10380 cx: &mut Context<Self>,
10381 ) {
10382 if self.take_rename(true, window, cx).is_some() {
10383 return;
10384 }
10385
10386 if self
10387 .context_menu
10388 .borrow_mut()
10389 .as_mut()
10390 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10391 .unwrap_or(false)
10392 {
10393 return;
10394 }
10395
10396 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10397 cx.propagate();
10398 return;
10399 }
10400
10401 let Some(row_count) = self.visible_row_count() else {
10402 return;
10403 };
10404
10405 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10406
10407 let autoscroll = if action.center_cursor {
10408 Autoscroll::center()
10409 } else {
10410 Autoscroll::fit()
10411 };
10412
10413 let text_layout_details = &self.text_layout_details(window);
10414
10415 self.change_selections(Some(autoscroll), window, cx, |s| {
10416 s.move_with(|map, selection| {
10417 if !selection.is_empty() {
10418 selection.goal = SelectionGoal::None;
10419 }
10420 let (cursor, goal) = movement::up_by_rows(
10421 map,
10422 selection.end,
10423 row_count,
10424 selection.goal,
10425 false,
10426 text_layout_details,
10427 );
10428 selection.collapse_to(cursor, goal);
10429 });
10430 });
10431 }
10432
10433 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10434 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10435 let text_layout_details = &self.text_layout_details(window);
10436 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10437 s.move_heads_with(|map, head, goal| {
10438 movement::up(map, head, goal, false, text_layout_details)
10439 })
10440 })
10441 }
10442
10443 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10444 self.take_rename(true, window, cx);
10445
10446 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10447 cx.propagate();
10448 return;
10449 }
10450
10451 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10452
10453 let text_layout_details = &self.text_layout_details(window);
10454 let selection_count = self.selections.count();
10455 let first_selection = self.selections.first_anchor();
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::down(
10463 map,
10464 selection.end,
10465 selection.goal,
10466 false,
10467 text_layout_details,
10468 );
10469 selection.collapse_to(cursor, goal);
10470 });
10471 });
10472
10473 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10474 {
10475 cx.propagate();
10476 }
10477 }
10478
10479 pub fn select_page_down(
10480 &mut self,
10481 _: &SelectPageDown,
10482 window: &mut Window,
10483 cx: &mut Context<Self>,
10484 ) {
10485 let Some(row_count) = self.visible_row_count() else {
10486 return;
10487 };
10488
10489 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10490
10491 let text_layout_details = &self.text_layout_details(window);
10492
10493 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10494 s.move_heads_with(|map, head, goal| {
10495 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10496 })
10497 })
10498 }
10499
10500 pub fn move_page_down(
10501 &mut self,
10502 action: &MovePageDown,
10503 window: &mut Window,
10504 cx: &mut Context<Self>,
10505 ) {
10506 if self.take_rename(true, window, cx).is_some() {
10507 return;
10508 }
10509
10510 if self
10511 .context_menu
10512 .borrow_mut()
10513 .as_mut()
10514 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10515 .unwrap_or(false)
10516 {
10517 return;
10518 }
10519
10520 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10521 cx.propagate();
10522 return;
10523 }
10524
10525 let Some(row_count) = self.visible_row_count() else {
10526 return;
10527 };
10528
10529 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10530
10531 let autoscroll = if action.center_cursor {
10532 Autoscroll::center()
10533 } else {
10534 Autoscroll::fit()
10535 };
10536
10537 let text_layout_details = &self.text_layout_details(window);
10538 self.change_selections(Some(autoscroll), window, cx, |s| {
10539 s.move_with(|map, selection| {
10540 if !selection.is_empty() {
10541 selection.goal = SelectionGoal::None;
10542 }
10543 let (cursor, goal) = movement::down_by_rows(
10544 map,
10545 selection.end,
10546 row_count,
10547 selection.goal,
10548 false,
10549 text_layout_details,
10550 );
10551 selection.collapse_to(cursor, goal);
10552 });
10553 });
10554 }
10555
10556 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10557 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10558 let text_layout_details = &self.text_layout_details(window);
10559 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10560 s.move_heads_with(|map, head, goal| {
10561 movement::down(map, head, goal, false, text_layout_details)
10562 })
10563 });
10564 }
10565
10566 pub fn context_menu_first(
10567 &mut self,
10568 _: &ContextMenuFirst,
10569 _window: &mut Window,
10570 cx: &mut Context<Self>,
10571 ) {
10572 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10573 context_menu.select_first(self.completion_provider.as_deref(), cx);
10574 }
10575 }
10576
10577 pub fn context_menu_prev(
10578 &mut self,
10579 _: &ContextMenuPrevious,
10580 _window: &mut Window,
10581 cx: &mut Context<Self>,
10582 ) {
10583 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10584 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10585 }
10586 }
10587
10588 pub fn context_menu_next(
10589 &mut self,
10590 _: &ContextMenuNext,
10591 _window: &mut Window,
10592 cx: &mut Context<Self>,
10593 ) {
10594 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10595 context_menu.select_next(self.completion_provider.as_deref(), cx);
10596 }
10597 }
10598
10599 pub fn context_menu_last(
10600 &mut self,
10601 _: &ContextMenuLast,
10602 _window: &mut Window,
10603 cx: &mut Context<Self>,
10604 ) {
10605 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10606 context_menu.select_last(self.completion_provider.as_deref(), cx);
10607 }
10608 }
10609
10610 pub fn move_to_previous_word_start(
10611 &mut self,
10612 _: &MoveToPreviousWordStart,
10613 window: &mut Window,
10614 cx: &mut Context<Self>,
10615 ) {
10616 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10617 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10618 s.move_cursors_with(|map, head, _| {
10619 (
10620 movement::previous_word_start(map, head),
10621 SelectionGoal::None,
10622 )
10623 });
10624 })
10625 }
10626
10627 pub fn move_to_previous_subword_start(
10628 &mut self,
10629 _: &MoveToPreviousSubwordStart,
10630 window: &mut Window,
10631 cx: &mut Context<Self>,
10632 ) {
10633 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10634 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10635 s.move_cursors_with(|map, head, _| {
10636 (
10637 movement::previous_subword_start(map, head),
10638 SelectionGoal::None,
10639 )
10640 });
10641 })
10642 }
10643
10644 pub fn select_to_previous_word_start(
10645 &mut self,
10646 _: &SelectToPreviousWordStart,
10647 window: &mut Window,
10648 cx: &mut Context<Self>,
10649 ) {
10650 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10651 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10652 s.move_heads_with(|map, head, _| {
10653 (
10654 movement::previous_word_start(map, head),
10655 SelectionGoal::None,
10656 )
10657 });
10658 })
10659 }
10660
10661 pub fn select_to_previous_subword_start(
10662 &mut self,
10663 _: &SelectToPreviousSubwordStart,
10664 window: &mut Window,
10665 cx: &mut Context<Self>,
10666 ) {
10667 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10668 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10669 s.move_heads_with(|map, head, _| {
10670 (
10671 movement::previous_subword_start(map, head),
10672 SelectionGoal::None,
10673 )
10674 });
10675 })
10676 }
10677
10678 pub fn delete_to_previous_word_start(
10679 &mut self,
10680 action: &DeleteToPreviousWordStart,
10681 window: &mut Window,
10682 cx: &mut Context<Self>,
10683 ) {
10684 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10685 self.transact(window, cx, |this, window, cx| {
10686 this.select_autoclose_pair(window, cx);
10687 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10688 s.move_with(|map, selection| {
10689 if selection.is_empty() {
10690 let cursor = if action.ignore_newlines {
10691 movement::previous_word_start(map, selection.head())
10692 } else {
10693 movement::previous_word_start_or_newline(map, selection.head())
10694 };
10695 selection.set_head(cursor, SelectionGoal::None);
10696 }
10697 });
10698 });
10699 this.insert("", window, cx);
10700 });
10701 }
10702
10703 pub fn delete_to_previous_subword_start(
10704 &mut self,
10705 _: &DeleteToPreviousSubwordStart,
10706 window: &mut Window,
10707 cx: &mut Context<Self>,
10708 ) {
10709 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10710 self.transact(window, cx, |this, window, cx| {
10711 this.select_autoclose_pair(window, cx);
10712 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10713 s.move_with(|map, selection| {
10714 if selection.is_empty() {
10715 let cursor = movement::previous_subword_start(map, selection.head());
10716 selection.set_head(cursor, SelectionGoal::None);
10717 }
10718 });
10719 });
10720 this.insert("", window, cx);
10721 });
10722 }
10723
10724 pub fn move_to_next_word_end(
10725 &mut self,
10726 _: &MoveToNextWordEnd,
10727 window: &mut Window,
10728 cx: &mut Context<Self>,
10729 ) {
10730 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10731 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10732 s.move_cursors_with(|map, head, _| {
10733 (movement::next_word_end(map, head), SelectionGoal::None)
10734 });
10735 })
10736 }
10737
10738 pub fn move_to_next_subword_end(
10739 &mut self,
10740 _: &MoveToNextSubwordEnd,
10741 window: &mut Window,
10742 cx: &mut Context<Self>,
10743 ) {
10744 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10745 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10746 s.move_cursors_with(|map, head, _| {
10747 (movement::next_subword_end(map, head), SelectionGoal::None)
10748 });
10749 })
10750 }
10751
10752 pub fn select_to_next_word_end(
10753 &mut self,
10754 _: &SelectToNextWordEnd,
10755 window: &mut Window,
10756 cx: &mut Context<Self>,
10757 ) {
10758 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10759 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10760 s.move_heads_with(|map, head, _| {
10761 (movement::next_word_end(map, head), SelectionGoal::None)
10762 });
10763 })
10764 }
10765
10766 pub fn select_to_next_subword_end(
10767 &mut self,
10768 _: &SelectToNextSubwordEnd,
10769 window: &mut Window,
10770 cx: &mut Context<Self>,
10771 ) {
10772 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10773 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10774 s.move_heads_with(|map, head, _| {
10775 (movement::next_subword_end(map, head), SelectionGoal::None)
10776 });
10777 })
10778 }
10779
10780 pub fn delete_to_next_word_end(
10781 &mut self,
10782 action: &DeleteToNextWordEnd,
10783 window: &mut Window,
10784 cx: &mut Context<Self>,
10785 ) {
10786 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10787 self.transact(window, cx, |this, window, cx| {
10788 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10789 s.move_with(|map, selection| {
10790 if selection.is_empty() {
10791 let cursor = if action.ignore_newlines {
10792 movement::next_word_end(map, selection.head())
10793 } else {
10794 movement::next_word_end_or_newline(map, selection.head())
10795 };
10796 selection.set_head(cursor, SelectionGoal::None);
10797 }
10798 });
10799 });
10800 this.insert("", window, cx);
10801 });
10802 }
10803
10804 pub fn delete_to_next_subword_end(
10805 &mut self,
10806 _: &DeleteToNextSubwordEnd,
10807 window: &mut Window,
10808 cx: &mut Context<Self>,
10809 ) {
10810 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10811 self.transact(window, cx, |this, window, cx| {
10812 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10813 s.move_with(|map, selection| {
10814 if selection.is_empty() {
10815 let cursor = movement::next_subword_end(map, selection.head());
10816 selection.set_head(cursor, SelectionGoal::None);
10817 }
10818 });
10819 });
10820 this.insert("", window, cx);
10821 });
10822 }
10823
10824 pub fn move_to_beginning_of_line(
10825 &mut self,
10826 action: &MoveToBeginningOfLine,
10827 window: &mut Window,
10828 cx: &mut Context<Self>,
10829 ) {
10830 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10831 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10832 s.move_cursors_with(|map, head, _| {
10833 (
10834 movement::indented_line_beginning(
10835 map,
10836 head,
10837 action.stop_at_soft_wraps,
10838 action.stop_at_indent,
10839 ),
10840 SelectionGoal::None,
10841 )
10842 });
10843 })
10844 }
10845
10846 pub fn select_to_beginning_of_line(
10847 &mut self,
10848 action: &SelectToBeginningOfLine,
10849 window: &mut Window,
10850 cx: &mut Context<Self>,
10851 ) {
10852 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10853 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10854 s.move_heads_with(|map, head, _| {
10855 (
10856 movement::indented_line_beginning(
10857 map,
10858 head,
10859 action.stop_at_soft_wraps,
10860 action.stop_at_indent,
10861 ),
10862 SelectionGoal::None,
10863 )
10864 });
10865 });
10866 }
10867
10868 pub fn delete_to_beginning_of_line(
10869 &mut self,
10870 action: &DeleteToBeginningOfLine,
10871 window: &mut Window,
10872 cx: &mut Context<Self>,
10873 ) {
10874 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10875 self.transact(window, cx, |this, window, cx| {
10876 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10877 s.move_with(|_, selection| {
10878 selection.reversed = true;
10879 });
10880 });
10881
10882 this.select_to_beginning_of_line(
10883 &SelectToBeginningOfLine {
10884 stop_at_soft_wraps: false,
10885 stop_at_indent: action.stop_at_indent,
10886 },
10887 window,
10888 cx,
10889 );
10890 this.backspace(&Backspace, window, cx);
10891 });
10892 }
10893
10894 pub fn move_to_end_of_line(
10895 &mut self,
10896 action: &MoveToEndOfLine,
10897 window: &mut Window,
10898 cx: &mut Context<Self>,
10899 ) {
10900 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10901 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10902 s.move_cursors_with(|map, head, _| {
10903 (
10904 movement::line_end(map, head, action.stop_at_soft_wraps),
10905 SelectionGoal::None,
10906 )
10907 });
10908 })
10909 }
10910
10911 pub fn select_to_end_of_line(
10912 &mut self,
10913 action: &SelectToEndOfLine,
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_heads_with(|map, head, _| {
10920 (
10921 movement::line_end(map, head, action.stop_at_soft_wraps),
10922 SelectionGoal::None,
10923 )
10924 });
10925 })
10926 }
10927
10928 pub fn delete_to_end_of_line(
10929 &mut self,
10930 _: &DeleteToEndOfLine,
10931 window: &mut Window,
10932 cx: &mut Context<Self>,
10933 ) {
10934 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10935 self.transact(window, cx, |this, window, cx| {
10936 this.select_to_end_of_line(
10937 &SelectToEndOfLine {
10938 stop_at_soft_wraps: false,
10939 },
10940 window,
10941 cx,
10942 );
10943 this.delete(&Delete, window, cx);
10944 });
10945 }
10946
10947 pub fn cut_to_end_of_line(
10948 &mut self,
10949 _: &CutToEndOfLine,
10950 window: &mut Window,
10951 cx: &mut Context<Self>,
10952 ) {
10953 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10954 self.transact(window, cx, |this, window, cx| {
10955 this.select_to_end_of_line(
10956 &SelectToEndOfLine {
10957 stop_at_soft_wraps: false,
10958 },
10959 window,
10960 cx,
10961 );
10962 this.cut(&Cut, window, cx);
10963 });
10964 }
10965
10966 pub fn move_to_start_of_paragraph(
10967 &mut self,
10968 _: &MoveToStartOfParagraph,
10969 window: &mut Window,
10970 cx: &mut Context<Self>,
10971 ) {
10972 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10973 cx.propagate();
10974 return;
10975 }
10976 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10977 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10978 s.move_with(|map, selection| {
10979 selection.collapse_to(
10980 movement::start_of_paragraph(map, selection.head(), 1),
10981 SelectionGoal::None,
10982 )
10983 });
10984 })
10985 }
10986
10987 pub fn move_to_end_of_paragraph(
10988 &mut self,
10989 _: &MoveToEndOfParagraph,
10990 window: &mut Window,
10991 cx: &mut Context<Self>,
10992 ) {
10993 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10994 cx.propagate();
10995 return;
10996 }
10997 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10998 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10999 s.move_with(|map, selection| {
11000 selection.collapse_to(
11001 movement::end_of_paragraph(map, selection.head(), 1),
11002 SelectionGoal::None,
11003 )
11004 });
11005 })
11006 }
11007
11008 pub fn select_to_start_of_paragraph(
11009 &mut self,
11010 _: &SelectToStartOfParagraph,
11011 window: &mut Window,
11012 cx: &mut Context<Self>,
11013 ) {
11014 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11015 cx.propagate();
11016 return;
11017 }
11018 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11019 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11020 s.move_heads_with(|map, head, _| {
11021 (
11022 movement::start_of_paragraph(map, head, 1),
11023 SelectionGoal::None,
11024 )
11025 });
11026 })
11027 }
11028
11029 pub fn select_to_end_of_paragraph(
11030 &mut self,
11031 _: &SelectToEndOfParagraph,
11032 window: &mut Window,
11033 cx: &mut Context<Self>,
11034 ) {
11035 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11036 cx.propagate();
11037 return;
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::end_of_paragraph(map, head, 1),
11044 SelectionGoal::None,
11045 )
11046 });
11047 })
11048 }
11049
11050 pub fn move_to_start_of_excerpt(
11051 &mut self,
11052 _: &MoveToStartOfExcerpt,
11053 window: &mut Window,
11054 cx: &mut Context<Self>,
11055 ) {
11056 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11057 cx.propagate();
11058 return;
11059 }
11060 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11061 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11062 s.move_with(|map, selection| {
11063 selection.collapse_to(
11064 movement::start_of_excerpt(
11065 map,
11066 selection.head(),
11067 workspace::searchable::Direction::Prev,
11068 ),
11069 SelectionGoal::None,
11070 )
11071 });
11072 })
11073 }
11074
11075 pub fn move_to_start_of_next_excerpt(
11076 &mut self,
11077 _: &MoveToStartOfNextExcerpt,
11078 window: &mut Window,
11079 cx: &mut Context<Self>,
11080 ) {
11081 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11082 cx.propagate();
11083 return;
11084 }
11085
11086 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11087 s.move_with(|map, selection| {
11088 selection.collapse_to(
11089 movement::start_of_excerpt(
11090 map,
11091 selection.head(),
11092 workspace::searchable::Direction::Next,
11093 ),
11094 SelectionGoal::None,
11095 )
11096 });
11097 })
11098 }
11099
11100 pub fn move_to_end_of_excerpt(
11101 &mut self,
11102 _: &MoveToEndOfExcerpt,
11103 window: &mut Window,
11104 cx: &mut Context<Self>,
11105 ) {
11106 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11107 cx.propagate();
11108 return;
11109 }
11110 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11111 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11112 s.move_with(|map, selection| {
11113 selection.collapse_to(
11114 movement::end_of_excerpt(
11115 map,
11116 selection.head(),
11117 workspace::searchable::Direction::Next,
11118 ),
11119 SelectionGoal::None,
11120 )
11121 });
11122 })
11123 }
11124
11125 pub fn move_to_end_of_previous_excerpt(
11126 &mut self,
11127 _: &MoveToEndOfPreviousExcerpt,
11128 window: &mut Window,
11129 cx: &mut Context<Self>,
11130 ) {
11131 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11132 cx.propagate();
11133 return;
11134 }
11135 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11136 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11137 s.move_with(|map, selection| {
11138 selection.collapse_to(
11139 movement::end_of_excerpt(
11140 map,
11141 selection.head(),
11142 workspace::searchable::Direction::Prev,
11143 ),
11144 SelectionGoal::None,
11145 )
11146 });
11147 })
11148 }
11149
11150 pub fn select_to_start_of_excerpt(
11151 &mut self,
11152 _: &SelectToStartOfExcerpt,
11153 window: &mut Window,
11154 cx: &mut Context<Self>,
11155 ) {
11156 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11157 cx.propagate();
11158 return;
11159 }
11160 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11161 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11162 s.move_heads_with(|map, head, _| {
11163 (
11164 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11165 SelectionGoal::None,
11166 )
11167 });
11168 })
11169 }
11170
11171 pub fn select_to_start_of_next_excerpt(
11172 &mut self,
11173 _: &SelectToStartOfNextExcerpt,
11174 window: &mut Window,
11175 cx: &mut Context<Self>,
11176 ) {
11177 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11178 cx.propagate();
11179 return;
11180 }
11181 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11182 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11183 s.move_heads_with(|map, head, _| {
11184 (
11185 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11186 SelectionGoal::None,
11187 )
11188 });
11189 })
11190 }
11191
11192 pub fn select_to_end_of_excerpt(
11193 &mut self,
11194 _: &SelectToEndOfExcerpt,
11195 window: &mut Window,
11196 cx: &mut Context<Self>,
11197 ) {
11198 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11199 cx.propagate();
11200 return;
11201 }
11202 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11203 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11204 s.move_heads_with(|map, head, _| {
11205 (
11206 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11207 SelectionGoal::None,
11208 )
11209 });
11210 })
11211 }
11212
11213 pub fn select_to_end_of_previous_excerpt(
11214 &mut self,
11215 _: &SelectToEndOfPreviousExcerpt,
11216 window: &mut Window,
11217 cx: &mut Context<Self>,
11218 ) {
11219 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11220 cx.propagate();
11221 return;
11222 }
11223 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11224 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11225 s.move_heads_with(|map, head, _| {
11226 (
11227 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11228 SelectionGoal::None,
11229 )
11230 });
11231 })
11232 }
11233
11234 pub fn move_to_beginning(
11235 &mut self,
11236 _: &MoveToBeginning,
11237 window: &mut Window,
11238 cx: &mut Context<Self>,
11239 ) {
11240 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11241 cx.propagate();
11242 return;
11243 }
11244 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11245 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11246 s.select_ranges(vec![0..0]);
11247 });
11248 }
11249
11250 pub fn select_to_beginning(
11251 &mut self,
11252 _: &SelectToBeginning,
11253 window: &mut Window,
11254 cx: &mut Context<Self>,
11255 ) {
11256 let mut selection = self.selections.last::<Point>(cx);
11257 selection.set_head(Point::zero(), SelectionGoal::None);
11258 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11259 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11260 s.select(vec![selection]);
11261 });
11262 }
11263
11264 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11265 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11266 cx.propagate();
11267 return;
11268 }
11269 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11270 let cursor = self.buffer.read(cx).read(cx).len();
11271 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11272 s.select_ranges(vec![cursor..cursor])
11273 });
11274 }
11275
11276 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11277 self.nav_history = nav_history;
11278 }
11279
11280 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11281 self.nav_history.as_ref()
11282 }
11283
11284 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11285 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11286 }
11287
11288 fn push_to_nav_history(
11289 &mut self,
11290 cursor_anchor: Anchor,
11291 new_position: Option<Point>,
11292 is_deactivate: bool,
11293 cx: &mut Context<Self>,
11294 ) {
11295 if let Some(nav_history) = self.nav_history.as_mut() {
11296 let buffer = self.buffer.read(cx).read(cx);
11297 let cursor_position = cursor_anchor.to_point(&buffer);
11298 let scroll_state = self.scroll_manager.anchor();
11299 let scroll_top_row = scroll_state.top_row(&buffer);
11300 drop(buffer);
11301
11302 if let Some(new_position) = new_position {
11303 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11304 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11305 return;
11306 }
11307 }
11308
11309 nav_history.push(
11310 Some(NavigationData {
11311 cursor_anchor,
11312 cursor_position,
11313 scroll_anchor: scroll_state,
11314 scroll_top_row,
11315 }),
11316 cx,
11317 );
11318 cx.emit(EditorEvent::PushedToNavHistory {
11319 anchor: cursor_anchor,
11320 is_deactivate,
11321 })
11322 }
11323 }
11324
11325 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11326 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11327 let buffer = self.buffer.read(cx).snapshot(cx);
11328 let mut selection = self.selections.first::<usize>(cx);
11329 selection.set_head(buffer.len(), SelectionGoal::None);
11330 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11331 s.select(vec![selection]);
11332 });
11333 }
11334
11335 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11336 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11337 let end = self.buffer.read(cx).read(cx).len();
11338 self.change_selections(None, window, cx, |s| {
11339 s.select_ranges(vec![0..end]);
11340 });
11341 }
11342
11343 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11344 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11346 let mut selections = self.selections.all::<Point>(cx);
11347 let max_point = display_map.buffer_snapshot.max_point();
11348 for selection in &mut selections {
11349 let rows = selection.spanned_rows(true, &display_map);
11350 selection.start = Point::new(rows.start.0, 0);
11351 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11352 selection.reversed = false;
11353 }
11354 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11355 s.select(selections);
11356 });
11357 }
11358
11359 pub fn split_selection_into_lines(
11360 &mut self,
11361 _: &SplitSelectionIntoLines,
11362 window: &mut Window,
11363 cx: &mut Context<Self>,
11364 ) {
11365 let selections = self
11366 .selections
11367 .all::<Point>(cx)
11368 .into_iter()
11369 .map(|selection| selection.start..selection.end)
11370 .collect::<Vec<_>>();
11371 self.unfold_ranges(&selections, true, true, cx);
11372
11373 let mut new_selection_ranges = Vec::new();
11374 {
11375 let buffer = self.buffer.read(cx).read(cx);
11376 for selection in selections {
11377 for row in selection.start.row..selection.end.row {
11378 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11379 new_selection_ranges.push(cursor..cursor);
11380 }
11381
11382 let is_multiline_selection = selection.start.row != selection.end.row;
11383 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11384 // so this action feels more ergonomic when paired with other selection operations
11385 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11386 if !should_skip_last {
11387 new_selection_ranges.push(selection.end..selection.end);
11388 }
11389 }
11390 }
11391 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11392 s.select_ranges(new_selection_ranges);
11393 });
11394 }
11395
11396 pub fn add_selection_above(
11397 &mut self,
11398 _: &AddSelectionAbove,
11399 window: &mut Window,
11400 cx: &mut Context<Self>,
11401 ) {
11402 self.add_selection(true, window, cx);
11403 }
11404
11405 pub fn add_selection_below(
11406 &mut self,
11407 _: &AddSelectionBelow,
11408 window: &mut Window,
11409 cx: &mut Context<Self>,
11410 ) {
11411 self.add_selection(false, window, cx);
11412 }
11413
11414 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11415 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11416
11417 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11418 let mut selections = self.selections.all::<Point>(cx);
11419 let text_layout_details = self.text_layout_details(window);
11420 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11421 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11422 let range = oldest_selection.display_range(&display_map).sorted();
11423
11424 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11425 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11426 let positions = start_x.min(end_x)..start_x.max(end_x);
11427
11428 selections.clear();
11429 let mut stack = Vec::new();
11430 for row in range.start.row().0..=range.end.row().0 {
11431 if let Some(selection) = self.selections.build_columnar_selection(
11432 &display_map,
11433 DisplayRow(row),
11434 &positions,
11435 oldest_selection.reversed,
11436 &text_layout_details,
11437 ) {
11438 stack.push(selection.id);
11439 selections.push(selection);
11440 }
11441 }
11442
11443 if above {
11444 stack.reverse();
11445 }
11446
11447 AddSelectionsState { above, stack }
11448 });
11449
11450 let last_added_selection = *state.stack.last().unwrap();
11451 let mut new_selections = Vec::new();
11452 if above == state.above {
11453 let end_row = if above {
11454 DisplayRow(0)
11455 } else {
11456 display_map.max_point().row()
11457 };
11458
11459 'outer: for selection in selections {
11460 if selection.id == last_added_selection {
11461 let range = selection.display_range(&display_map).sorted();
11462 debug_assert_eq!(range.start.row(), range.end.row());
11463 let mut row = range.start.row();
11464 let positions =
11465 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11466 px(start)..px(end)
11467 } else {
11468 let start_x =
11469 display_map.x_for_display_point(range.start, &text_layout_details);
11470 let end_x =
11471 display_map.x_for_display_point(range.end, &text_layout_details);
11472 start_x.min(end_x)..start_x.max(end_x)
11473 };
11474
11475 while row != end_row {
11476 if above {
11477 row.0 -= 1;
11478 } else {
11479 row.0 += 1;
11480 }
11481
11482 if let Some(new_selection) = self.selections.build_columnar_selection(
11483 &display_map,
11484 row,
11485 &positions,
11486 selection.reversed,
11487 &text_layout_details,
11488 ) {
11489 state.stack.push(new_selection.id);
11490 if above {
11491 new_selections.push(new_selection);
11492 new_selections.push(selection);
11493 } else {
11494 new_selections.push(selection);
11495 new_selections.push(new_selection);
11496 }
11497
11498 continue 'outer;
11499 }
11500 }
11501 }
11502
11503 new_selections.push(selection);
11504 }
11505 } else {
11506 new_selections = selections;
11507 new_selections.retain(|s| s.id != last_added_selection);
11508 state.stack.pop();
11509 }
11510
11511 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11512 s.select(new_selections);
11513 });
11514 if state.stack.len() > 1 {
11515 self.add_selections_state = Some(state);
11516 }
11517 }
11518
11519 pub fn select_next_match_internal(
11520 &mut self,
11521 display_map: &DisplaySnapshot,
11522 replace_newest: bool,
11523 autoscroll: Option<Autoscroll>,
11524 window: &mut Window,
11525 cx: &mut Context<Self>,
11526 ) -> Result<()> {
11527 fn select_next_match_ranges(
11528 this: &mut Editor,
11529 range: Range<usize>,
11530 replace_newest: bool,
11531 auto_scroll: Option<Autoscroll>,
11532 window: &mut Window,
11533 cx: &mut Context<Editor>,
11534 ) {
11535 this.unfold_ranges(&[range.clone()], false, true, cx);
11536 this.change_selections(auto_scroll, window, cx, |s| {
11537 if replace_newest {
11538 s.delete(s.newest_anchor().id);
11539 }
11540 s.insert_range(range.clone());
11541 });
11542 }
11543
11544 let buffer = &display_map.buffer_snapshot;
11545 let mut selections = self.selections.all::<usize>(cx);
11546 if let Some(mut select_next_state) = self.select_next_state.take() {
11547 let query = &select_next_state.query;
11548 if !select_next_state.done {
11549 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11550 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11551 let mut next_selected_range = None;
11552
11553 let bytes_after_last_selection =
11554 buffer.bytes_in_range(last_selection.end..buffer.len());
11555 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11556 let query_matches = query
11557 .stream_find_iter(bytes_after_last_selection)
11558 .map(|result| (last_selection.end, result))
11559 .chain(
11560 query
11561 .stream_find_iter(bytes_before_first_selection)
11562 .map(|result| (0, result)),
11563 );
11564
11565 for (start_offset, query_match) in query_matches {
11566 let query_match = query_match.unwrap(); // can only fail due to I/O
11567 let offset_range =
11568 start_offset + query_match.start()..start_offset + query_match.end();
11569 let display_range = offset_range.start.to_display_point(display_map)
11570 ..offset_range.end.to_display_point(display_map);
11571
11572 if !select_next_state.wordwise
11573 || (!movement::is_inside_word(display_map, display_range.start)
11574 && !movement::is_inside_word(display_map, display_range.end))
11575 {
11576 // TODO: This is n^2, because we might check all the selections
11577 if !selections
11578 .iter()
11579 .any(|selection| selection.range().overlaps(&offset_range))
11580 {
11581 next_selected_range = Some(offset_range);
11582 break;
11583 }
11584 }
11585 }
11586
11587 if let Some(next_selected_range) = next_selected_range {
11588 select_next_match_ranges(
11589 self,
11590 next_selected_range,
11591 replace_newest,
11592 autoscroll,
11593 window,
11594 cx,
11595 );
11596 } else {
11597 select_next_state.done = true;
11598 }
11599 }
11600
11601 self.select_next_state = Some(select_next_state);
11602 } else {
11603 let mut only_carets = true;
11604 let mut same_text_selected = true;
11605 let mut selected_text = None;
11606
11607 let mut selections_iter = selections.iter().peekable();
11608 while let Some(selection) = selections_iter.next() {
11609 if selection.start != selection.end {
11610 only_carets = false;
11611 }
11612
11613 if same_text_selected {
11614 if selected_text.is_none() {
11615 selected_text =
11616 Some(buffer.text_for_range(selection.range()).collect::<String>());
11617 }
11618
11619 if let Some(next_selection) = selections_iter.peek() {
11620 if next_selection.range().len() == selection.range().len() {
11621 let next_selected_text = buffer
11622 .text_for_range(next_selection.range())
11623 .collect::<String>();
11624 if Some(next_selected_text) != selected_text {
11625 same_text_selected = false;
11626 selected_text = None;
11627 }
11628 } else {
11629 same_text_selected = false;
11630 selected_text = None;
11631 }
11632 }
11633 }
11634 }
11635
11636 if only_carets {
11637 for selection in &mut selections {
11638 let word_range = movement::surrounding_word(
11639 display_map,
11640 selection.start.to_display_point(display_map),
11641 );
11642 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11643 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11644 selection.goal = SelectionGoal::None;
11645 selection.reversed = false;
11646 select_next_match_ranges(
11647 self,
11648 selection.start..selection.end,
11649 replace_newest,
11650 autoscroll,
11651 window,
11652 cx,
11653 );
11654 }
11655
11656 if selections.len() == 1 {
11657 let selection = selections
11658 .last()
11659 .expect("ensured that there's only one selection");
11660 let query = buffer
11661 .text_for_range(selection.start..selection.end)
11662 .collect::<String>();
11663 let is_empty = query.is_empty();
11664 let select_state = SelectNextState {
11665 query: AhoCorasick::new(&[query])?,
11666 wordwise: true,
11667 done: is_empty,
11668 };
11669 self.select_next_state = Some(select_state);
11670 } else {
11671 self.select_next_state = None;
11672 }
11673 } else if let Some(selected_text) = selected_text {
11674 self.select_next_state = Some(SelectNextState {
11675 query: AhoCorasick::new(&[selected_text])?,
11676 wordwise: false,
11677 done: false,
11678 });
11679 self.select_next_match_internal(
11680 display_map,
11681 replace_newest,
11682 autoscroll,
11683 window,
11684 cx,
11685 )?;
11686 }
11687 }
11688 Ok(())
11689 }
11690
11691 pub fn select_all_matches(
11692 &mut self,
11693 _action: &SelectAllMatches,
11694 window: &mut Window,
11695 cx: &mut Context<Self>,
11696 ) -> Result<()> {
11697 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11698
11699 self.push_to_selection_history();
11700 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11701
11702 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11703 let Some(select_next_state) = self.select_next_state.as_mut() else {
11704 return Ok(());
11705 };
11706 if select_next_state.done {
11707 return Ok(());
11708 }
11709
11710 let mut new_selections = self.selections.all::<usize>(cx);
11711
11712 let buffer = &display_map.buffer_snapshot;
11713 let query_matches = select_next_state
11714 .query
11715 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11716
11717 for query_match in query_matches {
11718 let query_match = query_match.unwrap(); // can only fail due to I/O
11719 let offset_range = query_match.start()..query_match.end();
11720 let display_range = offset_range.start.to_display_point(&display_map)
11721 ..offset_range.end.to_display_point(&display_map);
11722
11723 if !select_next_state.wordwise
11724 || (!movement::is_inside_word(&display_map, display_range.start)
11725 && !movement::is_inside_word(&display_map, display_range.end))
11726 {
11727 self.selections.change_with(cx, |selections| {
11728 new_selections.push(Selection {
11729 id: selections.new_selection_id(),
11730 start: offset_range.start,
11731 end: offset_range.end,
11732 reversed: false,
11733 goal: SelectionGoal::None,
11734 });
11735 });
11736 }
11737 }
11738
11739 new_selections.sort_by_key(|selection| selection.start);
11740 let mut ix = 0;
11741 while ix + 1 < new_selections.len() {
11742 let current_selection = &new_selections[ix];
11743 let next_selection = &new_selections[ix + 1];
11744 if current_selection.range().overlaps(&next_selection.range()) {
11745 if current_selection.id < next_selection.id {
11746 new_selections.remove(ix + 1);
11747 } else {
11748 new_selections.remove(ix);
11749 }
11750 } else {
11751 ix += 1;
11752 }
11753 }
11754
11755 let reversed = self.selections.oldest::<usize>(cx).reversed;
11756
11757 for selection in new_selections.iter_mut() {
11758 selection.reversed = reversed;
11759 }
11760
11761 select_next_state.done = true;
11762 self.unfold_ranges(
11763 &new_selections
11764 .iter()
11765 .map(|selection| selection.range())
11766 .collect::<Vec<_>>(),
11767 false,
11768 false,
11769 cx,
11770 );
11771 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11772 selections.select(new_selections)
11773 });
11774
11775 Ok(())
11776 }
11777
11778 pub fn select_next(
11779 &mut self,
11780 action: &SelectNext,
11781 window: &mut Window,
11782 cx: &mut Context<Self>,
11783 ) -> Result<()> {
11784 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11785 self.push_to_selection_history();
11786 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11787 self.select_next_match_internal(
11788 &display_map,
11789 action.replace_newest,
11790 Some(Autoscroll::newest()),
11791 window,
11792 cx,
11793 )?;
11794 Ok(())
11795 }
11796
11797 pub fn select_previous(
11798 &mut self,
11799 action: &SelectPrevious,
11800 window: &mut Window,
11801 cx: &mut Context<Self>,
11802 ) -> Result<()> {
11803 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11804 self.push_to_selection_history();
11805 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11806 let buffer = &display_map.buffer_snapshot;
11807 let mut selections = self.selections.all::<usize>(cx);
11808 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11809 let query = &select_prev_state.query;
11810 if !select_prev_state.done {
11811 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11812 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11813 let mut next_selected_range = None;
11814 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11815 let bytes_before_last_selection =
11816 buffer.reversed_bytes_in_range(0..last_selection.start);
11817 let bytes_after_first_selection =
11818 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11819 let query_matches = query
11820 .stream_find_iter(bytes_before_last_selection)
11821 .map(|result| (last_selection.start, result))
11822 .chain(
11823 query
11824 .stream_find_iter(bytes_after_first_selection)
11825 .map(|result| (buffer.len(), result)),
11826 );
11827 for (end_offset, query_match) in query_matches {
11828 let query_match = query_match.unwrap(); // can only fail due to I/O
11829 let offset_range =
11830 end_offset - query_match.end()..end_offset - query_match.start();
11831 let display_range = offset_range.start.to_display_point(&display_map)
11832 ..offset_range.end.to_display_point(&display_map);
11833
11834 if !select_prev_state.wordwise
11835 || (!movement::is_inside_word(&display_map, display_range.start)
11836 && !movement::is_inside_word(&display_map, display_range.end))
11837 {
11838 next_selected_range = Some(offset_range);
11839 break;
11840 }
11841 }
11842
11843 if let Some(next_selected_range) = next_selected_range {
11844 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11845 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11846 if action.replace_newest {
11847 s.delete(s.newest_anchor().id);
11848 }
11849 s.insert_range(next_selected_range);
11850 });
11851 } else {
11852 select_prev_state.done = true;
11853 }
11854 }
11855
11856 self.select_prev_state = Some(select_prev_state);
11857 } else {
11858 let mut only_carets = true;
11859 let mut same_text_selected = true;
11860 let mut selected_text = None;
11861
11862 let mut selections_iter = selections.iter().peekable();
11863 while let Some(selection) = selections_iter.next() {
11864 if selection.start != selection.end {
11865 only_carets = false;
11866 }
11867
11868 if same_text_selected {
11869 if selected_text.is_none() {
11870 selected_text =
11871 Some(buffer.text_for_range(selection.range()).collect::<String>());
11872 }
11873
11874 if let Some(next_selection) = selections_iter.peek() {
11875 if next_selection.range().len() == selection.range().len() {
11876 let next_selected_text = buffer
11877 .text_for_range(next_selection.range())
11878 .collect::<String>();
11879 if Some(next_selected_text) != selected_text {
11880 same_text_selected = false;
11881 selected_text = None;
11882 }
11883 } else {
11884 same_text_selected = false;
11885 selected_text = None;
11886 }
11887 }
11888 }
11889 }
11890
11891 if only_carets {
11892 for selection in &mut selections {
11893 let word_range = movement::surrounding_word(
11894 &display_map,
11895 selection.start.to_display_point(&display_map),
11896 );
11897 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11898 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11899 selection.goal = SelectionGoal::None;
11900 selection.reversed = false;
11901 }
11902 if selections.len() == 1 {
11903 let selection = selections
11904 .last()
11905 .expect("ensured that there's only one selection");
11906 let query = buffer
11907 .text_for_range(selection.start..selection.end)
11908 .collect::<String>();
11909 let is_empty = query.is_empty();
11910 let select_state = SelectNextState {
11911 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11912 wordwise: true,
11913 done: is_empty,
11914 };
11915 self.select_prev_state = Some(select_state);
11916 } else {
11917 self.select_prev_state = None;
11918 }
11919
11920 self.unfold_ranges(
11921 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11922 false,
11923 true,
11924 cx,
11925 );
11926 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11927 s.select(selections);
11928 });
11929 } else if let Some(selected_text) = selected_text {
11930 self.select_prev_state = Some(SelectNextState {
11931 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11932 wordwise: false,
11933 done: false,
11934 });
11935 self.select_previous(action, window, cx)?;
11936 }
11937 }
11938 Ok(())
11939 }
11940
11941 pub fn toggle_comments(
11942 &mut self,
11943 action: &ToggleComments,
11944 window: &mut Window,
11945 cx: &mut Context<Self>,
11946 ) {
11947 if self.read_only(cx) {
11948 return;
11949 }
11950 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11951 let text_layout_details = &self.text_layout_details(window);
11952 self.transact(window, cx, |this, window, cx| {
11953 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11954 let mut edits = Vec::new();
11955 let mut selection_edit_ranges = Vec::new();
11956 let mut last_toggled_row = None;
11957 let snapshot = this.buffer.read(cx).read(cx);
11958 let empty_str: Arc<str> = Arc::default();
11959 let mut suffixes_inserted = Vec::new();
11960 let ignore_indent = action.ignore_indent;
11961
11962 fn comment_prefix_range(
11963 snapshot: &MultiBufferSnapshot,
11964 row: MultiBufferRow,
11965 comment_prefix: &str,
11966 comment_prefix_whitespace: &str,
11967 ignore_indent: bool,
11968 ) -> Range<Point> {
11969 let indent_size = if ignore_indent {
11970 0
11971 } else {
11972 snapshot.indent_size_for_line(row).len
11973 };
11974
11975 let start = Point::new(row.0, indent_size);
11976
11977 let mut line_bytes = snapshot
11978 .bytes_in_range(start..snapshot.max_point())
11979 .flatten()
11980 .copied();
11981
11982 // If this line currently begins with the line comment prefix, then record
11983 // the range containing the prefix.
11984 if line_bytes
11985 .by_ref()
11986 .take(comment_prefix.len())
11987 .eq(comment_prefix.bytes())
11988 {
11989 // Include any whitespace that matches the comment prefix.
11990 let matching_whitespace_len = line_bytes
11991 .zip(comment_prefix_whitespace.bytes())
11992 .take_while(|(a, b)| a == b)
11993 .count() as u32;
11994 let end = Point::new(
11995 start.row,
11996 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11997 );
11998 start..end
11999 } else {
12000 start..start
12001 }
12002 }
12003
12004 fn comment_suffix_range(
12005 snapshot: &MultiBufferSnapshot,
12006 row: MultiBufferRow,
12007 comment_suffix: &str,
12008 comment_suffix_has_leading_space: bool,
12009 ) -> Range<Point> {
12010 let end = Point::new(row.0, snapshot.line_len(row));
12011 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12012
12013 let mut line_end_bytes = snapshot
12014 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12015 .flatten()
12016 .copied();
12017
12018 let leading_space_len = if suffix_start_column > 0
12019 && line_end_bytes.next() == Some(b' ')
12020 && comment_suffix_has_leading_space
12021 {
12022 1
12023 } else {
12024 0
12025 };
12026
12027 // If this line currently begins with the line comment prefix, then record
12028 // the range containing the prefix.
12029 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12030 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12031 start..end
12032 } else {
12033 end..end
12034 }
12035 }
12036
12037 // TODO: Handle selections that cross excerpts
12038 for selection in &mut selections {
12039 let start_column = snapshot
12040 .indent_size_for_line(MultiBufferRow(selection.start.row))
12041 .len;
12042 let language = if let Some(language) =
12043 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12044 {
12045 language
12046 } else {
12047 continue;
12048 };
12049
12050 selection_edit_ranges.clear();
12051
12052 // If multiple selections contain a given row, avoid processing that
12053 // row more than once.
12054 let mut start_row = MultiBufferRow(selection.start.row);
12055 if last_toggled_row == Some(start_row) {
12056 start_row = start_row.next_row();
12057 }
12058 let end_row =
12059 if selection.end.row > selection.start.row && selection.end.column == 0 {
12060 MultiBufferRow(selection.end.row - 1)
12061 } else {
12062 MultiBufferRow(selection.end.row)
12063 };
12064 last_toggled_row = Some(end_row);
12065
12066 if start_row > end_row {
12067 continue;
12068 }
12069
12070 // If the language has line comments, toggle those.
12071 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12072
12073 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12074 if ignore_indent {
12075 full_comment_prefixes = full_comment_prefixes
12076 .into_iter()
12077 .map(|s| Arc::from(s.trim_end()))
12078 .collect();
12079 }
12080
12081 if !full_comment_prefixes.is_empty() {
12082 let first_prefix = full_comment_prefixes
12083 .first()
12084 .expect("prefixes is non-empty");
12085 let prefix_trimmed_lengths = full_comment_prefixes
12086 .iter()
12087 .map(|p| p.trim_end_matches(' ').len())
12088 .collect::<SmallVec<[usize; 4]>>();
12089
12090 let mut all_selection_lines_are_comments = true;
12091
12092 for row in start_row.0..=end_row.0 {
12093 let row = MultiBufferRow(row);
12094 if start_row < end_row && snapshot.is_line_blank(row) {
12095 continue;
12096 }
12097
12098 let prefix_range = full_comment_prefixes
12099 .iter()
12100 .zip(prefix_trimmed_lengths.iter().copied())
12101 .map(|(prefix, trimmed_prefix_len)| {
12102 comment_prefix_range(
12103 snapshot.deref(),
12104 row,
12105 &prefix[..trimmed_prefix_len],
12106 &prefix[trimmed_prefix_len..],
12107 ignore_indent,
12108 )
12109 })
12110 .max_by_key(|range| range.end.column - range.start.column)
12111 .expect("prefixes is non-empty");
12112
12113 if prefix_range.is_empty() {
12114 all_selection_lines_are_comments = false;
12115 }
12116
12117 selection_edit_ranges.push(prefix_range);
12118 }
12119
12120 if all_selection_lines_are_comments {
12121 edits.extend(
12122 selection_edit_ranges
12123 .iter()
12124 .cloned()
12125 .map(|range| (range, empty_str.clone())),
12126 );
12127 } else {
12128 let min_column = selection_edit_ranges
12129 .iter()
12130 .map(|range| range.start.column)
12131 .min()
12132 .unwrap_or(0);
12133 edits.extend(selection_edit_ranges.iter().map(|range| {
12134 let position = Point::new(range.start.row, min_column);
12135 (position..position, first_prefix.clone())
12136 }));
12137 }
12138 } else if let Some((full_comment_prefix, comment_suffix)) =
12139 language.block_comment_delimiters()
12140 {
12141 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12142 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12143 let prefix_range = comment_prefix_range(
12144 snapshot.deref(),
12145 start_row,
12146 comment_prefix,
12147 comment_prefix_whitespace,
12148 ignore_indent,
12149 );
12150 let suffix_range = comment_suffix_range(
12151 snapshot.deref(),
12152 end_row,
12153 comment_suffix.trim_start_matches(' '),
12154 comment_suffix.starts_with(' '),
12155 );
12156
12157 if prefix_range.is_empty() || suffix_range.is_empty() {
12158 edits.push((
12159 prefix_range.start..prefix_range.start,
12160 full_comment_prefix.clone(),
12161 ));
12162 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12163 suffixes_inserted.push((end_row, comment_suffix.len()));
12164 } else {
12165 edits.push((prefix_range, empty_str.clone()));
12166 edits.push((suffix_range, empty_str.clone()));
12167 }
12168 } else {
12169 continue;
12170 }
12171 }
12172
12173 drop(snapshot);
12174 this.buffer.update(cx, |buffer, cx| {
12175 buffer.edit(edits, None, cx);
12176 });
12177
12178 // Adjust selections so that they end before any comment suffixes that
12179 // were inserted.
12180 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12181 let mut selections = this.selections.all::<Point>(cx);
12182 let snapshot = this.buffer.read(cx).read(cx);
12183 for selection in &mut selections {
12184 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12185 match row.cmp(&MultiBufferRow(selection.end.row)) {
12186 Ordering::Less => {
12187 suffixes_inserted.next();
12188 continue;
12189 }
12190 Ordering::Greater => break,
12191 Ordering::Equal => {
12192 if selection.end.column == snapshot.line_len(row) {
12193 if selection.is_empty() {
12194 selection.start.column -= suffix_len as u32;
12195 }
12196 selection.end.column -= suffix_len as u32;
12197 }
12198 break;
12199 }
12200 }
12201 }
12202 }
12203
12204 drop(snapshot);
12205 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12206 s.select(selections)
12207 });
12208
12209 let selections = this.selections.all::<Point>(cx);
12210 let selections_on_single_row = selections.windows(2).all(|selections| {
12211 selections[0].start.row == selections[1].start.row
12212 && selections[0].end.row == selections[1].end.row
12213 && selections[0].start.row == selections[0].end.row
12214 });
12215 let selections_selecting = selections
12216 .iter()
12217 .any(|selection| selection.start != selection.end);
12218 let advance_downwards = action.advance_downwards
12219 && selections_on_single_row
12220 && !selections_selecting
12221 && !matches!(this.mode, EditorMode::SingleLine { .. });
12222
12223 if advance_downwards {
12224 let snapshot = this.buffer.read(cx).snapshot(cx);
12225
12226 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12227 s.move_cursors_with(|display_snapshot, display_point, _| {
12228 let mut point = display_point.to_point(display_snapshot);
12229 point.row += 1;
12230 point = snapshot.clip_point(point, Bias::Left);
12231 let display_point = point.to_display_point(display_snapshot);
12232 let goal = SelectionGoal::HorizontalPosition(
12233 display_snapshot
12234 .x_for_display_point(display_point, text_layout_details)
12235 .into(),
12236 );
12237 (display_point, goal)
12238 })
12239 });
12240 }
12241 });
12242 }
12243
12244 pub fn select_enclosing_symbol(
12245 &mut self,
12246 _: &SelectEnclosingSymbol,
12247 window: &mut Window,
12248 cx: &mut Context<Self>,
12249 ) {
12250 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12251
12252 let buffer = self.buffer.read(cx).snapshot(cx);
12253 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12254
12255 fn update_selection(
12256 selection: &Selection<usize>,
12257 buffer_snap: &MultiBufferSnapshot,
12258 ) -> Option<Selection<usize>> {
12259 let cursor = selection.head();
12260 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12261 for symbol in symbols.iter().rev() {
12262 let start = symbol.range.start.to_offset(buffer_snap);
12263 let end = symbol.range.end.to_offset(buffer_snap);
12264 let new_range = start..end;
12265 if start < selection.start || end > selection.end {
12266 return Some(Selection {
12267 id: selection.id,
12268 start: new_range.start,
12269 end: new_range.end,
12270 goal: SelectionGoal::None,
12271 reversed: selection.reversed,
12272 });
12273 }
12274 }
12275 None
12276 }
12277
12278 let mut selected_larger_symbol = false;
12279 let new_selections = old_selections
12280 .iter()
12281 .map(|selection| match update_selection(selection, &buffer) {
12282 Some(new_selection) => {
12283 if new_selection.range() != selection.range() {
12284 selected_larger_symbol = true;
12285 }
12286 new_selection
12287 }
12288 None => selection.clone(),
12289 })
12290 .collect::<Vec<_>>();
12291
12292 if selected_larger_symbol {
12293 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12294 s.select(new_selections);
12295 });
12296 }
12297 }
12298
12299 pub fn select_larger_syntax_node(
12300 &mut self,
12301 _: &SelectLargerSyntaxNode,
12302 window: &mut Window,
12303 cx: &mut Context<Self>,
12304 ) {
12305 let Some(visible_row_count) = self.visible_row_count() else {
12306 return;
12307 };
12308 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12309 if old_selections.is_empty() {
12310 return;
12311 }
12312
12313 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12314
12315 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12316 let buffer = self.buffer.read(cx).snapshot(cx);
12317
12318 let mut selected_larger_node = false;
12319 let mut new_selections = old_selections
12320 .iter()
12321 .map(|selection| {
12322 let old_range = selection.start..selection.end;
12323 let mut new_range = old_range.clone();
12324 let mut new_node = None;
12325 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12326 {
12327 new_node = Some(node);
12328 new_range = match containing_range {
12329 MultiOrSingleBufferOffsetRange::Single(_) => break,
12330 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12331 };
12332 if !display_map.intersects_fold(new_range.start)
12333 && !display_map.intersects_fold(new_range.end)
12334 {
12335 break;
12336 }
12337 }
12338
12339 if let Some(node) = new_node {
12340 // Log the ancestor, to support using this action as a way to explore TreeSitter
12341 // nodes. Parent and grandparent are also logged because this operation will not
12342 // visit nodes that have the same range as their parent.
12343 log::info!("Node: {node:?}");
12344 let parent = node.parent();
12345 log::info!("Parent: {parent:?}");
12346 let grandparent = parent.and_then(|x| x.parent());
12347 log::info!("Grandparent: {grandparent:?}");
12348 }
12349
12350 selected_larger_node |= new_range != old_range;
12351 Selection {
12352 id: selection.id,
12353 start: new_range.start,
12354 end: new_range.end,
12355 goal: SelectionGoal::None,
12356 reversed: selection.reversed,
12357 }
12358 })
12359 .collect::<Vec<_>>();
12360
12361 if !selected_larger_node {
12362 return; // don't put this call in the history
12363 }
12364
12365 // scroll based on transformation done to the last selection created by the user
12366 let (last_old, last_new) = old_selections
12367 .last()
12368 .zip(new_selections.last().cloned())
12369 .expect("old_selections isn't empty");
12370
12371 // revert selection
12372 let is_selection_reversed = {
12373 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12374 new_selections.last_mut().expect("checked above").reversed =
12375 should_newest_selection_be_reversed;
12376 should_newest_selection_be_reversed
12377 };
12378
12379 if selected_larger_node {
12380 self.select_syntax_node_history.disable_clearing = true;
12381 self.change_selections(None, window, cx, |s| {
12382 s.select(new_selections.clone());
12383 });
12384 self.select_syntax_node_history.disable_clearing = false;
12385 }
12386
12387 let start_row = last_new.start.to_display_point(&display_map).row().0;
12388 let end_row = last_new.end.to_display_point(&display_map).row().0;
12389 let selection_height = end_row - start_row + 1;
12390 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12391
12392 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12393 let scroll_behavior = if fits_on_the_screen {
12394 self.request_autoscroll(Autoscroll::fit(), cx);
12395 SelectSyntaxNodeScrollBehavior::FitSelection
12396 } else if is_selection_reversed {
12397 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12398 SelectSyntaxNodeScrollBehavior::CursorTop
12399 } else {
12400 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12401 SelectSyntaxNodeScrollBehavior::CursorBottom
12402 };
12403
12404 self.select_syntax_node_history.push((
12405 old_selections,
12406 scroll_behavior,
12407 is_selection_reversed,
12408 ));
12409 }
12410
12411 pub fn select_smaller_syntax_node(
12412 &mut self,
12413 _: &SelectSmallerSyntaxNode,
12414 window: &mut Window,
12415 cx: &mut Context<Self>,
12416 ) {
12417 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12418
12419 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12420 self.select_syntax_node_history.pop()
12421 {
12422 if let Some(selection) = selections.last_mut() {
12423 selection.reversed = is_selection_reversed;
12424 }
12425
12426 self.select_syntax_node_history.disable_clearing = true;
12427 self.change_selections(None, window, cx, |s| {
12428 s.select(selections.to_vec());
12429 });
12430 self.select_syntax_node_history.disable_clearing = false;
12431
12432 match scroll_behavior {
12433 SelectSyntaxNodeScrollBehavior::CursorTop => {
12434 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12435 }
12436 SelectSyntaxNodeScrollBehavior::FitSelection => {
12437 self.request_autoscroll(Autoscroll::fit(), cx);
12438 }
12439 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12440 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12441 }
12442 }
12443 }
12444 }
12445
12446 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12447 if !EditorSettings::get_global(cx).gutter.runnables {
12448 self.clear_tasks();
12449 return Task::ready(());
12450 }
12451 let project = self.project.as_ref().map(Entity::downgrade);
12452 cx.spawn_in(window, async move |this, cx| {
12453 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12454 let Some(project) = project.and_then(|p| p.upgrade()) else {
12455 return;
12456 };
12457 let Ok(display_snapshot) = this.update(cx, |this, cx| {
12458 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12459 }) else {
12460 return;
12461 };
12462
12463 let hide_runnables = project
12464 .update(cx, |project, cx| {
12465 // Do not display any test indicators in non-dev server remote projects.
12466 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12467 })
12468 .unwrap_or(true);
12469 if hide_runnables {
12470 return;
12471 }
12472 let new_rows =
12473 cx.background_spawn({
12474 let snapshot = display_snapshot.clone();
12475 async move {
12476 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12477 }
12478 })
12479 .await;
12480
12481 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12482 this.update(cx, |this, _| {
12483 this.clear_tasks();
12484 for (key, value) in rows {
12485 this.insert_tasks(key, value);
12486 }
12487 })
12488 .ok();
12489 })
12490 }
12491 fn fetch_runnable_ranges(
12492 snapshot: &DisplaySnapshot,
12493 range: Range<Anchor>,
12494 ) -> Vec<language::RunnableRange> {
12495 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12496 }
12497
12498 fn runnable_rows(
12499 project: Entity<Project>,
12500 snapshot: DisplaySnapshot,
12501 runnable_ranges: Vec<RunnableRange>,
12502 mut cx: AsyncWindowContext,
12503 ) -> Vec<((BufferId, u32), RunnableTasks)> {
12504 runnable_ranges
12505 .into_iter()
12506 .filter_map(|mut runnable| {
12507 let tasks = cx
12508 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12509 .ok()?;
12510 if tasks.is_empty() {
12511 return None;
12512 }
12513
12514 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12515
12516 let row = snapshot
12517 .buffer_snapshot
12518 .buffer_line_for_row(MultiBufferRow(point.row))?
12519 .1
12520 .start
12521 .row;
12522
12523 let context_range =
12524 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12525 Some((
12526 (runnable.buffer_id, row),
12527 RunnableTasks {
12528 templates: tasks,
12529 offset: snapshot
12530 .buffer_snapshot
12531 .anchor_before(runnable.run_range.start),
12532 context_range,
12533 column: point.column,
12534 extra_variables: runnable.extra_captures,
12535 },
12536 ))
12537 })
12538 .collect()
12539 }
12540
12541 fn templates_with_tags(
12542 project: &Entity<Project>,
12543 runnable: &mut Runnable,
12544 cx: &mut App,
12545 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12546 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12547 let (worktree_id, file) = project
12548 .buffer_for_id(runnable.buffer, cx)
12549 .and_then(|buffer| buffer.read(cx).file())
12550 .map(|file| (file.worktree_id(cx), file.clone()))
12551 .unzip();
12552
12553 (
12554 project.task_store().read(cx).task_inventory().cloned(),
12555 worktree_id,
12556 file,
12557 )
12558 });
12559
12560 let tags = mem::take(&mut runnable.tags);
12561 let mut tags: Vec<_> = tags
12562 .into_iter()
12563 .flat_map(|tag| {
12564 let tag = tag.0.clone();
12565 inventory
12566 .as_ref()
12567 .into_iter()
12568 .flat_map(|inventory| {
12569 inventory.read(cx).list_tasks(
12570 file.clone(),
12571 Some(runnable.language.clone()),
12572 worktree_id,
12573 cx,
12574 )
12575 })
12576 .filter(move |(_, template)| {
12577 template.tags.iter().any(|source_tag| source_tag == &tag)
12578 })
12579 })
12580 .sorted_by_key(|(kind, _)| kind.to_owned())
12581 .collect();
12582 if let Some((leading_tag_source, _)) = tags.first() {
12583 // Strongest source wins; if we have worktree tag binding, prefer that to
12584 // global and language bindings;
12585 // if we have a global binding, prefer that to language binding.
12586 let first_mismatch = tags
12587 .iter()
12588 .position(|(tag_source, _)| tag_source != leading_tag_source);
12589 if let Some(index) = first_mismatch {
12590 tags.truncate(index);
12591 }
12592 }
12593
12594 tags
12595 }
12596
12597 pub fn move_to_enclosing_bracket(
12598 &mut self,
12599 _: &MoveToEnclosingBracket,
12600 window: &mut Window,
12601 cx: &mut Context<Self>,
12602 ) {
12603 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12604 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12605 s.move_offsets_with(|snapshot, selection| {
12606 let Some(enclosing_bracket_ranges) =
12607 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12608 else {
12609 return;
12610 };
12611
12612 let mut best_length = usize::MAX;
12613 let mut best_inside = false;
12614 let mut best_in_bracket_range = false;
12615 let mut best_destination = None;
12616 for (open, close) in enclosing_bracket_ranges {
12617 let close = close.to_inclusive();
12618 let length = close.end() - open.start;
12619 let inside = selection.start >= open.end && selection.end <= *close.start();
12620 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12621 || close.contains(&selection.head());
12622
12623 // If best is next to a bracket and current isn't, skip
12624 if !in_bracket_range && best_in_bracket_range {
12625 continue;
12626 }
12627
12628 // Prefer smaller lengths unless best is inside and current isn't
12629 if length > best_length && (best_inside || !inside) {
12630 continue;
12631 }
12632
12633 best_length = length;
12634 best_inside = inside;
12635 best_in_bracket_range = in_bracket_range;
12636 best_destination = Some(
12637 if close.contains(&selection.start) && close.contains(&selection.end) {
12638 if inside { open.end } else { open.start }
12639 } else if inside {
12640 *close.start()
12641 } else {
12642 *close.end()
12643 },
12644 );
12645 }
12646
12647 if let Some(destination) = best_destination {
12648 selection.collapse_to(destination, SelectionGoal::None);
12649 }
12650 })
12651 });
12652 }
12653
12654 pub fn undo_selection(
12655 &mut self,
12656 _: &UndoSelection,
12657 window: &mut Window,
12658 cx: &mut Context<Self>,
12659 ) {
12660 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12661 self.end_selection(window, cx);
12662 self.selection_history.mode = SelectionHistoryMode::Undoing;
12663 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12664 self.change_selections(None, window, cx, |s| {
12665 s.select_anchors(entry.selections.to_vec())
12666 });
12667 self.select_next_state = entry.select_next_state;
12668 self.select_prev_state = entry.select_prev_state;
12669 self.add_selections_state = entry.add_selections_state;
12670 self.request_autoscroll(Autoscroll::newest(), cx);
12671 }
12672 self.selection_history.mode = SelectionHistoryMode::Normal;
12673 }
12674
12675 pub fn redo_selection(
12676 &mut self,
12677 _: &RedoSelection,
12678 window: &mut Window,
12679 cx: &mut Context<Self>,
12680 ) {
12681 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12682 self.end_selection(window, cx);
12683 self.selection_history.mode = SelectionHistoryMode::Redoing;
12684 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12685 self.change_selections(None, window, cx, |s| {
12686 s.select_anchors(entry.selections.to_vec())
12687 });
12688 self.select_next_state = entry.select_next_state;
12689 self.select_prev_state = entry.select_prev_state;
12690 self.add_selections_state = entry.add_selections_state;
12691 self.request_autoscroll(Autoscroll::newest(), cx);
12692 }
12693 self.selection_history.mode = SelectionHistoryMode::Normal;
12694 }
12695
12696 pub fn expand_excerpts(
12697 &mut self,
12698 action: &ExpandExcerpts,
12699 _: &mut Window,
12700 cx: &mut Context<Self>,
12701 ) {
12702 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12703 }
12704
12705 pub fn expand_excerpts_down(
12706 &mut self,
12707 action: &ExpandExcerptsDown,
12708 _: &mut Window,
12709 cx: &mut Context<Self>,
12710 ) {
12711 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12712 }
12713
12714 pub fn expand_excerpts_up(
12715 &mut self,
12716 action: &ExpandExcerptsUp,
12717 _: &mut Window,
12718 cx: &mut Context<Self>,
12719 ) {
12720 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12721 }
12722
12723 pub fn expand_excerpts_for_direction(
12724 &mut self,
12725 lines: u32,
12726 direction: ExpandExcerptDirection,
12727
12728 cx: &mut Context<Self>,
12729 ) {
12730 let selections = self.selections.disjoint_anchors();
12731
12732 let lines = if lines == 0 {
12733 EditorSettings::get_global(cx).expand_excerpt_lines
12734 } else {
12735 lines
12736 };
12737
12738 self.buffer.update(cx, |buffer, cx| {
12739 let snapshot = buffer.snapshot(cx);
12740 let mut excerpt_ids = selections
12741 .iter()
12742 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12743 .collect::<Vec<_>>();
12744 excerpt_ids.sort();
12745 excerpt_ids.dedup();
12746 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12747 })
12748 }
12749
12750 pub fn expand_excerpt(
12751 &mut self,
12752 excerpt: ExcerptId,
12753 direction: ExpandExcerptDirection,
12754 window: &mut Window,
12755 cx: &mut Context<Self>,
12756 ) {
12757 let current_scroll_position = self.scroll_position(cx);
12758 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
12759 let mut should_scroll_up = false;
12760
12761 if direction == ExpandExcerptDirection::Down {
12762 let multi_buffer = self.buffer.read(cx);
12763 let snapshot = multi_buffer.snapshot(cx);
12764 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
12765 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12766 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
12767 let buffer_snapshot = buffer.read(cx).snapshot();
12768 let excerpt_end_row =
12769 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
12770 let last_row = buffer_snapshot.max_point().row;
12771 let lines_below = last_row.saturating_sub(excerpt_end_row);
12772 should_scroll_up = lines_below >= lines_to_expand;
12773 }
12774 }
12775 }
12776 }
12777
12778 self.buffer.update(cx, |buffer, cx| {
12779 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
12780 });
12781
12782 if should_scroll_up {
12783 let new_scroll_position =
12784 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
12785 self.set_scroll_position(new_scroll_position, window, cx);
12786 }
12787 }
12788
12789 pub fn go_to_singleton_buffer_point(
12790 &mut self,
12791 point: Point,
12792 window: &mut Window,
12793 cx: &mut Context<Self>,
12794 ) {
12795 self.go_to_singleton_buffer_range(point..point, window, cx);
12796 }
12797
12798 pub fn go_to_singleton_buffer_range(
12799 &mut self,
12800 range: Range<Point>,
12801 window: &mut Window,
12802 cx: &mut Context<Self>,
12803 ) {
12804 let multibuffer = self.buffer().read(cx);
12805 let Some(buffer) = multibuffer.as_singleton() else {
12806 return;
12807 };
12808 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12809 return;
12810 };
12811 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12812 return;
12813 };
12814 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12815 s.select_anchor_ranges([start..end])
12816 });
12817 }
12818
12819 fn go_to_diagnostic(
12820 &mut self,
12821 _: &GoToDiagnostic,
12822 window: &mut Window,
12823 cx: &mut Context<Self>,
12824 ) {
12825 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12826 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12827 }
12828
12829 fn go_to_prev_diagnostic(
12830 &mut self,
12831 _: &GoToPreviousDiagnostic,
12832 window: &mut Window,
12833 cx: &mut Context<Self>,
12834 ) {
12835 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12836 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12837 }
12838
12839 pub fn go_to_diagnostic_impl(
12840 &mut self,
12841 direction: Direction,
12842 window: &mut Window,
12843 cx: &mut Context<Self>,
12844 ) {
12845 let buffer = self.buffer.read(cx).snapshot(cx);
12846 let selection = self.selections.newest::<usize>(cx);
12847 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12848 if direction == Direction::Next {
12849 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12850 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12851 return;
12852 };
12853 self.activate_diagnostics(
12854 buffer_id,
12855 popover.local_diagnostic.diagnostic.group_id,
12856 window,
12857 cx,
12858 );
12859 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12860 let primary_range_start = active_diagnostics.primary_range.start;
12861 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12862 let mut new_selection = s.newest_anchor().clone();
12863 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12864 s.select_anchors(vec![new_selection.clone()]);
12865 });
12866 self.refresh_inline_completion(false, true, window, cx);
12867 }
12868 return;
12869 }
12870 }
12871
12872 let active_group_id = self
12873 .active_diagnostics
12874 .as_ref()
12875 .map(|active_group| active_group.group_id);
12876 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12877 active_diagnostics
12878 .primary_range
12879 .to_offset(&buffer)
12880 .to_inclusive()
12881 });
12882 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12883 if active_primary_range.contains(&selection.head()) {
12884 *active_primary_range.start()
12885 } else {
12886 selection.head()
12887 }
12888 } else {
12889 selection.head()
12890 };
12891
12892 let snapshot = self.snapshot(window, cx);
12893 let primary_diagnostics_before = buffer
12894 .diagnostics_in_range::<usize>(0..search_start)
12895 .filter(|entry| entry.diagnostic.is_primary)
12896 .filter(|entry| entry.range.start != entry.range.end)
12897 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12898 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12899 .collect::<Vec<_>>();
12900 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12901 primary_diagnostics_before
12902 .iter()
12903 .position(|entry| entry.diagnostic.group_id == active_group_id)
12904 });
12905
12906 let primary_diagnostics_after = buffer
12907 .diagnostics_in_range::<usize>(search_start..buffer.len())
12908 .filter(|entry| entry.diagnostic.is_primary)
12909 .filter(|entry| entry.range.start != entry.range.end)
12910 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12911 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12912 .collect::<Vec<_>>();
12913 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12914 primary_diagnostics_after
12915 .iter()
12916 .enumerate()
12917 .rev()
12918 .find_map(|(i, entry)| {
12919 if entry.diagnostic.group_id == active_group_id {
12920 Some(i)
12921 } else {
12922 None
12923 }
12924 })
12925 });
12926
12927 let next_primary_diagnostic = match direction {
12928 Direction::Prev => primary_diagnostics_before
12929 .iter()
12930 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12931 .rev()
12932 .next(),
12933 Direction::Next => primary_diagnostics_after
12934 .iter()
12935 .skip(
12936 last_same_group_diagnostic_after
12937 .map(|index| index + 1)
12938 .unwrap_or(0),
12939 )
12940 .next(),
12941 };
12942
12943 // Cycle around to the start of the buffer, potentially moving back to the start of
12944 // the currently active diagnostic.
12945 let cycle_around = || match direction {
12946 Direction::Prev => primary_diagnostics_after
12947 .iter()
12948 .rev()
12949 .chain(primary_diagnostics_before.iter().rev())
12950 .next(),
12951 Direction::Next => primary_diagnostics_before
12952 .iter()
12953 .chain(primary_diagnostics_after.iter())
12954 .next(),
12955 };
12956
12957 if let Some((primary_range, group_id)) = next_primary_diagnostic
12958 .or_else(cycle_around)
12959 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12960 {
12961 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12962 return;
12963 };
12964 self.activate_diagnostics(buffer_id, group_id, window, cx);
12965 if self.active_diagnostics.is_some() {
12966 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12967 s.select(vec![Selection {
12968 id: selection.id,
12969 start: primary_range.start,
12970 end: primary_range.start,
12971 reversed: false,
12972 goal: SelectionGoal::None,
12973 }]);
12974 });
12975 self.refresh_inline_completion(false, true, window, cx);
12976 }
12977 }
12978 }
12979
12980 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12981 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12982 let snapshot = self.snapshot(window, cx);
12983 let selection = self.selections.newest::<Point>(cx);
12984 self.go_to_hunk_before_or_after_position(
12985 &snapshot,
12986 selection.head(),
12987 Direction::Next,
12988 window,
12989 cx,
12990 );
12991 }
12992
12993 pub fn go_to_hunk_before_or_after_position(
12994 &mut self,
12995 snapshot: &EditorSnapshot,
12996 position: Point,
12997 direction: Direction,
12998 window: &mut Window,
12999 cx: &mut Context<Editor>,
13000 ) {
13001 let row = if direction == Direction::Next {
13002 self.hunk_after_position(snapshot, position)
13003 .map(|hunk| hunk.row_range.start)
13004 } else {
13005 self.hunk_before_position(snapshot, position)
13006 };
13007
13008 if let Some(row) = row {
13009 let destination = Point::new(row.0, 0);
13010 let autoscroll = Autoscroll::center();
13011
13012 self.unfold_ranges(&[destination..destination], false, false, cx);
13013 self.change_selections(Some(autoscroll), window, cx, |s| {
13014 s.select_ranges([destination..destination]);
13015 });
13016 }
13017 }
13018
13019 fn hunk_after_position(
13020 &mut self,
13021 snapshot: &EditorSnapshot,
13022 position: Point,
13023 ) -> Option<MultiBufferDiffHunk> {
13024 snapshot
13025 .buffer_snapshot
13026 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13027 .find(|hunk| hunk.row_range.start.0 > position.row)
13028 .or_else(|| {
13029 snapshot
13030 .buffer_snapshot
13031 .diff_hunks_in_range(Point::zero()..position)
13032 .find(|hunk| hunk.row_range.end.0 < position.row)
13033 })
13034 }
13035
13036 fn go_to_prev_hunk(
13037 &mut self,
13038 _: &GoToPreviousHunk,
13039 window: &mut Window,
13040 cx: &mut Context<Self>,
13041 ) {
13042 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13043 let snapshot = self.snapshot(window, cx);
13044 let selection = self.selections.newest::<Point>(cx);
13045 self.go_to_hunk_before_or_after_position(
13046 &snapshot,
13047 selection.head(),
13048 Direction::Prev,
13049 window,
13050 cx,
13051 );
13052 }
13053
13054 fn hunk_before_position(
13055 &mut self,
13056 snapshot: &EditorSnapshot,
13057 position: Point,
13058 ) -> Option<MultiBufferRow> {
13059 snapshot
13060 .buffer_snapshot
13061 .diff_hunk_before(position)
13062 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13063 }
13064
13065 fn go_to_line<T: 'static>(
13066 &mut self,
13067 position: Anchor,
13068 highlight_color: Option<Hsla>,
13069 window: &mut Window,
13070 cx: &mut Context<Self>,
13071 ) {
13072 let snapshot = self.snapshot(window, cx).display_snapshot;
13073 let position = position.to_point(&snapshot.buffer_snapshot);
13074 let start = snapshot
13075 .buffer_snapshot
13076 .clip_point(Point::new(position.row, 0), Bias::Left);
13077 let end = start + Point::new(1, 0);
13078 let start = snapshot.buffer_snapshot.anchor_before(start);
13079 let end = snapshot.buffer_snapshot.anchor_before(end);
13080
13081 self.highlight_rows::<T>(
13082 start..end,
13083 highlight_color
13084 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13085 false,
13086 cx,
13087 );
13088 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13089 }
13090
13091 pub fn go_to_definition(
13092 &mut self,
13093 _: &GoToDefinition,
13094 window: &mut Window,
13095 cx: &mut Context<Self>,
13096 ) -> Task<Result<Navigated>> {
13097 let definition =
13098 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13099 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13100 cx.spawn_in(window, async move |editor, cx| {
13101 if definition.await? == Navigated::Yes {
13102 return Ok(Navigated::Yes);
13103 }
13104 match fallback_strategy {
13105 GoToDefinitionFallback::None => Ok(Navigated::No),
13106 GoToDefinitionFallback::FindAllReferences => {
13107 match editor.update_in(cx, |editor, window, cx| {
13108 editor.find_all_references(&FindAllReferences, window, cx)
13109 })? {
13110 Some(references) => references.await,
13111 None => Ok(Navigated::No),
13112 }
13113 }
13114 }
13115 })
13116 }
13117
13118 pub fn go_to_declaration(
13119 &mut self,
13120 _: &GoToDeclaration,
13121 window: &mut Window,
13122 cx: &mut Context<Self>,
13123 ) -> Task<Result<Navigated>> {
13124 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13125 }
13126
13127 pub fn go_to_declaration_split(
13128 &mut self,
13129 _: &GoToDeclaration,
13130 window: &mut Window,
13131 cx: &mut Context<Self>,
13132 ) -> Task<Result<Navigated>> {
13133 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13134 }
13135
13136 pub fn go_to_implementation(
13137 &mut self,
13138 _: &GoToImplementation,
13139 window: &mut Window,
13140 cx: &mut Context<Self>,
13141 ) -> Task<Result<Navigated>> {
13142 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13143 }
13144
13145 pub fn go_to_implementation_split(
13146 &mut self,
13147 _: &GoToImplementationSplit,
13148 window: &mut Window,
13149 cx: &mut Context<Self>,
13150 ) -> Task<Result<Navigated>> {
13151 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13152 }
13153
13154 pub fn go_to_type_definition(
13155 &mut self,
13156 _: &GoToTypeDefinition,
13157 window: &mut Window,
13158 cx: &mut Context<Self>,
13159 ) -> Task<Result<Navigated>> {
13160 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13161 }
13162
13163 pub fn go_to_definition_split(
13164 &mut self,
13165 _: &GoToDefinitionSplit,
13166 window: &mut Window,
13167 cx: &mut Context<Self>,
13168 ) -> Task<Result<Navigated>> {
13169 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13170 }
13171
13172 pub fn go_to_type_definition_split(
13173 &mut self,
13174 _: &GoToTypeDefinitionSplit,
13175 window: &mut Window,
13176 cx: &mut Context<Self>,
13177 ) -> Task<Result<Navigated>> {
13178 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13179 }
13180
13181 fn go_to_definition_of_kind(
13182 &mut self,
13183 kind: GotoDefinitionKind,
13184 split: bool,
13185 window: &mut Window,
13186 cx: &mut Context<Self>,
13187 ) -> Task<Result<Navigated>> {
13188 let Some(provider) = self.semantics_provider.clone() else {
13189 return Task::ready(Ok(Navigated::No));
13190 };
13191 let head = self.selections.newest::<usize>(cx).head();
13192 let buffer = self.buffer.read(cx);
13193 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13194 text_anchor
13195 } else {
13196 return Task::ready(Ok(Navigated::No));
13197 };
13198
13199 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13200 return Task::ready(Ok(Navigated::No));
13201 };
13202
13203 cx.spawn_in(window, async move |editor, cx| {
13204 let definitions = definitions.await?;
13205 let navigated = editor
13206 .update_in(cx, |editor, window, cx| {
13207 editor.navigate_to_hover_links(
13208 Some(kind),
13209 definitions
13210 .into_iter()
13211 .filter(|location| {
13212 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13213 })
13214 .map(HoverLink::Text)
13215 .collect::<Vec<_>>(),
13216 split,
13217 window,
13218 cx,
13219 )
13220 })?
13221 .await?;
13222 anyhow::Ok(navigated)
13223 })
13224 }
13225
13226 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13227 let selection = self.selections.newest_anchor();
13228 let head = selection.head();
13229 let tail = selection.tail();
13230
13231 let Some((buffer, start_position)) =
13232 self.buffer.read(cx).text_anchor_for_position(head, cx)
13233 else {
13234 return;
13235 };
13236
13237 let end_position = if head != tail {
13238 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13239 return;
13240 };
13241 Some(pos)
13242 } else {
13243 None
13244 };
13245
13246 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13247 let url = if let Some(end_pos) = end_position {
13248 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13249 } else {
13250 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13251 };
13252
13253 if let Some(url) = url {
13254 editor.update(cx, |_, cx| {
13255 cx.open_url(&url);
13256 })
13257 } else {
13258 Ok(())
13259 }
13260 });
13261
13262 url_finder.detach();
13263 }
13264
13265 pub fn open_selected_filename(
13266 &mut self,
13267 _: &OpenSelectedFilename,
13268 window: &mut Window,
13269 cx: &mut Context<Self>,
13270 ) {
13271 let Some(workspace) = self.workspace() else {
13272 return;
13273 };
13274
13275 let position = self.selections.newest_anchor().head();
13276
13277 let Some((buffer, buffer_position)) =
13278 self.buffer.read(cx).text_anchor_for_position(position, cx)
13279 else {
13280 return;
13281 };
13282
13283 let project = self.project.clone();
13284
13285 cx.spawn_in(window, async move |_, cx| {
13286 let result = find_file(&buffer, project, buffer_position, cx).await;
13287
13288 if let Some((_, path)) = result {
13289 workspace
13290 .update_in(cx, |workspace, window, cx| {
13291 workspace.open_resolved_path(path, window, cx)
13292 })?
13293 .await?;
13294 }
13295 anyhow::Ok(())
13296 })
13297 .detach();
13298 }
13299
13300 pub(crate) fn navigate_to_hover_links(
13301 &mut self,
13302 kind: Option<GotoDefinitionKind>,
13303 mut definitions: Vec<HoverLink>,
13304 split: bool,
13305 window: &mut Window,
13306 cx: &mut Context<Editor>,
13307 ) -> Task<Result<Navigated>> {
13308 // If there is one definition, just open it directly
13309 if definitions.len() == 1 {
13310 let definition = definitions.pop().unwrap();
13311
13312 enum TargetTaskResult {
13313 Location(Option<Location>),
13314 AlreadyNavigated,
13315 }
13316
13317 let target_task = match definition {
13318 HoverLink::Text(link) => {
13319 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13320 }
13321 HoverLink::InlayHint(lsp_location, server_id) => {
13322 let computation =
13323 self.compute_target_location(lsp_location, server_id, window, cx);
13324 cx.background_spawn(async move {
13325 let location = computation.await?;
13326 Ok(TargetTaskResult::Location(location))
13327 })
13328 }
13329 HoverLink::Url(url) => {
13330 cx.open_url(&url);
13331 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13332 }
13333 HoverLink::File(path) => {
13334 if let Some(workspace) = self.workspace() {
13335 cx.spawn_in(window, async move |_, cx| {
13336 workspace
13337 .update_in(cx, |workspace, window, cx| {
13338 workspace.open_resolved_path(path, window, cx)
13339 })?
13340 .await
13341 .map(|_| TargetTaskResult::AlreadyNavigated)
13342 })
13343 } else {
13344 Task::ready(Ok(TargetTaskResult::Location(None)))
13345 }
13346 }
13347 };
13348 cx.spawn_in(window, async move |editor, cx| {
13349 let target = match target_task.await.context("target resolution task")? {
13350 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13351 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13352 TargetTaskResult::Location(Some(target)) => target,
13353 };
13354
13355 editor.update_in(cx, |editor, window, cx| {
13356 let Some(workspace) = editor.workspace() else {
13357 return Navigated::No;
13358 };
13359 let pane = workspace.read(cx).active_pane().clone();
13360
13361 let range = target.range.to_point(target.buffer.read(cx));
13362 let range = editor.range_for_match(&range);
13363 let range = collapse_multiline_range(range);
13364
13365 if !split
13366 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13367 {
13368 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13369 } else {
13370 window.defer(cx, move |window, cx| {
13371 let target_editor: Entity<Self> =
13372 workspace.update(cx, |workspace, cx| {
13373 let pane = if split {
13374 workspace.adjacent_pane(window, cx)
13375 } else {
13376 workspace.active_pane().clone()
13377 };
13378
13379 workspace.open_project_item(
13380 pane,
13381 target.buffer.clone(),
13382 true,
13383 true,
13384 window,
13385 cx,
13386 )
13387 });
13388 target_editor.update(cx, |target_editor, cx| {
13389 // When selecting a definition in a different buffer, disable the nav history
13390 // to avoid creating a history entry at the previous cursor location.
13391 pane.update(cx, |pane, _| pane.disable_history());
13392 target_editor.go_to_singleton_buffer_range(range, window, cx);
13393 pane.update(cx, |pane, _| pane.enable_history());
13394 });
13395 });
13396 }
13397 Navigated::Yes
13398 })
13399 })
13400 } else if !definitions.is_empty() {
13401 cx.spawn_in(window, async move |editor, cx| {
13402 let (title, location_tasks, workspace) = editor
13403 .update_in(cx, |editor, window, cx| {
13404 let tab_kind = match kind {
13405 Some(GotoDefinitionKind::Implementation) => "Implementations",
13406 _ => "Definitions",
13407 };
13408 let title = definitions
13409 .iter()
13410 .find_map(|definition| match definition {
13411 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13412 let buffer = origin.buffer.read(cx);
13413 format!(
13414 "{} for {}",
13415 tab_kind,
13416 buffer
13417 .text_for_range(origin.range.clone())
13418 .collect::<String>()
13419 )
13420 }),
13421 HoverLink::InlayHint(_, _) => None,
13422 HoverLink::Url(_) => None,
13423 HoverLink::File(_) => None,
13424 })
13425 .unwrap_or(tab_kind.to_string());
13426 let location_tasks = definitions
13427 .into_iter()
13428 .map(|definition| match definition {
13429 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13430 HoverLink::InlayHint(lsp_location, server_id) => editor
13431 .compute_target_location(lsp_location, server_id, window, cx),
13432 HoverLink::Url(_) => Task::ready(Ok(None)),
13433 HoverLink::File(_) => Task::ready(Ok(None)),
13434 })
13435 .collect::<Vec<_>>();
13436 (title, location_tasks, editor.workspace().clone())
13437 })
13438 .context("location tasks preparation")?;
13439
13440 let locations = future::join_all(location_tasks)
13441 .await
13442 .into_iter()
13443 .filter_map(|location| location.transpose())
13444 .collect::<Result<_>>()
13445 .context("location tasks")?;
13446
13447 let Some(workspace) = workspace else {
13448 return Ok(Navigated::No);
13449 };
13450 let opened = workspace
13451 .update_in(cx, |workspace, window, cx| {
13452 Self::open_locations_in_multibuffer(
13453 workspace,
13454 locations,
13455 title,
13456 split,
13457 MultibufferSelectionMode::First,
13458 window,
13459 cx,
13460 )
13461 })
13462 .ok();
13463
13464 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13465 })
13466 } else {
13467 Task::ready(Ok(Navigated::No))
13468 }
13469 }
13470
13471 fn compute_target_location(
13472 &self,
13473 lsp_location: lsp::Location,
13474 server_id: LanguageServerId,
13475 window: &mut Window,
13476 cx: &mut Context<Self>,
13477 ) -> Task<anyhow::Result<Option<Location>>> {
13478 let Some(project) = self.project.clone() else {
13479 return Task::ready(Ok(None));
13480 };
13481
13482 cx.spawn_in(window, async move |editor, cx| {
13483 let location_task = editor.update(cx, |_, cx| {
13484 project.update(cx, |project, cx| {
13485 let language_server_name = project
13486 .language_server_statuses(cx)
13487 .find(|(id, _)| server_id == *id)
13488 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13489 language_server_name.map(|language_server_name| {
13490 project.open_local_buffer_via_lsp(
13491 lsp_location.uri.clone(),
13492 server_id,
13493 language_server_name,
13494 cx,
13495 )
13496 })
13497 })
13498 })?;
13499 let location = match location_task {
13500 Some(task) => Some({
13501 let target_buffer_handle = task.await.context("open local buffer")?;
13502 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13503 let target_start = target_buffer
13504 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13505 let target_end = target_buffer
13506 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13507 target_buffer.anchor_after(target_start)
13508 ..target_buffer.anchor_before(target_end)
13509 })?;
13510 Location {
13511 buffer: target_buffer_handle,
13512 range,
13513 }
13514 }),
13515 None => None,
13516 };
13517 Ok(location)
13518 })
13519 }
13520
13521 pub fn find_all_references(
13522 &mut self,
13523 _: &FindAllReferences,
13524 window: &mut Window,
13525 cx: &mut Context<Self>,
13526 ) -> Option<Task<Result<Navigated>>> {
13527 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13528
13529 let selection = self.selections.newest::<usize>(cx);
13530 let multi_buffer = self.buffer.read(cx);
13531 let head = selection.head();
13532
13533 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13534 let head_anchor = multi_buffer_snapshot.anchor_at(
13535 head,
13536 if head < selection.tail() {
13537 Bias::Right
13538 } else {
13539 Bias::Left
13540 },
13541 );
13542
13543 match self
13544 .find_all_references_task_sources
13545 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13546 {
13547 Ok(_) => {
13548 log::info!(
13549 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13550 );
13551 return None;
13552 }
13553 Err(i) => {
13554 self.find_all_references_task_sources.insert(i, head_anchor);
13555 }
13556 }
13557
13558 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13559 let workspace = self.workspace()?;
13560 let project = workspace.read(cx).project().clone();
13561 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13562 Some(cx.spawn_in(window, async move |editor, cx| {
13563 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13564 if let Ok(i) = editor
13565 .find_all_references_task_sources
13566 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13567 {
13568 editor.find_all_references_task_sources.remove(i);
13569 }
13570 });
13571
13572 let locations = references.await?;
13573 if locations.is_empty() {
13574 return anyhow::Ok(Navigated::No);
13575 }
13576
13577 workspace.update_in(cx, |workspace, window, cx| {
13578 let title = locations
13579 .first()
13580 .as_ref()
13581 .map(|location| {
13582 let buffer = location.buffer.read(cx);
13583 format!(
13584 "References to `{}`",
13585 buffer
13586 .text_for_range(location.range.clone())
13587 .collect::<String>()
13588 )
13589 })
13590 .unwrap();
13591 Self::open_locations_in_multibuffer(
13592 workspace,
13593 locations,
13594 title,
13595 false,
13596 MultibufferSelectionMode::First,
13597 window,
13598 cx,
13599 );
13600 Navigated::Yes
13601 })
13602 }))
13603 }
13604
13605 /// Opens a multibuffer with the given project locations in it
13606 pub fn open_locations_in_multibuffer(
13607 workspace: &mut Workspace,
13608 mut locations: Vec<Location>,
13609 title: String,
13610 split: bool,
13611 multibuffer_selection_mode: MultibufferSelectionMode,
13612 window: &mut Window,
13613 cx: &mut Context<Workspace>,
13614 ) {
13615 // If there are multiple definitions, open them in a multibuffer
13616 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13617 let mut locations = locations.into_iter().peekable();
13618 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13619 let capability = workspace.project().read(cx).capability();
13620
13621 let excerpt_buffer = cx.new(|cx| {
13622 let mut multibuffer = MultiBuffer::new(capability);
13623 while let Some(location) = locations.next() {
13624 let buffer = location.buffer.read(cx);
13625 let mut ranges_for_buffer = Vec::new();
13626 let range = location.range.to_point(buffer);
13627 ranges_for_buffer.push(range.clone());
13628
13629 while let Some(next_location) = locations.peek() {
13630 if next_location.buffer == location.buffer {
13631 ranges_for_buffer.push(next_location.range.to_point(buffer));
13632 locations.next();
13633 } else {
13634 break;
13635 }
13636 }
13637
13638 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13639 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13640 PathKey::for_buffer(&location.buffer, cx),
13641 location.buffer.clone(),
13642 ranges_for_buffer,
13643 DEFAULT_MULTIBUFFER_CONTEXT,
13644 cx,
13645 );
13646 ranges.extend(new_ranges)
13647 }
13648
13649 multibuffer.with_title(title)
13650 });
13651
13652 let editor = cx.new(|cx| {
13653 Editor::for_multibuffer(
13654 excerpt_buffer,
13655 Some(workspace.project().clone()),
13656 window,
13657 cx,
13658 )
13659 });
13660 editor.update(cx, |editor, cx| {
13661 match multibuffer_selection_mode {
13662 MultibufferSelectionMode::First => {
13663 if let Some(first_range) = ranges.first() {
13664 editor.change_selections(None, window, cx, |selections| {
13665 selections.clear_disjoint();
13666 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13667 });
13668 }
13669 editor.highlight_background::<Self>(
13670 &ranges,
13671 |theme| theme.editor_highlighted_line_background,
13672 cx,
13673 );
13674 }
13675 MultibufferSelectionMode::All => {
13676 editor.change_selections(None, window, cx, |selections| {
13677 selections.clear_disjoint();
13678 selections.select_anchor_ranges(ranges);
13679 });
13680 }
13681 }
13682 editor.register_buffers_with_language_servers(cx);
13683 });
13684
13685 let item = Box::new(editor);
13686 let item_id = item.item_id();
13687
13688 if split {
13689 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13690 } else {
13691 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13692 let (preview_item_id, preview_item_idx) =
13693 workspace.active_pane().update(cx, |pane, _| {
13694 (pane.preview_item_id(), pane.preview_item_idx())
13695 });
13696
13697 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13698
13699 if let Some(preview_item_id) = preview_item_id {
13700 workspace.active_pane().update(cx, |pane, cx| {
13701 pane.remove_item(preview_item_id, false, false, window, cx);
13702 });
13703 }
13704 } else {
13705 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13706 }
13707 }
13708 workspace.active_pane().update(cx, |pane, cx| {
13709 pane.set_preview_item_id(Some(item_id), cx);
13710 });
13711 }
13712
13713 pub fn rename(
13714 &mut self,
13715 _: &Rename,
13716 window: &mut Window,
13717 cx: &mut Context<Self>,
13718 ) -> Option<Task<Result<()>>> {
13719 use language::ToOffset as _;
13720
13721 let provider = self.semantics_provider.clone()?;
13722 let selection = self.selections.newest_anchor().clone();
13723 let (cursor_buffer, cursor_buffer_position) = self
13724 .buffer
13725 .read(cx)
13726 .text_anchor_for_position(selection.head(), cx)?;
13727 let (tail_buffer, cursor_buffer_position_end) = self
13728 .buffer
13729 .read(cx)
13730 .text_anchor_for_position(selection.tail(), cx)?;
13731 if tail_buffer != cursor_buffer {
13732 return None;
13733 }
13734
13735 let snapshot = cursor_buffer.read(cx).snapshot();
13736 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13737 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13738 let prepare_rename = provider
13739 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13740 .unwrap_or_else(|| Task::ready(Ok(None)));
13741 drop(snapshot);
13742
13743 Some(cx.spawn_in(window, async move |this, cx| {
13744 let rename_range = if let Some(range) = prepare_rename.await? {
13745 Some(range)
13746 } else {
13747 this.update(cx, |this, cx| {
13748 let buffer = this.buffer.read(cx).snapshot(cx);
13749 let mut buffer_highlights = this
13750 .document_highlights_for_position(selection.head(), &buffer)
13751 .filter(|highlight| {
13752 highlight.start.excerpt_id == selection.head().excerpt_id
13753 && highlight.end.excerpt_id == selection.head().excerpt_id
13754 });
13755 buffer_highlights
13756 .next()
13757 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13758 })?
13759 };
13760 if let Some(rename_range) = rename_range {
13761 this.update_in(cx, |this, window, cx| {
13762 let snapshot = cursor_buffer.read(cx).snapshot();
13763 let rename_buffer_range = rename_range.to_offset(&snapshot);
13764 let cursor_offset_in_rename_range =
13765 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13766 let cursor_offset_in_rename_range_end =
13767 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13768
13769 this.take_rename(false, window, cx);
13770 let buffer = this.buffer.read(cx).read(cx);
13771 let cursor_offset = selection.head().to_offset(&buffer);
13772 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13773 let rename_end = rename_start + rename_buffer_range.len();
13774 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13775 let mut old_highlight_id = None;
13776 let old_name: Arc<str> = buffer
13777 .chunks(rename_start..rename_end, true)
13778 .map(|chunk| {
13779 if old_highlight_id.is_none() {
13780 old_highlight_id = chunk.syntax_highlight_id;
13781 }
13782 chunk.text
13783 })
13784 .collect::<String>()
13785 .into();
13786
13787 drop(buffer);
13788
13789 // Position the selection in the rename editor so that it matches the current selection.
13790 this.show_local_selections = false;
13791 let rename_editor = cx.new(|cx| {
13792 let mut editor = Editor::single_line(window, cx);
13793 editor.buffer.update(cx, |buffer, cx| {
13794 buffer.edit([(0..0, old_name.clone())], None, cx)
13795 });
13796 let rename_selection_range = match cursor_offset_in_rename_range
13797 .cmp(&cursor_offset_in_rename_range_end)
13798 {
13799 Ordering::Equal => {
13800 editor.select_all(&SelectAll, window, cx);
13801 return editor;
13802 }
13803 Ordering::Less => {
13804 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13805 }
13806 Ordering::Greater => {
13807 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13808 }
13809 };
13810 if rename_selection_range.end > old_name.len() {
13811 editor.select_all(&SelectAll, window, cx);
13812 } else {
13813 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13814 s.select_ranges([rename_selection_range]);
13815 });
13816 }
13817 editor
13818 });
13819 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13820 if e == &EditorEvent::Focused {
13821 cx.emit(EditorEvent::FocusedIn)
13822 }
13823 })
13824 .detach();
13825
13826 let write_highlights =
13827 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13828 let read_highlights =
13829 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13830 let ranges = write_highlights
13831 .iter()
13832 .flat_map(|(_, ranges)| ranges.iter())
13833 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13834 .cloned()
13835 .collect();
13836
13837 this.highlight_text::<Rename>(
13838 ranges,
13839 HighlightStyle {
13840 fade_out: Some(0.6),
13841 ..Default::default()
13842 },
13843 cx,
13844 );
13845 let rename_focus_handle = rename_editor.focus_handle(cx);
13846 window.focus(&rename_focus_handle);
13847 let block_id = this.insert_blocks(
13848 [BlockProperties {
13849 style: BlockStyle::Flex,
13850 placement: BlockPlacement::Below(range.start),
13851 height: Some(1),
13852 render: Arc::new({
13853 let rename_editor = rename_editor.clone();
13854 move |cx: &mut BlockContext| {
13855 let mut text_style = cx.editor_style.text.clone();
13856 if let Some(highlight_style) = old_highlight_id
13857 .and_then(|h| h.style(&cx.editor_style.syntax))
13858 {
13859 text_style = text_style.highlight(highlight_style);
13860 }
13861 div()
13862 .block_mouse_down()
13863 .pl(cx.anchor_x)
13864 .child(EditorElement::new(
13865 &rename_editor,
13866 EditorStyle {
13867 background: cx.theme().system().transparent,
13868 local_player: cx.editor_style.local_player,
13869 text: text_style,
13870 scrollbar_width: cx.editor_style.scrollbar_width,
13871 syntax: cx.editor_style.syntax.clone(),
13872 status: cx.editor_style.status.clone(),
13873 inlay_hints_style: HighlightStyle {
13874 font_weight: Some(FontWeight::BOLD),
13875 ..make_inlay_hints_style(cx.app)
13876 },
13877 inline_completion_styles: make_suggestion_styles(
13878 cx.app,
13879 ),
13880 ..EditorStyle::default()
13881 },
13882 ))
13883 .into_any_element()
13884 }
13885 }),
13886 priority: 0,
13887 }],
13888 Some(Autoscroll::fit()),
13889 cx,
13890 )[0];
13891 this.pending_rename = Some(RenameState {
13892 range,
13893 old_name,
13894 editor: rename_editor,
13895 block_id,
13896 });
13897 })?;
13898 }
13899
13900 Ok(())
13901 }))
13902 }
13903
13904 pub fn confirm_rename(
13905 &mut self,
13906 _: &ConfirmRename,
13907 window: &mut Window,
13908 cx: &mut Context<Self>,
13909 ) -> Option<Task<Result<()>>> {
13910 let rename = self.take_rename(false, window, cx)?;
13911 let workspace = self.workspace()?.downgrade();
13912 let (buffer, start) = self
13913 .buffer
13914 .read(cx)
13915 .text_anchor_for_position(rename.range.start, cx)?;
13916 let (end_buffer, _) = self
13917 .buffer
13918 .read(cx)
13919 .text_anchor_for_position(rename.range.end, cx)?;
13920 if buffer != end_buffer {
13921 return None;
13922 }
13923
13924 let old_name = rename.old_name;
13925 let new_name = rename.editor.read(cx).text(cx);
13926
13927 let rename = self.semantics_provider.as_ref()?.perform_rename(
13928 &buffer,
13929 start,
13930 new_name.clone(),
13931 cx,
13932 )?;
13933
13934 Some(cx.spawn_in(window, async move |editor, cx| {
13935 let project_transaction = rename.await?;
13936 Self::open_project_transaction(
13937 &editor,
13938 workspace,
13939 project_transaction,
13940 format!("Rename: {} → {}", old_name, new_name),
13941 cx,
13942 )
13943 .await?;
13944
13945 editor.update(cx, |editor, cx| {
13946 editor.refresh_document_highlights(cx);
13947 })?;
13948 Ok(())
13949 }))
13950 }
13951
13952 fn take_rename(
13953 &mut self,
13954 moving_cursor: bool,
13955 window: &mut Window,
13956 cx: &mut Context<Self>,
13957 ) -> Option<RenameState> {
13958 let rename = self.pending_rename.take()?;
13959 if rename.editor.focus_handle(cx).is_focused(window) {
13960 window.focus(&self.focus_handle);
13961 }
13962
13963 self.remove_blocks(
13964 [rename.block_id].into_iter().collect(),
13965 Some(Autoscroll::fit()),
13966 cx,
13967 );
13968 self.clear_highlights::<Rename>(cx);
13969 self.show_local_selections = true;
13970
13971 if moving_cursor {
13972 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13973 editor.selections.newest::<usize>(cx).head()
13974 });
13975
13976 // Update the selection to match the position of the selection inside
13977 // the rename editor.
13978 let snapshot = self.buffer.read(cx).read(cx);
13979 let rename_range = rename.range.to_offset(&snapshot);
13980 let cursor_in_editor = snapshot
13981 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13982 .min(rename_range.end);
13983 drop(snapshot);
13984
13985 self.change_selections(None, window, cx, |s| {
13986 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13987 });
13988 } else {
13989 self.refresh_document_highlights(cx);
13990 }
13991
13992 Some(rename)
13993 }
13994
13995 pub fn pending_rename(&self) -> Option<&RenameState> {
13996 self.pending_rename.as_ref()
13997 }
13998
13999 fn format(
14000 &mut self,
14001 _: &Format,
14002 window: &mut Window,
14003 cx: &mut Context<Self>,
14004 ) -> Option<Task<Result<()>>> {
14005 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14006
14007 let project = match &self.project {
14008 Some(project) => project.clone(),
14009 None => return None,
14010 };
14011
14012 Some(self.perform_format(
14013 project,
14014 FormatTrigger::Manual,
14015 FormatTarget::Buffers,
14016 window,
14017 cx,
14018 ))
14019 }
14020
14021 fn format_selections(
14022 &mut self,
14023 _: &FormatSelections,
14024 window: &mut Window,
14025 cx: &mut Context<Self>,
14026 ) -> Option<Task<Result<()>>> {
14027 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14028
14029 let project = match &self.project {
14030 Some(project) => project.clone(),
14031 None => return None,
14032 };
14033
14034 let ranges = self
14035 .selections
14036 .all_adjusted(cx)
14037 .into_iter()
14038 .map(|selection| selection.range())
14039 .collect_vec();
14040
14041 Some(self.perform_format(
14042 project,
14043 FormatTrigger::Manual,
14044 FormatTarget::Ranges(ranges),
14045 window,
14046 cx,
14047 ))
14048 }
14049
14050 fn perform_format(
14051 &mut self,
14052 project: Entity<Project>,
14053 trigger: FormatTrigger,
14054 target: FormatTarget,
14055 window: &mut Window,
14056 cx: &mut Context<Self>,
14057 ) -> Task<Result<()>> {
14058 let buffer = self.buffer.clone();
14059 let (buffers, target) = match target {
14060 FormatTarget::Buffers => {
14061 let mut buffers = buffer.read(cx).all_buffers();
14062 if trigger == FormatTrigger::Save {
14063 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14064 }
14065 (buffers, LspFormatTarget::Buffers)
14066 }
14067 FormatTarget::Ranges(selection_ranges) => {
14068 let multi_buffer = buffer.read(cx);
14069 let snapshot = multi_buffer.read(cx);
14070 let mut buffers = HashSet::default();
14071 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14072 BTreeMap::new();
14073 for selection_range in selection_ranges {
14074 for (buffer, buffer_range, _) in
14075 snapshot.range_to_buffer_ranges(selection_range)
14076 {
14077 let buffer_id = buffer.remote_id();
14078 let start = buffer.anchor_before(buffer_range.start);
14079 let end = buffer.anchor_after(buffer_range.end);
14080 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14081 buffer_id_to_ranges
14082 .entry(buffer_id)
14083 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14084 .or_insert_with(|| vec![start..end]);
14085 }
14086 }
14087 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14088 }
14089 };
14090
14091 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14092 let format = project.update(cx, |project, cx| {
14093 project.format(buffers, target, true, trigger, cx)
14094 });
14095
14096 cx.spawn_in(window, async move |_, cx| {
14097 let transaction = futures::select_biased! {
14098 transaction = format.log_err().fuse() => transaction,
14099 () = timeout => {
14100 log::warn!("timed out waiting for formatting");
14101 None
14102 }
14103 };
14104
14105 buffer
14106 .update(cx, |buffer, cx| {
14107 if let Some(transaction) = transaction {
14108 if !buffer.is_singleton() {
14109 buffer.push_transaction(&transaction.0, cx);
14110 }
14111 }
14112 cx.notify();
14113 })
14114 .ok();
14115
14116 Ok(())
14117 })
14118 }
14119
14120 fn organize_imports(
14121 &mut self,
14122 _: &OrganizeImports,
14123 window: &mut Window,
14124 cx: &mut Context<Self>,
14125 ) -> Option<Task<Result<()>>> {
14126 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14127 let project = match &self.project {
14128 Some(project) => project.clone(),
14129 None => return None,
14130 };
14131 Some(self.perform_code_action_kind(
14132 project,
14133 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14134 window,
14135 cx,
14136 ))
14137 }
14138
14139 fn perform_code_action_kind(
14140 &mut self,
14141 project: Entity<Project>,
14142 kind: CodeActionKind,
14143 window: &mut Window,
14144 cx: &mut Context<Self>,
14145 ) -> Task<Result<()>> {
14146 let buffer = self.buffer.clone();
14147 let buffers = buffer.read(cx).all_buffers();
14148 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14149 let apply_action = project.update(cx, |project, cx| {
14150 project.apply_code_action_kind(buffers, kind, true, cx)
14151 });
14152 cx.spawn_in(window, async move |_, cx| {
14153 let transaction = futures::select_biased! {
14154 () = timeout => {
14155 log::warn!("timed out waiting for executing code action");
14156 None
14157 }
14158 transaction = apply_action.log_err().fuse() => transaction,
14159 };
14160 buffer
14161 .update(cx, |buffer, cx| {
14162 // check if we need this
14163 if let Some(transaction) = transaction {
14164 if !buffer.is_singleton() {
14165 buffer.push_transaction(&transaction.0, cx);
14166 }
14167 }
14168 cx.notify();
14169 })
14170 .ok();
14171 Ok(())
14172 })
14173 }
14174
14175 fn restart_language_server(
14176 &mut self,
14177 _: &RestartLanguageServer,
14178 _: &mut Window,
14179 cx: &mut Context<Self>,
14180 ) {
14181 if let Some(project) = self.project.clone() {
14182 self.buffer.update(cx, |multi_buffer, cx| {
14183 project.update(cx, |project, cx| {
14184 project.restart_language_servers_for_buffers(
14185 multi_buffer.all_buffers().into_iter().collect(),
14186 cx,
14187 );
14188 });
14189 })
14190 }
14191 }
14192
14193 fn stop_language_server(
14194 &mut self,
14195 _: &StopLanguageServer,
14196 _: &mut Window,
14197 cx: &mut Context<Self>,
14198 ) {
14199 if let Some(project) = self.project.clone() {
14200 self.buffer.update(cx, |multi_buffer, cx| {
14201 project.update(cx, |project, cx| {
14202 project.stop_language_servers_for_buffers(
14203 multi_buffer.all_buffers().into_iter().collect(),
14204 cx,
14205 );
14206 cx.emit(project::Event::RefreshInlayHints);
14207 });
14208 });
14209 }
14210 }
14211
14212 fn cancel_language_server_work(
14213 workspace: &mut Workspace,
14214 _: &actions::CancelLanguageServerWork,
14215 _: &mut Window,
14216 cx: &mut Context<Workspace>,
14217 ) {
14218 let project = workspace.project();
14219 let buffers = workspace
14220 .active_item(cx)
14221 .and_then(|item| item.act_as::<Editor>(cx))
14222 .map_or(HashSet::default(), |editor| {
14223 editor.read(cx).buffer.read(cx).all_buffers()
14224 });
14225 project.update(cx, |project, cx| {
14226 project.cancel_language_server_work_for_buffers(buffers, cx);
14227 });
14228 }
14229
14230 fn show_character_palette(
14231 &mut self,
14232 _: &ShowCharacterPalette,
14233 window: &mut Window,
14234 _: &mut Context<Self>,
14235 ) {
14236 window.show_character_palette();
14237 }
14238
14239 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14240 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14241 let buffer = self.buffer.read(cx).snapshot(cx);
14242 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14243 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14244 let is_valid = buffer
14245 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14246 .any(|entry| {
14247 entry.diagnostic.is_primary
14248 && !entry.range.is_empty()
14249 && entry.range.start == primary_range_start
14250 && entry.diagnostic.message == active_diagnostics.primary_message
14251 });
14252
14253 if is_valid != active_diagnostics.is_valid {
14254 active_diagnostics.is_valid = is_valid;
14255 if is_valid {
14256 let mut new_styles = HashMap::default();
14257 for (block_id, diagnostic) in &active_diagnostics.blocks {
14258 new_styles.insert(
14259 *block_id,
14260 diagnostic_block_renderer(diagnostic.clone(), None, true),
14261 );
14262 }
14263 self.display_map.update(cx, |display_map, _cx| {
14264 display_map.replace_blocks(new_styles);
14265 });
14266 } else {
14267 self.dismiss_diagnostics(cx);
14268 }
14269 }
14270 }
14271 }
14272
14273 fn activate_diagnostics(
14274 &mut self,
14275 buffer_id: BufferId,
14276 group_id: usize,
14277 window: &mut Window,
14278 cx: &mut Context<Self>,
14279 ) {
14280 self.dismiss_diagnostics(cx);
14281 let snapshot = self.snapshot(window, cx);
14282 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14283 let buffer = self.buffer.read(cx).snapshot(cx);
14284
14285 let mut primary_range = None;
14286 let mut primary_message = None;
14287 let diagnostic_group = buffer
14288 .diagnostic_group(buffer_id, group_id)
14289 .filter_map(|entry| {
14290 let start = entry.range.start;
14291 let end = entry.range.end;
14292 if snapshot.is_line_folded(MultiBufferRow(start.row))
14293 && (start.row == end.row
14294 || snapshot.is_line_folded(MultiBufferRow(end.row)))
14295 {
14296 return None;
14297 }
14298 if entry.diagnostic.is_primary {
14299 primary_range = Some(entry.range.clone());
14300 primary_message = Some(entry.diagnostic.message.clone());
14301 }
14302 Some(entry)
14303 })
14304 .collect::<Vec<_>>();
14305 let primary_range = primary_range?;
14306 let primary_message = primary_message?;
14307
14308 let blocks = display_map
14309 .insert_blocks(
14310 diagnostic_group.iter().map(|entry| {
14311 let diagnostic = entry.diagnostic.clone();
14312 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14313 BlockProperties {
14314 style: BlockStyle::Fixed,
14315 placement: BlockPlacement::Below(
14316 buffer.anchor_after(entry.range.start),
14317 ),
14318 height: Some(message_height),
14319 render: diagnostic_block_renderer(diagnostic, None, true),
14320 priority: 0,
14321 }
14322 }),
14323 cx,
14324 )
14325 .into_iter()
14326 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14327 .collect();
14328
14329 Some(ActiveDiagnosticGroup {
14330 primary_range: buffer.anchor_before(primary_range.start)
14331 ..buffer.anchor_after(primary_range.end),
14332 primary_message,
14333 group_id,
14334 blocks,
14335 is_valid: true,
14336 })
14337 });
14338 }
14339
14340 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14341 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14342 self.display_map.update(cx, |display_map, cx| {
14343 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14344 });
14345 cx.notify();
14346 }
14347 }
14348
14349 /// Disable inline diagnostics rendering for this editor.
14350 pub fn disable_inline_diagnostics(&mut self) {
14351 self.inline_diagnostics_enabled = false;
14352 self.inline_diagnostics_update = Task::ready(());
14353 self.inline_diagnostics.clear();
14354 }
14355
14356 pub fn inline_diagnostics_enabled(&self) -> bool {
14357 self.inline_diagnostics_enabled
14358 }
14359
14360 pub fn show_inline_diagnostics(&self) -> bool {
14361 self.show_inline_diagnostics
14362 }
14363
14364 pub fn toggle_inline_diagnostics(
14365 &mut self,
14366 _: &ToggleInlineDiagnostics,
14367 window: &mut Window,
14368 cx: &mut Context<Editor>,
14369 ) {
14370 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14371 self.refresh_inline_diagnostics(false, window, cx);
14372 }
14373
14374 fn refresh_inline_diagnostics(
14375 &mut self,
14376 debounce: bool,
14377 window: &mut Window,
14378 cx: &mut Context<Self>,
14379 ) {
14380 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14381 self.inline_diagnostics_update = Task::ready(());
14382 self.inline_diagnostics.clear();
14383 return;
14384 }
14385
14386 let debounce_ms = ProjectSettings::get_global(cx)
14387 .diagnostics
14388 .inline
14389 .update_debounce_ms;
14390 let debounce = if debounce && debounce_ms > 0 {
14391 Some(Duration::from_millis(debounce_ms))
14392 } else {
14393 None
14394 };
14395 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14396 if let Some(debounce) = debounce {
14397 cx.background_executor().timer(debounce).await;
14398 }
14399 let Some(snapshot) = editor
14400 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14401 .ok()
14402 else {
14403 return;
14404 };
14405
14406 let new_inline_diagnostics = cx
14407 .background_spawn(async move {
14408 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14409 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14410 let message = diagnostic_entry
14411 .diagnostic
14412 .message
14413 .split_once('\n')
14414 .map(|(line, _)| line)
14415 .map(SharedString::new)
14416 .unwrap_or_else(|| {
14417 SharedString::from(diagnostic_entry.diagnostic.message)
14418 });
14419 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14420 let (Ok(i) | Err(i)) = inline_diagnostics
14421 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14422 inline_diagnostics.insert(
14423 i,
14424 (
14425 start_anchor,
14426 InlineDiagnostic {
14427 message,
14428 group_id: diagnostic_entry.diagnostic.group_id,
14429 start: diagnostic_entry.range.start.to_point(&snapshot),
14430 is_primary: diagnostic_entry.diagnostic.is_primary,
14431 severity: diagnostic_entry.diagnostic.severity,
14432 },
14433 ),
14434 );
14435 }
14436 inline_diagnostics
14437 })
14438 .await;
14439
14440 editor
14441 .update(cx, |editor, cx| {
14442 editor.inline_diagnostics = new_inline_diagnostics;
14443 cx.notify();
14444 })
14445 .ok();
14446 });
14447 }
14448
14449 pub fn set_selections_from_remote(
14450 &mut self,
14451 selections: Vec<Selection<Anchor>>,
14452 pending_selection: Option<Selection<Anchor>>,
14453 window: &mut Window,
14454 cx: &mut Context<Self>,
14455 ) {
14456 let old_cursor_position = self.selections.newest_anchor().head();
14457 self.selections.change_with(cx, |s| {
14458 s.select_anchors(selections);
14459 if let Some(pending_selection) = pending_selection {
14460 s.set_pending(pending_selection, SelectMode::Character);
14461 } else {
14462 s.clear_pending();
14463 }
14464 });
14465 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14466 }
14467
14468 fn push_to_selection_history(&mut self) {
14469 self.selection_history.push(SelectionHistoryEntry {
14470 selections: self.selections.disjoint_anchors(),
14471 select_next_state: self.select_next_state.clone(),
14472 select_prev_state: self.select_prev_state.clone(),
14473 add_selections_state: self.add_selections_state.clone(),
14474 });
14475 }
14476
14477 pub fn transact(
14478 &mut self,
14479 window: &mut Window,
14480 cx: &mut Context<Self>,
14481 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14482 ) -> Option<TransactionId> {
14483 self.start_transaction_at(Instant::now(), window, cx);
14484 update(self, window, cx);
14485 self.end_transaction_at(Instant::now(), cx)
14486 }
14487
14488 pub fn start_transaction_at(
14489 &mut self,
14490 now: Instant,
14491 window: &mut Window,
14492 cx: &mut Context<Self>,
14493 ) {
14494 self.end_selection(window, cx);
14495 if let Some(tx_id) = self
14496 .buffer
14497 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14498 {
14499 self.selection_history
14500 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14501 cx.emit(EditorEvent::TransactionBegun {
14502 transaction_id: tx_id,
14503 })
14504 }
14505 }
14506
14507 pub fn end_transaction_at(
14508 &mut self,
14509 now: Instant,
14510 cx: &mut Context<Self>,
14511 ) -> Option<TransactionId> {
14512 if let Some(transaction_id) = self
14513 .buffer
14514 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14515 {
14516 if let Some((_, end_selections)) =
14517 self.selection_history.transaction_mut(transaction_id)
14518 {
14519 *end_selections = Some(self.selections.disjoint_anchors());
14520 } else {
14521 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14522 }
14523
14524 cx.emit(EditorEvent::Edited { transaction_id });
14525 Some(transaction_id)
14526 } else {
14527 None
14528 }
14529 }
14530
14531 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14532 if self.selection_mark_mode {
14533 self.change_selections(None, window, cx, |s| {
14534 s.move_with(|_, sel| {
14535 sel.collapse_to(sel.head(), SelectionGoal::None);
14536 });
14537 })
14538 }
14539 self.selection_mark_mode = true;
14540 cx.notify();
14541 }
14542
14543 pub fn swap_selection_ends(
14544 &mut self,
14545 _: &actions::SwapSelectionEnds,
14546 window: &mut Window,
14547 cx: &mut Context<Self>,
14548 ) {
14549 self.change_selections(None, window, cx, |s| {
14550 s.move_with(|_, sel| {
14551 if sel.start != sel.end {
14552 sel.reversed = !sel.reversed
14553 }
14554 });
14555 });
14556 self.request_autoscroll(Autoscroll::newest(), cx);
14557 cx.notify();
14558 }
14559
14560 pub fn toggle_fold(
14561 &mut self,
14562 _: &actions::ToggleFold,
14563 window: &mut Window,
14564 cx: &mut Context<Self>,
14565 ) {
14566 if self.is_singleton(cx) {
14567 let selection = self.selections.newest::<Point>(cx);
14568
14569 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14570 let range = if selection.is_empty() {
14571 let point = selection.head().to_display_point(&display_map);
14572 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14573 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14574 .to_point(&display_map);
14575 start..end
14576 } else {
14577 selection.range()
14578 };
14579 if display_map.folds_in_range(range).next().is_some() {
14580 self.unfold_lines(&Default::default(), window, cx)
14581 } else {
14582 self.fold(&Default::default(), window, cx)
14583 }
14584 } else {
14585 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14586 let buffer_ids: HashSet<_> = self
14587 .selections
14588 .disjoint_anchor_ranges()
14589 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14590 .collect();
14591
14592 let should_unfold = buffer_ids
14593 .iter()
14594 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14595
14596 for buffer_id in buffer_ids {
14597 if should_unfold {
14598 self.unfold_buffer(buffer_id, cx);
14599 } else {
14600 self.fold_buffer(buffer_id, cx);
14601 }
14602 }
14603 }
14604 }
14605
14606 pub fn toggle_fold_recursive(
14607 &mut self,
14608 _: &actions::ToggleFoldRecursive,
14609 window: &mut Window,
14610 cx: &mut Context<Self>,
14611 ) {
14612 let selection = self.selections.newest::<Point>(cx);
14613
14614 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14615 let range = if selection.is_empty() {
14616 let point = selection.head().to_display_point(&display_map);
14617 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14618 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14619 .to_point(&display_map);
14620 start..end
14621 } else {
14622 selection.range()
14623 };
14624 if display_map.folds_in_range(range).next().is_some() {
14625 self.unfold_recursive(&Default::default(), window, cx)
14626 } else {
14627 self.fold_recursive(&Default::default(), window, cx)
14628 }
14629 }
14630
14631 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14632 if self.is_singleton(cx) {
14633 let mut to_fold = Vec::new();
14634 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14635 let selections = self.selections.all_adjusted(cx);
14636
14637 for selection in selections {
14638 let range = selection.range().sorted();
14639 let buffer_start_row = range.start.row;
14640
14641 if range.start.row != range.end.row {
14642 let mut found = false;
14643 let mut row = range.start.row;
14644 while row <= range.end.row {
14645 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14646 {
14647 found = true;
14648 row = crease.range().end.row + 1;
14649 to_fold.push(crease);
14650 } else {
14651 row += 1
14652 }
14653 }
14654 if found {
14655 continue;
14656 }
14657 }
14658
14659 for row in (0..=range.start.row).rev() {
14660 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14661 if crease.range().end.row >= buffer_start_row {
14662 to_fold.push(crease);
14663 if row <= range.start.row {
14664 break;
14665 }
14666 }
14667 }
14668 }
14669 }
14670
14671 self.fold_creases(to_fold, true, window, cx);
14672 } else {
14673 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14674 let buffer_ids = self
14675 .selections
14676 .disjoint_anchor_ranges()
14677 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14678 .collect::<HashSet<_>>();
14679 for buffer_id in buffer_ids {
14680 self.fold_buffer(buffer_id, cx);
14681 }
14682 }
14683 }
14684
14685 fn fold_at_level(
14686 &mut self,
14687 fold_at: &FoldAtLevel,
14688 window: &mut Window,
14689 cx: &mut Context<Self>,
14690 ) {
14691 if !self.buffer.read(cx).is_singleton() {
14692 return;
14693 }
14694
14695 let fold_at_level = fold_at.0;
14696 let snapshot = self.buffer.read(cx).snapshot(cx);
14697 let mut to_fold = Vec::new();
14698 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14699
14700 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14701 while start_row < end_row {
14702 match self
14703 .snapshot(window, cx)
14704 .crease_for_buffer_row(MultiBufferRow(start_row))
14705 {
14706 Some(crease) => {
14707 let nested_start_row = crease.range().start.row + 1;
14708 let nested_end_row = crease.range().end.row;
14709
14710 if current_level < fold_at_level {
14711 stack.push((nested_start_row, nested_end_row, current_level + 1));
14712 } else if current_level == fold_at_level {
14713 to_fold.push(crease);
14714 }
14715
14716 start_row = nested_end_row + 1;
14717 }
14718 None => start_row += 1,
14719 }
14720 }
14721 }
14722
14723 self.fold_creases(to_fold, true, window, cx);
14724 }
14725
14726 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14727 if self.buffer.read(cx).is_singleton() {
14728 let mut fold_ranges = Vec::new();
14729 let snapshot = self.buffer.read(cx).snapshot(cx);
14730
14731 for row in 0..snapshot.max_row().0 {
14732 if let Some(foldable_range) = self
14733 .snapshot(window, cx)
14734 .crease_for_buffer_row(MultiBufferRow(row))
14735 {
14736 fold_ranges.push(foldable_range);
14737 }
14738 }
14739
14740 self.fold_creases(fold_ranges, true, window, cx);
14741 } else {
14742 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14743 editor
14744 .update_in(cx, |editor, _, cx| {
14745 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14746 editor.fold_buffer(buffer_id, cx);
14747 }
14748 })
14749 .ok();
14750 });
14751 }
14752 }
14753
14754 pub fn fold_function_bodies(
14755 &mut self,
14756 _: &actions::FoldFunctionBodies,
14757 window: &mut Window,
14758 cx: &mut Context<Self>,
14759 ) {
14760 let snapshot = self.buffer.read(cx).snapshot(cx);
14761
14762 let ranges = snapshot
14763 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14764 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14765 .collect::<Vec<_>>();
14766
14767 let creases = ranges
14768 .into_iter()
14769 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14770 .collect();
14771
14772 self.fold_creases(creases, true, window, cx);
14773 }
14774
14775 pub fn fold_recursive(
14776 &mut self,
14777 _: &actions::FoldRecursive,
14778 window: &mut Window,
14779 cx: &mut Context<Self>,
14780 ) {
14781 let mut to_fold = Vec::new();
14782 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14783 let selections = self.selections.all_adjusted(cx);
14784
14785 for selection in selections {
14786 let range = selection.range().sorted();
14787 let buffer_start_row = range.start.row;
14788
14789 if range.start.row != range.end.row {
14790 let mut found = false;
14791 for row in range.start.row..=range.end.row {
14792 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14793 found = true;
14794 to_fold.push(crease);
14795 }
14796 }
14797 if found {
14798 continue;
14799 }
14800 }
14801
14802 for row in (0..=range.start.row).rev() {
14803 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14804 if crease.range().end.row >= buffer_start_row {
14805 to_fold.push(crease);
14806 } else {
14807 break;
14808 }
14809 }
14810 }
14811 }
14812
14813 self.fold_creases(to_fold, true, window, cx);
14814 }
14815
14816 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14817 let buffer_row = fold_at.buffer_row;
14818 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14819
14820 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14821 let autoscroll = self
14822 .selections
14823 .all::<Point>(cx)
14824 .iter()
14825 .any(|selection| crease.range().overlaps(&selection.range()));
14826
14827 self.fold_creases(vec![crease], autoscroll, window, cx);
14828 }
14829 }
14830
14831 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14832 if self.is_singleton(cx) {
14833 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14834 let buffer = &display_map.buffer_snapshot;
14835 let selections = self.selections.all::<Point>(cx);
14836 let ranges = selections
14837 .iter()
14838 .map(|s| {
14839 let range = s.display_range(&display_map).sorted();
14840 let mut start = range.start.to_point(&display_map);
14841 let mut end = range.end.to_point(&display_map);
14842 start.column = 0;
14843 end.column = buffer.line_len(MultiBufferRow(end.row));
14844 start..end
14845 })
14846 .collect::<Vec<_>>();
14847
14848 self.unfold_ranges(&ranges, true, true, cx);
14849 } else {
14850 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14851 let buffer_ids = self
14852 .selections
14853 .disjoint_anchor_ranges()
14854 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14855 .collect::<HashSet<_>>();
14856 for buffer_id in buffer_ids {
14857 self.unfold_buffer(buffer_id, cx);
14858 }
14859 }
14860 }
14861
14862 pub fn unfold_recursive(
14863 &mut self,
14864 _: &UnfoldRecursive,
14865 _window: &mut Window,
14866 cx: &mut Context<Self>,
14867 ) {
14868 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14869 let selections = self.selections.all::<Point>(cx);
14870 let ranges = selections
14871 .iter()
14872 .map(|s| {
14873 let mut range = s.display_range(&display_map).sorted();
14874 *range.start.column_mut() = 0;
14875 *range.end.column_mut() = display_map.line_len(range.end.row());
14876 let start = range.start.to_point(&display_map);
14877 let end = range.end.to_point(&display_map);
14878 start..end
14879 })
14880 .collect::<Vec<_>>();
14881
14882 self.unfold_ranges(&ranges, true, true, cx);
14883 }
14884
14885 pub fn unfold_at(
14886 &mut self,
14887 unfold_at: &UnfoldAt,
14888 _window: &mut Window,
14889 cx: &mut Context<Self>,
14890 ) {
14891 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14892
14893 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14894 ..Point::new(
14895 unfold_at.buffer_row.0,
14896 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14897 );
14898
14899 let autoscroll = self
14900 .selections
14901 .all::<Point>(cx)
14902 .iter()
14903 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14904
14905 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14906 }
14907
14908 pub fn unfold_all(
14909 &mut self,
14910 _: &actions::UnfoldAll,
14911 _window: &mut Window,
14912 cx: &mut Context<Self>,
14913 ) {
14914 if self.buffer.read(cx).is_singleton() {
14915 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14916 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14917 } else {
14918 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14919 editor
14920 .update(cx, |editor, cx| {
14921 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14922 editor.unfold_buffer(buffer_id, cx);
14923 }
14924 })
14925 .ok();
14926 });
14927 }
14928 }
14929
14930 pub fn fold_selected_ranges(
14931 &mut self,
14932 _: &FoldSelectedRanges,
14933 window: &mut Window,
14934 cx: &mut Context<Self>,
14935 ) {
14936 let selections = self.selections.all_adjusted(cx);
14937 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14938 let ranges = selections
14939 .into_iter()
14940 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
14941 .collect::<Vec<_>>();
14942 self.fold_creases(ranges, true, window, cx);
14943 }
14944
14945 pub fn fold_ranges<T: ToOffset + Clone>(
14946 &mut self,
14947 ranges: Vec<Range<T>>,
14948 auto_scroll: bool,
14949 window: &mut Window,
14950 cx: &mut Context<Self>,
14951 ) {
14952 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14953 let ranges = ranges
14954 .into_iter()
14955 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14956 .collect::<Vec<_>>();
14957 self.fold_creases(ranges, auto_scroll, window, cx);
14958 }
14959
14960 pub fn fold_creases<T: ToOffset + Clone>(
14961 &mut self,
14962 creases: Vec<Crease<T>>,
14963 auto_scroll: bool,
14964 window: &mut Window,
14965 cx: &mut Context<Self>,
14966 ) {
14967 if creases.is_empty() {
14968 return;
14969 }
14970
14971 let mut buffers_affected = HashSet::default();
14972 let multi_buffer = self.buffer().read(cx);
14973 for crease in &creases {
14974 if let Some((_, buffer, _)) =
14975 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14976 {
14977 buffers_affected.insert(buffer.read(cx).remote_id());
14978 };
14979 }
14980
14981 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14982
14983 if auto_scroll {
14984 self.request_autoscroll(Autoscroll::fit(), cx);
14985 }
14986
14987 cx.notify();
14988
14989 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14990 // Clear diagnostics block when folding a range that contains it.
14991 let snapshot = self.snapshot(window, cx);
14992 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14993 drop(snapshot);
14994 self.active_diagnostics = Some(active_diagnostics);
14995 self.dismiss_diagnostics(cx);
14996 } else {
14997 self.active_diagnostics = Some(active_diagnostics);
14998 }
14999 }
15000
15001 self.scrollbar_marker_state.dirty = true;
15002 self.folds_did_change(cx);
15003 }
15004
15005 /// Removes any folds whose ranges intersect any of the given ranges.
15006 pub fn unfold_ranges<T: ToOffset + Clone>(
15007 &mut self,
15008 ranges: &[Range<T>],
15009 inclusive: bool,
15010 auto_scroll: bool,
15011 cx: &mut Context<Self>,
15012 ) {
15013 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15014 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15015 });
15016 self.folds_did_change(cx);
15017 }
15018
15019 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15020 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15021 return;
15022 }
15023 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15024 self.display_map.update(cx, |display_map, cx| {
15025 display_map.fold_buffers([buffer_id], cx)
15026 });
15027 cx.emit(EditorEvent::BufferFoldToggled {
15028 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15029 folded: true,
15030 });
15031 cx.notify();
15032 }
15033
15034 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15035 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15036 return;
15037 }
15038 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15039 self.display_map.update(cx, |display_map, cx| {
15040 display_map.unfold_buffers([buffer_id], cx);
15041 });
15042 cx.emit(EditorEvent::BufferFoldToggled {
15043 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15044 folded: false,
15045 });
15046 cx.notify();
15047 }
15048
15049 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15050 self.display_map.read(cx).is_buffer_folded(buffer)
15051 }
15052
15053 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15054 self.display_map.read(cx).folded_buffers()
15055 }
15056
15057 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15058 self.display_map.update(cx, |display_map, cx| {
15059 display_map.disable_header_for_buffer(buffer_id, cx);
15060 });
15061 cx.notify();
15062 }
15063
15064 /// Removes any folds with the given ranges.
15065 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15066 &mut self,
15067 ranges: &[Range<T>],
15068 type_id: TypeId,
15069 auto_scroll: bool,
15070 cx: &mut Context<Self>,
15071 ) {
15072 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15073 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15074 });
15075 self.folds_did_change(cx);
15076 }
15077
15078 fn remove_folds_with<T: ToOffset + Clone>(
15079 &mut self,
15080 ranges: &[Range<T>],
15081 auto_scroll: bool,
15082 cx: &mut Context<Self>,
15083 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15084 ) {
15085 if ranges.is_empty() {
15086 return;
15087 }
15088
15089 let mut buffers_affected = HashSet::default();
15090 let multi_buffer = self.buffer().read(cx);
15091 for range in ranges {
15092 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15093 buffers_affected.insert(buffer.read(cx).remote_id());
15094 };
15095 }
15096
15097 self.display_map.update(cx, update);
15098
15099 if auto_scroll {
15100 self.request_autoscroll(Autoscroll::fit(), cx);
15101 }
15102
15103 cx.notify();
15104 self.scrollbar_marker_state.dirty = true;
15105 self.active_indent_guides_state.dirty = true;
15106 }
15107
15108 pub fn update_fold_widths(
15109 &mut self,
15110 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15111 cx: &mut Context<Self>,
15112 ) -> bool {
15113 self.display_map
15114 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15115 }
15116
15117 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15118 self.display_map.read(cx).fold_placeholder.clone()
15119 }
15120
15121 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15122 self.buffer.update(cx, |buffer, cx| {
15123 buffer.set_all_diff_hunks_expanded(cx);
15124 });
15125 }
15126
15127 pub fn expand_all_diff_hunks(
15128 &mut self,
15129 _: &ExpandAllDiffHunks,
15130 _window: &mut Window,
15131 cx: &mut Context<Self>,
15132 ) {
15133 self.buffer.update(cx, |buffer, cx| {
15134 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15135 });
15136 }
15137
15138 pub fn toggle_selected_diff_hunks(
15139 &mut self,
15140 _: &ToggleSelectedDiffHunks,
15141 _window: &mut Window,
15142 cx: &mut Context<Self>,
15143 ) {
15144 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15145 self.toggle_diff_hunks_in_ranges(ranges, cx);
15146 }
15147
15148 pub fn diff_hunks_in_ranges<'a>(
15149 &'a self,
15150 ranges: &'a [Range<Anchor>],
15151 buffer: &'a MultiBufferSnapshot,
15152 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15153 ranges.iter().flat_map(move |range| {
15154 let end_excerpt_id = range.end.excerpt_id;
15155 let range = range.to_point(buffer);
15156 let mut peek_end = range.end;
15157 if range.end.row < buffer.max_row().0 {
15158 peek_end = Point::new(range.end.row + 1, 0);
15159 }
15160 buffer
15161 .diff_hunks_in_range(range.start..peek_end)
15162 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15163 })
15164 }
15165
15166 pub fn has_stageable_diff_hunks_in_ranges(
15167 &self,
15168 ranges: &[Range<Anchor>],
15169 snapshot: &MultiBufferSnapshot,
15170 ) -> bool {
15171 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15172 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15173 }
15174
15175 pub fn toggle_staged_selected_diff_hunks(
15176 &mut self,
15177 _: &::git::ToggleStaged,
15178 _: &mut Window,
15179 cx: &mut Context<Self>,
15180 ) {
15181 let snapshot = self.buffer.read(cx).snapshot(cx);
15182 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15183 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15184 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15185 }
15186
15187 pub fn set_render_diff_hunk_controls(
15188 &mut self,
15189 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15190 cx: &mut Context<Self>,
15191 ) {
15192 self.render_diff_hunk_controls = render_diff_hunk_controls;
15193 cx.notify();
15194 }
15195
15196 pub fn stage_and_next(
15197 &mut self,
15198 _: &::git::StageAndNext,
15199 window: &mut Window,
15200 cx: &mut Context<Self>,
15201 ) {
15202 self.do_stage_or_unstage_and_next(true, window, cx);
15203 }
15204
15205 pub fn unstage_and_next(
15206 &mut self,
15207 _: &::git::UnstageAndNext,
15208 window: &mut Window,
15209 cx: &mut Context<Self>,
15210 ) {
15211 self.do_stage_or_unstage_and_next(false, window, cx);
15212 }
15213
15214 pub fn stage_or_unstage_diff_hunks(
15215 &mut self,
15216 stage: bool,
15217 ranges: Vec<Range<Anchor>>,
15218 cx: &mut Context<Self>,
15219 ) {
15220 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15221 cx.spawn(async move |this, cx| {
15222 task.await?;
15223 this.update(cx, |this, cx| {
15224 let snapshot = this.buffer.read(cx).snapshot(cx);
15225 let chunk_by = this
15226 .diff_hunks_in_ranges(&ranges, &snapshot)
15227 .chunk_by(|hunk| hunk.buffer_id);
15228 for (buffer_id, hunks) in &chunk_by {
15229 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15230 }
15231 })
15232 })
15233 .detach_and_log_err(cx);
15234 }
15235
15236 fn save_buffers_for_ranges_if_needed(
15237 &mut self,
15238 ranges: &[Range<Anchor>],
15239 cx: &mut Context<Editor>,
15240 ) -> Task<Result<()>> {
15241 let multibuffer = self.buffer.read(cx);
15242 let snapshot = multibuffer.read(cx);
15243 let buffer_ids: HashSet<_> = ranges
15244 .iter()
15245 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15246 .collect();
15247 drop(snapshot);
15248
15249 let mut buffers = HashSet::default();
15250 for buffer_id in buffer_ids {
15251 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15252 let buffer = buffer_entity.read(cx);
15253 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15254 {
15255 buffers.insert(buffer_entity);
15256 }
15257 }
15258 }
15259
15260 if let Some(project) = &self.project {
15261 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15262 } else {
15263 Task::ready(Ok(()))
15264 }
15265 }
15266
15267 fn do_stage_or_unstage_and_next(
15268 &mut self,
15269 stage: bool,
15270 window: &mut Window,
15271 cx: &mut Context<Self>,
15272 ) {
15273 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15274
15275 if ranges.iter().any(|range| range.start != range.end) {
15276 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15277 return;
15278 }
15279
15280 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15281 let snapshot = self.snapshot(window, cx);
15282 let position = self.selections.newest::<Point>(cx).head();
15283 let mut row = snapshot
15284 .buffer_snapshot
15285 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15286 .find(|hunk| hunk.row_range.start.0 > position.row)
15287 .map(|hunk| hunk.row_range.start);
15288
15289 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15290 // Outside of the project diff editor, wrap around to the beginning.
15291 if !all_diff_hunks_expanded {
15292 row = row.or_else(|| {
15293 snapshot
15294 .buffer_snapshot
15295 .diff_hunks_in_range(Point::zero()..position)
15296 .find(|hunk| hunk.row_range.end.0 < position.row)
15297 .map(|hunk| hunk.row_range.start)
15298 });
15299 }
15300
15301 if let Some(row) = row {
15302 let destination = Point::new(row.0, 0);
15303 let autoscroll = Autoscroll::center();
15304
15305 self.unfold_ranges(&[destination..destination], false, false, cx);
15306 self.change_selections(Some(autoscroll), window, cx, |s| {
15307 s.select_ranges([destination..destination]);
15308 });
15309 }
15310 }
15311
15312 fn do_stage_or_unstage(
15313 &self,
15314 stage: bool,
15315 buffer_id: BufferId,
15316 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15317 cx: &mut App,
15318 ) -> Option<()> {
15319 let project = self.project.as_ref()?;
15320 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15321 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15322 let buffer_snapshot = buffer.read(cx).snapshot();
15323 let file_exists = buffer_snapshot
15324 .file()
15325 .is_some_and(|file| file.disk_state().exists());
15326 diff.update(cx, |diff, cx| {
15327 diff.stage_or_unstage_hunks(
15328 stage,
15329 &hunks
15330 .map(|hunk| buffer_diff::DiffHunk {
15331 buffer_range: hunk.buffer_range,
15332 diff_base_byte_range: hunk.diff_base_byte_range,
15333 secondary_status: hunk.secondary_status,
15334 range: Point::zero()..Point::zero(), // unused
15335 })
15336 .collect::<Vec<_>>(),
15337 &buffer_snapshot,
15338 file_exists,
15339 cx,
15340 )
15341 });
15342 None
15343 }
15344
15345 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15346 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15347 self.buffer
15348 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15349 }
15350
15351 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15352 self.buffer.update(cx, |buffer, cx| {
15353 let ranges = vec![Anchor::min()..Anchor::max()];
15354 if !buffer.all_diff_hunks_expanded()
15355 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15356 {
15357 buffer.collapse_diff_hunks(ranges, cx);
15358 true
15359 } else {
15360 false
15361 }
15362 })
15363 }
15364
15365 fn toggle_diff_hunks_in_ranges(
15366 &mut self,
15367 ranges: Vec<Range<Anchor>>,
15368 cx: &mut Context<Editor>,
15369 ) {
15370 self.buffer.update(cx, |buffer, cx| {
15371 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15372 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15373 })
15374 }
15375
15376 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15377 self.buffer.update(cx, |buffer, cx| {
15378 let snapshot = buffer.snapshot(cx);
15379 let excerpt_id = range.end.excerpt_id;
15380 let point_range = range.to_point(&snapshot);
15381 let expand = !buffer.single_hunk_is_expanded(range, cx);
15382 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15383 })
15384 }
15385
15386 pub(crate) fn apply_all_diff_hunks(
15387 &mut self,
15388 _: &ApplyAllDiffHunks,
15389 window: &mut Window,
15390 cx: &mut Context<Self>,
15391 ) {
15392 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15393
15394 let buffers = self.buffer.read(cx).all_buffers();
15395 for branch_buffer in buffers {
15396 branch_buffer.update(cx, |branch_buffer, cx| {
15397 branch_buffer.merge_into_base(Vec::new(), cx);
15398 });
15399 }
15400
15401 if let Some(project) = self.project.clone() {
15402 self.save(true, project, window, cx).detach_and_log_err(cx);
15403 }
15404 }
15405
15406 pub(crate) fn apply_selected_diff_hunks(
15407 &mut self,
15408 _: &ApplyDiffHunk,
15409 window: &mut Window,
15410 cx: &mut Context<Self>,
15411 ) {
15412 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15413 let snapshot = self.snapshot(window, cx);
15414 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15415 let mut ranges_by_buffer = HashMap::default();
15416 self.transact(window, cx, |editor, _window, cx| {
15417 for hunk in hunks {
15418 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15419 ranges_by_buffer
15420 .entry(buffer.clone())
15421 .or_insert_with(Vec::new)
15422 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15423 }
15424 }
15425
15426 for (buffer, ranges) in ranges_by_buffer {
15427 buffer.update(cx, |buffer, cx| {
15428 buffer.merge_into_base(ranges, cx);
15429 });
15430 }
15431 });
15432
15433 if let Some(project) = self.project.clone() {
15434 self.save(true, project, window, cx).detach_and_log_err(cx);
15435 }
15436 }
15437
15438 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15439 if hovered != self.gutter_hovered {
15440 self.gutter_hovered = hovered;
15441 cx.notify();
15442 }
15443 }
15444
15445 pub fn insert_blocks(
15446 &mut self,
15447 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15448 autoscroll: Option<Autoscroll>,
15449 cx: &mut Context<Self>,
15450 ) -> Vec<CustomBlockId> {
15451 let blocks = self
15452 .display_map
15453 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15454 if let Some(autoscroll) = autoscroll {
15455 self.request_autoscroll(autoscroll, cx);
15456 }
15457 cx.notify();
15458 blocks
15459 }
15460
15461 pub fn resize_blocks(
15462 &mut self,
15463 heights: HashMap<CustomBlockId, u32>,
15464 autoscroll: Option<Autoscroll>,
15465 cx: &mut Context<Self>,
15466 ) {
15467 self.display_map
15468 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15469 if let Some(autoscroll) = autoscroll {
15470 self.request_autoscroll(autoscroll, cx);
15471 }
15472 cx.notify();
15473 }
15474
15475 pub fn replace_blocks(
15476 &mut self,
15477 renderers: HashMap<CustomBlockId, RenderBlock>,
15478 autoscroll: Option<Autoscroll>,
15479 cx: &mut Context<Self>,
15480 ) {
15481 self.display_map
15482 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15483 if let Some(autoscroll) = autoscroll {
15484 self.request_autoscroll(autoscroll, cx);
15485 }
15486 cx.notify();
15487 }
15488
15489 pub fn remove_blocks(
15490 &mut self,
15491 block_ids: HashSet<CustomBlockId>,
15492 autoscroll: Option<Autoscroll>,
15493 cx: &mut Context<Self>,
15494 ) {
15495 self.display_map.update(cx, |display_map, cx| {
15496 display_map.remove_blocks(block_ids, cx)
15497 });
15498 if let Some(autoscroll) = autoscroll {
15499 self.request_autoscroll(autoscroll, cx);
15500 }
15501 cx.notify();
15502 }
15503
15504 pub fn row_for_block(
15505 &self,
15506 block_id: CustomBlockId,
15507 cx: &mut Context<Self>,
15508 ) -> Option<DisplayRow> {
15509 self.display_map
15510 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15511 }
15512
15513 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15514 self.focused_block = Some(focused_block);
15515 }
15516
15517 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15518 self.focused_block.take()
15519 }
15520
15521 pub fn insert_creases(
15522 &mut self,
15523 creases: impl IntoIterator<Item = Crease<Anchor>>,
15524 cx: &mut Context<Self>,
15525 ) -> Vec<CreaseId> {
15526 self.display_map
15527 .update(cx, |map, cx| map.insert_creases(creases, cx))
15528 }
15529
15530 pub fn remove_creases(
15531 &mut self,
15532 ids: impl IntoIterator<Item = CreaseId>,
15533 cx: &mut Context<Self>,
15534 ) {
15535 self.display_map
15536 .update(cx, |map, cx| map.remove_creases(ids, cx));
15537 }
15538
15539 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15540 self.display_map
15541 .update(cx, |map, cx| map.snapshot(cx))
15542 .longest_row()
15543 }
15544
15545 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15546 self.display_map
15547 .update(cx, |map, cx| map.snapshot(cx))
15548 .max_point()
15549 }
15550
15551 pub fn text(&self, cx: &App) -> String {
15552 self.buffer.read(cx).read(cx).text()
15553 }
15554
15555 pub fn is_empty(&self, cx: &App) -> bool {
15556 self.buffer.read(cx).read(cx).is_empty()
15557 }
15558
15559 pub fn text_option(&self, cx: &App) -> Option<String> {
15560 let text = self.text(cx);
15561 let text = text.trim();
15562
15563 if text.is_empty() {
15564 return None;
15565 }
15566
15567 Some(text.to_string())
15568 }
15569
15570 pub fn set_text(
15571 &mut self,
15572 text: impl Into<Arc<str>>,
15573 window: &mut Window,
15574 cx: &mut Context<Self>,
15575 ) {
15576 self.transact(window, cx, |this, _, cx| {
15577 this.buffer
15578 .read(cx)
15579 .as_singleton()
15580 .expect("you can only call set_text on editors for singleton buffers")
15581 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15582 });
15583 }
15584
15585 pub fn display_text(&self, cx: &mut App) -> String {
15586 self.display_map
15587 .update(cx, |map, cx| map.snapshot(cx))
15588 .text()
15589 }
15590
15591 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15592 let mut wrap_guides = smallvec::smallvec![];
15593
15594 if self.show_wrap_guides == Some(false) {
15595 return wrap_guides;
15596 }
15597
15598 let settings = self.buffer.read(cx).language_settings(cx);
15599 if settings.show_wrap_guides {
15600 match self.soft_wrap_mode(cx) {
15601 SoftWrap::Column(soft_wrap) => {
15602 wrap_guides.push((soft_wrap as usize, true));
15603 }
15604 SoftWrap::Bounded(soft_wrap) => {
15605 wrap_guides.push((soft_wrap as usize, true));
15606 }
15607 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15608 }
15609 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15610 }
15611
15612 wrap_guides
15613 }
15614
15615 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15616 let settings = self.buffer.read(cx).language_settings(cx);
15617 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15618 match mode {
15619 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15620 SoftWrap::None
15621 }
15622 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15623 language_settings::SoftWrap::PreferredLineLength => {
15624 SoftWrap::Column(settings.preferred_line_length)
15625 }
15626 language_settings::SoftWrap::Bounded => {
15627 SoftWrap::Bounded(settings.preferred_line_length)
15628 }
15629 }
15630 }
15631
15632 pub fn set_soft_wrap_mode(
15633 &mut self,
15634 mode: language_settings::SoftWrap,
15635
15636 cx: &mut Context<Self>,
15637 ) {
15638 self.soft_wrap_mode_override = Some(mode);
15639 cx.notify();
15640 }
15641
15642 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15643 self.hard_wrap = hard_wrap;
15644 cx.notify();
15645 }
15646
15647 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15648 self.text_style_refinement = Some(style);
15649 }
15650
15651 /// called by the Element so we know what style we were most recently rendered with.
15652 pub(crate) fn set_style(
15653 &mut self,
15654 style: EditorStyle,
15655 window: &mut Window,
15656 cx: &mut Context<Self>,
15657 ) {
15658 let rem_size = window.rem_size();
15659 self.display_map.update(cx, |map, cx| {
15660 map.set_font(
15661 style.text.font(),
15662 style.text.font_size.to_pixels(rem_size),
15663 cx,
15664 )
15665 });
15666 self.style = Some(style);
15667 }
15668
15669 pub fn style(&self) -> Option<&EditorStyle> {
15670 self.style.as_ref()
15671 }
15672
15673 // Called by the element. This method is not designed to be called outside of the editor
15674 // element's layout code because it does not notify when rewrapping is computed synchronously.
15675 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15676 self.display_map
15677 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15678 }
15679
15680 pub fn set_soft_wrap(&mut self) {
15681 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15682 }
15683
15684 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15685 if self.soft_wrap_mode_override.is_some() {
15686 self.soft_wrap_mode_override.take();
15687 } else {
15688 let soft_wrap = match self.soft_wrap_mode(cx) {
15689 SoftWrap::GitDiff => return,
15690 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15691 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15692 language_settings::SoftWrap::None
15693 }
15694 };
15695 self.soft_wrap_mode_override = Some(soft_wrap);
15696 }
15697 cx.notify();
15698 }
15699
15700 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15701 let Some(workspace) = self.workspace() else {
15702 return;
15703 };
15704 let fs = workspace.read(cx).app_state().fs.clone();
15705 let current_show = TabBarSettings::get_global(cx).show;
15706 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15707 setting.show = Some(!current_show);
15708 });
15709 }
15710
15711 pub fn toggle_indent_guides(
15712 &mut self,
15713 _: &ToggleIndentGuides,
15714 _: &mut Window,
15715 cx: &mut Context<Self>,
15716 ) {
15717 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15718 self.buffer
15719 .read(cx)
15720 .language_settings(cx)
15721 .indent_guides
15722 .enabled
15723 });
15724 self.show_indent_guides = Some(!currently_enabled);
15725 cx.notify();
15726 }
15727
15728 fn should_show_indent_guides(&self) -> Option<bool> {
15729 self.show_indent_guides
15730 }
15731
15732 pub fn toggle_line_numbers(
15733 &mut self,
15734 _: &ToggleLineNumbers,
15735 _: &mut Window,
15736 cx: &mut Context<Self>,
15737 ) {
15738 let mut editor_settings = EditorSettings::get_global(cx).clone();
15739 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15740 EditorSettings::override_global(editor_settings, cx);
15741 }
15742
15743 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15744 if let Some(show_line_numbers) = self.show_line_numbers {
15745 return show_line_numbers;
15746 }
15747 EditorSettings::get_global(cx).gutter.line_numbers
15748 }
15749
15750 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15751 self.use_relative_line_numbers
15752 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15753 }
15754
15755 pub fn toggle_relative_line_numbers(
15756 &mut self,
15757 _: &ToggleRelativeLineNumbers,
15758 _: &mut Window,
15759 cx: &mut Context<Self>,
15760 ) {
15761 let is_relative = self.should_use_relative_line_numbers(cx);
15762 self.set_relative_line_number(Some(!is_relative), cx)
15763 }
15764
15765 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15766 self.use_relative_line_numbers = is_relative;
15767 cx.notify();
15768 }
15769
15770 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15771 self.show_gutter = show_gutter;
15772 cx.notify();
15773 }
15774
15775 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15776 self.show_scrollbars = show_scrollbars;
15777 cx.notify();
15778 }
15779
15780 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15781 self.show_line_numbers = Some(show_line_numbers);
15782 cx.notify();
15783 }
15784
15785 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15786 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15787 cx.notify();
15788 }
15789
15790 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15791 self.show_code_actions = Some(show_code_actions);
15792 cx.notify();
15793 }
15794
15795 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15796 self.show_runnables = Some(show_runnables);
15797 cx.notify();
15798 }
15799
15800 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15801 self.show_breakpoints = Some(show_breakpoints);
15802 cx.notify();
15803 }
15804
15805 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15806 if self.display_map.read(cx).masked != masked {
15807 self.display_map.update(cx, |map, _| map.masked = masked);
15808 }
15809 cx.notify()
15810 }
15811
15812 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15813 self.show_wrap_guides = Some(show_wrap_guides);
15814 cx.notify();
15815 }
15816
15817 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15818 self.show_indent_guides = Some(show_indent_guides);
15819 cx.notify();
15820 }
15821
15822 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15823 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15824 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15825 if let Some(dir) = file.abs_path(cx).parent() {
15826 return Some(dir.to_owned());
15827 }
15828 }
15829
15830 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15831 return Some(project_path.path.to_path_buf());
15832 }
15833 }
15834
15835 None
15836 }
15837
15838 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15839 self.active_excerpt(cx)?
15840 .1
15841 .read(cx)
15842 .file()
15843 .and_then(|f| f.as_local())
15844 }
15845
15846 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15847 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15848 let buffer = buffer.read(cx);
15849 if let Some(project_path) = buffer.project_path(cx) {
15850 let project = self.project.as_ref()?.read(cx);
15851 project.absolute_path(&project_path, cx)
15852 } else {
15853 buffer
15854 .file()
15855 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15856 }
15857 })
15858 }
15859
15860 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15861 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15862 let project_path = buffer.read(cx).project_path(cx)?;
15863 let project = self.project.as_ref()?.read(cx);
15864 let entry = project.entry_for_path(&project_path, cx)?;
15865 let path = entry.path.to_path_buf();
15866 Some(path)
15867 })
15868 }
15869
15870 pub fn reveal_in_finder(
15871 &mut self,
15872 _: &RevealInFileManager,
15873 _window: &mut Window,
15874 cx: &mut Context<Self>,
15875 ) {
15876 if let Some(target) = self.target_file(cx) {
15877 cx.reveal_path(&target.abs_path(cx));
15878 }
15879 }
15880
15881 pub fn copy_path(
15882 &mut self,
15883 _: &zed_actions::workspace::CopyPath,
15884 _window: &mut Window,
15885 cx: &mut Context<Self>,
15886 ) {
15887 if let Some(path) = self.target_file_abs_path(cx) {
15888 if let Some(path) = path.to_str() {
15889 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15890 }
15891 }
15892 }
15893
15894 pub fn copy_relative_path(
15895 &mut self,
15896 _: &zed_actions::workspace::CopyRelativePath,
15897 _window: &mut Window,
15898 cx: &mut Context<Self>,
15899 ) {
15900 if let Some(path) = self.target_file_path(cx) {
15901 if let Some(path) = path.to_str() {
15902 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15903 }
15904 }
15905 }
15906
15907 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15908 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15909 buffer.read(cx).project_path(cx)
15910 } else {
15911 None
15912 }
15913 }
15914
15915 // Returns true if the editor handled a go-to-line request
15916 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
15917 maybe!({
15918 let breakpoint_store = self.breakpoint_store.as_ref()?;
15919
15920 let Some((_, _, active_position)) =
15921 breakpoint_store.read(cx).active_position().cloned()
15922 else {
15923 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15924 return None;
15925 };
15926
15927 let snapshot = self
15928 .project
15929 .as_ref()?
15930 .read(cx)
15931 .buffer_for_id(active_position.buffer_id?, cx)?
15932 .read(cx)
15933 .snapshot();
15934
15935 let mut handled = false;
15936 for (id, ExcerptRange { context, .. }) in self
15937 .buffer
15938 .read(cx)
15939 .excerpts_for_buffer(active_position.buffer_id?, cx)
15940 {
15941 if context.start.cmp(&active_position, &snapshot).is_ge()
15942 || context.end.cmp(&active_position, &snapshot).is_lt()
15943 {
15944 continue;
15945 }
15946 let snapshot = self.buffer.read(cx).snapshot(cx);
15947 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15948
15949 handled = true;
15950 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15951 self.go_to_line::<DebugCurrentRowHighlight>(
15952 multibuffer_anchor,
15953 Some(cx.theme().colors().editor_debugger_active_line_background),
15954 window,
15955 cx,
15956 );
15957
15958 cx.notify();
15959 }
15960 handled.then_some(())
15961 })
15962 .is_some()
15963 }
15964
15965 pub fn copy_file_name_without_extension(
15966 &mut self,
15967 _: &CopyFileNameWithoutExtension,
15968 _: &mut Window,
15969 cx: &mut Context<Self>,
15970 ) {
15971 if let Some(file) = self.target_file(cx) {
15972 if let Some(file_stem) = file.path().file_stem() {
15973 if let Some(name) = file_stem.to_str() {
15974 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15975 }
15976 }
15977 }
15978 }
15979
15980 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15981 if let Some(file) = self.target_file(cx) {
15982 if let Some(file_name) = file.path().file_name() {
15983 if let Some(name) = file_name.to_str() {
15984 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15985 }
15986 }
15987 }
15988 }
15989
15990 pub fn toggle_git_blame(
15991 &mut self,
15992 _: &::git::Blame,
15993 window: &mut Window,
15994 cx: &mut Context<Self>,
15995 ) {
15996 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15997
15998 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15999 self.start_git_blame(true, window, cx);
16000 }
16001
16002 cx.notify();
16003 }
16004
16005 pub fn toggle_git_blame_inline(
16006 &mut self,
16007 _: &ToggleGitBlameInline,
16008 window: &mut Window,
16009 cx: &mut Context<Self>,
16010 ) {
16011 self.toggle_git_blame_inline_internal(true, window, cx);
16012 cx.notify();
16013 }
16014
16015 pub fn open_git_blame_commit(
16016 &mut self,
16017 _: &OpenGitBlameCommit,
16018 window: &mut Window,
16019 cx: &mut Context<Self>,
16020 ) {
16021 self.open_git_blame_commit_internal(window, cx);
16022 }
16023
16024 fn open_git_blame_commit_internal(
16025 &mut self,
16026 window: &mut Window,
16027 cx: &mut Context<Self>,
16028 ) -> Option<()> {
16029 let blame = self.blame.as_ref()?;
16030 let snapshot = self.snapshot(window, cx);
16031 let cursor = self.selections.newest::<Point>(cx).head();
16032 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16033 let blame_entry = blame
16034 .update(cx, |blame, cx| {
16035 blame
16036 .blame_for_rows(
16037 &[RowInfo {
16038 buffer_id: Some(buffer.remote_id()),
16039 buffer_row: Some(point.row),
16040 ..Default::default()
16041 }],
16042 cx,
16043 )
16044 .next()
16045 })
16046 .flatten()?;
16047 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16048 let repo = blame.read(cx).repository(cx)?;
16049 let workspace = self.workspace()?.downgrade();
16050 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16051 None
16052 }
16053
16054 pub fn git_blame_inline_enabled(&self) -> bool {
16055 self.git_blame_inline_enabled
16056 }
16057
16058 pub fn toggle_selection_menu(
16059 &mut self,
16060 _: &ToggleSelectionMenu,
16061 _: &mut Window,
16062 cx: &mut Context<Self>,
16063 ) {
16064 self.show_selection_menu = self
16065 .show_selection_menu
16066 .map(|show_selections_menu| !show_selections_menu)
16067 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16068
16069 cx.notify();
16070 }
16071
16072 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16073 self.show_selection_menu
16074 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16075 }
16076
16077 fn start_git_blame(
16078 &mut self,
16079 user_triggered: bool,
16080 window: &mut Window,
16081 cx: &mut Context<Self>,
16082 ) {
16083 if let Some(project) = self.project.as_ref() {
16084 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16085 return;
16086 };
16087
16088 if buffer.read(cx).file().is_none() {
16089 return;
16090 }
16091
16092 let focused = self.focus_handle(cx).contains_focused(window, cx);
16093
16094 let project = project.clone();
16095 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16096 self.blame_subscription =
16097 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16098 self.blame = Some(blame);
16099 }
16100 }
16101
16102 fn toggle_git_blame_inline_internal(
16103 &mut self,
16104 user_triggered: bool,
16105 window: &mut Window,
16106 cx: &mut Context<Self>,
16107 ) {
16108 if self.git_blame_inline_enabled {
16109 self.git_blame_inline_enabled = false;
16110 self.show_git_blame_inline = false;
16111 self.show_git_blame_inline_delay_task.take();
16112 } else {
16113 self.git_blame_inline_enabled = true;
16114 self.start_git_blame_inline(user_triggered, window, cx);
16115 }
16116
16117 cx.notify();
16118 }
16119
16120 fn start_git_blame_inline(
16121 &mut self,
16122 user_triggered: bool,
16123 window: &mut Window,
16124 cx: &mut Context<Self>,
16125 ) {
16126 self.start_git_blame(user_triggered, window, cx);
16127
16128 if ProjectSettings::get_global(cx)
16129 .git
16130 .inline_blame_delay()
16131 .is_some()
16132 {
16133 self.start_inline_blame_timer(window, cx);
16134 } else {
16135 self.show_git_blame_inline = true
16136 }
16137 }
16138
16139 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16140 self.blame.as_ref()
16141 }
16142
16143 pub fn show_git_blame_gutter(&self) -> bool {
16144 self.show_git_blame_gutter
16145 }
16146
16147 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16148 self.show_git_blame_gutter && self.has_blame_entries(cx)
16149 }
16150
16151 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16152 self.show_git_blame_inline
16153 && (self.focus_handle.is_focused(window)
16154 || self
16155 .git_blame_inline_tooltip
16156 .as_ref()
16157 .and_then(|t| t.upgrade())
16158 .is_some())
16159 && !self.newest_selection_head_on_empty_line(cx)
16160 && self.has_blame_entries(cx)
16161 }
16162
16163 fn has_blame_entries(&self, cx: &App) -> bool {
16164 self.blame()
16165 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16166 }
16167
16168 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16169 let cursor_anchor = self.selections.newest_anchor().head();
16170
16171 let snapshot = self.buffer.read(cx).snapshot(cx);
16172 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16173
16174 snapshot.line_len(buffer_row) == 0
16175 }
16176
16177 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16178 let buffer_and_selection = maybe!({
16179 let selection = self.selections.newest::<Point>(cx);
16180 let selection_range = selection.range();
16181
16182 let multi_buffer = self.buffer().read(cx);
16183 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16184 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16185
16186 let (buffer, range, _) = if selection.reversed {
16187 buffer_ranges.first()
16188 } else {
16189 buffer_ranges.last()
16190 }?;
16191
16192 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16193 ..text::ToPoint::to_point(&range.end, &buffer).row;
16194 Some((
16195 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16196 selection,
16197 ))
16198 });
16199
16200 let Some((buffer, selection)) = buffer_and_selection else {
16201 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16202 };
16203
16204 let Some(project) = self.project.as_ref() else {
16205 return Task::ready(Err(anyhow!("editor does not have project")));
16206 };
16207
16208 project.update(cx, |project, cx| {
16209 project.get_permalink_to_line(&buffer, selection, cx)
16210 })
16211 }
16212
16213 pub fn copy_permalink_to_line(
16214 &mut self,
16215 _: &CopyPermalinkToLine,
16216 window: &mut Window,
16217 cx: &mut Context<Self>,
16218 ) {
16219 let permalink_task = self.get_permalink_to_line(cx);
16220 let workspace = self.workspace();
16221
16222 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16223 Ok(permalink) => {
16224 cx.update(|_, cx| {
16225 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16226 })
16227 .ok();
16228 }
16229 Err(err) => {
16230 let message = format!("Failed to copy permalink: {err}");
16231
16232 Err::<(), anyhow::Error>(err).log_err();
16233
16234 if let Some(workspace) = workspace {
16235 workspace
16236 .update_in(cx, |workspace, _, cx| {
16237 struct CopyPermalinkToLine;
16238
16239 workspace.show_toast(
16240 Toast::new(
16241 NotificationId::unique::<CopyPermalinkToLine>(),
16242 message,
16243 ),
16244 cx,
16245 )
16246 })
16247 .ok();
16248 }
16249 }
16250 })
16251 .detach();
16252 }
16253
16254 pub fn copy_file_location(
16255 &mut self,
16256 _: &CopyFileLocation,
16257 _: &mut Window,
16258 cx: &mut Context<Self>,
16259 ) {
16260 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16261 if let Some(file) = self.target_file(cx) {
16262 if let Some(path) = file.path().to_str() {
16263 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16264 }
16265 }
16266 }
16267
16268 pub fn open_permalink_to_line(
16269 &mut self,
16270 _: &OpenPermalinkToLine,
16271 window: &mut Window,
16272 cx: &mut Context<Self>,
16273 ) {
16274 let permalink_task = self.get_permalink_to_line(cx);
16275 let workspace = self.workspace();
16276
16277 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16278 Ok(permalink) => {
16279 cx.update(|_, cx| {
16280 cx.open_url(permalink.as_ref());
16281 })
16282 .ok();
16283 }
16284 Err(err) => {
16285 let message = format!("Failed to open permalink: {err}");
16286
16287 Err::<(), anyhow::Error>(err).log_err();
16288
16289 if let Some(workspace) = workspace {
16290 workspace
16291 .update(cx, |workspace, cx| {
16292 struct OpenPermalinkToLine;
16293
16294 workspace.show_toast(
16295 Toast::new(
16296 NotificationId::unique::<OpenPermalinkToLine>(),
16297 message,
16298 ),
16299 cx,
16300 )
16301 })
16302 .ok();
16303 }
16304 }
16305 })
16306 .detach();
16307 }
16308
16309 pub fn insert_uuid_v4(
16310 &mut self,
16311 _: &InsertUuidV4,
16312 window: &mut Window,
16313 cx: &mut Context<Self>,
16314 ) {
16315 self.insert_uuid(UuidVersion::V4, window, cx);
16316 }
16317
16318 pub fn insert_uuid_v7(
16319 &mut self,
16320 _: &InsertUuidV7,
16321 window: &mut Window,
16322 cx: &mut Context<Self>,
16323 ) {
16324 self.insert_uuid(UuidVersion::V7, window, cx);
16325 }
16326
16327 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16328 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16329 self.transact(window, cx, |this, window, cx| {
16330 let edits = this
16331 .selections
16332 .all::<Point>(cx)
16333 .into_iter()
16334 .map(|selection| {
16335 let uuid = match version {
16336 UuidVersion::V4 => uuid::Uuid::new_v4(),
16337 UuidVersion::V7 => uuid::Uuid::now_v7(),
16338 };
16339
16340 (selection.range(), uuid.to_string())
16341 });
16342 this.edit(edits, cx);
16343 this.refresh_inline_completion(true, false, window, cx);
16344 });
16345 }
16346
16347 pub fn open_selections_in_multibuffer(
16348 &mut self,
16349 _: &OpenSelectionsInMultibuffer,
16350 window: &mut Window,
16351 cx: &mut Context<Self>,
16352 ) {
16353 let multibuffer = self.buffer.read(cx);
16354
16355 let Some(buffer) = multibuffer.as_singleton() else {
16356 return;
16357 };
16358
16359 let Some(workspace) = self.workspace() else {
16360 return;
16361 };
16362
16363 let locations = self
16364 .selections
16365 .disjoint_anchors()
16366 .iter()
16367 .map(|range| Location {
16368 buffer: buffer.clone(),
16369 range: range.start.text_anchor..range.end.text_anchor,
16370 })
16371 .collect::<Vec<_>>();
16372
16373 let title = multibuffer.title(cx).to_string();
16374
16375 cx.spawn_in(window, async move |_, cx| {
16376 workspace.update_in(cx, |workspace, window, cx| {
16377 Self::open_locations_in_multibuffer(
16378 workspace,
16379 locations,
16380 format!("Selections for '{title}'"),
16381 false,
16382 MultibufferSelectionMode::All,
16383 window,
16384 cx,
16385 );
16386 })
16387 })
16388 .detach();
16389 }
16390
16391 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16392 /// last highlight added will be used.
16393 ///
16394 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16395 pub fn highlight_rows<T: 'static>(
16396 &mut self,
16397 range: Range<Anchor>,
16398 color: Hsla,
16399 should_autoscroll: bool,
16400 cx: &mut Context<Self>,
16401 ) {
16402 let snapshot = self.buffer().read(cx).snapshot(cx);
16403 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16404 let ix = row_highlights.binary_search_by(|highlight| {
16405 Ordering::Equal
16406 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16407 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16408 });
16409
16410 if let Err(mut ix) = ix {
16411 let index = post_inc(&mut self.highlight_order);
16412
16413 // If this range intersects with the preceding highlight, then merge it with
16414 // the preceding highlight. Otherwise insert a new highlight.
16415 let mut merged = false;
16416 if ix > 0 {
16417 let prev_highlight = &mut row_highlights[ix - 1];
16418 if prev_highlight
16419 .range
16420 .end
16421 .cmp(&range.start, &snapshot)
16422 .is_ge()
16423 {
16424 ix -= 1;
16425 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16426 prev_highlight.range.end = range.end;
16427 }
16428 merged = true;
16429 prev_highlight.index = index;
16430 prev_highlight.color = color;
16431 prev_highlight.should_autoscroll = should_autoscroll;
16432 }
16433 }
16434
16435 if !merged {
16436 row_highlights.insert(
16437 ix,
16438 RowHighlight {
16439 range: range.clone(),
16440 index,
16441 color,
16442 should_autoscroll,
16443 },
16444 );
16445 }
16446
16447 // If any of the following highlights intersect with this one, merge them.
16448 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16449 let highlight = &row_highlights[ix];
16450 if next_highlight
16451 .range
16452 .start
16453 .cmp(&highlight.range.end, &snapshot)
16454 .is_le()
16455 {
16456 if next_highlight
16457 .range
16458 .end
16459 .cmp(&highlight.range.end, &snapshot)
16460 .is_gt()
16461 {
16462 row_highlights[ix].range.end = next_highlight.range.end;
16463 }
16464 row_highlights.remove(ix + 1);
16465 } else {
16466 break;
16467 }
16468 }
16469 }
16470 }
16471
16472 /// Remove any highlighted row ranges of the given type that intersect the
16473 /// given ranges.
16474 pub fn remove_highlighted_rows<T: 'static>(
16475 &mut self,
16476 ranges_to_remove: Vec<Range<Anchor>>,
16477 cx: &mut Context<Self>,
16478 ) {
16479 let snapshot = self.buffer().read(cx).snapshot(cx);
16480 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16481 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16482 row_highlights.retain(|highlight| {
16483 while let Some(range_to_remove) = ranges_to_remove.peek() {
16484 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16485 Ordering::Less | Ordering::Equal => {
16486 ranges_to_remove.next();
16487 }
16488 Ordering::Greater => {
16489 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16490 Ordering::Less | Ordering::Equal => {
16491 return false;
16492 }
16493 Ordering::Greater => break,
16494 }
16495 }
16496 }
16497 }
16498
16499 true
16500 })
16501 }
16502
16503 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16504 pub fn clear_row_highlights<T: 'static>(&mut self) {
16505 self.highlighted_rows.remove(&TypeId::of::<T>());
16506 }
16507
16508 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16509 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16510 self.highlighted_rows
16511 .get(&TypeId::of::<T>())
16512 .map_or(&[] as &[_], |vec| vec.as_slice())
16513 .iter()
16514 .map(|highlight| (highlight.range.clone(), highlight.color))
16515 }
16516
16517 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16518 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16519 /// Allows to ignore certain kinds of highlights.
16520 pub fn highlighted_display_rows(
16521 &self,
16522 window: &mut Window,
16523 cx: &mut App,
16524 ) -> BTreeMap<DisplayRow, LineHighlight> {
16525 let snapshot = self.snapshot(window, cx);
16526 let mut used_highlight_orders = HashMap::default();
16527 self.highlighted_rows
16528 .iter()
16529 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16530 .fold(
16531 BTreeMap::<DisplayRow, LineHighlight>::new(),
16532 |mut unique_rows, highlight| {
16533 let start = highlight.range.start.to_display_point(&snapshot);
16534 let end = highlight.range.end.to_display_point(&snapshot);
16535 let start_row = start.row().0;
16536 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16537 && end.column() == 0
16538 {
16539 end.row().0.saturating_sub(1)
16540 } else {
16541 end.row().0
16542 };
16543 for row in start_row..=end_row {
16544 let used_index =
16545 used_highlight_orders.entry(row).or_insert(highlight.index);
16546 if highlight.index >= *used_index {
16547 *used_index = highlight.index;
16548 unique_rows.insert(DisplayRow(row), highlight.color.into());
16549 }
16550 }
16551 unique_rows
16552 },
16553 )
16554 }
16555
16556 pub fn highlighted_display_row_for_autoscroll(
16557 &self,
16558 snapshot: &DisplaySnapshot,
16559 ) -> Option<DisplayRow> {
16560 self.highlighted_rows
16561 .values()
16562 .flat_map(|highlighted_rows| highlighted_rows.iter())
16563 .filter_map(|highlight| {
16564 if highlight.should_autoscroll {
16565 Some(highlight.range.start.to_display_point(snapshot).row())
16566 } else {
16567 None
16568 }
16569 })
16570 .min()
16571 }
16572
16573 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16574 self.highlight_background::<SearchWithinRange>(
16575 ranges,
16576 |colors| colors.editor_document_highlight_read_background,
16577 cx,
16578 )
16579 }
16580
16581 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16582 self.breadcrumb_header = Some(new_header);
16583 }
16584
16585 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16586 self.clear_background_highlights::<SearchWithinRange>(cx);
16587 }
16588
16589 pub fn highlight_background<T: 'static>(
16590 &mut self,
16591 ranges: &[Range<Anchor>],
16592 color_fetcher: fn(&ThemeColors) -> Hsla,
16593 cx: &mut Context<Self>,
16594 ) {
16595 self.background_highlights
16596 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16597 self.scrollbar_marker_state.dirty = true;
16598 cx.notify();
16599 }
16600
16601 pub fn clear_background_highlights<T: 'static>(
16602 &mut self,
16603 cx: &mut Context<Self>,
16604 ) -> Option<BackgroundHighlight> {
16605 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16606 if !text_highlights.1.is_empty() {
16607 self.scrollbar_marker_state.dirty = true;
16608 cx.notify();
16609 }
16610 Some(text_highlights)
16611 }
16612
16613 pub fn highlight_gutter<T: 'static>(
16614 &mut self,
16615 ranges: &[Range<Anchor>],
16616 color_fetcher: fn(&App) -> Hsla,
16617 cx: &mut Context<Self>,
16618 ) {
16619 self.gutter_highlights
16620 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16621 cx.notify();
16622 }
16623
16624 pub fn clear_gutter_highlights<T: 'static>(
16625 &mut self,
16626 cx: &mut Context<Self>,
16627 ) -> Option<GutterHighlight> {
16628 cx.notify();
16629 self.gutter_highlights.remove(&TypeId::of::<T>())
16630 }
16631
16632 #[cfg(feature = "test-support")]
16633 pub fn all_text_background_highlights(
16634 &self,
16635 window: &mut Window,
16636 cx: &mut Context<Self>,
16637 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16638 let snapshot = self.snapshot(window, cx);
16639 let buffer = &snapshot.buffer_snapshot;
16640 let start = buffer.anchor_before(0);
16641 let end = buffer.anchor_after(buffer.len());
16642 let theme = cx.theme().colors();
16643 self.background_highlights_in_range(start..end, &snapshot, theme)
16644 }
16645
16646 #[cfg(feature = "test-support")]
16647 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16648 let snapshot = self.buffer().read(cx).snapshot(cx);
16649
16650 let highlights = self
16651 .background_highlights
16652 .get(&TypeId::of::<items::BufferSearchHighlights>());
16653
16654 if let Some((_color, ranges)) = highlights {
16655 ranges
16656 .iter()
16657 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16658 .collect_vec()
16659 } else {
16660 vec![]
16661 }
16662 }
16663
16664 fn document_highlights_for_position<'a>(
16665 &'a self,
16666 position: Anchor,
16667 buffer: &'a MultiBufferSnapshot,
16668 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16669 let read_highlights = self
16670 .background_highlights
16671 .get(&TypeId::of::<DocumentHighlightRead>())
16672 .map(|h| &h.1);
16673 let write_highlights = self
16674 .background_highlights
16675 .get(&TypeId::of::<DocumentHighlightWrite>())
16676 .map(|h| &h.1);
16677 let left_position = position.bias_left(buffer);
16678 let right_position = position.bias_right(buffer);
16679 read_highlights
16680 .into_iter()
16681 .chain(write_highlights)
16682 .flat_map(move |ranges| {
16683 let start_ix = match ranges.binary_search_by(|probe| {
16684 let cmp = probe.end.cmp(&left_position, buffer);
16685 if cmp.is_ge() {
16686 Ordering::Greater
16687 } else {
16688 Ordering::Less
16689 }
16690 }) {
16691 Ok(i) | Err(i) => i,
16692 };
16693
16694 ranges[start_ix..]
16695 .iter()
16696 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16697 })
16698 }
16699
16700 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16701 self.background_highlights
16702 .get(&TypeId::of::<T>())
16703 .map_or(false, |(_, highlights)| !highlights.is_empty())
16704 }
16705
16706 pub fn background_highlights_in_range(
16707 &self,
16708 search_range: Range<Anchor>,
16709 display_snapshot: &DisplaySnapshot,
16710 theme: &ThemeColors,
16711 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16712 let mut results = Vec::new();
16713 for (color_fetcher, ranges) in self.background_highlights.values() {
16714 let color = color_fetcher(theme);
16715 let start_ix = match ranges.binary_search_by(|probe| {
16716 let cmp = probe
16717 .end
16718 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16719 if cmp.is_gt() {
16720 Ordering::Greater
16721 } else {
16722 Ordering::Less
16723 }
16724 }) {
16725 Ok(i) | Err(i) => i,
16726 };
16727 for range in &ranges[start_ix..] {
16728 if range
16729 .start
16730 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16731 .is_ge()
16732 {
16733 break;
16734 }
16735
16736 let start = range.start.to_display_point(display_snapshot);
16737 let end = range.end.to_display_point(display_snapshot);
16738 results.push((start..end, color))
16739 }
16740 }
16741 results
16742 }
16743
16744 pub fn background_highlight_row_ranges<T: 'static>(
16745 &self,
16746 search_range: Range<Anchor>,
16747 display_snapshot: &DisplaySnapshot,
16748 count: usize,
16749 ) -> Vec<RangeInclusive<DisplayPoint>> {
16750 let mut results = Vec::new();
16751 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16752 return vec![];
16753 };
16754
16755 let start_ix = match ranges.binary_search_by(|probe| {
16756 let cmp = probe
16757 .end
16758 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16759 if cmp.is_gt() {
16760 Ordering::Greater
16761 } else {
16762 Ordering::Less
16763 }
16764 }) {
16765 Ok(i) | Err(i) => i,
16766 };
16767 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16768 if let (Some(start_display), Some(end_display)) = (start, end) {
16769 results.push(
16770 start_display.to_display_point(display_snapshot)
16771 ..=end_display.to_display_point(display_snapshot),
16772 );
16773 }
16774 };
16775 let mut start_row: Option<Point> = None;
16776 let mut end_row: Option<Point> = None;
16777 if ranges.len() > count {
16778 return Vec::new();
16779 }
16780 for range in &ranges[start_ix..] {
16781 if range
16782 .start
16783 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16784 .is_ge()
16785 {
16786 break;
16787 }
16788 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16789 if let Some(current_row) = &end_row {
16790 if end.row == current_row.row {
16791 continue;
16792 }
16793 }
16794 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16795 if start_row.is_none() {
16796 assert_eq!(end_row, None);
16797 start_row = Some(start);
16798 end_row = Some(end);
16799 continue;
16800 }
16801 if let Some(current_end) = end_row.as_mut() {
16802 if start.row > current_end.row + 1 {
16803 push_region(start_row, end_row);
16804 start_row = Some(start);
16805 end_row = Some(end);
16806 } else {
16807 // Merge two hunks.
16808 *current_end = end;
16809 }
16810 } else {
16811 unreachable!();
16812 }
16813 }
16814 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16815 push_region(start_row, end_row);
16816 results
16817 }
16818
16819 pub fn gutter_highlights_in_range(
16820 &self,
16821 search_range: Range<Anchor>,
16822 display_snapshot: &DisplaySnapshot,
16823 cx: &App,
16824 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16825 let mut results = Vec::new();
16826 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16827 let color = color_fetcher(cx);
16828 let start_ix = match ranges.binary_search_by(|probe| {
16829 let cmp = probe
16830 .end
16831 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16832 if cmp.is_gt() {
16833 Ordering::Greater
16834 } else {
16835 Ordering::Less
16836 }
16837 }) {
16838 Ok(i) | Err(i) => i,
16839 };
16840 for range in &ranges[start_ix..] {
16841 if range
16842 .start
16843 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16844 .is_ge()
16845 {
16846 break;
16847 }
16848
16849 let start = range.start.to_display_point(display_snapshot);
16850 let end = range.end.to_display_point(display_snapshot);
16851 results.push((start..end, color))
16852 }
16853 }
16854 results
16855 }
16856
16857 /// Get the text ranges corresponding to the redaction query
16858 pub fn redacted_ranges(
16859 &self,
16860 search_range: Range<Anchor>,
16861 display_snapshot: &DisplaySnapshot,
16862 cx: &App,
16863 ) -> Vec<Range<DisplayPoint>> {
16864 display_snapshot
16865 .buffer_snapshot
16866 .redacted_ranges(search_range, |file| {
16867 if let Some(file) = file {
16868 file.is_private()
16869 && EditorSettings::get(
16870 Some(SettingsLocation {
16871 worktree_id: file.worktree_id(cx),
16872 path: file.path().as_ref(),
16873 }),
16874 cx,
16875 )
16876 .redact_private_values
16877 } else {
16878 false
16879 }
16880 })
16881 .map(|range| {
16882 range.start.to_display_point(display_snapshot)
16883 ..range.end.to_display_point(display_snapshot)
16884 })
16885 .collect()
16886 }
16887
16888 pub fn highlight_text<T: 'static>(
16889 &mut self,
16890 ranges: Vec<Range<Anchor>>,
16891 style: HighlightStyle,
16892 cx: &mut Context<Self>,
16893 ) {
16894 self.display_map.update(cx, |map, _| {
16895 map.highlight_text(TypeId::of::<T>(), ranges, style)
16896 });
16897 cx.notify();
16898 }
16899
16900 pub(crate) fn highlight_inlays<T: 'static>(
16901 &mut self,
16902 highlights: Vec<InlayHighlight>,
16903 style: HighlightStyle,
16904 cx: &mut Context<Self>,
16905 ) {
16906 self.display_map.update(cx, |map, _| {
16907 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16908 });
16909 cx.notify();
16910 }
16911
16912 pub fn text_highlights<'a, T: 'static>(
16913 &'a self,
16914 cx: &'a App,
16915 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16916 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16917 }
16918
16919 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16920 let cleared = self
16921 .display_map
16922 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16923 if cleared {
16924 cx.notify();
16925 }
16926 }
16927
16928 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16929 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16930 && self.focus_handle.is_focused(window)
16931 }
16932
16933 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16934 self.show_cursor_when_unfocused = is_enabled;
16935 cx.notify();
16936 }
16937
16938 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16939 cx.notify();
16940 }
16941
16942 fn on_buffer_event(
16943 &mut self,
16944 multibuffer: &Entity<MultiBuffer>,
16945 event: &multi_buffer::Event,
16946 window: &mut Window,
16947 cx: &mut Context<Self>,
16948 ) {
16949 match event {
16950 multi_buffer::Event::Edited {
16951 singleton_buffer_edited,
16952 edited_buffer: buffer_edited,
16953 } => {
16954 self.scrollbar_marker_state.dirty = true;
16955 self.active_indent_guides_state.dirty = true;
16956 self.refresh_active_diagnostics(cx);
16957 self.refresh_code_actions(window, cx);
16958 if self.has_active_inline_completion() {
16959 self.update_visible_inline_completion(window, cx);
16960 }
16961 if let Some(buffer) = buffer_edited {
16962 let buffer_id = buffer.read(cx).remote_id();
16963 if !self.registered_buffers.contains_key(&buffer_id) {
16964 if let Some(project) = self.project.as_ref() {
16965 project.update(cx, |project, cx| {
16966 self.registered_buffers.insert(
16967 buffer_id,
16968 project.register_buffer_with_language_servers(&buffer, cx),
16969 );
16970 })
16971 }
16972 }
16973 }
16974 cx.emit(EditorEvent::BufferEdited);
16975 cx.emit(SearchEvent::MatchesInvalidated);
16976 if *singleton_buffer_edited {
16977 if let Some(project) = &self.project {
16978 #[allow(clippy::mutable_key_type)]
16979 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16980 multibuffer
16981 .all_buffers()
16982 .into_iter()
16983 .filter_map(|buffer| {
16984 buffer.update(cx, |buffer, cx| {
16985 let language = buffer.language()?;
16986 let should_discard = project.update(cx, |project, cx| {
16987 project.is_local()
16988 && !project.has_language_servers_for(buffer, cx)
16989 });
16990 should_discard.not().then_some(language.clone())
16991 })
16992 })
16993 .collect::<HashSet<_>>()
16994 });
16995 if !languages_affected.is_empty() {
16996 self.refresh_inlay_hints(
16997 InlayHintRefreshReason::BufferEdited(languages_affected),
16998 cx,
16999 );
17000 }
17001 }
17002 }
17003
17004 let Some(project) = &self.project else { return };
17005 let (telemetry, is_via_ssh) = {
17006 let project = project.read(cx);
17007 let telemetry = project.client().telemetry().clone();
17008 let is_via_ssh = project.is_via_ssh();
17009 (telemetry, is_via_ssh)
17010 };
17011 refresh_linked_ranges(self, window, cx);
17012 telemetry.log_edit_event("editor", is_via_ssh);
17013 }
17014 multi_buffer::Event::ExcerptsAdded {
17015 buffer,
17016 predecessor,
17017 excerpts,
17018 } => {
17019 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17020 let buffer_id = buffer.read(cx).remote_id();
17021 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17022 if let Some(project) = &self.project {
17023 get_uncommitted_diff_for_buffer(
17024 project,
17025 [buffer.clone()],
17026 self.buffer.clone(),
17027 cx,
17028 )
17029 .detach();
17030 }
17031 }
17032 cx.emit(EditorEvent::ExcerptsAdded {
17033 buffer: buffer.clone(),
17034 predecessor: *predecessor,
17035 excerpts: excerpts.clone(),
17036 });
17037 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17038 }
17039 multi_buffer::Event::ExcerptsRemoved { ids } => {
17040 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17041 let buffer = self.buffer.read(cx);
17042 self.registered_buffers
17043 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17044 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17045 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17046 }
17047 multi_buffer::Event::ExcerptsEdited {
17048 excerpt_ids,
17049 buffer_ids,
17050 } => {
17051 self.display_map.update(cx, |map, cx| {
17052 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17053 });
17054 cx.emit(EditorEvent::ExcerptsEdited {
17055 ids: excerpt_ids.clone(),
17056 })
17057 }
17058 multi_buffer::Event::ExcerptsExpanded { ids } => {
17059 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17060 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17061 }
17062 multi_buffer::Event::Reparsed(buffer_id) => {
17063 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17064 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17065
17066 cx.emit(EditorEvent::Reparsed(*buffer_id));
17067 }
17068 multi_buffer::Event::DiffHunksToggled => {
17069 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17070 }
17071 multi_buffer::Event::LanguageChanged(buffer_id) => {
17072 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17073 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17074 cx.emit(EditorEvent::Reparsed(*buffer_id));
17075 cx.notify();
17076 }
17077 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17078 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17079 multi_buffer::Event::FileHandleChanged
17080 | multi_buffer::Event::Reloaded
17081 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17082 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17083 multi_buffer::Event::DiagnosticsUpdated => {
17084 self.refresh_active_diagnostics(cx);
17085 self.refresh_inline_diagnostics(true, window, cx);
17086 self.scrollbar_marker_state.dirty = true;
17087 cx.notify();
17088 }
17089 _ => {}
17090 };
17091 }
17092
17093 fn on_display_map_changed(
17094 &mut self,
17095 _: Entity<DisplayMap>,
17096 _: &mut Window,
17097 cx: &mut Context<Self>,
17098 ) {
17099 cx.notify();
17100 }
17101
17102 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17103 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17104 self.update_edit_prediction_settings(cx);
17105 self.refresh_inline_completion(true, false, window, cx);
17106 self.refresh_inlay_hints(
17107 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17108 self.selections.newest_anchor().head(),
17109 &self.buffer.read(cx).snapshot(cx),
17110 cx,
17111 )),
17112 cx,
17113 );
17114
17115 let old_cursor_shape = self.cursor_shape;
17116
17117 {
17118 let editor_settings = EditorSettings::get_global(cx);
17119 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17120 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17121 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17122 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17123 }
17124
17125 if old_cursor_shape != self.cursor_shape {
17126 cx.emit(EditorEvent::CursorShapeChanged);
17127 }
17128
17129 let project_settings = ProjectSettings::get_global(cx);
17130 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17131
17132 if self.mode == EditorMode::Full {
17133 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17134 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17135 if self.show_inline_diagnostics != show_inline_diagnostics {
17136 self.show_inline_diagnostics = show_inline_diagnostics;
17137 self.refresh_inline_diagnostics(false, window, cx);
17138 }
17139
17140 if self.git_blame_inline_enabled != inline_blame_enabled {
17141 self.toggle_git_blame_inline_internal(false, window, cx);
17142 }
17143 }
17144
17145 cx.notify();
17146 }
17147
17148 pub fn set_searchable(&mut self, searchable: bool) {
17149 self.searchable = searchable;
17150 }
17151
17152 pub fn searchable(&self) -> bool {
17153 self.searchable
17154 }
17155
17156 fn open_proposed_changes_editor(
17157 &mut self,
17158 _: &OpenProposedChangesEditor,
17159 window: &mut Window,
17160 cx: &mut Context<Self>,
17161 ) {
17162 let Some(workspace) = self.workspace() else {
17163 cx.propagate();
17164 return;
17165 };
17166
17167 let selections = self.selections.all::<usize>(cx);
17168 let multi_buffer = self.buffer.read(cx);
17169 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17170 let mut new_selections_by_buffer = HashMap::default();
17171 for selection in selections {
17172 for (buffer, range, _) in
17173 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17174 {
17175 let mut range = range.to_point(buffer);
17176 range.start.column = 0;
17177 range.end.column = buffer.line_len(range.end.row);
17178 new_selections_by_buffer
17179 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17180 .or_insert(Vec::new())
17181 .push(range)
17182 }
17183 }
17184
17185 let proposed_changes_buffers = new_selections_by_buffer
17186 .into_iter()
17187 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17188 .collect::<Vec<_>>();
17189 let proposed_changes_editor = cx.new(|cx| {
17190 ProposedChangesEditor::new(
17191 "Proposed changes",
17192 proposed_changes_buffers,
17193 self.project.clone(),
17194 window,
17195 cx,
17196 )
17197 });
17198
17199 window.defer(cx, move |window, cx| {
17200 workspace.update(cx, |workspace, cx| {
17201 workspace.active_pane().update(cx, |pane, cx| {
17202 pane.add_item(
17203 Box::new(proposed_changes_editor),
17204 true,
17205 true,
17206 None,
17207 window,
17208 cx,
17209 );
17210 });
17211 });
17212 });
17213 }
17214
17215 pub fn open_excerpts_in_split(
17216 &mut self,
17217 _: &OpenExcerptsSplit,
17218 window: &mut Window,
17219 cx: &mut Context<Self>,
17220 ) {
17221 self.open_excerpts_common(None, true, window, cx)
17222 }
17223
17224 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17225 self.open_excerpts_common(None, false, window, cx)
17226 }
17227
17228 fn open_excerpts_common(
17229 &mut self,
17230 jump_data: Option<JumpData>,
17231 split: bool,
17232 window: &mut Window,
17233 cx: &mut Context<Self>,
17234 ) {
17235 let Some(workspace) = self.workspace() else {
17236 cx.propagate();
17237 return;
17238 };
17239
17240 if self.buffer.read(cx).is_singleton() {
17241 cx.propagate();
17242 return;
17243 }
17244
17245 let mut new_selections_by_buffer = HashMap::default();
17246 match &jump_data {
17247 Some(JumpData::MultiBufferPoint {
17248 excerpt_id,
17249 position,
17250 anchor,
17251 line_offset_from_top,
17252 }) => {
17253 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17254 if let Some(buffer) = multi_buffer_snapshot
17255 .buffer_id_for_excerpt(*excerpt_id)
17256 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17257 {
17258 let buffer_snapshot = buffer.read(cx).snapshot();
17259 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17260 language::ToPoint::to_point(anchor, &buffer_snapshot)
17261 } else {
17262 buffer_snapshot.clip_point(*position, Bias::Left)
17263 };
17264 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17265 new_selections_by_buffer.insert(
17266 buffer,
17267 (
17268 vec![jump_to_offset..jump_to_offset],
17269 Some(*line_offset_from_top),
17270 ),
17271 );
17272 }
17273 }
17274 Some(JumpData::MultiBufferRow {
17275 row,
17276 line_offset_from_top,
17277 }) => {
17278 let point = MultiBufferPoint::new(row.0, 0);
17279 if let Some((buffer, buffer_point, _)) =
17280 self.buffer.read(cx).point_to_buffer_point(point, cx)
17281 {
17282 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17283 new_selections_by_buffer
17284 .entry(buffer)
17285 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17286 .0
17287 .push(buffer_offset..buffer_offset)
17288 }
17289 }
17290 None => {
17291 let selections = self.selections.all::<usize>(cx);
17292 let multi_buffer = self.buffer.read(cx);
17293 for selection in selections {
17294 for (snapshot, range, _, anchor) in multi_buffer
17295 .snapshot(cx)
17296 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17297 {
17298 if let Some(anchor) = anchor {
17299 // selection is in a deleted hunk
17300 let Some(buffer_id) = anchor.buffer_id else {
17301 continue;
17302 };
17303 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17304 continue;
17305 };
17306 let offset = text::ToOffset::to_offset(
17307 &anchor.text_anchor,
17308 &buffer_handle.read(cx).snapshot(),
17309 );
17310 let range = offset..offset;
17311 new_selections_by_buffer
17312 .entry(buffer_handle)
17313 .or_insert((Vec::new(), None))
17314 .0
17315 .push(range)
17316 } else {
17317 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17318 else {
17319 continue;
17320 };
17321 new_selections_by_buffer
17322 .entry(buffer_handle)
17323 .or_insert((Vec::new(), None))
17324 .0
17325 .push(range)
17326 }
17327 }
17328 }
17329 }
17330 }
17331
17332 new_selections_by_buffer
17333 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17334
17335 if new_selections_by_buffer.is_empty() {
17336 return;
17337 }
17338
17339 // We defer the pane interaction because we ourselves are a workspace item
17340 // and activating a new item causes the pane to call a method on us reentrantly,
17341 // which panics if we're on the stack.
17342 window.defer(cx, move |window, cx| {
17343 workspace.update(cx, |workspace, cx| {
17344 let pane = if split {
17345 workspace.adjacent_pane(window, cx)
17346 } else {
17347 workspace.active_pane().clone()
17348 };
17349
17350 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17351 let editor = buffer
17352 .read(cx)
17353 .file()
17354 .is_none()
17355 .then(|| {
17356 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17357 // so `workspace.open_project_item` will never find them, always opening a new editor.
17358 // Instead, we try to activate the existing editor in the pane first.
17359 let (editor, pane_item_index) =
17360 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17361 let editor = item.downcast::<Editor>()?;
17362 let singleton_buffer =
17363 editor.read(cx).buffer().read(cx).as_singleton()?;
17364 if singleton_buffer == buffer {
17365 Some((editor, i))
17366 } else {
17367 None
17368 }
17369 })?;
17370 pane.update(cx, |pane, cx| {
17371 pane.activate_item(pane_item_index, true, true, window, cx)
17372 });
17373 Some(editor)
17374 })
17375 .flatten()
17376 .unwrap_or_else(|| {
17377 workspace.open_project_item::<Self>(
17378 pane.clone(),
17379 buffer,
17380 true,
17381 true,
17382 window,
17383 cx,
17384 )
17385 });
17386
17387 editor.update(cx, |editor, cx| {
17388 let autoscroll = match scroll_offset {
17389 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17390 None => Autoscroll::newest(),
17391 };
17392 let nav_history = editor.nav_history.take();
17393 editor.change_selections(Some(autoscroll), window, cx, |s| {
17394 s.select_ranges(ranges);
17395 });
17396 editor.nav_history = nav_history;
17397 });
17398 }
17399 })
17400 });
17401 }
17402
17403 // For now, don't allow opening excerpts in buffers that aren't backed by
17404 // regular project files.
17405 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17406 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17407 }
17408
17409 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17410 let snapshot = self.buffer.read(cx).read(cx);
17411 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17412 Some(
17413 ranges
17414 .iter()
17415 .map(move |range| {
17416 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17417 })
17418 .collect(),
17419 )
17420 }
17421
17422 fn selection_replacement_ranges(
17423 &self,
17424 range: Range<OffsetUtf16>,
17425 cx: &mut App,
17426 ) -> Vec<Range<OffsetUtf16>> {
17427 let selections = self.selections.all::<OffsetUtf16>(cx);
17428 let newest_selection = selections
17429 .iter()
17430 .max_by_key(|selection| selection.id)
17431 .unwrap();
17432 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17433 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17434 let snapshot = self.buffer.read(cx).read(cx);
17435 selections
17436 .into_iter()
17437 .map(|mut selection| {
17438 selection.start.0 =
17439 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17440 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17441 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17442 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17443 })
17444 .collect()
17445 }
17446
17447 fn report_editor_event(
17448 &self,
17449 event_type: &'static str,
17450 file_extension: Option<String>,
17451 cx: &App,
17452 ) {
17453 if cfg!(any(test, feature = "test-support")) {
17454 return;
17455 }
17456
17457 let Some(project) = &self.project else { return };
17458
17459 // If None, we are in a file without an extension
17460 let file = self
17461 .buffer
17462 .read(cx)
17463 .as_singleton()
17464 .and_then(|b| b.read(cx).file());
17465 let file_extension = file_extension.or(file
17466 .as_ref()
17467 .and_then(|file| Path::new(file.file_name(cx)).extension())
17468 .and_then(|e| e.to_str())
17469 .map(|a| a.to_string()));
17470
17471 let vim_mode = cx
17472 .global::<SettingsStore>()
17473 .raw_user_settings()
17474 .get("vim_mode")
17475 == Some(&serde_json::Value::Bool(true));
17476
17477 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17478 let copilot_enabled = edit_predictions_provider
17479 == language::language_settings::EditPredictionProvider::Copilot;
17480 let copilot_enabled_for_language = self
17481 .buffer
17482 .read(cx)
17483 .language_settings(cx)
17484 .show_edit_predictions;
17485
17486 let project = project.read(cx);
17487 telemetry::event!(
17488 event_type,
17489 file_extension,
17490 vim_mode,
17491 copilot_enabled,
17492 copilot_enabled_for_language,
17493 edit_predictions_provider,
17494 is_via_ssh = project.is_via_ssh(),
17495 );
17496 }
17497
17498 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17499 /// with each line being an array of {text, highlight} objects.
17500 fn copy_highlight_json(
17501 &mut self,
17502 _: &CopyHighlightJson,
17503 window: &mut Window,
17504 cx: &mut Context<Self>,
17505 ) {
17506 #[derive(Serialize)]
17507 struct Chunk<'a> {
17508 text: String,
17509 highlight: Option<&'a str>,
17510 }
17511
17512 let snapshot = self.buffer.read(cx).snapshot(cx);
17513 let range = self
17514 .selected_text_range(false, window, cx)
17515 .and_then(|selection| {
17516 if selection.range.is_empty() {
17517 None
17518 } else {
17519 Some(selection.range)
17520 }
17521 })
17522 .unwrap_or_else(|| 0..snapshot.len());
17523
17524 let chunks = snapshot.chunks(range, true);
17525 let mut lines = Vec::new();
17526 let mut line: VecDeque<Chunk> = VecDeque::new();
17527
17528 let Some(style) = self.style.as_ref() else {
17529 return;
17530 };
17531
17532 for chunk in chunks {
17533 let highlight = chunk
17534 .syntax_highlight_id
17535 .and_then(|id| id.name(&style.syntax));
17536 let mut chunk_lines = chunk.text.split('\n').peekable();
17537 while let Some(text) = chunk_lines.next() {
17538 let mut merged_with_last_token = false;
17539 if let Some(last_token) = line.back_mut() {
17540 if last_token.highlight == highlight {
17541 last_token.text.push_str(text);
17542 merged_with_last_token = true;
17543 }
17544 }
17545
17546 if !merged_with_last_token {
17547 line.push_back(Chunk {
17548 text: text.into(),
17549 highlight,
17550 });
17551 }
17552
17553 if chunk_lines.peek().is_some() {
17554 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17555 line.pop_front();
17556 }
17557 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17558 line.pop_back();
17559 }
17560
17561 lines.push(mem::take(&mut line));
17562 }
17563 }
17564 }
17565
17566 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17567 return;
17568 };
17569 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17570 }
17571
17572 pub fn open_context_menu(
17573 &mut self,
17574 _: &OpenContextMenu,
17575 window: &mut Window,
17576 cx: &mut Context<Self>,
17577 ) {
17578 self.request_autoscroll(Autoscroll::newest(), cx);
17579 let position = self.selections.newest_display(cx).start;
17580 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17581 }
17582
17583 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17584 &self.inlay_hint_cache
17585 }
17586
17587 pub fn replay_insert_event(
17588 &mut self,
17589 text: &str,
17590 relative_utf16_range: Option<Range<isize>>,
17591 window: &mut Window,
17592 cx: &mut Context<Self>,
17593 ) {
17594 if !self.input_enabled {
17595 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17596 return;
17597 }
17598 if let Some(relative_utf16_range) = relative_utf16_range {
17599 let selections = self.selections.all::<OffsetUtf16>(cx);
17600 self.change_selections(None, window, cx, |s| {
17601 let new_ranges = selections.into_iter().map(|range| {
17602 let start = OffsetUtf16(
17603 range
17604 .head()
17605 .0
17606 .saturating_add_signed(relative_utf16_range.start),
17607 );
17608 let end = OffsetUtf16(
17609 range
17610 .head()
17611 .0
17612 .saturating_add_signed(relative_utf16_range.end),
17613 );
17614 start..end
17615 });
17616 s.select_ranges(new_ranges);
17617 });
17618 }
17619
17620 self.handle_input(text, window, cx);
17621 }
17622
17623 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17624 let Some(provider) = self.semantics_provider.as_ref() else {
17625 return false;
17626 };
17627
17628 let mut supports = false;
17629 self.buffer().update(cx, |this, cx| {
17630 this.for_each_buffer(|buffer| {
17631 supports |= provider.supports_inlay_hints(buffer, cx);
17632 });
17633 });
17634
17635 supports
17636 }
17637
17638 pub fn is_focused(&self, window: &Window) -> bool {
17639 self.focus_handle.is_focused(window)
17640 }
17641
17642 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17643 cx.emit(EditorEvent::Focused);
17644
17645 if let Some(descendant) = self
17646 .last_focused_descendant
17647 .take()
17648 .and_then(|descendant| descendant.upgrade())
17649 {
17650 window.focus(&descendant);
17651 } else {
17652 if let Some(blame) = self.blame.as_ref() {
17653 blame.update(cx, GitBlame::focus)
17654 }
17655
17656 self.blink_manager.update(cx, BlinkManager::enable);
17657 self.show_cursor_names(window, cx);
17658 self.buffer.update(cx, |buffer, cx| {
17659 buffer.finalize_last_transaction(cx);
17660 if self.leader_peer_id.is_none() {
17661 buffer.set_active_selections(
17662 &self.selections.disjoint_anchors(),
17663 self.selections.line_mode,
17664 self.cursor_shape,
17665 cx,
17666 );
17667 }
17668 });
17669 }
17670 }
17671
17672 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17673 cx.emit(EditorEvent::FocusedIn)
17674 }
17675
17676 fn handle_focus_out(
17677 &mut self,
17678 event: FocusOutEvent,
17679 _window: &mut Window,
17680 cx: &mut Context<Self>,
17681 ) {
17682 if event.blurred != self.focus_handle {
17683 self.last_focused_descendant = Some(event.blurred);
17684 }
17685 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17686 }
17687
17688 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17689 self.blink_manager.update(cx, BlinkManager::disable);
17690 self.buffer
17691 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17692
17693 if let Some(blame) = self.blame.as_ref() {
17694 blame.update(cx, GitBlame::blur)
17695 }
17696 if !self.hover_state.focused(window, cx) {
17697 hide_hover(self, cx);
17698 }
17699 if !self
17700 .context_menu
17701 .borrow()
17702 .as_ref()
17703 .is_some_and(|context_menu| context_menu.focused(window, cx))
17704 {
17705 self.hide_context_menu(window, cx);
17706 }
17707 self.discard_inline_completion(false, cx);
17708 cx.emit(EditorEvent::Blurred);
17709 cx.notify();
17710 }
17711
17712 pub fn register_action<A: Action>(
17713 &mut self,
17714 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17715 ) -> Subscription {
17716 let id = self.next_editor_action_id.post_inc();
17717 let listener = Arc::new(listener);
17718 self.editor_actions.borrow_mut().insert(
17719 id,
17720 Box::new(move |window, _| {
17721 let listener = listener.clone();
17722 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17723 let action = action.downcast_ref().unwrap();
17724 if phase == DispatchPhase::Bubble {
17725 listener(action, window, cx)
17726 }
17727 })
17728 }),
17729 );
17730
17731 let editor_actions = self.editor_actions.clone();
17732 Subscription::new(move || {
17733 editor_actions.borrow_mut().remove(&id);
17734 })
17735 }
17736
17737 pub fn file_header_size(&self) -> u32 {
17738 FILE_HEADER_HEIGHT
17739 }
17740
17741 pub fn restore(
17742 &mut self,
17743 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17744 window: &mut Window,
17745 cx: &mut Context<Self>,
17746 ) {
17747 let workspace = self.workspace();
17748 let project = self.project.as_ref();
17749 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17750 let mut tasks = Vec::new();
17751 for (buffer_id, changes) in revert_changes {
17752 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17753 buffer.update(cx, |buffer, cx| {
17754 buffer.edit(
17755 changes
17756 .into_iter()
17757 .map(|(range, text)| (range, text.to_string())),
17758 None,
17759 cx,
17760 );
17761 });
17762
17763 if let Some(project) =
17764 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17765 {
17766 project.update(cx, |project, cx| {
17767 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17768 })
17769 }
17770 }
17771 }
17772 tasks
17773 });
17774 cx.spawn_in(window, async move |_, cx| {
17775 for (buffer, task) in save_tasks {
17776 let result = task.await;
17777 if result.is_err() {
17778 let Some(path) = buffer
17779 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17780 .ok()
17781 else {
17782 continue;
17783 };
17784 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17785 let Some(task) = cx
17786 .update_window_entity(&workspace, |workspace, window, cx| {
17787 workspace
17788 .open_path_preview(path, None, false, false, false, window, cx)
17789 })
17790 .ok()
17791 else {
17792 continue;
17793 };
17794 task.await.log_err();
17795 }
17796 }
17797 }
17798 })
17799 .detach();
17800 self.change_selections(None, window, cx, |selections| selections.refresh());
17801 }
17802
17803 pub fn to_pixel_point(
17804 &self,
17805 source: multi_buffer::Anchor,
17806 editor_snapshot: &EditorSnapshot,
17807 window: &mut Window,
17808 ) -> Option<gpui::Point<Pixels>> {
17809 let source_point = source.to_display_point(editor_snapshot);
17810 self.display_to_pixel_point(source_point, editor_snapshot, window)
17811 }
17812
17813 pub fn display_to_pixel_point(
17814 &self,
17815 source: DisplayPoint,
17816 editor_snapshot: &EditorSnapshot,
17817 window: &mut Window,
17818 ) -> Option<gpui::Point<Pixels>> {
17819 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17820 let text_layout_details = self.text_layout_details(window);
17821 let scroll_top = text_layout_details
17822 .scroll_anchor
17823 .scroll_position(editor_snapshot)
17824 .y;
17825
17826 if source.row().as_f32() < scroll_top.floor() {
17827 return None;
17828 }
17829 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17830 let source_y = line_height * (source.row().as_f32() - scroll_top);
17831 Some(gpui::Point::new(source_x, source_y))
17832 }
17833
17834 pub fn has_visible_completions_menu(&self) -> bool {
17835 !self.edit_prediction_preview_is_active()
17836 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17837 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17838 })
17839 }
17840
17841 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17842 self.addons
17843 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17844 }
17845
17846 pub fn unregister_addon<T: Addon>(&mut self) {
17847 self.addons.remove(&std::any::TypeId::of::<T>());
17848 }
17849
17850 pub fn addon<T: Addon>(&self) -> Option<&T> {
17851 let type_id = std::any::TypeId::of::<T>();
17852 self.addons
17853 .get(&type_id)
17854 .and_then(|item| item.to_any().downcast_ref::<T>())
17855 }
17856
17857 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17858 let text_layout_details = self.text_layout_details(window);
17859 let style = &text_layout_details.editor_style;
17860 let font_id = window.text_system().resolve_font(&style.text.font());
17861 let font_size = style.text.font_size.to_pixels(window.rem_size());
17862 let line_height = style.text.line_height_in_pixels(window.rem_size());
17863 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17864
17865 gpui::Size::new(em_width, line_height)
17866 }
17867
17868 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17869 self.load_diff_task.clone()
17870 }
17871
17872 fn read_metadata_from_db(
17873 &mut self,
17874 item_id: u64,
17875 workspace_id: WorkspaceId,
17876 window: &mut Window,
17877 cx: &mut Context<Editor>,
17878 ) {
17879 if self.is_singleton(cx)
17880 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17881 {
17882 let buffer_snapshot = OnceCell::new();
17883
17884 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17885 if !folds.is_empty() {
17886 let snapshot =
17887 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17888 self.fold_ranges(
17889 folds
17890 .into_iter()
17891 .map(|(start, end)| {
17892 snapshot.clip_offset(start, Bias::Left)
17893 ..snapshot.clip_offset(end, Bias::Right)
17894 })
17895 .collect(),
17896 false,
17897 window,
17898 cx,
17899 );
17900 }
17901 }
17902
17903 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17904 if !selections.is_empty() {
17905 let snapshot =
17906 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17907 self.change_selections(None, window, cx, |s| {
17908 s.select_ranges(selections.into_iter().map(|(start, end)| {
17909 snapshot.clip_offset(start, Bias::Left)
17910 ..snapshot.clip_offset(end, Bias::Right)
17911 }));
17912 });
17913 }
17914 };
17915 }
17916
17917 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17918 }
17919}
17920
17921fn insert_extra_newline_brackets(
17922 buffer: &MultiBufferSnapshot,
17923 range: Range<usize>,
17924 language: &language::LanguageScope,
17925) -> bool {
17926 let leading_whitespace_len = buffer
17927 .reversed_chars_at(range.start)
17928 .take_while(|c| c.is_whitespace() && *c != '\n')
17929 .map(|c| c.len_utf8())
17930 .sum::<usize>();
17931 let trailing_whitespace_len = buffer
17932 .chars_at(range.end)
17933 .take_while(|c| c.is_whitespace() && *c != '\n')
17934 .map(|c| c.len_utf8())
17935 .sum::<usize>();
17936 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17937
17938 language.brackets().any(|(pair, enabled)| {
17939 let pair_start = pair.start.trim_end();
17940 let pair_end = pair.end.trim_start();
17941
17942 enabled
17943 && pair.newline
17944 && buffer.contains_str_at(range.end, pair_end)
17945 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17946 })
17947}
17948
17949fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17950 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17951 [(buffer, range, _)] => (*buffer, range.clone()),
17952 _ => return false,
17953 };
17954 let pair = {
17955 let mut result: Option<BracketMatch> = None;
17956
17957 for pair in buffer
17958 .all_bracket_ranges(range.clone())
17959 .filter(move |pair| {
17960 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17961 })
17962 {
17963 let len = pair.close_range.end - pair.open_range.start;
17964
17965 if let Some(existing) = &result {
17966 let existing_len = existing.close_range.end - existing.open_range.start;
17967 if len > existing_len {
17968 continue;
17969 }
17970 }
17971
17972 result = Some(pair);
17973 }
17974
17975 result
17976 };
17977 let Some(pair) = pair else {
17978 return false;
17979 };
17980 pair.newline_only
17981 && buffer
17982 .chars_for_range(pair.open_range.end..range.start)
17983 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17984 .all(|c| c.is_whitespace() && c != '\n')
17985}
17986
17987fn get_uncommitted_diff_for_buffer(
17988 project: &Entity<Project>,
17989 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17990 buffer: Entity<MultiBuffer>,
17991 cx: &mut App,
17992) -> Task<()> {
17993 let mut tasks = Vec::new();
17994 project.update(cx, |project, cx| {
17995 for buffer in buffers {
17996 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
17997 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17998 }
17999 }
18000 });
18001 cx.spawn(async move |cx| {
18002 let diffs = future::join_all(tasks).await;
18003 buffer
18004 .update(cx, |buffer, cx| {
18005 for diff in diffs.into_iter().flatten() {
18006 buffer.add_diff(diff, cx);
18007 }
18008 })
18009 .ok();
18010 })
18011}
18012
18013fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18014 let tab_size = tab_size.get() as usize;
18015 let mut width = offset;
18016
18017 for ch in text.chars() {
18018 width += if ch == '\t' {
18019 tab_size - (width % tab_size)
18020 } else {
18021 1
18022 };
18023 }
18024
18025 width - offset
18026}
18027
18028#[cfg(test)]
18029mod tests {
18030 use super::*;
18031
18032 #[test]
18033 fn test_string_size_with_expanded_tabs() {
18034 let nz = |val| NonZeroU32::new(val).unwrap();
18035 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18036 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18037 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18038 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18039 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18040 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18041 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18042 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18043 }
18044}
18045
18046/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18047struct WordBreakingTokenizer<'a> {
18048 input: &'a str,
18049}
18050
18051impl<'a> WordBreakingTokenizer<'a> {
18052 fn new(input: &'a str) -> Self {
18053 Self { input }
18054 }
18055}
18056
18057fn is_char_ideographic(ch: char) -> bool {
18058 use unicode_script::Script::*;
18059 use unicode_script::UnicodeScript;
18060 matches!(ch.script(), Han | Tangut | Yi)
18061}
18062
18063fn is_grapheme_ideographic(text: &str) -> bool {
18064 text.chars().any(is_char_ideographic)
18065}
18066
18067fn is_grapheme_whitespace(text: &str) -> bool {
18068 text.chars().any(|x| x.is_whitespace())
18069}
18070
18071fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18072 text.chars().next().map_or(false, |ch| {
18073 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18074 })
18075}
18076
18077#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18078enum WordBreakToken<'a> {
18079 Word { token: &'a str, grapheme_len: usize },
18080 InlineWhitespace { token: &'a str, grapheme_len: usize },
18081 Newline,
18082}
18083
18084impl<'a> Iterator for WordBreakingTokenizer<'a> {
18085 /// Yields a span, the count of graphemes in the token, and whether it was
18086 /// whitespace. Note that it also breaks at word boundaries.
18087 type Item = WordBreakToken<'a>;
18088
18089 fn next(&mut self) -> Option<Self::Item> {
18090 use unicode_segmentation::UnicodeSegmentation;
18091 if self.input.is_empty() {
18092 return None;
18093 }
18094
18095 let mut iter = self.input.graphemes(true).peekable();
18096 let mut offset = 0;
18097 let mut grapheme_len = 0;
18098 if let Some(first_grapheme) = iter.next() {
18099 let is_newline = first_grapheme == "\n";
18100 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18101 offset += first_grapheme.len();
18102 grapheme_len += 1;
18103 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18104 if let Some(grapheme) = iter.peek().copied() {
18105 if should_stay_with_preceding_ideograph(grapheme) {
18106 offset += grapheme.len();
18107 grapheme_len += 1;
18108 }
18109 }
18110 } else {
18111 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18112 let mut next_word_bound = words.peek().copied();
18113 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18114 next_word_bound = words.next();
18115 }
18116 while let Some(grapheme) = iter.peek().copied() {
18117 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18118 break;
18119 };
18120 if is_grapheme_whitespace(grapheme) != is_whitespace
18121 || (grapheme == "\n") != is_newline
18122 {
18123 break;
18124 };
18125 offset += grapheme.len();
18126 grapheme_len += 1;
18127 iter.next();
18128 }
18129 }
18130 let token = &self.input[..offset];
18131 self.input = &self.input[offset..];
18132 if token == "\n" {
18133 Some(WordBreakToken::Newline)
18134 } else if is_whitespace {
18135 Some(WordBreakToken::InlineWhitespace {
18136 token,
18137 grapheme_len,
18138 })
18139 } else {
18140 Some(WordBreakToken::Word {
18141 token,
18142 grapheme_len,
18143 })
18144 }
18145 } else {
18146 None
18147 }
18148 }
18149}
18150
18151#[test]
18152fn test_word_breaking_tokenizer() {
18153 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18154 ("", &[]),
18155 (" ", &[whitespace(" ", 2)]),
18156 ("Ʒ", &[word("Ʒ", 1)]),
18157 ("Ǽ", &[word("Ǽ", 1)]),
18158 ("⋑", &[word("⋑", 1)]),
18159 ("⋑⋑", &[word("⋑⋑", 2)]),
18160 (
18161 "原理,进而",
18162 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18163 ),
18164 (
18165 "hello world",
18166 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18167 ),
18168 (
18169 "hello, world",
18170 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18171 ),
18172 (
18173 " hello world",
18174 &[
18175 whitespace(" ", 2),
18176 word("hello", 5),
18177 whitespace(" ", 1),
18178 word("world", 5),
18179 ],
18180 ),
18181 (
18182 "这是什么 \n 钢笔",
18183 &[
18184 word("这", 1),
18185 word("是", 1),
18186 word("什", 1),
18187 word("么", 1),
18188 whitespace(" ", 1),
18189 newline(),
18190 whitespace(" ", 1),
18191 word("钢", 1),
18192 word("笔", 1),
18193 ],
18194 ),
18195 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18196 ];
18197
18198 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18199 WordBreakToken::Word {
18200 token,
18201 grapheme_len,
18202 }
18203 }
18204
18205 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18206 WordBreakToken::InlineWhitespace {
18207 token,
18208 grapheme_len,
18209 }
18210 }
18211
18212 fn newline() -> WordBreakToken<'static> {
18213 WordBreakToken::Newline
18214 }
18215
18216 for (input, result) in tests {
18217 assert_eq!(
18218 WordBreakingTokenizer::new(input)
18219 .collect::<Vec<_>>()
18220 .as_slice(),
18221 *result,
18222 );
18223 }
18224}
18225
18226fn wrap_with_prefix(
18227 line_prefix: String,
18228 unwrapped_text: String,
18229 wrap_column: usize,
18230 tab_size: NonZeroU32,
18231 preserve_existing_whitespace: bool,
18232) -> String {
18233 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18234 let mut wrapped_text = String::new();
18235 let mut current_line = line_prefix.clone();
18236
18237 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18238 let mut current_line_len = line_prefix_len;
18239 let mut in_whitespace = false;
18240 for token in tokenizer {
18241 let have_preceding_whitespace = in_whitespace;
18242 match token {
18243 WordBreakToken::Word {
18244 token,
18245 grapheme_len,
18246 } => {
18247 in_whitespace = false;
18248 if current_line_len + grapheme_len > wrap_column
18249 && current_line_len != line_prefix_len
18250 {
18251 wrapped_text.push_str(current_line.trim_end());
18252 wrapped_text.push('\n');
18253 current_line.truncate(line_prefix.len());
18254 current_line_len = line_prefix_len;
18255 }
18256 current_line.push_str(token);
18257 current_line_len += grapheme_len;
18258 }
18259 WordBreakToken::InlineWhitespace {
18260 mut token,
18261 mut grapheme_len,
18262 } => {
18263 in_whitespace = true;
18264 if have_preceding_whitespace && !preserve_existing_whitespace {
18265 continue;
18266 }
18267 if !preserve_existing_whitespace {
18268 token = " ";
18269 grapheme_len = 1;
18270 }
18271 if current_line_len + grapheme_len > wrap_column {
18272 wrapped_text.push_str(current_line.trim_end());
18273 wrapped_text.push('\n');
18274 current_line.truncate(line_prefix.len());
18275 current_line_len = line_prefix_len;
18276 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18277 current_line.push_str(token);
18278 current_line_len += grapheme_len;
18279 }
18280 }
18281 WordBreakToken::Newline => {
18282 in_whitespace = true;
18283 if preserve_existing_whitespace {
18284 wrapped_text.push_str(current_line.trim_end());
18285 wrapped_text.push('\n');
18286 current_line.truncate(line_prefix.len());
18287 current_line_len = line_prefix_len;
18288 } else if have_preceding_whitespace {
18289 continue;
18290 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18291 {
18292 wrapped_text.push_str(current_line.trim_end());
18293 wrapped_text.push('\n');
18294 current_line.truncate(line_prefix.len());
18295 current_line_len = line_prefix_len;
18296 } else if current_line_len != line_prefix_len {
18297 current_line.push(' ');
18298 current_line_len += 1;
18299 }
18300 }
18301 }
18302 }
18303
18304 if !current_line.is_empty() {
18305 wrapped_text.push_str(¤t_line);
18306 }
18307 wrapped_text
18308}
18309
18310#[test]
18311fn test_wrap_with_prefix() {
18312 assert_eq!(
18313 wrap_with_prefix(
18314 "# ".to_string(),
18315 "abcdefg".to_string(),
18316 4,
18317 NonZeroU32::new(4).unwrap(),
18318 false,
18319 ),
18320 "# abcdefg"
18321 );
18322 assert_eq!(
18323 wrap_with_prefix(
18324 "".to_string(),
18325 "\thello world".to_string(),
18326 8,
18327 NonZeroU32::new(4).unwrap(),
18328 false,
18329 ),
18330 "hello\nworld"
18331 );
18332 assert_eq!(
18333 wrap_with_prefix(
18334 "// ".to_string(),
18335 "xx \nyy zz aa bb cc".to_string(),
18336 12,
18337 NonZeroU32::new(4).unwrap(),
18338 false,
18339 ),
18340 "// xx yy zz\n// aa bb cc"
18341 );
18342 assert_eq!(
18343 wrap_with_prefix(
18344 String::new(),
18345 "这是什么 \n 钢笔".to_string(),
18346 3,
18347 NonZeroU32::new(4).unwrap(),
18348 false,
18349 ),
18350 "这是什\n么 钢\n笔"
18351 );
18352}
18353
18354pub trait CollaborationHub {
18355 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18356 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18357 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18358}
18359
18360impl CollaborationHub for Entity<Project> {
18361 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18362 self.read(cx).collaborators()
18363 }
18364
18365 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18366 self.read(cx).user_store().read(cx).participant_indices()
18367 }
18368
18369 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18370 let this = self.read(cx);
18371 let user_ids = this.collaborators().values().map(|c| c.user_id);
18372 this.user_store().read_with(cx, |user_store, cx| {
18373 user_store.participant_names(user_ids, cx)
18374 })
18375 }
18376}
18377
18378pub trait SemanticsProvider {
18379 fn hover(
18380 &self,
18381 buffer: &Entity<Buffer>,
18382 position: text::Anchor,
18383 cx: &mut App,
18384 ) -> Option<Task<Vec<project::Hover>>>;
18385
18386 fn inlay_hints(
18387 &self,
18388 buffer_handle: Entity<Buffer>,
18389 range: Range<text::Anchor>,
18390 cx: &mut App,
18391 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18392
18393 fn resolve_inlay_hint(
18394 &self,
18395 hint: InlayHint,
18396 buffer_handle: Entity<Buffer>,
18397 server_id: LanguageServerId,
18398 cx: &mut App,
18399 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18400
18401 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18402
18403 fn document_highlights(
18404 &self,
18405 buffer: &Entity<Buffer>,
18406 position: text::Anchor,
18407 cx: &mut App,
18408 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18409
18410 fn definitions(
18411 &self,
18412 buffer: &Entity<Buffer>,
18413 position: text::Anchor,
18414 kind: GotoDefinitionKind,
18415 cx: &mut App,
18416 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18417
18418 fn range_for_rename(
18419 &self,
18420 buffer: &Entity<Buffer>,
18421 position: text::Anchor,
18422 cx: &mut App,
18423 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18424
18425 fn perform_rename(
18426 &self,
18427 buffer: &Entity<Buffer>,
18428 position: text::Anchor,
18429 new_name: String,
18430 cx: &mut App,
18431 ) -> Option<Task<Result<ProjectTransaction>>>;
18432}
18433
18434pub trait CompletionProvider {
18435 fn completions(
18436 &self,
18437 excerpt_id: ExcerptId,
18438 buffer: &Entity<Buffer>,
18439 buffer_position: text::Anchor,
18440 trigger: CompletionContext,
18441 window: &mut Window,
18442 cx: &mut Context<Editor>,
18443 ) -> Task<Result<Option<Vec<Completion>>>>;
18444
18445 fn resolve_completions(
18446 &self,
18447 buffer: Entity<Buffer>,
18448 completion_indices: Vec<usize>,
18449 completions: Rc<RefCell<Box<[Completion]>>>,
18450 cx: &mut Context<Editor>,
18451 ) -> Task<Result<bool>>;
18452
18453 fn apply_additional_edits_for_completion(
18454 &self,
18455 _buffer: Entity<Buffer>,
18456 _completions: Rc<RefCell<Box<[Completion]>>>,
18457 _completion_index: usize,
18458 _push_to_history: bool,
18459 _cx: &mut Context<Editor>,
18460 ) -> Task<Result<Option<language::Transaction>>> {
18461 Task::ready(Ok(None))
18462 }
18463
18464 fn is_completion_trigger(
18465 &self,
18466 buffer: &Entity<Buffer>,
18467 position: language::Anchor,
18468 text: &str,
18469 trigger_in_words: bool,
18470 cx: &mut Context<Editor>,
18471 ) -> bool;
18472
18473 fn sort_completions(&self) -> bool {
18474 true
18475 }
18476
18477 fn filter_completions(&self) -> bool {
18478 true
18479 }
18480}
18481
18482pub trait CodeActionProvider {
18483 fn id(&self) -> Arc<str>;
18484
18485 fn code_actions(
18486 &self,
18487 buffer: &Entity<Buffer>,
18488 range: Range<text::Anchor>,
18489 window: &mut Window,
18490 cx: &mut App,
18491 ) -> Task<Result<Vec<CodeAction>>>;
18492
18493 fn apply_code_action(
18494 &self,
18495 buffer_handle: Entity<Buffer>,
18496 action: CodeAction,
18497 excerpt_id: ExcerptId,
18498 push_to_history: bool,
18499 window: &mut Window,
18500 cx: &mut App,
18501 ) -> Task<Result<ProjectTransaction>>;
18502}
18503
18504impl CodeActionProvider for Entity<Project> {
18505 fn id(&self) -> Arc<str> {
18506 "project".into()
18507 }
18508
18509 fn code_actions(
18510 &self,
18511 buffer: &Entity<Buffer>,
18512 range: Range<text::Anchor>,
18513 _window: &mut Window,
18514 cx: &mut App,
18515 ) -> Task<Result<Vec<CodeAction>>> {
18516 self.update(cx, |project, cx| {
18517 let code_lens = project.code_lens(buffer, range.clone(), cx);
18518 let code_actions = project.code_actions(buffer, range, None, cx);
18519 cx.background_spawn(async move {
18520 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18521 Ok(code_lens
18522 .context("code lens fetch")?
18523 .into_iter()
18524 .chain(code_actions.context("code action fetch")?)
18525 .collect())
18526 })
18527 })
18528 }
18529
18530 fn apply_code_action(
18531 &self,
18532 buffer_handle: Entity<Buffer>,
18533 action: CodeAction,
18534 _excerpt_id: ExcerptId,
18535 push_to_history: bool,
18536 _window: &mut Window,
18537 cx: &mut App,
18538 ) -> Task<Result<ProjectTransaction>> {
18539 self.update(cx, |project, cx| {
18540 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18541 })
18542 }
18543}
18544
18545fn snippet_completions(
18546 project: &Project,
18547 buffer: &Entity<Buffer>,
18548 buffer_position: text::Anchor,
18549 cx: &mut App,
18550) -> Task<Result<Vec<Completion>>> {
18551 let language = buffer.read(cx).language_at(buffer_position);
18552 let language_name = language.as_ref().map(|language| language.lsp_id());
18553 let snippet_store = project.snippets().read(cx);
18554 let snippets = snippet_store.snippets_for(language_name, cx);
18555
18556 if snippets.is_empty() {
18557 return Task::ready(Ok(vec![]));
18558 }
18559 let snapshot = buffer.read(cx).text_snapshot();
18560 let chars: String = snapshot
18561 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18562 .collect();
18563
18564 let scope = language.map(|language| language.default_scope());
18565 let executor = cx.background_executor().clone();
18566
18567 cx.background_spawn(async move {
18568 let classifier = CharClassifier::new(scope).for_completion(true);
18569 let mut last_word = chars
18570 .chars()
18571 .take_while(|c| classifier.is_word(*c))
18572 .collect::<String>();
18573 last_word = last_word.chars().rev().collect();
18574
18575 if last_word.is_empty() {
18576 return Ok(vec![]);
18577 }
18578
18579 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18580 let to_lsp = |point: &text::Anchor| {
18581 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18582 point_to_lsp(end)
18583 };
18584 let lsp_end = to_lsp(&buffer_position);
18585
18586 let candidates = snippets
18587 .iter()
18588 .enumerate()
18589 .flat_map(|(ix, snippet)| {
18590 snippet
18591 .prefix
18592 .iter()
18593 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18594 })
18595 .collect::<Vec<StringMatchCandidate>>();
18596
18597 let mut matches = fuzzy::match_strings(
18598 &candidates,
18599 &last_word,
18600 last_word.chars().any(|c| c.is_uppercase()),
18601 100,
18602 &Default::default(),
18603 executor,
18604 )
18605 .await;
18606
18607 // Remove all candidates where the query's start does not match the start of any word in the candidate
18608 if let Some(query_start) = last_word.chars().next() {
18609 matches.retain(|string_match| {
18610 split_words(&string_match.string).any(|word| {
18611 // Check that the first codepoint of the word as lowercase matches the first
18612 // codepoint of the query as lowercase
18613 word.chars()
18614 .flat_map(|codepoint| codepoint.to_lowercase())
18615 .zip(query_start.to_lowercase())
18616 .all(|(word_cp, query_cp)| word_cp == query_cp)
18617 })
18618 });
18619 }
18620
18621 let matched_strings = matches
18622 .into_iter()
18623 .map(|m| m.string)
18624 .collect::<HashSet<_>>();
18625
18626 let result: Vec<Completion> = snippets
18627 .into_iter()
18628 .filter_map(|snippet| {
18629 let matching_prefix = snippet
18630 .prefix
18631 .iter()
18632 .find(|prefix| matched_strings.contains(*prefix))?;
18633 let start = as_offset - last_word.len();
18634 let start = snapshot.anchor_before(start);
18635 let range = start..buffer_position;
18636 let lsp_start = to_lsp(&start);
18637 let lsp_range = lsp::Range {
18638 start: lsp_start,
18639 end: lsp_end,
18640 };
18641 Some(Completion {
18642 old_range: range,
18643 new_text: snippet.body.clone(),
18644 source: CompletionSource::Lsp {
18645 server_id: LanguageServerId(usize::MAX),
18646 resolved: true,
18647 lsp_completion: Box::new(lsp::CompletionItem {
18648 label: snippet.prefix.first().unwrap().clone(),
18649 kind: Some(CompletionItemKind::SNIPPET),
18650 label_details: snippet.description.as_ref().map(|description| {
18651 lsp::CompletionItemLabelDetails {
18652 detail: Some(description.clone()),
18653 description: None,
18654 }
18655 }),
18656 insert_text_format: Some(InsertTextFormat::SNIPPET),
18657 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18658 lsp::InsertReplaceEdit {
18659 new_text: snippet.body.clone(),
18660 insert: lsp_range,
18661 replace: lsp_range,
18662 },
18663 )),
18664 filter_text: Some(snippet.body.clone()),
18665 sort_text: Some(char::MAX.to_string()),
18666 ..lsp::CompletionItem::default()
18667 }),
18668 lsp_defaults: None,
18669 },
18670 label: CodeLabel {
18671 text: matching_prefix.clone(),
18672 runs: Vec::new(),
18673 filter_range: 0..matching_prefix.len(),
18674 },
18675 icon_path: None,
18676 documentation: snippet
18677 .description
18678 .clone()
18679 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18680 insert_text_mode: None,
18681 confirm: None,
18682 })
18683 })
18684 .collect();
18685
18686 Ok(result)
18687 })
18688}
18689
18690impl CompletionProvider for Entity<Project> {
18691 fn completions(
18692 &self,
18693 _excerpt_id: ExcerptId,
18694 buffer: &Entity<Buffer>,
18695 buffer_position: text::Anchor,
18696 options: CompletionContext,
18697 _window: &mut Window,
18698 cx: &mut Context<Editor>,
18699 ) -> Task<Result<Option<Vec<Completion>>>> {
18700 self.update(cx, |project, cx| {
18701 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18702 let project_completions = project.completions(buffer, buffer_position, options, cx);
18703 cx.background_spawn(async move {
18704 let snippets_completions = snippets.await?;
18705 match project_completions.await? {
18706 Some(mut completions) => {
18707 completions.extend(snippets_completions);
18708 Ok(Some(completions))
18709 }
18710 None => {
18711 if snippets_completions.is_empty() {
18712 Ok(None)
18713 } else {
18714 Ok(Some(snippets_completions))
18715 }
18716 }
18717 }
18718 })
18719 })
18720 }
18721
18722 fn resolve_completions(
18723 &self,
18724 buffer: Entity<Buffer>,
18725 completion_indices: Vec<usize>,
18726 completions: Rc<RefCell<Box<[Completion]>>>,
18727 cx: &mut Context<Editor>,
18728 ) -> Task<Result<bool>> {
18729 self.update(cx, |project, cx| {
18730 project.lsp_store().update(cx, |lsp_store, cx| {
18731 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18732 })
18733 })
18734 }
18735
18736 fn apply_additional_edits_for_completion(
18737 &self,
18738 buffer: Entity<Buffer>,
18739 completions: Rc<RefCell<Box<[Completion]>>>,
18740 completion_index: usize,
18741 push_to_history: bool,
18742 cx: &mut Context<Editor>,
18743 ) -> Task<Result<Option<language::Transaction>>> {
18744 self.update(cx, |project, cx| {
18745 project.lsp_store().update(cx, |lsp_store, cx| {
18746 lsp_store.apply_additional_edits_for_completion(
18747 buffer,
18748 completions,
18749 completion_index,
18750 push_to_history,
18751 cx,
18752 )
18753 })
18754 })
18755 }
18756
18757 fn is_completion_trigger(
18758 &self,
18759 buffer: &Entity<Buffer>,
18760 position: language::Anchor,
18761 text: &str,
18762 trigger_in_words: bool,
18763 cx: &mut Context<Editor>,
18764 ) -> bool {
18765 let mut chars = text.chars();
18766 let char = if let Some(char) = chars.next() {
18767 char
18768 } else {
18769 return false;
18770 };
18771 if chars.next().is_some() {
18772 return false;
18773 }
18774
18775 let buffer = buffer.read(cx);
18776 let snapshot = buffer.snapshot();
18777 if !snapshot.settings_at(position, cx).show_completions_on_input {
18778 return false;
18779 }
18780 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18781 if trigger_in_words && classifier.is_word(char) {
18782 return true;
18783 }
18784
18785 buffer.completion_triggers().contains(text)
18786 }
18787}
18788
18789impl SemanticsProvider for Entity<Project> {
18790 fn hover(
18791 &self,
18792 buffer: &Entity<Buffer>,
18793 position: text::Anchor,
18794 cx: &mut App,
18795 ) -> Option<Task<Vec<project::Hover>>> {
18796 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18797 }
18798
18799 fn document_highlights(
18800 &self,
18801 buffer: &Entity<Buffer>,
18802 position: text::Anchor,
18803 cx: &mut App,
18804 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18805 Some(self.update(cx, |project, cx| {
18806 project.document_highlights(buffer, position, cx)
18807 }))
18808 }
18809
18810 fn definitions(
18811 &self,
18812 buffer: &Entity<Buffer>,
18813 position: text::Anchor,
18814 kind: GotoDefinitionKind,
18815 cx: &mut App,
18816 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18817 Some(self.update(cx, |project, cx| match kind {
18818 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18819 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18820 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18821 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18822 }))
18823 }
18824
18825 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18826 // TODO: make this work for remote projects
18827 self.update(cx, |this, cx| {
18828 buffer.update(cx, |buffer, cx| {
18829 this.any_language_server_supports_inlay_hints(buffer, cx)
18830 })
18831 })
18832 }
18833
18834 fn inlay_hints(
18835 &self,
18836 buffer_handle: Entity<Buffer>,
18837 range: Range<text::Anchor>,
18838 cx: &mut App,
18839 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18840 Some(self.update(cx, |project, cx| {
18841 project.inlay_hints(buffer_handle, range, cx)
18842 }))
18843 }
18844
18845 fn resolve_inlay_hint(
18846 &self,
18847 hint: InlayHint,
18848 buffer_handle: Entity<Buffer>,
18849 server_id: LanguageServerId,
18850 cx: &mut App,
18851 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18852 Some(self.update(cx, |project, cx| {
18853 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18854 }))
18855 }
18856
18857 fn range_for_rename(
18858 &self,
18859 buffer: &Entity<Buffer>,
18860 position: text::Anchor,
18861 cx: &mut App,
18862 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18863 Some(self.update(cx, |project, cx| {
18864 let buffer = buffer.clone();
18865 let task = project.prepare_rename(buffer.clone(), position, cx);
18866 cx.spawn(async move |_, cx| {
18867 Ok(match task.await? {
18868 PrepareRenameResponse::Success(range) => Some(range),
18869 PrepareRenameResponse::InvalidPosition => None,
18870 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18871 // Fallback on using TreeSitter info to determine identifier range
18872 buffer.update(cx, |buffer, _| {
18873 let snapshot = buffer.snapshot();
18874 let (range, kind) = snapshot.surrounding_word(position);
18875 if kind != Some(CharKind::Word) {
18876 return None;
18877 }
18878 Some(
18879 snapshot.anchor_before(range.start)
18880 ..snapshot.anchor_after(range.end),
18881 )
18882 })?
18883 }
18884 })
18885 })
18886 }))
18887 }
18888
18889 fn perform_rename(
18890 &self,
18891 buffer: &Entity<Buffer>,
18892 position: text::Anchor,
18893 new_name: String,
18894 cx: &mut App,
18895 ) -> Option<Task<Result<ProjectTransaction>>> {
18896 Some(self.update(cx, |project, cx| {
18897 project.perform_rename(buffer.clone(), position, new_name, cx)
18898 }))
18899 }
18900}
18901
18902fn inlay_hint_settings(
18903 location: Anchor,
18904 snapshot: &MultiBufferSnapshot,
18905 cx: &mut Context<Editor>,
18906) -> InlayHintSettings {
18907 let file = snapshot.file_at(location);
18908 let language = snapshot.language_at(location).map(|l| l.name());
18909 language_settings(language, file, cx).inlay_hints
18910}
18911
18912fn consume_contiguous_rows(
18913 contiguous_row_selections: &mut Vec<Selection<Point>>,
18914 selection: &Selection<Point>,
18915 display_map: &DisplaySnapshot,
18916 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18917) -> (MultiBufferRow, MultiBufferRow) {
18918 contiguous_row_selections.push(selection.clone());
18919 let start_row = MultiBufferRow(selection.start.row);
18920 let mut end_row = ending_row(selection, display_map);
18921
18922 while let Some(next_selection) = selections.peek() {
18923 if next_selection.start.row <= end_row.0 {
18924 end_row = ending_row(next_selection, display_map);
18925 contiguous_row_selections.push(selections.next().unwrap().clone());
18926 } else {
18927 break;
18928 }
18929 }
18930 (start_row, end_row)
18931}
18932
18933fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18934 if next_selection.end.column > 0 || next_selection.is_empty() {
18935 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18936 } else {
18937 MultiBufferRow(next_selection.end.row)
18938 }
18939}
18940
18941impl EditorSnapshot {
18942 pub fn remote_selections_in_range<'a>(
18943 &'a self,
18944 range: &'a Range<Anchor>,
18945 collaboration_hub: &dyn CollaborationHub,
18946 cx: &'a App,
18947 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18948 let participant_names = collaboration_hub.user_names(cx);
18949 let participant_indices = collaboration_hub.user_participant_indices(cx);
18950 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18951 let collaborators_by_replica_id = collaborators_by_peer_id
18952 .iter()
18953 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18954 .collect::<HashMap<_, _>>();
18955 self.buffer_snapshot
18956 .selections_in_range(range, false)
18957 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18958 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18959 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18960 let user_name = participant_names.get(&collaborator.user_id).cloned();
18961 Some(RemoteSelection {
18962 replica_id,
18963 selection,
18964 cursor_shape,
18965 line_mode,
18966 participant_index,
18967 peer_id: collaborator.peer_id,
18968 user_name,
18969 })
18970 })
18971 }
18972
18973 pub fn hunks_for_ranges(
18974 &self,
18975 ranges: impl IntoIterator<Item = Range<Point>>,
18976 ) -> Vec<MultiBufferDiffHunk> {
18977 let mut hunks = Vec::new();
18978 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18979 HashMap::default();
18980 for query_range in ranges {
18981 let query_rows =
18982 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18983 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18984 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18985 ) {
18986 // Include deleted hunks that are adjacent to the query range, because
18987 // otherwise they would be missed.
18988 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18989 if hunk.status().is_deleted() {
18990 intersects_range |= hunk.row_range.start == query_rows.end;
18991 intersects_range |= hunk.row_range.end == query_rows.start;
18992 }
18993 if intersects_range {
18994 if !processed_buffer_rows
18995 .entry(hunk.buffer_id)
18996 .or_default()
18997 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18998 {
18999 continue;
19000 }
19001 hunks.push(hunk);
19002 }
19003 }
19004 }
19005
19006 hunks
19007 }
19008
19009 fn display_diff_hunks_for_rows<'a>(
19010 &'a self,
19011 display_rows: Range<DisplayRow>,
19012 folded_buffers: &'a HashSet<BufferId>,
19013 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19014 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19015 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19016
19017 self.buffer_snapshot
19018 .diff_hunks_in_range(buffer_start..buffer_end)
19019 .filter_map(|hunk| {
19020 if folded_buffers.contains(&hunk.buffer_id) {
19021 return None;
19022 }
19023
19024 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19025 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19026
19027 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19028 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19029
19030 let display_hunk = if hunk_display_start.column() != 0 {
19031 DisplayDiffHunk::Folded {
19032 display_row: hunk_display_start.row(),
19033 }
19034 } else {
19035 let mut end_row = hunk_display_end.row();
19036 if hunk_display_end.column() > 0 {
19037 end_row.0 += 1;
19038 }
19039 let is_created_file = hunk.is_created_file();
19040 DisplayDiffHunk::Unfolded {
19041 status: hunk.status(),
19042 diff_base_byte_range: hunk.diff_base_byte_range,
19043 display_row_range: hunk_display_start.row()..end_row,
19044 multi_buffer_range: Anchor::range_in_buffer(
19045 hunk.excerpt_id,
19046 hunk.buffer_id,
19047 hunk.buffer_range,
19048 ),
19049 is_created_file,
19050 }
19051 };
19052
19053 Some(display_hunk)
19054 })
19055 }
19056
19057 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19058 self.display_snapshot.buffer_snapshot.language_at(position)
19059 }
19060
19061 pub fn is_focused(&self) -> bool {
19062 self.is_focused
19063 }
19064
19065 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19066 self.placeholder_text.as_ref()
19067 }
19068
19069 pub fn scroll_position(&self) -> gpui::Point<f32> {
19070 self.scroll_anchor.scroll_position(&self.display_snapshot)
19071 }
19072
19073 fn gutter_dimensions(
19074 &self,
19075 font_id: FontId,
19076 font_size: Pixels,
19077 max_line_number_width: Pixels,
19078 cx: &App,
19079 ) -> Option<GutterDimensions> {
19080 if !self.show_gutter {
19081 return None;
19082 }
19083
19084 let descent = cx.text_system().descent(font_id, font_size);
19085 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19086 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19087
19088 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19089 matches!(
19090 ProjectSettings::get_global(cx).git.git_gutter,
19091 Some(GitGutterSetting::TrackedFiles)
19092 )
19093 });
19094 let gutter_settings = EditorSettings::get_global(cx).gutter;
19095 let show_line_numbers = self
19096 .show_line_numbers
19097 .unwrap_or(gutter_settings.line_numbers);
19098 let line_gutter_width = if show_line_numbers {
19099 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19100 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19101 max_line_number_width.max(min_width_for_number_on_gutter)
19102 } else {
19103 0.0.into()
19104 };
19105
19106 let show_code_actions = self
19107 .show_code_actions
19108 .unwrap_or(gutter_settings.code_actions);
19109
19110 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19111 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19112
19113 let git_blame_entries_width =
19114 self.git_blame_gutter_max_author_length
19115 .map(|max_author_length| {
19116 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19117 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19118
19119 /// The number of characters to dedicate to gaps and margins.
19120 const SPACING_WIDTH: usize = 4;
19121
19122 let max_char_count = max_author_length.min(renderer.max_author_length())
19123 + ::git::SHORT_SHA_LENGTH
19124 + MAX_RELATIVE_TIMESTAMP.len()
19125 + SPACING_WIDTH;
19126
19127 em_advance * max_char_count
19128 });
19129
19130 let is_singleton = self.buffer_snapshot.is_singleton();
19131
19132 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19133 left_padding += if !is_singleton {
19134 em_width * 4.0
19135 } else if show_code_actions || show_runnables || show_breakpoints {
19136 em_width * 3.0
19137 } else if show_git_gutter && show_line_numbers {
19138 em_width * 2.0
19139 } else if show_git_gutter || show_line_numbers {
19140 em_width
19141 } else {
19142 px(0.)
19143 };
19144
19145 let shows_folds = is_singleton && gutter_settings.folds;
19146
19147 let right_padding = if shows_folds && show_line_numbers {
19148 em_width * 4.0
19149 } else if shows_folds || (!is_singleton && show_line_numbers) {
19150 em_width * 3.0
19151 } else if show_line_numbers {
19152 em_width
19153 } else {
19154 px(0.)
19155 };
19156
19157 Some(GutterDimensions {
19158 left_padding,
19159 right_padding,
19160 width: line_gutter_width + left_padding + right_padding,
19161 margin: -descent,
19162 git_blame_entries_width,
19163 })
19164 }
19165
19166 pub fn render_crease_toggle(
19167 &self,
19168 buffer_row: MultiBufferRow,
19169 row_contains_cursor: bool,
19170 editor: Entity<Editor>,
19171 window: &mut Window,
19172 cx: &mut App,
19173 ) -> Option<AnyElement> {
19174 let folded = self.is_line_folded(buffer_row);
19175 let mut is_foldable = false;
19176
19177 if let Some(crease) = self
19178 .crease_snapshot
19179 .query_row(buffer_row, &self.buffer_snapshot)
19180 {
19181 is_foldable = true;
19182 match crease {
19183 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19184 if let Some(render_toggle) = render_toggle {
19185 let toggle_callback =
19186 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19187 if folded {
19188 editor.update(cx, |editor, cx| {
19189 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19190 });
19191 } else {
19192 editor.update(cx, |editor, cx| {
19193 editor.unfold_at(
19194 &crate::UnfoldAt { buffer_row },
19195 window,
19196 cx,
19197 )
19198 });
19199 }
19200 });
19201 return Some((render_toggle)(
19202 buffer_row,
19203 folded,
19204 toggle_callback,
19205 window,
19206 cx,
19207 ));
19208 }
19209 }
19210 }
19211 }
19212
19213 is_foldable |= self.starts_indent(buffer_row);
19214
19215 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19216 Some(
19217 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19218 .toggle_state(folded)
19219 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19220 if folded {
19221 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19222 } else {
19223 this.fold_at(&FoldAt { buffer_row }, window, cx);
19224 }
19225 }))
19226 .into_any_element(),
19227 )
19228 } else {
19229 None
19230 }
19231 }
19232
19233 pub fn render_crease_trailer(
19234 &self,
19235 buffer_row: MultiBufferRow,
19236 window: &mut Window,
19237 cx: &mut App,
19238 ) -> Option<AnyElement> {
19239 let folded = self.is_line_folded(buffer_row);
19240 if let Crease::Inline { render_trailer, .. } = self
19241 .crease_snapshot
19242 .query_row(buffer_row, &self.buffer_snapshot)?
19243 {
19244 let render_trailer = render_trailer.as_ref()?;
19245 Some(render_trailer(buffer_row, folded, window, cx))
19246 } else {
19247 None
19248 }
19249 }
19250}
19251
19252impl Deref for EditorSnapshot {
19253 type Target = DisplaySnapshot;
19254
19255 fn deref(&self) -> &Self::Target {
19256 &self.display_snapshot
19257 }
19258}
19259
19260#[derive(Clone, Debug, PartialEq, Eq)]
19261pub enum EditorEvent {
19262 InputIgnored {
19263 text: Arc<str>,
19264 },
19265 InputHandled {
19266 utf16_range_to_replace: Option<Range<isize>>,
19267 text: Arc<str>,
19268 },
19269 ExcerptsAdded {
19270 buffer: Entity<Buffer>,
19271 predecessor: ExcerptId,
19272 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19273 },
19274 ExcerptsRemoved {
19275 ids: Vec<ExcerptId>,
19276 },
19277 BufferFoldToggled {
19278 ids: Vec<ExcerptId>,
19279 folded: bool,
19280 },
19281 ExcerptsEdited {
19282 ids: Vec<ExcerptId>,
19283 },
19284 ExcerptsExpanded {
19285 ids: Vec<ExcerptId>,
19286 },
19287 BufferEdited,
19288 Edited {
19289 transaction_id: clock::Lamport,
19290 },
19291 Reparsed(BufferId),
19292 Focused,
19293 FocusedIn,
19294 Blurred,
19295 DirtyChanged,
19296 Saved,
19297 TitleChanged,
19298 DiffBaseChanged,
19299 SelectionsChanged {
19300 local: bool,
19301 },
19302 ScrollPositionChanged {
19303 local: bool,
19304 autoscroll: bool,
19305 },
19306 Closed,
19307 TransactionUndone {
19308 transaction_id: clock::Lamport,
19309 },
19310 TransactionBegun {
19311 transaction_id: clock::Lamport,
19312 },
19313 Reloaded,
19314 CursorShapeChanged,
19315 PushedToNavHistory {
19316 anchor: Anchor,
19317 is_deactivate: bool,
19318 },
19319}
19320
19321impl EventEmitter<EditorEvent> for Editor {}
19322
19323impl Focusable for Editor {
19324 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19325 self.focus_handle.clone()
19326 }
19327}
19328
19329impl Render for Editor {
19330 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19331 let settings = ThemeSettings::get_global(cx);
19332
19333 let mut text_style = match self.mode {
19334 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19335 color: cx.theme().colors().editor_foreground,
19336 font_family: settings.ui_font.family.clone(),
19337 font_features: settings.ui_font.features.clone(),
19338 font_fallbacks: settings.ui_font.fallbacks.clone(),
19339 font_size: rems(0.875).into(),
19340 font_weight: settings.ui_font.weight,
19341 line_height: relative(settings.buffer_line_height.value()),
19342 ..Default::default()
19343 },
19344 EditorMode::Full => TextStyle {
19345 color: cx.theme().colors().editor_foreground,
19346 font_family: settings.buffer_font.family.clone(),
19347 font_features: settings.buffer_font.features.clone(),
19348 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19349 font_size: settings.buffer_font_size(cx).into(),
19350 font_weight: settings.buffer_font.weight,
19351 line_height: relative(settings.buffer_line_height.value()),
19352 ..Default::default()
19353 },
19354 };
19355 if let Some(text_style_refinement) = &self.text_style_refinement {
19356 text_style.refine(text_style_refinement)
19357 }
19358
19359 let background = match self.mode {
19360 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19361 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19362 EditorMode::Full => cx.theme().colors().editor_background,
19363 };
19364
19365 EditorElement::new(
19366 &cx.entity(),
19367 EditorStyle {
19368 background,
19369 local_player: cx.theme().players().local(),
19370 text: text_style,
19371 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19372 syntax: cx.theme().syntax().clone(),
19373 status: cx.theme().status().clone(),
19374 inlay_hints_style: make_inlay_hints_style(cx),
19375 inline_completion_styles: make_suggestion_styles(cx),
19376 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19377 },
19378 )
19379 }
19380}
19381
19382impl EntityInputHandler for Editor {
19383 fn text_for_range(
19384 &mut self,
19385 range_utf16: Range<usize>,
19386 adjusted_range: &mut Option<Range<usize>>,
19387 _: &mut Window,
19388 cx: &mut Context<Self>,
19389 ) -> Option<String> {
19390 let snapshot = self.buffer.read(cx).read(cx);
19391 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19392 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19393 if (start.0..end.0) != range_utf16 {
19394 adjusted_range.replace(start.0..end.0);
19395 }
19396 Some(snapshot.text_for_range(start..end).collect())
19397 }
19398
19399 fn selected_text_range(
19400 &mut self,
19401 ignore_disabled_input: bool,
19402 _: &mut Window,
19403 cx: &mut Context<Self>,
19404 ) -> Option<UTF16Selection> {
19405 // Prevent the IME menu from appearing when holding down an alphabetic key
19406 // while input is disabled.
19407 if !ignore_disabled_input && !self.input_enabled {
19408 return None;
19409 }
19410
19411 let selection = self.selections.newest::<OffsetUtf16>(cx);
19412 let range = selection.range();
19413
19414 Some(UTF16Selection {
19415 range: range.start.0..range.end.0,
19416 reversed: selection.reversed,
19417 })
19418 }
19419
19420 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19421 let snapshot = self.buffer.read(cx).read(cx);
19422 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19423 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19424 }
19425
19426 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19427 self.clear_highlights::<InputComposition>(cx);
19428 self.ime_transaction.take();
19429 }
19430
19431 fn replace_text_in_range(
19432 &mut self,
19433 range_utf16: Option<Range<usize>>,
19434 text: &str,
19435 window: &mut Window,
19436 cx: &mut Context<Self>,
19437 ) {
19438 if !self.input_enabled {
19439 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19440 return;
19441 }
19442
19443 self.transact(window, cx, |this, window, cx| {
19444 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19445 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19446 Some(this.selection_replacement_ranges(range_utf16, cx))
19447 } else {
19448 this.marked_text_ranges(cx)
19449 };
19450
19451 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19452 let newest_selection_id = this.selections.newest_anchor().id;
19453 this.selections
19454 .all::<OffsetUtf16>(cx)
19455 .iter()
19456 .zip(ranges_to_replace.iter())
19457 .find_map(|(selection, range)| {
19458 if selection.id == newest_selection_id {
19459 Some(
19460 (range.start.0 as isize - selection.head().0 as isize)
19461 ..(range.end.0 as isize - selection.head().0 as isize),
19462 )
19463 } else {
19464 None
19465 }
19466 })
19467 });
19468
19469 cx.emit(EditorEvent::InputHandled {
19470 utf16_range_to_replace: range_to_replace,
19471 text: text.into(),
19472 });
19473
19474 if let Some(new_selected_ranges) = new_selected_ranges {
19475 this.change_selections(None, window, cx, |selections| {
19476 selections.select_ranges(new_selected_ranges)
19477 });
19478 this.backspace(&Default::default(), window, cx);
19479 }
19480
19481 this.handle_input(text, window, cx);
19482 });
19483
19484 if let Some(transaction) = self.ime_transaction {
19485 self.buffer.update(cx, |buffer, cx| {
19486 buffer.group_until_transaction(transaction, cx);
19487 });
19488 }
19489
19490 self.unmark_text(window, cx);
19491 }
19492
19493 fn replace_and_mark_text_in_range(
19494 &mut self,
19495 range_utf16: Option<Range<usize>>,
19496 text: &str,
19497 new_selected_range_utf16: Option<Range<usize>>,
19498 window: &mut Window,
19499 cx: &mut Context<Self>,
19500 ) {
19501 if !self.input_enabled {
19502 return;
19503 }
19504
19505 let transaction = self.transact(window, cx, |this, window, cx| {
19506 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19507 let snapshot = this.buffer.read(cx).read(cx);
19508 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19509 for marked_range in &mut marked_ranges {
19510 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19511 marked_range.start.0 += relative_range_utf16.start;
19512 marked_range.start =
19513 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19514 marked_range.end =
19515 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19516 }
19517 }
19518 Some(marked_ranges)
19519 } else if let Some(range_utf16) = range_utf16 {
19520 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19521 Some(this.selection_replacement_ranges(range_utf16, cx))
19522 } else {
19523 None
19524 };
19525
19526 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19527 let newest_selection_id = this.selections.newest_anchor().id;
19528 this.selections
19529 .all::<OffsetUtf16>(cx)
19530 .iter()
19531 .zip(ranges_to_replace.iter())
19532 .find_map(|(selection, range)| {
19533 if selection.id == newest_selection_id {
19534 Some(
19535 (range.start.0 as isize - selection.head().0 as isize)
19536 ..(range.end.0 as isize - selection.head().0 as isize),
19537 )
19538 } else {
19539 None
19540 }
19541 })
19542 });
19543
19544 cx.emit(EditorEvent::InputHandled {
19545 utf16_range_to_replace: range_to_replace,
19546 text: text.into(),
19547 });
19548
19549 if let Some(ranges) = ranges_to_replace {
19550 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19551 }
19552
19553 let marked_ranges = {
19554 let snapshot = this.buffer.read(cx).read(cx);
19555 this.selections
19556 .disjoint_anchors()
19557 .iter()
19558 .map(|selection| {
19559 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19560 })
19561 .collect::<Vec<_>>()
19562 };
19563
19564 if text.is_empty() {
19565 this.unmark_text(window, cx);
19566 } else {
19567 this.highlight_text::<InputComposition>(
19568 marked_ranges.clone(),
19569 HighlightStyle {
19570 underline: Some(UnderlineStyle {
19571 thickness: px(1.),
19572 color: None,
19573 wavy: false,
19574 }),
19575 ..Default::default()
19576 },
19577 cx,
19578 );
19579 }
19580
19581 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19582 let use_autoclose = this.use_autoclose;
19583 let use_auto_surround = this.use_auto_surround;
19584 this.set_use_autoclose(false);
19585 this.set_use_auto_surround(false);
19586 this.handle_input(text, window, cx);
19587 this.set_use_autoclose(use_autoclose);
19588 this.set_use_auto_surround(use_auto_surround);
19589
19590 if let Some(new_selected_range) = new_selected_range_utf16 {
19591 let snapshot = this.buffer.read(cx).read(cx);
19592 let new_selected_ranges = marked_ranges
19593 .into_iter()
19594 .map(|marked_range| {
19595 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19596 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19597 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19598 snapshot.clip_offset_utf16(new_start, Bias::Left)
19599 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19600 })
19601 .collect::<Vec<_>>();
19602
19603 drop(snapshot);
19604 this.change_selections(None, window, cx, |selections| {
19605 selections.select_ranges(new_selected_ranges)
19606 });
19607 }
19608 });
19609
19610 self.ime_transaction = self.ime_transaction.or(transaction);
19611 if let Some(transaction) = self.ime_transaction {
19612 self.buffer.update(cx, |buffer, cx| {
19613 buffer.group_until_transaction(transaction, cx);
19614 });
19615 }
19616
19617 if self.text_highlights::<InputComposition>(cx).is_none() {
19618 self.ime_transaction.take();
19619 }
19620 }
19621
19622 fn bounds_for_range(
19623 &mut self,
19624 range_utf16: Range<usize>,
19625 element_bounds: gpui::Bounds<Pixels>,
19626 window: &mut Window,
19627 cx: &mut Context<Self>,
19628 ) -> Option<gpui::Bounds<Pixels>> {
19629 let text_layout_details = self.text_layout_details(window);
19630 let gpui::Size {
19631 width: em_width,
19632 height: line_height,
19633 } = self.character_size(window);
19634
19635 let snapshot = self.snapshot(window, cx);
19636 let scroll_position = snapshot.scroll_position();
19637 let scroll_left = scroll_position.x * em_width;
19638
19639 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19640 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19641 + self.gutter_dimensions.width
19642 + self.gutter_dimensions.margin;
19643 let y = line_height * (start.row().as_f32() - scroll_position.y);
19644
19645 Some(Bounds {
19646 origin: element_bounds.origin + point(x, y),
19647 size: size(em_width, line_height),
19648 })
19649 }
19650
19651 fn character_index_for_point(
19652 &mut self,
19653 point: gpui::Point<Pixels>,
19654 _window: &mut Window,
19655 _cx: &mut Context<Self>,
19656 ) -> Option<usize> {
19657 let position_map = self.last_position_map.as_ref()?;
19658 if !position_map.text_hitbox.contains(&point) {
19659 return None;
19660 }
19661 let display_point = position_map.point_for_position(point).previous_valid;
19662 let anchor = position_map
19663 .snapshot
19664 .display_point_to_anchor(display_point, Bias::Left);
19665 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19666 Some(utf16_offset.0)
19667 }
19668}
19669
19670trait SelectionExt {
19671 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19672 fn spanned_rows(
19673 &self,
19674 include_end_if_at_line_start: bool,
19675 map: &DisplaySnapshot,
19676 ) -> Range<MultiBufferRow>;
19677}
19678
19679impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19680 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19681 let start = self
19682 .start
19683 .to_point(&map.buffer_snapshot)
19684 .to_display_point(map);
19685 let end = self
19686 .end
19687 .to_point(&map.buffer_snapshot)
19688 .to_display_point(map);
19689 if self.reversed {
19690 end..start
19691 } else {
19692 start..end
19693 }
19694 }
19695
19696 fn spanned_rows(
19697 &self,
19698 include_end_if_at_line_start: bool,
19699 map: &DisplaySnapshot,
19700 ) -> Range<MultiBufferRow> {
19701 let start = self.start.to_point(&map.buffer_snapshot);
19702 let mut end = self.end.to_point(&map.buffer_snapshot);
19703 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19704 end.row -= 1;
19705 }
19706
19707 let buffer_start = map.prev_line_boundary(start).0;
19708 let buffer_end = map.next_line_boundary(end).0;
19709 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19710 }
19711}
19712
19713impl<T: InvalidationRegion> InvalidationStack<T> {
19714 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19715 where
19716 S: Clone + ToOffset,
19717 {
19718 while let Some(region) = self.last() {
19719 let all_selections_inside_invalidation_ranges =
19720 if selections.len() == region.ranges().len() {
19721 selections
19722 .iter()
19723 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19724 .all(|(selection, invalidation_range)| {
19725 let head = selection.head().to_offset(buffer);
19726 invalidation_range.start <= head && invalidation_range.end >= head
19727 })
19728 } else {
19729 false
19730 };
19731
19732 if all_selections_inside_invalidation_ranges {
19733 break;
19734 } else {
19735 self.pop();
19736 }
19737 }
19738 }
19739}
19740
19741impl<T> Default for InvalidationStack<T> {
19742 fn default() -> Self {
19743 Self(Default::default())
19744 }
19745}
19746
19747impl<T> Deref for InvalidationStack<T> {
19748 type Target = Vec<T>;
19749
19750 fn deref(&self) -> &Self::Target {
19751 &self.0
19752 }
19753}
19754
19755impl<T> DerefMut for InvalidationStack<T> {
19756 fn deref_mut(&mut self) -> &mut Self::Target {
19757 &mut self.0
19758 }
19759}
19760
19761impl InvalidationRegion for SnippetState {
19762 fn ranges(&self) -> &[Range<Anchor>] {
19763 &self.ranges[self.active_index]
19764 }
19765}
19766
19767pub fn diagnostic_block_renderer(
19768 diagnostic: Diagnostic,
19769 max_message_rows: Option<u8>,
19770 allow_closing: bool,
19771) -> RenderBlock {
19772 let (text_without_backticks, code_ranges) =
19773 highlight_diagnostic_message(&diagnostic, max_message_rows);
19774
19775 Arc::new(move |cx: &mut BlockContext| {
19776 let group_id: SharedString = cx.block_id.to_string().into();
19777
19778 let mut text_style = cx.window.text_style().clone();
19779 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19780 let theme_settings = ThemeSettings::get_global(cx);
19781 text_style.font_family = theme_settings.buffer_font.family.clone();
19782 text_style.font_style = theme_settings.buffer_font.style;
19783 text_style.font_features = theme_settings.buffer_font.features.clone();
19784 text_style.font_weight = theme_settings.buffer_font.weight;
19785
19786 let multi_line_diagnostic = diagnostic.message.contains('\n');
19787
19788 let buttons = |diagnostic: &Diagnostic| {
19789 if multi_line_diagnostic {
19790 v_flex()
19791 } else {
19792 h_flex()
19793 }
19794 .when(allow_closing, |div| {
19795 div.children(diagnostic.is_primary.then(|| {
19796 IconButton::new("close-block", IconName::XCircle)
19797 .icon_color(Color::Muted)
19798 .size(ButtonSize::Compact)
19799 .style(ButtonStyle::Transparent)
19800 .visible_on_hover(group_id.clone())
19801 .on_click(move |_click, window, cx| {
19802 window.dispatch_action(Box::new(Cancel), cx)
19803 })
19804 .tooltip(|window, cx| {
19805 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19806 })
19807 }))
19808 })
19809 .child(
19810 IconButton::new("copy-block", IconName::Copy)
19811 .icon_color(Color::Muted)
19812 .size(ButtonSize::Compact)
19813 .style(ButtonStyle::Transparent)
19814 .visible_on_hover(group_id.clone())
19815 .on_click({
19816 let message = diagnostic.message.clone();
19817 move |_click, _, cx| {
19818 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19819 }
19820 })
19821 .tooltip(Tooltip::text("Copy diagnostic message")),
19822 )
19823 };
19824
19825 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19826 AvailableSpace::min_size(),
19827 cx.window,
19828 cx.app,
19829 );
19830
19831 h_flex()
19832 .id(cx.block_id)
19833 .group(group_id.clone())
19834 .relative()
19835 .size_full()
19836 .block_mouse_down()
19837 .pl(cx.gutter_dimensions.width)
19838 .w(cx.max_width - cx.gutter_dimensions.full_width())
19839 .child(
19840 div()
19841 .flex()
19842 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19843 .flex_shrink(),
19844 )
19845 .child(buttons(&diagnostic))
19846 .child(div().flex().flex_shrink_0().child(
19847 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19848 &text_style,
19849 code_ranges.iter().map(|range| {
19850 (
19851 range.clone(),
19852 HighlightStyle {
19853 font_weight: Some(FontWeight::BOLD),
19854 ..Default::default()
19855 },
19856 )
19857 }),
19858 ),
19859 ))
19860 .into_any_element()
19861 })
19862}
19863
19864fn inline_completion_edit_text(
19865 current_snapshot: &BufferSnapshot,
19866 edits: &[(Range<Anchor>, String)],
19867 edit_preview: &EditPreview,
19868 include_deletions: bool,
19869 cx: &App,
19870) -> HighlightedText {
19871 let edits = edits
19872 .iter()
19873 .map(|(anchor, text)| {
19874 (
19875 anchor.start.text_anchor..anchor.end.text_anchor,
19876 text.clone(),
19877 )
19878 })
19879 .collect::<Vec<_>>();
19880
19881 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19882}
19883
19884pub fn highlight_diagnostic_message(
19885 diagnostic: &Diagnostic,
19886 mut max_message_rows: Option<u8>,
19887) -> (SharedString, Vec<Range<usize>>) {
19888 let mut text_without_backticks = String::new();
19889 let mut code_ranges = Vec::new();
19890
19891 if let Some(source) = &diagnostic.source {
19892 text_without_backticks.push_str(source);
19893 code_ranges.push(0..source.len());
19894 text_without_backticks.push_str(": ");
19895 }
19896
19897 let mut prev_offset = 0;
19898 let mut in_code_block = false;
19899 let has_row_limit = max_message_rows.is_some();
19900 let mut newline_indices = diagnostic
19901 .message
19902 .match_indices('\n')
19903 .filter(|_| has_row_limit)
19904 .map(|(ix, _)| ix)
19905 .fuse()
19906 .peekable();
19907
19908 for (quote_ix, _) in diagnostic
19909 .message
19910 .match_indices('`')
19911 .chain([(diagnostic.message.len(), "")])
19912 {
19913 let mut first_newline_ix = None;
19914 let mut last_newline_ix = None;
19915 while let Some(newline_ix) = newline_indices.peek() {
19916 if *newline_ix < quote_ix {
19917 if first_newline_ix.is_none() {
19918 first_newline_ix = Some(*newline_ix);
19919 }
19920 last_newline_ix = Some(*newline_ix);
19921
19922 if let Some(rows_left) = &mut max_message_rows {
19923 if *rows_left == 0 {
19924 break;
19925 } else {
19926 *rows_left -= 1;
19927 }
19928 }
19929 let _ = newline_indices.next();
19930 } else {
19931 break;
19932 }
19933 }
19934 let prev_len = text_without_backticks.len();
19935 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19936 text_without_backticks.push_str(new_text);
19937 if in_code_block {
19938 code_ranges.push(prev_len..text_without_backticks.len());
19939 }
19940 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19941 in_code_block = !in_code_block;
19942 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19943 text_without_backticks.push_str("...");
19944 break;
19945 }
19946 }
19947
19948 (text_without_backticks.into(), code_ranges)
19949}
19950
19951fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19952 match severity {
19953 DiagnosticSeverity::ERROR => colors.error,
19954 DiagnosticSeverity::WARNING => colors.warning,
19955 DiagnosticSeverity::INFORMATION => colors.info,
19956 DiagnosticSeverity::HINT => colors.info,
19957 _ => colors.ignored,
19958 }
19959}
19960
19961pub fn styled_runs_for_code_label<'a>(
19962 label: &'a CodeLabel,
19963 syntax_theme: &'a theme::SyntaxTheme,
19964) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19965 let fade_out = HighlightStyle {
19966 fade_out: Some(0.35),
19967 ..Default::default()
19968 };
19969
19970 let mut prev_end = label.filter_range.end;
19971 label
19972 .runs
19973 .iter()
19974 .enumerate()
19975 .flat_map(move |(ix, (range, highlight_id))| {
19976 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19977 style
19978 } else {
19979 return Default::default();
19980 };
19981 let mut muted_style = style;
19982 muted_style.highlight(fade_out);
19983
19984 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19985 if range.start >= label.filter_range.end {
19986 if range.start > prev_end {
19987 runs.push((prev_end..range.start, fade_out));
19988 }
19989 runs.push((range.clone(), muted_style));
19990 } else if range.end <= label.filter_range.end {
19991 runs.push((range.clone(), style));
19992 } else {
19993 runs.push((range.start..label.filter_range.end, style));
19994 runs.push((label.filter_range.end..range.end, muted_style));
19995 }
19996 prev_end = cmp::max(prev_end, range.end);
19997
19998 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19999 runs.push((prev_end..label.text.len(), fade_out));
20000 }
20001
20002 runs
20003 })
20004}
20005
20006pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20007 let mut prev_index = 0;
20008 let mut prev_codepoint: Option<char> = None;
20009 text.char_indices()
20010 .chain([(text.len(), '\0')])
20011 .filter_map(move |(index, codepoint)| {
20012 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20013 let is_boundary = index == text.len()
20014 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20015 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20016 if is_boundary {
20017 let chunk = &text[prev_index..index];
20018 prev_index = index;
20019 Some(chunk)
20020 } else {
20021 None
20022 }
20023 })
20024}
20025
20026pub trait RangeToAnchorExt: Sized {
20027 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20028
20029 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20030 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20031 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20032 }
20033}
20034
20035impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20036 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20037 let start_offset = self.start.to_offset(snapshot);
20038 let end_offset = self.end.to_offset(snapshot);
20039 if start_offset == end_offset {
20040 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20041 } else {
20042 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20043 }
20044 }
20045}
20046
20047pub trait RowExt {
20048 fn as_f32(&self) -> f32;
20049
20050 fn next_row(&self) -> Self;
20051
20052 fn previous_row(&self) -> Self;
20053
20054 fn minus(&self, other: Self) -> u32;
20055}
20056
20057impl RowExt for DisplayRow {
20058 fn as_f32(&self) -> f32 {
20059 self.0 as f32
20060 }
20061
20062 fn next_row(&self) -> Self {
20063 Self(self.0 + 1)
20064 }
20065
20066 fn previous_row(&self) -> Self {
20067 Self(self.0.saturating_sub(1))
20068 }
20069
20070 fn minus(&self, other: Self) -> u32 {
20071 self.0 - other.0
20072 }
20073}
20074
20075impl RowExt for MultiBufferRow {
20076 fn as_f32(&self) -> f32 {
20077 self.0 as f32
20078 }
20079
20080 fn next_row(&self) -> Self {
20081 Self(self.0 + 1)
20082 }
20083
20084 fn previous_row(&self) -> Self {
20085 Self(self.0.saturating_sub(1))
20086 }
20087
20088 fn minus(&self, other: Self) -> u32 {
20089 self.0 - other.0
20090 }
20091}
20092
20093trait RowRangeExt {
20094 type Row;
20095
20096 fn len(&self) -> usize;
20097
20098 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20099}
20100
20101impl RowRangeExt for Range<MultiBufferRow> {
20102 type Row = MultiBufferRow;
20103
20104 fn len(&self) -> usize {
20105 (self.end.0 - self.start.0) as usize
20106 }
20107
20108 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20109 (self.start.0..self.end.0).map(MultiBufferRow)
20110 }
20111}
20112
20113impl RowRangeExt for Range<DisplayRow> {
20114 type Row = DisplayRow;
20115
20116 fn len(&self) -> usize {
20117 (self.end.0 - self.start.0) as usize
20118 }
20119
20120 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20121 (self.start.0..self.end.0).map(DisplayRow)
20122 }
20123}
20124
20125/// If select range has more than one line, we
20126/// just point the cursor to range.start.
20127fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20128 if range.start.row == range.end.row {
20129 range
20130 } else {
20131 range.start..range.start
20132 }
20133}
20134pub struct KillRing(ClipboardItem);
20135impl Global for KillRing {}
20136
20137const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20138
20139enum BreakpointPromptEditAction {
20140 Log,
20141 Condition,
20142 HitCondition,
20143}
20144
20145struct BreakpointPromptEditor {
20146 pub(crate) prompt: Entity<Editor>,
20147 editor: WeakEntity<Editor>,
20148 breakpoint_anchor: Anchor,
20149 breakpoint: Breakpoint,
20150 edit_action: BreakpointPromptEditAction,
20151 block_ids: HashSet<CustomBlockId>,
20152 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20153 _subscriptions: Vec<Subscription>,
20154}
20155
20156impl BreakpointPromptEditor {
20157 const MAX_LINES: u8 = 4;
20158
20159 fn new(
20160 editor: WeakEntity<Editor>,
20161 breakpoint_anchor: Anchor,
20162 breakpoint: Breakpoint,
20163 edit_action: BreakpointPromptEditAction,
20164 window: &mut Window,
20165 cx: &mut Context<Self>,
20166 ) -> Self {
20167 let base_text = match edit_action {
20168 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20169 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20170 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20171 }
20172 .map(|msg| msg.to_string())
20173 .unwrap_or_default();
20174
20175 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20176 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20177
20178 let prompt = cx.new(|cx| {
20179 let mut prompt = Editor::new(
20180 EditorMode::AutoHeight {
20181 max_lines: Self::MAX_LINES as usize,
20182 },
20183 buffer,
20184 None,
20185 window,
20186 cx,
20187 );
20188 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20189 prompt.set_show_cursor_when_unfocused(false, cx);
20190 prompt.set_placeholder_text(
20191 match edit_action {
20192 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20193 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20194 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20195 },
20196 cx,
20197 );
20198
20199 prompt
20200 });
20201
20202 Self {
20203 prompt,
20204 editor,
20205 breakpoint_anchor,
20206 breakpoint,
20207 edit_action,
20208 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20209 block_ids: Default::default(),
20210 _subscriptions: vec![],
20211 }
20212 }
20213
20214 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20215 self.block_ids.extend(block_ids)
20216 }
20217
20218 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20219 if let Some(editor) = self.editor.upgrade() {
20220 let message = self
20221 .prompt
20222 .read(cx)
20223 .buffer
20224 .read(cx)
20225 .as_singleton()
20226 .expect("A multi buffer in breakpoint prompt isn't possible")
20227 .read(cx)
20228 .as_rope()
20229 .to_string();
20230
20231 editor.update(cx, |editor, cx| {
20232 editor.edit_breakpoint_at_anchor(
20233 self.breakpoint_anchor,
20234 self.breakpoint.clone(),
20235 match self.edit_action {
20236 BreakpointPromptEditAction::Log => {
20237 BreakpointEditAction::EditLogMessage(message.into())
20238 }
20239 BreakpointPromptEditAction::Condition => {
20240 BreakpointEditAction::EditCondition(message.into())
20241 }
20242 BreakpointPromptEditAction::HitCondition => {
20243 BreakpointEditAction::EditHitCondition(message.into())
20244 }
20245 },
20246 cx,
20247 );
20248
20249 editor.remove_blocks(self.block_ids.clone(), None, cx);
20250 cx.focus_self(window);
20251 });
20252 }
20253 }
20254
20255 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20256 self.editor
20257 .update(cx, |editor, cx| {
20258 editor.remove_blocks(self.block_ids.clone(), None, cx);
20259 window.focus(&editor.focus_handle);
20260 })
20261 .log_err();
20262 }
20263
20264 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20265 let settings = ThemeSettings::get_global(cx);
20266 let text_style = TextStyle {
20267 color: if self.prompt.read(cx).read_only(cx) {
20268 cx.theme().colors().text_disabled
20269 } else {
20270 cx.theme().colors().text
20271 },
20272 font_family: settings.buffer_font.family.clone(),
20273 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20274 font_size: settings.buffer_font_size(cx).into(),
20275 font_weight: settings.buffer_font.weight,
20276 line_height: relative(settings.buffer_line_height.value()),
20277 ..Default::default()
20278 };
20279 EditorElement::new(
20280 &self.prompt,
20281 EditorStyle {
20282 background: cx.theme().colors().editor_background,
20283 local_player: cx.theme().players().local(),
20284 text: text_style,
20285 ..Default::default()
20286 },
20287 )
20288 }
20289}
20290
20291impl Render for BreakpointPromptEditor {
20292 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20293 let gutter_dimensions = *self.gutter_dimensions.lock();
20294 h_flex()
20295 .key_context("Editor")
20296 .bg(cx.theme().colors().editor_background)
20297 .border_y_1()
20298 .border_color(cx.theme().status().info_border)
20299 .size_full()
20300 .py(window.line_height() / 2.5)
20301 .on_action(cx.listener(Self::confirm))
20302 .on_action(cx.listener(Self::cancel))
20303 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20304 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20305 }
20306}
20307
20308impl Focusable for BreakpointPromptEditor {
20309 fn focus_handle(&self, cx: &App) -> FocusHandle {
20310 self.prompt.focus_handle(cx)
20311 }
20312}
20313
20314fn all_edits_insertions_or_deletions(
20315 edits: &Vec<(Range<Anchor>, String)>,
20316 snapshot: &MultiBufferSnapshot,
20317) -> bool {
20318 let mut all_insertions = true;
20319 let mut all_deletions = true;
20320
20321 for (range, new_text) in edits.iter() {
20322 let range_is_empty = range.to_offset(&snapshot).is_empty();
20323 let text_is_empty = new_text.is_empty();
20324
20325 if range_is_empty != text_is_empty {
20326 if range_is_empty {
20327 all_deletions = false;
20328 } else {
20329 all_insertions = false;
20330 }
20331 } else {
20332 return false;
20333 }
20334
20335 if !all_insertions && !all_deletions {
20336 return false;
20337 }
20338 }
20339 all_insertions || all_deletions
20340}
20341
20342struct MissingEditPredictionKeybindingTooltip;
20343
20344impl Render for MissingEditPredictionKeybindingTooltip {
20345 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20346 ui::tooltip_container(window, cx, |container, _, cx| {
20347 container
20348 .flex_shrink_0()
20349 .max_w_80()
20350 .min_h(rems_from_px(124.))
20351 .justify_between()
20352 .child(
20353 v_flex()
20354 .flex_1()
20355 .text_ui_sm(cx)
20356 .child(Label::new("Conflict with Accept Keybinding"))
20357 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20358 )
20359 .child(
20360 h_flex()
20361 .pb_1()
20362 .gap_1()
20363 .items_end()
20364 .w_full()
20365 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20366 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20367 }))
20368 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20369 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20370 })),
20371 )
20372 })
20373 }
20374}
20375
20376#[derive(Debug, Clone, Copy, PartialEq)]
20377pub struct LineHighlight {
20378 pub background: Background,
20379 pub border: Option<gpui::Hsla>,
20380}
20381
20382impl From<Hsla> for LineHighlight {
20383 fn from(hsla: Hsla) -> Self {
20384 Self {
20385 background: hsla.into(),
20386 border: None,
20387 }
20388 }
20389}
20390
20391impl From<Background> for LineHighlight {
20392 fn from(background: Background) -> Self {
20393 Self {
20394 background,
20395 border: None,
20396 }
20397 }
20398}
20399
20400fn render_diff_hunk_controls(
20401 row: u32,
20402 status: &DiffHunkStatus,
20403 hunk_range: Range<Anchor>,
20404 is_created_file: bool,
20405 line_height: Pixels,
20406 editor: &Entity<Editor>,
20407 _window: &mut Window,
20408 cx: &mut App,
20409) -> AnyElement {
20410 h_flex()
20411 .h(line_height)
20412 .mr_1()
20413 .gap_1()
20414 .px_0p5()
20415 .pb_1()
20416 .border_x_1()
20417 .border_b_1()
20418 .border_color(cx.theme().colors().border_variant)
20419 .rounded_b_lg()
20420 .bg(cx.theme().colors().editor_background)
20421 .gap_1()
20422 .occlude()
20423 .shadow_md()
20424 .child(if status.has_secondary_hunk() {
20425 Button::new(("stage", row as u64), "Stage")
20426 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20427 .tooltip({
20428 let focus_handle = editor.focus_handle(cx);
20429 move |window, cx| {
20430 Tooltip::for_action_in(
20431 "Stage Hunk",
20432 &::git::ToggleStaged,
20433 &focus_handle,
20434 window,
20435 cx,
20436 )
20437 }
20438 })
20439 .on_click({
20440 let editor = editor.clone();
20441 move |_event, _window, cx| {
20442 editor.update(cx, |editor, cx| {
20443 editor.stage_or_unstage_diff_hunks(
20444 true,
20445 vec![hunk_range.start..hunk_range.start],
20446 cx,
20447 );
20448 });
20449 }
20450 })
20451 } else {
20452 Button::new(("unstage", row as u64), "Unstage")
20453 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20454 .tooltip({
20455 let focus_handle = editor.focus_handle(cx);
20456 move |window, cx| {
20457 Tooltip::for_action_in(
20458 "Unstage Hunk",
20459 &::git::ToggleStaged,
20460 &focus_handle,
20461 window,
20462 cx,
20463 )
20464 }
20465 })
20466 .on_click({
20467 let editor = editor.clone();
20468 move |_event, _window, cx| {
20469 editor.update(cx, |editor, cx| {
20470 editor.stage_or_unstage_diff_hunks(
20471 false,
20472 vec![hunk_range.start..hunk_range.start],
20473 cx,
20474 );
20475 });
20476 }
20477 })
20478 })
20479 .child(
20480 Button::new(("restore", row as u64), "Restore")
20481 .tooltip({
20482 let focus_handle = editor.focus_handle(cx);
20483 move |window, cx| {
20484 Tooltip::for_action_in(
20485 "Restore Hunk",
20486 &::git::Restore,
20487 &focus_handle,
20488 window,
20489 cx,
20490 )
20491 }
20492 })
20493 .on_click({
20494 let editor = editor.clone();
20495 move |_event, window, cx| {
20496 editor.update(cx, |editor, cx| {
20497 let snapshot = editor.snapshot(window, cx);
20498 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20499 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20500 });
20501 }
20502 })
20503 .disabled(is_created_file),
20504 )
20505 .when(
20506 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20507 |el| {
20508 el.child(
20509 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20510 .shape(IconButtonShape::Square)
20511 .icon_size(IconSize::Small)
20512 // .disabled(!has_multiple_hunks)
20513 .tooltip({
20514 let focus_handle = editor.focus_handle(cx);
20515 move |window, cx| {
20516 Tooltip::for_action_in(
20517 "Next Hunk",
20518 &GoToHunk,
20519 &focus_handle,
20520 window,
20521 cx,
20522 )
20523 }
20524 })
20525 .on_click({
20526 let editor = editor.clone();
20527 move |_event, window, cx| {
20528 editor.update(cx, |editor, cx| {
20529 let snapshot = editor.snapshot(window, cx);
20530 let position =
20531 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20532 editor.go_to_hunk_before_or_after_position(
20533 &snapshot,
20534 position,
20535 Direction::Next,
20536 window,
20537 cx,
20538 );
20539 editor.expand_selected_diff_hunks(cx);
20540 });
20541 }
20542 }),
20543 )
20544 .child(
20545 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20546 .shape(IconButtonShape::Square)
20547 .icon_size(IconSize::Small)
20548 // .disabled(!has_multiple_hunks)
20549 .tooltip({
20550 let focus_handle = editor.focus_handle(cx);
20551 move |window, cx| {
20552 Tooltip::for_action_in(
20553 "Previous Hunk",
20554 &GoToPreviousHunk,
20555 &focus_handle,
20556 window,
20557 cx,
20558 )
20559 }
20560 })
20561 .on_click({
20562 let editor = editor.clone();
20563 move |_event, window, cx| {
20564 editor.update(cx, |editor, cx| {
20565 let snapshot = editor.snapshot(window, cx);
20566 let point =
20567 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20568 editor.go_to_hunk_before_or_after_position(
20569 &snapshot,
20570 point,
20571 Direction::Prev,
20572 window,
20573 cx,
20574 );
20575 editor.expand_selected_diff_hunks(cx);
20576 });
20577 }
20578 }),
20579 )
20580 },
20581 )
20582 .into_any_element()
20583}