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 editor.go_to_active_debug_line(window, cx);
1388 }
1389 _ => {}
1390 },
1391 ));
1392 }
1393 }
1394
1395 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1396
1397 let inlay_hint_settings =
1398 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1399 let focus_handle = cx.focus_handle();
1400 cx.on_focus(&focus_handle, window, Self::handle_focus)
1401 .detach();
1402 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1403 .detach();
1404 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1405 .detach();
1406 cx.on_blur(&focus_handle, window, Self::handle_blur)
1407 .detach();
1408
1409 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1410 Some(false)
1411 } else {
1412 None
1413 };
1414
1415 let breakpoint_store = match (mode, project.as_ref()) {
1416 (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
1417 _ => None,
1418 };
1419
1420 let mut code_action_providers = Vec::new();
1421 let mut load_uncommitted_diff = None;
1422 if let Some(project) = project.clone() {
1423 load_uncommitted_diff = Some(
1424 get_uncommitted_diff_for_buffer(
1425 &project,
1426 buffer.read(cx).all_buffers(),
1427 buffer.clone(),
1428 cx,
1429 )
1430 .shared(),
1431 );
1432 code_action_providers.push(Rc::new(project) as Rc<_>);
1433 }
1434
1435 let mut this = Self {
1436 focus_handle,
1437 show_cursor_when_unfocused: false,
1438 last_focused_descendant: None,
1439 buffer: buffer.clone(),
1440 display_map: display_map.clone(),
1441 selections,
1442 scroll_manager: ScrollManager::new(cx),
1443 columnar_selection_tail: None,
1444 add_selections_state: None,
1445 select_next_state: None,
1446 select_prev_state: None,
1447 selection_history: Default::default(),
1448 autoclose_regions: Default::default(),
1449 snippet_stack: Default::default(),
1450 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1451 ime_transaction: Default::default(),
1452 active_diagnostics: None,
1453 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1454 inline_diagnostics_update: Task::ready(()),
1455 inline_diagnostics: Vec::new(),
1456 soft_wrap_mode_override,
1457 hard_wrap: None,
1458 completion_provider: project.clone().map(|project| Box::new(project) as _),
1459 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1460 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1461 project,
1462 blink_manager: blink_manager.clone(),
1463 show_local_selections: true,
1464 show_scrollbars: true,
1465 mode,
1466 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1467 show_gutter: mode == EditorMode::Full,
1468 show_line_numbers: None,
1469 use_relative_line_numbers: None,
1470 show_git_diff_gutter: None,
1471 show_code_actions: None,
1472 show_runnables: None,
1473 show_breakpoints: None,
1474 show_wrap_guides: None,
1475 show_indent_guides,
1476 placeholder_text: None,
1477 highlight_order: 0,
1478 highlighted_rows: HashMap::default(),
1479 background_highlights: Default::default(),
1480 gutter_highlights: TreeMap::default(),
1481 scrollbar_marker_state: ScrollbarMarkerState::default(),
1482 active_indent_guides_state: ActiveIndentGuidesState::default(),
1483 nav_history: None,
1484 context_menu: RefCell::new(None),
1485 context_menu_options: None,
1486 mouse_context_menu: None,
1487 completion_tasks: Default::default(),
1488 signature_help_state: SignatureHelpState::default(),
1489 auto_signature_help: None,
1490 find_all_references_task_sources: Vec::new(),
1491 next_completion_id: 0,
1492 next_inlay_id: 0,
1493 code_action_providers,
1494 available_code_actions: Default::default(),
1495 code_actions_task: Default::default(),
1496 selection_highlight_task: Default::default(),
1497 document_highlights_task: Default::default(),
1498 linked_editing_range_task: Default::default(),
1499 pending_rename: Default::default(),
1500 searchable: true,
1501 cursor_shape: EditorSettings::get_global(cx)
1502 .cursor_shape
1503 .unwrap_or_default(),
1504 current_line_highlight: None,
1505 autoindent_mode: Some(AutoindentMode::EachLine),
1506 collapse_matches: false,
1507 workspace: None,
1508 input_enabled: true,
1509 use_modal_editing: mode == EditorMode::Full,
1510 read_only: false,
1511 use_autoclose: true,
1512 use_auto_surround: true,
1513 auto_replace_emoji_shortcode: false,
1514 jsx_tag_auto_close_enabled_in_any_buffer: false,
1515 leader_peer_id: None,
1516 remote_id: None,
1517 hover_state: Default::default(),
1518 pending_mouse_down: None,
1519 hovered_link_state: Default::default(),
1520 edit_prediction_provider: None,
1521 active_inline_completion: None,
1522 stale_inline_completion_in_menu: None,
1523 edit_prediction_preview: EditPredictionPreview::Inactive {
1524 released_too_fast: false,
1525 },
1526 inline_diagnostics_enabled: mode == EditorMode::Full,
1527 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1528
1529 gutter_hovered: false,
1530 pixel_position_of_newest_cursor: None,
1531 last_bounds: None,
1532 last_position_map: None,
1533 expect_bounds_change: None,
1534 gutter_dimensions: GutterDimensions::default(),
1535 style: None,
1536 show_cursor_names: false,
1537 hovered_cursors: Default::default(),
1538 next_editor_action_id: EditorActionId::default(),
1539 editor_actions: Rc::default(),
1540 inline_completions_hidden_for_vim_mode: false,
1541 show_inline_completions_override: None,
1542 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1543 edit_prediction_settings: EditPredictionSettings::Disabled,
1544 edit_prediction_indent_conflict: false,
1545 edit_prediction_requires_modifier_in_indent_conflict: true,
1546 custom_context_menu: None,
1547 show_git_blame_gutter: false,
1548 show_git_blame_inline: false,
1549 show_selection_menu: None,
1550 show_git_blame_inline_delay_task: None,
1551 git_blame_inline_tooltip: None,
1552 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1553 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1554 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1555 .session
1556 .restore_unsaved_buffers,
1557 blame: None,
1558 blame_subscription: None,
1559 tasks: Default::default(),
1560
1561 breakpoint_store,
1562 gutter_breakpoint_indicator: (None, None),
1563 _subscriptions: vec![
1564 cx.observe(&buffer, Self::on_buffer_changed),
1565 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1566 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1567 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1568 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1569 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1570 cx.observe_window_activation(window, |editor, window, cx| {
1571 let active = window.is_window_active();
1572 editor.blink_manager.update(cx, |blink_manager, cx| {
1573 if active {
1574 blink_manager.enable(cx);
1575 } else {
1576 blink_manager.disable(cx);
1577 }
1578 });
1579 }),
1580 ],
1581 tasks_update_task: None,
1582 linked_edit_ranges: Default::default(),
1583 in_project_search: false,
1584 previous_search_ranges: None,
1585 breadcrumb_header: None,
1586 focused_block: None,
1587 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1588 addons: HashMap::default(),
1589 registered_buffers: HashMap::default(),
1590 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1591 selection_mark_mode: false,
1592 toggle_fold_multiple_buffers: Task::ready(()),
1593 serialize_selections: Task::ready(()),
1594 serialize_folds: Task::ready(()),
1595 text_style_refinement: None,
1596 load_diff_task: load_uncommitted_diff,
1597 mouse_cursor_hidden: false,
1598 hide_mouse_mode: EditorSettings::get_global(cx)
1599 .hide_mouse
1600 .unwrap_or_default(),
1601 };
1602 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1603 this._subscriptions
1604 .push(cx.observe(breakpoints, |_, _, cx| {
1605 cx.notify();
1606 }));
1607 }
1608 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1609 this._subscriptions.extend(project_subscriptions);
1610
1611 this._subscriptions.push(cx.subscribe_in(
1612 &cx.entity(),
1613 window,
1614 |editor, _, e: &EditorEvent, window, cx| {
1615 if let EditorEvent::SelectionsChanged { local } = e {
1616 if *local {
1617 let new_anchor = editor.scroll_manager.anchor();
1618 let snapshot = editor.snapshot(window, cx);
1619 editor.update_restoration_data(cx, move |data| {
1620 data.scroll_position = (
1621 new_anchor.top_row(&snapshot.buffer_snapshot),
1622 new_anchor.offset,
1623 );
1624 });
1625 }
1626 }
1627 },
1628 ));
1629
1630 this.end_selection(window, cx);
1631 this.scroll_manager.show_scrollbars(window, cx);
1632 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1633
1634 if mode == EditorMode::Full {
1635 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1636 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1637
1638 if this.git_blame_inline_enabled {
1639 this.git_blame_inline_enabled = true;
1640 this.start_git_blame_inline(false, window, cx);
1641 }
1642
1643 this.go_to_active_debug_line(window, cx);
1644
1645 if let Some(buffer) = buffer.read(cx).as_singleton() {
1646 if let Some(project) = this.project.as_ref() {
1647 let handle = project.update(cx, |project, cx| {
1648 project.register_buffer_with_language_servers(&buffer, cx)
1649 });
1650 this.registered_buffers
1651 .insert(buffer.read(cx).remote_id(), handle);
1652 }
1653 }
1654 }
1655
1656 this.report_editor_event("Editor Opened", None, cx);
1657 this
1658 }
1659
1660 pub fn deploy_mouse_context_menu(
1661 &mut self,
1662 position: gpui::Point<Pixels>,
1663 context_menu: Entity<ContextMenu>,
1664 window: &mut Window,
1665 cx: &mut Context<Self>,
1666 ) {
1667 self.mouse_context_menu = Some(MouseContextMenu::new(
1668 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1669 context_menu,
1670 window,
1671 cx,
1672 ));
1673 }
1674
1675 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1676 self.mouse_context_menu
1677 .as_ref()
1678 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1679 }
1680
1681 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1682 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1683 }
1684
1685 fn key_context_internal(
1686 &self,
1687 has_active_edit_prediction: bool,
1688 window: &Window,
1689 cx: &App,
1690 ) -> KeyContext {
1691 let mut key_context = KeyContext::new_with_defaults();
1692 key_context.add("Editor");
1693 let mode = match self.mode {
1694 EditorMode::SingleLine { .. } => "single_line",
1695 EditorMode::AutoHeight { .. } => "auto_height",
1696 EditorMode::Full => "full",
1697 };
1698
1699 if EditorSettings::jupyter_enabled(cx) {
1700 key_context.add("jupyter");
1701 }
1702
1703 key_context.set("mode", mode);
1704 if self.pending_rename.is_some() {
1705 key_context.add("renaming");
1706 }
1707
1708 match self.context_menu.borrow().as_ref() {
1709 Some(CodeContextMenu::Completions(_)) => {
1710 key_context.add("menu");
1711 key_context.add("showing_completions");
1712 }
1713 Some(CodeContextMenu::CodeActions(_)) => {
1714 key_context.add("menu");
1715 key_context.add("showing_code_actions")
1716 }
1717 None => {}
1718 }
1719
1720 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1721 if !self.focus_handle(cx).contains_focused(window, cx)
1722 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1723 {
1724 for addon in self.addons.values() {
1725 addon.extend_key_context(&mut key_context, cx)
1726 }
1727 }
1728
1729 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1730 if let Some(extension) = singleton_buffer
1731 .read(cx)
1732 .file()
1733 .and_then(|file| file.path().extension()?.to_str())
1734 {
1735 key_context.set("extension", extension.to_string());
1736 }
1737 } else {
1738 key_context.add("multibuffer");
1739 }
1740
1741 if has_active_edit_prediction {
1742 if self.edit_prediction_in_conflict() {
1743 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1744 } else {
1745 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1746 key_context.add("copilot_suggestion");
1747 }
1748 }
1749
1750 if self.selection_mark_mode {
1751 key_context.add("selection_mode");
1752 }
1753
1754 key_context
1755 }
1756
1757 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1758 self.mouse_cursor_hidden = match origin {
1759 HideMouseCursorOrigin::TypingAction => {
1760 matches!(
1761 self.hide_mouse_mode,
1762 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1763 )
1764 }
1765 HideMouseCursorOrigin::MovementAction => {
1766 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1767 }
1768 };
1769 }
1770
1771 pub fn edit_prediction_in_conflict(&self) -> bool {
1772 if !self.show_edit_predictions_in_menu() {
1773 return false;
1774 }
1775
1776 let showing_completions = self
1777 .context_menu
1778 .borrow()
1779 .as_ref()
1780 .map_or(false, |context| {
1781 matches!(context, CodeContextMenu::Completions(_))
1782 });
1783
1784 showing_completions
1785 || self.edit_prediction_requires_modifier()
1786 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1787 // bindings to insert tab characters.
1788 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1789 }
1790
1791 pub fn accept_edit_prediction_keybind(
1792 &self,
1793 window: &Window,
1794 cx: &App,
1795 ) -> AcceptEditPredictionBinding {
1796 let key_context = self.key_context_internal(true, window, cx);
1797 let in_conflict = self.edit_prediction_in_conflict();
1798
1799 AcceptEditPredictionBinding(
1800 window
1801 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1802 .into_iter()
1803 .filter(|binding| {
1804 !in_conflict
1805 || binding
1806 .keystrokes()
1807 .first()
1808 .map_or(false, |keystroke| keystroke.modifiers.modified())
1809 })
1810 .rev()
1811 .min_by_key(|binding| {
1812 binding
1813 .keystrokes()
1814 .first()
1815 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1816 }),
1817 )
1818 }
1819
1820 pub fn new_file(
1821 workspace: &mut Workspace,
1822 _: &workspace::NewFile,
1823 window: &mut Window,
1824 cx: &mut Context<Workspace>,
1825 ) {
1826 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1827 "Failed to create buffer",
1828 window,
1829 cx,
1830 |e, _, _| match e.error_code() {
1831 ErrorCode::RemoteUpgradeRequired => Some(format!(
1832 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1833 e.error_tag("required").unwrap_or("the latest version")
1834 )),
1835 _ => None,
1836 },
1837 );
1838 }
1839
1840 pub fn new_in_workspace(
1841 workspace: &mut Workspace,
1842 window: &mut Window,
1843 cx: &mut Context<Workspace>,
1844 ) -> Task<Result<Entity<Editor>>> {
1845 let project = workspace.project().clone();
1846 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1847
1848 cx.spawn_in(window, async move |workspace, cx| {
1849 let buffer = create.await?;
1850 workspace.update_in(cx, |workspace, window, cx| {
1851 let editor =
1852 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1853 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1854 editor
1855 })
1856 })
1857 }
1858
1859 fn new_file_vertical(
1860 workspace: &mut Workspace,
1861 _: &workspace::NewFileSplitVertical,
1862 window: &mut Window,
1863 cx: &mut Context<Workspace>,
1864 ) {
1865 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1866 }
1867
1868 fn new_file_horizontal(
1869 workspace: &mut Workspace,
1870 _: &workspace::NewFileSplitHorizontal,
1871 window: &mut Window,
1872 cx: &mut Context<Workspace>,
1873 ) {
1874 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1875 }
1876
1877 fn new_file_in_direction(
1878 workspace: &mut Workspace,
1879 direction: SplitDirection,
1880 window: &mut Window,
1881 cx: &mut Context<Workspace>,
1882 ) {
1883 let project = workspace.project().clone();
1884 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1885
1886 cx.spawn_in(window, async move |workspace, cx| {
1887 let buffer = create.await?;
1888 workspace.update_in(cx, move |workspace, window, cx| {
1889 workspace.split_item(
1890 direction,
1891 Box::new(
1892 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1893 ),
1894 window,
1895 cx,
1896 )
1897 })?;
1898 anyhow::Ok(())
1899 })
1900 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1901 match e.error_code() {
1902 ErrorCode::RemoteUpgradeRequired => Some(format!(
1903 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1904 e.error_tag("required").unwrap_or("the latest version")
1905 )),
1906 _ => None,
1907 }
1908 });
1909 }
1910
1911 pub fn leader_peer_id(&self) -> Option<PeerId> {
1912 self.leader_peer_id
1913 }
1914
1915 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1916 &self.buffer
1917 }
1918
1919 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1920 self.workspace.as_ref()?.0.upgrade()
1921 }
1922
1923 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1924 self.buffer().read(cx).title(cx)
1925 }
1926
1927 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1928 let git_blame_gutter_max_author_length = self
1929 .render_git_blame_gutter(cx)
1930 .then(|| {
1931 if let Some(blame) = self.blame.as_ref() {
1932 let max_author_length =
1933 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1934 Some(max_author_length)
1935 } else {
1936 None
1937 }
1938 })
1939 .flatten();
1940
1941 EditorSnapshot {
1942 mode: self.mode,
1943 show_gutter: self.show_gutter,
1944 show_line_numbers: self.show_line_numbers,
1945 show_git_diff_gutter: self.show_git_diff_gutter,
1946 show_code_actions: self.show_code_actions,
1947 show_runnables: self.show_runnables,
1948 show_breakpoints: self.show_breakpoints,
1949 git_blame_gutter_max_author_length,
1950 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1951 scroll_anchor: self.scroll_manager.anchor(),
1952 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1953 placeholder_text: self.placeholder_text.clone(),
1954 is_focused: self.focus_handle.is_focused(window),
1955 current_line_highlight: self
1956 .current_line_highlight
1957 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1958 gutter_hovered: self.gutter_hovered,
1959 }
1960 }
1961
1962 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1963 self.buffer.read(cx).language_at(point, cx)
1964 }
1965
1966 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1967 self.buffer.read(cx).read(cx).file_at(point).cloned()
1968 }
1969
1970 pub fn active_excerpt(
1971 &self,
1972 cx: &App,
1973 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1974 self.buffer
1975 .read(cx)
1976 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1977 }
1978
1979 pub fn mode(&self) -> EditorMode {
1980 self.mode
1981 }
1982
1983 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1984 self.collaboration_hub.as_deref()
1985 }
1986
1987 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1988 self.collaboration_hub = Some(hub);
1989 }
1990
1991 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1992 self.in_project_search = in_project_search;
1993 }
1994
1995 pub fn set_custom_context_menu(
1996 &mut self,
1997 f: impl 'static
1998 + Fn(
1999 &mut Self,
2000 DisplayPoint,
2001 &mut Window,
2002 &mut Context<Self>,
2003 ) -> Option<Entity<ui::ContextMenu>>,
2004 ) {
2005 self.custom_context_menu = Some(Box::new(f))
2006 }
2007
2008 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2009 self.completion_provider = provider;
2010 }
2011
2012 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2013 self.semantics_provider.clone()
2014 }
2015
2016 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2017 self.semantics_provider = provider;
2018 }
2019
2020 pub fn set_edit_prediction_provider<T>(
2021 &mut self,
2022 provider: Option<Entity<T>>,
2023 window: &mut Window,
2024 cx: &mut Context<Self>,
2025 ) where
2026 T: EditPredictionProvider,
2027 {
2028 self.edit_prediction_provider =
2029 provider.map(|provider| RegisteredInlineCompletionProvider {
2030 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2031 if this.focus_handle.is_focused(window) {
2032 this.update_visible_inline_completion(window, cx);
2033 }
2034 }),
2035 provider: Arc::new(provider),
2036 });
2037 self.update_edit_prediction_settings(cx);
2038 self.refresh_inline_completion(false, false, window, cx);
2039 }
2040
2041 pub fn placeholder_text(&self) -> Option<&str> {
2042 self.placeholder_text.as_deref()
2043 }
2044
2045 pub fn set_placeholder_text(
2046 &mut self,
2047 placeholder_text: impl Into<Arc<str>>,
2048 cx: &mut Context<Self>,
2049 ) {
2050 let placeholder_text = Some(placeholder_text.into());
2051 if self.placeholder_text != placeholder_text {
2052 self.placeholder_text = placeholder_text;
2053 cx.notify();
2054 }
2055 }
2056
2057 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2058 self.cursor_shape = cursor_shape;
2059
2060 // Disrupt blink for immediate user feedback that the cursor shape has changed
2061 self.blink_manager.update(cx, BlinkManager::show_cursor);
2062
2063 cx.notify();
2064 }
2065
2066 pub fn set_current_line_highlight(
2067 &mut self,
2068 current_line_highlight: Option<CurrentLineHighlight>,
2069 ) {
2070 self.current_line_highlight = current_line_highlight;
2071 }
2072
2073 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2074 self.collapse_matches = collapse_matches;
2075 }
2076
2077 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2078 let buffers = self.buffer.read(cx).all_buffers();
2079 let Some(project) = self.project.as_ref() else {
2080 return;
2081 };
2082 project.update(cx, |project, cx| {
2083 for buffer in buffers {
2084 self.registered_buffers
2085 .entry(buffer.read(cx).remote_id())
2086 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2087 }
2088 })
2089 }
2090
2091 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2092 if self.collapse_matches {
2093 return range.start..range.start;
2094 }
2095 range.clone()
2096 }
2097
2098 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2099 if self.display_map.read(cx).clip_at_line_ends != clip {
2100 self.display_map
2101 .update(cx, |map, _| map.clip_at_line_ends = clip);
2102 }
2103 }
2104
2105 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2106 self.input_enabled = input_enabled;
2107 }
2108
2109 pub fn set_inline_completions_hidden_for_vim_mode(
2110 &mut self,
2111 hidden: bool,
2112 window: &mut Window,
2113 cx: &mut Context<Self>,
2114 ) {
2115 if hidden != self.inline_completions_hidden_for_vim_mode {
2116 self.inline_completions_hidden_for_vim_mode = hidden;
2117 if hidden {
2118 self.update_visible_inline_completion(window, cx);
2119 } else {
2120 self.refresh_inline_completion(true, false, window, cx);
2121 }
2122 }
2123 }
2124
2125 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2126 self.menu_inline_completions_policy = value;
2127 }
2128
2129 pub fn set_autoindent(&mut self, autoindent: bool) {
2130 if autoindent {
2131 self.autoindent_mode = Some(AutoindentMode::EachLine);
2132 } else {
2133 self.autoindent_mode = None;
2134 }
2135 }
2136
2137 pub fn read_only(&self, cx: &App) -> bool {
2138 self.read_only || self.buffer.read(cx).read_only()
2139 }
2140
2141 pub fn set_read_only(&mut self, read_only: bool) {
2142 self.read_only = read_only;
2143 }
2144
2145 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2146 self.use_autoclose = autoclose;
2147 }
2148
2149 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2150 self.use_auto_surround = auto_surround;
2151 }
2152
2153 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2154 self.auto_replace_emoji_shortcode = auto_replace;
2155 }
2156
2157 pub fn toggle_edit_predictions(
2158 &mut self,
2159 _: &ToggleEditPrediction,
2160 window: &mut Window,
2161 cx: &mut Context<Self>,
2162 ) {
2163 if self.show_inline_completions_override.is_some() {
2164 self.set_show_edit_predictions(None, window, cx);
2165 } else {
2166 let show_edit_predictions = !self.edit_predictions_enabled();
2167 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2168 }
2169 }
2170
2171 pub fn set_show_edit_predictions(
2172 &mut self,
2173 show_edit_predictions: Option<bool>,
2174 window: &mut Window,
2175 cx: &mut Context<Self>,
2176 ) {
2177 self.show_inline_completions_override = show_edit_predictions;
2178 self.update_edit_prediction_settings(cx);
2179
2180 if let Some(false) = show_edit_predictions {
2181 self.discard_inline_completion(false, cx);
2182 } else {
2183 self.refresh_inline_completion(false, true, window, cx);
2184 }
2185 }
2186
2187 fn inline_completions_disabled_in_scope(
2188 &self,
2189 buffer: &Entity<Buffer>,
2190 buffer_position: language::Anchor,
2191 cx: &App,
2192 ) -> bool {
2193 let snapshot = buffer.read(cx).snapshot();
2194 let settings = snapshot.settings_at(buffer_position, cx);
2195
2196 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2197 return false;
2198 };
2199
2200 scope.override_name().map_or(false, |scope_name| {
2201 settings
2202 .edit_predictions_disabled_in
2203 .iter()
2204 .any(|s| s == scope_name)
2205 })
2206 }
2207
2208 pub fn set_use_modal_editing(&mut self, to: bool) {
2209 self.use_modal_editing = to;
2210 }
2211
2212 pub fn use_modal_editing(&self) -> bool {
2213 self.use_modal_editing
2214 }
2215
2216 fn selections_did_change(
2217 &mut self,
2218 local: bool,
2219 old_cursor_position: &Anchor,
2220 show_completions: bool,
2221 window: &mut Window,
2222 cx: &mut Context<Self>,
2223 ) {
2224 window.invalidate_character_coordinates();
2225
2226 // Copy selections to primary selection buffer
2227 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2228 if local {
2229 let selections = self.selections.all::<usize>(cx);
2230 let buffer_handle = self.buffer.read(cx).read(cx);
2231
2232 let mut text = String::new();
2233 for (index, selection) in selections.iter().enumerate() {
2234 let text_for_selection = buffer_handle
2235 .text_for_range(selection.start..selection.end)
2236 .collect::<String>();
2237
2238 text.push_str(&text_for_selection);
2239 if index != selections.len() - 1 {
2240 text.push('\n');
2241 }
2242 }
2243
2244 if !text.is_empty() {
2245 cx.write_to_primary(ClipboardItem::new_string(text));
2246 }
2247 }
2248
2249 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2250 self.buffer.update(cx, |buffer, cx| {
2251 buffer.set_active_selections(
2252 &self.selections.disjoint_anchors(),
2253 self.selections.line_mode,
2254 self.cursor_shape,
2255 cx,
2256 )
2257 });
2258 }
2259 let display_map = self
2260 .display_map
2261 .update(cx, |display_map, cx| display_map.snapshot(cx));
2262 let buffer = &display_map.buffer_snapshot;
2263 self.add_selections_state = None;
2264 self.select_next_state = None;
2265 self.select_prev_state = None;
2266 self.select_syntax_node_history.try_clear();
2267 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2268 self.snippet_stack
2269 .invalidate(&self.selections.disjoint_anchors(), buffer);
2270 self.take_rename(false, window, cx);
2271
2272 let new_cursor_position = self.selections.newest_anchor().head();
2273
2274 self.push_to_nav_history(
2275 *old_cursor_position,
2276 Some(new_cursor_position.to_point(buffer)),
2277 false,
2278 cx,
2279 );
2280
2281 if local {
2282 let new_cursor_position = self.selections.newest_anchor().head();
2283 let mut context_menu = self.context_menu.borrow_mut();
2284 let completion_menu = match context_menu.as_ref() {
2285 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2286 _ => {
2287 *context_menu = None;
2288 None
2289 }
2290 };
2291 if let Some(buffer_id) = new_cursor_position.buffer_id {
2292 if !self.registered_buffers.contains_key(&buffer_id) {
2293 if let Some(project) = self.project.as_ref() {
2294 project.update(cx, |project, cx| {
2295 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2296 return;
2297 };
2298 self.registered_buffers.insert(
2299 buffer_id,
2300 project.register_buffer_with_language_servers(&buffer, cx),
2301 );
2302 })
2303 }
2304 }
2305 }
2306
2307 if let Some(completion_menu) = completion_menu {
2308 let cursor_position = new_cursor_position.to_offset(buffer);
2309 let (word_range, kind) =
2310 buffer.surrounding_word(completion_menu.initial_position, true);
2311 if kind == Some(CharKind::Word)
2312 && word_range.to_inclusive().contains(&cursor_position)
2313 {
2314 let mut completion_menu = completion_menu.clone();
2315 drop(context_menu);
2316
2317 let query = Self::completion_query(buffer, cursor_position);
2318 cx.spawn(async move |this, cx| {
2319 completion_menu
2320 .filter(query.as_deref(), cx.background_executor().clone())
2321 .await;
2322
2323 this.update(cx, |this, cx| {
2324 let mut context_menu = this.context_menu.borrow_mut();
2325 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2326 else {
2327 return;
2328 };
2329
2330 if menu.id > completion_menu.id {
2331 return;
2332 }
2333
2334 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2335 drop(context_menu);
2336 cx.notify();
2337 })
2338 })
2339 .detach();
2340
2341 if show_completions {
2342 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2343 }
2344 } else {
2345 drop(context_menu);
2346 self.hide_context_menu(window, cx);
2347 }
2348 } else {
2349 drop(context_menu);
2350 }
2351
2352 hide_hover(self, cx);
2353
2354 if old_cursor_position.to_display_point(&display_map).row()
2355 != new_cursor_position.to_display_point(&display_map).row()
2356 {
2357 self.available_code_actions.take();
2358 }
2359 self.refresh_code_actions(window, cx);
2360 self.refresh_document_highlights(cx);
2361 self.refresh_selected_text_highlights(window, cx);
2362 refresh_matching_bracket_highlights(self, window, cx);
2363 self.update_visible_inline_completion(window, cx);
2364 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2365 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2366 if self.git_blame_inline_enabled {
2367 self.start_inline_blame_timer(window, cx);
2368 }
2369 }
2370
2371 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2372 cx.emit(EditorEvent::SelectionsChanged { local });
2373
2374 let selections = &self.selections.disjoint;
2375 if selections.len() == 1 {
2376 cx.emit(SearchEvent::ActiveMatchChanged)
2377 }
2378 if local {
2379 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2380 let inmemory_selections = selections
2381 .iter()
2382 .map(|s| {
2383 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2384 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2385 })
2386 .collect();
2387 self.update_restoration_data(cx, |data| {
2388 data.selections = inmemory_selections;
2389 });
2390
2391 if WorkspaceSettings::get(None, cx).restore_on_startup
2392 != RestoreOnStartupBehavior::None
2393 {
2394 if let Some(workspace_id) =
2395 self.workspace.as_ref().and_then(|workspace| workspace.1)
2396 {
2397 let snapshot = self.buffer().read(cx).snapshot(cx);
2398 let selections = selections.clone();
2399 let background_executor = cx.background_executor().clone();
2400 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2401 self.serialize_selections = cx.background_spawn(async move {
2402 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2403 let db_selections = selections
2404 .iter()
2405 .map(|selection| {
2406 (
2407 selection.start.to_offset(&snapshot),
2408 selection.end.to_offset(&snapshot),
2409 )
2410 })
2411 .collect();
2412
2413 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2414 .await
2415 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2416 .log_err();
2417 });
2418 }
2419 }
2420 }
2421 }
2422
2423 cx.notify();
2424 }
2425
2426 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2427 use text::ToOffset as _;
2428 use text::ToPoint as _;
2429
2430 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2431 return;
2432 }
2433
2434 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2435 return;
2436 };
2437
2438 let snapshot = singleton.read(cx).snapshot();
2439 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2440 let display_snapshot = display_map.snapshot(cx);
2441
2442 display_snapshot
2443 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2444 .map(|fold| {
2445 fold.range.start.text_anchor.to_point(&snapshot)
2446 ..fold.range.end.text_anchor.to_point(&snapshot)
2447 })
2448 .collect()
2449 });
2450 self.update_restoration_data(cx, |data| {
2451 data.folds = inmemory_folds;
2452 });
2453
2454 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2455 return;
2456 };
2457 let background_executor = cx.background_executor().clone();
2458 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2459 let db_folds = self.display_map.update(cx, |display_map, cx| {
2460 display_map
2461 .snapshot(cx)
2462 .folds_in_range(0..snapshot.len())
2463 .map(|fold| {
2464 (
2465 fold.range.start.text_anchor.to_offset(&snapshot),
2466 fold.range.end.text_anchor.to_offset(&snapshot),
2467 )
2468 })
2469 .collect()
2470 });
2471 self.serialize_folds = cx.background_spawn(async move {
2472 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2473 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2474 .await
2475 .with_context(|| {
2476 format!(
2477 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2478 )
2479 })
2480 .log_err();
2481 });
2482 }
2483
2484 pub fn sync_selections(
2485 &mut self,
2486 other: Entity<Editor>,
2487 cx: &mut Context<Self>,
2488 ) -> gpui::Subscription {
2489 let other_selections = other.read(cx).selections.disjoint.to_vec();
2490 self.selections.change_with(cx, |selections| {
2491 selections.select_anchors(other_selections);
2492 });
2493
2494 let other_subscription =
2495 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2496 EditorEvent::SelectionsChanged { local: true } => {
2497 let other_selections = other.read(cx).selections.disjoint.to_vec();
2498 if other_selections.is_empty() {
2499 return;
2500 }
2501 this.selections.change_with(cx, |selections| {
2502 selections.select_anchors(other_selections);
2503 });
2504 }
2505 _ => {}
2506 });
2507
2508 let this_subscription =
2509 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2510 EditorEvent::SelectionsChanged { local: true } => {
2511 let these_selections = this.selections.disjoint.to_vec();
2512 if these_selections.is_empty() {
2513 return;
2514 }
2515 other.update(cx, |other_editor, cx| {
2516 other_editor.selections.change_with(cx, |selections| {
2517 selections.select_anchors(these_selections);
2518 })
2519 });
2520 }
2521 _ => {}
2522 });
2523
2524 Subscription::join(other_subscription, this_subscription)
2525 }
2526
2527 pub fn change_selections<R>(
2528 &mut self,
2529 autoscroll: Option<Autoscroll>,
2530 window: &mut Window,
2531 cx: &mut Context<Self>,
2532 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2533 ) -> R {
2534 self.change_selections_inner(autoscroll, true, window, cx, change)
2535 }
2536
2537 fn change_selections_inner<R>(
2538 &mut self,
2539 autoscroll: Option<Autoscroll>,
2540 request_completions: bool,
2541 window: &mut Window,
2542 cx: &mut Context<Self>,
2543 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2544 ) -> R {
2545 let old_cursor_position = self.selections.newest_anchor().head();
2546 self.push_to_selection_history();
2547
2548 let (changed, result) = self.selections.change_with(cx, change);
2549
2550 if changed {
2551 if let Some(autoscroll) = autoscroll {
2552 self.request_autoscroll(autoscroll, cx);
2553 }
2554 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2555
2556 if self.should_open_signature_help_automatically(
2557 &old_cursor_position,
2558 self.signature_help_state.backspace_pressed(),
2559 cx,
2560 ) {
2561 self.show_signature_help(&ShowSignatureHelp, window, cx);
2562 }
2563 self.signature_help_state.set_backspace_pressed(false);
2564 }
2565
2566 result
2567 }
2568
2569 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2570 where
2571 I: IntoIterator<Item = (Range<S>, T)>,
2572 S: ToOffset,
2573 T: Into<Arc<str>>,
2574 {
2575 if self.read_only(cx) {
2576 return;
2577 }
2578
2579 self.buffer
2580 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2581 }
2582
2583 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2584 where
2585 I: IntoIterator<Item = (Range<S>, T)>,
2586 S: ToOffset,
2587 T: Into<Arc<str>>,
2588 {
2589 if self.read_only(cx) {
2590 return;
2591 }
2592
2593 self.buffer.update(cx, |buffer, cx| {
2594 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2595 });
2596 }
2597
2598 pub fn edit_with_block_indent<I, S, T>(
2599 &mut self,
2600 edits: I,
2601 original_indent_columns: Vec<Option<u32>>,
2602 cx: &mut Context<Self>,
2603 ) where
2604 I: IntoIterator<Item = (Range<S>, T)>,
2605 S: ToOffset,
2606 T: Into<Arc<str>>,
2607 {
2608 if self.read_only(cx) {
2609 return;
2610 }
2611
2612 self.buffer.update(cx, |buffer, cx| {
2613 buffer.edit(
2614 edits,
2615 Some(AutoindentMode::Block {
2616 original_indent_columns,
2617 }),
2618 cx,
2619 )
2620 });
2621 }
2622
2623 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2624 self.hide_context_menu(window, cx);
2625
2626 match phase {
2627 SelectPhase::Begin {
2628 position,
2629 add,
2630 click_count,
2631 } => self.begin_selection(position, add, click_count, window, cx),
2632 SelectPhase::BeginColumnar {
2633 position,
2634 goal_column,
2635 reset,
2636 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2637 SelectPhase::Extend {
2638 position,
2639 click_count,
2640 } => self.extend_selection(position, click_count, window, cx),
2641 SelectPhase::Update {
2642 position,
2643 goal_column,
2644 scroll_delta,
2645 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2646 SelectPhase::End => self.end_selection(window, cx),
2647 }
2648 }
2649
2650 fn extend_selection(
2651 &mut self,
2652 position: DisplayPoint,
2653 click_count: usize,
2654 window: &mut Window,
2655 cx: &mut Context<Self>,
2656 ) {
2657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2658 let tail = self.selections.newest::<usize>(cx).tail();
2659 self.begin_selection(position, false, click_count, window, cx);
2660
2661 let position = position.to_offset(&display_map, Bias::Left);
2662 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2663
2664 let mut pending_selection = self
2665 .selections
2666 .pending_anchor()
2667 .expect("extend_selection not called with pending selection");
2668 if position >= tail {
2669 pending_selection.start = tail_anchor;
2670 } else {
2671 pending_selection.end = tail_anchor;
2672 pending_selection.reversed = true;
2673 }
2674
2675 let mut pending_mode = self.selections.pending_mode().unwrap();
2676 match &mut pending_mode {
2677 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2678 _ => {}
2679 }
2680
2681 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2682 s.set_pending(pending_selection, pending_mode)
2683 });
2684 }
2685
2686 fn begin_selection(
2687 &mut self,
2688 position: DisplayPoint,
2689 add: bool,
2690 click_count: usize,
2691 window: &mut Window,
2692 cx: &mut Context<Self>,
2693 ) {
2694 if !self.focus_handle.is_focused(window) {
2695 self.last_focused_descendant = None;
2696 window.focus(&self.focus_handle);
2697 }
2698
2699 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2700 let buffer = &display_map.buffer_snapshot;
2701 let newest_selection = self.selections.newest_anchor().clone();
2702 let position = display_map.clip_point(position, Bias::Left);
2703
2704 let start;
2705 let end;
2706 let mode;
2707 let mut auto_scroll;
2708 match click_count {
2709 1 => {
2710 start = buffer.anchor_before(position.to_point(&display_map));
2711 end = start;
2712 mode = SelectMode::Character;
2713 auto_scroll = true;
2714 }
2715 2 => {
2716 let range = movement::surrounding_word(&display_map, position);
2717 start = buffer.anchor_before(range.start.to_point(&display_map));
2718 end = buffer.anchor_before(range.end.to_point(&display_map));
2719 mode = SelectMode::Word(start..end);
2720 auto_scroll = true;
2721 }
2722 3 => {
2723 let position = display_map
2724 .clip_point(position, Bias::Left)
2725 .to_point(&display_map);
2726 let line_start = display_map.prev_line_boundary(position).0;
2727 let next_line_start = buffer.clip_point(
2728 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2729 Bias::Left,
2730 );
2731 start = buffer.anchor_before(line_start);
2732 end = buffer.anchor_before(next_line_start);
2733 mode = SelectMode::Line(start..end);
2734 auto_scroll = true;
2735 }
2736 _ => {
2737 start = buffer.anchor_before(0);
2738 end = buffer.anchor_before(buffer.len());
2739 mode = SelectMode::All;
2740 auto_scroll = false;
2741 }
2742 }
2743 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2744
2745 let point_to_delete: Option<usize> = {
2746 let selected_points: Vec<Selection<Point>> =
2747 self.selections.disjoint_in_range(start..end, cx);
2748
2749 if !add || click_count > 1 {
2750 None
2751 } else if !selected_points.is_empty() {
2752 Some(selected_points[0].id)
2753 } else {
2754 let clicked_point_already_selected =
2755 self.selections.disjoint.iter().find(|selection| {
2756 selection.start.to_point(buffer) == start.to_point(buffer)
2757 || selection.end.to_point(buffer) == end.to_point(buffer)
2758 });
2759
2760 clicked_point_already_selected.map(|selection| selection.id)
2761 }
2762 };
2763
2764 let selections_count = self.selections.count();
2765
2766 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2767 if let Some(point_to_delete) = point_to_delete {
2768 s.delete(point_to_delete);
2769
2770 if selections_count == 1 {
2771 s.set_pending_anchor_range(start..end, mode);
2772 }
2773 } else {
2774 if !add {
2775 s.clear_disjoint();
2776 } else if click_count > 1 {
2777 s.delete(newest_selection.id)
2778 }
2779
2780 s.set_pending_anchor_range(start..end, mode);
2781 }
2782 });
2783 }
2784
2785 fn begin_columnar_selection(
2786 &mut self,
2787 position: DisplayPoint,
2788 goal_column: u32,
2789 reset: bool,
2790 window: &mut Window,
2791 cx: &mut Context<Self>,
2792 ) {
2793 if !self.focus_handle.is_focused(window) {
2794 self.last_focused_descendant = None;
2795 window.focus(&self.focus_handle);
2796 }
2797
2798 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2799
2800 if reset {
2801 let pointer_position = display_map
2802 .buffer_snapshot
2803 .anchor_before(position.to_point(&display_map));
2804
2805 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2806 s.clear_disjoint();
2807 s.set_pending_anchor_range(
2808 pointer_position..pointer_position,
2809 SelectMode::Character,
2810 );
2811 });
2812 }
2813
2814 let tail = self.selections.newest::<Point>(cx).tail();
2815 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2816
2817 if !reset {
2818 self.select_columns(
2819 tail.to_display_point(&display_map),
2820 position,
2821 goal_column,
2822 &display_map,
2823 window,
2824 cx,
2825 );
2826 }
2827 }
2828
2829 fn update_selection(
2830 &mut self,
2831 position: DisplayPoint,
2832 goal_column: u32,
2833 scroll_delta: gpui::Point<f32>,
2834 window: &mut Window,
2835 cx: &mut Context<Self>,
2836 ) {
2837 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2838
2839 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2840 let tail = tail.to_display_point(&display_map);
2841 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2842 } else if let Some(mut pending) = self.selections.pending_anchor() {
2843 let buffer = self.buffer.read(cx).snapshot(cx);
2844 let head;
2845 let tail;
2846 let mode = self.selections.pending_mode().unwrap();
2847 match &mode {
2848 SelectMode::Character => {
2849 head = position.to_point(&display_map);
2850 tail = pending.tail().to_point(&buffer);
2851 }
2852 SelectMode::Word(original_range) => {
2853 let original_display_range = original_range.start.to_display_point(&display_map)
2854 ..original_range.end.to_display_point(&display_map);
2855 let original_buffer_range = original_display_range.start.to_point(&display_map)
2856 ..original_display_range.end.to_point(&display_map);
2857 if movement::is_inside_word(&display_map, position)
2858 || original_display_range.contains(&position)
2859 {
2860 let word_range = movement::surrounding_word(&display_map, position);
2861 if word_range.start < original_display_range.start {
2862 head = word_range.start.to_point(&display_map);
2863 } else {
2864 head = word_range.end.to_point(&display_map);
2865 }
2866 } else {
2867 head = position.to_point(&display_map);
2868 }
2869
2870 if head <= original_buffer_range.start {
2871 tail = original_buffer_range.end;
2872 } else {
2873 tail = original_buffer_range.start;
2874 }
2875 }
2876 SelectMode::Line(original_range) => {
2877 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2878
2879 let position = display_map
2880 .clip_point(position, Bias::Left)
2881 .to_point(&display_map);
2882 let line_start = display_map.prev_line_boundary(position).0;
2883 let next_line_start = buffer.clip_point(
2884 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2885 Bias::Left,
2886 );
2887
2888 if line_start < original_range.start {
2889 head = line_start
2890 } else {
2891 head = next_line_start
2892 }
2893
2894 if head <= original_range.start {
2895 tail = original_range.end;
2896 } else {
2897 tail = original_range.start;
2898 }
2899 }
2900 SelectMode::All => {
2901 return;
2902 }
2903 };
2904
2905 if head < tail {
2906 pending.start = buffer.anchor_before(head);
2907 pending.end = buffer.anchor_before(tail);
2908 pending.reversed = true;
2909 } else {
2910 pending.start = buffer.anchor_before(tail);
2911 pending.end = buffer.anchor_before(head);
2912 pending.reversed = false;
2913 }
2914
2915 self.change_selections(None, window, cx, |s| {
2916 s.set_pending(pending, mode);
2917 });
2918 } else {
2919 log::error!("update_selection dispatched with no pending selection");
2920 return;
2921 }
2922
2923 self.apply_scroll_delta(scroll_delta, window, cx);
2924 cx.notify();
2925 }
2926
2927 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2928 self.columnar_selection_tail.take();
2929 if self.selections.pending_anchor().is_some() {
2930 let selections = self.selections.all::<usize>(cx);
2931 self.change_selections(None, window, cx, |s| {
2932 s.select(selections);
2933 s.clear_pending();
2934 });
2935 }
2936 }
2937
2938 fn select_columns(
2939 &mut self,
2940 tail: DisplayPoint,
2941 head: DisplayPoint,
2942 goal_column: u32,
2943 display_map: &DisplaySnapshot,
2944 window: &mut Window,
2945 cx: &mut Context<Self>,
2946 ) {
2947 let start_row = cmp::min(tail.row(), head.row());
2948 let end_row = cmp::max(tail.row(), head.row());
2949 let start_column = cmp::min(tail.column(), goal_column);
2950 let end_column = cmp::max(tail.column(), goal_column);
2951 let reversed = start_column < tail.column();
2952
2953 let selection_ranges = (start_row.0..=end_row.0)
2954 .map(DisplayRow)
2955 .filter_map(|row| {
2956 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2957 let start = display_map
2958 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2959 .to_point(display_map);
2960 let end = display_map
2961 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2962 .to_point(display_map);
2963 if reversed {
2964 Some(end..start)
2965 } else {
2966 Some(start..end)
2967 }
2968 } else {
2969 None
2970 }
2971 })
2972 .collect::<Vec<_>>();
2973
2974 self.change_selections(None, window, cx, |s| {
2975 s.select_ranges(selection_ranges);
2976 });
2977 cx.notify();
2978 }
2979
2980 pub fn has_pending_nonempty_selection(&self) -> bool {
2981 let pending_nonempty_selection = match self.selections.pending_anchor() {
2982 Some(Selection { start, end, .. }) => start != end,
2983 None => false,
2984 };
2985
2986 pending_nonempty_selection
2987 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2988 }
2989
2990 pub fn has_pending_selection(&self) -> bool {
2991 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2992 }
2993
2994 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2995 self.selection_mark_mode = false;
2996
2997 if self.clear_expanded_diff_hunks(cx) {
2998 cx.notify();
2999 return;
3000 }
3001 if self.dismiss_menus_and_popups(true, window, cx) {
3002 return;
3003 }
3004
3005 if self.mode == EditorMode::Full
3006 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3007 {
3008 return;
3009 }
3010
3011 cx.propagate();
3012 }
3013
3014 pub fn dismiss_menus_and_popups(
3015 &mut self,
3016 is_user_requested: bool,
3017 window: &mut Window,
3018 cx: &mut Context<Self>,
3019 ) -> bool {
3020 if self.take_rename(false, window, cx).is_some() {
3021 return true;
3022 }
3023
3024 if hide_hover(self, cx) {
3025 return true;
3026 }
3027
3028 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3029 return true;
3030 }
3031
3032 if self.hide_context_menu(window, cx).is_some() {
3033 return true;
3034 }
3035
3036 if self.mouse_context_menu.take().is_some() {
3037 return true;
3038 }
3039
3040 if is_user_requested && self.discard_inline_completion(true, cx) {
3041 return true;
3042 }
3043
3044 if self.snippet_stack.pop().is_some() {
3045 return true;
3046 }
3047
3048 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3049 self.dismiss_diagnostics(cx);
3050 return true;
3051 }
3052
3053 false
3054 }
3055
3056 fn linked_editing_ranges_for(
3057 &self,
3058 selection: Range<text::Anchor>,
3059 cx: &App,
3060 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3061 if self.linked_edit_ranges.is_empty() {
3062 return None;
3063 }
3064 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3065 selection.end.buffer_id.and_then(|end_buffer_id| {
3066 if selection.start.buffer_id != Some(end_buffer_id) {
3067 return None;
3068 }
3069 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3070 let snapshot = buffer.read(cx).snapshot();
3071 self.linked_edit_ranges
3072 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3073 .map(|ranges| (ranges, snapshot, buffer))
3074 })?;
3075 use text::ToOffset as TO;
3076 // find offset from the start of current range to current cursor position
3077 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3078
3079 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3080 let start_difference = start_offset - start_byte_offset;
3081 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3082 let end_difference = end_offset - start_byte_offset;
3083 // Current range has associated linked ranges.
3084 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3085 for range in linked_ranges.iter() {
3086 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3087 let end_offset = start_offset + end_difference;
3088 let start_offset = start_offset + start_difference;
3089 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3090 continue;
3091 }
3092 if self.selections.disjoint_anchor_ranges().any(|s| {
3093 if s.start.buffer_id != selection.start.buffer_id
3094 || s.end.buffer_id != selection.end.buffer_id
3095 {
3096 return false;
3097 }
3098 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3099 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3100 }) {
3101 continue;
3102 }
3103 let start = buffer_snapshot.anchor_after(start_offset);
3104 let end = buffer_snapshot.anchor_after(end_offset);
3105 linked_edits
3106 .entry(buffer.clone())
3107 .or_default()
3108 .push(start..end);
3109 }
3110 Some(linked_edits)
3111 }
3112
3113 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3114 let text: Arc<str> = text.into();
3115
3116 if self.read_only(cx) {
3117 return;
3118 }
3119
3120 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3121
3122 let selections = self.selections.all_adjusted(cx);
3123 let mut bracket_inserted = false;
3124 let mut edits = Vec::new();
3125 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3126 let mut new_selections = Vec::with_capacity(selections.len());
3127 let mut new_autoclose_regions = Vec::new();
3128 let snapshot = self.buffer.read(cx).read(cx);
3129
3130 for (selection, autoclose_region) in
3131 self.selections_with_autoclose_regions(selections, &snapshot)
3132 {
3133 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3134 // Determine if the inserted text matches the opening or closing
3135 // bracket of any of this language's bracket pairs.
3136 let mut bracket_pair = None;
3137 let mut is_bracket_pair_start = false;
3138 let mut is_bracket_pair_end = false;
3139 if !text.is_empty() {
3140 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3141 // and they are removing the character that triggered IME popup.
3142 for (pair, enabled) in scope.brackets() {
3143 if !pair.close && !pair.surround {
3144 continue;
3145 }
3146
3147 if enabled && pair.start.ends_with(text.as_ref()) {
3148 let prefix_len = pair.start.len() - text.len();
3149 let preceding_text_matches_prefix = prefix_len == 0
3150 || (selection.start.column >= (prefix_len as u32)
3151 && snapshot.contains_str_at(
3152 Point::new(
3153 selection.start.row,
3154 selection.start.column - (prefix_len as u32),
3155 ),
3156 &pair.start[..prefix_len],
3157 ));
3158 if preceding_text_matches_prefix {
3159 bracket_pair = Some(pair.clone());
3160 is_bracket_pair_start = true;
3161 break;
3162 }
3163 }
3164 if pair.end.as_str() == text.as_ref() {
3165 bracket_pair = Some(pair.clone());
3166 is_bracket_pair_end = true;
3167 break;
3168 }
3169 }
3170 }
3171
3172 if let Some(bracket_pair) = bracket_pair {
3173 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3174 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3175 let auto_surround =
3176 self.use_auto_surround && snapshot_settings.use_auto_surround;
3177 if selection.is_empty() {
3178 if is_bracket_pair_start {
3179 // If the inserted text is a suffix of an opening bracket and the
3180 // selection is preceded by the rest of the opening bracket, then
3181 // insert the closing bracket.
3182 let following_text_allows_autoclose = snapshot
3183 .chars_at(selection.start)
3184 .next()
3185 .map_or(true, |c| scope.should_autoclose_before(c));
3186
3187 let preceding_text_allows_autoclose = selection.start.column == 0
3188 || snapshot.reversed_chars_at(selection.start).next().map_or(
3189 true,
3190 |c| {
3191 bracket_pair.start != bracket_pair.end
3192 || !snapshot
3193 .char_classifier_at(selection.start)
3194 .is_word(c)
3195 },
3196 );
3197
3198 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3199 && bracket_pair.start.len() == 1
3200 {
3201 let target = bracket_pair.start.chars().next().unwrap();
3202 let current_line_count = snapshot
3203 .reversed_chars_at(selection.start)
3204 .take_while(|&c| c != '\n')
3205 .filter(|&c| c == target)
3206 .count();
3207 current_line_count % 2 == 1
3208 } else {
3209 false
3210 };
3211
3212 if autoclose
3213 && bracket_pair.close
3214 && following_text_allows_autoclose
3215 && preceding_text_allows_autoclose
3216 && !is_closing_quote
3217 {
3218 let anchor = snapshot.anchor_before(selection.end);
3219 new_selections.push((selection.map(|_| anchor), text.len()));
3220 new_autoclose_regions.push((
3221 anchor,
3222 text.len(),
3223 selection.id,
3224 bracket_pair.clone(),
3225 ));
3226 edits.push((
3227 selection.range(),
3228 format!("{}{}", text, bracket_pair.end).into(),
3229 ));
3230 bracket_inserted = true;
3231 continue;
3232 }
3233 }
3234
3235 if let Some(region) = autoclose_region {
3236 // If the selection is followed by an auto-inserted closing bracket,
3237 // then don't insert that closing bracket again; just move the selection
3238 // past the closing bracket.
3239 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3240 && text.as_ref() == region.pair.end.as_str();
3241 if should_skip {
3242 let anchor = snapshot.anchor_after(selection.end);
3243 new_selections
3244 .push((selection.map(|_| anchor), region.pair.end.len()));
3245 continue;
3246 }
3247 }
3248
3249 let always_treat_brackets_as_autoclosed = snapshot
3250 .language_settings_at(selection.start, cx)
3251 .always_treat_brackets_as_autoclosed;
3252 if always_treat_brackets_as_autoclosed
3253 && is_bracket_pair_end
3254 && snapshot.contains_str_at(selection.end, text.as_ref())
3255 {
3256 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3257 // and the inserted text is a closing bracket and the selection is followed
3258 // by the closing bracket then move the selection past the closing bracket.
3259 let anchor = snapshot.anchor_after(selection.end);
3260 new_selections.push((selection.map(|_| anchor), text.len()));
3261 continue;
3262 }
3263 }
3264 // If an opening bracket is 1 character long and is typed while
3265 // text is selected, then surround that text with the bracket pair.
3266 else if auto_surround
3267 && bracket_pair.surround
3268 && is_bracket_pair_start
3269 && bracket_pair.start.chars().count() == 1
3270 {
3271 edits.push((selection.start..selection.start, text.clone()));
3272 edits.push((
3273 selection.end..selection.end,
3274 bracket_pair.end.as_str().into(),
3275 ));
3276 bracket_inserted = true;
3277 new_selections.push((
3278 Selection {
3279 id: selection.id,
3280 start: snapshot.anchor_after(selection.start),
3281 end: snapshot.anchor_before(selection.end),
3282 reversed: selection.reversed,
3283 goal: selection.goal,
3284 },
3285 0,
3286 ));
3287 continue;
3288 }
3289 }
3290 }
3291
3292 if self.auto_replace_emoji_shortcode
3293 && selection.is_empty()
3294 && text.as_ref().ends_with(':')
3295 {
3296 if let Some(possible_emoji_short_code) =
3297 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3298 {
3299 if !possible_emoji_short_code.is_empty() {
3300 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3301 let emoji_shortcode_start = Point::new(
3302 selection.start.row,
3303 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3304 );
3305
3306 // Remove shortcode from buffer
3307 edits.push((
3308 emoji_shortcode_start..selection.start,
3309 "".to_string().into(),
3310 ));
3311 new_selections.push((
3312 Selection {
3313 id: selection.id,
3314 start: snapshot.anchor_after(emoji_shortcode_start),
3315 end: snapshot.anchor_before(selection.start),
3316 reversed: selection.reversed,
3317 goal: selection.goal,
3318 },
3319 0,
3320 ));
3321
3322 // Insert emoji
3323 let selection_start_anchor = snapshot.anchor_after(selection.start);
3324 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3325 edits.push((selection.start..selection.end, emoji.to_string().into()));
3326
3327 continue;
3328 }
3329 }
3330 }
3331 }
3332
3333 // If not handling any auto-close operation, then just replace the selected
3334 // text with the given input and move the selection to the end of the
3335 // newly inserted text.
3336 let anchor = snapshot.anchor_after(selection.end);
3337 if !self.linked_edit_ranges.is_empty() {
3338 let start_anchor = snapshot.anchor_before(selection.start);
3339
3340 let is_word_char = text.chars().next().map_or(true, |char| {
3341 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3342 classifier.is_word(char)
3343 });
3344
3345 if is_word_char {
3346 if let Some(ranges) = self
3347 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3348 {
3349 for (buffer, edits) in ranges {
3350 linked_edits
3351 .entry(buffer.clone())
3352 .or_default()
3353 .extend(edits.into_iter().map(|range| (range, text.clone())));
3354 }
3355 }
3356 }
3357 }
3358
3359 new_selections.push((selection.map(|_| anchor), 0));
3360 edits.push((selection.start..selection.end, text.clone()));
3361 }
3362
3363 drop(snapshot);
3364
3365 self.transact(window, cx, |this, window, cx| {
3366 let initial_buffer_versions =
3367 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3368
3369 this.buffer.update(cx, |buffer, cx| {
3370 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3371 });
3372 for (buffer, edits) in linked_edits {
3373 buffer.update(cx, |buffer, cx| {
3374 let snapshot = buffer.snapshot();
3375 let edits = edits
3376 .into_iter()
3377 .map(|(range, text)| {
3378 use text::ToPoint as TP;
3379 let end_point = TP::to_point(&range.end, &snapshot);
3380 let start_point = TP::to_point(&range.start, &snapshot);
3381 (start_point..end_point, text)
3382 })
3383 .sorted_by_key(|(range, _)| range.start);
3384 buffer.edit(edits, None, cx);
3385 })
3386 }
3387 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3388 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3389 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3390 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3391 .zip(new_selection_deltas)
3392 .map(|(selection, delta)| Selection {
3393 id: selection.id,
3394 start: selection.start + delta,
3395 end: selection.end + delta,
3396 reversed: selection.reversed,
3397 goal: SelectionGoal::None,
3398 })
3399 .collect::<Vec<_>>();
3400
3401 let mut i = 0;
3402 for (position, delta, selection_id, pair) in new_autoclose_regions {
3403 let position = position.to_offset(&map.buffer_snapshot) + delta;
3404 let start = map.buffer_snapshot.anchor_before(position);
3405 let end = map.buffer_snapshot.anchor_after(position);
3406 while let Some(existing_state) = this.autoclose_regions.get(i) {
3407 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3408 Ordering::Less => i += 1,
3409 Ordering::Greater => break,
3410 Ordering::Equal => {
3411 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3412 Ordering::Less => i += 1,
3413 Ordering::Equal => break,
3414 Ordering::Greater => break,
3415 }
3416 }
3417 }
3418 }
3419 this.autoclose_regions.insert(
3420 i,
3421 AutocloseRegion {
3422 selection_id,
3423 range: start..end,
3424 pair,
3425 },
3426 );
3427 }
3428
3429 let had_active_inline_completion = this.has_active_inline_completion();
3430 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3431 s.select(new_selections)
3432 });
3433
3434 if !bracket_inserted {
3435 if let Some(on_type_format_task) =
3436 this.trigger_on_type_formatting(text.to_string(), window, cx)
3437 {
3438 on_type_format_task.detach_and_log_err(cx);
3439 }
3440 }
3441
3442 let editor_settings = EditorSettings::get_global(cx);
3443 if bracket_inserted
3444 && (editor_settings.auto_signature_help
3445 || editor_settings.show_signature_help_after_edits)
3446 {
3447 this.show_signature_help(&ShowSignatureHelp, window, cx);
3448 }
3449
3450 let trigger_in_words =
3451 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3452 if this.hard_wrap.is_some() {
3453 let latest: Range<Point> = this.selections.newest(cx).range();
3454 if latest.is_empty()
3455 && this
3456 .buffer()
3457 .read(cx)
3458 .snapshot(cx)
3459 .line_len(MultiBufferRow(latest.start.row))
3460 == latest.start.column
3461 {
3462 this.rewrap_impl(
3463 RewrapOptions {
3464 override_language_settings: true,
3465 preserve_existing_whitespace: true,
3466 },
3467 cx,
3468 )
3469 }
3470 }
3471 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3472 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3473 this.refresh_inline_completion(true, false, window, cx);
3474 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3475 });
3476 }
3477
3478 fn find_possible_emoji_shortcode_at_position(
3479 snapshot: &MultiBufferSnapshot,
3480 position: Point,
3481 ) -> Option<String> {
3482 let mut chars = Vec::new();
3483 let mut found_colon = false;
3484 for char in snapshot.reversed_chars_at(position).take(100) {
3485 // Found a possible emoji shortcode in the middle of the buffer
3486 if found_colon {
3487 if char.is_whitespace() {
3488 chars.reverse();
3489 return Some(chars.iter().collect());
3490 }
3491 // If the previous character is not a whitespace, we are in the middle of a word
3492 // and we only want to complete the shortcode if the word is made up of other emojis
3493 let mut containing_word = String::new();
3494 for ch in snapshot
3495 .reversed_chars_at(position)
3496 .skip(chars.len() + 1)
3497 .take(100)
3498 {
3499 if ch.is_whitespace() {
3500 break;
3501 }
3502 containing_word.push(ch);
3503 }
3504 let containing_word = containing_word.chars().rev().collect::<String>();
3505 if util::word_consists_of_emojis(containing_word.as_str()) {
3506 chars.reverse();
3507 return Some(chars.iter().collect());
3508 }
3509 }
3510
3511 if char.is_whitespace() || !char.is_ascii() {
3512 return None;
3513 }
3514 if char == ':' {
3515 found_colon = true;
3516 } else {
3517 chars.push(char);
3518 }
3519 }
3520 // Found a possible emoji shortcode at the beginning of the buffer
3521 chars.reverse();
3522 Some(chars.iter().collect())
3523 }
3524
3525 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3526 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3527 self.transact(window, cx, |this, window, cx| {
3528 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3529 let selections = this.selections.all::<usize>(cx);
3530 let multi_buffer = this.buffer.read(cx);
3531 let buffer = multi_buffer.snapshot(cx);
3532 selections
3533 .iter()
3534 .map(|selection| {
3535 let start_point = selection.start.to_point(&buffer);
3536 let mut indent =
3537 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3538 indent.len = cmp::min(indent.len, start_point.column);
3539 let start = selection.start;
3540 let end = selection.end;
3541 let selection_is_empty = start == end;
3542 let language_scope = buffer.language_scope_at(start);
3543 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3544 &language_scope
3545 {
3546 let insert_extra_newline =
3547 insert_extra_newline_brackets(&buffer, start..end, language)
3548 || insert_extra_newline_tree_sitter(&buffer, start..end);
3549
3550 // Comment extension on newline is allowed only for cursor selections
3551 let comment_delimiter = maybe!({
3552 if !selection_is_empty {
3553 return None;
3554 }
3555
3556 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3557 return None;
3558 }
3559
3560 let delimiters = language.line_comment_prefixes();
3561 let max_len_of_delimiter =
3562 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3563 let (snapshot, range) =
3564 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3565
3566 let mut index_of_first_non_whitespace = 0;
3567 let comment_candidate = snapshot
3568 .chars_for_range(range)
3569 .skip_while(|c| {
3570 let should_skip = c.is_whitespace();
3571 if should_skip {
3572 index_of_first_non_whitespace += 1;
3573 }
3574 should_skip
3575 })
3576 .take(max_len_of_delimiter)
3577 .collect::<String>();
3578 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3579 comment_candidate.starts_with(comment_prefix.as_ref())
3580 })?;
3581 let cursor_is_placed_after_comment_marker =
3582 index_of_first_non_whitespace + comment_prefix.len()
3583 <= start_point.column as usize;
3584 if cursor_is_placed_after_comment_marker {
3585 Some(comment_prefix.clone())
3586 } else {
3587 None
3588 }
3589 });
3590 (comment_delimiter, insert_extra_newline)
3591 } else {
3592 (None, false)
3593 };
3594
3595 let capacity_for_delimiter = comment_delimiter
3596 .as_deref()
3597 .map(str::len)
3598 .unwrap_or_default();
3599 let mut new_text =
3600 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3601 new_text.push('\n');
3602 new_text.extend(indent.chars());
3603 if let Some(delimiter) = &comment_delimiter {
3604 new_text.push_str(delimiter);
3605 }
3606 if insert_extra_newline {
3607 new_text = new_text.repeat(2);
3608 }
3609
3610 let anchor = buffer.anchor_after(end);
3611 let new_selection = selection.map(|_| anchor);
3612 (
3613 (start..end, new_text),
3614 (insert_extra_newline, new_selection),
3615 )
3616 })
3617 .unzip()
3618 };
3619
3620 this.edit_with_autoindent(edits, cx);
3621 let buffer = this.buffer.read(cx).snapshot(cx);
3622 let new_selections = selection_fixup_info
3623 .into_iter()
3624 .map(|(extra_newline_inserted, new_selection)| {
3625 let mut cursor = new_selection.end.to_point(&buffer);
3626 if extra_newline_inserted {
3627 cursor.row -= 1;
3628 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3629 }
3630 new_selection.map(|_| cursor)
3631 })
3632 .collect();
3633
3634 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3635 s.select(new_selections)
3636 });
3637 this.refresh_inline_completion(true, false, window, cx);
3638 });
3639 }
3640
3641 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3642 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3643
3644 let buffer = self.buffer.read(cx);
3645 let snapshot = buffer.snapshot(cx);
3646
3647 let mut edits = Vec::new();
3648 let mut rows = Vec::new();
3649
3650 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3651 let cursor = selection.head();
3652 let row = cursor.row;
3653
3654 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3655
3656 let newline = "\n".to_string();
3657 edits.push((start_of_line..start_of_line, newline));
3658
3659 rows.push(row + rows_inserted as u32);
3660 }
3661
3662 self.transact(window, cx, |editor, window, cx| {
3663 editor.edit(edits, cx);
3664
3665 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3666 let mut index = 0;
3667 s.move_cursors_with(|map, _, _| {
3668 let row = rows[index];
3669 index += 1;
3670
3671 let point = Point::new(row, 0);
3672 let boundary = map.next_line_boundary(point).1;
3673 let clipped = map.clip_point(boundary, Bias::Left);
3674
3675 (clipped, SelectionGoal::None)
3676 });
3677 });
3678
3679 let mut indent_edits = Vec::new();
3680 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3681 for row in rows {
3682 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3683 for (row, indent) in indents {
3684 if indent.len == 0 {
3685 continue;
3686 }
3687
3688 let text = match indent.kind {
3689 IndentKind::Space => " ".repeat(indent.len as usize),
3690 IndentKind::Tab => "\t".repeat(indent.len as usize),
3691 };
3692 let point = Point::new(row.0, 0);
3693 indent_edits.push((point..point, text));
3694 }
3695 }
3696 editor.edit(indent_edits, cx);
3697 });
3698 }
3699
3700 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3701 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3702
3703 let buffer = self.buffer.read(cx);
3704 let snapshot = buffer.snapshot(cx);
3705
3706 let mut edits = Vec::new();
3707 let mut rows = Vec::new();
3708 let mut rows_inserted = 0;
3709
3710 for selection in self.selections.all_adjusted(cx) {
3711 let cursor = selection.head();
3712 let row = cursor.row;
3713
3714 let point = Point::new(row + 1, 0);
3715 let start_of_line = snapshot.clip_point(point, Bias::Left);
3716
3717 let newline = "\n".to_string();
3718 edits.push((start_of_line..start_of_line, newline));
3719
3720 rows_inserted += 1;
3721 rows.push(row + rows_inserted);
3722 }
3723
3724 self.transact(window, cx, |editor, window, cx| {
3725 editor.edit(edits, cx);
3726
3727 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3728 let mut index = 0;
3729 s.move_cursors_with(|map, _, _| {
3730 let row = rows[index];
3731 index += 1;
3732
3733 let point = Point::new(row, 0);
3734 let boundary = map.next_line_boundary(point).1;
3735 let clipped = map.clip_point(boundary, Bias::Left);
3736
3737 (clipped, SelectionGoal::None)
3738 });
3739 });
3740
3741 let mut indent_edits = Vec::new();
3742 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3743 for row in rows {
3744 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3745 for (row, indent) in indents {
3746 if indent.len == 0 {
3747 continue;
3748 }
3749
3750 let text = match indent.kind {
3751 IndentKind::Space => " ".repeat(indent.len as usize),
3752 IndentKind::Tab => "\t".repeat(indent.len as usize),
3753 };
3754 let point = Point::new(row.0, 0);
3755 indent_edits.push((point..point, text));
3756 }
3757 }
3758 editor.edit(indent_edits, cx);
3759 });
3760 }
3761
3762 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3763 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3764 original_indent_columns: Vec::new(),
3765 });
3766 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3767 }
3768
3769 fn insert_with_autoindent_mode(
3770 &mut self,
3771 text: &str,
3772 autoindent_mode: Option<AutoindentMode>,
3773 window: &mut Window,
3774 cx: &mut Context<Self>,
3775 ) {
3776 if self.read_only(cx) {
3777 return;
3778 }
3779
3780 let text: Arc<str> = text.into();
3781 self.transact(window, cx, |this, window, cx| {
3782 let old_selections = this.selections.all_adjusted(cx);
3783 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3784 let anchors = {
3785 let snapshot = buffer.read(cx);
3786 old_selections
3787 .iter()
3788 .map(|s| {
3789 let anchor = snapshot.anchor_after(s.head());
3790 s.map(|_| anchor)
3791 })
3792 .collect::<Vec<_>>()
3793 };
3794 buffer.edit(
3795 old_selections
3796 .iter()
3797 .map(|s| (s.start..s.end, text.clone())),
3798 autoindent_mode,
3799 cx,
3800 );
3801 anchors
3802 });
3803
3804 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3805 s.select_anchors(selection_anchors);
3806 });
3807
3808 cx.notify();
3809 });
3810 }
3811
3812 fn trigger_completion_on_input(
3813 &mut self,
3814 text: &str,
3815 trigger_in_words: bool,
3816 window: &mut Window,
3817 cx: &mut Context<Self>,
3818 ) {
3819 let ignore_completion_provider = self
3820 .context_menu
3821 .borrow()
3822 .as_ref()
3823 .map(|menu| match menu {
3824 CodeContextMenu::Completions(completions_menu) => {
3825 completions_menu.ignore_completion_provider
3826 }
3827 CodeContextMenu::CodeActions(_) => false,
3828 })
3829 .unwrap_or(false);
3830
3831 if ignore_completion_provider {
3832 self.show_word_completions(&ShowWordCompletions, window, cx);
3833 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3834 self.show_completions(
3835 &ShowCompletions {
3836 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3837 },
3838 window,
3839 cx,
3840 );
3841 } else {
3842 self.hide_context_menu(window, cx);
3843 }
3844 }
3845
3846 fn is_completion_trigger(
3847 &self,
3848 text: &str,
3849 trigger_in_words: bool,
3850 cx: &mut Context<Self>,
3851 ) -> bool {
3852 let position = self.selections.newest_anchor().head();
3853 let multibuffer = self.buffer.read(cx);
3854 let Some(buffer) = position
3855 .buffer_id
3856 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3857 else {
3858 return false;
3859 };
3860
3861 if let Some(completion_provider) = &self.completion_provider {
3862 completion_provider.is_completion_trigger(
3863 &buffer,
3864 position.text_anchor,
3865 text,
3866 trigger_in_words,
3867 cx,
3868 )
3869 } else {
3870 false
3871 }
3872 }
3873
3874 /// If any empty selections is touching the start of its innermost containing autoclose
3875 /// region, expand it to select the brackets.
3876 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3877 let selections = self.selections.all::<usize>(cx);
3878 let buffer = self.buffer.read(cx).read(cx);
3879 let new_selections = self
3880 .selections_with_autoclose_regions(selections, &buffer)
3881 .map(|(mut selection, region)| {
3882 if !selection.is_empty() {
3883 return selection;
3884 }
3885
3886 if let Some(region) = region {
3887 let mut range = region.range.to_offset(&buffer);
3888 if selection.start == range.start && range.start >= region.pair.start.len() {
3889 range.start -= region.pair.start.len();
3890 if buffer.contains_str_at(range.start, ®ion.pair.start)
3891 && buffer.contains_str_at(range.end, ®ion.pair.end)
3892 {
3893 range.end += region.pair.end.len();
3894 selection.start = range.start;
3895 selection.end = range.end;
3896
3897 return selection;
3898 }
3899 }
3900 }
3901
3902 let always_treat_brackets_as_autoclosed = buffer
3903 .language_settings_at(selection.start, cx)
3904 .always_treat_brackets_as_autoclosed;
3905
3906 if !always_treat_brackets_as_autoclosed {
3907 return selection;
3908 }
3909
3910 if let Some(scope) = buffer.language_scope_at(selection.start) {
3911 for (pair, enabled) in scope.brackets() {
3912 if !enabled || !pair.close {
3913 continue;
3914 }
3915
3916 if buffer.contains_str_at(selection.start, &pair.end) {
3917 let pair_start_len = pair.start.len();
3918 if buffer.contains_str_at(
3919 selection.start.saturating_sub(pair_start_len),
3920 &pair.start,
3921 ) {
3922 selection.start -= pair_start_len;
3923 selection.end += pair.end.len();
3924
3925 return selection;
3926 }
3927 }
3928 }
3929 }
3930
3931 selection
3932 })
3933 .collect();
3934
3935 drop(buffer);
3936 self.change_selections(None, window, cx, |selections| {
3937 selections.select(new_selections)
3938 });
3939 }
3940
3941 /// Iterate the given selections, and for each one, find the smallest surrounding
3942 /// autoclose region. This uses the ordering of the selections and the autoclose
3943 /// regions to avoid repeated comparisons.
3944 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3945 &'a self,
3946 selections: impl IntoIterator<Item = Selection<D>>,
3947 buffer: &'a MultiBufferSnapshot,
3948 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3949 let mut i = 0;
3950 let mut regions = self.autoclose_regions.as_slice();
3951 selections.into_iter().map(move |selection| {
3952 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3953
3954 let mut enclosing = None;
3955 while let Some(pair_state) = regions.get(i) {
3956 if pair_state.range.end.to_offset(buffer) < range.start {
3957 regions = ®ions[i + 1..];
3958 i = 0;
3959 } else if pair_state.range.start.to_offset(buffer) > range.end {
3960 break;
3961 } else {
3962 if pair_state.selection_id == selection.id {
3963 enclosing = Some(pair_state);
3964 }
3965 i += 1;
3966 }
3967 }
3968
3969 (selection, enclosing)
3970 })
3971 }
3972
3973 /// Remove any autoclose regions that no longer contain their selection.
3974 fn invalidate_autoclose_regions(
3975 &mut self,
3976 mut selections: &[Selection<Anchor>],
3977 buffer: &MultiBufferSnapshot,
3978 ) {
3979 self.autoclose_regions.retain(|state| {
3980 let mut i = 0;
3981 while let Some(selection) = selections.get(i) {
3982 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3983 selections = &selections[1..];
3984 continue;
3985 }
3986 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3987 break;
3988 }
3989 if selection.id == state.selection_id {
3990 return true;
3991 } else {
3992 i += 1;
3993 }
3994 }
3995 false
3996 });
3997 }
3998
3999 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4000 let offset = position.to_offset(buffer);
4001 let (word_range, kind) = buffer.surrounding_word(offset, true);
4002 if offset > word_range.start && kind == Some(CharKind::Word) {
4003 Some(
4004 buffer
4005 .text_for_range(word_range.start..offset)
4006 .collect::<String>(),
4007 )
4008 } else {
4009 None
4010 }
4011 }
4012
4013 pub fn toggle_inlay_hints(
4014 &mut self,
4015 _: &ToggleInlayHints,
4016 _: &mut Window,
4017 cx: &mut Context<Self>,
4018 ) {
4019 self.refresh_inlay_hints(
4020 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4021 cx,
4022 );
4023 }
4024
4025 pub fn inlay_hints_enabled(&self) -> bool {
4026 self.inlay_hint_cache.enabled
4027 }
4028
4029 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4030 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4031 return;
4032 }
4033
4034 let reason_description = reason.description();
4035 let ignore_debounce = matches!(
4036 reason,
4037 InlayHintRefreshReason::SettingsChange(_)
4038 | InlayHintRefreshReason::Toggle(_)
4039 | InlayHintRefreshReason::ExcerptsRemoved(_)
4040 | InlayHintRefreshReason::ModifiersChanged(_)
4041 );
4042 let (invalidate_cache, required_languages) = match reason {
4043 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4044 match self.inlay_hint_cache.modifiers_override(enabled) {
4045 Some(enabled) => {
4046 if enabled {
4047 (InvalidationStrategy::RefreshRequested, None)
4048 } else {
4049 self.splice_inlays(
4050 &self
4051 .visible_inlay_hints(cx)
4052 .iter()
4053 .map(|inlay| inlay.id)
4054 .collect::<Vec<InlayId>>(),
4055 Vec::new(),
4056 cx,
4057 );
4058 return;
4059 }
4060 }
4061 None => return,
4062 }
4063 }
4064 InlayHintRefreshReason::Toggle(enabled) => {
4065 if self.inlay_hint_cache.toggle(enabled) {
4066 if enabled {
4067 (InvalidationStrategy::RefreshRequested, None)
4068 } else {
4069 self.splice_inlays(
4070 &self
4071 .visible_inlay_hints(cx)
4072 .iter()
4073 .map(|inlay| inlay.id)
4074 .collect::<Vec<InlayId>>(),
4075 Vec::new(),
4076 cx,
4077 );
4078 return;
4079 }
4080 } else {
4081 return;
4082 }
4083 }
4084 InlayHintRefreshReason::SettingsChange(new_settings) => {
4085 match self.inlay_hint_cache.update_settings(
4086 &self.buffer,
4087 new_settings,
4088 self.visible_inlay_hints(cx),
4089 cx,
4090 ) {
4091 ControlFlow::Break(Some(InlaySplice {
4092 to_remove,
4093 to_insert,
4094 })) => {
4095 self.splice_inlays(&to_remove, to_insert, cx);
4096 return;
4097 }
4098 ControlFlow::Break(None) => return,
4099 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4100 }
4101 }
4102 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4103 if let Some(InlaySplice {
4104 to_remove,
4105 to_insert,
4106 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4107 {
4108 self.splice_inlays(&to_remove, to_insert, cx);
4109 }
4110 return;
4111 }
4112 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4113 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4114 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4115 }
4116 InlayHintRefreshReason::RefreshRequested => {
4117 (InvalidationStrategy::RefreshRequested, None)
4118 }
4119 };
4120
4121 if let Some(InlaySplice {
4122 to_remove,
4123 to_insert,
4124 }) = self.inlay_hint_cache.spawn_hint_refresh(
4125 reason_description,
4126 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4127 invalidate_cache,
4128 ignore_debounce,
4129 cx,
4130 ) {
4131 self.splice_inlays(&to_remove, to_insert, cx);
4132 }
4133 }
4134
4135 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4136 self.display_map
4137 .read(cx)
4138 .current_inlays()
4139 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4140 .cloned()
4141 .collect()
4142 }
4143
4144 pub fn excerpts_for_inlay_hints_query(
4145 &self,
4146 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4147 cx: &mut Context<Editor>,
4148 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4149 let Some(project) = self.project.as_ref() else {
4150 return HashMap::default();
4151 };
4152 let project = project.read(cx);
4153 let multi_buffer = self.buffer().read(cx);
4154 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4155 let multi_buffer_visible_start = self
4156 .scroll_manager
4157 .anchor()
4158 .anchor
4159 .to_point(&multi_buffer_snapshot);
4160 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4161 multi_buffer_visible_start
4162 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4163 Bias::Left,
4164 );
4165 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4166 multi_buffer_snapshot
4167 .range_to_buffer_ranges(multi_buffer_visible_range)
4168 .into_iter()
4169 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4170 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4171 let buffer_file = project::File::from_dyn(buffer.file())?;
4172 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4173 let worktree_entry = buffer_worktree
4174 .read(cx)
4175 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4176 if worktree_entry.is_ignored {
4177 return None;
4178 }
4179
4180 let language = buffer.language()?;
4181 if let Some(restrict_to_languages) = restrict_to_languages {
4182 if !restrict_to_languages.contains(language) {
4183 return None;
4184 }
4185 }
4186 Some((
4187 excerpt_id,
4188 (
4189 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4190 buffer.version().clone(),
4191 excerpt_visible_range,
4192 ),
4193 ))
4194 })
4195 .collect()
4196 }
4197
4198 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4199 TextLayoutDetails {
4200 text_system: window.text_system().clone(),
4201 editor_style: self.style.clone().unwrap(),
4202 rem_size: window.rem_size(),
4203 scroll_anchor: self.scroll_manager.anchor(),
4204 visible_rows: self.visible_line_count(),
4205 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4206 }
4207 }
4208
4209 pub fn splice_inlays(
4210 &self,
4211 to_remove: &[InlayId],
4212 to_insert: Vec<Inlay>,
4213 cx: &mut Context<Self>,
4214 ) {
4215 self.display_map.update(cx, |display_map, cx| {
4216 display_map.splice_inlays(to_remove, to_insert, cx)
4217 });
4218 cx.notify();
4219 }
4220
4221 fn trigger_on_type_formatting(
4222 &self,
4223 input: String,
4224 window: &mut Window,
4225 cx: &mut Context<Self>,
4226 ) -> Option<Task<Result<()>>> {
4227 if input.len() != 1 {
4228 return None;
4229 }
4230
4231 let project = self.project.as_ref()?;
4232 let position = self.selections.newest_anchor().head();
4233 let (buffer, buffer_position) = self
4234 .buffer
4235 .read(cx)
4236 .text_anchor_for_position(position, cx)?;
4237
4238 let settings = language_settings::language_settings(
4239 buffer
4240 .read(cx)
4241 .language_at(buffer_position)
4242 .map(|l| l.name()),
4243 buffer.read(cx).file(),
4244 cx,
4245 );
4246 if !settings.use_on_type_format {
4247 return None;
4248 }
4249
4250 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4251 // hence we do LSP request & edit on host side only — add formats to host's history.
4252 let push_to_lsp_host_history = true;
4253 // If this is not the host, append its history with new edits.
4254 let push_to_client_history = project.read(cx).is_via_collab();
4255
4256 let on_type_formatting = project.update(cx, |project, cx| {
4257 project.on_type_format(
4258 buffer.clone(),
4259 buffer_position,
4260 input,
4261 push_to_lsp_host_history,
4262 cx,
4263 )
4264 });
4265 Some(cx.spawn_in(window, async move |editor, cx| {
4266 if let Some(transaction) = on_type_formatting.await? {
4267 if push_to_client_history {
4268 buffer
4269 .update(cx, |buffer, _| {
4270 buffer.push_transaction(transaction, Instant::now());
4271 })
4272 .ok();
4273 }
4274 editor.update(cx, |editor, cx| {
4275 editor.refresh_document_highlights(cx);
4276 })?;
4277 }
4278 Ok(())
4279 }))
4280 }
4281
4282 pub fn show_word_completions(
4283 &mut self,
4284 _: &ShowWordCompletions,
4285 window: &mut Window,
4286 cx: &mut Context<Self>,
4287 ) {
4288 self.open_completions_menu(true, None, window, cx);
4289 }
4290
4291 pub fn show_completions(
4292 &mut self,
4293 options: &ShowCompletions,
4294 window: &mut Window,
4295 cx: &mut Context<Self>,
4296 ) {
4297 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4298 }
4299
4300 fn open_completions_menu(
4301 &mut self,
4302 ignore_completion_provider: bool,
4303 trigger: Option<&str>,
4304 window: &mut Window,
4305 cx: &mut Context<Self>,
4306 ) {
4307 if self.pending_rename.is_some() {
4308 return;
4309 }
4310 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4311 return;
4312 }
4313
4314 let position = self.selections.newest_anchor().head();
4315 if position.diff_base_anchor.is_some() {
4316 return;
4317 }
4318 let (buffer, buffer_position) =
4319 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4320 output
4321 } else {
4322 return;
4323 };
4324 let buffer_snapshot = buffer.read(cx).snapshot();
4325 let show_completion_documentation = buffer_snapshot
4326 .settings_at(buffer_position, cx)
4327 .show_completion_documentation;
4328
4329 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4330
4331 let trigger_kind = match trigger {
4332 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4333 CompletionTriggerKind::TRIGGER_CHARACTER
4334 }
4335 _ => CompletionTriggerKind::INVOKED,
4336 };
4337 let completion_context = CompletionContext {
4338 trigger_character: trigger.and_then(|trigger| {
4339 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4340 Some(String::from(trigger))
4341 } else {
4342 None
4343 }
4344 }),
4345 trigger_kind,
4346 };
4347
4348 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4349 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4350 let word_to_exclude = buffer_snapshot
4351 .text_for_range(old_range.clone())
4352 .collect::<String>();
4353 (
4354 buffer_snapshot.anchor_before(old_range.start)
4355 ..buffer_snapshot.anchor_after(old_range.end),
4356 Some(word_to_exclude),
4357 )
4358 } else {
4359 (buffer_position..buffer_position, None)
4360 };
4361
4362 let completion_settings = language_settings(
4363 buffer_snapshot
4364 .language_at(buffer_position)
4365 .map(|language| language.name()),
4366 buffer_snapshot.file(),
4367 cx,
4368 )
4369 .completions;
4370
4371 // The document can be large, so stay in reasonable bounds when searching for words,
4372 // otherwise completion pop-up might be slow to appear.
4373 const WORD_LOOKUP_ROWS: u32 = 5_000;
4374 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4375 let min_word_search = buffer_snapshot.clip_point(
4376 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4377 Bias::Left,
4378 );
4379 let max_word_search = buffer_snapshot.clip_point(
4380 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4381 Bias::Right,
4382 );
4383 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4384 ..buffer_snapshot.point_to_offset(max_word_search);
4385
4386 let provider = self
4387 .completion_provider
4388 .as_ref()
4389 .filter(|_| !ignore_completion_provider);
4390 let skip_digits = query
4391 .as_ref()
4392 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4393
4394 let (mut words, provided_completions) = match provider {
4395 Some(provider) => {
4396 let completions = provider.completions(
4397 position.excerpt_id,
4398 &buffer,
4399 buffer_position,
4400 completion_context,
4401 window,
4402 cx,
4403 );
4404
4405 let words = match completion_settings.words {
4406 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4407 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4408 .background_spawn(async move {
4409 buffer_snapshot.words_in_range(WordsQuery {
4410 fuzzy_contents: None,
4411 range: word_search_range,
4412 skip_digits,
4413 })
4414 }),
4415 };
4416
4417 (words, completions)
4418 }
4419 None => (
4420 cx.background_spawn(async move {
4421 buffer_snapshot.words_in_range(WordsQuery {
4422 fuzzy_contents: None,
4423 range: word_search_range,
4424 skip_digits,
4425 })
4426 }),
4427 Task::ready(Ok(None)),
4428 ),
4429 };
4430
4431 let sort_completions = provider
4432 .as_ref()
4433 .map_or(false, |provider| provider.sort_completions());
4434
4435 let filter_completions = provider
4436 .as_ref()
4437 .map_or(true, |provider| provider.filter_completions());
4438
4439 let id = post_inc(&mut self.next_completion_id);
4440 let task = cx.spawn_in(window, async move |editor, cx| {
4441 async move {
4442 editor.update(cx, |this, _| {
4443 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4444 })?;
4445
4446 let mut completions = Vec::new();
4447 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4448 completions.extend(provided_completions);
4449 if completion_settings.words == WordsCompletionMode::Fallback {
4450 words = Task::ready(BTreeMap::default());
4451 }
4452 }
4453
4454 let mut words = words.await;
4455 if let Some(word_to_exclude) = &word_to_exclude {
4456 words.remove(word_to_exclude);
4457 }
4458 for lsp_completion in &completions {
4459 words.remove(&lsp_completion.new_text);
4460 }
4461 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4462 old_range: old_range.clone(),
4463 new_text: word.clone(),
4464 label: CodeLabel::plain(word, None),
4465 icon_path: None,
4466 documentation: None,
4467 source: CompletionSource::BufferWord {
4468 word_range,
4469 resolved: false,
4470 },
4471 insert_text_mode: Some(InsertTextMode::AS_IS),
4472 confirm: None,
4473 }));
4474
4475 let menu = if completions.is_empty() {
4476 None
4477 } else {
4478 let mut menu = CompletionsMenu::new(
4479 id,
4480 sort_completions,
4481 show_completion_documentation,
4482 ignore_completion_provider,
4483 position,
4484 buffer.clone(),
4485 completions.into(),
4486 );
4487
4488 menu.filter(
4489 if filter_completions {
4490 query.as_deref()
4491 } else {
4492 None
4493 },
4494 cx.background_executor().clone(),
4495 )
4496 .await;
4497
4498 menu.visible().then_some(menu)
4499 };
4500
4501 editor.update_in(cx, |editor, window, cx| {
4502 match editor.context_menu.borrow().as_ref() {
4503 None => {}
4504 Some(CodeContextMenu::Completions(prev_menu)) => {
4505 if prev_menu.id > id {
4506 return;
4507 }
4508 }
4509 _ => return,
4510 }
4511
4512 if editor.focus_handle.is_focused(window) && menu.is_some() {
4513 let mut menu = menu.unwrap();
4514 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4515
4516 *editor.context_menu.borrow_mut() =
4517 Some(CodeContextMenu::Completions(menu));
4518
4519 if editor.show_edit_predictions_in_menu() {
4520 editor.update_visible_inline_completion(window, cx);
4521 } else {
4522 editor.discard_inline_completion(false, cx);
4523 }
4524
4525 cx.notify();
4526 } else if editor.completion_tasks.len() <= 1 {
4527 // If there are no more completion tasks and the last menu was
4528 // empty, we should hide it.
4529 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4530 // If it was already hidden and we don't show inline
4531 // completions in the menu, we should also show the
4532 // inline-completion when available.
4533 if was_hidden && editor.show_edit_predictions_in_menu() {
4534 editor.update_visible_inline_completion(window, cx);
4535 }
4536 }
4537 })?;
4538
4539 anyhow::Ok(())
4540 }
4541 .log_err()
4542 .await
4543 });
4544
4545 self.completion_tasks.push((id, task));
4546 }
4547
4548 #[cfg(feature = "test-support")]
4549 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4550 let menu = self.context_menu.borrow();
4551 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4552 let completions = menu.completions.borrow();
4553 Some(completions.to_vec())
4554 } else {
4555 None
4556 }
4557 }
4558
4559 pub fn confirm_completion(
4560 &mut self,
4561 action: &ConfirmCompletion,
4562 window: &mut Window,
4563 cx: &mut Context<Self>,
4564 ) -> Option<Task<Result<()>>> {
4565 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4566 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4567 }
4568
4569 pub fn compose_completion(
4570 &mut self,
4571 action: &ComposeCompletion,
4572 window: &mut Window,
4573 cx: &mut Context<Self>,
4574 ) -> Option<Task<Result<()>>> {
4575 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4576 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4577 }
4578
4579 fn do_completion(
4580 &mut self,
4581 item_ix: Option<usize>,
4582 intent: CompletionIntent,
4583 window: &mut Window,
4584 cx: &mut Context<Editor>,
4585 ) -> Option<Task<Result<()>>> {
4586 use language::ToOffset as _;
4587
4588 let completions_menu =
4589 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4590 menu
4591 } else {
4592 return None;
4593 };
4594
4595 let candidate_id = {
4596 let entries = completions_menu.entries.borrow();
4597 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4598 if self.show_edit_predictions_in_menu() {
4599 self.discard_inline_completion(true, cx);
4600 }
4601 mat.candidate_id
4602 };
4603
4604 let buffer_handle = completions_menu.buffer;
4605 let completion = completions_menu
4606 .completions
4607 .borrow()
4608 .get(candidate_id)?
4609 .clone();
4610 cx.stop_propagation();
4611
4612 let snippet;
4613 let new_text;
4614 if completion.is_snippet() {
4615 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4616 new_text = snippet.as_ref().unwrap().text.clone();
4617 } else {
4618 snippet = None;
4619 new_text = completion.new_text.clone();
4620 };
4621 let selections = self.selections.all::<usize>(cx);
4622 let buffer = buffer_handle.read(cx);
4623 let old_range = completion.old_range.to_offset(buffer);
4624 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4625
4626 let newest_selection = self.selections.newest_anchor();
4627 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4628 return None;
4629 }
4630
4631 let lookbehind = newest_selection
4632 .start
4633 .text_anchor
4634 .to_offset(buffer)
4635 .saturating_sub(old_range.start);
4636 let lookahead = old_range
4637 .end
4638 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4639 let mut common_prefix_len = 0;
4640 for (a, b) in old_text.chars().zip(new_text.chars()) {
4641 if a == b {
4642 common_prefix_len += a.len_utf8();
4643 } else {
4644 break;
4645 }
4646 }
4647
4648 let snapshot = self.buffer.read(cx).snapshot(cx);
4649 let mut range_to_replace: Option<Range<usize>> = None;
4650 let mut ranges = Vec::new();
4651 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4652 for selection in &selections {
4653 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4654 let start = selection.start.saturating_sub(lookbehind);
4655 let end = selection.end + lookahead;
4656 if selection.id == newest_selection.id {
4657 range_to_replace = Some(start + common_prefix_len..end);
4658 }
4659 ranges.push(start + common_prefix_len..end);
4660 } else {
4661 common_prefix_len = 0;
4662 ranges.clear();
4663 ranges.extend(selections.iter().map(|s| {
4664 if s.id == newest_selection.id {
4665 range_to_replace = Some(old_range.clone());
4666 old_range.clone()
4667 } else {
4668 s.start..s.end
4669 }
4670 }));
4671 break;
4672 }
4673 if !self.linked_edit_ranges.is_empty() {
4674 let start_anchor = snapshot.anchor_before(selection.head());
4675 let end_anchor = snapshot.anchor_after(selection.tail());
4676 if let Some(ranges) = self
4677 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4678 {
4679 for (buffer, edits) in ranges {
4680 linked_edits.entry(buffer.clone()).or_default().extend(
4681 edits
4682 .into_iter()
4683 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4684 );
4685 }
4686 }
4687 }
4688 }
4689 let text = &new_text[common_prefix_len..];
4690
4691 let utf16_range_to_replace = range_to_replace.map(|range| {
4692 let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
4693 let selection_start_utf16 = newest_selection.start.0 as isize;
4694
4695 range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4696 ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4697 });
4698 cx.emit(EditorEvent::InputHandled {
4699 utf16_range_to_replace,
4700 text: text.into(),
4701 });
4702
4703 self.transact(window, cx, |this, window, cx| {
4704 if let Some(mut snippet) = snippet {
4705 snippet.text = text.to_string();
4706 for tabstop in snippet
4707 .tabstops
4708 .iter_mut()
4709 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4710 {
4711 tabstop.start -= common_prefix_len as isize;
4712 tabstop.end -= common_prefix_len as isize;
4713 }
4714
4715 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4716 } else {
4717 this.buffer.update(cx, |buffer, cx| {
4718 let edits = ranges.iter().map(|range| (range.clone(), text));
4719 let auto_indent = if completion.insert_text_mode == Some(InsertTextMode::AS_IS)
4720 {
4721 None
4722 } else {
4723 this.autoindent_mode.clone()
4724 };
4725 buffer.edit(edits, auto_indent, cx);
4726 });
4727 }
4728 for (buffer, edits) in linked_edits {
4729 buffer.update(cx, |buffer, cx| {
4730 let snapshot = buffer.snapshot();
4731 let edits = edits
4732 .into_iter()
4733 .map(|(range, text)| {
4734 use text::ToPoint as TP;
4735 let end_point = TP::to_point(&range.end, &snapshot);
4736 let start_point = TP::to_point(&range.start, &snapshot);
4737 (start_point..end_point, text)
4738 })
4739 .sorted_by_key(|(range, _)| range.start);
4740 buffer.edit(edits, None, cx);
4741 })
4742 }
4743
4744 this.refresh_inline_completion(true, false, window, cx);
4745 });
4746
4747 let show_new_completions_on_confirm = completion
4748 .confirm
4749 .as_ref()
4750 .map_or(false, |confirm| confirm(intent, window, cx));
4751 if show_new_completions_on_confirm {
4752 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4753 }
4754
4755 let provider = self.completion_provider.as_ref()?;
4756 drop(completion);
4757 let apply_edits = provider.apply_additional_edits_for_completion(
4758 buffer_handle,
4759 completions_menu.completions.clone(),
4760 candidate_id,
4761 true,
4762 cx,
4763 );
4764
4765 let editor_settings = EditorSettings::get_global(cx);
4766 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4767 // After the code completion is finished, users often want to know what signatures are needed.
4768 // so we should automatically call signature_help
4769 self.show_signature_help(&ShowSignatureHelp, window, cx);
4770 }
4771
4772 Some(cx.foreground_executor().spawn(async move {
4773 apply_edits.await?;
4774 Ok(())
4775 }))
4776 }
4777
4778 pub fn toggle_code_actions(
4779 &mut self,
4780 action: &ToggleCodeActions,
4781 window: &mut Window,
4782 cx: &mut Context<Self>,
4783 ) {
4784 let mut context_menu = self.context_menu.borrow_mut();
4785 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4786 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4787 // Toggle if we're selecting the same one
4788 *context_menu = None;
4789 cx.notify();
4790 return;
4791 } else {
4792 // Otherwise, clear it and start a new one
4793 *context_menu = None;
4794 cx.notify();
4795 }
4796 }
4797 drop(context_menu);
4798 let snapshot = self.snapshot(window, cx);
4799 let deployed_from_indicator = action.deployed_from_indicator;
4800 let mut task = self.code_actions_task.take();
4801 let action = action.clone();
4802 cx.spawn_in(window, async move |editor, cx| {
4803 while let Some(prev_task) = task {
4804 prev_task.await.log_err();
4805 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4806 }
4807
4808 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4809 if editor.focus_handle.is_focused(window) {
4810 let multibuffer_point = action
4811 .deployed_from_indicator
4812 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4813 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4814 let (buffer, buffer_row) = snapshot
4815 .buffer_snapshot
4816 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4817 .and_then(|(buffer_snapshot, range)| {
4818 editor
4819 .buffer
4820 .read(cx)
4821 .buffer(buffer_snapshot.remote_id())
4822 .map(|buffer| (buffer, range.start.row))
4823 })?;
4824 let (_, code_actions) = editor
4825 .available_code_actions
4826 .clone()
4827 .and_then(|(location, code_actions)| {
4828 let snapshot = location.buffer.read(cx).snapshot();
4829 let point_range = location.range.to_point(&snapshot);
4830 let point_range = point_range.start.row..=point_range.end.row;
4831 if point_range.contains(&buffer_row) {
4832 Some((location, code_actions))
4833 } else {
4834 None
4835 }
4836 })
4837 .unzip();
4838 let buffer_id = buffer.read(cx).remote_id();
4839 let tasks = editor
4840 .tasks
4841 .get(&(buffer_id, buffer_row))
4842 .map(|t| Arc::new(t.to_owned()));
4843 if tasks.is_none() && code_actions.is_none() {
4844 return None;
4845 }
4846
4847 editor.completion_tasks.clear();
4848 editor.discard_inline_completion(false, cx);
4849 let task_context =
4850 tasks
4851 .as_ref()
4852 .zip(editor.project.clone())
4853 .map(|(tasks, project)| {
4854 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4855 });
4856
4857 let debugger_flag = cx.has_flag::<Debugger>();
4858
4859 Some(cx.spawn_in(window, async move |editor, cx| {
4860 let task_context = match task_context {
4861 Some(task_context) => task_context.await,
4862 None => None,
4863 };
4864 let resolved_tasks =
4865 tasks.zip(task_context).map(|(tasks, task_context)| {
4866 Rc::new(ResolvedTasks {
4867 templates: tasks.resolve(&task_context).collect(),
4868 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4869 multibuffer_point.row,
4870 tasks.column,
4871 )),
4872 })
4873 });
4874 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
4875 tasks
4876 .templates
4877 .iter()
4878 .filter(|task| {
4879 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
4880 debugger_flag
4881 } else {
4882 true
4883 }
4884 })
4885 .count()
4886 == 1
4887 }) && code_actions
4888 .as_ref()
4889 .map_or(true, |actions| actions.is_empty());
4890 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4891 *editor.context_menu.borrow_mut() =
4892 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4893 buffer,
4894 actions: CodeActionContents {
4895 tasks: resolved_tasks,
4896 actions: code_actions,
4897 },
4898 selected_item: Default::default(),
4899 scroll_handle: UniformListScrollHandle::default(),
4900 deployed_from_indicator,
4901 }));
4902 if spawn_straight_away {
4903 if let Some(task) = editor.confirm_code_action(
4904 &ConfirmCodeAction { item_ix: Some(0) },
4905 window,
4906 cx,
4907 ) {
4908 cx.notify();
4909 return task;
4910 }
4911 }
4912 cx.notify();
4913 Task::ready(Ok(()))
4914 }) {
4915 task.await
4916 } else {
4917 Ok(())
4918 }
4919 }))
4920 } else {
4921 Some(Task::ready(Ok(())))
4922 }
4923 })?;
4924 if let Some(task) = spawned_test_task {
4925 task.await?;
4926 }
4927
4928 Ok::<_, anyhow::Error>(())
4929 })
4930 .detach_and_log_err(cx);
4931 }
4932
4933 pub fn confirm_code_action(
4934 &mut self,
4935 action: &ConfirmCodeAction,
4936 window: &mut Window,
4937 cx: &mut Context<Self>,
4938 ) -> Option<Task<Result<()>>> {
4939 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4940
4941 let actions_menu =
4942 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4943 menu
4944 } else {
4945 return None;
4946 };
4947
4948 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4949 let action = actions_menu.actions.get(action_ix)?;
4950 let title = action.label();
4951 let buffer = actions_menu.buffer;
4952 let workspace = self.workspace()?;
4953
4954 match action {
4955 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4956 match resolved_task.task_type() {
4957 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
4958 workspace::tasks::schedule_resolved_task(
4959 workspace,
4960 task_source_kind,
4961 resolved_task,
4962 false,
4963 cx,
4964 );
4965
4966 Some(Task::ready(Ok(())))
4967 }),
4968 task::TaskType::Debug(debug_args) => {
4969 if debug_args.locator.is_some() {
4970 workspace.update(cx, |workspace, cx| {
4971 workspace::tasks::schedule_resolved_task(
4972 workspace,
4973 task_source_kind,
4974 resolved_task,
4975 false,
4976 cx,
4977 );
4978 });
4979
4980 return Some(Task::ready(Ok(())));
4981 }
4982
4983 if let Some(project) = self.project.as_ref() {
4984 project
4985 .update(cx, |project, cx| {
4986 project.start_debug_session(
4987 resolved_task.resolved_debug_adapter_config().unwrap(),
4988 cx,
4989 )
4990 })
4991 .detach_and_log_err(cx);
4992 Some(Task::ready(Ok(())))
4993 } else {
4994 Some(Task::ready(Ok(())))
4995 }
4996 }
4997 }
4998 }
4999 CodeActionsItem::CodeAction {
5000 excerpt_id,
5001 action,
5002 provider,
5003 } => {
5004 let apply_code_action =
5005 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5006 let workspace = workspace.downgrade();
5007 Some(cx.spawn_in(window, async move |editor, cx| {
5008 let project_transaction = apply_code_action.await?;
5009 Self::open_project_transaction(
5010 &editor,
5011 workspace,
5012 project_transaction,
5013 title,
5014 cx,
5015 )
5016 .await
5017 }))
5018 }
5019 }
5020 }
5021
5022 pub async fn open_project_transaction(
5023 this: &WeakEntity<Editor>,
5024 workspace: WeakEntity<Workspace>,
5025 transaction: ProjectTransaction,
5026 title: String,
5027 cx: &mut AsyncWindowContext,
5028 ) -> Result<()> {
5029 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5030 cx.update(|_, cx| {
5031 entries.sort_unstable_by_key(|(buffer, _)| {
5032 buffer.read(cx).file().map(|f| f.path().clone())
5033 });
5034 })?;
5035
5036 // If the project transaction's edits are all contained within this editor, then
5037 // avoid opening a new editor to display them.
5038
5039 if let Some((buffer, transaction)) = entries.first() {
5040 if entries.len() == 1 {
5041 let excerpt = this.update(cx, |editor, cx| {
5042 editor
5043 .buffer()
5044 .read(cx)
5045 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5046 })?;
5047 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5048 if excerpted_buffer == *buffer {
5049 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5050 let excerpt_range = excerpt_range.to_offset(buffer);
5051 buffer
5052 .edited_ranges_for_transaction::<usize>(transaction)
5053 .all(|range| {
5054 excerpt_range.start <= range.start
5055 && excerpt_range.end >= range.end
5056 })
5057 })?;
5058
5059 if all_edits_within_excerpt {
5060 return Ok(());
5061 }
5062 }
5063 }
5064 }
5065 } else {
5066 return Ok(());
5067 }
5068
5069 let mut ranges_to_highlight = Vec::new();
5070 let excerpt_buffer = cx.new(|cx| {
5071 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5072 for (buffer_handle, transaction) in &entries {
5073 let edited_ranges = buffer_handle
5074 .read(cx)
5075 .edited_ranges_for_transaction::<Point>(transaction)
5076 .collect::<Vec<_>>();
5077 let (ranges, _) = multibuffer.set_excerpts_for_path(
5078 PathKey::for_buffer(buffer_handle, cx),
5079 buffer_handle.clone(),
5080 edited_ranges,
5081 DEFAULT_MULTIBUFFER_CONTEXT,
5082 cx,
5083 );
5084
5085 ranges_to_highlight.extend(ranges);
5086 }
5087 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5088 multibuffer
5089 })?;
5090
5091 workspace.update_in(cx, |workspace, window, cx| {
5092 let project = workspace.project().clone();
5093 let editor =
5094 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5095 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5096 editor.update(cx, |editor, cx| {
5097 editor.highlight_background::<Self>(
5098 &ranges_to_highlight,
5099 |theme| theme.editor_highlighted_line_background,
5100 cx,
5101 );
5102 });
5103 })?;
5104
5105 Ok(())
5106 }
5107
5108 pub fn clear_code_action_providers(&mut self) {
5109 self.code_action_providers.clear();
5110 self.available_code_actions.take();
5111 }
5112
5113 pub fn add_code_action_provider(
5114 &mut self,
5115 provider: Rc<dyn CodeActionProvider>,
5116 window: &mut Window,
5117 cx: &mut Context<Self>,
5118 ) {
5119 if self
5120 .code_action_providers
5121 .iter()
5122 .any(|existing_provider| existing_provider.id() == provider.id())
5123 {
5124 return;
5125 }
5126
5127 self.code_action_providers.push(provider);
5128 self.refresh_code_actions(window, cx);
5129 }
5130
5131 pub fn remove_code_action_provider(
5132 &mut self,
5133 id: Arc<str>,
5134 window: &mut Window,
5135 cx: &mut Context<Self>,
5136 ) {
5137 self.code_action_providers
5138 .retain(|provider| provider.id() != id);
5139 self.refresh_code_actions(window, cx);
5140 }
5141
5142 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5143 let buffer = self.buffer.read(cx);
5144 let newest_selection = self.selections.newest_anchor().clone();
5145 if newest_selection.head().diff_base_anchor.is_some() {
5146 return None;
5147 }
5148 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
5149 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
5150 if start_buffer != end_buffer {
5151 return None;
5152 }
5153
5154 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5155 cx.background_executor()
5156 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5157 .await;
5158
5159 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5160 let providers = this.code_action_providers.clone();
5161 let tasks = this
5162 .code_action_providers
5163 .iter()
5164 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5165 .collect::<Vec<_>>();
5166 (providers, tasks)
5167 })?;
5168
5169 let mut actions = Vec::new();
5170 for (provider, provider_actions) in
5171 providers.into_iter().zip(future::join_all(tasks).await)
5172 {
5173 if let Some(provider_actions) = provider_actions.log_err() {
5174 actions.extend(provider_actions.into_iter().map(|action| {
5175 AvailableCodeAction {
5176 excerpt_id: newest_selection.start.excerpt_id,
5177 action,
5178 provider: provider.clone(),
5179 }
5180 }));
5181 }
5182 }
5183
5184 this.update(cx, |this, cx| {
5185 this.available_code_actions = if actions.is_empty() {
5186 None
5187 } else {
5188 Some((
5189 Location {
5190 buffer: start_buffer,
5191 range: start..end,
5192 },
5193 actions.into(),
5194 ))
5195 };
5196 cx.notify();
5197 })
5198 }));
5199 None
5200 }
5201
5202 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5203 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5204 self.show_git_blame_inline = false;
5205
5206 self.show_git_blame_inline_delay_task =
5207 Some(cx.spawn_in(window, async move |this, cx| {
5208 cx.background_executor().timer(delay).await;
5209
5210 this.update(cx, |this, cx| {
5211 this.show_git_blame_inline = true;
5212 cx.notify();
5213 })
5214 .log_err();
5215 }));
5216 }
5217 }
5218
5219 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5220 if self.pending_rename.is_some() {
5221 return None;
5222 }
5223
5224 let provider = self.semantics_provider.clone()?;
5225 let buffer = self.buffer.read(cx);
5226 let newest_selection = self.selections.newest_anchor().clone();
5227 let cursor_position = newest_selection.head();
5228 let (cursor_buffer, cursor_buffer_position) =
5229 buffer.text_anchor_for_position(cursor_position, cx)?;
5230 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5231 if cursor_buffer != tail_buffer {
5232 return None;
5233 }
5234 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5235 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5236 cx.background_executor()
5237 .timer(Duration::from_millis(debounce))
5238 .await;
5239
5240 let highlights = if let Some(highlights) = cx
5241 .update(|cx| {
5242 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5243 })
5244 .ok()
5245 .flatten()
5246 {
5247 highlights.await.log_err()
5248 } else {
5249 None
5250 };
5251
5252 if let Some(highlights) = highlights {
5253 this.update(cx, |this, cx| {
5254 if this.pending_rename.is_some() {
5255 return;
5256 }
5257
5258 let buffer_id = cursor_position.buffer_id;
5259 let buffer = this.buffer.read(cx);
5260 if !buffer
5261 .text_anchor_for_position(cursor_position, cx)
5262 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5263 {
5264 return;
5265 }
5266
5267 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5268 let mut write_ranges = Vec::new();
5269 let mut read_ranges = Vec::new();
5270 for highlight in highlights {
5271 for (excerpt_id, excerpt_range) in
5272 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5273 {
5274 let start = highlight
5275 .range
5276 .start
5277 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5278 let end = highlight
5279 .range
5280 .end
5281 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5282 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5283 continue;
5284 }
5285
5286 let range = Anchor {
5287 buffer_id,
5288 excerpt_id,
5289 text_anchor: start,
5290 diff_base_anchor: None,
5291 }..Anchor {
5292 buffer_id,
5293 excerpt_id,
5294 text_anchor: end,
5295 diff_base_anchor: None,
5296 };
5297 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5298 write_ranges.push(range);
5299 } else {
5300 read_ranges.push(range);
5301 }
5302 }
5303 }
5304
5305 this.highlight_background::<DocumentHighlightRead>(
5306 &read_ranges,
5307 |theme| theme.editor_document_highlight_read_background,
5308 cx,
5309 );
5310 this.highlight_background::<DocumentHighlightWrite>(
5311 &write_ranges,
5312 |theme| theme.editor_document_highlight_write_background,
5313 cx,
5314 );
5315 cx.notify();
5316 })
5317 .log_err();
5318 }
5319 }));
5320 None
5321 }
5322
5323 pub fn refresh_selected_text_highlights(
5324 &mut self,
5325 window: &mut Window,
5326 cx: &mut Context<Editor>,
5327 ) {
5328 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5329 return;
5330 }
5331 self.selection_highlight_task.take();
5332 if !EditorSettings::get_global(cx).selection_highlight {
5333 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5334 return;
5335 }
5336 if self.selections.count() != 1 || self.selections.line_mode {
5337 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5338 return;
5339 }
5340 let selection = self.selections.newest::<Point>(cx);
5341 if selection.is_empty() || selection.start.row != selection.end.row {
5342 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5343 return;
5344 }
5345 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5346 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5347 cx.background_executor()
5348 .timer(Duration::from_millis(debounce))
5349 .await;
5350 let Some(Some(matches_task)) = editor
5351 .update_in(cx, |editor, _, cx| {
5352 if editor.selections.count() != 1 || editor.selections.line_mode {
5353 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5354 return None;
5355 }
5356 let selection = editor.selections.newest::<Point>(cx);
5357 if selection.is_empty() || selection.start.row != selection.end.row {
5358 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5359 return None;
5360 }
5361 let buffer = editor.buffer().read(cx).snapshot(cx);
5362 let query = buffer.text_for_range(selection.range()).collect::<String>();
5363 if query.trim().is_empty() {
5364 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5365 return None;
5366 }
5367 Some(cx.background_spawn(async move {
5368 let mut ranges = Vec::new();
5369 let selection_anchors = selection.range().to_anchors(&buffer);
5370 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5371 for (search_buffer, search_range, excerpt_id) in
5372 buffer.range_to_buffer_ranges(range)
5373 {
5374 ranges.extend(
5375 project::search::SearchQuery::text(
5376 query.clone(),
5377 false,
5378 false,
5379 false,
5380 Default::default(),
5381 Default::default(),
5382 None,
5383 )
5384 .unwrap()
5385 .search(search_buffer, Some(search_range.clone()))
5386 .await
5387 .into_iter()
5388 .filter_map(
5389 |match_range| {
5390 let start = search_buffer.anchor_after(
5391 search_range.start + match_range.start,
5392 );
5393 let end = search_buffer.anchor_before(
5394 search_range.start + match_range.end,
5395 );
5396 let range = Anchor::range_in_buffer(
5397 excerpt_id,
5398 search_buffer.remote_id(),
5399 start..end,
5400 );
5401 (range != selection_anchors).then_some(range)
5402 },
5403 ),
5404 );
5405 }
5406 }
5407 ranges
5408 }))
5409 })
5410 .log_err()
5411 else {
5412 return;
5413 };
5414 let matches = matches_task.await;
5415 editor
5416 .update_in(cx, |editor, _, cx| {
5417 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5418 if !matches.is_empty() {
5419 editor.highlight_background::<SelectedTextHighlight>(
5420 &matches,
5421 |theme| theme.editor_document_highlight_bracket_background,
5422 cx,
5423 )
5424 }
5425 })
5426 .log_err();
5427 }));
5428 }
5429
5430 pub fn refresh_inline_completion(
5431 &mut self,
5432 debounce: bool,
5433 user_requested: bool,
5434 window: &mut Window,
5435 cx: &mut Context<Self>,
5436 ) -> Option<()> {
5437 let provider = self.edit_prediction_provider()?;
5438 let cursor = self.selections.newest_anchor().head();
5439 let (buffer, cursor_buffer_position) =
5440 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5441
5442 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5443 self.discard_inline_completion(false, cx);
5444 return None;
5445 }
5446
5447 if !user_requested
5448 && (!self.should_show_edit_predictions()
5449 || !self.is_focused(window)
5450 || buffer.read(cx).is_empty())
5451 {
5452 self.discard_inline_completion(false, cx);
5453 return None;
5454 }
5455
5456 self.update_visible_inline_completion(window, cx);
5457 provider.refresh(
5458 self.project.clone(),
5459 buffer,
5460 cursor_buffer_position,
5461 debounce,
5462 cx,
5463 );
5464 Some(())
5465 }
5466
5467 fn show_edit_predictions_in_menu(&self) -> bool {
5468 match self.edit_prediction_settings {
5469 EditPredictionSettings::Disabled => false,
5470 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5471 }
5472 }
5473
5474 pub fn edit_predictions_enabled(&self) -> bool {
5475 match self.edit_prediction_settings {
5476 EditPredictionSettings::Disabled => false,
5477 EditPredictionSettings::Enabled { .. } => true,
5478 }
5479 }
5480
5481 fn edit_prediction_requires_modifier(&self) -> bool {
5482 match self.edit_prediction_settings {
5483 EditPredictionSettings::Disabled => false,
5484 EditPredictionSettings::Enabled {
5485 preview_requires_modifier,
5486 ..
5487 } => preview_requires_modifier,
5488 }
5489 }
5490
5491 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5492 if self.edit_prediction_provider.is_none() {
5493 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5494 } else {
5495 let selection = self.selections.newest_anchor();
5496 let cursor = selection.head();
5497
5498 if let Some((buffer, cursor_buffer_position)) =
5499 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5500 {
5501 self.edit_prediction_settings =
5502 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5503 }
5504 }
5505 }
5506
5507 fn edit_prediction_settings_at_position(
5508 &self,
5509 buffer: &Entity<Buffer>,
5510 buffer_position: language::Anchor,
5511 cx: &App,
5512 ) -> EditPredictionSettings {
5513 if self.mode != EditorMode::Full
5514 || !self.show_inline_completions_override.unwrap_or(true)
5515 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5516 {
5517 return EditPredictionSettings::Disabled;
5518 }
5519
5520 let buffer = buffer.read(cx);
5521
5522 let file = buffer.file();
5523
5524 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5525 return EditPredictionSettings::Disabled;
5526 };
5527
5528 let by_provider = matches!(
5529 self.menu_inline_completions_policy,
5530 MenuInlineCompletionsPolicy::ByProvider
5531 );
5532
5533 let show_in_menu = by_provider
5534 && self
5535 .edit_prediction_provider
5536 .as_ref()
5537 .map_or(false, |provider| {
5538 provider.provider.show_completions_in_menu()
5539 });
5540
5541 let preview_requires_modifier =
5542 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5543
5544 EditPredictionSettings::Enabled {
5545 show_in_menu,
5546 preview_requires_modifier,
5547 }
5548 }
5549
5550 fn should_show_edit_predictions(&self) -> bool {
5551 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5552 }
5553
5554 pub fn edit_prediction_preview_is_active(&self) -> bool {
5555 matches!(
5556 self.edit_prediction_preview,
5557 EditPredictionPreview::Active { .. }
5558 )
5559 }
5560
5561 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5562 let cursor = self.selections.newest_anchor().head();
5563 if let Some((buffer, cursor_position)) =
5564 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5565 {
5566 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5567 } else {
5568 false
5569 }
5570 }
5571
5572 fn edit_predictions_enabled_in_buffer(
5573 &self,
5574 buffer: &Entity<Buffer>,
5575 buffer_position: language::Anchor,
5576 cx: &App,
5577 ) -> bool {
5578 maybe!({
5579 if self.read_only(cx) {
5580 return Some(false);
5581 }
5582 let provider = self.edit_prediction_provider()?;
5583 if !provider.is_enabled(&buffer, buffer_position, cx) {
5584 return Some(false);
5585 }
5586 let buffer = buffer.read(cx);
5587 let Some(file) = buffer.file() else {
5588 return Some(true);
5589 };
5590 let settings = all_language_settings(Some(file), cx);
5591 Some(settings.edit_predictions_enabled_for_file(file, cx))
5592 })
5593 .unwrap_or(false)
5594 }
5595
5596 fn cycle_inline_completion(
5597 &mut self,
5598 direction: Direction,
5599 window: &mut Window,
5600 cx: &mut Context<Self>,
5601 ) -> Option<()> {
5602 let provider = self.edit_prediction_provider()?;
5603 let cursor = self.selections.newest_anchor().head();
5604 let (buffer, cursor_buffer_position) =
5605 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5606 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5607 return None;
5608 }
5609
5610 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5611 self.update_visible_inline_completion(window, cx);
5612
5613 Some(())
5614 }
5615
5616 pub fn show_inline_completion(
5617 &mut self,
5618 _: &ShowEditPrediction,
5619 window: &mut Window,
5620 cx: &mut Context<Self>,
5621 ) {
5622 if !self.has_active_inline_completion() {
5623 self.refresh_inline_completion(false, true, window, cx);
5624 return;
5625 }
5626
5627 self.update_visible_inline_completion(window, cx);
5628 }
5629
5630 pub fn display_cursor_names(
5631 &mut self,
5632 _: &DisplayCursorNames,
5633 window: &mut Window,
5634 cx: &mut Context<Self>,
5635 ) {
5636 self.show_cursor_names(window, cx);
5637 }
5638
5639 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5640 self.show_cursor_names = true;
5641 cx.notify();
5642 cx.spawn_in(window, async move |this, cx| {
5643 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5644 this.update(cx, |this, cx| {
5645 this.show_cursor_names = false;
5646 cx.notify()
5647 })
5648 .ok()
5649 })
5650 .detach();
5651 }
5652
5653 pub fn next_edit_prediction(
5654 &mut self,
5655 _: &NextEditPrediction,
5656 window: &mut Window,
5657 cx: &mut Context<Self>,
5658 ) {
5659 if self.has_active_inline_completion() {
5660 self.cycle_inline_completion(Direction::Next, window, cx);
5661 } else {
5662 let is_copilot_disabled = self
5663 .refresh_inline_completion(false, true, window, cx)
5664 .is_none();
5665 if is_copilot_disabled {
5666 cx.propagate();
5667 }
5668 }
5669 }
5670
5671 pub fn previous_edit_prediction(
5672 &mut self,
5673 _: &PreviousEditPrediction,
5674 window: &mut Window,
5675 cx: &mut Context<Self>,
5676 ) {
5677 if self.has_active_inline_completion() {
5678 self.cycle_inline_completion(Direction::Prev, window, cx);
5679 } else {
5680 let is_copilot_disabled = self
5681 .refresh_inline_completion(false, true, window, cx)
5682 .is_none();
5683 if is_copilot_disabled {
5684 cx.propagate();
5685 }
5686 }
5687 }
5688
5689 pub fn accept_edit_prediction(
5690 &mut self,
5691 _: &AcceptEditPrediction,
5692 window: &mut Window,
5693 cx: &mut Context<Self>,
5694 ) {
5695 if self.show_edit_predictions_in_menu() {
5696 self.hide_context_menu(window, cx);
5697 }
5698
5699 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5700 return;
5701 };
5702
5703 self.report_inline_completion_event(
5704 active_inline_completion.completion_id.clone(),
5705 true,
5706 cx,
5707 );
5708
5709 match &active_inline_completion.completion {
5710 InlineCompletion::Move { target, .. } => {
5711 let target = *target;
5712
5713 if let Some(position_map) = &self.last_position_map {
5714 if position_map
5715 .visible_row_range
5716 .contains(&target.to_display_point(&position_map.snapshot).row())
5717 || !self.edit_prediction_requires_modifier()
5718 {
5719 self.unfold_ranges(&[target..target], true, false, cx);
5720 // Note that this is also done in vim's handler of the Tab action.
5721 self.change_selections(
5722 Some(Autoscroll::newest()),
5723 window,
5724 cx,
5725 |selections| {
5726 selections.select_anchor_ranges([target..target]);
5727 },
5728 );
5729 self.clear_row_highlights::<EditPredictionPreview>();
5730
5731 self.edit_prediction_preview
5732 .set_previous_scroll_position(None);
5733 } else {
5734 self.edit_prediction_preview
5735 .set_previous_scroll_position(Some(
5736 position_map.snapshot.scroll_anchor,
5737 ));
5738
5739 self.highlight_rows::<EditPredictionPreview>(
5740 target..target,
5741 cx.theme().colors().editor_highlighted_line_background,
5742 true,
5743 cx,
5744 );
5745 self.request_autoscroll(Autoscroll::fit(), cx);
5746 }
5747 }
5748 }
5749 InlineCompletion::Edit { edits, .. } => {
5750 if let Some(provider) = self.edit_prediction_provider() {
5751 provider.accept(cx);
5752 }
5753
5754 let snapshot = self.buffer.read(cx).snapshot(cx);
5755 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5756
5757 self.buffer.update(cx, |buffer, cx| {
5758 buffer.edit(edits.iter().cloned(), None, cx)
5759 });
5760
5761 self.change_selections(None, window, cx, |s| {
5762 s.select_anchor_ranges([last_edit_end..last_edit_end])
5763 });
5764
5765 self.update_visible_inline_completion(window, cx);
5766 if self.active_inline_completion.is_none() {
5767 self.refresh_inline_completion(true, true, window, cx);
5768 }
5769
5770 cx.notify();
5771 }
5772 }
5773
5774 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5775 }
5776
5777 pub fn accept_partial_inline_completion(
5778 &mut self,
5779 _: &AcceptPartialEditPrediction,
5780 window: &mut Window,
5781 cx: &mut Context<Self>,
5782 ) {
5783 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5784 return;
5785 };
5786 if self.selections.count() != 1 {
5787 return;
5788 }
5789
5790 self.report_inline_completion_event(
5791 active_inline_completion.completion_id.clone(),
5792 true,
5793 cx,
5794 );
5795
5796 match &active_inline_completion.completion {
5797 InlineCompletion::Move { target, .. } => {
5798 let target = *target;
5799 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5800 selections.select_anchor_ranges([target..target]);
5801 });
5802 }
5803 InlineCompletion::Edit { edits, .. } => {
5804 // Find an insertion that starts at the cursor position.
5805 let snapshot = self.buffer.read(cx).snapshot(cx);
5806 let cursor_offset = self.selections.newest::<usize>(cx).head();
5807 let insertion = edits.iter().find_map(|(range, text)| {
5808 let range = range.to_offset(&snapshot);
5809 if range.is_empty() && range.start == cursor_offset {
5810 Some(text)
5811 } else {
5812 None
5813 }
5814 });
5815
5816 if let Some(text) = insertion {
5817 let mut partial_completion = text
5818 .chars()
5819 .by_ref()
5820 .take_while(|c| c.is_alphabetic())
5821 .collect::<String>();
5822 if partial_completion.is_empty() {
5823 partial_completion = text
5824 .chars()
5825 .by_ref()
5826 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5827 .collect::<String>();
5828 }
5829
5830 cx.emit(EditorEvent::InputHandled {
5831 utf16_range_to_replace: None,
5832 text: partial_completion.clone().into(),
5833 });
5834
5835 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5836
5837 self.refresh_inline_completion(true, true, window, cx);
5838 cx.notify();
5839 } else {
5840 self.accept_edit_prediction(&Default::default(), window, cx);
5841 }
5842 }
5843 }
5844 }
5845
5846 fn discard_inline_completion(
5847 &mut self,
5848 should_report_inline_completion_event: bool,
5849 cx: &mut Context<Self>,
5850 ) -> bool {
5851 if should_report_inline_completion_event {
5852 let completion_id = self
5853 .active_inline_completion
5854 .as_ref()
5855 .and_then(|active_completion| active_completion.completion_id.clone());
5856
5857 self.report_inline_completion_event(completion_id, false, cx);
5858 }
5859
5860 if let Some(provider) = self.edit_prediction_provider() {
5861 provider.discard(cx);
5862 }
5863
5864 self.take_active_inline_completion(cx)
5865 }
5866
5867 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5868 let Some(provider) = self.edit_prediction_provider() else {
5869 return;
5870 };
5871
5872 let Some((_, buffer, _)) = self
5873 .buffer
5874 .read(cx)
5875 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5876 else {
5877 return;
5878 };
5879
5880 let extension = buffer
5881 .read(cx)
5882 .file()
5883 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5884
5885 let event_type = match accepted {
5886 true => "Edit Prediction Accepted",
5887 false => "Edit Prediction Discarded",
5888 };
5889 telemetry::event!(
5890 event_type,
5891 provider = provider.name(),
5892 prediction_id = id,
5893 suggestion_accepted = accepted,
5894 file_extension = extension,
5895 );
5896 }
5897
5898 pub fn has_active_inline_completion(&self) -> bool {
5899 self.active_inline_completion.is_some()
5900 }
5901
5902 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5903 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5904 return false;
5905 };
5906
5907 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5908 self.clear_highlights::<InlineCompletionHighlight>(cx);
5909 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5910 true
5911 }
5912
5913 /// Returns true when we're displaying the edit prediction popover below the cursor
5914 /// like we are not previewing and the LSP autocomplete menu is visible
5915 /// or we are in `when_holding_modifier` mode.
5916 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5917 if self.edit_prediction_preview_is_active()
5918 || !self.show_edit_predictions_in_menu()
5919 || !self.edit_predictions_enabled()
5920 {
5921 return false;
5922 }
5923
5924 if self.has_visible_completions_menu() {
5925 return true;
5926 }
5927
5928 has_completion && self.edit_prediction_requires_modifier()
5929 }
5930
5931 fn handle_modifiers_changed(
5932 &mut self,
5933 modifiers: Modifiers,
5934 position_map: &PositionMap,
5935 window: &mut Window,
5936 cx: &mut Context<Self>,
5937 ) {
5938 if self.show_edit_predictions_in_menu() {
5939 self.update_edit_prediction_preview(&modifiers, window, cx);
5940 }
5941
5942 self.update_selection_mode(&modifiers, position_map, window, cx);
5943
5944 let mouse_position = window.mouse_position();
5945 if !position_map.text_hitbox.is_hovered(window) {
5946 return;
5947 }
5948
5949 self.update_hovered_link(
5950 position_map.point_for_position(mouse_position),
5951 &position_map.snapshot,
5952 modifiers,
5953 window,
5954 cx,
5955 )
5956 }
5957
5958 fn update_selection_mode(
5959 &mut self,
5960 modifiers: &Modifiers,
5961 position_map: &PositionMap,
5962 window: &mut Window,
5963 cx: &mut Context<Self>,
5964 ) {
5965 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5966 return;
5967 }
5968
5969 let mouse_position = window.mouse_position();
5970 let point_for_position = position_map.point_for_position(mouse_position);
5971 let position = point_for_position.previous_valid;
5972
5973 self.select(
5974 SelectPhase::BeginColumnar {
5975 position,
5976 reset: false,
5977 goal_column: point_for_position.exact_unclipped.column(),
5978 },
5979 window,
5980 cx,
5981 );
5982 }
5983
5984 fn update_edit_prediction_preview(
5985 &mut self,
5986 modifiers: &Modifiers,
5987 window: &mut Window,
5988 cx: &mut Context<Self>,
5989 ) {
5990 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5991 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5992 return;
5993 };
5994
5995 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5996 if matches!(
5997 self.edit_prediction_preview,
5998 EditPredictionPreview::Inactive { .. }
5999 ) {
6000 self.edit_prediction_preview = EditPredictionPreview::Active {
6001 previous_scroll_position: None,
6002 since: Instant::now(),
6003 };
6004
6005 self.update_visible_inline_completion(window, cx);
6006 cx.notify();
6007 }
6008 } else if let EditPredictionPreview::Active {
6009 previous_scroll_position,
6010 since,
6011 } = self.edit_prediction_preview
6012 {
6013 if let (Some(previous_scroll_position), Some(position_map)) =
6014 (previous_scroll_position, self.last_position_map.as_ref())
6015 {
6016 self.set_scroll_position(
6017 previous_scroll_position
6018 .scroll_position(&position_map.snapshot.display_snapshot),
6019 window,
6020 cx,
6021 );
6022 }
6023
6024 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6025 released_too_fast: since.elapsed() < Duration::from_millis(200),
6026 };
6027 self.clear_row_highlights::<EditPredictionPreview>();
6028 self.update_visible_inline_completion(window, cx);
6029 cx.notify();
6030 }
6031 }
6032
6033 fn update_visible_inline_completion(
6034 &mut self,
6035 _window: &mut Window,
6036 cx: &mut Context<Self>,
6037 ) -> Option<()> {
6038 let selection = self.selections.newest_anchor();
6039 let cursor = selection.head();
6040 let multibuffer = self.buffer.read(cx).snapshot(cx);
6041 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6042 let excerpt_id = cursor.excerpt_id;
6043
6044 let show_in_menu = self.show_edit_predictions_in_menu();
6045 let completions_menu_has_precedence = !show_in_menu
6046 && (self.context_menu.borrow().is_some()
6047 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6048
6049 if completions_menu_has_precedence
6050 || !offset_selection.is_empty()
6051 || self
6052 .active_inline_completion
6053 .as_ref()
6054 .map_or(false, |completion| {
6055 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6056 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6057 !invalidation_range.contains(&offset_selection.head())
6058 })
6059 {
6060 self.discard_inline_completion(false, cx);
6061 return None;
6062 }
6063
6064 self.take_active_inline_completion(cx);
6065 let Some(provider) = self.edit_prediction_provider() else {
6066 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6067 return None;
6068 };
6069
6070 let (buffer, cursor_buffer_position) =
6071 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6072
6073 self.edit_prediction_settings =
6074 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6075
6076 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6077
6078 if self.edit_prediction_indent_conflict {
6079 let cursor_point = cursor.to_point(&multibuffer);
6080
6081 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6082
6083 if let Some((_, indent)) = indents.iter().next() {
6084 if indent.len == cursor_point.column {
6085 self.edit_prediction_indent_conflict = false;
6086 }
6087 }
6088 }
6089
6090 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6091 let edits = inline_completion
6092 .edits
6093 .into_iter()
6094 .flat_map(|(range, new_text)| {
6095 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6096 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6097 Some((start..end, new_text))
6098 })
6099 .collect::<Vec<_>>();
6100 if edits.is_empty() {
6101 return None;
6102 }
6103
6104 let first_edit_start = edits.first().unwrap().0.start;
6105 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6106 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6107
6108 let last_edit_end = edits.last().unwrap().0.end;
6109 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6110 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6111
6112 let cursor_row = cursor.to_point(&multibuffer).row;
6113
6114 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6115
6116 let mut inlay_ids = Vec::new();
6117 let invalidation_row_range;
6118 let move_invalidation_row_range = if cursor_row < edit_start_row {
6119 Some(cursor_row..edit_end_row)
6120 } else if cursor_row > edit_end_row {
6121 Some(edit_start_row..cursor_row)
6122 } else {
6123 None
6124 };
6125 let is_move =
6126 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6127 let completion = if is_move {
6128 invalidation_row_range =
6129 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6130 let target = first_edit_start;
6131 InlineCompletion::Move { target, snapshot }
6132 } else {
6133 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6134 && !self.inline_completions_hidden_for_vim_mode;
6135
6136 if show_completions_in_buffer {
6137 if edits
6138 .iter()
6139 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6140 {
6141 let mut inlays = Vec::new();
6142 for (range, new_text) in &edits {
6143 let inlay = Inlay::inline_completion(
6144 post_inc(&mut self.next_inlay_id),
6145 range.start,
6146 new_text.as_str(),
6147 );
6148 inlay_ids.push(inlay.id);
6149 inlays.push(inlay);
6150 }
6151
6152 self.splice_inlays(&[], inlays, cx);
6153 } else {
6154 let background_color = cx.theme().status().deleted_background;
6155 self.highlight_text::<InlineCompletionHighlight>(
6156 edits.iter().map(|(range, _)| range.clone()).collect(),
6157 HighlightStyle {
6158 background_color: Some(background_color),
6159 ..Default::default()
6160 },
6161 cx,
6162 );
6163 }
6164 }
6165
6166 invalidation_row_range = edit_start_row..edit_end_row;
6167
6168 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6169 if provider.show_tab_accept_marker() {
6170 EditDisplayMode::TabAccept
6171 } else {
6172 EditDisplayMode::Inline
6173 }
6174 } else {
6175 EditDisplayMode::DiffPopover
6176 };
6177
6178 InlineCompletion::Edit {
6179 edits,
6180 edit_preview: inline_completion.edit_preview,
6181 display_mode,
6182 snapshot,
6183 }
6184 };
6185
6186 let invalidation_range = multibuffer
6187 .anchor_before(Point::new(invalidation_row_range.start, 0))
6188 ..multibuffer.anchor_after(Point::new(
6189 invalidation_row_range.end,
6190 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6191 ));
6192
6193 self.stale_inline_completion_in_menu = None;
6194 self.active_inline_completion = Some(InlineCompletionState {
6195 inlay_ids,
6196 completion,
6197 completion_id: inline_completion.id,
6198 invalidation_range,
6199 });
6200
6201 cx.notify();
6202
6203 Some(())
6204 }
6205
6206 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6207 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6208 }
6209
6210 fn render_code_actions_indicator(
6211 &self,
6212 _style: &EditorStyle,
6213 row: DisplayRow,
6214 is_active: bool,
6215 breakpoint: Option<&(Anchor, Breakpoint)>,
6216 cx: &mut Context<Self>,
6217 ) -> Option<IconButton> {
6218 let color = Color::Muted;
6219 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6220 let show_tooltip = !self.context_menu_visible();
6221
6222 if self.available_code_actions.is_some() {
6223 Some(
6224 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6225 .shape(ui::IconButtonShape::Square)
6226 .icon_size(IconSize::XSmall)
6227 .icon_color(color)
6228 .toggle_state(is_active)
6229 .when(show_tooltip, |this| {
6230 this.tooltip({
6231 let focus_handle = self.focus_handle.clone();
6232 move |window, cx| {
6233 Tooltip::for_action_in(
6234 "Toggle Code Actions",
6235 &ToggleCodeActions {
6236 deployed_from_indicator: None,
6237 },
6238 &focus_handle,
6239 window,
6240 cx,
6241 )
6242 }
6243 })
6244 })
6245 .on_click(cx.listener(move |editor, _e, window, cx| {
6246 window.focus(&editor.focus_handle(cx));
6247 editor.toggle_code_actions(
6248 &ToggleCodeActions {
6249 deployed_from_indicator: Some(row),
6250 },
6251 window,
6252 cx,
6253 );
6254 }))
6255 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6256 editor.set_breakpoint_context_menu(
6257 row,
6258 position,
6259 event.down.position,
6260 window,
6261 cx,
6262 );
6263 })),
6264 )
6265 } else {
6266 None
6267 }
6268 }
6269
6270 fn clear_tasks(&mut self) {
6271 self.tasks.clear()
6272 }
6273
6274 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6275 if self.tasks.insert(key, value).is_some() {
6276 // This case should hopefully be rare, but just in case...
6277 log::error!(
6278 "multiple different run targets found on a single line, only the last target will be rendered"
6279 )
6280 }
6281 }
6282
6283 /// Get all display points of breakpoints that will be rendered within editor
6284 ///
6285 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6286 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6287 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6288 fn active_breakpoints(
6289 &self,
6290 range: Range<DisplayRow>,
6291 window: &mut Window,
6292 cx: &mut Context<Self>,
6293 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6294 let mut breakpoint_display_points = HashMap::default();
6295
6296 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6297 return breakpoint_display_points;
6298 };
6299
6300 let snapshot = self.snapshot(window, cx);
6301
6302 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6303 let Some(project) = self.project.as_ref() else {
6304 return breakpoint_display_points;
6305 };
6306
6307 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6308 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6309
6310 for (buffer_snapshot, range, excerpt_id) in
6311 multi_buffer_snapshot.range_to_buffer_ranges(range)
6312 {
6313 let Some(buffer) = project.read_with(cx, |this, cx| {
6314 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6315 }) else {
6316 continue;
6317 };
6318 let breakpoints = breakpoint_store.read(cx).breakpoints(
6319 &buffer,
6320 Some(
6321 buffer_snapshot.anchor_before(range.start)
6322 ..buffer_snapshot.anchor_after(range.end),
6323 ),
6324 buffer_snapshot,
6325 cx,
6326 );
6327 for (anchor, breakpoint) in breakpoints {
6328 let multi_buffer_anchor =
6329 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6330 let position = multi_buffer_anchor
6331 .to_point(&multi_buffer_snapshot)
6332 .to_display_point(&snapshot);
6333
6334 breakpoint_display_points
6335 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6336 }
6337 }
6338
6339 breakpoint_display_points
6340 }
6341
6342 fn breakpoint_context_menu(
6343 &self,
6344 anchor: Anchor,
6345 window: &mut Window,
6346 cx: &mut Context<Self>,
6347 ) -> Entity<ui::ContextMenu> {
6348 let weak_editor = cx.weak_entity();
6349 let focus_handle = self.focus_handle(cx);
6350
6351 let row = self
6352 .buffer
6353 .read(cx)
6354 .snapshot(cx)
6355 .summary_for_anchor::<Point>(&anchor)
6356 .row;
6357
6358 let breakpoint = self
6359 .breakpoint_at_row(row, window, cx)
6360 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6361
6362 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6363 "Edit Log Breakpoint"
6364 } else {
6365 "Set Log Breakpoint"
6366 };
6367
6368 let condition_breakpoint_msg = if breakpoint
6369 .as_ref()
6370 .is_some_and(|bp| bp.1.condition.is_some())
6371 {
6372 "Edit Condition Breakpoint"
6373 } else {
6374 "Set Condition Breakpoint"
6375 };
6376
6377 let hit_condition_breakpoint_msg = if breakpoint
6378 .as_ref()
6379 .is_some_and(|bp| bp.1.hit_condition.is_some())
6380 {
6381 "Edit Hit Condition Breakpoint"
6382 } else {
6383 "Set Hit Condition Breakpoint"
6384 };
6385
6386 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6387 "Unset Breakpoint"
6388 } else {
6389 "Set Breakpoint"
6390 };
6391
6392 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6393 BreakpointState::Enabled => Some("Disable"),
6394 BreakpointState::Disabled => Some("Enable"),
6395 });
6396
6397 let (anchor, breakpoint) =
6398 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6399
6400 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6401 menu.on_blur_subscription(Subscription::new(|| {}))
6402 .context(focus_handle)
6403 .when_some(toggle_state_msg, |this, msg| {
6404 this.entry(msg, None, {
6405 let weak_editor = weak_editor.clone();
6406 let breakpoint = breakpoint.clone();
6407 move |_window, cx| {
6408 weak_editor
6409 .update(cx, |this, cx| {
6410 this.edit_breakpoint_at_anchor(
6411 anchor,
6412 breakpoint.as_ref().clone(),
6413 BreakpointEditAction::InvertState,
6414 cx,
6415 );
6416 })
6417 .log_err();
6418 }
6419 })
6420 })
6421 .entry(set_breakpoint_msg, None, {
6422 let weak_editor = weak_editor.clone();
6423 let breakpoint = breakpoint.clone();
6424 move |_window, cx| {
6425 weak_editor
6426 .update(cx, |this, cx| {
6427 this.edit_breakpoint_at_anchor(
6428 anchor,
6429 breakpoint.as_ref().clone(),
6430 BreakpointEditAction::Toggle,
6431 cx,
6432 );
6433 })
6434 .log_err();
6435 }
6436 })
6437 .entry(log_breakpoint_msg, None, {
6438 let breakpoint = breakpoint.clone();
6439 let weak_editor = weak_editor.clone();
6440 move |window, cx| {
6441 weak_editor
6442 .update(cx, |this, cx| {
6443 this.add_edit_breakpoint_block(
6444 anchor,
6445 breakpoint.as_ref(),
6446 BreakpointPromptEditAction::Log,
6447 window,
6448 cx,
6449 );
6450 })
6451 .log_err();
6452 }
6453 })
6454 .entry(condition_breakpoint_msg, None, {
6455 let breakpoint = breakpoint.clone();
6456 let weak_editor = weak_editor.clone();
6457 move |window, cx| {
6458 weak_editor
6459 .update(cx, |this, cx| {
6460 this.add_edit_breakpoint_block(
6461 anchor,
6462 breakpoint.as_ref(),
6463 BreakpointPromptEditAction::Condition,
6464 window,
6465 cx,
6466 );
6467 })
6468 .log_err();
6469 }
6470 })
6471 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6472 weak_editor
6473 .update(cx, |this, cx| {
6474 this.add_edit_breakpoint_block(
6475 anchor,
6476 breakpoint.as_ref(),
6477 BreakpointPromptEditAction::HitCondition,
6478 window,
6479 cx,
6480 );
6481 })
6482 .log_err();
6483 })
6484 })
6485 }
6486
6487 fn render_breakpoint(
6488 &self,
6489 position: Anchor,
6490 row: DisplayRow,
6491 breakpoint: &Breakpoint,
6492 cx: &mut Context<Self>,
6493 ) -> IconButton {
6494 let (color, icon) = {
6495 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6496 (false, false) => ui::IconName::DebugBreakpoint,
6497 (true, false) => ui::IconName::DebugLogBreakpoint,
6498 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6499 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6500 };
6501
6502 let color = if self
6503 .gutter_breakpoint_indicator
6504 .0
6505 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6506 {
6507 Color::Hint
6508 } else {
6509 Color::Debugger
6510 };
6511
6512 (color, icon)
6513 };
6514
6515 let breakpoint = Arc::from(breakpoint.clone());
6516
6517 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6518 .icon_size(IconSize::XSmall)
6519 .size(ui::ButtonSize::None)
6520 .icon_color(color)
6521 .style(ButtonStyle::Transparent)
6522 .on_click(cx.listener({
6523 let breakpoint = breakpoint.clone();
6524
6525 move |editor, event: &ClickEvent, window, cx| {
6526 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6527 BreakpointEditAction::InvertState
6528 } else {
6529 BreakpointEditAction::Toggle
6530 };
6531
6532 window.focus(&editor.focus_handle(cx));
6533 editor.edit_breakpoint_at_anchor(
6534 position,
6535 breakpoint.as_ref().clone(),
6536 edit_action,
6537 cx,
6538 );
6539 }
6540 }))
6541 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6542 editor.set_breakpoint_context_menu(
6543 row,
6544 Some(position),
6545 event.down.position,
6546 window,
6547 cx,
6548 );
6549 }))
6550 }
6551
6552 fn build_tasks_context(
6553 project: &Entity<Project>,
6554 buffer: &Entity<Buffer>,
6555 buffer_row: u32,
6556 tasks: &Arc<RunnableTasks>,
6557 cx: &mut Context<Self>,
6558 ) -> Task<Option<task::TaskContext>> {
6559 let position = Point::new(buffer_row, tasks.column);
6560 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6561 let location = Location {
6562 buffer: buffer.clone(),
6563 range: range_start..range_start,
6564 };
6565 // Fill in the environmental variables from the tree-sitter captures
6566 let mut captured_task_variables = TaskVariables::default();
6567 for (capture_name, value) in tasks.extra_variables.clone() {
6568 captured_task_variables.insert(
6569 task::VariableName::Custom(capture_name.into()),
6570 value.clone(),
6571 );
6572 }
6573 project.update(cx, |project, cx| {
6574 project.task_store().update(cx, |task_store, cx| {
6575 task_store.task_context_for_location(captured_task_variables, location, cx)
6576 })
6577 })
6578 }
6579
6580 pub fn spawn_nearest_task(
6581 &mut self,
6582 action: &SpawnNearestTask,
6583 window: &mut Window,
6584 cx: &mut Context<Self>,
6585 ) {
6586 let Some((workspace, _)) = self.workspace.clone() else {
6587 return;
6588 };
6589 let Some(project) = self.project.clone() else {
6590 return;
6591 };
6592
6593 // Try to find a closest, enclosing node using tree-sitter that has a
6594 // task
6595 let Some((buffer, buffer_row, tasks)) = self
6596 .find_enclosing_node_task(cx)
6597 // Or find the task that's closest in row-distance.
6598 .or_else(|| self.find_closest_task(cx))
6599 else {
6600 return;
6601 };
6602
6603 let reveal_strategy = action.reveal;
6604 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6605 cx.spawn_in(window, async move |_, cx| {
6606 let context = task_context.await?;
6607 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6608
6609 let resolved = resolved_task.resolved.as_mut()?;
6610 resolved.reveal = reveal_strategy;
6611
6612 workspace
6613 .update(cx, |workspace, cx| {
6614 workspace::tasks::schedule_resolved_task(
6615 workspace,
6616 task_source_kind,
6617 resolved_task,
6618 false,
6619 cx,
6620 );
6621 })
6622 .ok()
6623 })
6624 .detach();
6625 }
6626
6627 fn find_closest_task(
6628 &mut self,
6629 cx: &mut Context<Self>,
6630 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6631 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6632
6633 let ((buffer_id, row), tasks) = self
6634 .tasks
6635 .iter()
6636 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6637
6638 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6639 let tasks = Arc::new(tasks.to_owned());
6640 Some((buffer, *row, tasks))
6641 }
6642
6643 fn find_enclosing_node_task(
6644 &mut self,
6645 cx: &mut Context<Self>,
6646 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6647 let snapshot = self.buffer.read(cx).snapshot(cx);
6648 let offset = self.selections.newest::<usize>(cx).head();
6649 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6650 let buffer_id = excerpt.buffer().remote_id();
6651
6652 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6653 let mut cursor = layer.node().walk();
6654
6655 while cursor.goto_first_child_for_byte(offset).is_some() {
6656 if cursor.node().end_byte() == offset {
6657 cursor.goto_next_sibling();
6658 }
6659 }
6660
6661 // Ascend to the smallest ancestor that contains the range and has a task.
6662 loop {
6663 let node = cursor.node();
6664 let node_range = node.byte_range();
6665 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6666
6667 // Check if this node contains our offset
6668 if node_range.start <= offset && node_range.end >= offset {
6669 // If it contains offset, check for task
6670 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6671 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6672 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6673 }
6674 }
6675
6676 if !cursor.goto_parent() {
6677 break;
6678 }
6679 }
6680 None
6681 }
6682
6683 fn render_run_indicator(
6684 &self,
6685 _style: &EditorStyle,
6686 is_active: bool,
6687 row: DisplayRow,
6688 breakpoint: Option<(Anchor, Breakpoint)>,
6689 cx: &mut Context<Self>,
6690 ) -> IconButton {
6691 let color = Color::Muted;
6692 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6693
6694 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6695 .shape(ui::IconButtonShape::Square)
6696 .icon_size(IconSize::XSmall)
6697 .icon_color(color)
6698 .toggle_state(is_active)
6699 .on_click(cx.listener(move |editor, _e, window, cx| {
6700 window.focus(&editor.focus_handle(cx));
6701 editor.toggle_code_actions(
6702 &ToggleCodeActions {
6703 deployed_from_indicator: Some(row),
6704 },
6705 window,
6706 cx,
6707 );
6708 }))
6709 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6710 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6711 }))
6712 }
6713
6714 pub fn context_menu_visible(&self) -> bool {
6715 !self.edit_prediction_preview_is_active()
6716 && self
6717 .context_menu
6718 .borrow()
6719 .as_ref()
6720 .map_or(false, |menu| menu.visible())
6721 }
6722
6723 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6724 self.context_menu
6725 .borrow()
6726 .as_ref()
6727 .map(|menu| menu.origin())
6728 }
6729
6730 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6731 self.context_menu_options = Some(options);
6732 }
6733
6734 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6735 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6736
6737 fn render_edit_prediction_popover(
6738 &mut self,
6739 text_bounds: &Bounds<Pixels>,
6740 content_origin: gpui::Point<Pixels>,
6741 editor_snapshot: &EditorSnapshot,
6742 visible_row_range: Range<DisplayRow>,
6743 scroll_top: f32,
6744 scroll_bottom: f32,
6745 line_layouts: &[LineWithInvisibles],
6746 line_height: Pixels,
6747 scroll_pixel_position: gpui::Point<Pixels>,
6748 newest_selection_head: Option<DisplayPoint>,
6749 editor_width: Pixels,
6750 style: &EditorStyle,
6751 window: &mut Window,
6752 cx: &mut App,
6753 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6754 let active_inline_completion = self.active_inline_completion.as_ref()?;
6755
6756 if self.edit_prediction_visible_in_cursor_popover(true) {
6757 return None;
6758 }
6759
6760 match &active_inline_completion.completion {
6761 InlineCompletion::Move { target, .. } => {
6762 let target_display_point = target.to_display_point(editor_snapshot);
6763
6764 if self.edit_prediction_requires_modifier() {
6765 if !self.edit_prediction_preview_is_active() {
6766 return None;
6767 }
6768
6769 self.render_edit_prediction_modifier_jump_popover(
6770 text_bounds,
6771 content_origin,
6772 visible_row_range,
6773 line_layouts,
6774 line_height,
6775 scroll_pixel_position,
6776 newest_selection_head,
6777 target_display_point,
6778 window,
6779 cx,
6780 )
6781 } else {
6782 self.render_edit_prediction_eager_jump_popover(
6783 text_bounds,
6784 content_origin,
6785 editor_snapshot,
6786 visible_row_range,
6787 scroll_top,
6788 scroll_bottom,
6789 line_height,
6790 scroll_pixel_position,
6791 target_display_point,
6792 editor_width,
6793 window,
6794 cx,
6795 )
6796 }
6797 }
6798 InlineCompletion::Edit {
6799 display_mode: EditDisplayMode::Inline,
6800 ..
6801 } => None,
6802 InlineCompletion::Edit {
6803 display_mode: EditDisplayMode::TabAccept,
6804 edits,
6805 ..
6806 } => {
6807 let range = &edits.first()?.0;
6808 let target_display_point = range.end.to_display_point(editor_snapshot);
6809
6810 self.render_edit_prediction_end_of_line_popover(
6811 "Accept",
6812 editor_snapshot,
6813 visible_row_range,
6814 target_display_point,
6815 line_height,
6816 scroll_pixel_position,
6817 content_origin,
6818 editor_width,
6819 window,
6820 cx,
6821 )
6822 }
6823 InlineCompletion::Edit {
6824 edits,
6825 edit_preview,
6826 display_mode: EditDisplayMode::DiffPopover,
6827 snapshot,
6828 } => self.render_edit_prediction_diff_popover(
6829 text_bounds,
6830 content_origin,
6831 editor_snapshot,
6832 visible_row_range,
6833 line_layouts,
6834 line_height,
6835 scroll_pixel_position,
6836 newest_selection_head,
6837 editor_width,
6838 style,
6839 edits,
6840 edit_preview,
6841 snapshot,
6842 window,
6843 cx,
6844 ),
6845 }
6846 }
6847
6848 fn render_edit_prediction_modifier_jump_popover(
6849 &mut self,
6850 text_bounds: &Bounds<Pixels>,
6851 content_origin: gpui::Point<Pixels>,
6852 visible_row_range: Range<DisplayRow>,
6853 line_layouts: &[LineWithInvisibles],
6854 line_height: Pixels,
6855 scroll_pixel_position: gpui::Point<Pixels>,
6856 newest_selection_head: Option<DisplayPoint>,
6857 target_display_point: DisplayPoint,
6858 window: &mut Window,
6859 cx: &mut App,
6860 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6861 let scrolled_content_origin =
6862 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6863
6864 const SCROLL_PADDING_Y: Pixels = px(12.);
6865
6866 if target_display_point.row() < visible_row_range.start {
6867 return self.render_edit_prediction_scroll_popover(
6868 |_| SCROLL_PADDING_Y,
6869 IconName::ArrowUp,
6870 visible_row_range,
6871 line_layouts,
6872 newest_selection_head,
6873 scrolled_content_origin,
6874 window,
6875 cx,
6876 );
6877 } else if target_display_point.row() >= visible_row_range.end {
6878 return self.render_edit_prediction_scroll_popover(
6879 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6880 IconName::ArrowDown,
6881 visible_row_range,
6882 line_layouts,
6883 newest_selection_head,
6884 scrolled_content_origin,
6885 window,
6886 cx,
6887 );
6888 }
6889
6890 const POLE_WIDTH: Pixels = px(2.);
6891
6892 let line_layout =
6893 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6894 let target_column = target_display_point.column() as usize;
6895
6896 let target_x = line_layout.x_for_index(target_column);
6897 let target_y =
6898 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6899
6900 let flag_on_right = target_x < text_bounds.size.width / 2.;
6901
6902 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6903 border_color.l += 0.001;
6904
6905 let mut element = v_flex()
6906 .items_end()
6907 .when(flag_on_right, |el| el.items_start())
6908 .child(if flag_on_right {
6909 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6910 .rounded_bl(px(0.))
6911 .rounded_tl(px(0.))
6912 .border_l_2()
6913 .border_color(border_color)
6914 } else {
6915 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6916 .rounded_br(px(0.))
6917 .rounded_tr(px(0.))
6918 .border_r_2()
6919 .border_color(border_color)
6920 })
6921 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6922 .into_any();
6923
6924 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6925
6926 let mut origin = scrolled_content_origin + point(target_x, target_y)
6927 - point(
6928 if flag_on_right {
6929 POLE_WIDTH
6930 } else {
6931 size.width - POLE_WIDTH
6932 },
6933 size.height - line_height,
6934 );
6935
6936 origin.x = origin.x.max(content_origin.x);
6937
6938 element.prepaint_at(origin, window, cx);
6939
6940 Some((element, origin))
6941 }
6942
6943 fn render_edit_prediction_scroll_popover(
6944 &mut self,
6945 to_y: impl Fn(Size<Pixels>) -> Pixels,
6946 scroll_icon: IconName,
6947 visible_row_range: Range<DisplayRow>,
6948 line_layouts: &[LineWithInvisibles],
6949 newest_selection_head: Option<DisplayPoint>,
6950 scrolled_content_origin: gpui::Point<Pixels>,
6951 window: &mut Window,
6952 cx: &mut App,
6953 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6954 let mut element = self
6955 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6956 .into_any();
6957
6958 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6959
6960 let cursor = newest_selection_head?;
6961 let cursor_row_layout =
6962 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6963 let cursor_column = cursor.column() as usize;
6964
6965 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6966
6967 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6968
6969 element.prepaint_at(origin, window, cx);
6970 Some((element, origin))
6971 }
6972
6973 fn render_edit_prediction_eager_jump_popover(
6974 &mut self,
6975 text_bounds: &Bounds<Pixels>,
6976 content_origin: gpui::Point<Pixels>,
6977 editor_snapshot: &EditorSnapshot,
6978 visible_row_range: Range<DisplayRow>,
6979 scroll_top: f32,
6980 scroll_bottom: f32,
6981 line_height: Pixels,
6982 scroll_pixel_position: gpui::Point<Pixels>,
6983 target_display_point: DisplayPoint,
6984 editor_width: Pixels,
6985 window: &mut Window,
6986 cx: &mut App,
6987 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6988 if target_display_point.row().as_f32() < scroll_top {
6989 let mut element = self
6990 .render_edit_prediction_line_popover(
6991 "Jump to Edit",
6992 Some(IconName::ArrowUp),
6993 window,
6994 cx,
6995 )?
6996 .into_any();
6997
6998 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6999 let offset = point(
7000 (text_bounds.size.width - size.width) / 2.,
7001 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7002 );
7003
7004 let origin = text_bounds.origin + offset;
7005 element.prepaint_at(origin, window, cx);
7006 Some((element, origin))
7007 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7008 let mut element = self
7009 .render_edit_prediction_line_popover(
7010 "Jump to Edit",
7011 Some(IconName::ArrowDown),
7012 window,
7013 cx,
7014 )?
7015 .into_any();
7016
7017 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7018 let offset = point(
7019 (text_bounds.size.width - size.width) / 2.,
7020 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7021 );
7022
7023 let origin = text_bounds.origin + offset;
7024 element.prepaint_at(origin, window, cx);
7025 Some((element, origin))
7026 } else {
7027 self.render_edit_prediction_end_of_line_popover(
7028 "Jump to Edit",
7029 editor_snapshot,
7030 visible_row_range,
7031 target_display_point,
7032 line_height,
7033 scroll_pixel_position,
7034 content_origin,
7035 editor_width,
7036 window,
7037 cx,
7038 )
7039 }
7040 }
7041
7042 fn render_edit_prediction_end_of_line_popover(
7043 self: &mut Editor,
7044 label: &'static str,
7045 editor_snapshot: &EditorSnapshot,
7046 visible_row_range: Range<DisplayRow>,
7047 target_display_point: DisplayPoint,
7048 line_height: Pixels,
7049 scroll_pixel_position: gpui::Point<Pixels>,
7050 content_origin: gpui::Point<Pixels>,
7051 editor_width: Pixels,
7052 window: &mut Window,
7053 cx: &mut App,
7054 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7055 let target_line_end = DisplayPoint::new(
7056 target_display_point.row(),
7057 editor_snapshot.line_len(target_display_point.row()),
7058 );
7059
7060 let mut element = self
7061 .render_edit_prediction_line_popover(label, None, window, cx)?
7062 .into_any();
7063
7064 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7065
7066 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7067
7068 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7069 let mut origin = start_point
7070 + line_origin
7071 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7072 origin.x = origin.x.max(content_origin.x);
7073
7074 let max_x = content_origin.x + editor_width - size.width;
7075
7076 if origin.x > max_x {
7077 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7078
7079 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7080 origin.y += offset;
7081 IconName::ArrowUp
7082 } else {
7083 origin.y -= offset;
7084 IconName::ArrowDown
7085 };
7086
7087 element = self
7088 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7089 .into_any();
7090
7091 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7092
7093 origin.x = content_origin.x + editor_width - size.width - px(2.);
7094 }
7095
7096 element.prepaint_at(origin, window, cx);
7097 Some((element, origin))
7098 }
7099
7100 fn render_edit_prediction_diff_popover(
7101 self: &Editor,
7102 text_bounds: &Bounds<Pixels>,
7103 content_origin: gpui::Point<Pixels>,
7104 editor_snapshot: &EditorSnapshot,
7105 visible_row_range: Range<DisplayRow>,
7106 line_layouts: &[LineWithInvisibles],
7107 line_height: Pixels,
7108 scroll_pixel_position: gpui::Point<Pixels>,
7109 newest_selection_head: Option<DisplayPoint>,
7110 editor_width: Pixels,
7111 style: &EditorStyle,
7112 edits: &Vec<(Range<Anchor>, String)>,
7113 edit_preview: &Option<language::EditPreview>,
7114 snapshot: &language::BufferSnapshot,
7115 window: &mut Window,
7116 cx: &mut App,
7117 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7118 let edit_start = edits
7119 .first()
7120 .unwrap()
7121 .0
7122 .start
7123 .to_display_point(editor_snapshot);
7124 let edit_end = edits
7125 .last()
7126 .unwrap()
7127 .0
7128 .end
7129 .to_display_point(editor_snapshot);
7130
7131 let is_visible = visible_row_range.contains(&edit_start.row())
7132 || visible_row_range.contains(&edit_end.row());
7133 if !is_visible {
7134 return None;
7135 }
7136
7137 let highlighted_edits =
7138 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7139
7140 let styled_text = highlighted_edits.to_styled_text(&style.text);
7141 let line_count = highlighted_edits.text.lines().count();
7142
7143 const BORDER_WIDTH: Pixels = px(1.);
7144
7145 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7146 let has_keybind = keybind.is_some();
7147
7148 let mut element = h_flex()
7149 .items_start()
7150 .child(
7151 h_flex()
7152 .bg(cx.theme().colors().editor_background)
7153 .border(BORDER_WIDTH)
7154 .shadow_sm()
7155 .border_color(cx.theme().colors().border)
7156 .rounded_l_lg()
7157 .when(line_count > 1, |el| el.rounded_br_lg())
7158 .pr_1()
7159 .child(styled_text),
7160 )
7161 .child(
7162 h_flex()
7163 .h(line_height + BORDER_WIDTH * 2.)
7164 .px_1p5()
7165 .gap_1()
7166 // Workaround: For some reason, there's a gap if we don't do this
7167 .ml(-BORDER_WIDTH)
7168 .shadow(smallvec![gpui::BoxShadow {
7169 color: gpui::black().opacity(0.05),
7170 offset: point(px(1.), px(1.)),
7171 blur_radius: px(2.),
7172 spread_radius: px(0.),
7173 }])
7174 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7175 .border(BORDER_WIDTH)
7176 .border_color(cx.theme().colors().border)
7177 .rounded_r_lg()
7178 .id("edit_prediction_diff_popover_keybind")
7179 .when(!has_keybind, |el| {
7180 let status_colors = cx.theme().status();
7181
7182 el.bg(status_colors.error_background)
7183 .border_color(status_colors.error.opacity(0.6))
7184 .child(Icon::new(IconName::Info).color(Color::Error))
7185 .cursor_default()
7186 .hoverable_tooltip(move |_window, cx| {
7187 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7188 })
7189 })
7190 .children(keybind),
7191 )
7192 .into_any();
7193
7194 let longest_row =
7195 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7196 let longest_line_width = if visible_row_range.contains(&longest_row) {
7197 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7198 } else {
7199 layout_line(
7200 longest_row,
7201 editor_snapshot,
7202 style,
7203 editor_width,
7204 |_| false,
7205 window,
7206 cx,
7207 )
7208 .width
7209 };
7210
7211 let viewport_bounds =
7212 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7213 right: -EditorElement::SCROLLBAR_WIDTH,
7214 ..Default::default()
7215 });
7216
7217 let x_after_longest =
7218 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7219 - scroll_pixel_position.x;
7220
7221 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7222
7223 // Fully visible if it can be displayed within the window (allow overlapping other
7224 // panes). However, this is only allowed if the popover starts within text_bounds.
7225 let can_position_to_the_right = x_after_longest < text_bounds.right()
7226 && x_after_longest + element_bounds.width < viewport_bounds.right();
7227
7228 let mut origin = if can_position_to_the_right {
7229 point(
7230 x_after_longest,
7231 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7232 - scroll_pixel_position.y,
7233 )
7234 } else {
7235 let cursor_row = newest_selection_head.map(|head| head.row());
7236 let above_edit = edit_start
7237 .row()
7238 .0
7239 .checked_sub(line_count as u32)
7240 .map(DisplayRow);
7241 let below_edit = Some(edit_end.row() + 1);
7242 let above_cursor =
7243 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7244 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7245
7246 // Place the edit popover adjacent to the edit if there is a location
7247 // available that is onscreen and does not obscure the cursor. Otherwise,
7248 // place it adjacent to the cursor.
7249 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7250 .into_iter()
7251 .flatten()
7252 .find(|&start_row| {
7253 let end_row = start_row + line_count as u32;
7254 visible_row_range.contains(&start_row)
7255 && visible_row_range.contains(&end_row)
7256 && cursor_row.map_or(true, |cursor_row| {
7257 !((start_row..end_row).contains(&cursor_row))
7258 })
7259 })?;
7260
7261 content_origin
7262 + point(
7263 -scroll_pixel_position.x,
7264 row_target.as_f32() * line_height - scroll_pixel_position.y,
7265 )
7266 };
7267
7268 origin.x -= BORDER_WIDTH;
7269
7270 window.defer_draw(element, origin, 1);
7271
7272 // Do not return an element, since it will already be drawn due to defer_draw.
7273 None
7274 }
7275
7276 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7277 px(30.)
7278 }
7279
7280 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7281 if self.read_only(cx) {
7282 cx.theme().players().read_only()
7283 } else {
7284 self.style.as_ref().unwrap().local_player
7285 }
7286 }
7287
7288 fn render_edit_prediction_accept_keybind(
7289 &self,
7290 window: &mut Window,
7291 cx: &App,
7292 ) -> Option<AnyElement> {
7293 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7294 let accept_keystroke = accept_binding.keystroke()?;
7295
7296 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7297
7298 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7299 Color::Accent
7300 } else {
7301 Color::Muted
7302 };
7303
7304 h_flex()
7305 .px_0p5()
7306 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7307 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7308 .text_size(TextSize::XSmall.rems(cx))
7309 .child(h_flex().children(ui::render_modifiers(
7310 &accept_keystroke.modifiers,
7311 PlatformStyle::platform(),
7312 Some(modifiers_color),
7313 Some(IconSize::XSmall.rems().into()),
7314 true,
7315 )))
7316 .when(is_platform_style_mac, |parent| {
7317 parent.child(accept_keystroke.key.clone())
7318 })
7319 .when(!is_platform_style_mac, |parent| {
7320 parent.child(
7321 Key::new(
7322 util::capitalize(&accept_keystroke.key),
7323 Some(Color::Default),
7324 )
7325 .size(Some(IconSize::XSmall.rems().into())),
7326 )
7327 })
7328 .into_any()
7329 .into()
7330 }
7331
7332 fn render_edit_prediction_line_popover(
7333 &self,
7334 label: impl Into<SharedString>,
7335 icon: Option<IconName>,
7336 window: &mut Window,
7337 cx: &App,
7338 ) -> Option<Stateful<Div>> {
7339 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7340
7341 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7342 let has_keybind = keybind.is_some();
7343
7344 let result = h_flex()
7345 .id("ep-line-popover")
7346 .py_0p5()
7347 .pl_1()
7348 .pr(padding_right)
7349 .gap_1()
7350 .rounded_md()
7351 .border_1()
7352 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7353 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7354 .shadow_sm()
7355 .when(!has_keybind, |el| {
7356 let status_colors = cx.theme().status();
7357
7358 el.bg(status_colors.error_background)
7359 .border_color(status_colors.error.opacity(0.6))
7360 .pl_2()
7361 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7362 .cursor_default()
7363 .hoverable_tooltip(move |_window, cx| {
7364 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7365 })
7366 })
7367 .children(keybind)
7368 .child(
7369 Label::new(label)
7370 .size(LabelSize::Small)
7371 .when(!has_keybind, |el| {
7372 el.color(cx.theme().status().error.into()).strikethrough()
7373 }),
7374 )
7375 .when(!has_keybind, |el| {
7376 el.child(
7377 h_flex().ml_1().child(
7378 Icon::new(IconName::Info)
7379 .size(IconSize::Small)
7380 .color(cx.theme().status().error.into()),
7381 ),
7382 )
7383 })
7384 .when_some(icon, |element, icon| {
7385 element.child(
7386 div()
7387 .mt(px(1.5))
7388 .child(Icon::new(icon).size(IconSize::Small)),
7389 )
7390 });
7391
7392 Some(result)
7393 }
7394
7395 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7396 let accent_color = cx.theme().colors().text_accent;
7397 let editor_bg_color = cx.theme().colors().editor_background;
7398 editor_bg_color.blend(accent_color.opacity(0.1))
7399 }
7400
7401 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7402 let accent_color = cx.theme().colors().text_accent;
7403 let editor_bg_color = cx.theme().colors().editor_background;
7404 editor_bg_color.blend(accent_color.opacity(0.6))
7405 }
7406
7407 fn render_edit_prediction_cursor_popover(
7408 &self,
7409 min_width: Pixels,
7410 max_width: Pixels,
7411 cursor_point: Point,
7412 style: &EditorStyle,
7413 accept_keystroke: Option<&gpui::Keystroke>,
7414 _window: &Window,
7415 cx: &mut Context<Editor>,
7416 ) -> Option<AnyElement> {
7417 let provider = self.edit_prediction_provider.as_ref()?;
7418
7419 if provider.provider.needs_terms_acceptance(cx) {
7420 return Some(
7421 h_flex()
7422 .min_w(min_width)
7423 .flex_1()
7424 .px_2()
7425 .py_1()
7426 .gap_3()
7427 .elevation_2(cx)
7428 .hover(|style| style.bg(cx.theme().colors().element_hover))
7429 .id("accept-terms")
7430 .cursor_pointer()
7431 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7432 .on_click(cx.listener(|this, _event, window, cx| {
7433 cx.stop_propagation();
7434 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7435 window.dispatch_action(
7436 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7437 cx,
7438 );
7439 }))
7440 .child(
7441 h_flex()
7442 .flex_1()
7443 .gap_2()
7444 .child(Icon::new(IconName::ZedPredict))
7445 .child(Label::new("Accept Terms of Service"))
7446 .child(div().w_full())
7447 .child(
7448 Icon::new(IconName::ArrowUpRight)
7449 .color(Color::Muted)
7450 .size(IconSize::Small),
7451 )
7452 .into_any_element(),
7453 )
7454 .into_any(),
7455 );
7456 }
7457
7458 let is_refreshing = provider.provider.is_refreshing(cx);
7459
7460 fn pending_completion_container() -> Div {
7461 h_flex()
7462 .h_full()
7463 .flex_1()
7464 .gap_2()
7465 .child(Icon::new(IconName::ZedPredict))
7466 }
7467
7468 let completion = match &self.active_inline_completion {
7469 Some(prediction) => {
7470 if !self.has_visible_completions_menu() {
7471 const RADIUS: Pixels = px(6.);
7472 const BORDER_WIDTH: Pixels = px(1.);
7473
7474 return Some(
7475 h_flex()
7476 .elevation_2(cx)
7477 .border(BORDER_WIDTH)
7478 .border_color(cx.theme().colors().border)
7479 .when(accept_keystroke.is_none(), |el| {
7480 el.border_color(cx.theme().status().error)
7481 })
7482 .rounded(RADIUS)
7483 .rounded_tl(px(0.))
7484 .overflow_hidden()
7485 .child(div().px_1p5().child(match &prediction.completion {
7486 InlineCompletion::Move { target, snapshot } => {
7487 use text::ToPoint as _;
7488 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7489 {
7490 Icon::new(IconName::ZedPredictDown)
7491 } else {
7492 Icon::new(IconName::ZedPredictUp)
7493 }
7494 }
7495 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7496 }))
7497 .child(
7498 h_flex()
7499 .gap_1()
7500 .py_1()
7501 .px_2()
7502 .rounded_r(RADIUS - BORDER_WIDTH)
7503 .border_l_1()
7504 .border_color(cx.theme().colors().border)
7505 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7506 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7507 el.child(
7508 Label::new("Hold")
7509 .size(LabelSize::Small)
7510 .when(accept_keystroke.is_none(), |el| {
7511 el.strikethrough()
7512 })
7513 .line_height_style(LineHeightStyle::UiLabel),
7514 )
7515 })
7516 .id("edit_prediction_cursor_popover_keybind")
7517 .when(accept_keystroke.is_none(), |el| {
7518 let status_colors = cx.theme().status();
7519
7520 el.bg(status_colors.error_background)
7521 .border_color(status_colors.error.opacity(0.6))
7522 .child(Icon::new(IconName::Info).color(Color::Error))
7523 .cursor_default()
7524 .hoverable_tooltip(move |_window, cx| {
7525 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7526 .into()
7527 })
7528 })
7529 .when_some(
7530 accept_keystroke.as_ref(),
7531 |el, accept_keystroke| {
7532 el.child(h_flex().children(ui::render_modifiers(
7533 &accept_keystroke.modifiers,
7534 PlatformStyle::platform(),
7535 Some(Color::Default),
7536 Some(IconSize::XSmall.rems().into()),
7537 false,
7538 )))
7539 },
7540 ),
7541 )
7542 .into_any(),
7543 );
7544 }
7545
7546 self.render_edit_prediction_cursor_popover_preview(
7547 prediction,
7548 cursor_point,
7549 style,
7550 cx,
7551 )?
7552 }
7553
7554 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7555 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7556 stale_completion,
7557 cursor_point,
7558 style,
7559 cx,
7560 )?,
7561
7562 None => {
7563 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7564 }
7565 },
7566
7567 None => pending_completion_container().child(Label::new("No Prediction")),
7568 };
7569
7570 let completion = if is_refreshing {
7571 completion
7572 .with_animation(
7573 "loading-completion",
7574 Animation::new(Duration::from_secs(2))
7575 .repeat()
7576 .with_easing(pulsating_between(0.4, 0.8)),
7577 |label, delta| label.opacity(delta),
7578 )
7579 .into_any_element()
7580 } else {
7581 completion.into_any_element()
7582 };
7583
7584 let has_completion = self.active_inline_completion.is_some();
7585
7586 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7587 Some(
7588 h_flex()
7589 .min_w(min_width)
7590 .max_w(max_width)
7591 .flex_1()
7592 .elevation_2(cx)
7593 .border_color(cx.theme().colors().border)
7594 .child(
7595 div()
7596 .flex_1()
7597 .py_1()
7598 .px_2()
7599 .overflow_hidden()
7600 .child(completion),
7601 )
7602 .when_some(accept_keystroke, |el, accept_keystroke| {
7603 if !accept_keystroke.modifiers.modified() {
7604 return el;
7605 }
7606
7607 el.child(
7608 h_flex()
7609 .h_full()
7610 .border_l_1()
7611 .rounded_r_lg()
7612 .border_color(cx.theme().colors().border)
7613 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7614 .gap_1()
7615 .py_1()
7616 .px_2()
7617 .child(
7618 h_flex()
7619 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7620 .when(is_platform_style_mac, |parent| parent.gap_1())
7621 .child(h_flex().children(ui::render_modifiers(
7622 &accept_keystroke.modifiers,
7623 PlatformStyle::platform(),
7624 Some(if !has_completion {
7625 Color::Muted
7626 } else {
7627 Color::Default
7628 }),
7629 None,
7630 false,
7631 ))),
7632 )
7633 .child(Label::new("Preview").into_any_element())
7634 .opacity(if has_completion { 1.0 } else { 0.4 }),
7635 )
7636 })
7637 .into_any(),
7638 )
7639 }
7640
7641 fn render_edit_prediction_cursor_popover_preview(
7642 &self,
7643 completion: &InlineCompletionState,
7644 cursor_point: Point,
7645 style: &EditorStyle,
7646 cx: &mut Context<Editor>,
7647 ) -> Option<Div> {
7648 use text::ToPoint as _;
7649
7650 fn render_relative_row_jump(
7651 prefix: impl Into<String>,
7652 current_row: u32,
7653 target_row: u32,
7654 ) -> Div {
7655 let (row_diff, arrow) = if target_row < current_row {
7656 (current_row - target_row, IconName::ArrowUp)
7657 } else {
7658 (target_row - current_row, IconName::ArrowDown)
7659 };
7660
7661 h_flex()
7662 .child(
7663 Label::new(format!("{}{}", prefix.into(), row_diff))
7664 .color(Color::Muted)
7665 .size(LabelSize::Small),
7666 )
7667 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7668 }
7669
7670 match &completion.completion {
7671 InlineCompletion::Move {
7672 target, snapshot, ..
7673 } => Some(
7674 h_flex()
7675 .px_2()
7676 .gap_2()
7677 .flex_1()
7678 .child(
7679 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7680 Icon::new(IconName::ZedPredictDown)
7681 } else {
7682 Icon::new(IconName::ZedPredictUp)
7683 },
7684 )
7685 .child(Label::new("Jump to Edit")),
7686 ),
7687
7688 InlineCompletion::Edit {
7689 edits,
7690 edit_preview,
7691 snapshot,
7692 display_mode: _,
7693 } => {
7694 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7695
7696 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7697 &snapshot,
7698 &edits,
7699 edit_preview.as_ref()?,
7700 true,
7701 cx,
7702 )
7703 .first_line_preview();
7704
7705 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7706 .with_default_highlights(&style.text, highlighted_edits.highlights);
7707
7708 let preview = h_flex()
7709 .gap_1()
7710 .min_w_16()
7711 .child(styled_text)
7712 .when(has_more_lines, |parent| parent.child("…"));
7713
7714 let left = if first_edit_row != cursor_point.row {
7715 render_relative_row_jump("", cursor_point.row, first_edit_row)
7716 .into_any_element()
7717 } else {
7718 Icon::new(IconName::ZedPredict).into_any_element()
7719 };
7720
7721 Some(
7722 h_flex()
7723 .h_full()
7724 .flex_1()
7725 .gap_2()
7726 .pr_1()
7727 .overflow_x_hidden()
7728 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7729 .child(left)
7730 .child(preview),
7731 )
7732 }
7733 }
7734 }
7735
7736 fn render_context_menu(
7737 &self,
7738 style: &EditorStyle,
7739 max_height_in_lines: u32,
7740 window: &mut Window,
7741 cx: &mut Context<Editor>,
7742 ) -> Option<AnyElement> {
7743 let menu = self.context_menu.borrow();
7744 let menu = menu.as_ref()?;
7745 if !menu.visible() {
7746 return None;
7747 };
7748 Some(menu.render(style, max_height_in_lines, window, cx))
7749 }
7750
7751 fn render_context_menu_aside(
7752 &mut self,
7753 max_size: Size<Pixels>,
7754 window: &mut Window,
7755 cx: &mut Context<Editor>,
7756 ) -> Option<AnyElement> {
7757 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7758 if menu.visible() {
7759 menu.render_aside(self, max_size, window, cx)
7760 } else {
7761 None
7762 }
7763 })
7764 }
7765
7766 fn hide_context_menu(
7767 &mut self,
7768 window: &mut Window,
7769 cx: &mut Context<Self>,
7770 ) -> Option<CodeContextMenu> {
7771 cx.notify();
7772 self.completion_tasks.clear();
7773 let context_menu = self.context_menu.borrow_mut().take();
7774 self.stale_inline_completion_in_menu.take();
7775 self.update_visible_inline_completion(window, cx);
7776 context_menu
7777 }
7778
7779 fn show_snippet_choices(
7780 &mut self,
7781 choices: &Vec<String>,
7782 selection: Range<Anchor>,
7783 cx: &mut Context<Self>,
7784 ) {
7785 if selection.start.buffer_id.is_none() {
7786 return;
7787 }
7788 let buffer_id = selection.start.buffer_id.unwrap();
7789 let buffer = self.buffer().read(cx).buffer(buffer_id);
7790 let id = post_inc(&mut self.next_completion_id);
7791
7792 if let Some(buffer) = buffer {
7793 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7794 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7795 ));
7796 }
7797 }
7798
7799 pub fn insert_snippet(
7800 &mut self,
7801 insertion_ranges: &[Range<usize>],
7802 snippet: Snippet,
7803 window: &mut Window,
7804 cx: &mut Context<Self>,
7805 ) -> Result<()> {
7806 struct Tabstop<T> {
7807 is_end_tabstop: bool,
7808 ranges: Vec<Range<T>>,
7809 choices: Option<Vec<String>>,
7810 }
7811
7812 let tabstops = self.buffer.update(cx, |buffer, cx| {
7813 let snippet_text: Arc<str> = snippet.text.clone().into();
7814 let edits = insertion_ranges
7815 .iter()
7816 .cloned()
7817 .map(|range| (range, snippet_text.clone()));
7818 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7819
7820 let snapshot = &*buffer.read(cx);
7821 let snippet = &snippet;
7822 snippet
7823 .tabstops
7824 .iter()
7825 .map(|tabstop| {
7826 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7827 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7828 });
7829 let mut tabstop_ranges = tabstop
7830 .ranges
7831 .iter()
7832 .flat_map(|tabstop_range| {
7833 let mut delta = 0_isize;
7834 insertion_ranges.iter().map(move |insertion_range| {
7835 let insertion_start = insertion_range.start as isize + delta;
7836 delta +=
7837 snippet.text.len() as isize - insertion_range.len() as isize;
7838
7839 let start = ((insertion_start + tabstop_range.start) as usize)
7840 .min(snapshot.len());
7841 let end = ((insertion_start + tabstop_range.end) as usize)
7842 .min(snapshot.len());
7843 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7844 })
7845 })
7846 .collect::<Vec<_>>();
7847 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7848
7849 Tabstop {
7850 is_end_tabstop,
7851 ranges: tabstop_ranges,
7852 choices: tabstop.choices.clone(),
7853 }
7854 })
7855 .collect::<Vec<_>>()
7856 });
7857 if let Some(tabstop) = tabstops.first() {
7858 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7859 s.select_ranges(tabstop.ranges.iter().cloned());
7860 });
7861
7862 if let Some(choices) = &tabstop.choices {
7863 if let Some(selection) = tabstop.ranges.first() {
7864 self.show_snippet_choices(choices, selection.clone(), cx)
7865 }
7866 }
7867
7868 // If we're already at the last tabstop and it's at the end of the snippet,
7869 // we're done, we don't need to keep the state around.
7870 if !tabstop.is_end_tabstop {
7871 let choices = tabstops
7872 .iter()
7873 .map(|tabstop| tabstop.choices.clone())
7874 .collect();
7875
7876 let ranges = tabstops
7877 .into_iter()
7878 .map(|tabstop| tabstop.ranges)
7879 .collect::<Vec<_>>();
7880
7881 self.snippet_stack.push(SnippetState {
7882 active_index: 0,
7883 ranges,
7884 choices,
7885 });
7886 }
7887
7888 // Check whether the just-entered snippet ends with an auto-closable bracket.
7889 if self.autoclose_regions.is_empty() {
7890 let snapshot = self.buffer.read(cx).snapshot(cx);
7891 for selection in &mut self.selections.all::<Point>(cx) {
7892 let selection_head = selection.head();
7893 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7894 continue;
7895 };
7896
7897 let mut bracket_pair = None;
7898 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7899 let prev_chars = snapshot
7900 .reversed_chars_at(selection_head)
7901 .collect::<String>();
7902 for (pair, enabled) in scope.brackets() {
7903 if enabled
7904 && pair.close
7905 && prev_chars.starts_with(pair.start.as_str())
7906 && next_chars.starts_with(pair.end.as_str())
7907 {
7908 bracket_pair = Some(pair.clone());
7909 break;
7910 }
7911 }
7912 if let Some(pair) = bracket_pair {
7913 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
7914 let autoclose_enabled =
7915 self.use_autoclose && snapshot_settings.use_autoclose;
7916 if autoclose_enabled {
7917 let start = snapshot.anchor_after(selection_head);
7918 let end = snapshot.anchor_after(selection_head);
7919 self.autoclose_regions.push(AutocloseRegion {
7920 selection_id: selection.id,
7921 range: start..end,
7922 pair,
7923 });
7924 }
7925 }
7926 }
7927 }
7928 }
7929 Ok(())
7930 }
7931
7932 pub fn move_to_next_snippet_tabstop(
7933 &mut self,
7934 window: &mut Window,
7935 cx: &mut Context<Self>,
7936 ) -> bool {
7937 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7938 }
7939
7940 pub fn move_to_prev_snippet_tabstop(
7941 &mut self,
7942 window: &mut Window,
7943 cx: &mut Context<Self>,
7944 ) -> bool {
7945 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7946 }
7947
7948 pub fn move_to_snippet_tabstop(
7949 &mut self,
7950 bias: Bias,
7951 window: &mut Window,
7952 cx: &mut Context<Self>,
7953 ) -> bool {
7954 if let Some(mut snippet) = self.snippet_stack.pop() {
7955 match bias {
7956 Bias::Left => {
7957 if snippet.active_index > 0 {
7958 snippet.active_index -= 1;
7959 } else {
7960 self.snippet_stack.push(snippet);
7961 return false;
7962 }
7963 }
7964 Bias::Right => {
7965 if snippet.active_index + 1 < snippet.ranges.len() {
7966 snippet.active_index += 1;
7967 } else {
7968 self.snippet_stack.push(snippet);
7969 return false;
7970 }
7971 }
7972 }
7973 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7974 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7975 s.select_anchor_ranges(current_ranges.iter().cloned())
7976 });
7977
7978 if let Some(choices) = &snippet.choices[snippet.active_index] {
7979 if let Some(selection) = current_ranges.first() {
7980 self.show_snippet_choices(&choices, selection.clone(), cx);
7981 }
7982 }
7983
7984 // If snippet state is not at the last tabstop, push it back on the stack
7985 if snippet.active_index + 1 < snippet.ranges.len() {
7986 self.snippet_stack.push(snippet);
7987 }
7988 return true;
7989 }
7990 }
7991
7992 false
7993 }
7994
7995 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7996 self.transact(window, cx, |this, window, cx| {
7997 this.select_all(&SelectAll, window, cx);
7998 this.insert("", window, cx);
7999 });
8000 }
8001
8002 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8003 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8004 self.transact(window, cx, |this, window, cx| {
8005 this.select_autoclose_pair(window, cx);
8006 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8007 if !this.linked_edit_ranges.is_empty() {
8008 let selections = this.selections.all::<MultiBufferPoint>(cx);
8009 let snapshot = this.buffer.read(cx).snapshot(cx);
8010
8011 for selection in selections.iter() {
8012 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8013 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8014 if selection_start.buffer_id != selection_end.buffer_id {
8015 continue;
8016 }
8017 if let Some(ranges) =
8018 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8019 {
8020 for (buffer, entries) in ranges {
8021 linked_ranges.entry(buffer).or_default().extend(entries);
8022 }
8023 }
8024 }
8025 }
8026
8027 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8028 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8029 for selection in &mut selections {
8030 if selection.is_empty() {
8031 let old_head = selection.head();
8032 let mut new_head =
8033 movement::left(&display_map, old_head.to_display_point(&display_map))
8034 .to_point(&display_map);
8035 if let Some((buffer, line_buffer_range)) = display_map
8036 .buffer_snapshot
8037 .buffer_line_for_row(MultiBufferRow(old_head.row))
8038 {
8039 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8040 let indent_len = match indent_size.kind {
8041 IndentKind::Space => {
8042 buffer.settings_at(line_buffer_range.start, cx).tab_size
8043 }
8044 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8045 };
8046 if old_head.column <= indent_size.len && old_head.column > 0 {
8047 let indent_len = indent_len.get();
8048 new_head = cmp::min(
8049 new_head,
8050 MultiBufferPoint::new(
8051 old_head.row,
8052 ((old_head.column - 1) / indent_len) * indent_len,
8053 ),
8054 );
8055 }
8056 }
8057
8058 selection.set_head(new_head, SelectionGoal::None);
8059 }
8060 }
8061
8062 this.signature_help_state.set_backspace_pressed(true);
8063 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8064 s.select(selections)
8065 });
8066 this.insert("", window, cx);
8067 let empty_str: Arc<str> = Arc::from("");
8068 for (buffer, edits) in linked_ranges {
8069 let snapshot = buffer.read(cx).snapshot();
8070 use text::ToPoint as TP;
8071
8072 let edits = edits
8073 .into_iter()
8074 .map(|range| {
8075 let end_point = TP::to_point(&range.end, &snapshot);
8076 let mut start_point = TP::to_point(&range.start, &snapshot);
8077
8078 if end_point == start_point {
8079 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8080 .saturating_sub(1);
8081 start_point =
8082 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8083 };
8084
8085 (start_point..end_point, empty_str.clone())
8086 })
8087 .sorted_by_key(|(range, _)| range.start)
8088 .collect::<Vec<_>>();
8089 buffer.update(cx, |this, cx| {
8090 this.edit(edits, None, cx);
8091 })
8092 }
8093 this.refresh_inline_completion(true, false, window, cx);
8094 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8095 });
8096 }
8097
8098 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8099 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8100 self.transact(window, cx, |this, window, cx| {
8101 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8102 s.move_with(|map, selection| {
8103 if selection.is_empty() {
8104 let cursor = movement::right(map, selection.head());
8105 selection.end = cursor;
8106 selection.reversed = true;
8107 selection.goal = SelectionGoal::None;
8108 }
8109 })
8110 });
8111 this.insert("", window, cx);
8112 this.refresh_inline_completion(true, false, window, cx);
8113 });
8114 }
8115
8116 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8117 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8118 if self.move_to_prev_snippet_tabstop(window, cx) {
8119 return;
8120 }
8121 self.outdent(&Outdent, window, cx);
8122 }
8123
8124 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8125 if self.move_to_next_snippet_tabstop(window, cx) {
8126 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8127 return;
8128 }
8129 if self.read_only(cx) {
8130 return;
8131 }
8132 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8133 let mut selections = self.selections.all_adjusted(cx);
8134 let buffer = self.buffer.read(cx);
8135 let snapshot = buffer.snapshot(cx);
8136 let rows_iter = selections.iter().map(|s| s.head().row);
8137 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8138
8139 let mut edits = Vec::new();
8140 let mut prev_edited_row = 0;
8141 let mut row_delta = 0;
8142 for selection in &mut selections {
8143 if selection.start.row != prev_edited_row {
8144 row_delta = 0;
8145 }
8146 prev_edited_row = selection.end.row;
8147
8148 // If the selection is non-empty, then increase the indentation of the selected lines.
8149 if !selection.is_empty() {
8150 row_delta =
8151 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8152 continue;
8153 }
8154
8155 // If the selection is empty and the cursor is in the leading whitespace before the
8156 // suggested indentation, then auto-indent the line.
8157 let cursor = selection.head();
8158 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8159 if let Some(suggested_indent) =
8160 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8161 {
8162 if cursor.column < suggested_indent.len
8163 && cursor.column <= current_indent.len
8164 && current_indent.len <= suggested_indent.len
8165 {
8166 selection.start = Point::new(cursor.row, suggested_indent.len);
8167 selection.end = selection.start;
8168 if row_delta == 0 {
8169 edits.extend(Buffer::edit_for_indent_size_adjustment(
8170 cursor.row,
8171 current_indent,
8172 suggested_indent,
8173 ));
8174 row_delta = suggested_indent.len - current_indent.len;
8175 }
8176 continue;
8177 }
8178 }
8179
8180 // Otherwise, insert a hard or soft tab.
8181 let settings = buffer.language_settings_at(cursor, cx);
8182 let tab_size = if settings.hard_tabs {
8183 IndentSize::tab()
8184 } else {
8185 let tab_size = settings.tab_size.get();
8186 let char_column = snapshot
8187 .text_for_range(Point::new(cursor.row, 0)..cursor)
8188 .flat_map(str::chars)
8189 .count()
8190 + row_delta as usize;
8191 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
8192 IndentSize::spaces(chars_to_next_tab_stop)
8193 };
8194 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8195 selection.end = selection.start;
8196 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8197 row_delta += tab_size.len;
8198 }
8199
8200 self.transact(window, cx, |this, window, cx| {
8201 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8202 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8203 s.select(selections)
8204 });
8205 this.refresh_inline_completion(true, false, window, cx);
8206 });
8207 }
8208
8209 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8210 if self.read_only(cx) {
8211 return;
8212 }
8213 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8214 let mut selections = self.selections.all::<Point>(cx);
8215 let mut prev_edited_row = 0;
8216 let mut row_delta = 0;
8217 let mut edits = Vec::new();
8218 let buffer = self.buffer.read(cx);
8219 let snapshot = buffer.snapshot(cx);
8220 for selection in &mut selections {
8221 if selection.start.row != prev_edited_row {
8222 row_delta = 0;
8223 }
8224 prev_edited_row = selection.end.row;
8225
8226 row_delta =
8227 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8228 }
8229
8230 self.transact(window, cx, |this, window, cx| {
8231 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8232 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8233 s.select(selections)
8234 });
8235 });
8236 }
8237
8238 fn indent_selection(
8239 buffer: &MultiBuffer,
8240 snapshot: &MultiBufferSnapshot,
8241 selection: &mut Selection<Point>,
8242 edits: &mut Vec<(Range<Point>, String)>,
8243 delta_for_start_row: u32,
8244 cx: &App,
8245 ) -> u32 {
8246 let settings = buffer.language_settings_at(selection.start, cx);
8247 let tab_size = settings.tab_size.get();
8248 let indent_kind = if settings.hard_tabs {
8249 IndentKind::Tab
8250 } else {
8251 IndentKind::Space
8252 };
8253 let mut start_row = selection.start.row;
8254 let mut end_row = selection.end.row + 1;
8255
8256 // If a selection ends at the beginning of a line, don't indent
8257 // that last line.
8258 if selection.end.column == 0 && selection.end.row > selection.start.row {
8259 end_row -= 1;
8260 }
8261
8262 // Avoid re-indenting a row that has already been indented by a
8263 // previous selection, but still update this selection's column
8264 // to reflect that indentation.
8265 if delta_for_start_row > 0 {
8266 start_row += 1;
8267 selection.start.column += delta_for_start_row;
8268 if selection.end.row == selection.start.row {
8269 selection.end.column += delta_for_start_row;
8270 }
8271 }
8272
8273 let mut delta_for_end_row = 0;
8274 let has_multiple_rows = start_row + 1 != end_row;
8275 for row in start_row..end_row {
8276 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8277 let indent_delta = match (current_indent.kind, indent_kind) {
8278 (IndentKind::Space, IndentKind::Space) => {
8279 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8280 IndentSize::spaces(columns_to_next_tab_stop)
8281 }
8282 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8283 (_, IndentKind::Tab) => IndentSize::tab(),
8284 };
8285
8286 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8287 0
8288 } else {
8289 selection.start.column
8290 };
8291 let row_start = Point::new(row, start);
8292 edits.push((
8293 row_start..row_start,
8294 indent_delta.chars().collect::<String>(),
8295 ));
8296
8297 // Update this selection's endpoints to reflect the indentation.
8298 if row == selection.start.row {
8299 selection.start.column += indent_delta.len;
8300 }
8301 if row == selection.end.row {
8302 selection.end.column += indent_delta.len;
8303 delta_for_end_row = indent_delta.len;
8304 }
8305 }
8306
8307 if selection.start.row == selection.end.row {
8308 delta_for_start_row + delta_for_end_row
8309 } else {
8310 delta_for_end_row
8311 }
8312 }
8313
8314 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8315 if self.read_only(cx) {
8316 return;
8317 }
8318 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8320 let selections = self.selections.all::<Point>(cx);
8321 let mut deletion_ranges = Vec::new();
8322 let mut last_outdent = None;
8323 {
8324 let buffer = self.buffer.read(cx);
8325 let snapshot = buffer.snapshot(cx);
8326 for selection in &selections {
8327 let settings = buffer.language_settings_at(selection.start, cx);
8328 let tab_size = settings.tab_size.get();
8329 let mut rows = selection.spanned_rows(false, &display_map);
8330
8331 // Avoid re-outdenting a row that has already been outdented by a
8332 // previous selection.
8333 if let Some(last_row) = last_outdent {
8334 if last_row == rows.start {
8335 rows.start = rows.start.next_row();
8336 }
8337 }
8338 let has_multiple_rows = rows.len() > 1;
8339 for row in rows.iter_rows() {
8340 let indent_size = snapshot.indent_size_for_line(row);
8341 if indent_size.len > 0 {
8342 let deletion_len = match indent_size.kind {
8343 IndentKind::Space => {
8344 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8345 if columns_to_prev_tab_stop == 0 {
8346 tab_size
8347 } else {
8348 columns_to_prev_tab_stop
8349 }
8350 }
8351 IndentKind::Tab => 1,
8352 };
8353 let start = if has_multiple_rows
8354 || deletion_len > selection.start.column
8355 || indent_size.len < selection.start.column
8356 {
8357 0
8358 } else {
8359 selection.start.column - deletion_len
8360 };
8361 deletion_ranges.push(
8362 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8363 );
8364 last_outdent = Some(row);
8365 }
8366 }
8367 }
8368 }
8369
8370 self.transact(window, cx, |this, window, cx| {
8371 this.buffer.update(cx, |buffer, cx| {
8372 let empty_str: Arc<str> = Arc::default();
8373 buffer.edit(
8374 deletion_ranges
8375 .into_iter()
8376 .map(|range| (range, empty_str.clone())),
8377 None,
8378 cx,
8379 );
8380 });
8381 let selections = this.selections.all::<usize>(cx);
8382 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8383 s.select(selections)
8384 });
8385 });
8386 }
8387
8388 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8389 if self.read_only(cx) {
8390 return;
8391 }
8392 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8393 let selections = self
8394 .selections
8395 .all::<usize>(cx)
8396 .into_iter()
8397 .map(|s| s.range());
8398
8399 self.transact(window, cx, |this, window, cx| {
8400 this.buffer.update(cx, |buffer, cx| {
8401 buffer.autoindent_ranges(selections, cx);
8402 });
8403 let selections = this.selections.all::<usize>(cx);
8404 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8405 s.select(selections)
8406 });
8407 });
8408 }
8409
8410 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8411 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8412 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8413 let selections = self.selections.all::<Point>(cx);
8414
8415 let mut new_cursors = Vec::new();
8416 let mut edit_ranges = Vec::new();
8417 let mut selections = selections.iter().peekable();
8418 while let Some(selection) = selections.next() {
8419 let mut rows = selection.spanned_rows(false, &display_map);
8420 let goal_display_column = selection.head().to_display_point(&display_map).column();
8421
8422 // Accumulate contiguous regions of rows that we want to delete.
8423 while let Some(next_selection) = selections.peek() {
8424 let next_rows = next_selection.spanned_rows(false, &display_map);
8425 if next_rows.start <= rows.end {
8426 rows.end = next_rows.end;
8427 selections.next().unwrap();
8428 } else {
8429 break;
8430 }
8431 }
8432
8433 let buffer = &display_map.buffer_snapshot;
8434 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8435 let edit_end;
8436 let cursor_buffer_row;
8437 if buffer.max_point().row >= rows.end.0 {
8438 // If there's a line after the range, delete the \n from the end of the row range
8439 // and position the cursor on the next line.
8440 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8441 cursor_buffer_row = rows.end;
8442 } else {
8443 // If there isn't a line after the range, delete the \n from the line before the
8444 // start of the row range and position the cursor there.
8445 edit_start = edit_start.saturating_sub(1);
8446 edit_end = buffer.len();
8447 cursor_buffer_row = rows.start.previous_row();
8448 }
8449
8450 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8451 *cursor.column_mut() =
8452 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8453
8454 new_cursors.push((
8455 selection.id,
8456 buffer.anchor_after(cursor.to_point(&display_map)),
8457 ));
8458 edit_ranges.push(edit_start..edit_end);
8459 }
8460
8461 self.transact(window, cx, |this, window, cx| {
8462 let buffer = this.buffer.update(cx, |buffer, cx| {
8463 let empty_str: Arc<str> = Arc::default();
8464 buffer.edit(
8465 edit_ranges
8466 .into_iter()
8467 .map(|range| (range, empty_str.clone())),
8468 None,
8469 cx,
8470 );
8471 buffer.snapshot(cx)
8472 });
8473 let new_selections = new_cursors
8474 .into_iter()
8475 .map(|(id, cursor)| {
8476 let cursor = cursor.to_point(&buffer);
8477 Selection {
8478 id,
8479 start: cursor,
8480 end: cursor,
8481 reversed: false,
8482 goal: SelectionGoal::None,
8483 }
8484 })
8485 .collect();
8486
8487 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8488 s.select(new_selections);
8489 });
8490 });
8491 }
8492
8493 pub fn join_lines_impl(
8494 &mut self,
8495 insert_whitespace: bool,
8496 window: &mut Window,
8497 cx: &mut Context<Self>,
8498 ) {
8499 if self.read_only(cx) {
8500 return;
8501 }
8502 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8503 for selection in self.selections.all::<Point>(cx) {
8504 let start = MultiBufferRow(selection.start.row);
8505 // Treat single line selections as if they include the next line. Otherwise this action
8506 // would do nothing for single line selections individual cursors.
8507 let end = if selection.start.row == selection.end.row {
8508 MultiBufferRow(selection.start.row + 1)
8509 } else {
8510 MultiBufferRow(selection.end.row)
8511 };
8512
8513 if let Some(last_row_range) = row_ranges.last_mut() {
8514 if start <= last_row_range.end {
8515 last_row_range.end = end;
8516 continue;
8517 }
8518 }
8519 row_ranges.push(start..end);
8520 }
8521
8522 let snapshot = self.buffer.read(cx).snapshot(cx);
8523 let mut cursor_positions = Vec::new();
8524 for row_range in &row_ranges {
8525 let anchor = snapshot.anchor_before(Point::new(
8526 row_range.end.previous_row().0,
8527 snapshot.line_len(row_range.end.previous_row()),
8528 ));
8529 cursor_positions.push(anchor..anchor);
8530 }
8531
8532 self.transact(window, cx, |this, window, cx| {
8533 for row_range in row_ranges.into_iter().rev() {
8534 for row in row_range.iter_rows().rev() {
8535 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8536 let next_line_row = row.next_row();
8537 let indent = snapshot.indent_size_for_line(next_line_row);
8538 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8539
8540 let replace =
8541 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8542 " "
8543 } else {
8544 ""
8545 };
8546
8547 this.buffer.update(cx, |buffer, cx| {
8548 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8549 });
8550 }
8551 }
8552
8553 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8554 s.select_anchor_ranges(cursor_positions)
8555 });
8556 });
8557 }
8558
8559 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8560 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8561 self.join_lines_impl(true, window, cx);
8562 }
8563
8564 pub fn sort_lines_case_sensitive(
8565 &mut self,
8566 _: &SortLinesCaseSensitive,
8567 window: &mut Window,
8568 cx: &mut Context<Self>,
8569 ) {
8570 self.manipulate_lines(window, cx, |lines| lines.sort())
8571 }
8572
8573 pub fn sort_lines_case_insensitive(
8574 &mut self,
8575 _: &SortLinesCaseInsensitive,
8576 window: &mut Window,
8577 cx: &mut Context<Self>,
8578 ) {
8579 self.manipulate_lines(window, cx, |lines| {
8580 lines.sort_by_key(|line| line.to_lowercase())
8581 })
8582 }
8583
8584 pub fn unique_lines_case_insensitive(
8585 &mut self,
8586 _: &UniqueLinesCaseInsensitive,
8587 window: &mut Window,
8588 cx: &mut Context<Self>,
8589 ) {
8590 self.manipulate_lines(window, cx, |lines| {
8591 let mut seen = HashSet::default();
8592 lines.retain(|line| seen.insert(line.to_lowercase()));
8593 })
8594 }
8595
8596 pub fn unique_lines_case_sensitive(
8597 &mut self,
8598 _: &UniqueLinesCaseSensitive,
8599 window: &mut Window,
8600 cx: &mut Context<Self>,
8601 ) {
8602 self.manipulate_lines(window, cx, |lines| {
8603 let mut seen = HashSet::default();
8604 lines.retain(|line| seen.insert(*line));
8605 })
8606 }
8607
8608 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8609 let Some(project) = self.project.clone() else {
8610 return;
8611 };
8612 self.reload(project, window, cx)
8613 .detach_and_notify_err(window, cx);
8614 }
8615
8616 pub fn restore_file(
8617 &mut self,
8618 _: &::git::RestoreFile,
8619 window: &mut Window,
8620 cx: &mut Context<Self>,
8621 ) {
8622 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8623 let mut buffer_ids = HashSet::default();
8624 let snapshot = self.buffer().read(cx).snapshot(cx);
8625 for selection in self.selections.all::<usize>(cx) {
8626 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8627 }
8628
8629 let buffer = self.buffer().read(cx);
8630 let ranges = buffer_ids
8631 .into_iter()
8632 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8633 .collect::<Vec<_>>();
8634
8635 self.restore_hunks_in_ranges(ranges, window, cx);
8636 }
8637
8638 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8639 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8640 let selections = self
8641 .selections
8642 .all(cx)
8643 .into_iter()
8644 .map(|s| s.range())
8645 .collect();
8646 self.restore_hunks_in_ranges(selections, window, cx);
8647 }
8648
8649 pub fn restore_hunks_in_ranges(
8650 &mut self,
8651 ranges: Vec<Range<Point>>,
8652 window: &mut Window,
8653 cx: &mut Context<Editor>,
8654 ) {
8655 let mut revert_changes = HashMap::default();
8656 let chunk_by = self
8657 .snapshot(window, cx)
8658 .hunks_for_ranges(ranges)
8659 .into_iter()
8660 .chunk_by(|hunk| hunk.buffer_id);
8661 for (buffer_id, hunks) in &chunk_by {
8662 let hunks = hunks.collect::<Vec<_>>();
8663 for hunk in &hunks {
8664 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8665 }
8666 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8667 }
8668 drop(chunk_by);
8669 if !revert_changes.is_empty() {
8670 self.transact(window, cx, |editor, window, cx| {
8671 editor.restore(revert_changes, window, cx);
8672 });
8673 }
8674 }
8675
8676 pub fn open_active_item_in_terminal(
8677 &mut self,
8678 _: &OpenInTerminal,
8679 window: &mut Window,
8680 cx: &mut Context<Self>,
8681 ) {
8682 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8683 let project_path = buffer.read(cx).project_path(cx)?;
8684 let project = self.project.as_ref()?.read(cx);
8685 let entry = project.entry_for_path(&project_path, cx)?;
8686 let parent = match &entry.canonical_path {
8687 Some(canonical_path) => canonical_path.to_path_buf(),
8688 None => project.absolute_path(&project_path, cx)?,
8689 }
8690 .parent()?
8691 .to_path_buf();
8692 Some(parent)
8693 }) {
8694 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8695 }
8696 }
8697
8698 fn set_breakpoint_context_menu(
8699 &mut self,
8700 display_row: DisplayRow,
8701 position: Option<Anchor>,
8702 clicked_point: gpui::Point<Pixels>,
8703 window: &mut Window,
8704 cx: &mut Context<Self>,
8705 ) {
8706 if !cx.has_flag::<Debugger>() {
8707 return;
8708 }
8709 let source = self
8710 .buffer
8711 .read(cx)
8712 .snapshot(cx)
8713 .anchor_before(Point::new(display_row.0, 0u32));
8714
8715 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8716
8717 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8718 self,
8719 source,
8720 clicked_point,
8721 context_menu,
8722 window,
8723 cx,
8724 );
8725 }
8726
8727 fn add_edit_breakpoint_block(
8728 &mut self,
8729 anchor: Anchor,
8730 breakpoint: &Breakpoint,
8731 edit_action: BreakpointPromptEditAction,
8732 window: &mut Window,
8733 cx: &mut Context<Self>,
8734 ) {
8735 let weak_editor = cx.weak_entity();
8736 let bp_prompt = cx.new(|cx| {
8737 BreakpointPromptEditor::new(
8738 weak_editor,
8739 anchor,
8740 breakpoint.clone(),
8741 edit_action,
8742 window,
8743 cx,
8744 )
8745 });
8746
8747 let height = bp_prompt.update(cx, |this, cx| {
8748 this.prompt
8749 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8750 });
8751 let cloned_prompt = bp_prompt.clone();
8752 let blocks = vec![BlockProperties {
8753 style: BlockStyle::Sticky,
8754 placement: BlockPlacement::Above(anchor),
8755 height: Some(height),
8756 render: Arc::new(move |cx| {
8757 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8758 cloned_prompt.clone().into_any_element()
8759 }),
8760 priority: 0,
8761 }];
8762
8763 let focus_handle = bp_prompt.focus_handle(cx);
8764 window.focus(&focus_handle);
8765
8766 let block_ids = self.insert_blocks(blocks, None, cx);
8767 bp_prompt.update(cx, |prompt, _| {
8768 prompt.add_block_ids(block_ids);
8769 });
8770 }
8771
8772 fn breakpoint_at_cursor_head(
8773 &self,
8774 window: &mut Window,
8775 cx: &mut Context<Self>,
8776 ) -> Option<(Anchor, Breakpoint)> {
8777 let cursor_position: Point = self.selections.newest(cx).head();
8778 self.breakpoint_at_row(cursor_position.row, window, cx)
8779 }
8780
8781 pub(crate) fn breakpoint_at_row(
8782 &self,
8783 row: u32,
8784 window: &mut Window,
8785 cx: &mut Context<Self>,
8786 ) -> Option<(Anchor, Breakpoint)> {
8787 let snapshot = self.snapshot(window, cx);
8788 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8789
8790 let project = self.project.clone()?;
8791
8792 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8793 snapshot
8794 .buffer_snapshot
8795 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8796 })?;
8797
8798 let enclosing_excerpt = breakpoint_position.excerpt_id;
8799 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8800 let buffer_snapshot = buffer.read(cx).snapshot();
8801
8802 let row = buffer_snapshot
8803 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8804 .row;
8805
8806 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8807 let anchor_end = snapshot
8808 .buffer_snapshot
8809 .anchor_after(Point::new(row, line_len));
8810
8811 let bp = self
8812 .breakpoint_store
8813 .as_ref()?
8814 .read_with(cx, |breakpoint_store, cx| {
8815 breakpoint_store
8816 .breakpoints(
8817 &buffer,
8818 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8819 &buffer_snapshot,
8820 cx,
8821 )
8822 .next()
8823 .and_then(|(anchor, bp)| {
8824 let breakpoint_row = buffer_snapshot
8825 .summary_for_anchor::<text::PointUtf16>(anchor)
8826 .row;
8827
8828 if breakpoint_row == row {
8829 snapshot
8830 .buffer_snapshot
8831 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8832 .map(|anchor| (anchor, bp.clone()))
8833 } else {
8834 None
8835 }
8836 })
8837 });
8838 bp
8839 }
8840
8841 pub fn edit_log_breakpoint(
8842 &mut self,
8843 _: &EditLogBreakpoint,
8844 window: &mut Window,
8845 cx: &mut Context<Self>,
8846 ) {
8847 let (anchor, bp) = self
8848 .breakpoint_at_cursor_head(window, cx)
8849 .unwrap_or_else(|| {
8850 let cursor_position: Point = self.selections.newest(cx).head();
8851
8852 let breakpoint_position = self
8853 .snapshot(window, cx)
8854 .display_snapshot
8855 .buffer_snapshot
8856 .anchor_after(Point::new(cursor_position.row, 0));
8857
8858 (
8859 breakpoint_position,
8860 Breakpoint {
8861 message: None,
8862 state: BreakpointState::Enabled,
8863 condition: None,
8864 hit_condition: None,
8865 },
8866 )
8867 });
8868
8869 self.add_edit_breakpoint_block(anchor, &bp, BreakpointPromptEditAction::Log, window, cx);
8870 }
8871
8872 pub fn enable_breakpoint(
8873 &mut self,
8874 _: &crate::actions::EnableBreakpoint,
8875 window: &mut Window,
8876 cx: &mut Context<Self>,
8877 ) {
8878 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8879 if breakpoint.is_disabled() {
8880 self.edit_breakpoint_at_anchor(
8881 anchor,
8882 breakpoint,
8883 BreakpointEditAction::InvertState,
8884 cx,
8885 );
8886 }
8887 }
8888 }
8889
8890 pub fn disable_breakpoint(
8891 &mut self,
8892 _: &crate::actions::DisableBreakpoint,
8893 window: &mut Window,
8894 cx: &mut Context<Self>,
8895 ) {
8896 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8897 if breakpoint.is_enabled() {
8898 self.edit_breakpoint_at_anchor(
8899 anchor,
8900 breakpoint,
8901 BreakpointEditAction::InvertState,
8902 cx,
8903 );
8904 }
8905 }
8906 }
8907
8908 pub fn toggle_breakpoint(
8909 &mut self,
8910 _: &crate::actions::ToggleBreakpoint,
8911 window: &mut Window,
8912 cx: &mut Context<Self>,
8913 ) {
8914 let edit_action = BreakpointEditAction::Toggle;
8915
8916 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8917 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8918 } else {
8919 let cursor_position: Point = self.selections.newest(cx).head();
8920
8921 let breakpoint_position = self
8922 .snapshot(window, cx)
8923 .display_snapshot
8924 .buffer_snapshot
8925 .anchor_after(Point::new(cursor_position.row, 0));
8926
8927 self.edit_breakpoint_at_anchor(
8928 breakpoint_position,
8929 Breakpoint::new_standard(),
8930 edit_action,
8931 cx,
8932 );
8933 }
8934 }
8935
8936 pub fn edit_breakpoint_at_anchor(
8937 &mut self,
8938 breakpoint_position: Anchor,
8939 breakpoint: Breakpoint,
8940 edit_action: BreakpointEditAction,
8941 cx: &mut Context<Self>,
8942 ) {
8943 let Some(breakpoint_store) = &self.breakpoint_store else {
8944 return;
8945 };
8946
8947 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8948 if breakpoint_position == Anchor::min() {
8949 self.buffer()
8950 .read(cx)
8951 .excerpt_buffer_ids()
8952 .into_iter()
8953 .next()
8954 } else {
8955 None
8956 }
8957 }) else {
8958 return;
8959 };
8960
8961 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8962 return;
8963 };
8964
8965 breakpoint_store.update(cx, |breakpoint_store, cx| {
8966 breakpoint_store.toggle_breakpoint(
8967 buffer,
8968 (breakpoint_position.text_anchor, breakpoint),
8969 edit_action,
8970 cx,
8971 );
8972 });
8973
8974 cx.notify();
8975 }
8976
8977 #[cfg(any(test, feature = "test-support"))]
8978 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8979 self.breakpoint_store.clone()
8980 }
8981
8982 pub fn prepare_restore_change(
8983 &self,
8984 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8985 hunk: &MultiBufferDiffHunk,
8986 cx: &mut App,
8987 ) -> Option<()> {
8988 if hunk.is_created_file() {
8989 return None;
8990 }
8991 let buffer = self.buffer.read(cx);
8992 let diff = buffer.diff_for(hunk.buffer_id)?;
8993 let buffer = buffer.buffer(hunk.buffer_id)?;
8994 let buffer = buffer.read(cx);
8995 let original_text = diff
8996 .read(cx)
8997 .base_text()
8998 .as_rope()
8999 .slice(hunk.diff_base_byte_range.clone());
9000 let buffer_snapshot = buffer.snapshot();
9001 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9002 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9003 probe
9004 .0
9005 .start
9006 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9007 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9008 }) {
9009 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9010 Some(())
9011 } else {
9012 None
9013 }
9014 }
9015
9016 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9017 self.manipulate_lines(window, cx, |lines| lines.reverse())
9018 }
9019
9020 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9021 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9022 }
9023
9024 fn manipulate_lines<Fn>(
9025 &mut self,
9026 window: &mut Window,
9027 cx: &mut Context<Self>,
9028 mut callback: Fn,
9029 ) where
9030 Fn: FnMut(&mut Vec<&str>),
9031 {
9032 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9033
9034 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9035 let buffer = self.buffer.read(cx).snapshot(cx);
9036
9037 let mut edits = Vec::new();
9038
9039 let selections = self.selections.all::<Point>(cx);
9040 let mut selections = selections.iter().peekable();
9041 let mut contiguous_row_selections = Vec::new();
9042 let mut new_selections = Vec::new();
9043 let mut added_lines = 0;
9044 let mut removed_lines = 0;
9045
9046 while let Some(selection) = selections.next() {
9047 let (start_row, end_row) = consume_contiguous_rows(
9048 &mut contiguous_row_selections,
9049 selection,
9050 &display_map,
9051 &mut selections,
9052 );
9053
9054 let start_point = Point::new(start_row.0, 0);
9055 let end_point = Point::new(
9056 end_row.previous_row().0,
9057 buffer.line_len(end_row.previous_row()),
9058 );
9059 let text = buffer
9060 .text_for_range(start_point..end_point)
9061 .collect::<String>();
9062
9063 let mut lines = text.split('\n').collect_vec();
9064
9065 let lines_before = lines.len();
9066 callback(&mut lines);
9067 let lines_after = lines.len();
9068
9069 edits.push((start_point..end_point, lines.join("\n")));
9070
9071 // Selections must change based on added and removed line count
9072 let start_row =
9073 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9074 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9075 new_selections.push(Selection {
9076 id: selection.id,
9077 start: start_row,
9078 end: end_row,
9079 goal: SelectionGoal::None,
9080 reversed: selection.reversed,
9081 });
9082
9083 if lines_after > lines_before {
9084 added_lines += lines_after - lines_before;
9085 } else if lines_before > lines_after {
9086 removed_lines += lines_before - lines_after;
9087 }
9088 }
9089
9090 self.transact(window, cx, |this, window, cx| {
9091 let buffer = this.buffer.update(cx, |buffer, cx| {
9092 buffer.edit(edits, None, cx);
9093 buffer.snapshot(cx)
9094 });
9095
9096 // Recalculate offsets on newly edited buffer
9097 let new_selections = new_selections
9098 .iter()
9099 .map(|s| {
9100 let start_point = Point::new(s.start.0, 0);
9101 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9102 Selection {
9103 id: s.id,
9104 start: buffer.point_to_offset(start_point),
9105 end: buffer.point_to_offset(end_point),
9106 goal: s.goal,
9107 reversed: s.reversed,
9108 }
9109 })
9110 .collect();
9111
9112 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9113 s.select(new_selections);
9114 });
9115
9116 this.request_autoscroll(Autoscroll::fit(), cx);
9117 });
9118 }
9119
9120 pub fn convert_to_upper_case(
9121 &mut self,
9122 _: &ConvertToUpperCase,
9123 window: &mut Window,
9124 cx: &mut Context<Self>,
9125 ) {
9126 self.manipulate_text(window, cx, |text| text.to_uppercase())
9127 }
9128
9129 pub fn convert_to_lower_case(
9130 &mut self,
9131 _: &ConvertToLowerCase,
9132 window: &mut Window,
9133 cx: &mut Context<Self>,
9134 ) {
9135 self.manipulate_text(window, cx, |text| text.to_lowercase())
9136 }
9137
9138 pub fn convert_to_title_case(
9139 &mut self,
9140 _: &ConvertToTitleCase,
9141 window: &mut Window,
9142 cx: &mut Context<Self>,
9143 ) {
9144 self.manipulate_text(window, cx, |text| {
9145 text.split('\n')
9146 .map(|line| line.to_case(Case::Title))
9147 .join("\n")
9148 })
9149 }
9150
9151 pub fn convert_to_snake_case(
9152 &mut self,
9153 _: &ConvertToSnakeCase,
9154 window: &mut Window,
9155 cx: &mut Context<Self>,
9156 ) {
9157 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9158 }
9159
9160 pub fn convert_to_kebab_case(
9161 &mut self,
9162 _: &ConvertToKebabCase,
9163 window: &mut Window,
9164 cx: &mut Context<Self>,
9165 ) {
9166 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9167 }
9168
9169 pub fn convert_to_upper_camel_case(
9170 &mut self,
9171 _: &ConvertToUpperCamelCase,
9172 window: &mut Window,
9173 cx: &mut Context<Self>,
9174 ) {
9175 self.manipulate_text(window, cx, |text| {
9176 text.split('\n')
9177 .map(|line| line.to_case(Case::UpperCamel))
9178 .join("\n")
9179 })
9180 }
9181
9182 pub fn convert_to_lower_camel_case(
9183 &mut self,
9184 _: &ConvertToLowerCamelCase,
9185 window: &mut Window,
9186 cx: &mut Context<Self>,
9187 ) {
9188 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9189 }
9190
9191 pub fn convert_to_opposite_case(
9192 &mut self,
9193 _: &ConvertToOppositeCase,
9194 window: &mut Window,
9195 cx: &mut Context<Self>,
9196 ) {
9197 self.manipulate_text(window, cx, |text| {
9198 text.chars()
9199 .fold(String::with_capacity(text.len()), |mut t, c| {
9200 if c.is_uppercase() {
9201 t.extend(c.to_lowercase());
9202 } else {
9203 t.extend(c.to_uppercase());
9204 }
9205 t
9206 })
9207 })
9208 }
9209
9210 pub fn convert_to_rot13(
9211 &mut self,
9212 _: &ConvertToRot13,
9213 window: &mut Window,
9214 cx: &mut Context<Self>,
9215 ) {
9216 self.manipulate_text(window, cx, |text| {
9217 text.chars()
9218 .map(|c| match c {
9219 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9220 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9221 _ => c,
9222 })
9223 .collect()
9224 })
9225 }
9226
9227 pub fn convert_to_rot47(
9228 &mut self,
9229 _: &ConvertToRot47,
9230 window: &mut Window,
9231 cx: &mut Context<Self>,
9232 ) {
9233 self.manipulate_text(window, cx, |text| {
9234 text.chars()
9235 .map(|c| {
9236 let code_point = c as u32;
9237 if code_point >= 33 && code_point <= 126 {
9238 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9239 }
9240 c
9241 })
9242 .collect()
9243 })
9244 }
9245
9246 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9247 where
9248 Fn: FnMut(&str) -> String,
9249 {
9250 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9251 let buffer = self.buffer.read(cx).snapshot(cx);
9252
9253 let mut new_selections = Vec::new();
9254 let mut edits = Vec::new();
9255 let mut selection_adjustment = 0i32;
9256
9257 for selection in self.selections.all::<usize>(cx) {
9258 let selection_is_empty = selection.is_empty();
9259
9260 let (start, end) = if selection_is_empty {
9261 let word_range = movement::surrounding_word(
9262 &display_map,
9263 selection.start.to_display_point(&display_map),
9264 );
9265 let start = word_range.start.to_offset(&display_map, Bias::Left);
9266 let end = word_range.end.to_offset(&display_map, Bias::Left);
9267 (start, end)
9268 } else {
9269 (selection.start, selection.end)
9270 };
9271
9272 let text = buffer.text_for_range(start..end).collect::<String>();
9273 let old_length = text.len() as i32;
9274 let text = callback(&text);
9275
9276 new_selections.push(Selection {
9277 start: (start as i32 - selection_adjustment) as usize,
9278 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9279 goal: SelectionGoal::None,
9280 ..selection
9281 });
9282
9283 selection_adjustment += old_length - text.len() as i32;
9284
9285 edits.push((start..end, text));
9286 }
9287
9288 self.transact(window, cx, |this, window, cx| {
9289 this.buffer.update(cx, |buffer, cx| {
9290 buffer.edit(edits, None, cx);
9291 });
9292
9293 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9294 s.select(new_selections);
9295 });
9296
9297 this.request_autoscroll(Autoscroll::fit(), cx);
9298 });
9299 }
9300
9301 pub fn duplicate(
9302 &mut self,
9303 upwards: bool,
9304 whole_lines: bool,
9305 window: &mut Window,
9306 cx: &mut Context<Self>,
9307 ) {
9308 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9309
9310 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9311 let buffer = &display_map.buffer_snapshot;
9312 let selections = self.selections.all::<Point>(cx);
9313
9314 let mut edits = Vec::new();
9315 let mut selections_iter = selections.iter().peekable();
9316 while let Some(selection) = selections_iter.next() {
9317 let mut rows = selection.spanned_rows(false, &display_map);
9318 // duplicate line-wise
9319 if whole_lines || selection.start == selection.end {
9320 // Avoid duplicating the same lines twice.
9321 while let Some(next_selection) = selections_iter.peek() {
9322 let next_rows = next_selection.spanned_rows(false, &display_map);
9323 if next_rows.start < rows.end {
9324 rows.end = next_rows.end;
9325 selections_iter.next().unwrap();
9326 } else {
9327 break;
9328 }
9329 }
9330
9331 // Copy the text from the selected row region and splice it either at the start
9332 // or end of the region.
9333 let start = Point::new(rows.start.0, 0);
9334 let end = Point::new(
9335 rows.end.previous_row().0,
9336 buffer.line_len(rows.end.previous_row()),
9337 );
9338 let text = buffer
9339 .text_for_range(start..end)
9340 .chain(Some("\n"))
9341 .collect::<String>();
9342 let insert_location = if upwards {
9343 Point::new(rows.end.0, 0)
9344 } else {
9345 start
9346 };
9347 edits.push((insert_location..insert_location, text));
9348 } else {
9349 // duplicate character-wise
9350 let start = selection.start;
9351 let end = selection.end;
9352 let text = buffer.text_for_range(start..end).collect::<String>();
9353 edits.push((selection.end..selection.end, text));
9354 }
9355 }
9356
9357 self.transact(window, cx, |this, _, cx| {
9358 this.buffer.update(cx, |buffer, cx| {
9359 buffer.edit(edits, None, cx);
9360 });
9361
9362 this.request_autoscroll(Autoscroll::fit(), cx);
9363 });
9364 }
9365
9366 pub fn duplicate_line_up(
9367 &mut self,
9368 _: &DuplicateLineUp,
9369 window: &mut Window,
9370 cx: &mut Context<Self>,
9371 ) {
9372 self.duplicate(true, true, window, cx);
9373 }
9374
9375 pub fn duplicate_line_down(
9376 &mut self,
9377 _: &DuplicateLineDown,
9378 window: &mut Window,
9379 cx: &mut Context<Self>,
9380 ) {
9381 self.duplicate(false, true, window, cx);
9382 }
9383
9384 pub fn duplicate_selection(
9385 &mut self,
9386 _: &DuplicateSelection,
9387 window: &mut Window,
9388 cx: &mut Context<Self>,
9389 ) {
9390 self.duplicate(false, false, window, cx);
9391 }
9392
9393 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9394 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9395
9396 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9397 let buffer = self.buffer.read(cx).snapshot(cx);
9398
9399 let mut edits = Vec::new();
9400 let mut unfold_ranges = Vec::new();
9401 let mut refold_creases = Vec::new();
9402
9403 let selections = self.selections.all::<Point>(cx);
9404 let mut selections = selections.iter().peekable();
9405 let mut contiguous_row_selections = Vec::new();
9406 let mut new_selections = Vec::new();
9407
9408 while let Some(selection) = selections.next() {
9409 // Find all the selections that span a contiguous row range
9410 let (start_row, end_row) = consume_contiguous_rows(
9411 &mut contiguous_row_selections,
9412 selection,
9413 &display_map,
9414 &mut selections,
9415 );
9416
9417 // Move the text spanned by the row range to be before the line preceding the row range
9418 if start_row.0 > 0 {
9419 let range_to_move = Point::new(
9420 start_row.previous_row().0,
9421 buffer.line_len(start_row.previous_row()),
9422 )
9423 ..Point::new(
9424 end_row.previous_row().0,
9425 buffer.line_len(end_row.previous_row()),
9426 );
9427 let insertion_point = display_map
9428 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9429 .0;
9430
9431 // Don't move lines across excerpts
9432 if buffer
9433 .excerpt_containing(insertion_point..range_to_move.end)
9434 .is_some()
9435 {
9436 let text = buffer
9437 .text_for_range(range_to_move.clone())
9438 .flat_map(|s| s.chars())
9439 .skip(1)
9440 .chain(['\n'])
9441 .collect::<String>();
9442
9443 edits.push((
9444 buffer.anchor_after(range_to_move.start)
9445 ..buffer.anchor_before(range_to_move.end),
9446 String::new(),
9447 ));
9448 let insertion_anchor = buffer.anchor_after(insertion_point);
9449 edits.push((insertion_anchor..insertion_anchor, text));
9450
9451 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9452
9453 // Move selections up
9454 new_selections.extend(contiguous_row_selections.drain(..).map(
9455 |mut selection| {
9456 selection.start.row -= row_delta;
9457 selection.end.row -= row_delta;
9458 selection
9459 },
9460 ));
9461
9462 // Move folds up
9463 unfold_ranges.push(range_to_move.clone());
9464 for fold in display_map.folds_in_range(
9465 buffer.anchor_before(range_to_move.start)
9466 ..buffer.anchor_after(range_to_move.end),
9467 ) {
9468 let mut start = fold.range.start.to_point(&buffer);
9469 let mut end = fold.range.end.to_point(&buffer);
9470 start.row -= row_delta;
9471 end.row -= row_delta;
9472 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9473 }
9474 }
9475 }
9476
9477 // If we didn't move line(s), preserve the existing selections
9478 new_selections.append(&mut contiguous_row_selections);
9479 }
9480
9481 self.transact(window, cx, |this, window, cx| {
9482 this.unfold_ranges(&unfold_ranges, true, true, cx);
9483 this.buffer.update(cx, |buffer, cx| {
9484 for (range, text) in edits {
9485 buffer.edit([(range, text)], None, cx);
9486 }
9487 });
9488 this.fold_creases(refold_creases, true, window, cx);
9489 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9490 s.select(new_selections);
9491 })
9492 });
9493 }
9494
9495 pub fn move_line_down(
9496 &mut self,
9497 _: &MoveLineDown,
9498 window: &mut Window,
9499 cx: &mut Context<Self>,
9500 ) {
9501 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9502
9503 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9504 let buffer = self.buffer.read(cx).snapshot(cx);
9505
9506 let mut edits = Vec::new();
9507 let mut unfold_ranges = Vec::new();
9508 let mut refold_creases = Vec::new();
9509
9510 let selections = self.selections.all::<Point>(cx);
9511 let mut selections = selections.iter().peekable();
9512 let mut contiguous_row_selections = Vec::new();
9513 let mut new_selections = Vec::new();
9514
9515 while let Some(selection) = selections.next() {
9516 // Find all the selections that span a contiguous row range
9517 let (start_row, end_row) = consume_contiguous_rows(
9518 &mut contiguous_row_selections,
9519 selection,
9520 &display_map,
9521 &mut selections,
9522 );
9523
9524 // Move the text spanned by the row range to be after the last line of the row range
9525 if end_row.0 <= buffer.max_point().row {
9526 let range_to_move =
9527 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9528 let insertion_point = display_map
9529 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9530 .0;
9531
9532 // Don't move lines across excerpt boundaries
9533 if buffer
9534 .excerpt_containing(range_to_move.start..insertion_point)
9535 .is_some()
9536 {
9537 let mut text = String::from("\n");
9538 text.extend(buffer.text_for_range(range_to_move.clone()));
9539 text.pop(); // Drop trailing newline
9540 edits.push((
9541 buffer.anchor_after(range_to_move.start)
9542 ..buffer.anchor_before(range_to_move.end),
9543 String::new(),
9544 ));
9545 let insertion_anchor = buffer.anchor_after(insertion_point);
9546 edits.push((insertion_anchor..insertion_anchor, text));
9547
9548 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9549
9550 // Move selections down
9551 new_selections.extend(contiguous_row_selections.drain(..).map(
9552 |mut selection| {
9553 selection.start.row += row_delta;
9554 selection.end.row += row_delta;
9555 selection
9556 },
9557 ));
9558
9559 // Move folds down
9560 unfold_ranges.push(range_to_move.clone());
9561 for fold in display_map.folds_in_range(
9562 buffer.anchor_before(range_to_move.start)
9563 ..buffer.anchor_after(range_to_move.end),
9564 ) {
9565 let mut start = fold.range.start.to_point(&buffer);
9566 let mut end = fold.range.end.to_point(&buffer);
9567 start.row += row_delta;
9568 end.row += row_delta;
9569 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9570 }
9571 }
9572 }
9573
9574 // If we didn't move line(s), preserve the existing selections
9575 new_selections.append(&mut contiguous_row_selections);
9576 }
9577
9578 self.transact(window, cx, |this, window, cx| {
9579 this.unfold_ranges(&unfold_ranges, true, true, cx);
9580 this.buffer.update(cx, |buffer, cx| {
9581 for (range, text) in edits {
9582 buffer.edit([(range, text)], None, cx);
9583 }
9584 });
9585 this.fold_creases(refold_creases, true, window, cx);
9586 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9587 s.select(new_selections)
9588 });
9589 });
9590 }
9591
9592 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9593 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9594 let text_layout_details = &self.text_layout_details(window);
9595 self.transact(window, cx, |this, window, cx| {
9596 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9597 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9598 s.move_with(|display_map, selection| {
9599 if !selection.is_empty() {
9600 return;
9601 }
9602
9603 let mut head = selection.head();
9604 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9605 if head.column() == display_map.line_len(head.row()) {
9606 transpose_offset = display_map
9607 .buffer_snapshot
9608 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9609 }
9610
9611 if transpose_offset == 0 {
9612 return;
9613 }
9614
9615 *head.column_mut() += 1;
9616 head = display_map.clip_point(head, Bias::Right);
9617 let goal = SelectionGoal::HorizontalPosition(
9618 display_map
9619 .x_for_display_point(head, text_layout_details)
9620 .into(),
9621 );
9622 selection.collapse_to(head, goal);
9623
9624 let transpose_start = display_map
9625 .buffer_snapshot
9626 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9627 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9628 let transpose_end = display_map
9629 .buffer_snapshot
9630 .clip_offset(transpose_offset + 1, Bias::Right);
9631 if let Some(ch) =
9632 display_map.buffer_snapshot.chars_at(transpose_start).next()
9633 {
9634 edits.push((transpose_start..transpose_offset, String::new()));
9635 edits.push((transpose_end..transpose_end, ch.to_string()));
9636 }
9637 }
9638 });
9639 edits
9640 });
9641 this.buffer
9642 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9643 let selections = this.selections.all::<usize>(cx);
9644 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9645 s.select(selections);
9646 });
9647 });
9648 }
9649
9650 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9651 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9652 self.rewrap_impl(RewrapOptions::default(), cx)
9653 }
9654
9655 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9656 let buffer = self.buffer.read(cx).snapshot(cx);
9657 let selections = self.selections.all::<Point>(cx);
9658 let mut selections = selections.iter().peekable();
9659
9660 let mut edits = Vec::new();
9661 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9662
9663 while let Some(selection) = selections.next() {
9664 let mut start_row = selection.start.row;
9665 let mut end_row = selection.end.row;
9666
9667 // Skip selections that overlap with a range that has already been rewrapped.
9668 let selection_range = start_row..end_row;
9669 if rewrapped_row_ranges
9670 .iter()
9671 .any(|range| range.overlaps(&selection_range))
9672 {
9673 continue;
9674 }
9675
9676 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9677
9678 // Since not all lines in the selection may be at the same indent
9679 // level, choose the indent size that is the most common between all
9680 // of the lines.
9681 //
9682 // If there is a tie, we use the deepest indent.
9683 let (indent_size, indent_end) = {
9684 let mut indent_size_occurrences = HashMap::default();
9685 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9686
9687 for row in start_row..=end_row {
9688 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9689 rows_by_indent_size.entry(indent).or_default().push(row);
9690 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9691 }
9692
9693 let indent_size = indent_size_occurrences
9694 .into_iter()
9695 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9696 .map(|(indent, _)| indent)
9697 .unwrap_or_default();
9698 let row = rows_by_indent_size[&indent_size][0];
9699 let indent_end = Point::new(row, indent_size.len);
9700
9701 (indent_size, indent_end)
9702 };
9703
9704 let mut line_prefix = indent_size.chars().collect::<String>();
9705
9706 let mut inside_comment = false;
9707 if let Some(comment_prefix) =
9708 buffer
9709 .language_scope_at(selection.head())
9710 .and_then(|language| {
9711 language
9712 .line_comment_prefixes()
9713 .iter()
9714 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9715 .cloned()
9716 })
9717 {
9718 line_prefix.push_str(&comment_prefix);
9719 inside_comment = true;
9720 }
9721
9722 let language_settings = buffer.language_settings_at(selection.head(), cx);
9723 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9724 RewrapBehavior::InComments => inside_comment,
9725 RewrapBehavior::InSelections => !selection.is_empty(),
9726 RewrapBehavior::Anywhere => true,
9727 };
9728
9729 let should_rewrap = options.override_language_settings
9730 || allow_rewrap_based_on_language
9731 || self.hard_wrap.is_some();
9732 if !should_rewrap {
9733 continue;
9734 }
9735
9736 if selection.is_empty() {
9737 'expand_upwards: while start_row > 0 {
9738 let prev_row = start_row - 1;
9739 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9740 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9741 {
9742 start_row = prev_row;
9743 } else {
9744 break 'expand_upwards;
9745 }
9746 }
9747
9748 'expand_downwards: while end_row < buffer.max_point().row {
9749 let next_row = end_row + 1;
9750 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9751 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9752 {
9753 end_row = next_row;
9754 } else {
9755 break 'expand_downwards;
9756 }
9757 }
9758 }
9759
9760 let start = Point::new(start_row, 0);
9761 let start_offset = start.to_offset(&buffer);
9762 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9763 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9764 let Some(lines_without_prefixes) = selection_text
9765 .lines()
9766 .map(|line| {
9767 line.strip_prefix(&line_prefix)
9768 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9769 .ok_or_else(|| {
9770 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9771 })
9772 })
9773 .collect::<Result<Vec<_>, _>>()
9774 .log_err()
9775 else {
9776 continue;
9777 };
9778
9779 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9780 buffer
9781 .language_settings_at(Point::new(start_row, 0), cx)
9782 .preferred_line_length as usize
9783 });
9784 let wrapped_text = wrap_with_prefix(
9785 line_prefix,
9786 lines_without_prefixes.join("\n"),
9787 wrap_column,
9788 tab_size,
9789 options.preserve_existing_whitespace,
9790 );
9791
9792 // TODO: should always use char-based diff while still supporting cursor behavior that
9793 // matches vim.
9794 let mut diff_options = DiffOptions::default();
9795 if options.override_language_settings {
9796 diff_options.max_word_diff_len = 0;
9797 diff_options.max_word_diff_line_count = 0;
9798 } else {
9799 diff_options.max_word_diff_len = usize::MAX;
9800 diff_options.max_word_diff_line_count = usize::MAX;
9801 }
9802
9803 for (old_range, new_text) in
9804 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9805 {
9806 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9807 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9808 edits.push((edit_start..edit_end, new_text));
9809 }
9810
9811 rewrapped_row_ranges.push(start_row..=end_row);
9812 }
9813
9814 self.buffer
9815 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9816 }
9817
9818 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9819 let mut text = String::new();
9820 let buffer = self.buffer.read(cx).snapshot(cx);
9821 let mut selections = self.selections.all::<Point>(cx);
9822 let mut clipboard_selections = Vec::with_capacity(selections.len());
9823 {
9824 let max_point = buffer.max_point();
9825 let mut is_first = true;
9826 for selection in &mut selections {
9827 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9828 if is_entire_line {
9829 selection.start = Point::new(selection.start.row, 0);
9830 if !selection.is_empty() && selection.end.column == 0 {
9831 selection.end = cmp::min(max_point, selection.end);
9832 } else {
9833 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9834 }
9835 selection.goal = SelectionGoal::None;
9836 }
9837 if is_first {
9838 is_first = false;
9839 } else {
9840 text += "\n";
9841 }
9842 let mut len = 0;
9843 for chunk in buffer.text_for_range(selection.start..selection.end) {
9844 text.push_str(chunk);
9845 len += chunk.len();
9846 }
9847 clipboard_selections.push(ClipboardSelection {
9848 len,
9849 is_entire_line,
9850 first_line_indent: buffer
9851 .indent_size_for_line(MultiBufferRow(selection.start.row))
9852 .len,
9853 });
9854 }
9855 }
9856
9857 self.transact(window, cx, |this, window, cx| {
9858 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9859 s.select(selections);
9860 });
9861 this.insert("", window, cx);
9862 });
9863 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9864 }
9865
9866 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9867 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9868 let item = self.cut_common(window, cx);
9869 cx.write_to_clipboard(item);
9870 }
9871
9872 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9873 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9874 self.change_selections(None, window, cx, |s| {
9875 s.move_with(|snapshot, sel| {
9876 if sel.is_empty() {
9877 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9878 }
9879 });
9880 });
9881 let item = self.cut_common(window, cx);
9882 cx.set_global(KillRing(item))
9883 }
9884
9885 pub fn kill_ring_yank(
9886 &mut self,
9887 _: &KillRingYank,
9888 window: &mut Window,
9889 cx: &mut Context<Self>,
9890 ) {
9891 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9892 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9893 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9894 (kill_ring.text().to_string(), kill_ring.metadata_json())
9895 } else {
9896 return;
9897 }
9898 } else {
9899 return;
9900 };
9901 self.do_paste(&text, metadata, false, window, cx);
9902 }
9903
9904 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9905 self.do_copy(true, cx);
9906 }
9907
9908 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9909 self.do_copy(false, cx);
9910 }
9911
9912 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9913 let selections = self.selections.all::<Point>(cx);
9914 let buffer = self.buffer.read(cx).read(cx);
9915 let mut text = String::new();
9916
9917 let mut clipboard_selections = Vec::with_capacity(selections.len());
9918 {
9919 let max_point = buffer.max_point();
9920 let mut is_first = true;
9921 for selection in &selections {
9922 let mut start = selection.start;
9923 let mut end = selection.end;
9924 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9925 if is_entire_line {
9926 start = Point::new(start.row, 0);
9927 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9928 }
9929
9930 let mut trimmed_selections = Vec::new();
9931 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9932 let row = MultiBufferRow(start.row);
9933 let first_indent = buffer.indent_size_for_line(row);
9934 if first_indent.len == 0 || start.column > first_indent.len {
9935 trimmed_selections.push(start..end);
9936 } else {
9937 trimmed_selections.push(
9938 Point::new(row.0, first_indent.len)
9939 ..Point::new(row.0, buffer.line_len(row)),
9940 );
9941 for row in start.row + 1..=end.row {
9942 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
9943 if row_indent_size.len >= first_indent.len {
9944 trimmed_selections.push(
9945 Point::new(row, first_indent.len)
9946 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
9947 );
9948 } else {
9949 trimmed_selections.clear();
9950 trimmed_selections.push(start..end);
9951 break;
9952 }
9953 }
9954 }
9955 } else {
9956 trimmed_selections.push(start..end);
9957 }
9958
9959 for trimmed_range in trimmed_selections {
9960 if is_first {
9961 is_first = false;
9962 } else {
9963 text += "\n";
9964 }
9965 let mut len = 0;
9966 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
9967 text.push_str(chunk);
9968 len += chunk.len();
9969 }
9970 clipboard_selections.push(ClipboardSelection {
9971 len,
9972 is_entire_line,
9973 first_line_indent: buffer
9974 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
9975 .len,
9976 });
9977 }
9978 }
9979 }
9980
9981 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9982 text,
9983 clipboard_selections,
9984 ));
9985 }
9986
9987 pub fn do_paste(
9988 &mut self,
9989 text: &String,
9990 clipboard_selections: Option<Vec<ClipboardSelection>>,
9991 handle_entire_lines: bool,
9992 window: &mut Window,
9993 cx: &mut Context<Self>,
9994 ) {
9995 if self.read_only(cx) {
9996 return;
9997 }
9998
9999 let clipboard_text = Cow::Borrowed(text);
10000
10001 self.transact(window, cx, |this, window, cx| {
10002 if let Some(mut clipboard_selections) = clipboard_selections {
10003 let old_selections = this.selections.all::<usize>(cx);
10004 let all_selections_were_entire_line =
10005 clipboard_selections.iter().all(|s| s.is_entire_line);
10006 let first_selection_indent_column =
10007 clipboard_selections.first().map(|s| s.first_line_indent);
10008 if clipboard_selections.len() != old_selections.len() {
10009 clipboard_selections.drain(..);
10010 }
10011 let cursor_offset = this.selections.last::<usize>(cx).head();
10012 let mut auto_indent_on_paste = true;
10013
10014 this.buffer.update(cx, |buffer, cx| {
10015 let snapshot = buffer.read(cx);
10016 auto_indent_on_paste = snapshot
10017 .language_settings_at(cursor_offset, cx)
10018 .auto_indent_on_paste;
10019
10020 let mut start_offset = 0;
10021 let mut edits = Vec::new();
10022 let mut original_indent_columns = Vec::new();
10023 for (ix, selection) in old_selections.iter().enumerate() {
10024 let to_insert;
10025 let entire_line;
10026 let original_indent_column;
10027 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10028 let end_offset = start_offset + clipboard_selection.len;
10029 to_insert = &clipboard_text[start_offset..end_offset];
10030 entire_line = clipboard_selection.is_entire_line;
10031 start_offset = end_offset + 1;
10032 original_indent_column = Some(clipboard_selection.first_line_indent);
10033 } else {
10034 to_insert = clipboard_text.as_str();
10035 entire_line = all_selections_were_entire_line;
10036 original_indent_column = first_selection_indent_column
10037 }
10038
10039 // If the corresponding selection was empty when this slice of the
10040 // clipboard text was written, then the entire line containing the
10041 // selection was copied. If this selection is also currently empty,
10042 // then paste the line before the current line of the buffer.
10043 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10044 let column = selection.start.to_point(&snapshot).column as usize;
10045 let line_start = selection.start - column;
10046 line_start..line_start
10047 } else {
10048 selection.range()
10049 };
10050
10051 edits.push((range, to_insert));
10052 original_indent_columns.push(original_indent_column);
10053 }
10054 drop(snapshot);
10055
10056 buffer.edit(
10057 edits,
10058 if auto_indent_on_paste {
10059 Some(AutoindentMode::Block {
10060 original_indent_columns,
10061 })
10062 } else {
10063 None
10064 },
10065 cx,
10066 );
10067 });
10068
10069 let selections = this.selections.all::<usize>(cx);
10070 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10071 s.select(selections)
10072 });
10073 } else {
10074 this.insert(&clipboard_text, window, cx);
10075 }
10076 });
10077 }
10078
10079 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10080 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10081 if let Some(item) = cx.read_from_clipboard() {
10082 let entries = item.entries();
10083
10084 match entries.first() {
10085 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10086 // of all the pasted entries.
10087 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10088 .do_paste(
10089 clipboard_string.text(),
10090 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10091 true,
10092 window,
10093 cx,
10094 ),
10095 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10096 }
10097 }
10098 }
10099
10100 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10101 if self.read_only(cx) {
10102 return;
10103 }
10104
10105 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10106
10107 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10108 if let Some((selections, _)) =
10109 self.selection_history.transaction(transaction_id).cloned()
10110 {
10111 self.change_selections(None, window, cx, |s| {
10112 s.select_anchors(selections.to_vec());
10113 });
10114 } else {
10115 log::error!(
10116 "No entry in selection_history found for undo. \
10117 This may correspond to a bug where undo does not update the selection. \
10118 If this is occurring, please add details to \
10119 https://github.com/zed-industries/zed/issues/22692"
10120 );
10121 }
10122 self.request_autoscroll(Autoscroll::fit(), cx);
10123 self.unmark_text(window, cx);
10124 self.refresh_inline_completion(true, false, window, cx);
10125 cx.emit(EditorEvent::Edited { transaction_id });
10126 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10127 }
10128 }
10129
10130 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10131 if self.read_only(cx) {
10132 return;
10133 }
10134
10135 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10136
10137 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10138 if let Some((_, Some(selections))) =
10139 self.selection_history.transaction(transaction_id).cloned()
10140 {
10141 self.change_selections(None, window, cx, |s| {
10142 s.select_anchors(selections.to_vec());
10143 });
10144 } else {
10145 log::error!(
10146 "No entry in selection_history found for redo. \
10147 This may correspond to a bug where undo does not update the selection. \
10148 If this is occurring, please add details to \
10149 https://github.com/zed-industries/zed/issues/22692"
10150 );
10151 }
10152 self.request_autoscroll(Autoscroll::fit(), cx);
10153 self.unmark_text(window, cx);
10154 self.refresh_inline_completion(true, false, window, cx);
10155 cx.emit(EditorEvent::Edited { transaction_id });
10156 }
10157 }
10158
10159 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10160 self.buffer
10161 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10162 }
10163
10164 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10165 self.buffer
10166 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10167 }
10168
10169 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10170 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10171 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10172 s.move_with(|map, selection| {
10173 let cursor = if selection.is_empty() {
10174 movement::left(map, selection.start)
10175 } else {
10176 selection.start
10177 };
10178 selection.collapse_to(cursor, SelectionGoal::None);
10179 });
10180 })
10181 }
10182
10183 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10184 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10185 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10186 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10187 })
10188 }
10189
10190 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10191 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10192 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10193 s.move_with(|map, selection| {
10194 let cursor = if selection.is_empty() {
10195 movement::right(map, selection.end)
10196 } else {
10197 selection.end
10198 };
10199 selection.collapse_to(cursor, SelectionGoal::None)
10200 });
10201 })
10202 }
10203
10204 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10205 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10206 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10207 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10208 })
10209 }
10210
10211 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10212 if self.take_rename(true, window, cx).is_some() {
10213 return;
10214 }
10215
10216 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10217 cx.propagate();
10218 return;
10219 }
10220
10221 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10222
10223 let text_layout_details = &self.text_layout_details(window);
10224 let selection_count = self.selections.count();
10225 let first_selection = self.selections.first_anchor();
10226
10227 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10228 s.move_with(|map, selection| {
10229 if !selection.is_empty() {
10230 selection.goal = SelectionGoal::None;
10231 }
10232 let (cursor, goal) = movement::up(
10233 map,
10234 selection.start,
10235 selection.goal,
10236 false,
10237 text_layout_details,
10238 );
10239 selection.collapse_to(cursor, goal);
10240 });
10241 });
10242
10243 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10244 {
10245 cx.propagate();
10246 }
10247 }
10248
10249 pub fn move_up_by_lines(
10250 &mut self,
10251 action: &MoveUpByLines,
10252 window: &mut Window,
10253 cx: &mut Context<Self>,
10254 ) {
10255 if self.take_rename(true, window, cx).is_some() {
10256 return;
10257 }
10258
10259 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10260 cx.propagate();
10261 return;
10262 }
10263
10264 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10265
10266 let text_layout_details = &self.text_layout_details(window);
10267
10268 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10269 s.move_with(|map, selection| {
10270 if !selection.is_empty() {
10271 selection.goal = SelectionGoal::None;
10272 }
10273 let (cursor, goal) = movement::up_by_rows(
10274 map,
10275 selection.start,
10276 action.lines,
10277 selection.goal,
10278 false,
10279 text_layout_details,
10280 );
10281 selection.collapse_to(cursor, goal);
10282 });
10283 })
10284 }
10285
10286 pub fn move_down_by_lines(
10287 &mut self,
10288 action: &MoveDownByLines,
10289 window: &mut Window,
10290 cx: &mut Context<Self>,
10291 ) {
10292 if self.take_rename(true, window, cx).is_some() {
10293 return;
10294 }
10295
10296 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10297 cx.propagate();
10298 return;
10299 }
10300
10301 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10302
10303 let text_layout_details = &self.text_layout_details(window);
10304
10305 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10306 s.move_with(|map, selection| {
10307 if !selection.is_empty() {
10308 selection.goal = SelectionGoal::None;
10309 }
10310 let (cursor, goal) = movement::down_by_rows(
10311 map,
10312 selection.start,
10313 action.lines,
10314 selection.goal,
10315 false,
10316 text_layout_details,
10317 );
10318 selection.collapse_to(cursor, goal);
10319 });
10320 })
10321 }
10322
10323 pub fn select_down_by_lines(
10324 &mut self,
10325 action: &SelectDownByLines,
10326 window: &mut Window,
10327 cx: &mut Context<Self>,
10328 ) {
10329 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10330 let text_layout_details = &self.text_layout_details(window);
10331 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10332 s.move_heads_with(|map, head, goal| {
10333 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10334 })
10335 })
10336 }
10337
10338 pub fn select_up_by_lines(
10339 &mut self,
10340 action: &SelectUpByLines,
10341 window: &mut Window,
10342 cx: &mut Context<Self>,
10343 ) {
10344 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10345 let text_layout_details = &self.text_layout_details(window);
10346 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10347 s.move_heads_with(|map, head, goal| {
10348 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10349 })
10350 })
10351 }
10352
10353 pub fn select_page_up(
10354 &mut self,
10355 _: &SelectPageUp,
10356 window: &mut Window,
10357 cx: &mut Context<Self>,
10358 ) {
10359 let Some(row_count) = self.visible_row_count() else {
10360 return;
10361 };
10362
10363 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10364
10365 let text_layout_details = &self.text_layout_details(window);
10366
10367 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10368 s.move_heads_with(|map, head, goal| {
10369 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10370 })
10371 })
10372 }
10373
10374 pub fn move_page_up(
10375 &mut self,
10376 action: &MovePageUp,
10377 window: &mut Window,
10378 cx: &mut Context<Self>,
10379 ) {
10380 if self.take_rename(true, window, cx).is_some() {
10381 return;
10382 }
10383
10384 if self
10385 .context_menu
10386 .borrow_mut()
10387 .as_mut()
10388 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10389 .unwrap_or(false)
10390 {
10391 return;
10392 }
10393
10394 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10395 cx.propagate();
10396 return;
10397 }
10398
10399 let Some(row_count) = self.visible_row_count() else {
10400 return;
10401 };
10402
10403 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10404
10405 let autoscroll = if action.center_cursor {
10406 Autoscroll::center()
10407 } else {
10408 Autoscroll::fit()
10409 };
10410
10411 let text_layout_details = &self.text_layout_details(window);
10412
10413 self.change_selections(Some(autoscroll), window, cx, |s| {
10414 s.move_with(|map, selection| {
10415 if !selection.is_empty() {
10416 selection.goal = SelectionGoal::None;
10417 }
10418 let (cursor, goal) = movement::up_by_rows(
10419 map,
10420 selection.end,
10421 row_count,
10422 selection.goal,
10423 false,
10424 text_layout_details,
10425 );
10426 selection.collapse_to(cursor, goal);
10427 });
10428 });
10429 }
10430
10431 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10432 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10433 let text_layout_details = &self.text_layout_details(window);
10434 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10435 s.move_heads_with(|map, head, goal| {
10436 movement::up(map, head, goal, false, text_layout_details)
10437 })
10438 })
10439 }
10440
10441 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10442 self.take_rename(true, window, cx);
10443
10444 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10445 cx.propagate();
10446 return;
10447 }
10448
10449 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10450
10451 let text_layout_details = &self.text_layout_details(window);
10452 let selection_count = self.selections.count();
10453 let first_selection = self.selections.first_anchor();
10454
10455 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10456 s.move_with(|map, selection| {
10457 if !selection.is_empty() {
10458 selection.goal = SelectionGoal::None;
10459 }
10460 let (cursor, goal) = movement::down(
10461 map,
10462 selection.end,
10463 selection.goal,
10464 false,
10465 text_layout_details,
10466 );
10467 selection.collapse_to(cursor, goal);
10468 });
10469 });
10470
10471 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10472 {
10473 cx.propagate();
10474 }
10475 }
10476
10477 pub fn select_page_down(
10478 &mut self,
10479 _: &SelectPageDown,
10480 window: &mut Window,
10481 cx: &mut Context<Self>,
10482 ) {
10483 let Some(row_count) = self.visible_row_count() else {
10484 return;
10485 };
10486
10487 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10488
10489 let text_layout_details = &self.text_layout_details(window);
10490
10491 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10492 s.move_heads_with(|map, head, goal| {
10493 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10494 })
10495 })
10496 }
10497
10498 pub fn move_page_down(
10499 &mut self,
10500 action: &MovePageDown,
10501 window: &mut Window,
10502 cx: &mut Context<Self>,
10503 ) {
10504 if self.take_rename(true, window, cx).is_some() {
10505 return;
10506 }
10507
10508 if self
10509 .context_menu
10510 .borrow_mut()
10511 .as_mut()
10512 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10513 .unwrap_or(false)
10514 {
10515 return;
10516 }
10517
10518 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10519 cx.propagate();
10520 return;
10521 }
10522
10523 let Some(row_count) = self.visible_row_count() else {
10524 return;
10525 };
10526
10527 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10528
10529 let autoscroll = if action.center_cursor {
10530 Autoscroll::center()
10531 } else {
10532 Autoscroll::fit()
10533 };
10534
10535 let text_layout_details = &self.text_layout_details(window);
10536 self.change_selections(Some(autoscroll), window, cx, |s| {
10537 s.move_with(|map, selection| {
10538 if !selection.is_empty() {
10539 selection.goal = SelectionGoal::None;
10540 }
10541 let (cursor, goal) = movement::down_by_rows(
10542 map,
10543 selection.end,
10544 row_count,
10545 selection.goal,
10546 false,
10547 text_layout_details,
10548 );
10549 selection.collapse_to(cursor, goal);
10550 });
10551 });
10552 }
10553
10554 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10555 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10556 let text_layout_details = &self.text_layout_details(window);
10557 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10558 s.move_heads_with(|map, head, goal| {
10559 movement::down(map, head, goal, false, text_layout_details)
10560 })
10561 });
10562 }
10563
10564 pub fn context_menu_first(
10565 &mut self,
10566 _: &ContextMenuFirst,
10567 _window: &mut Window,
10568 cx: &mut Context<Self>,
10569 ) {
10570 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10571 context_menu.select_first(self.completion_provider.as_deref(), cx);
10572 }
10573 }
10574
10575 pub fn context_menu_prev(
10576 &mut self,
10577 _: &ContextMenuPrevious,
10578 _window: &mut Window,
10579 cx: &mut Context<Self>,
10580 ) {
10581 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10582 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10583 }
10584 }
10585
10586 pub fn context_menu_next(
10587 &mut self,
10588 _: &ContextMenuNext,
10589 _window: &mut Window,
10590 cx: &mut Context<Self>,
10591 ) {
10592 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10593 context_menu.select_next(self.completion_provider.as_deref(), cx);
10594 }
10595 }
10596
10597 pub fn context_menu_last(
10598 &mut self,
10599 _: &ContextMenuLast,
10600 _window: &mut Window,
10601 cx: &mut Context<Self>,
10602 ) {
10603 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10604 context_menu.select_last(self.completion_provider.as_deref(), cx);
10605 }
10606 }
10607
10608 pub fn move_to_previous_word_start(
10609 &mut self,
10610 _: &MoveToPreviousWordStart,
10611 window: &mut Window,
10612 cx: &mut Context<Self>,
10613 ) {
10614 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10615 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10616 s.move_cursors_with(|map, head, _| {
10617 (
10618 movement::previous_word_start(map, head),
10619 SelectionGoal::None,
10620 )
10621 });
10622 })
10623 }
10624
10625 pub fn move_to_previous_subword_start(
10626 &mut self,
10627 _: &MoveToPreviousSubwordStart,
10628 window: &mut Window,
10629 cx: &mut Context<Self>,
10630 ) {
10631 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10632 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10633 s.move_cursors_with(|map, head, _| {
10634 (
10635 movement::previous_subword_start(map, head),
10636 SelectionGoal::None,
10637 )
10638 });
10639 })
10640 }
10641
10642 pub fn select_to_previous_word_start(
10643 &mut self,
10644 _: &SelectToPreviousWordStart,
10645 window: &mut Window,
10646 cx: &mut Context<Self>,
10647 ) {
10648 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10649 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10650 s.move_heads_with(|map, head, _| {
10651 (
10652 movement::previous_word_start(map, head),
10653 SelectionGoal::None,
10654 )
10655 });
10656 })
10657 }
10658
10659 pub fn select_to_previous_subword_start(
10660 &mut self,
10661 _: &SelectToPreviousSubwordStart,
10662 window: &mut Window,
10663 cx: &mut Context<Self>,
10664 ) {
10665 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10666 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10667 s.move_heads_with(|map, head, _| {
10668 (
10669 movement::previous_subword_start(map, head),
10670 SelectionGoal::None,
10671 )
10672 });
10673 })
10674 }
10675
10676 pub fn delete_to_previous_word_start(
10677 &mut self,
10678 action: &DeleteToPreviousWordStart,
10679 window: &mut Window,
10680 cx: &mut Context<Self>,
10681 ) {
10682 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10683 self.transact(window, cx, |this, window, cx| {
10684 this.select_autoclose_pair(window, cx);
10685 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686 s.move_with(|map, selection| {
10687 if selection.is_empty() {
10688 let cursor = if action.ignore_newlines {
10689 movement::previous_word_start(map, selection.head())
10690 } else {
10691 movement::previous_word_start_or_newline(map, selection.head())
10692 };
10693 selection.set_head(cursor, SelectionGoal::None);
10694 }
10695 });
10696 });
10697 this.insert("", window, cx);
10698 });
10699 }
10700
10701 pub fn delete_to_previous_subword_start(
10702 &mut self,
10703 _: &DeleteToPreviousSubwordStart,
10704 window: &mut Window,
10705 cx: &mut Context<Self>,
10706 ) {
10707 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10708 self.transact(window, cx, |this, window, cx| {
10709 this.select_autoclose_pair(window, cx);
10710 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10711 s.move_with(|map, selection| {
10712 if selection.is_empty() {
10713 let cursor = movement::previous_subword_start(map, selection.head());
10714 selection.set_head(cursor, SelectionGoal::None);
10715 }
10716 });
10717 });
10718 this.insert("", window, cx);
10719 });
10720 }
10721
10722 pub fn move_to_next_word_end(
10723 &mut self,
10724 _: &MoveToNextWordEnd,
10725 window: &mut Window,
10726 cx: &mut Context<Self>,
10727 ) {
10728 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10729 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10730 s.move_cursors_with(|map, head, _| {
10731 (movement::next_word_end(map, head), SelectionGoal::None)
10732 });
10733 })
10734 }
10735
10736 pub fn move_to_next_subword_end(
10737 &mut self,
10738 _: &MoveToNextSubwordEnd,
10739 window: &mut Window,
10740 cx: &mut Context<Self>,
10741 ) {
10742 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10743 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10744 s.move_cursors_with(|map, head, _| {
10745 (movement::next_subword_end(map, head), SelectionGoal::None)
10746 });
10747 })
10748 }
10749
10750 pub fn select_to_next_word_end(
10751 &mut self,
10752 _: &SelectToNextWordEnd,
10753 window: &mut Window,
10754 cx: &mut Context<Self>,
10755 ) {
10756 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10757 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10758 s.move_heads_with(|map, head, _| {
10759 (movement::next_word_end(map, head), SelectionGoal::None)
10760 });
10761 })
10762 }
10763
10764 pub fn select_to_next_subword_end(
10765 &mut self,
10766 _: &SelectToNextSubwordEnd,
10767 window: &mut Window,
10768 cx: &mut Context<Self>,
10769 ) {
10770 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10771 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10772 s.move_heads_with(|map, head, _| {
10773 (movement::next_subword_end(map, head), SelectionGoal::None)
10774 });
10775 })
10776 }
10777
10778 pub fn delete_to_next_word_end(
10779 &mut self,
10780 action: &DeleteToNextWordEnd,
10781 window: &mut Window,
10782 cx: &mut Context<Self>,
10783 ) {
10784 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10785 self.transact(window, cx, |this, window, cx| {
10786 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10787 s.move_with(|map, selection| {
10788 if selection.is_empty() {
10789 let cursor = if action.ignore_newlines {
10790 movement::next_word_end(map, selection.head())
10791 } else {
10792 movement::next_word_end_or_newline(map, selection.head())
10793 };
10794 selection.set_head(cursor, SelectionGoal::None);
10795 }
10796 });
10797 });
10798 this.insert("", window, cx);
10799 });
10800 }
10801
10802 pub fn delete_to_next_subword_end(
10803 &mut self,
10804 _: &DeleteToNextSubwordEnd,
10805 window: &mut Window,
10806 cx: &mut Context<Self>,
10807 ) {
10808 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10809 self.transact(window, cx, |this, window, cx| {
10810 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10811 s.move_with(|map, selection| {
10812 if selection.is_empty() {
10813 let cursor = movement::next_subword_end(map, selection.head());
10814 selection.set_head(cursor, SelectionGoal::None);
10815 }
10816 });
10817 });
10818 this.insert("", window, cx);
10819 });
10820 }
10821
10822 pub fn move_to_beginning_of_line(
10823 &mut self,
10824 action: &MoveToBeginningOfLine,
10825 window: &mut Window,
10826 cx: &mut Context<Self>,
10827 ) {
10828 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10829 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10830 s.move_cursors_with(|map, head, _| {
10831 (
10832 movement::indented_line_beginning(
10833 map,
10834 head,
10835 action.stop_at_soft_wraps,
10836 action.stop_at_indent,
10837 ),
10838 SelectionGoal::None,
10839 )
10840 });
10841 })
10842 }
10843
10844 pub fn select_to_beginning_of_line(
10845 &mut self,
10846 action: &SelectToBeginningOfLine,
10847 window: &mut Window,
10848 cx: &mut Context<Self>,
10849 ) {
10850 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10851 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10852 s.move_heads_with(|map, head, _| {
10853 (
10854 movement::indented_line_beginning(
10855 map,
10856 head,
10857 action.stop_at_soft_wraps,
10858 action.stop_at_indent,
10859 ),
10860 SelectionGoal::None,
10861 )
10862 });
10863 });
10864 }
10865
10866 pub fn delete_to_beginning_of_line(
10867 &mut self,
10868 action: &DeleteToBeginningOfLine,
10869 window: &mut Window,
10870 cx: &mut Context<Self>,
10871 ) {
10872 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10873 self.transact(window, cx, |this, window, cx| {
10874 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10875 s.move_with(|_, selection| {
10876 selection.reversed = true;
10877 });
10878 });
10879
10880 this.select_to_beginning_of_line(
10881 &SelectToBeginningOfLine {
10882 stop_at_soft_wraps: false,
10883 stop_at_indent: action.stop_at_indent,
10884 },
10885 window,
10886 cx,
10887 );
10888 this.backspace(&Backspace, window, cx);
10889 });
10890 }
10891
10892 pub fn move_to_end_of_line(
10893 &mut self,
10894 action: &MoveToEndOfLine,
10895 window: &mut Window,
10896 cx: &mut Context<Self>,
10897 ) {
10898 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10899 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10900 s.move_cursors_with(|map, head, _| {
10901 (
10902 movement::line_end(map, head, action.stop_at_soft_wraps),
10903 SelectionGoal::None,
10904 )
10905 });
10906 })
10907 }
10908
10909 pub fn select_to_end_of_line(
10910 &mut self,
10911 action: &SelectToEndOfLine,
10912 window: &mut Window,
10913 cx: &mut Context<Self>,
10914 ) {
10915 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10916 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10917 s.move_heads_with(|map, head, _| {
10918 (
10919 movement::line_end(map, head, action.stop_at_soft_wraps),
10920 SelectionGoal::None,
10921 )
10922 });
10923 })
10924 }
10925
10926 pub fn delete_to_end_of_line(
10927 &mut self,
10928 _: &DeleteToEndOfLine,
10929 window: &mut Window,
10930 cx: &mut Context<Self>,
10931 ) {
10932 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10933 self.transact(window, cx, |this, window, cx| {
10934 this.select_to_end_of_line(
10935 &SelectToEndOfLine {
10936 stop_at_soft_wraps: false,
10937 },
10938 window,
10939 cx,
10940 );
10941 this.delete(&Delete, window, cx);
10942 });
10943 }
10944
10945 pub fn cut_to_end_of_line(
10946 &mut self,
10947 _: &CutToEndOfLine,
10948 window: &mut Window,
10949 cx: &mut Context<Self>,
10950 ) {
10951 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10952 self.transact(window, cx, |this, window, cx| {
10953 this.select_to_end_of_line(
10954 &SelectToEndOfLine {
10955 stop_at_soft_wraps: false,
10956 },
10957 window,
10958 cx,
10959 );
10960 this.cut(&Cut, window, cx);
10961 });
10962 }
10963
10964 pub fn move_to_start_of_paragraph(
10965 &mut self,
10966 _: &MoveToStartOfParagraph,
10967 window: &mut Window,
10968 cx: &mut Context<Self>,
10969 ) {
10970 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10971 cx.propagate();
10972 return;
10973 }
10974 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10976 s.move_with(|map, selection| {
10977 selection.collapse_to(
10978 movement::start_of_paragraph(map, selection.head(), 1),
10979 SelectionGoal::None,
10980 )
10981 });
10982 })
10983 }
10984
10985 pub fn move_to_end_of_paragraph(
10986 &mut self,
10987 _: &MoveToEndOfParagraph,
10988 window: &mut Window,
10989 cx: &mut Context<Self>,
10990 ) {
10991 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10992 cx.propagate();
10993 return;
10994 }
10995 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10996 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10997 s.move_with(|map, selection| {
10998 selection.collapse_to(
10999 movement::end_of_paragraph(map, selection.head(), 1),
11000 SelectionGoal::None,
11001 )
11002 });
11003 })
11004 }
11005
11006 pub fn select_to_start_of_paragraph(
11007 &mut self,
11008 _: &SelectToStartOfParagraph,
11009 window: &mut Window,
11010 cx: &mut Context<Self>,
11011 ) {
11012 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11013 cx.propagate();
11014 return;
11015 }
11016 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11017 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11018 s.move_heads_with(|map, head, _| {
11019 (
11020 movement::start_of_paragraph(map, head, 1),
11021 SelectionGoal::None,
11022 )
11023 });
11024 })
11025 }
11026
11027 pub fn select_to_end_of_paragraph(
11028 &mut self,
11029 _: &SelectToEndOfParagraph,
11030 window: &mut Window,
11031 cx: &mut Context<Self>,
11032 ) {
11033 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11034 cx.propagate();
11035 return;
11036 }
11037 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11038 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11039 s.move_heads_with(|map, head, _| {
11040 (
11041 movement::end_of_paragraph(map, head, 1),
11042 SelectionGoal::None,
11043 )
11044 });
11045 })
11046 }
11047
11048 pub fn move_to_start_of_excerpt(
11049 &mut self,
11050 _: &MoveToStartOfExcerpt,
11051 window: &mut Window,
11052 cx: &mut Context<Self>,
11053 ) {
11054 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11055 cx.propagate();
11056 return;
11057 }
11058 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11059 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11060 s.move_with(|map, selection| {
11061 selection.collapse_to(
11062 movement::start_of_excerpt(
11063 map,
11064 selection.head(),
11065 workspace::searchable::Direction::Prev,
11066 ),
11067 SelectionGoal::None,
11068 )
11069 });
11070 })
11071 }
11072
11073 pub fn move_to_start_of_next_excerpt(
11074 &mut self,
11075 _: &MoveToStartOfNextExcerpt,
11076 window: &mut Window,
11077 cx: &mut Context<Self>,
11078 ) {
11079 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11080 cx.propagate();
11081 return;
11082 }
11083
11084 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11085 s.move_with(|map, selection| {
11086 selection.collapse_to(
11087 movement::start_of_excerpt(
11088 map,
11089 selection.head(),
11090 workspace::searchable::Direction::Next,
11091 ),
11092 SelectionGoal::None,
11093 )
11094 });
11095 })
11096 }
11097
11098 pub fn move_to_end_of_excerpt(
11099 &mut self,
11100 _: &MoveToEndOfExcerpt,
11101 window: &mut Window,
11102 cx: &mut Context<Self>,
11103 ) {
11104 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11105 cx.propagate();
11106 return;
11107 }
11108 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11109 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11110 s.move_with(|map, selection| {
11111 selection.collapse_to(
11112 movement::end_of_excerpt(
11113 map,
11114 selection.head(),
11115 workspace::searchable::Direction::Next,
11116 ),
11117 SelectionGoal::None,
11118 )
11119 });
11120 })
11121 }
11122
11123 pub fn move_to_end_of_previous_excerpt(
11124 &mut self,
11125 _: &MoveToEndOfPreviousExcerpt,
11126 window: &mut Window,
11127 cx: &mut Context<Self>,
11128 ) {
11129 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11130 cx.propagate();
11131 return;
11132 }
11133 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11134 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11135 s.move_with(|map, selection| {
11136 selection.collapse_to(
11137 movement::end_of_excerpt(
11138 map,
11139 selection.head(),
11140 workspace::searchable::Direction::Prev,
11141 ),
11142 SelectionGoal::None,
11143 )
11144 });
11145 })
11146 }
11147
11148 pub fn select_to_start_of_excerpt(
11149 &mut self,
11150 _: &SelectToStartOfExcerpt,
11151 window: &mut Window,
11152 cx: &mut Context<Self>,
11153 ) {
11154 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11155 cx.propagate();
11156 return;
11157 }
11158 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11159 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11160 s.move_heads_with(|map, head, _| {
11161 (
11162 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11163 SelectionGoal::None,
11164 )
11165 });
11166 })
11167 }
11168
11169 pub fn select_to_start_of_next_excerpt(
11170 &mut self,
11171 _: &SelectToStartOfNextExcerpt,
11172 window: &mut Window,
11173 cx: &mut Context<Self>,
11174 ) {
11175 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11176 cx.propagate();
11177 return;
11178 }
11179 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11180 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11181 s.move_heads_with(|map, head, _| {
11182 (
11183 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11184 SelectionGoal::None,
11185 )
11186 });
11187 })
11188 }
11189
11190 pub fn select_to_end_of_excerpt(
11191 &mut self,
11192 _: &SelectToEndOfExcerpt,
11193 window: &mut Window,
11194 cx: &mut Context<Self>,
11195 ) {
11196 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11197 cx.propagate();
11198 return;
11199 }
11200 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11201 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11202 s.move_heads_with(|map, head, _| {
11203 (
11204 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11205 SelectionGoal::None,
11206 )
11207 });
11208 })
11209 }
11210
11211 pub fn select_to_end_of_previous_excerpt(
11212 &mut self,
11213 _: &SelectToEndOfPreviousExcerpt,
11214 window: &mut Window,
11215 cx: &mut Context<Self>,
11216 ) {
11217 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11218 cx.propagate();
11219 return;
11220 }
11221 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11222 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11223 s.move_heads_with(|map, head, _| {
11224 (
11225 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11226 SelectionGoal::None,
11227 )
11228 });
11229 })
11230 }
11231
11232 pub fn move_to_beginning(
11233 &mut self,
11234 _: &MoveToBeginning,
11235 window: &mut Window,
11236 cx: &mut Context<Self>,
11237 ) {
11238 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11239 cx.propagate();
11240 return;
11241 }
11242 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11243 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11244 s.select_ranges(vec![0..0]);
11245 });
11246 }
11247
11248 pub fn select_to_beginning(
11249 &mut self,
11250 _: &SelectToBeginning,
11251 window: &mut Window,
11252 cx: &mut Context<Self>,
11253 ) {
11254 let mut selection = self.selections.last::<Point>(cx);
11255 selection.set_head(Point::zero(), SelectionGoal::None);
11256 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11257 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11258 s.select(vec![selection]);
11259 });
11260 }
11261
11262 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11263 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11264 cx.propagate();
11265 return;
11266 }
11267 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11268 let cursor = self.buffer.read(cx).read(cx).len();
11269 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11270 s.select_ranges(vec![cursor..cursor])
11271 });
11272 }
11273
11274 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11275 self.nav_history = nav_history;
11276 }
11277
11278 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11279 self.nav_history.as_ref()
11280 }
11281
11282 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11283 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11284 }
11285
11286 fn push_to_nav_history(
11287 &mut self,
11288 cursor_anchor: Anchor,
11289 new_position: Option<Point>,
11290 is_deactivate: bool,
11291 cx: &mut Context<Self>,
11292 ) {
11293 if let Some(nav_history) = self.nav_history.as_mut() {
11294 let buffer = self.buffer.read(cx).read(cx);
11295 let cursor_position = cursor_anchor.to_point(&buffer);
11296 let scroll_state = self.scroll_manager.anchor();
11297 let scroll_top_row = scroll_state.top_row(&buffer);
11298 drop(buffer);
11299
11300 if let Some(new_position) = new_position {
11301 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11302 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11303 return;
11304 }
11305 }
11306
11307 nav_history.push(
11308 Some(NavigationData {
11309 cursor_anchor,
11310 cursor_position,
11311 scroll_anchor: scroll_state,
11312 scroll_top_row,
11313 }),
11314 cx,
11315 );
11316 cx.emit(EditorEvent::PushedToNavHistory {
11317 anchor: cursor_anchor,
11318 is_deactivate,
11319 })
11320 }
11321 }
11322
11323 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11324 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11325 let buffer = self.buffer.read(cx).snapshot(cx);
11326 let mut selection = self.selections.first::<usize>(cx);
11327 selection.set_head(buffer.len(), SelectionGoal::None);
11328 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11329 s.select(vec![selection]);
11330 });
11331 }
11332
11333 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11334 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11335 let end = self.buffer.read(cx).read(cx).len();
11336 self.change_selections(None, window, cx, |s| {
11337 s.select_ranges(vec![0..end]);
11338 });
11339 }
11340
11341 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11342 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11343 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11344 let mut selections = self.selections.all::<Point>(cx);
11345 let max_point = display_map.buffer_snapshot.max_point();
11346 for selection in &mut selections {
11347 let rows = selection.spanned_rows(true, &display_map);
11348 selection.start = Point::new(rows.start.0, 0);
11349 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11350 selection.reversed = false;
11351 }
11352 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11353 s.select(selections);
11354 });
11355 }
11356
11357 pub fn split_selection_into_lines(
11358 &mut self,
11359 _: &SplitSelectionIntoLines,
11360 window: &mut Window,
11361 cx: &mut Context<Self>,
11362 ) {
11363 let selections = self
11364 .selections
11365 .all::<Point>(cx)
11366 .into_iter()
11367 .map(|selection| selection.start..selection.end)
11368 .collect::<Vec<_>>();
11369 self.unfold_ranges(&selections, true, true, cx);
11370
11371 let mut new_selection_ranges = Vec::new();
11372 {
11373 let buffer = self.buffer.read(cx).read(cx);
11374 for selection in selections {
11375 for row in selection.start.row..selection.end.row {
11376 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11377 new_selection_ranges.push(cursor..cursor);
11378 }
11379
11380 let is_multiline_selection = selection.start.row != selection.end.row;
11381 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11382 // so this action feels more ergonomic when paired with other selection operations
11383 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11384 if !should_skip_last {
11385 new_selection_ranges.push(selection.end..selection.end);
11386 }
11387 }
11388 }
11389 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11390 s.select_ranges(new_selection_ranges);
11391 });
11392 }
11393
11394 pub fn add_selection_above(
11395 &mut self,
11396 _: &AddSelectionAbove,
11397 window: &mut Window,
11398 cx: &mut Context<Self>,
11399 ) {
11400 self.add_selection(true, window, cx);
11401 }
11402
11403 pub fn add_selection_below(
11404 &mut self,
11405 _: &AddSelectionBelow,
11406 window: &mut Window,
11407 cx: &mut Context<Self>,
11408 ) {
11409 self.add_selection(false, window, cx);
11410 }
11411
11412 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11413 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11414
11415 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11416 let mut selections = self.selections.all::<Point>(cx);
11417 let text_layout_details = self.text_layout_details(window);
11418 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11419 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11420 let range = oldest_selection.display_range(&display_map).sorted();
11421
11422 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11423 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11424 let positions = start_x.min(end_x)..start_x.max(end_x);
11425
11426 selections.clear();
11427 let mut stack = Vec::new();
11428 for row in range.start.row().0..=range.end.row().0 {
11429 if let Some(selection) = self.selections.build_columnar_selection(
11430 &display_map,
11431 DisplayRow(row),
11432 &positions,
11433 oldest_selection.reversed,
11434 &text_layout_details,
11435 ) {
11436 stack.push(selection.id);
11437 selections.push(selection);
11438 }
11439 }
11440
11441 if above {
11442 stack.reverse();
11443 }
11444
11445 AddSelectionsState { above, stack }
11446 });
11447
11448 let last_added_selection = *state.stack.last().unwrap();
11449 let mut new_selections = Vec::new();
11450 if above == state.above {
11451 let end_row = if above {
11452 DisplayRow(0)
11453 } else {
11454 display_map.max_point().row()
11455 };
11456
11457 'outer: for selection in selections {
11458 if selection.id == last_added_selection {
11459 let range = selection.display_range(&display_map).sorted();
11460 debug_assert_eq!(range.start.row(), range.end.row());
11461 let mut row = range.start.row();
11462 let positions =
11463 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11464 px(start)..px(end)
11465 } else {
11466 let start_x =
11467 display_map.x_for_display_point(range.start, &text_layout_details);
11468 let end_x =
11469 display_map.x_for_display_point(range.end, &text_layout_details);
11470 start_x.min(end_x)..start_x.max(end_x)
11471 };
11472
11473 while row != end_row {
11474 if above {
11475 row.0 -= 1;
11476 } else {
11477 row.0 += 1;
11478 }
11479
11480 if let Some(new_selection) = self.selections.build_columnar_selection(
11481 &display_map,
11482 row,
11483 &positions,
11484 selection.reversed,
11485 &text_layout_details,
11486 ) {
11487 state.stack.push(new_selection.id);
11488 if above {
11489 new_selections.push(new_selection);
11490 new_selections.push(selection);
11491 } else {
11492 new_selections.push(selection);
11493 new_selections.push(new_selection);
11494 }
11495
11496 continue 'outer;
11497 }
11498 }
11499 }
11500
11501 new_selections.push(selection);
11502 }
11503 } else {
11504 new_selections = selections;
11505 new_selections.retain(|s| s.id != last_added_selection);
11506 state.stack.pop();
11507 }
11508
11509 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11510 s.select(new_selections);
11511 });
11512 if state.stack.len() > 1 {
11513 self.add_selections_state = Some(state);
11514 }
11515 }
11516
11517 pub fn select_next_match_internal(
11518 &mut self,
11519 display_map: &DisplaySnapshot,
11520 replace_newest: bool,
11521 autoscroll: Option<Autoscroll>,
11522 window: &mut Window,
11523 cx: &mut Context<Self>,
11524 ) -> Result<()> {
11525 fn select_next_match_ranges(
11526 this: &mut Editor,
11527 range: Range<usize>,
11528 replace_newest: bool,
11529 auto_scroll: Option<Autoscroll>,
11530 window: &mut Window,
11531 cx: &mut Context<Editor>,
11532 ) {
11533 this.unfold_ranges(&[range.clone()], false, true, cx);
11534 this.change_selections(auto_scroll, window, cx, |s| {
11535 if replace_newest {
11536 s.delete(s.newest_anchor().id);
11537 }
11538 s.insert_range(range.clone());
11539 });
11540 }
11541
11542 let buffer = &display_map.buffer_snapshot;
11543 let mut selections = self.selections.all::<usize>(cx);
11544 if let Some(mut select_next_state) = self.select_next_state.take() {
11545 let query = &select_next_state.query;
11546 if !select_next_state.done {
11547 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11548 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11549 let mut next_selected_range = None;
11550
11551 let bytes_after_last_selection =
11552 buffer.bytes_in_range(last_selection.end..buffer.len());
11553 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11554 let query_matches = query
11555 .stream_find_iter(bytes_after_last_selection)
11556 .map(|result| (last_selection.end, result))
11557 .chain(
11558 query
11559 .stream_find_iter(bytes_before_first_selection)
11560 .map(|result| (0, result)),
11561 );
11562
11563 for (start_offset, query_match) in query_matches {
11564 let query_match = query_match.unwrap(); // can only fail due to I/O
11565 let offset_range =
11566 start_offset + query_match.start()..start_offset + query_match.end();
11567 let display_range = offset_range.start.to_display_point(display_map)
11568 ..offset_range.end.to_display_point(display_map);
11569
11570 if !select_next_state.wordwise
11571 || (!movement::is_inside_word(display_map, display_range.start)
11572 && !movement::is_inside_word(display_map, display_range.end))
11573 {
11574 // TODO: This is n^2, because we might check all the selections
11575 if !selections
11576 .iter()
11577 .any(|selection| selection.range().overlaps(&offset_range))
11578 {
11579 next_selected_range = Some(offset_range);
11580 break;
11581 }
11582 }
11583 }
11584
11585 if let Some(next_selected_range) = next_selected_range {
11586 select_next_match_ranges(
11587 self,
11588 next_selected_range,
11589 replace_newest,
11590 autoscroll,
11591 window,
11592 cx,
11593 );
11594 } else {
11595 select_next_state.done = true;
11596 }
11597 }
11598
11599 self.select_next_state = Some(select_next_state);
11600 } else {
11601 let mut only_carets = true;
11602 let mut same_text_selected = true;
11603 let mut selected_text = None;
11604
11605 let mut selections_iter = selections.iter().peekable();
11606 while let Some(selection) = selections_iter.next() {
11607 if selection.start != selection.end {
11608 only_carets = false;
11609 }
11610
11611 if same_text_selected {
11612 if selected_text.is_none() {
11613 selected_text =
11614 Some(buffer.text_for_range(selection.range()).collect::<String>());
11615 }
11616
11617 if let Some(next_selection) = selections_iter.peek() {
11618 if next_selection.range().len() == selection.range().len() {
11619 let next_selected_text = buffer
11620 .text_for_range(next_selection.range())
11621 .collect::<String>();
11622 if Some(next_selected_text) != selected_text {
11623 same_text_selected = false;
11624 selected_text = None;
11625 }
11626 } else {
11627 same_text_selected = false;
11628 selected_text = None;
11629 }
11630 }
11631 }
11632 }
11633
11634 if only_carets {
11635 for selection in &mut selections {
11636 let word_range = movement::surrounding_word(
11637 display_map,
11638 selection.start.to_display_point(display_map),
11639 );
11640 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11641 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11642 selection.goal = SelectionGoal::None;
11643 selection.reversed = false;
11644 select_next_match_ranges(
11645 self,
11646 selection.start..selection.end,
11647 replace_newest,
11648 autoscroll,
11649 window,
11650 cx,
11651 );
11652 }
11653
11654 if selections.len() == 1 {
11655 let selection = selections
11656 .last()
11657 .expect("ensured that there's only one selection");
11658 let query = buffer
11659 .text_for_range(selection.start..selection.end)
11660 .collect::<String>();
11661 let is_empty = query.is_empty();
11662 let select_state = SelectNextState {
11663 query: AhoCorasick::new(&[query])?,
11664 wordwise: true,
11665 done: is_empty,
11666 };
11667 self.select_next_state = Some(select_state);
11668 } else {
11669 self.select_next_state = None;
11670 }
11671 } else if let Some(selected_text) = selected_text {
11672 self.select_next_state = Some(SelectNextState {
11673 query: AhoCorasick::new(&[selected_text])?,
11674 wordwise: false,
11675 done: false,
11676 });
11677 self.select_next_match_internal(
11678 display_map,
11679 replace_newest,
11680 autoscroll,
11681 window,
11682 cx,
11683 )?;
11684 }
11685 }
11686 Ok(())
11687 }
11688
11689 pub fn select_all_matches(
11690 &mut self,
11691 _action: &SelectAllMatches,
11692 window: &mut Window,
11693 cx: &mut Context<Self>,
11694 ) -> Result<()> {
11695 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11696
11697 self.push_to_selection_history();
11698 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11699
11700 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11701 let Some(select_next_state) = self.select_next_state.as_mut() else {
11702 return Ok(());
11703 };
11704 if select_next_state.done {
11705 return Ok(());
11706 }
11707
11708 let mut new_selections = self.selections.all::<usize>(cx);
11709
11710 let buffer = &display_map.buffer_snapshot;
11711 let query_matches = select_next_state
11712 .query
11713 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11714
11715 for query_match in query_matches {
11716 let query_match = query_match.unwrap(); // can only fail due to I/O
11717 let offset_range = query_match.start()..query_match.end();
11718 let display_range = offset_range.start.to_display_point(&display_map)
11719 ..offset_range.end.to_display_point(&display_map);
11720
11721 if !select_next_state.wordwise
11722 || (!movement::is_inside_word(&display_map, display_range.start)
11723 && !movement::is_inside_word(&display_map, display_range.end))
11724 {
11725 self.selections.change_with(cx, |selections| {
11726 new_selections.push(Selection {
11727 id: selections.new_selection_id(),
11728 start: offset_range.start,
11729 end: offset_range.end,
11730 reversed: false,
11731 goal: SelectionGoal::None,
11732 });
11733 });
11734 }
11735 }
11736
11737 new_selections.sort_by_key(|selection| selection.start);
11738 let mut ix = 0;
11739 while ix + 1 < new_selections.len() {
11740 let current_selection = &new_selections[ix];
11741 let next_selection = &new_selections[ix + 1];
11742 if current_selection.range().overlaps(&next_selection.range()) {
11743 if current_selection.id < next_selection.id {
11744 new_selections.remove(ix + 1);
11745 } else {
11746 new_selections.remove(ix);
11747 }
11748 } else {
11749 ix += 1;
11750 }
11751 }
11752
11753 let reversed = self.selections.oldest::<usize>(cx).reversed;
11754
11755 for selection in new_selections.iter_mut() {
11756 selection.reversed = reversed;
11757 }
11758
11759 select_next_state.done = true;
11760 self.unfold_ranges(
11761 &new_selections
11762 .iter()
11763 .map(|selection| selection.range())
11764 .collect::<Vec<_>>(),
11765 false,
11766 false,
11767 cx,
11768 );
11769 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11770 selections.select(new_selections)
11771 });
11772
11773 Ok(())
11774 }
11775
11776 pub fn select_next(
11777 &mut self,
11778 action: &SelectNext,
11779 window: &mut Window,
11780 cx: &mut Context<Self>,
11781 ) -> Result<()> {
11782 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11783 self.push_to_selection_history();
11784 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11785 self.select_next_match_internal(
11786 &display_map,
11787 action.replace_newest,
11788 Some(Autoscroll::newest()),
11789 window,
11790 cx,
11791 )?;
11792 Ok(())
11793 }
11794
11795 pub fn select_previous(
11796 &mut self,
11797 action: &SelectPrevious,
11798 window: &mut Window,
11799 cx: &mut Context<Self>,
11800 ) -> Result<()> {
11801 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11802 self.push_to_selection_history();
11803 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11804 let buffer = &display_map.buffer_snapshot;
11805 let mut selections = self.selections.all::<usize>(cx);
11806 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11807 let query = &select_prev_state.query;
11808 if !select_prev_state.done {
11809 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11810 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11811 let mut next_selected_range = None;
11812 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11813 let bytes_before_last_selection =
11814 buffer.reversed_bytes_in_range(0..last_selection.start);
11815 let bytes_after_first_selection =
11816 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11817 let query_matches = query
11818 .stream_find_iter(bytes_before_last_selection)
11819 .map(|result| (last_selection.start, result))
11820 .chain(
11821 query
11822 .stream_find_iter(bytes_after_first_selection)
11823 .map(|result| (buffer.len(), result)),
11824 );
11825 for (end_offset, query_match) in query_matches {
11826 let query_match = query_match.unwrap(); // can only fail due to I/O
11827 let offset_range =
11828 end_offset - query_match.end()..end_offset - query_match.start();
11829 let display_range = offset_range.start.to_display_point(&display_map)
11830 ..offset_range.end.to_display_point(&display_map);
11831
11832 if !select_prev_state.wordwise
11833 || (!movement::is_inside_word(&display_map, display_range.start)
11834 && !movement::is_inside_word(&display_map, display_range.end))
11835 {
11836 next_selected_range = Some(offset_range);
11837 break;
11838 }
11839 }
11840
11841 if let Some(next_selected_range) = next_selected_range {
11842 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11843 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11844 if action.replace_newest {
11845 s.delete(s.newest_anchor().id);
11846 }
11847 s.insert_range(next_selected_range);
11848 });
11849 } else {
11850 select_prev_state.done = true;
11851 }
11852 }
11853
11854 self.select_prev_state = Some(select_prev_state);
11855 } else {
11856 let mut only_carets = true;
11857 let mut same_text_selected = true;
11858 let mut selected_text = None;
11859
11860 let mut selections_iter = selections.iter().peekable();
11861 while let Some(selection) = selections_iter.next() {
11862 if selection.start != selection.end {
11863 only_carets = false;
11864 }
11865
11866 if same_text_selected {
11867 if selected_text.is_none() {
11868 selected_text =
11869 Some(buffer.text_for_range(selection.range()).collect::<String>());
11870 }
11871
11872 if let Some(next_selection) = selections_iter.peek() {
11873 if next_selection.range().len() == selection.range().len() {
11874 let next_selected_text = buffer
11875 .text_for_range(next_selection.range())
11876 .collect::<String>();
11877 if Some(next_selected_text) != selected_text {
11878 same_text_selected = false;
11879 selected_text = None;
11880 }
11881 } else {
11882 same_text_selected = false;
11883 selected_text = None;
11884 }
11885 }
11886 }
11887 }
11888
11889 if only_carets {
11890 for selection in &mut selections {
11891 let word_range = movement::surrounding_word(
11892 &display_map,
11893 selection.start.to_display_point(&display_map),
11894 );
11895 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11896 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11897 selection.goal = SelectionGoal::None;
11898 selection.reversed = false;
11899 }
11900 if selections.len() == 1 {
11901 let selection = selections
11902 .last()
11903 .expect("ensured that there's only one selection");
11904 let query = buffer
11905 .text_for_range(selection.start..selection.end)
11906 .collect::<String>();
11907 let is_empty = query.is_empty();
11908 let select_state = SelectNextState {
11909 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11910 wordwise: true,
11911 done: is_empty,
11912 };
11913 self.select_prev_state = Some(select_state);
11914 } else {
11915 self.select_prev_state = None;
11916 }
11917
11918 self.unfold_ranges(
11919 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11920 false,
11921 true,
11922 cx,
11923 );
11924 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11925 s.select(selections);
11926 });
11927 } else if let Some(selected_text) = selected_text {
11928 self.select_prev_state = Some(SelectNextState {
11929 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11930 wordwise: false,
11931 done: false,
11932 });
11933 self.select_previous(action, window, cx)?;
11934 }
11935 }
11936 Ok(())
11937 }
11938
11939 pub fn toggle_comments(
11940 &mut self,
11941 action: &ToggleComments,
11942 window: &mut Window,
11943 cx: &mut Context<Self>,
11944 ) {
11945 if self.read_only(cx) {
11946 return;
11947 }
11948 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11949 let text_layout_details = &self.text_layout_details(window);
11950 self.transact(window, cx, |this, window, cx| {
11951 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11952 let mut edits = Vec::new();
11953 let mut selection_edit_ranges = Vec::new();
11954 let mut last_toggled_row = None;
11955 let snapshot = this.buffer.read(cx).read(cx);
11956 let empty_str: Arc<str> = Arc::default();
11957 let mut suffixes_inserted = Vec::new();
11958 let ignore_indent = action.ignore_indent;
11959
11960 fn comment_prefix_range(
11961 snapshot: &MultiBufferSnapshot,
11962 row: MultiBufferRow,
11963 comment_prefix: &str,
11964 comment_prefix_whitespace: &str,
11965 ignore_indent: bool,
11966 ) -> Range<Point> {
11967 let indent_size = if ignore_indent {
11968 0
11969 } else {
11970 snapshot.indent_size_for_line(row).len
11971 };
11972
11973 let start = Point::new(row.0, indent_size);
11974
11975 let mut line_bytes = snapshot
11976 .bytes_in_range(start..snapshot.max_point())
11977 .flatten()
11978 .copied();
11979
11980 // If this line currently begins with the line comment prefix, then record
11981 // the range containing the prefix.
11982 if line_bytes
11983 .by_ref()
11984 .take(comment_prefix.len())
11985 .eq(comment_prefix.bytes())
11986 {
11987 // Include any whitespace that matches the comment prefix.
11988 let matching_whitespace_len = line_bytes
11989 .zip(comment_prefix_whitespace.bytes())
11990 .take_while(|(a, b)| a == b)
11991 .count() as u32;
11992 let end = Point::new(
11993 start.row,
11994 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11995 );
11996 start..end
11997 } else {
11998 start..start
11999 }
12000 }
12001
12002 fn comment_suffix_range(
12003 snapshot: &MultiBufferSnapshot,
12004 row: MultiBufferRow,
12005 comment_suffix: &str,
12006 comment_suffix_has_leading_space: bool,
12007 ) -> Range<Point> {
12008 let end = Point::new(row.0, snapshot.line_len(row));
12009 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12010
12011 let mut line_end_bytes = snapshot
12012 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12013 .flatten()
12014 .copied();
12015
12016 let leading_space_len = if suffix_start_column > 0
12017 && line_end_bytes.next() == Some(b' ')
12018 && comment_suffix_has_leading_space
12019 {
12020 1
12021 } else {
12022 0
12023 };
12024
12025 // If this line currently begins with the line comment prefix, then record
12026 // the range containing the prefix.
12027 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12028 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12029 start..end
12030 } else {
12031 end..end
12032 }
12033 }
12034
12035 // TODO: Handle selections that cross excerpts
12036 for selection in &mut selections {
12037 let start_column = snapshot
12038 .indent_size_for_line(MultiBufferRow(selection.start.row))
12039 .len;
12040 let language = if let Some(language) =
12041 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12042 {
12043 language
12044 } else {
12045 continue;
12046 };
12047
12048 selection_edit_ranges.clear();
12049
12050 // If multiple selections contain a given row, avoid processing that
12051 // row more than once.
12052 let mut start_row = MultiBufferRow(selection.start.row);
12053 if last_toggled_row == Some(start_row) {
12054 start_row = start_row.next_row();
12055 }
12056 let end_row =
12057 if selection.end.row > selection.start.row && selection.end.column == 0 {
12058 MultiBufferRow(selection.end.row - 1)
12059 } else {
12060 MultiBufferRow(selection.end.row)
12061 };
12062 last_toggled_row = Some(end_row);
12063
12064 if start_row > end_row {
12065 continue;
12066 }
12067
12068 // If the language has line comments, toggle those.
12069 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12070
12071 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12072 if ignore_indent {
12073 full_comment_prefixes = full_comment_prefixes
12074 .into_iter()
12075 .map(|s| Arc::from(s.trim_end()))
12076 .collect();
12077 }
12078
12079 if !full_comment_prefixes.is_empty() {
12080 let first_prefix = full_comment_prefixes
12081 .first()
12082 .expect("prefixes is non-empty");
12083 let prefix_trimmed_lengths = full_comment_prefixes
12084 .iter()
12085 .map(|p| p.trim_end_matches(' ').len())
12086 .collect::<SmallVec<[usize; 4]>>();
12087
12088 let mut all_selection_lines_are_comments = true;
12089
12090 for row in start_row.0..=end_row.0 {
12091 let row = MultiBufferRow(row);
12092 if start_row < end_row && snapshot.is_line_blank(row) {
12093 continue;
12094 }
12095
12096 let prefix_range = full_comment_prefixes
12097 .iter()
12098 .zip(prefix_trimmed_lengths.iter().copied())
12099 .map(|(prefix, trimmed_prefix_len)| {
12100 comment_prefix_range(
12101 snapshot.deref(),
12102 row,
12103 &prefix[..trimmed_prefix_len],
12104 &prefix[trimmed_prefix_len..],
12105 ignore_indent,
12106 )
12107 })
12108 .max_by_key(|range| range.end.column - range.start.column)
12109 .expect("prefixes is non-empty");
12110
12111 if prefix_range.is_empty() {
12112 all_selection_lines_are_comments = false;
12113 }
12114
12115 selection_edit_ranges.push(prefix_range);
12116 }
12117
12118 if all_selection_lines_are_comments {
12119 edits.extend(
12120 selection_edit_ranges
12121 .iter()
12122 .cloned()
12123 .map(|range| (range, empty_str.clone())),
12124 );
12125 } else {
12126 let min_column = selection_edit_ranges
12127 .iter()
12128 .map(|range| range.start.column)
12129 .min()
12130 .unwrap_or(0);
12131 edits.extend(selection_edit_ranges.iter().map(|range| {
12132 let position = Point::new(range.start.row, min_column);
12133 (position..position, first_prefix.clone())
12134 }));
12135 }
12136 } else if let Some((full_comment_prefix, comment_suffix)) =
12137 language.block_comment_delimiters()
12138 {
12139 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12140 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12141 let prefix_range = comment_prefix_range(
12142 snapshot.deref(),
12143 start_row,
12144 comment_prefix,
12145 comment_prefix_whitespace,
12146 ignore_indent,
12147 );
12148 let suffix_range = comment_suffix_range(
12149 snapshot.deref(),
12150 end_row,
12151 comment_suffix.trim_start_matches(' '),
12152 comment_suffix.starts_with(' '),
12153 );
12154
12155 if prefix_range.is_empty() || suffix_range.is_empty() {
12156 edits.push((
12157 prefix_range.start..prefix_range.start,
12158 full_comment_prefix.clone(),
12159 ));
12160 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12161 suffixes_inserted.push((end_row, comment_suffix.len()));
12162 } else {
12163 edits.push((prefix_range, empty_str.clone()));
12164 edits.push((suffix_range, empty_str.clone()));
12165 }
12166 } else {
12167 continue;
12168 }
12169 }
12170
12171 drop(snapshot);
12172 this.buffer.update(cx, |buffer, cx| {
12173 buffer.edit(edits, None, cx);
12174 });
12175
12176 // Adjust selections so that they end before any comment suffixes that
12177 // were inserted.
12178 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12179 let mut selections = this.selections.all::<Point>(cx);
12180 let snapshot = this.buffer.read(cx).read(cx);
12181 for selection in &mut selections {
12182 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12183 match row.cmp(&MultiBufferRow(selection.end.row)) {
12184 Ordering::Less => {
12185 suffixes_inserted.next();
12186 continue;
12187 }
12188 Ordering::Greater => break,
12189 Ordering::Equal => {
12190 if selection.end.column == snapshot.line_len(row) {
12191 if selection.is_empty() {
12192 selection.start.column -= suffix_len as u32;
12193 }
12194 selection.end.column -= suffix_len as u32;
12195 }
12196 break;
12197 }
12198 }
12199 }
12200 }
12201
12202 drop(snapshot);
12203 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12204 s.select(selections)
12205 });
12206
12207 let selections = this.selections.all::<Point>(cx);
12208 let selections_on_single_row = selections.windows(2).all(|selections| {
12209 selections[0].start.row == selections[1].start.row
12210 && selections[0].end.row == selections[1].end.row
12211 && selections[0].start.row == selections[0].end.row
12212 });
12213 let selections_selecting = selections
12214 .iter()
12215 .any(|selection| selection.start != selection.end);
12216 let advance_downwards = action.advance_downwards
12217 && selections_on_single_row
12218 && !selections_selecting
12219 && !matches!(this.mode, EditorMode::SingleLine { .. });
12220
12221 if advance_downwards {
12222 let snapshot = this.buffer.read(cx).snapshot(cx);
12223
12224 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12225 s.move_cursors_with(|display_snapshot, display_point, _| {
12226 let mut point = display_point.to_point(display_snapshot);
12227 point.row += 1;
12228 point = snapshot.clip_point(point, Bias::Left);
12229 let display_point = point.to_display_point(display_snapshot);
12230 let goal = SelectionGoal::HorizontalPosition(
12231 display_snapshot
12232 .x_for_display_point(display_point, text_layout_details)
12233 .into(),
12234 );
12235 (display_point, goal)
12236 })
12237 });
12238 }
12239 });
12240 }
12241
12242 pub fn select_enclosing_symbol(
12243 &mut self,
12244 _: &SelectEnclosingSymbol,
12245 window: &mut Window,
12246 cx: &mut Context<Self>,
12247 ) {
12248 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12249
12250 let buffer = self.buffer.read(cx).snapshot(cx);
12251 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12252
12253 fn update_selection(
12254 selection: &Selection<usize>,
12255 buffer_snap: &MultiBufferSnapshot,
12256 ) -> Option<Selection<usize>> {
12257 let cursor = selection.head();
12258 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12259 for symbol in symbols.iter().rev() {
12260 let start = symbol.range.start.to_offset(buffer_snap);
12261 let end = symbol.range.end.to_offset(buffer_snap);
12262 let new_range = start..end;
12263 if start < selection.start || end > selection.end {
12264 return Some(Selection {
12265 id: selection.id,
12266 start: new_range.start,
12267 end: new_range.end,
12268 goal: SelectionGoal::None,
12269 reversed: selection.reversed,
12270 });
12271 }
12272 }
12273 None
12274 }
12275
12276 let mut selected_larger_symbol = false;
12277 let new_selections = old_selections
12278 .iter()
12279 .map(|selection| match update_selection(selection, &buffer) {
12280 Some(new_selection) => {
12281 if new_selection.range() != selection.range() {
12282 selected_larger_symbol = true;
12283 }
12284 new_selection
12285 }
12286 None => selection.clone(),
12287 })
12288 .collect::<Vec<_>>();
12289
12290 if selected_larger_symbol {
12291 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12292 s.select(new_selections);
12293 });
12294 }
12295 }
12296
12297 pub fn select_larger_syntax_node(
12298 &mut self,
12299 _: &SelectLargerSyntaxNode,
12300 window: &mut Window,
12301 cx: &mut Context<Self>,
12302 ) {
12303 let Some(visible_row_count) = self.visible_row_count() else {
12304 return;
12305 };
12306 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12307 if old_selections.is_empty() {
12308 return;
12309 }
12310
12311 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12312
12313 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12314 let buffer = self.buffer.read(cx).snapshot(cx);
12315
12316 let mut selected_larger_node = false;
12317 let mut new_selections = old_selections
12318 .iter()
12319 .map(|selection| {
12320 let old_range = selection.start..selection.end;
12321 let mut new_range = old_range.clone();
12322 let mut new_node = None;
12323 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12324 {
12325 new_node = Some(node);
12326 new_range = match containing_range {
12327 MultiOrSingleBufferOffsetRange::Single(_) => break,
12328 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12329 };
12330 if !display_map.intersects_fold(new_range.start)
12331 && !display_map.intersects_fold(new_range.end)
12332 {
12333 break;
12334 }
12335 }
12336
12337 if let Some(node) = new_node {
12338 // Log the ancestor, to support using this action as a way to explore TreeSitter
12339 // nodes. Parent and grandparent are also logged because this operation will not
12340 // visit nodes that have the same range as their parent.
12341 log::info!("Node: {node:?}");
12342 let parent = node.parent();
12343 log::info!("Parent: {parent:?}");
12344 let grandparent = parent.and_then(|x| x.parent());
12345 log::info!("Grandparent: {grandparent:?}");
12346 }
12347
12348 selected_larger_node |= new_range != old_range;
12349 Selection {
12350 id: selection.id,
12351 start: new_range.start,
12352 end: new_range.end,
12353 goal: SelectionGoal::None,
12354 reversed: selection.reversed,
12355 }
12356 })
12357 .collect::<Vec<_>>();
12358
12359 if !selected_larger_node {
12360 return; // don't put this call in the history
12361 }
12362
12363 // scroll based on transformation done to the last selection created by the user
12364 let (last_old, last_new) = old_selections
12365 .last()
12366 .zip(new_selections.last().cloned())
12367 .expect("old_selections isn't empty");
12368
12369 // revert selection
12370 let is_selection_reversed = {
12371 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12372 new_selections.last_mut().expect("checked above").reversed =
12373 should_newest_selection_be_reversed;
12374 should_newest_selection_be_reversed
12375 };
12376
12377 if selected_larger_node {
12378 self.select_syntax_node_history.disable_clearing = true;
12379 self.change_selections(None, window, cx, |s| {
12380 s.select(new_selections.clone());
12381 });
12382 self.select_syntax_node_history.disable_clearing = false;
12383 }
12384
12385 let start_row = last_new.start.to_display_point(&display_map).row().0;
12386 let end_row = last_new.end.to_display_point(&display_map).row().0;
12387 let selection_height = end_row - start_row + 1;
12388 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12389
12390 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12391 let scroll_behavior = if fits_on_the_screen {
12392 self.request_autoscroll(Autoscroll::fit(), cx);
12393 SelectSyntaxNodeScrollBehavior::FitSelection
12394 } else if is_selection_reversed {
12395 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12396 SelectSyntaxNodeScrollBehavior::CursorTop
12397 } else {
12398 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12399 SelectSyntaxNodeScrollBehavior::CursorBottom
12400 };
12401
12402 self.select_syntax_node_history.push((
12403 old_selections,
12404 scroll_behavior,
12405 is_selection_reversed,
12406 ));
12407 }
12408
12409 pub fn select_smaller_syntax_node(
12410 &mut self,
12411 _: &SelectSmallerSyntaxNode,
12412 window: &mut Window,
12413 cx: &mut Context<Self>,
12414 ) {
12415 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12416
12417 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12418 self.select_syntax_node_history.pop()
12419 {
12420 if let Some(selection) = selections.last_mut() {
12421 selection.reversed = is_selection_reversed;
12422 }
12423
12424 self.select_syntax_node_history.disable_clearing = true;
12425 self.change_selections(None, window, cx, |s| {
12426 s.select(selections.to_vec());
12427 });
12428 self.select_syntax_node_history.disable_clearing = false;
12429
12430 match scroll_behavior {
12431 SelectSyntaxNodeScrollBehavior::CursorTop => {
12432 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12433 }
12434 SelectSyntaxNodeScrollBehavior::FitSelection => {
12435 self.request_autoscroll(Autoscroll::fit(), cx);
12436 }
12437 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12438 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12439 }
12440 }
12441 }
12442 }
12443
12444 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12445 if !EditorSettings::get_global(cx).gutter.runnables {
12446 self.clear_tasks();
12447 return Task::ready(());
12448 }
12449 let project = self.project.as_ref().map(Entity::downgrade);
12450 cx.spawn_in(window, async move |this, cx| {
12451 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12452 let Some(project) = project.and_then(|p| p.upgrade()) else {
12453 return;
12454 };
12455 let Ok(display_snapshot) = this.update(cx, |this, cx| {
12456 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12457 }) else {
12458 return;
12459 };
12460
12461 let hide_runnables = project
12462 .update(cx, |project, cx| {
12463 // Do not display any test indicators in non-dev server remote projects.
12464 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12465 })
12466 .unwrap_or(true);
12467 if hide_runnables {
12468 return;
12469 }
12470 let new_rows =
12471 cx.background_spawn({
12472 let snapshot = display_snapshot.clone();
12473 async move {
12474 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12475 }
12476 })
12477 .await;
12478
12479 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12480 this.update(cx, |this, _| {
12481 this.clear_tasks();
12482 for (key, value) in rows {
12483 this.insert_tasks(key, value);
12484 }
12485 })
12486 .ok();
12487 })
12488 }
12489 fn fetch_runnable_ranges(
12490 snapshot: &DisplaySnapshot,
12491 range: Range<Anchor>,
12492 ) -> Vec<language::RunnableRange> {
12493 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12494 }
12495
12496 fn runnable_rows(
12497 project: Entity<Project>,
12498 snapshot: DisplaySnapshot,
12499 runnable_ranges: Vec<RunnableRange>,
12500 mut cx: AsyncWindowContext,
12501 ) -> Vec<((BufferId, u32), RunnableTasks)> {
12502 runnable_ranges
12503 .into_iter()
12504 .filter_map(|mut runnable| {
12505 let tasks = cx
12506 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12507 .ok()?;
12508 if tasks.is_empty() {
12509 return None;
12510 }
12511
12512 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12513
12514 let row = snapshot
12515 .buffer_snapshot
12516 .buffer_line_for_row(MultiBufferRow(point.row))?
12517 .1
12518 .start
12519 .row;
12520
12521 let context_range =
12522 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12523 Some((
12524 (runnable.buffer_id, row),
12525 RunnableTasks {
12526 templates: tasks,
12527 offset: snapshot
12528 .buffer_snapshot
12529 .anchor_before(runnable.run_range.start),
12530 context_range,
12531 column: point.column,
12532 extra_variables: runnable.extra_captures,
12533 },
12534 ))
12535 })
12536 .collect()
12537 }
12538
12539 fn templates_with_tags(
12540 project: &Entity<Project>,
12541 runnable: &mut Runnable,
12542 cx: &mut App,
12543 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12544 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12545 let (worktree_id, file) = project
12546 .buffer_for_id(runnable.buffer, cx)
12547 .and_then(|buffer| buffer.read(cx).file())
12548 .map(|file| (file.worktree_id(cx), file.clone()))
12549 .unzip();
12550
12551 (
12552 project.task_store().read(cx).task_inventory().cloned(),
12553 worktree_id,
12554 file,
12555 )
12556 });
12557
12558 let tags = mem::take(&mut runnable.tags);
12559 let mut tags: Vec<_> = tags
12560 .into_iter()
12561 .flat_map(|tag| {
12562 let tag = tag.0.clone();
12563 inventory
12564 .as_ref()
12565 .into_iter()
12566 .flat_map(|inventory| {
12567 inventory.read(cx).list_tasks(
12568 file.clone(),
12569 Some(runnable.language.clone()),
12570 worktree_id,
12571 cx,
12572 )
12573 })
12574 .filter(move |(_, template)| {
12575 template.tags.iter().any(|source_tag| source_tag == &tag)
12576 })
12577 })
12578 .sorted_by_key(|(kind, _)| kind.to_owned())
12579 .collect();
12580 if let Some((leading_tag_source, _)) = tags.first() {
12581 // Strongest source wins; if we have worktree tag binding, prefer that to
12582 // global and language bindings;
12583 // if we have a global binding, prefer that to language binding.
12584 let first_mismatch = tags
12585 .iter()
12586 .position(|(tag_source, _)| tag_source != leading_tag_source);
12587 if let Some(index) = first_mismatch {
12588 tags.truncate(index);
12589 }
12590 }
12591
12592 tags
12593 }
12594
12595 pub fn move_to_enclosing_bracket(
12596 &mut self,
12597 _: &MoveToEnclosingBracket,
12598 window: &mut Window,
12599 cx: &mut Context<Self>,
12600 ) {
12601 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12602 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12603 s.move_offsets_with(|snapshot, selection| {
12604 let Some(enclosing_bracket_ranges) =
12605 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12606 else {
12607 return;
12608 };
12609
12610 let mut best_length = usize::MAX;
12611 let mut best_inside = false;
12612 let mut best_in_bracket_range = false;
12613 let mut best_destination = None;
12614 for (open, close) in enclosing_bracket_ranges {
12615 let close = close.to_inclusive();
12616 let length = close.end() - open.start;
12617 let inside = selection.start >= open.end && selection.end <= *close.start();
12618 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12619 || close.contains(&selection.head());
12620
12621 // If best is next to a bracket and current isn't, skip
12622 if !in_bracket_range && best_in_bracket_range {
12623 continue;
12624 }
12625
12626 // Prefer smaller lengths unless best is inside and current isn't
12627 if length > best_length && (best_inside || !inside) {
12628 continue;
12629 }
12630
12631 best_length = length;
12632 best_inside = inside;
12633 best_in_bracket_range = in_bracket_range;
12634 best_destination = Some(
12635 if close.contains(&selection.start) && close.contains(&selection.end) {
12636 if inside { open.end } else { open.start }
12637 } else if inside {
12638 *close.start()
12639 } else {
12640 *close.end()
12641 },
12642 );
12643 }
12644
12645 if let Some(destination) = best_destination {
12646 selection.collapse_to(destination, SelectionGoal::None);
12647 }
12648 })
12649 });
12650 }
12651
12652 pub fn undo_selection(
12653 &mut self,
12654 _: &UndoSelection,
12655 window: &mut Window,
12656 cx: &mut Context<Self>,
12657 ) {
12658 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12659 self.end_selection(window, cx);
12660 self.selection_history.mode = SelectionHistoryMode::Undoing;
12661 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12662 self.change_selections(None, window, cx, |s| {
12663 s.select_anchors(entry.selections.to_vec())
12664 });
12665 self.select_next_state = entry.select_next_state;
12666 self.select_prev_state = entry.select_prev_state;
12667 self.add_selections_state = entry.add_selections_state;
12668 self.request_autoscroll(Autoscroll::newest(), cx);
12669 }
12670 self.selection_history.mode = SelectionHistoryMode::Normal;
12671 }
12672
12673 pub fn redo_selection(
12674 &mut self,
12675 _: &RedoSelection,
12676 window: &mut Window,
12677 cx: &mut Context<Self>,
12678 ) {
12679 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12680 self.end_selection(window, cx);
12681 self.selection_history.mode = SelectionHistoryMode::Redoing;
12682 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12683 self.change_selections(None, window, cx, |s| {
12684 s.select_anchors(entry.selections.to_vec())
12685 });
12686 self.select_next_state = entry.select_next_state;
12687 self.select_prev_state = entry.select_prev_state;
12688 self.add_selections_state = entry.add_selections_state;
12689 self.request_autoscroll(Autoscroll::newest(), cx);
12690 }
12691 self.selection_history.mode = SelectionHistoryMode::Normal;
12692 }
12693
12694 pub fn expand_excerpts(
12695 &mut self,
12696 action: &ExpandExcerpts,
12697 _: &mut Window,
12698 cx: &mut Context<Self>,
12699 ) {
12700 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12701 }
12702
12703 pub fn expand_excerpts_down(
12704 &mut self,
12705 action: &ExpandExcerptsDown,
12706 _: &mut Window,
12707 cx: &mut Context<Self>,
12708 ) {
12709 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12710 }
12711
12712 pub fn expand_excerpts_up(
12713 &mut self,
12714 action: &ExpandExcerptsUp,
12715 _: &mut Window,
12716 cx: &mut Context<Self>,
12717 ) {
12718 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12719 }
12720
12721 pub fn expand_excerpts_for_direction(
12722 &mut self,
12723 lines: u32,
12724 direction: ExpandExcerptDirection,
12725
12726 cx: &mut Context<Self>,
12727 ) {
12728 let selections = self.selections.disjoint_anchors();
12729
12730 let lines = if lines == 0 {
12731 EditorSettings::get_global(cx).expand_excerpt_lines
12732 } else {
12733 lines
12734 };
12735
12736 self.buffer.update(cx, |buffer, cx| {
12737 let snapshot = buffer.snapshot(cx);
12738 let mut excerpt_ids = selections
12739 .iter()
12740 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12741 .collect::<Vec<_>>();
12742 excerpt_ids.sort();
12743 excerpt_ids.dedup();
12744 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12745 })
12746 }
12747
12748 pub fn expand_excerpt(
12749 &mut self,
12750 excerpt: ExcerptId,
12751 direction: ExpandExcerptDirection,
12752 window: &mut Window,
12753 cx: &mut Context<Self>,
12754 ) {
12755 let current_scroll_position = self.scroll_position(cx);
12756 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
12757 let mut should_scroll_up = false;
12758
12759 if direction == ExpandExcerptDirection::Down {
12760 let multi_buffer = self.buffer.read(cx);
12761 let snapshot = multi_buffer.snapshot(cx);
12762 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
12763 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12764 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
12765 let buffer_snapshot = buffer.read(cx).snapshot();
12766 let excerpt_end_row =
12767 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
12768 let last_row = buffer_snapshot.max_point().row;
12769 let lines_below = last_row.saturating_sub(excerpt_end_row);
12770 should_scroll_up = lines_below >= lines_to_expand;
12771 }
12772 }
12773 }
12774 }
12775
12776 self.buffer.update(cx, |buffer, cx| {
12777 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
12778 });
12779
12780 if should_scroll_up {
12781 let new_scroll_position =
12782 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
12783 self.set_scroll_position(new_scroll_position, window, cx);
12784 }
12785 }
12786
12787 pub fn go_to_singleton_buffer_point(
12788 &mut self,
12789 point: Point,
12790 window: &mut Window,
12791 cx: &mut Context<Self>,
12792 ) {
12793 self.go_to_singleton_buffer_range(point..point, window, cx);
12794 }
12795
12796 pub fn go_to_singleton_buffer_range(
12797 &mut self,
12798 range: Range<Point>,
12799 window: &mut Window,
12800 cx: &mut Context<Self>,
12801 ) {
12802 let multibuffer = self.buffer().read(cx);
12803 let Some(buffer) = multibuffer.as_singleton() else {
12804 return;
12805 };
12806 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12807 return;
12808 };
12809 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12810 return;
12811 };
12812 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12813 s.select_anchor_ranges([start..end])
12814 });
12815 }
12816
12817 fn go_to_diagnostic(
12818 &mut self,
12819 _: &GoToDiagnostic,
12820 window: &mut Window,
12821 cx: &mut Context<Self>,
12822 ) {
12823 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12824 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12825 }
12826
12827 fn go_to_prev_diagnostic(
12828 &mut self,
12829 _: &GoToPreviousDiagnostic,
12830 window: &mut Window,
12831 cx: &mut Context<Self>,
12832 ) {
12833 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12834 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12835 }
12836
12837 pub fn go_to_diagnostic_impl(
12838 &mut self,
12839 direction: Direction,
12840 window: &mut Window,
12841 cx: &mut Context<Self>,
12842 ) {
12843 let buffer = self.buffer.read(cx).snapshot(cx);
12844 let selection = self.selections.newest::<usize>(cx);
12845 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12846 if direction == Direction::Next {
12847 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12848 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12849 return;
12850 };
12851 self.activate_diagnostics(
12852 buffer_id,
12853 popover.local_diagnostic.diagnostic.group_id,
12854 window,
12855 cx,
12856 );
12857 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12858 let primary_range_start = active_diagnostics.primary_range.start;
12859 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12860 let mut new_selection = s.newest_anchor().clone();
12861 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12862 s.select_anchors(vec![new_selection.clone()]);
12863 });
12864 self.refresh_inline_completion(false, true, window, cx);
12865 }
12866 return;
12867 }
12868 }
12869
12870 let active_group_id = self
12871 .active_diagnostics
12872 .as_ref()
12873 .map(|active_group| active_group.group_id);
12874 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12875 active_diagnostics
12876 .primary_range
12877 .to_offset(&buffer)
12878 .to_inclusive()
12879 });
12880 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12881 if active_primary_range.contains(&selection.head()) {
12882 *active_primary_range.start()
12883 } else {
12884 selection.head()
12885 }
12886 } else {
12887 selection.head()
12888 };
12889
12890 let snapshot = self.snapshot(window, cx);
12891 let primary_diagnostics_before = buffer
12892 .diagnostics_in_range::<usize>(0..search_start)
12893 .filter(|entry| entry.diagnostic.is_primary)
12894 .filter(|entry| entry.range.start != entry.range.end)
12895 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12896 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12897 .collect::<Vec<_>>();
12898 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12899 primary_diagnostics_before
12900 .iter()
12901 .position(|entry| entry.diagnostic.group_id == active_group_id)
12902 });
12903
12904 let primary_diagnostics_after = buffer
12905 .diagnostics_in_range::<usize>(search_start..buffer.len())
12906 .filter(|entry| entry.diagnostic.is_primary)
12907 .filter(|entry| entry.range.start != entry.range.end)
12908 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12909 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12910 .collect::<Vec<_>>();
12911 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12912 primary_diagnostics_after
12913 .iter()
12914 .enumerate()
12915 .rev()
12916 .find_map(|(i, entry)| {
12917 if entry.diagnostic.group_id == active_group_id {
12918 Some(i)
12919 } else {
12920 None
12921 }
12922 })
12923 });
12924
12925 let next_primary_diagnostic = match direction {
12926 Direction::Prev => primary_diagnostics_before
12927 .iter()
12928 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12929 .rev()
12930 .next(),
12931 Direction::Next => primary_diagnostics_after
12932 .iter()
12933 .skip(
12934 last_same_group_diagnostic_after
12935 .map(|index| index + 1)
12936 .unwrap_or(0),
12937 )
12938 .next(),
12939 };
12940
12941 // Cycle around to the start of the buffer, potentially moving back to the start of
12942 // the currently active diagnostic.
12943 let cycle_around = || match direction {
12944 Direction::Prev => primary_diagnostics_after
12945 .iter()
12946 .rev()
12947 .chain(primary_diagnostics_before.iter().rev())
12948 .next(),
12949 Direction::Next => primary_diagnostics_before
12950 .iter()
12951 .chain(primary_diagnostics_after.iter())
12952 .next(),
12953 };
12954
12955 if let Some((primary_range, group_id)) = next_primary_diagnostic
12956 .or_else(cycle_around)
12957 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12958 {
12959 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12960 return;
12961 };
12962 self.activate_diagnostics(buffer_id, group_id, window, cx);
12963 if self.active_diagnostics.is_some() {
12964 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12965 s.select(vec![Selection {
12966 id: selection.id,
12967 start: primary_range.start,
12968 end: primary_range.start,
12969 reversed: false,
12970 goal: SelectionGoal::None,
12971 }]);
12972 });
12973 self.refresh_inline_completion(false, true, window, cx);
12974 }
12975 }
12976 }
12977
12978 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12979 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12980 let snapshot = self.snapshot(window, cx);
12981 let selection = self.selections.newest::<Point>(cx);
12982 self.go_to_hunk_before_or_after_position(
12983 &snapshot,
12984 selection.head(),
12985 Direction::Next,
12986 window,
12987 cx,
12988 );
12989 }
12990
12991 pub fn go_to_hunk_before_or_after_position(
12992 &mut self,
12993 snapshot: &EditorSnapshot,
12994 position: Point,
12995 direction: Direction,
12996 window: &mut Window,
12997 cx: &mut Context<Editor>,
12998 ) {
12999 let row = if direction == Direction::Next {
13000 self.hunk_after_position(snapshot, position)
13001 .map(|hunk| hunk.row_range.start)
13002 } else {
13003 self.hunk_before_position(snapshot, position)
13004 };
13005
13006 if let Some(row) = row {
13007 let destination = Point::new(row.0, 0);
13008 let autoscroll = Autoscroll::center();
13009
13010 self.unfold_ranges(&[destination..destination], false, false, cx);
13011 self.change_selections(Some(autoscroll), window, cx, |s| {
13012 s.select_ranges([destination..destination]);
13013 });
13014 }
13015 }
13016
13017 fn hunk_after_position(
13018 &mut self,
13019 snapshot: &EditorSnapshot,
13020 position: Point,
13021 ) -> Option<MultiBufferDiffHunk> {
13022 snapshot
13023 .buffer_snapshot
13024 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13025 .find(|hunk| hunk.row_range.start.0 > position.row)
13026 .or_else(|| {
13027 snapshot
13028 .buffer_snapshot
13029 .diff_hunks_in_range(Point::zero()..position)
13030 .find(|hunk| hunk.row_range.end.0 < position.row)
13031 })
13032 }
13033
13034 fn go_to_prev_hunk(
13035 &mut self,
13036 _: &GoToPreviousHunk,
13037 window: &mut Window,
13038 cx: &mut Context<Self>,
13039 ) {
13040 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13041 let snapshot = self.snapshot(window, cx);
13042 let selection = self.selections.newest::<Point>(cx);
13043 self.go_to_hunk_before_or_after_position(
13044 &snapshot,
13045 selection.head(),
13046 Direction::Prev,
13047 window,
13048 cx,
13049 );
13050 }
13051
13052 fn hunk_before_position(
13053 &mut self,
13054 snapshot: &EditorSnapshot,
13055 position: Point,
13056 ) -> Option<MultiBufferRow> {
13057 snapshot
13058 .buffer_snapshot
13059 .diff_hunk_before(position)
13060 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13061 }
13062
13063 fn go_to_line<T: 'static>(
13064 &mut self,
13065 position: Anchor,
13066 highlight_color: Option<Hsla>,
13067 window: &mut Window,
13068 cx: &mut Context<Self>,
13069 ) {
13070 let snapshot = self.snapshot(window, cx).display_snapshot;
13071 let position = position.to_point(&snapshot.buffer_snapshot);
13072 let start = snapshot
13073 .buffer_snapshot
13074 .clip_point(Point::new(position.row, 0), Bias::Left);
13075 let end = start + Point::new(1, 0);
13076 let start = snapshot.buffer_snapshot.anchor_before(start);
13077 let end = snapshot.buffer_snapshot.anchor_before(end);
13078
13079 self.highlight_rows::<T>(
13080 start..end,
13081 highlight_color
13082 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13083 false,
13084 cx,
13085 );
13086 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13087 }
13088
13089 pub fn go_to_definition(
13090 &mut self,
13091 _: &GoToDefinition,
13092 window: &mut Window,
13093 cx: &mut Context<Self>,
13094 ) -> Task<Result<Navigated>> {
13095 let definition =
13096 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13097 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13098 cx.spawn_in(window, async move |editor, cx| {
13099 if definition.await? == Navigated::Yes {
13100 return Ok(Navigated::Yes);
13101 }
13102 match fallback_strategy {
13103 GoToDefinitionFallback::None => Ok(Navigated::No),
13104 GoToDefinitionFallback::FindAllReferences => {
13105 match editor.update_in(cx, |editor, window, cx| {
13106 editor.find_all_references(&FindAllReferences, window, cx)
13107 })? {
13108 Some(references) => references.await,
13109 None => Ok(Navigated::No),
13110 }
13111 }
13112 }
13113 })
13114 }
13115
13116 pub fn go_to_declaration(
13117 &mut self,
13118 _: &GoToDeclaration,
13119 window: &mut Window,
13120 cx: &mut Context<Self>,
13121 ) -> Task<Result<Navigated>> {
13122 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13123 }
13124
13125 pub fn go_to_declaration_split(
13126 &mut self,
13127 _: &GoToDeclaration,
13128 window: &mut Window,
13129 cx: &mut Context<Self>,
13130 ) -> Task<Result<Navigated>> {
13131 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13132 }
13133
13134 pub fn go_to_implementation(
13135 &mut self,
13136 _: &GoToImplementation,
13137 window: &mut Window,
13138 cx: &mut Context<Self>,
13139 ) -> Task<Result<Navigated>> {
13140 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13141 }
13142
13143 pub fn go_to_implementation_split(
13144 &mut self,
13145 _: &GoToImplementationSplit,
13146 window: &mut Window,
13147 cx: &mut Context<Self>,
13148 ) -> Task<Result<Navigated>> {
13149 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13150 }
13151
13152 pub fn go_to_type_definition(
13153 &mut self,
13154 _: &GoToTypeDefinition,
13155 window: &mut Window,
13156 cx: &mut Context<Self>,
13157 ) -> Task<Result<Navigated>> {
13158 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13159 }
13160
13161 pub fn go_to_definition_split(
13162 &mut self,
13163 _: &GoToDefinitionSplit,
13164 window: &mut Window,
13165 cx: &mut Context<Self>,
13166 ) -> Task<Result<Navigated>> {
13167 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13168 }
13169
13170 pub fn go_to_type_definition_split(
13171 &mut self,
13172 _: &GoToTypeDefinitionSplit,
13173 window: &mut Window,
13174 cx: &mut Context<Self>,
13175 ) -> Task<Result<Navigated>> {
13176 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13177 }
13178
13179 fn go_to_definition_of_kind(
13180 &mut self,
13181 kind: GotoDefinitionKind,
13182 split: bool,
13183 window: &mut Window,
13184 cx: &mut Context<Self>,
13185 ) -> Task<Result<Navigated>> {
13186 let Some(provider) = self.semantics_provider.clone() else {
13187 return Task::ready(Ok(Navigated::No));
13188 };
13189 let head = self.selections.newest::<usize>(cx).head();
13190 let buffer = self.buffer.read(cx);
13191 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13192 text_anchor
13193 } else {
13194 return Task::ready(Ok(Navigated::No));
13195 };
13196
13197 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13198 return Task::ready(Ok(Navigated::No));
13199 };
13200
13201 cx.spawn_in(window, async move |editor, cx| {
13202 let definitions = definitions.await?;
13203 let navigated = editor
13204 .update_in(cx, |editor, window, cx| {
13205 editor.navigate_to_hover_links(
13206 Some(kind),
13207 definitions
13208 .into_iter()
13209 .filter(|location| {
13210 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13211 })
13212 .map(HoverLink::Text)
13213 .collect::<Vec<_>>(),
13214 split,
13215 window,
13216 cx,
13217 )
13218 })?
13219 .await?;
13220 anyhow::Ok(navigated)
13221 })
13222 }
13223
13224 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13225 let selection = self.selections.newest_anchor();
13226 let head = selection.head();
13227 let tail = selection.tail();
13228
13229 let Some((buffer, start_position)) =
13230 self.buffer.read(cx).text_anchor_for_position(head, cx)
13231 else {
13232 return;
13233 };
13234
13235 let end_position = if head != tail {
13236 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13237 return;
13238 };
13239 Some(pos)
13240 } else {
13241 None
13242 };
13243
13244 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13245 let url = if let Some(end_pos) = end_position {
13246 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13247 } else {
13248 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13249 };
13250
13251 if let Some(url) = url {
13252 editor.update(cx, |_, cx| {
13253 cx.open_url(&url);
13254 })
13255 } else {
13256 Ok(())
13257 }
13258 });
13259
13260 url_finder.detach();
13261 }
13262
13263 pub fn open_selected_filename(
13264 &mut self,
13265 _: &OpenSelectedFilename,
13266 window: &mut Window,
13267 cx: &mut Context<Self>,
13268 ) {
13269 let Some(workspace) = self.workspace() else {
13270 return;
13271 };
13272
13273 let position = self.selections.newest_anchor().head();
13274
13275 let Some((buffer, buffer_position)) =
13276 self.buffer.read(cx).text_anchor_for_position(position, cx)
13277 else {
13278 return;
13279 };
13280
13281 let project = self.project.clone();
13282
13283 cx.spawn_in(window, async move |_, cx| {
13284 let result = find_file(&buffer, project, buffer_position, cx).await;
13285
13286 if let Some((_, path)) = result {
13287 workspace
13288 .update_in(cx, |workspace, window, cx| {
13289 workspace.open_resolved_path(path, window, cx)
13290 })?
13291 .await?;
13292 }
13293 anyhow::Ok(())
13294 })
13295 .detach();
13296 }
13297
13298 pub(crate) fn navigate_to_hover_links(
13299 &mut self,
13300 kind: Option<GotoDefinitionKind>,
13301 mut definitions: Vec<HoverLink>,
13302 split: bool,
13303 window: &mut Window,
13304 cx: &mut Context<Editor>,
13305 ) -> Task<Result<Navigated>> {
13306 // If there is one definition, just open it directly
13307 if definitions.len() == 1 {
13308 let definition = definitions.pop().unwrap();
13309
13310 enum TargetTaskResult {
13311 Location(Option<Location>),
13312 AlreadyNavigated,
13313 }
13314
13315 let target_task = match definition {
13316 HoverLink::Text(link) => {
13317 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13318 }
13319 HoverLink::InlayHint(lsp_location, server_id) => {
13320 let computation =
13321 self.compute_target_location(lsp_location, server_id, window, cx);
13322 cx.background_spawn(async move {
13323 let location = computation.await?;
13324 Ok(TargetTaskResult::Location(location))
13325 })
13326 }
13327 HoverLink::Url(url) => {
13328 cx.open_url(&url);
13329 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13330 }
13331 HoverLink::File(path) => {
13332 if let Some(workspace) = self.workspace() {
13333 cx.spawn_in(window, async move |_, cx| {
13334 workspace
13335 .update_in(cx, |workspace, window, cx| {
13336 workspace.open_resolved_path(path, window, cx)
13337 })?
13338 .await
13339 .map(|_| TargetTaskResult::AlreadyNavigated)
13340 })
13341 } else {
13342 Task::ready(Ok(TargetTaskResult::Location(None)))
13343 }
13344 }
13345 };
13346 cx.spawn_in(window, async move |editor, cx| {
13347 let target = match target_task.await.context("target resolution task")? {
13348 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13349 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13350 TargetTaskResult::Location(Some(target)) => target,
13351 };
13352
13353 editor.update_in(cx, |editor, window, cx| {
13354 let Some(workspace) = editor.workspace() else {
13355 return Navigated::No;
13356 };
13357 let pane = workspace.read(cx).active_pane().clone();
13358
13359 let range = target.range.to_point(target.buffer.read(cx));
13360 let range = editor.range_for_match(&range);
13361 let range = collapse_multiline_range(range);
13362
13363 if !split
13364 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13365 {
13366 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13367 } else {
13368 window.defer(cx, move |window, cx| {
13369 let target_editor: Entity<Self> =
13370 workspace.update(cx, |workspace, cx| {
13371 let pane = if split {
13372 workspace.adjacent_pane(window, cx)
13373 } else {
13374 workspace.active_pane().clone()
13375 };
13376
13377 workspace.open_project_item(
13378 pane,
13379 target.buffer.clone(),
13380 true,
13381 true,
13382 window,
13383 cx,
13384 )
13385 });
13386 target_editor.update(cx, |target_editor, cx| {
13387 // When selecting a definition in a different buffer, disable the nav history
13388 // to avoid creating a history entry at the previous cursor location.
13389 pane.update(cx, |pane, _| pane.disable_history());
13390 target_editor.go_to_singleton_buffer_range(range, window, cx);
13391 pane.update(cx, |pane, _| pane.enable_history());
13392 });
13393 });
13394 }
13395 Navigated::Yes
13396 })
13397 })
13398 } else if !definitions.is_empty() {
13399 cx.spawn_in(window, async move |editor, cx| {
13400 let (title, location_tasks, workspace) = editor
13401 .update_in(cx, |editor, window, cx| {
13402 let tab_kind = match kind {
13403 Some(GotoDefinitionKind::Implementation) => "Implementations",
13404 _ => "Definitions",
13405 };
13406 let title = definitions
13407 .iter()
13408 .find_map(|definition| match definition {
13409 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13410 let buffer = origin.buffer.read(cx);
13411 format!(
13412 "{} for {}",
13413 tab_kind,
13414 buffer
13415 .text_for_range(origin.range.clone())
13416 .collect::<String>()
13417 )
13418 }),
13419 HoverLink::InlayHint(_, _) => None,
13420 HoverLink::Url(_) => None,
13421 HoverLink::File(_) => None,
13422 })
13423 .unwrap_or(tab_kind.to_string());
13424 let location_tasks = definitions
13425 .into_iter()
13426 .map(|definition| match definition {
13427 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13428 HoverLink::InlayHint(lsp_location, server_id) => editor
13429 .compute_target_location(lsp_location, server_id, window, cx),
13430 HoverLink::Url(_) => Task::ready(Ok(None)),
13431 HoverLink::File(_) => Task::ready(Ok(None)),
13432 })
13433 .collect::<Vec<_>>();
13434 (title, location_tasks, editor.workspace().clone())
13435 })
13436 .context("location tasks preparation")?;
13437
13438 let locations = future::join_all(location_tasks)
13439 .await
13440 .into_iter()
13441 .filter_map(|location| location.transpose())
13442 .collect::<Result<_>>()
13443 .context("location tasks")?;
13444
13445 let Some(workspace) = workspace else {
13446 return Ok(Navigated::No);
13447 };
13448 let opened = workspace
13449 .update_in(cx, |workspace, window, cx| {
13450 Self::open_locations_in_multibuffer(
13451 workspace,
13452 locations,
13453 title,
13454 split,
13455 MultibufferSelectionMode::First,
13456 window,
13457 cx,
13458 )
13459 })
13460 .ok();
13461
13462 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13463 })
13464 } else {
13465 Task::ready(Ok(Navigated::No))
13466 }
13467 }
13468
13469 fn compute_target_location(
13470 &self,
13471 lsp_location: lsp::Location,
13472 server_id: LanguageServerId,
13473 window: &mut Window,
13474 cx: &mut Context<Self>,
13475 ) -> Task<anyhow::Result<Option<Location>>> {
13476 let Some(project) = self.project.clone() else {
13477 return Task::ready(Ok(None));
13478 };
13479
13480 cx.spawn_in(window, async move |editor, cx| {
13481 let location_task = editor.update(cx, |_, cx| {
13482 project.update(cx, |project, cx| {
13483 let language_server_name = project
13484 .language_server_statuses(cx)
13485 .find(|(id, _)| server_id == *id)
13486 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13487 language_server_name.map(|language_server_name| {
13488 project.open_local_buffer_via_lsp(
13489 lsp_location.uri.clone(),
13490 server_id,
13491 language_server_name,
13492 cx,
13493 )
13494 })
13495 })
13496 })?;
13497 let location = match location_task {
13498 Some(task) => Some({
13499 let target_buffer_handle = task.await.context("open local buffer")?;
13500 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13501 let target_start = target_buffer
13502 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13503 let target_end = target_buffer
13504 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13505 target_buffer.anchor_after(target_start)
13506 ..target_buffer.anchor_before(target_end)
13507 })?;
13508 Location {
13509 buffer: target_buffer_handle,
13510 range,
13511 }
13512 }),
13513 None => None,
13514 };
13515 Ok(location)
13516 })
13517 }
13518
13519 pub fn find_all_references(
13520 &mut self,
13521 _: &FindAllReferences,
13522 window: &mut Window,
13523 cx: &mut Context<Self>,
13524 ) -> Option<Task<Result<Navigated>>> {
13525 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
13526
13527 let selection = self.selections.newest::<usize>(cx);
13528 let multi_buffer = self.buffer.read(cx);
13529 let head = selection.head();
13530
13531 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13532 let head_anchor = multi_buffer_snapshot.anchor_at(
13533 head,
13534 if head < selection.tail() {
13535 Bias::Right
13536 } else {
13537 Bias::Left
13538 },
13539 );
13540
13541 match self
13542 .find_all_references_task_sources
13543 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13544 {
13545 Ok(_) => {
13546 log::info!(
13547 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13548 );
13549 return None;
13550 }
13551 Err(i) => {
13552 self.find_all_references_task_sources.insert(i, head_anchor);
13553 }
13554 }
13555
13556 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13557 let workspace = self.workspace()?;
13558 let project = workspace.read(cx).project().clone();
13559 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13560 Some(cx.spawn_in(window, async move |editor, cx| {
13561 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13562 if let Ok(i) = editor
13563 .find_all_references_task_sources
13564 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13565 {
13566 editor.find_all_references_task_sources.remove(i);
13567 }
13568 });
13569
13570 let locations = references.await?;
13571 if locations.is_empty() {
13572 return anyhow::Ok(Navigated::No);
13573 }
13574
13575 workspace.update_in(cx, |workspace, window, cx| {
13576 let title = locations
13577 .first()
13578 .as_ref()
13579 .map(|location| {
13580 let buffer = location.buffer.read(cx);
13581 format!(
13582 "References to `{}`",
13583 buffer
13584 .text_for_range(location.range.clone())
13585 .collect::<String>()
13586 )
13587 })
13588 .unwrap();
13589 Self::open_locations_in_multibuffer(
13590 workspace,
13591 locations,
13592 title,
13593 false,
13594 MultibufferSelectionMode::First,
13595 window,
13596 cx,
13597 );
13598 Navigated::Yes
13599 })
13600 }))
13601 }
13602
13603 /// Opens a multibuffer with the given project locations in it
13604 pub fn open_locations_in_multibuffer(
13605 workspace: &mut Workspace,
13606 mut locations: Vec<Location>,
13607 title: String,
13608 split: bool,
13609 multibuffer_selection_mode: MultibufferSelectionMode,
13610 window: &mut Window,
13611 cx: &mut Context<Workspace>,
13612 ) {
13613 // If there are multiple definitions, open them in a multibuffer
13614 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13615 let mut locations = locations.into_iter().peekable();
13616 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13617 let capability = workspace.project().read(cx).capability();
13618
13619 let excerpt_buffer = cx.new(|cx| {
13620 let mut multibuffer = MultiBuffer::new(capability);
13621 while let Some(location) = locations.next() {
13622 let buffer = location.buffer.read(cx);
13623 let mut ranges_for_buffer = Vec::new();
13624 let range = location.range.to_point(buffer);
13625 ranges_for_buffer.push(range.clone());
13626
13627 while let Some(next_location) = locations.peek() {
13628 if next_location.buffer == location.buffer {
13629 ranges_for_buffer.push(next_location.range.to_point(buffer));
13630 locations.next();
13631 } else {
13632 break;
13633 }
13634 }
13635
13636 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13637 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13638 PathKey::for_buffer(&location.buffer, cx),
13639 location.buffer.clone(),
13640 ranges_for_buffer,
13641 DEFAULT_MULTIBUFFER_CONTEXT,
13642 cx,
13643 );
13644 ranges.extend(new_ranges)
13645 }
13646
13647 multibuffer.with_title(title)
13648 });
13649
13650 let editor = cx.new(|cx| {
13651 Editor::for_multibuffer(
13652 excerpt_buffer,
13653 Some(workspace.project().clone()),
13654 window,
13655 cx,
13656 )
13657 });
13658 editor.update(cx, |editor, cx| {
13659 match multibuffer_selection_mode {
13660 MultibufferSelectionMode::First => {
13661 if let Some(first_range) = ranges.first() {
13662 editor.change_selections(None, window, cx, |selections| {
13663 selections.clear_disjoint();
13664 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13665 });
13666 }
13667 editor.highlight_background::<Self>(
13668 &ranges,
13669 |theme| theme.editor_highlighted_line_background,
13670 cx,
13671 );
13672 }
13673 MultibufferSelectionMode::All => {
13674 editor.change_selections(None, window, cx, |selections| {
13675 selections.clear_disjoint();
13676 selections.select_anchor_ranges(ranges);
13677 });
13678 }
13679 }
13680 editor.register_buffers_with_language_servers(cx);
13681 });
13682
13683 let item = Box::new(editor);
13684 let item_id = item.item_id();
13685
13686 if split {
13687 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13688 } else {
13689 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13690 let (preview_item_id, preview_item_idx) =
13691 workspace.active_pane().update(cx, |pane, _| {
13692 (pane.preview_item_id(), pane.preview_item_idx())
13693 });
13694
13695 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13696
13697 if let Some(preview_item_id) = preview_item_id {
13698 workspace.active_pane().update(cx, |pane, cx| {
13699 pane.remove_item(preview_item_id, false, false, window, cx);
13700 });
13701 }
13702 } else {
13703 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13704 }
13705 }
13706 workspace.active_pane().update(cx, |pane, cx| {
13707 pane.set_preview_item_id(Some(item_id), cx);
13708 });
13709 }
13710
13711 pub fn rename(
13712 &mut self,
13713 _: &Rename,
13714 window: &mut Window,
13715 cx: &mut Context<Self>,
13716 ) -> Option<Task<Result<()>>> {
13717 use language::ToOffset as _;
13718
13719 let provider = self.semantics_provider.clone()?;
13720 let selection = self.selections.newest_anchor().clone();
13721 let (cursor_buffer, cursor_buffer_position) = self
13722 .buffer
13723 .read(cx)
13724 .text_anchor_for_position(selection.head(), cx)?;
13725 let (tail_buffer, cursor_buffer_position_end) = self
13726 .buffer
13727 .read(cx)
13728 .text_anchor_for_position(selection.tail(), cx)?;
13729 if tail_buffer != cursor_buffer {
13730 return None;
13731 }
13732
13733 let snapshot = cursor_buffer.read(cx).snapshot();
13734 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13735 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13736 let prepare_rename = provider
13737 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13738 .unwrap_or_else(|| Task::ready(Ok(None)));
13739 drop(snapshot);
13740
13741 Some(cx.spawn_in(window, async move |this, cx| {
13742 let rename_range = if let Some(range) = prepare_rename.await? {
13743 Some(range)
13744 } else {
13745 this.update(cx, |this, cx| {
13746 let buffer = this.buffer.read(cx).snapshot(cx);
13747 let mut buffer_highlights = this
13748 .document_highlights_for_position(selection.head(), &buffer)
13749 .filter(|highlight| {
13750 highlight.start.excerpt_id == selection.head().excerpt_id
13751 && highlight.end.excerpt_id == selection.head().excerpt_id
13752 });
13753 buffer_highlights
13754 .next()
13755 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13756 })?
13757 };
13758 if let Some(rename_range) = rename_range {
13759 this.update_in(cx, |this, window, cx| {
13760 let snapshot = cursor_buffer.read(cx).snapshot();
13761 let rename_buffer_range = rename_range.to_offset(&snapshot);
13762 let cursor_offset_in_rename_range =
13763 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13764 let cursor_offset_in_rename_range_end =
13765 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13766
13767 this.take_rename(false, window, cx);
13768 let buffer = this.buffer.read(cx).read(cx);
13769 let cursor_offset = selection.head().to_offset(&buffer);
13770 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13771 let rename_end = rename_start + rename_buffer_range.len();
13772 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13773 let mut old_highlight_id = None;
13774 let old_name: Arc<str> = buffer
13775 .chunks(rename_start..rename_end, true)
13776 .map(|chunk| {
13777 if old_highlight_id.is_none() {
13778 old_highlight_id = chunk.syntax_highlight_id;
13779 }
13780 chunk.text
13781 })
13782 .collect::<String>()
13783 .into();
13784
13785 drop(buffer);
13786
13787 // Position the selection in the rename editor so that it matches the current selection.
13788 this.show_local_selections = false;
13789 let rename_editor = cx.new(|cx| {
13790 let mut editor = Editor::single_line(window, cx);
13791 editor.buffer.update(cx, |buffer, cx| {
13792 buffer.edit([(0..0, old_name.clone())], None, cx)
13793 });
13794 let rename_selection_range = match cursor_offset_in_rename_range
13795 .cmp(&cursor_offset_in_rename_range_end)
13796 {
13797 Ordering::Equal => {
13798 editor.select_all(&SelectAll, window, cx);
13799 return editor;
13800 }
13801 Ordering::Less => {
13802 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13803 }
13804 Ordering::Greater => {
13805 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13806 }
13807 };
13808 if rename_selection_range.end > old_name.len() {
13809 editor.select_all(&SelectAll, window, cx);
13810 } else {
13811 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13812 s.select_ranges([rename_selection_range]);
13813 });
13814 }
13815 editor
13816 });
13817 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13818 if e == &EditorEvent::Focused {
13819 cx.emit(EditorEvent::FocusedIn)
13820 }
13821 })
13822 .detach();
13823
13824 let write_highlights =
13825 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13826 let read_highlights =
13827 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13828 let ranges = write_highlights
13829 .iter()
13830 .flat_map(|(_, ranges)| ranges.iter())
13831 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13832 .cloned()
13833 .collect();
13834
13835 this.highlight_text::<Rename>(
13836 ranges,
13837 HighlightStyle {
13838 fade_out: Some(0.6),
13839 ..Default::default()
13840 },
13841 cx,
13842 );
13843 let rename_focus_handle = rename_editor.focus_handle(cx);
13844 window.focus(&rename_focus_handle);
13845 let block_id = this.insert_blocks(
13846 [BlockProperties {
13847 style: BlockStyle::Flex,
13848 placement: BlockPlacement::Below(range.start),
13849 height: Some(1),
13850 render: Arc::new({
13851 let rename_editor = rename_editor.clone();
13852 move |cx: &mut BlockContext| {
13853 let mut text_style = cx.editor_style.text.clone();
13854 if let Some(highlight_style) = old_highlight_id
13855 .and_then(|h| h.style(&cx.editor_style.syntax))
13856 {
13857 text_style = text_style.highlight(highlight_style);
13858 }
13859 div()
13860 .block_mouse_down()
13861 .pl(cx.anchor_x)
13862 .child(EditorElement::new(
13863 &rename_editor,
13864 EditorStyle {
13865 background: cx.theme().system().transparent,
13866 local_player: cx.editor_style.local_player,
13867 text: text_style,
13868 scrollbar_width: cx.editor_style.scrollbar_width,
13869 syntax: cx.editor_style.syntax.clone(),
13870 status: cx.editor_style.status.clone(),
13871 inlay_hints_style: HighlightStyle {
13872 font_weight: Some(FontWeight::BOLD),
13873 ..make_inlay_hints_style(cx.app)
13874 },
13875 inline_completion_styles: make_suggestion_styles(
13876 cx.app,
13877 ),
13878 ..EditorStyle::default()
13879 },
13880 ))
13881 .into_any_element()
13882 }
13883 }),
13884 priority: 0,
13885 }],
13886 Some(Autoscroll::fit()),
13887 cx,
13888 )[0];
13889 this.pending_rename = Some(RenameState {
13890 range,
13891 old_name,
13892 editor: rename_editor,
13893 block_id,
13894 });
13895 })?;
13896 }
13897
13898 Ok(())
13899 }))
13900 }
13901
13902 pub fn confirm_rename(
13903 &mut self,
13904 _: &ConfirmRename,
13905 window: &mut Window,
13906 cx: &mut Context<Self>,
13907 ) -> Option<Task<Result<()>>> {
13908 let rename = self.take_rename(false, window, cx)?;
13909 let workspace = self.workspace()?.downgrade();
13910 let (buffer, start) = self
13911 .buffer
13912 .read(cx)
13913 .text_anchor_for_position(rename.range.start, cx)?;
13914 let (end_buffer, _) = self
13915 .buffer
13916 .read(cx)
13917 .text_anchor_for_position(rename.range.end, cx)?;
13918 if buffer != end_buffer {
13919 return None;
13920 }
13921
13922 let old_name = rename.old_name;
13923 let new_name = rename.editor.read(cx).text(cx);
13924
13925 let rename = self.semantics_provider.as_ref()?.perform_rename(
13926 &buffer,
13927 start,
13928 new_name.clone(),
13929 cx,
13930 )?;
13931
13932 Some(cx.spawn_in(window, async move |editor, cx| {
13933 let project_transaction = rename.await?;
13934 Self::open_project_transaction(
13935 &editor,
13936 workspace,
13937 project_transaction,
13938 format!("Rename: {} → {}", old_name, new_name),
13939 cx,
13940 )
13941 .await?;
13942
13943 editor.update(cx, |editor, cx| {
13944 editor.refresh_document_highlights(cx);
13945 })?;
13946 Ok(())
13947 }))
13948 }
13949
13950 fn take_rename(
13951 &mut self,
13952 moving_cursor: bool,
13953 window: &mut Window,
13954 cx: &mut Context<Self>,
13955 ) -> Option<RenameState> {
13956 let rename = self.pending_rename.take()?;
13957 if rename.editor.focus_handle(cx).is_focused(window) {
13958 window.focus(&self.focus_handle);
13959 }
13960
13961 self.remove_blocks(
13962 [rename.block_id].into_iter().collect(),
13963 Some(Autoscroll::fit()),
13964 cx,
13965 );
13966 self.clear_highlights::<Rename>(cx);
13967 self.show_local_selections = true;
13968
13969 if moving_cursor {
13970 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13971 editor.selections.newest::<usize>(cx).head()
13972 });
13973
13974 // Update the selection to match the position of the selection inside
13975 // the rename editor.
13976 let snapshot = self.buffer.read(cx).read(cx);
13977 let rename_range = rename.range.to_offset(&snapshot);
13978 let cursor_in_editor = snapshot
13979 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13980 .min(rename_range.end);
13981 drop(snapshot);
13982
13983 self.change_selections(None, window, cx, |s| {
13984 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13985 });
13986 } else {
13987 self.refresh_document_highlights(cx);
13988 }
13989
13990 Some(rename)
13991 }
13992
13993 pub fn pending_rename(&self) -> Option<&RenameState> {
13994 self.pending_rename.as_ref()
13995 }
13996
13997 fn format(
13998 &mut self,
13999 _: &Format,
14000 window: &mut Window,
14001 cx: &mut Context<Self>,
14002 ) -> Option<Task<Result<()>>> {
14003 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14004
14005 let project = match &self.project {
14006 Some(project) => project.clone(),
14007 None => return None,
14008 };
14009
14010 Some(self.perform_format(
14011 project,
14012 FormatTrigger::Manual,
14013 FormatTarget::Buffers,
14014 window,
14015 cx,
14016 ))
14017 }
14018
14019 fn format_selections(
14020 &mut self,
14021 _: &FormatSelections,
14022 window: &mut Window,
14023 cx: &mut Context<Self>,
14024 ) -> Option<Task<Result<()>>> {
14025 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14026
14027 let project = match &self.project {
14028 Some(project) => project.clone(),
14029 None => return None,
14030 };
14031
14032 let ranges = self
14033 .selections
14034 .all_adjusted(cx)
14035 .into_iter()
14036 .map(|selection| selection.range())
14037 .collect_vec();
14038
14039 Some(self.perform_format(
14040 project,
14041 FormatTrigger::Manual,
14042 FormatTarget::Ranges(ranges),
14043 window,
14044 cx,
14045 ))
14046 }
14047
14048 fn perform_format(
14049 &mut self,
14050 project: Entity<Project>,
14051 trigger: FormatTrigger,
14052 target: FormatTarget,
14053 window: &mut Window,
14054 cx: &mut Context<Self>,
14055 ) -> Task<Result<()>> {
14056 let buffer = self.buffer.clone();
14057 let (buffers, target) = match target {
14058 FormatTarget::Buffers => {
14059 let mut buffers = buffer.read(cx).all_buffers();
14060 if trigger == FormatTrigger::Save {
14061 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14062 }
14063 (buffers, LspFormatTarget::Buffers)
14064 }
14065 FormatTarget::Ranges(selection_ranges) => {
14066 let multi_buffer = buffer.read(cx);
14067 let snapshot = multi_buffer.read(cx);
14068 let mut buffers = HashSet::default();
14069 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14070 BTreeMap::new();
14071 for selection_range in selection_ranges {
14072 for (buffer, buffer_range, _) in
14073 snapshot.range_to_buffer_ranges(selection_range)
14074 {
14075 let buffer_id = buffer.remote_id();
14076 let start = buffer.anchor_before(buffer_range.start);
14077 let end = buffer.anchor_after(buffer_range.end);
14078 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14079 buffer_id_to_ranges
14080 .entry(buffer_id)
14081 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14082 .or_insert_with(|| vec![start..end]);
14083 }
14084 }
14085 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14086 }
14087 };
14088
14089 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14090 let format = project.update(cx, |project, cx| {
14091 project.format(buffers, target, true, trigger, cx)
14092 });
14093
14094 cx.spawn_in(window, async move |_, cx| {
14095 let transaction = futures::select_biased! {
14096 transaction = format.log_err().fuse() => transaction,
14097 () = timeout => {
14098 log::warn!("timed out waiting for formatting");
14099 None
14100 }
14101 };
14102
14103 buffer
14104 .update(cx, |buffer, cx| {
14105 if let Some(transaction) = transaction {
14106 if !buffer.is_singleton() {
14107 buffer.push_transaction(&transaction.0, cx);
14108 }
14109 }
14110 cx.notify();
14111 })
14112 .ok();
14113
14114 Ok(())
14115 })
14116 }
14117
14118 fn organize_imports(
14119 &mut self,
14120 _: &OrganizeImports,
14121 window: &mut Window,
14122 cx: &mut Context<Self>,
14123 ) -> Option<Task<Result<()>>> {
14124 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14125 let project = match &self.project {
14126 Some(project) => project.clone(),
14127 None => return None,
14128 };
14129 Some(self.perform_code_action_kind(
14130 project,
14131 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14132 window,
14133 cx,
14134 ))
14135 }
14136
14137 fn perform_code_action_kind(
14138 &mut self,
14139 project: Entity<Project>,
14140 kind: CodeActionKind,
14141 window: &mut Window,
14142 cx: &mut Context<Self>,
14143 ) -> Task<Result<()>> {
14144 let buffer = self.buffer.clone();
14145 let buffers = buffer.read(cx).all_buffers();
14146 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14147 let apply_action = project.update(cx, |project, cx| {
14148 project.apply_code_action_kind(buffers, kind, true, cx)
14149 });
14150 cx.spawn_in(window, async move |_, cx| {
14151 let transaction = futures::select_biased! {
14152 () = timeout => {
14153 log::warn!("timed out waiting for executing code action");
14154 None
14155 }
14156 transaction = apply_action.log_err().fuse() => transaction,
14157 };
14158 buffer
14159 .update(cx, |buffer, cx| {
14160 // check if we need this
14161 if let Some(transaction) = transaction {
14162 if !buffer.is_singleton() {
14163 buffer.push_transaction(&transaction.0, cx);
14164 }
14165 }
14166 cx.notify();
14167 })
14168 .ok();
14169 Ok(())
14170 })
14171 }
14172
14173 fn restart_language_server(
14174 &mut self,
14175 _: &RestartLanguageServer,
14176 _: &mut Window,
14177 cx: &mut Context<Self>,
14178 ) {
14179 if let Some(project) = self.project.clone() {
14180 self.buffer.update(cx, |multi_buffer, cx| {
14181 project.update(cx, |project, cx| {
14182 project.restart_language_servers_for_buffers(
14183 multi_buffer.all_buffers().into_iter().collect(),
14184 cx,
14185 );
14186 });
14187 })
14188 }
14189 }
14190
14191 fn stop_language_server(
14192 &mut self,
14193 _: &StopLanguageServer,
14194 _: &mut Window,
14195 cx: &mut Context<Self>,
14196 ) {
14197 if let Some(project) = self.project.clone() {
14198 self.buffer.update(cx, |multi_buffer, cx| {
14199 project.update(cx, |project, cx| {
14200 project.stop_language_servers_for_buffers(
14201 multi_buffer.all_buffers().into_iter().collect(),
14202 cx,
14203 );
14204 cx.emit(project::Event::RefreshInlayHints);
14205 });
14206 });
14207 }
14208 }
14209
14210 fn cancel_language_server_work(
14211 workspace: &mut Workspace,
14212 _: &actions::CancelLanguageServerWork,
14213 _: &mut Window,
14214 cx: &mut Context<Workspace>,
14215 ) {
14216 let project = workspace.project();
14217 let buffers = workspace
14218 .active_item(cx)
14219 .and_then(|item| item.act_as::<Editor>(cx))
14220 .map_or(HashSet::default(), |editor| {
14221 editor.read(cx).buffer.read(cx).all_buffers()
14222 });
14223 project.update(cx, |project, cx| {
14224 project.cancel_language_server_work_for_buffers(buffers, cx);
14225 });
14226 }
14227
14228 fn show_character_palette(
14229 &mut self,
14230 _: &ShowCharacterPalette,
14231 window: &mut Window,
14232 _: &mut Context<Self>,
14233 ) {
14234 window.show_character_palette();
14235 }
14236
14237 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14238 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
14239 let buffer = self.buffer.read(cx).snapshot(cx);
14240 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
14241 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
14242 let is_valid = buffer
14243 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14244 .any(|entry| {
14245 entry.diagnostic.is_primary
14246 && !entry.range.is_empty()
14247 && entry.range.start == primary_range_start
14248 && entry.diagnostic.message == active_diagnostics.primary_message
14249 });
14250
14251 if is_valid != active_diagnostics.is_valid {
14252 active_diagnostics.is_valid = is_valid;
14253 if is_valid {
14254 let mut new_styles = HashMap::default();
14255 for (block_id, diagnostic) in &active_diagnostics.blocks {
14256 new_styles.insert(
14257 *block_id,
14258 diagnostic_block_renderer(diagnostic.clone(), None, true),
14259 );
14260 }
14261 self.display_map.update(cx, |display_map, _cx| {
14262 display_map.replace_blocks(new_styles);
14263 });
14264 } else {
14265 self.dismiss_diagnostics(cx);
14266 }
14267 }
14268 }
14269 }
14270
14271 fn activate_diagnostics(
14272 &mut self,
14273 buffer_id: BufferId,
14274 group_id: usize,
14275 window: &mut Window,
14276 cx: &mut Context<Self>,
14277 ) {
14278 self.dismiss_diagnostics(cx);
14279 let snapshot = self.snapshot(window, cx);
14280 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
14281 let buffer = self.buffer.read(cx).snapshot(cx);
14282
14283 let mut primary_range = None;
14284 let mut primary_message = None;
14285 let diagnostic_group = buffer
14286 .diagnostic_group(buffer_id, group_id)
14287 .filter_map(|entry| {
14288 let start = entry.range.start;
14289 let end = entry.range.end;
14290 if snapshot.is_line_folded(MultiBufferRow(start.row))
14291 && (start.row == end.row
14292 || snapshot.is_line_folded(MultiBufferRow(end.row)))
14293 {
14294 return None;
14295 }
14296 if entry.diagnostic.is_primary {
14297 primary_range = Some(entry.range.clone());
14298 primary_message = Some(entry.diagnostic.message.clone());
14299 }
14300 Some(entry)
14301 })
14302 .collect::<Vec<_>>();
14303 let primary_range = primary_range?;
14304 let primary_message = primary_message?;
14305
14306 let blocks = display_map
14307 .insert_blocks(
14308 diagnostic_group.iter().map(|entry| {
14309 let diagnostic = entry.diagnostic.clone();
14310 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
14311 BlockProperties {
14312 style: BlockStyle::Fixed,
14313 placement: BlockPlacement::Below(
14314 buffer.anchor_after(entry.range.start),
14315 ),
14316 height: Some(message_height),
14317 render: diagnostic_block_renderer(diagnostic, None, true),
14318 priority: 0,
14319 }
14320 }),
14321 cx,
14322 )
14323 .into_iter()
14324 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
14325 .collect();
14326
14327 Some(ActiveDiagnosticGroup {
14328 primary_range: buffer.anchor_before(primary_range.start)
14329 ..buffer.anchor_after(primary_range.end),
14330 primary_message,
14331 group_id,
14332 blocks,
14333 is_valid: true,
14334 })
14335 });
14336 }
14337
14338 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14339 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
14340 self.display_map.update(cx, |display_map, cx| {
14341 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
14342 });
14343 cx.notify();
14344 }
14345 }
14346
14347 /// Disable inline diagnostics rendering for this editor.
14348 pub fn disable_inline_diagnostics(&mut self) {
14349 self.inline_diagnostics_enabled = false;
14350 self.inline_diagnostics_update = Task::ready(());
14351 self.inline_diagnostics.clear();
14352 }
14353
14354 pub fn inline_diagnostics_enabled(&self) -> bool {
14355 self.inline_diagnostics_enabled
14356 }
14357
14358 pub fn show_inline_diagnostics(&self) -> bool {
14359 self.show_inline_diagnostics
14360 }
14361
14362 pub fn toggle_inline_diagnostics(
14363 &mut self,
14364 _: &ToggleInlineDiagnostics,
14365 window: &mut Window,
14366 cx: &mut Context<Editor>,
14367 ) {
14368 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14369 self.refresh_inline_diagnostics(false, window, cx);
14370 }
14371
14372 fn refresh_inline_diagnostics(
14373 &mut self,
14374 debounce: bool,
14375 window: &mut Window,
14376 cx: &mut Context<Self>,
14377 ) {
14378 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14379 self.inline_diagnostics_update = Task::ready(());
14380 self.inline_diagnostics.clear();
14381 return;
14382 }
14383
14384 let debounce_ms = ProjectSettings::get_global(cx)
14385 .diagnostics
14386 .inline
14387 .update_debounce_ms;
14388 let debounce = if debounce && debounce_ms > 0 {
14389 Some(Duration::from_millis(debounce_ms))
14390 } else {
14391 None
14392 };
14393 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14394 if let Some(debounce) = debounce {
14395 cx.background_executor().timer(debounce).await;
14396 }
14397 let Some(snapshot) = editor
14398 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14399 .ok()
14400 else {
14401 return;
14402 };
14403
14404 let new_inline_diagnostics = cx
14405 .background_spawn(async move {
14406 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14407 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14408 let message = diagnostic_entry
14409 .diagnostic
14410 .message
14411 .split_once('\n')
14412 .map(|(line, _)| line)
14413 .map(SharedString::new)
14414 .unwrap_or_else(|| {
14415 SharedString::from(diagnostic_entry.diagnostic.message)
14416 });
14417 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14418 let (Ok(i) | Err(i)) = inline_diagnostics
14419 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14420 inline_diagnostics.insert(
14421 i,
14422 (
14423 start_anchor,
14424 InlineDiagnostic {
14425 message,
14426 group_id: diagnostic_entry.diagnostic.group_id,
14427 start: diagnostic_entry.range.start.to_point(&snapshot),
14428 is_primary: diagnostic_entry.diagnostic.is_primary,
14429 severity: diagnostic_entry.diagnostic.severity,
14430 },
14431 ),
14432 );
14433 }
14434 inline_diagnostics
14435 })
14436 .await;
14437
14438 editor
14439 .update(cx, |editor, cx| {
14440 editor.inline_diagnostics = new_inline_diagnostics;
14441 cx.notify();
14442 })
14443 .ok();
14444 });
14445 }
14446
14447 pub fn set_selections_from_remote(
14448 &mut self,
14449 selections: Vec<Selection<Anchor>>,
14450 pending_selection: Option<Selection<Anchor>>,
14451 window: &mut Window,
14452 cx: &mut Context<Self>,
14453 ) {
14454 let old_cursor_position = self.selections.newest_anchor().head();
14455 self.selections.change_with(cx, |s| {
14456 s.select_anchors(selections);
14457 if let Some(pending_selection) = pending_selection {
14458 s.set_pending(pending_selection, SelectMode::Character);
14459 } else {
14460 s.clear_pending();
14461 }
14462 });
14463 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14464 }
14465
14466 fn push_to_selection_history(&mut self) {
14467 self.selection_history.push(SelectionHistoryEntry {
14468 selections: self.selections.disjoint_anchors(),
14469 select_next_state: self.select_next_state.clone(),
14470 select_prev_state: self.select_prev_state.clone(),
14471 add_selections_state: self.add_selections_state.clone(),
14472 });
14473 }
14474
14475 pub fn transact(
14476 &mut self,
14477 window: &mut Window,
14478 cx: &mut Context<Self>,
14479 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14480 ) -> Option<TransactionId> {
14481 self.start_transaction_at(Instant::now(), window, cx);
14482 update(self, window, cx);
14483 self.end_transaction_at(Instant::now(), cx)
14484 }
14485
14486 pub fn start_transaction_at(
14487 &mut self,
14488 now: Instant,
14489 window: &mut Window,
14490 cx: &mut Context<Self>,
14491 ) {
14492 self.end_selection(window, cx);
14493 if let Some(tx_id) = self
14494 .buffer
14495 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14496 {
14497 self.selection_history
14498 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14499 cx.emit(EditorEvent::TransactionBegun {
14500 transaction_id: tx_id,
14501 })
14502 }
14503 }
14504
14505 pub fn end_transaction_at(
14506 &mut self,
14507 now: Instant,
14508 cx: &mut Context<Self>,
14509 ) -> Option<TransactionId> {
14510 if let Some(transaction_id) = self
14511 .buffer
14512 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14513 {
14514 if let Some((_, end_selections)) =
14515 self.selection_history.transaction_mut(transaction_id)
14516 {
14517 *end_selections = Some(self.selections.disjoint_anchors());
14518 } else {
14519 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14520 }
14521
14522 cx.emit(EditorEvent::Edited { transaction_id });
14523 Some(transaction_id)
14524 } else {
14525 None
14526 }
14527 }
14528
14529 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14530 if self.selection_mark_mode {
14531 self.change_selections(None, window, cx, |s| {
14532 s.move_with(|_, sel| {
14533 sel.collapse_to(sel.head(), SelectionGoal::None);
14534 });
14535 })
14536 }
14537 self.selection_mark_mode = true;
14538 cx.notify();
14539 }
14540
14541 pub fn swap_selection_ends(
14542 &mut self,
14543 _: &actions::SwapSelectionEnds,
14544 window: &mut Window,
14545 cx: &mut Context<Self>,
14546 ) {
14547 self.change_selections(None, window, cx, |s| {
14548 s.move_with(|_, sel| {
14549 if sel.start != sel.end {
14550 sel.reversed = !sel.reversed
14551 }
14552 });
14553 });
14554 self.request_autoscroll(Autoscroll::newest(), cx);
14555 cx.notify();
14556 }
14557
14558 pub fn toggle_fold(
14559 &mut self,
14560 _: &actions::ToggleFold,
14561 window: &mut Window,
14562 cx: &mut Context<Self>,
14563 ) {
14564 if self.is_singleton(cx) {
14565 let selection = self.selections.newest::<Point>(cx);
14566
14567 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14568 let range = if selection.is_empty() {
14569 let point = selection.head().to_display_point(&display_map);
14570 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14571 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14572 .to_point(&display_map);
14573 start..end
14574 } else {
14575 selection.range()
14576 };
14577 if display_map.folds_in_range(range).next().is_some() {
14578 self.unfold_lines(&Default::default(), window, cx)
14579 } else {
14580 self.fold(&Default::default(), window, cx)
14581 }
14582 } else {
14583 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14584 let buffer_ids: HashSet<_> = self
14585 .selections
14586 .disjoint_anchor_ranges()
14587 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14588 .collect();
14589
14590 let should_unfold = buffer_ids
14591 .iter()
14592 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14593
14594 for buffer_id in buffer_ids {
14595 if should_unfold {
14596 self.unfold_buffer(buffer_id, cx);
14597 } else {
14598 self.fold_buffer(buffer_id, cx);
14599 }
14600 }
14601 }
14602 }
14603
14604 pub fn toggle_fold_recursive(
14605 &mut self,
14606 _: &actions::ToggleFoldRecursive,
14607 window: &mut Window,
14608 cx: &mut Context<Self>,
14609 ) {
14610 let selection = self.selections.newest::<Point>(cx);
14611
14612 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14613 let range = if selection.is_empty() {
14614 let point = selection.head().to_display_point(&display_map);
14615 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14616 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14617 .to_point(&display_map);
14618 start..end
14619 } else {
14620 selection.range()
14621 };
14622 if display_map.folds_in_range(range).next().is_some() {
14623 self.unfold_recursive(&Default::default(), window, cx)
14624 } else {
14625 self.fold_recursive(&Default::default(), window, cx)
14626 }
14627 }
14628
14629 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14630 if self.is_singleton(cx) {
14631 let mut to_fold = Vec::new();
14632 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14633 let selections = self.selections.all_adjusted(cx);
14634
14635 for selection in selections {
14636 let range = selection.range().sorted();
14637 let buffer_start_row = range.start.row;
14638
14639 if range.start.row != range.end.row {
14640 let mut found = false;
14641 let mut row = range.start.row;
14642 while row <= range.end.row {
14643 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14644 {
14645 found = true;
14646 row = crease.range().end.row + 1;
14647 to_fold.push(crease);
14648 } else {
14649 row += 1
14650 }
14651 }
14652 if found {
14653 continue;
14654 }
14655 }
14656
14657 for row in (0..=range.start.row).rev() {
14658 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14659 if crease.range().end.row >= buffer_start_row {
14660 to_fold.push(crease);
14661 if row <= range.start.row {
14662 break;
14663 }
14664 }
14665 }
14666 }
14667 }
14668
14669 self.fold_creases(to_fold, true, window, cx);
14670 } else {
14671 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14672 let buffer_ids = self
14673 .selections
14674 .disjoint_anchor_ranges()
14675 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14676 .collect::<HashSet<_>>();
14677 for buffer_id in buffer_ids {
14678 self.fold_buffer(buffer_id, cx);
14679 }
14680 }
14681 }
14682
14683 fn fold_at_level(
14684 &mut self,
14685 fold_at: &FoldAtLevel,
14686 window: &mut Window,
14687 cx: &mut Context<Self>,
14688 ) {
14689 if !self.buffer.read(cx).is_singleton() {
14690 return;
14691 }
14692
14693 let fold_at_level = fold_at.0;
14694 let snapshot = self.buffer.read(cx).snapshot(cx);
14695 let mut to_fold = Vec::new();
14696 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14697
14698 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14699 while start_row < end_row {
14700 match self
14701 .snapshot(window, cx)
14702 .crease_for_buffer_row(MultiBufferRow(start_row))
14703 {
14704 Some(crease) => {
14705 let nested_start_row = crease.range().start.row + 1;
14706 let nested_end_row = crease.range().end.row;
14707
14708 if current_level < fold_at_level {
14709 stack.push((nested_start_row, nested_end_row, current_level + 1));
14710 } else if current_level == fold_at_level {
14711 to_fold.push(crease);
14712 }
14713
14714 start_row = nested_end_row + 1;
14715 }
14716 None => start_row += 1,
14717 }
14718 }
14719 }
14720
14721 self.fold_creases(to_fold, true, window, cx);
14722 }
14723
14724 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14725 if self.buffer.read(cx).is_singleton() {
14726 let mut fold_ranges = Vec::new();
14727 let snapshot = self.buffer.read(cx).snapshot(cx);
14728
14729 for row in 0..snapshot.max_row().0 {
14730 if let Some(foldable_range) = self
14731 .snapshot(window, cx)
14732 .crease_for_buffer_row(MultiBufferRow(row))
14733 {
14734 fold_ranges.push(foldable_range);
14735 }
14736 }
14737
14738 self.fold_creases(fold_ranges, true, window, cx);
14739 } else {
14740 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14741 editor
14742 .update_in(cx, |editor, _, cx| {
14743 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14744 editor.fold_buffer(buffer_id, cx);
14745 }
14746 })
14747 .ok();
14748 });
14749 }
14750 }
14751
14752 pub fn fold_function_bodies(
14753 &mut self,
14754 _: &actions::FoldFunctionBodies,
14755 window: &mut Window,
14756 cx: &mut Context<Self>,
14757 ) {
14758 let snapshot = self.buffer.read(cx).snapshot(cx);
14759
14760 let ranges = snapshot
14761 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14762 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14763 .collect::<Vec<_>>();
14764
14765 let creases = ranges
14766 .into_iter()
14767 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14768 .collect();
14769
14770 self.fold_creases(creases, true, window, cx);
14771 }
14772
14773 pub fn fold_recursive(
14774 &mut self,
14775 _: &actions::FoldRecursive,
14776 window: &mut Window,
14777 cx: &mut Context<Self>,
14778 ) {
14779 let mut to_fold = Vec::new();
14780 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14781 let selections = self.selections.all_adjusted(cx);
14782
14783 for selection in selections {
14784 let range = selection.range().sorted();
14785 let buffer_start_row = range.start.row;
14786
14787 if range.start.row != range.end.row {
14788 let mut found = false;
14789 for row in range.start.row..=range.end.row {
14790 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14791 found = true;
14792 to_fold.push(crease);
14793 }
14794 }
14795 if found {
14796 continue;
14797 }
14798 }
14799
14800 for row in (0..=range.start.row).rev() {
14801 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14802 if crease.range().end.row >= buffer_start_row {
14803 to_fold.push(crease);
14804 } else {
14805 break;
14806 }
14807 }
14808 }
14809 }
14810
14811 self.fold_creases(to_fold, true, window, cx);
14812 }
14813
14814 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14815 let buffer_row = fold_at.buffer_row;
14816 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14817
14818 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14819 let autoscroll = self
14820 .selections
14821 .all::<Point>(cx)
14822 .iter()
14823 .any(|selection| crease.range().overlaps(&selection.range()));
14824
14825 self.fold_creases(vec![crease], autoscroll, window, cx);
14826 }
14827 }
14828
14829 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14830 if self.is_singleton(cx) {
14831 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14832 let buffer = &display_map.buffer_snapshot;
14833 let selections = self.selections.all::<Point>(cx);
14834 let ranges = selections
14835 .iter()
14836 .map(|s| {
14837 let range = s.display_range(&display_map).sorted();
14838 let mut start = range.start.to_point(&display_map);
14839 let mut end = range.end.to_point(&display_map);
14840 start.column = 0;
14841 end.column = buffer.line_len(MultiBufferRow(end.row));
14842 start..end
14843 })
14844 .collect::<Vec<_>>();
14845
14846 self.unfold_ranges(&ranges, true, true, cx);
14847 } else {
14848 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14849 let buffer_ids = self
14850 .selections
14851 .disjoint_anchor_ranges()
14852 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14853 .collect::<HashSet<_>>();
14854 for buffer_id in buffer_ids {
14855 self.unfold_buffer(buffer_id, cx);
14856 }
14857 }
14858 }
14859
14860 pub fn unfold_recursive(
14861 &mut self,
14862 _: &UnfoldRecursive,
14863 _window: &mut Window,
14864 cx: &mut Context<Self>,
14865 ) {
14866 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14867 let selections = self.selections.all::<Point>(cx);
14868 let ranges = selections
14869 .iter()
14870 .map(|s| {
14871 let mut range = s.display_range(&display_map).sorted();
14872 *range.start.column_mut() = 0;
14873 *range.end.column_mut() = display_map.line_len(range.end.row());
14874 let start = range.start.to_point(&display_map);
14875 let end = range.end.to_point(&display_map);
14876 start..end
14877 })
14878 .collect::<Vec<_>>();
14879
14880 self.unfold_ranges(&ranges, true, true, cx);
14881 }
14882
14883 pub fn unfold_at(
14884 &mut self,
14885 unfold_at: &UnfoldAt,
14886 _window: &mut Window,
14887 cx: &mut Context<Self>,
14888 ) {
14889 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14890
14891 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14892 ..Point::new(
14893 unfold_at.buffer_row.0,
14894 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14895 );
14896
14897 let autoscroll = self
14898 .selections
14899 .all::<Point>(cx)
14900 .iter()
14901 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14902
14903 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14904 }
14905
14906 pub fn unfold_all(
14907 &mut self,
14908 _: &actions::UnfoldAll,
14909 _window: &mut Window,
14910 cx: &mut Context<Self>,
14911 ) {
14912 if self.buffer.read(cx).is_singleton() {
14913 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14914 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14915 } else {
14916 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14917 editor
14918 .update(cx, |editor, cx| {
14919 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14920 editor.unfold_buffer(buffer_id, cx);
14921 }
14922 })
14923 .ok();
14924 });
14925 }
14926 }
14927
14928 pub fn fold_selected_ranges(
14929 &mut self,
14930 _: &FoldSelectedRanges,
14931 window: &mut Window,
14932 cx: &mut Context<Self>,
14933 ) {
14934 let selections = self.selections.all_adjusted(cx);
14935 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14936 let ranges = selections
14937 .into_iter()
14938 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
14939 .collect::<Vec<_>>();
14940 self.fold_creases(ranges, true, window, cx);
14941 }
14942
14943 pub fn fold_ranges<T: ToOffset + Clone>(
14944 &mut self,
14945 ranges: Vec<Range<T>>,
14946 auto_scroll: bool,
14947 window: &mut Window,
14948 cx: &mut Context<Self>,
14949 ) {
14950 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14951 let ranges = ranges
14952 .into_iter()
14953 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14954 .collect::<Vec<_>>();
14955 self.fold_creases(ranges, auto_scroll, window, cx);
14956 }
14957
14958 pub fn fold_creases<T: ToOffset + Clone>(
14959 &mut self,
14960 creases: Vec<Crease<T>>,
14961 auto_scroll: bool,
14962 window: &mut Window,
14963 cx: &mut Context<Self>,
14964 ) {
14965 if creases.is_empty() {
14966 return;
14967 }
14968
14969 let mut buffers_affected = HashSet::default();
14970 let multi_buffer = self.buffer().read(cx);
14971 for crease in &creases {
14972 if let Some((_, buffer, _)) =
14973 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14974 {
14975 buffers_affected.insert(buffer.read(cx).remote_id());
14976 };
14977 }
14978
14979 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14980
14981 if auto_scroll {
14982 self.request_autoscroll(Autoscroll::fit(), cx);
14983 }
14984
14985 cx.notify();
14986
14987 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14988 // Clear diagnostics block when folding a range that contains it.
14989 let snapshot = self.snapshot(window, cx);
14990 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14991 drop(snapshot);
14992 self.active_diagnostics = Some(active_diagnostics);
14993 self.dismiss_diagnostics(cx);
14994 } else {
14995 self.active_diagnostics = Some(active_diagnostics);
14996 }
14997 }
14998
14999 self.scrollbar_marker_state.dirty = true;
15000 self.folds_did_change(cx);
15001 }
15002
15003 /// Removes any folds whose ranges intersect any of the given ranges.
15004 pub fn unfold_ranges<T: ToOffset + Clone>(
15005 &mut self,
15006 ranges: &[Range<T>],
15007 inclusive: bool,
15008 auto_scroll: bool,
15009 cx: &mut Context<Self>,
15010 ) {
15011 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15012 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15013 });
15014 self.folds_did_change(cx);
15015 }
15016
15017 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15018 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15019 return;
15020 }
15021 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15022 self.display_map.update(cx, |display_map, cx| {
15023 display_map.fold_buffers([buffer_id], cx)
15024 });
15025 cx.emit(EditorEvent::BufferFoldToggled {
15026 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15027 folded: true,
15028 });
15029 cx.notify();
15030 }
15031
15032 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15033 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15034 return;
15035 }
15036 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15037 self.display_map.update(cx, |display_map, cx| {
15038 display_map.unfold_buffers([buffer_id], cx);
15039 });
15040 cx.emit(EditorEvent::BufferFoldToggled {
15041 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15042 folded: false,
15043 });
15044 cx.notify();
15045 }
15046
15047 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15048 self.display_map.read(cx).is_buffer_folded(buffer)
15049 }
15050
15051 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15052 self.display_map.read(cx).folded_buffers()
15053 }
15054
15055 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15056 self.display_map.update(cx, |display_map, cx| {
15057 display_map.disable_header_for_buffer(buffer_id, cx);
15058 });
15059 cx.notify();
15060 }
15061
15062 /// Removes any folds with the given ranges.
15063 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15064 &mut self,
15065 ranges: &[Range<T>],
15066 type_id: TypeId,
15067 auto_scroll: bool,
15068 cx: &mut Context<Self>,
15069 ) {
15070 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15071 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15072 });
15073 self.folds_did_change(cx);
15074 }
15075
15076 fn remove_folds_with<T: ToOffset + Clone>(
15077 &mut self,
15078 ranges: &[Range<T>],
15079 auto_scroll: bool,
15080 cx: &mut Context<Self>,
15081 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15082 ) {
15083 if ranges.is_empty() {
15084 return;
15085 }
15086
15087 let mut buffers_affected = HashSet::default();
15088 let multi_buffer = self.buffer().read(cx);
15089 for range in ranges {
15090 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15091 buffers_affected.insert(buffer.read(cx).remote_id());
15092 };
15093 }
15094
15095 self.display_map.update(cx, update);
15096
15097 if auto_scroll {
15098 self.request_autoscroll(Autoscroll::fit(), cx);
15099 }
15100
15101 cx.notify();
15102 self.scrollbar_marker_state.dirty = true;
15103 self.active_indent_guides_state.dirty = true;
15104 }
15105
15106 pub fn update_fold_widths(
15107 &mut self,
15108 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15109 cx: &mut Context<Self>,
15110 ) -> bool {
15111 self.display_map
15112 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15113 }
15114
15115 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15116 self.display_map.read(cx).fold_placeholder.clone()
15117 }
15118
15119 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15120 self.buffer.update(cx, |buffer, cx| {
15121 buffer.set_all_diff_hunks_expanded(cx);
15122 });
15123 }
15124
15125 pub fn expand_all_diff_hunks(
15126 &mut self,
15127 _: &ExpandAllDiffHunks,
15128 _window: &mut Window,
15129 cx: &mut Context<Self>,
15130 ) {
15131 self.buffer.update(cx, |buffer, cx| {
15132 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15133 });
15134 }
15135
15136 pub fn toggle_selected_diff_hunks(
15137 &mut self,
15138 _: &ToggleSelectedDiffHunks,
15139 _window: &mut Window,
15140 cx: &mut Context<Self>,
15141 ) {
15142 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15143 self.toggle_diff_hunks_in_ranges(ranges, cx);
15144 }
15145
15146 pub fn diff_hunks_in_ranges<'a>(
15147 &'a self,
15148 ranges: &'a [Range<Anchor>],
15149 buffer: &'a MultiBufferSnapshot,
15150 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15151 ranges.iter().flat_map(move |range| {
15152 let end_excerpt_id = range.end.excerpt_id;
15153 let range = range.to_point(buffer);
15154 let mut peek_end = range.end;
15155 if range.end.row < buffer.max_row().0 {
15156 peek_end = Point::new(range.end.row + 1, 0);
15157 }
15158 buffer
15159 .diff_hunks_in_range(range.start..peek_end)
15160 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15161 })
15162 }
15163
15164 pub fn has_stageable_diff_hunks_in_ranges(
15165 &self,
15166 ranges: &[Range<Anchor>],
15167 snapshot: &MultiBufferSnapshot,
15168 ) -> bool {
15169 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15170 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15171 }
15172
15173 pub fn toggle_staged_selected_diff_hunks(
15174 &mut self,
15175 _: &::git::ToggleStaged,
15176 _: &mut Window,
15177 cx: &mut Context<Self>,
15178 ) {
15179 let snapshot = self.buffer.read(cx).snapshot(cx);
15180 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15181 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15182 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15183 }
15184
15185 pub fn set_render_diff_hunk_controls(
15186 &mut self,
15187 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15188 cx: &mut Context<Self>,
15189 ) {
15190 self.render_diff_hunk_controls = render_diff_hunk_controls;
15191 cx.notify();
15192 }
15193
15194 pub fn stage_and_next(
15195 &mut self,
15196 _: &::git::StageAndNext,
15197 window: &mut Window,
15198 cx: &mut Context<Self>,
15199 ) {
15200 self.do_stage_or_unstage_and_next(true, window, cx);
15201 }
15202
15203 pub fn unstage_and_next(
15204 &mut self,
15205 _: &::git::UnstageAndNext,
15206 window: &mut Window,
15207 cx: &mut Context<Self>,
15208 ) {
15209 self.do_stage_or_unstage_and_next(false, window, cx);
15210 }
15211
15212 pub fn stage_or_unstage_diff_hunks(
15213 &mut self,
15214 stage: bool,
15215 ranges: Vec<Range<Anchor>>,
15216 cx: &mut Context<Self>,
15217 ) {
15218 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15219 cx.spawn(async move |this, cx| {
15220 task.await?;
15221 this.update(cx, |this, cx| {
15222 let snapshot = this.buffer.read(cx).snapshot(cx);
15223 let chunk_by = this
15224 .diff_hunks_in_ranges(&ranges, &snapshot)
15225 .chunk_by(|hunk| hunk.buffer_id);
15226 for (buffer_id, hunks) in &chunk_by {
15227 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15228 }
15229 })
15230 })
15231 .detach_and_log_err(cx);
15232 }
15233
15234 fn save_buffers_for_ranges_if_needed(
15235 &mut self,
15236 ranges: &[Range<Anchor>],
15237 cx: &mut Context<Editor>,
15238 ) -> Task<Result<()>> {
15239 let multibuffer = self.buffer.read(cx);
15240 let snapshot = multibuffer.read(cx);
15241 let buffer_ids: HashSet<_> = ranges
15242 .iter()
15243 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15244 .collect();
15245 drop(snapshot);
15246
15247 let mut buffers = HashSet::default();
15248 for buffer_id in buffer_ids {
15249 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15250 let buffer = buffer_entity.read(cx);
15251 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15252 {
15253 buffers.insert(buffer_entity);
15254 }
15255 }
15256 }
15257
15258 if let Some(project) = &self.project {
15259 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15260 } else {
15261 Task::ready(Ok(()))
15262 }
15263 }
15264
15265 fn do_stage_or_unstage_and_next(
15266 &mut self,
15267 stage: bool,
15268 window: &mut Window,
15269 cx: &mut Context<Self>,
15270 ) {
15271 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15272
15273 if ranges.iter().any(|range| range.start != range.end) {
15274 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15275 return;
15276 }
15277
15278 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15279 let snapshot = self.snapshot(window, cx);
15280 let position = self.selections.newest::<Point>(cx).head();
15281 let mut row = snapshot
15282 .buffer_snapshot
15283 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15284 .find(|hunk| hunk.row_range.start.0 > position.row)
15285 .map(|hunk| hunk.row_range.start);
15286
15287 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15288 // Outside of the project diff editor, wrap around to the beginning.
15289 if !all_diff_hunks_expanded {
15290 row = row.or_else(|| {
15291 snapshot
15292 .buffer_snapshot
15293 .diff_hunks_in_range(Point::zero()..position)
15294 .find(|hunk| hunk.row_range.end.0 < position.row)
15295 .map(|hunk| hunk.row_range.start)
15296 });
15297 }
15298
15299 if let Some(row) = row {
15300 let destination = Point::new(row.0, 0);
15301 let autoscroll = Autoscroll::center();
15302
15303 self.unfold_ranges(&[destination..destination], false, false, cx);
15304 self.change_selections(Some(autoscroll), window, cx, |s| {
15305 s.select_ranges([destination..destination]);
15306 });
15307 }
15308 }
15309
15310 fn do_stage_or_unstage(
15311 &self,
15312 stage: bool,
15313 buffer_id: BufferId,
15314 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15315 cx: &mut App,
15316 ) -> Option<()> {
15317 let project = self.project.as_ref()?;
15318 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15319 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15320 let buffer_snapshot = buffer.read(cx).snapshot();
15321 let file_exists = buffer_snapshot
15322 .file()
15323 .is_some_and(|file| file.disk_state().exists());
15324 diff.update(cx, |diff, cx| {
15325 diff.stage_or_unstage_hunks(
15326 stage,
15327 &hunks
15328 .map(|hunk| buffer_diff::DiffHunk {
15329 buffer_range: hunk.buffer_range,
15330 diff_base_byte_range: hunk.diff_base_byte_range,
15331 secondary_status: hunk.secondary_status,
15332 range: Point::zero()..Point::zero(), // unused
15333 })
15334 .collect::<Vec<_>>(),
15335 &buffer_snapshot,
15336 file_exists,
15337 cx,
15338 )
15339 });
15340 None
15341 }
15342
15343 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15344 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15345 self.buffer
15346 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15347 }
15348
15349 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15350 self.buffer.update(cx, |buffer, cx| {
15351 let ranges = vec![Anchor::min()..Anchor::max()];
15352 if !buffer.all_diff_hunks_expanded()
15353 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15354 {
15355 buffer.collapse_diff_hunks(ranges, cx);
15356 true
15357 } else {
15358 false
15359 }
15360 })
15361 }
15362
15363 fn toggle_diff_hunks_in_ranges(
15364 &mut self,
15365 ranges: Vec<Range<Anchor>>,
15366 cx: &mut Context<Editor>,
15367 ) {
15368 self.buffer.update(cx, |buffer, cx| {
15369 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15370 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15371 })
15372 }
15373
15374 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15375 self.buffer.update(cx, |buffer, cx| {
15376 let snapshot = buffer.snapshot(cx);
15377 let excerpt_id = range.end.excerpt_id;
15378 let point_range = range.to_point(&snapshot);
15379 let expand = !buffer.single_hunk_is_expanded(range, cx);
15380 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15381 })
15382 }
15383
15384 pub(crate) fn apply_all_diff_hunks(
15385 &mut self,
15386 _: &ApplyAllDiffHunks,
15387 window: &mut Window,
15388 cx: &mut Context<Self>,
15389 ) {
15390 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15391
15392 let buffers = self.buffer.read(cx).all_buffers();
15393 for branch_buffer in buffers {
15394 branch_buffer.update(cx, |branch_buffer, cx| {
15395 branch_buffer.merge_into_base(Vec::new(), cx);
15396 });
15397 }
15398
15399 if let Some(project) = self.project.clone() {
15400 self.save(true, project, window, cx).detach_and_log_err(cx);
15401 }
15402 }
15403
15404 pub(crate) fn apply_selected_diff_hunks(
15405 &mut self,
15406 _: &ApplyDiffHunk,
15407 window: &mut Window,
15408 cx: &mut Context<Self>,
15409 ) {
15410 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15411 let snapshot = self.snapshot(window, cx);
15412 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15413 let mut ranges_by_buffer = HashMap::default();
15414 self.transact(window, cx, |editor, _window, cx| {
15415 for hunk in hunks {
15416 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15417 ranges_by_buffer
15418 .entry(buffer.clone())
15419 .or_insert_with(Vec::new)
15420 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15421 }
15422 }
15423
15424 for (buffer, ranges) in ranges_by_buffer {
15425 buffer.update(cx, |buffer, cx| {
15426 buffer.merge_into_base(ranges, cx);
15427 });
15428 }
15429 });
15430
15431 if let Some(project) = self.project.clone() {
15432 self.save(true, project, window, cx).detach_and_log_err(cx);
15433 }
15434 }
15435
15436 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15437 if hovered != self.gutter_hovered {
15438 self.gutter_hovered = hovered;
15439 cx.notify();
15440 }
15441 }
15442
15443 pub fn insert_blocks(
15444 &mut self,
15445 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15446 autoscroll: Option<Autoscroll>,
15447 cx: &mut Context<Self>,
15448 ) -> Vec<CustomBlockId> {
15449 let blocks = self
15450 .display_map
15451 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15452 if let Some(autoscroll) = autoscroll {
15453 self.request_autoscroll(autoscroll, cx);
15454 }
15455 cx.notify();
15456 blocks
15457 }
15458
15459 pub fn resize_blocks(
15460 &mut self,
15461 heights: HashMap<CustomBlockId, u32>,
15462 autoscroll: Option<Autoscroll>,
15463 cx: &mut Context<Self>,
15464 ) {
15465 self.display_map
15466 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15467 if let Some(autoscroll) = autoscroll {
15468 self.request_autoscroll(autoscroll, cx);
15469 }
15470 cx.notify();
15471 }
15472
15473 pub fn replace_blocks(
15474 &mut self,
15475 renderers: HashMap<CustomBlockId, RenderBlock>,
15476 autoscroll: Option<Autoscroll>,
15477 cx: &mut Context<Self>,
15478 ) {
15479 self.display_map
15480 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15481 if let Some(autoscroll) = autoscroll {
15482 self.request_autoscroll(autoscroll, cx);
15483 }
15484 cx.notify();
15485 }
15486
15487 pub fn remove_blocks(
15488 &mut self,
15489 block_ids: HashSet<CustomBlockId>,
15490 autoscroll: Option<Autoscroll>,
15491 cx: &mut Context<Self>,
15492 ) {
15493 self.display_map.update(cx, |display_map, cx| {
15494 display_map.remove_blocks(block_ids, cx)
15495 });
15496 if let Some(autoscroll) = autoscroll {
15497 self.request_autoscroll(autoscroll, cx);
15498 }
15499 cx.notify();
15500 }
15501
15502 pub fn row_for_block(
15503 &self,
15504 block_id: CustomBlockId,
15505 cx: &mut Context<Self>,
15506 ) -> Option<DisplayRow> {
15507 self.display_map
15508 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15509 }
15510
15511 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15512 self.focused_block = Some(focused_block);
15513 }
15514
15515 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15516 self.focused_block.take()
15517 }
15518
15519 pub fn insert_creases(
15520 &mut self,
15521 creases: impl IntoIterator<Item = Crease<Anchor>>,
15522 cx: &mut Context<Self>,
15523 ) -> Vec<CreaseId> {
15524 self.display_map
15525 .update(cx, |map, cx| map.insert_creases(creases, cx))
15526 }
15527
15528 pub fn remove_creases(
15529 &mut self,
15530 ids: impl IntoIterator<Item = CreaseId>,
15531 cx: &mut Context<Self>,
15532 ) {
15533 self.display_map
15534 .update(cx, |map, cx| map.remove_creases(ids, cx));
15535 }
15536
15537 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15538 self.display_map
15539 .update(cx, |map, cx| map.snapshot(cx))
15540 .longest_row()
15541 }
15542
15543 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15544 self.display_map
15545 .update(cx, |map, cx| map.snapshot(cx))
15546 .max_point()
15547 }
15548
15549 pub fn text(&self, cx: &App) -> String {
15550 self.buffer.read(cx).read(cx).text()
15551 }
15552
15553 pub fn is_empty(&self, cx: &App) -> bool {
15554 self.buffer.read(cx).read(cx).is_empty()
15555 }
15556
15557 pub fn text_option(&self, cx: &App) -> Option<String> {
15558 let text = self.text(cx);
15559 let text = text.trim();
15560
15561 if text.is_empty() {
15562 return None;
15563 }
15564
15565 Some(text.to_string())
15566 }
15567
15568 pub fn set_text(
15569 &mut self,
15570 text: impl Into<Arc<str>>,
15571 window: &mut Window,
15572 cx: &mut Context<Self>,
15573 ) {
15574 self.transact(window, cx, |this, _, cx| {
15575 this.buffer
15576 .read(cx)
15577 .as_singleton()
15578 .expect("you can only call set_text on editors for singleton buffers")
15579 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15580 });
15581 }
15582
15583 pub fn display_text(&self, cx: &mut App) -> String {
15584 self.display_map
15585 .update(cx, |map, cx| map.snapshot(cx))
15586 .text()
15587 }
15588
15589 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15590 let mut wrap_guides = smallvec::smallvec![];
15591
15592 if self.show_wrap_guides == Some(false) {
15593 return wrap_guides;
15594 }
15595
15596 let settings = self.buffer.read(cx).language_settings(cx);
15597 if settings.show_wrap_guides {
15598 match self.soft_wrap_mode(cx) {
15599 SoftWrap::Column(soft_wrap) => {
15600 wrap_guides.push((soft_wrap as usize, true));
15601 }
15602 SoftWrap::Bounded(soft_wrap) => {
15603 wrap_guides.push((soft_wrap as usize, true));
15604 }
15605 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15606 }
15607 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15608 }
15609
15610 wrap_guides
15611 }
15612
15613 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15614 let settings = self.buffer.read(cx).language_settings(cx);
15615 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15616 match mode {
15617 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15618 SoftWrap::None
15619 }
15620 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15621 language_settings::SoftWrap::PreferredLineLength => {
15622 SoftWrap::Column(settings.preferred_line_length)
15623 }
15624 language_settings::SoftWrap::Bounded => {
15625 SoftWrap::Bounded(settings.preferred_line_length)
15626 }
15627 }
15628 }
15629
15630 pub fn set_soft_wrap_mode(
15631 &mut self,
15632 mode: language_settings::SoftWrap,
15633
15634 cx: &mut Context<Self>,
15635 ) {
15636 self.soft_wrap_mode_override = Some(mode);
15637 cx.notify();
15638 }
15639
15640 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15641 self.hard_wrap = hard_wrap;
15642 cx.notify();
15643 }
15644
15645 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15646 self.text_style_refinement = Some(style);
15647 }
15648
15649 /// called by the Element so we know what style we were most recently rendered with.
15650 pub(crate) fn set_style(
15651 &mut self,
15652 style: EditorStyle,
15653 window: &mut Window,
15654 cx: &mut Context<Self>,
15655 ) {
15656 let rem_size = window.rem_size();
15657 self.display_map.update(cx, |map, cx| {
15658 map.set_font(
15659 style.text.font(),
15660 style.text.font_size.to_pixels(rem_size),
15661 cx,
15662 )
15663 });
15664 self.style = Some(style);
15665 }
15666
15667 pub fn style(&self) -> Option<&EditorStyle> {
15668 self.style.as_ref()
15669 }
15670
15671 // Called by the element. This method is not designed to be called outside of the editor
15672 // element's layout code because it does not notify when rewrapping is computed synchronously.
15673 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15674 self.display_map
15675 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15676 }
15677
15678 pub fn set_soft_wrap(&mut self) {
15679 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15680 }
15681
15682 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15683 if self.soft_wrap_mode_override.is_some() {
15684 self.soft_wrap_mode_override.take();
15685 } else {
15686 let soft_wrap = match self.soft_wrap_mode(cx) {
15687 SoftWrap::GitDiff => return,
15688 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15689 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15690 language_settings::SoftWrap::None
15691 }
15692 };
15693 self.soft_wrap_mode_override = Some(soft_wrap);
15694 }
15695 cx.notify();
15696 }
15697
15698 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15699 let Some(workspace) = self.workspace() else {
15700 return;
15701 };
15702 let fs = workspace.read(cx).app_state().fs.clone();
15703 let current_show = TabBarSettings::get_global(cx).show;
15704 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15705 setting.show = Some(!current_show);
15706 });
15707 }
15708
15709 pub fn toggle_indent_guides(
15710 &mut self,
15711 _: &ToggleIndentGuides,
15712 _: &mut Window,
15713 cx: &mut Context<Self>,
15714 ) {
15715 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15716 self.buffer
15717 .read(cx)
15718 .language_settings(cx)
15719 .indent_guides
15720 .enabled
15721 });
15722 self.show_indent_guides = Some(!currently_enabled);
15723 cx.notify();
15724 }
15725
15726 fn should_show_indent_guides(&self) -> Option<bool> {
15727 self.show_indent_guides
15728 }
15729
15730 pub fn toggle_line_numbers(
15731 &mut self,
15732 _: &ToggleLineNumbers,
15733 _: &mut Window,
15734 cx: &mut Context<Self>,
15735 ) {
15736 let mut editor_settings = EditorSettings::get_global(cx).clone();
15737 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15738 EditorSettings::override_global(editor_settings, cx);
15739 }
15740
15741 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15742 if let Some(show_line_numbers) = self.show_line_numbers {
15743 return show_line_numbers;
15744 }
15745 EditorSettings::get_global(cx).gutter.line_numbers
15746 }
15747
15748 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15749 self.use_relative_line_numbers
15750 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15751 }
15752
15753 pub fn toggle_relative_line_numbers(
15754 &mut self,
15755 _: &ToggleRelativeLineNumbers,
15756 _: &mut Window,
15757 cx: &mut Context<Self>,
15758 ) {
15759 let is_relative = self.should_use_relative_line_numbers(cx);
15760 self.set_relative_line_number(Some(!is_relative), cx)
15761 }
15762
15763 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15764 self.use_relative_line_numbers = is_relative;
15765 cx.notify();
15766 }
15767
15768 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15769 self.show_gutter = show_gutter;
15770 cx.notify();
15771 }
15772
15773 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15774 self.show_scrollbars = show_scrollbars;
15775 cx.notify();
15776 }
15777
15778 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15779 self.show_line_numbers = Some(show_line_numbers);
15780 cx.notify();
15781 }
15782
15783 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15784 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15785 cx.notify();
15786 }
15787
15788 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15789 self.show_code_actions = Some(show_code_actions);
15790 cx.notify();
15791 }
15792
15793 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15794 self.show_runnables = Some(show_runnables);
15795 cx.notify();
15796 }
15797
15798 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15799 self.show_breakpoints = Some(show_breakpoints);
15800 cx.notify();
15801 }
15802
15803 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15804 if self.display_map.read(cx).masked != masked {
15805 self.display_map.update(cx, |map, _| map.masked = masked);
15806 }
15807 cx.notify()
15808 }
15809
15810 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15811 self.show_wrap_guides = Some(show_wrap_guides);
15812 cx.notify();
15813 }
15814
15815 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15816 self.show_indent_guides = Some(show_indent_guides);
15817 cx.notify();
15818 }
15819
15820 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15821 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15822 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15823 if let Some(dir) = file.abs_path(cx).parent() {
15824 return Some(dir.to_owned());
15825 }
15826 }
15827
15828 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15829 return Some(project_path.path.to_path_buf());
15830 }
15831 }
15832
15833 None
15834 }
15835
15836 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15837 self.active_excerpt(cx)?
15838 .1
15839 .read(cx)
15840 .file()
15841 .and_then(|f| f.as_local())
15842 }
15843
15844 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15845 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15846 let buffer = buffer.read(cx);
15847 if let Some(project_path) = buffer.project_path(cx) {
15848 let project = self.project.as_ref()?.read(cx);
15849 project.absolute_path(&project_path, cx)
15850 } else {
15851 buffer
15852 .file()
15853 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15854 }
15855 })
15856 }
15857
15858 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15859 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15860 let project_path = buffer.read(cx).project_path(cx)?;
15861 let project = self.project.as_ref()?.read(cx);
15862 let entry = project.entry_for_path(&project_path, cx)?;
15863 let path = entry.path.to_path_buf();
15864 Some(path)
15865 })
15866 }
15867
15868 pub fn reveal_in_finder(
15869 &mut self,
15870 _: &RevealInFileManager,
15871 _window: &mut Window,
15872 cx: &mut Context<Self>,
15873 ) {
15874 if let Some(target) = self.target_file(cx) {
15875 cx.reveal_path(&target.abs_path(cx));
15876 }
15877 }
15878
15879 pub fn copy_path(
15880 &mut self,
15881 _: &zed_actions::workspace::CopyPath,
15882 _window: &mut Window,
15883 cx: &mut Context<Self>,
15884 ) {
15885 if let Some(path) = self.target_file_abs_path(cx) {
15886 if let Some(path) = path.to_str() {
15887 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15888 }
15889 }
15890 }
15891
15892 pub fn copy_relative_path(
15893 &mut self,
15894 _: &zed_actions::workspace::CopyRelativePath,
15895 _window: &mut Window,
15896 cx: &mut Context<Self>,
15897 ) {
15898 if let Some(path) = self.target_file_path(cx) {
15899 if let Some(path) = path.to_str() {
15900 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15901 }
15902 }
15903 }
15904
15905 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15906 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15907 buffer.read(cx).project_path(cx)
15908 } else {
15909 None
15910 }
15911 }
15912
15913 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15914 let _ = maybe!({
15915 let breakpoint_store = self.breakpoint_store.as_ref()?;
15916
15917 let Some((_, _, active_position)) =
15918 breakpoint_store.read(cx).active_position().cloned()
15919 else {
15920 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15921 return None;
15922 };
15923
15924 let snapshot = self
15925 .project
15926 .as_ref()?
15927 .read(cx)
15928 .buffer_for_id(active_position.buffer_id?, cx)?
15929 .read(cx)
15930 .snapshot();
15931
15932 for (id, ExcerptRange { context, .. }) in self
15933 .buffer
15934 .read(cx)
15935 .excerpts_for_buffer(active_position.buffer_id?, cx)
15936 {
15937 if context.start.cmp(&active_position, &snapshot).is_ge()
15938 || context.end.cmp(&active_position, &snapshot).is_lt()
15939 {
15940 continue;
15941 }
15942 let snapshot = self.buffer.read(cx).snapshot(cx);
15943 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15944
15945 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15946 self.go_to_line::<DebugCurrentRowHighlight>(
15947 multibuffer_anchor,
15948 Some(cx.theme().colors().editor_debugger_active_line_background),
15949 window,
15950 cx,
15951 );
15952
15953 cx.notify();
15954 }
15955
15956 Some(())
15957 });
15958 }
15959
15960 pub fn copy_file_name_without_extension(
15961 &mut self,
15962 _: &CopyFileNameWithoutExtension,
15963 _: &mut Window,
15964 cx: &mut Context<Self>,
15965 ) {
15966 if let Some(file) = self.target_file(cx) {
15967 if let Some(file_stem) = file.path().file_stem() {
15968 if let Some(name) = file_stem.to_str() {
15969 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15970 }
15971 }
15972 }
15973 }
15974
15975 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15976 if let Some(file) = self.target_file(cx) {
15977 if let Some(file_name) = file.path().file_name() {
15978 if let Some(name) = file_name.to_str() {
15979 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15980 }
15981 }
15982 }
15983 }
15984
15985 pub fn toggle_git_blame(
15986 &mut self,
15987 _: &::git::Blame,
15988 window: &mut Window,
15989 cx: &mut Context<Self>,
15990 ) {
15991 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15992
15993 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15994 self.start_git_blame(true, window, cx);
15995 }
15996
15997 cx.notify();
15998 }
15999
16000 pub fn toggle_git_blame_inline(
16001 &mut self,
16002 _: &ToggleGitBlameInline,
16003 window: &mut Window,
16004 cx: &mut Context<Self>,
16005 ) {
16006 self.toggle_git_blame_inline_internal(true, window, cx);
16007 cx.notify();
16008 }
16009
16010 pub fn open_git_blame_commit(
16011 &mut self,
16012 _: &OpenGitBlameCommit,
16013 window: &mut Window,
16014 cx: &mut Context<Self>,
16015 ) {
16016 self.open_git_blame_commit_internal(window, cx);
16017 }
16018
16019 fn open_git_blame_commit_internal(
16020 &mut self,
16021 window: &mut Window,
16022 cx: &mut Context<Self>,
16023 ) -> Option<()> {
16024 let blame = self.blame.as_ref()?;
16025 let snapshot = self.snapshot(window, cx);
16026 let cursor = self.selections.newest::<Point>(cx).head();
16027 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16028 let blame_entry = blame
16029 .update(cx, |blame, cx| {
16030 blame
16031 .blame_for_rows(
16032 &[RowInfo {
16033 buffer_id: Some(buffer.remote_id()),
16034 buffer_row: Some(point.row),
16035 ..Default::default()
16036 }],
16037 cx,
16038 )
16039 .next()
16040 })
16041 .flatten()?;
16042 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16043 let repo = blame.read(cx).repository(cx)?;
16044 let workspace = self.workspace()?.downgrade();
16045 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16046 None
16047 }
16048
16049 pub fn git_blame_inline_enabled(&self) -> bool {
16050 self.git_blame_inline_enabled
16051 }
16052
16053 pub fn toggle_selection_menu(
16054 &mut self,
16055 _: &ToggleSelectionMenu,
16056 _: &mut Window,
16057 cx: &mut Context<Self>,
16058 ) {
16059 self.show_selection_menu = self
16060 .show_selection_menu
16061 .map(|show_selections_menu| !show_selections_menu)
16062 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16063
16064 cx.notify();
16065 }
16066
16067 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16068 self.show_selection_menu
16069 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16070 }
16071
16072 fn start_git_blame(
16073 &mut self,
16074 user_triggered: bool,
16075 window: &mut Window,
16076 cx: &mut Context<Self>,
16077 ) {
16078 if let Some(project) = self.project.as_ref() {
16079 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16080 return;
16081 };
16082
16083 if buffer.read(cx).file().is_none() {
16084 return;
16085 }
16086
16087 let focused = self.focus_handle(cx).contains_focused(window, cx);
16088
16089 let project = project.clone();
16090 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16091 self.blame_subscription =
16092 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16093 self.blame = Some(blame);
16094 }
16095 }
16096
16097 fn toggle_git_blame_inline_internal(
16098 &mut self,
16099 user_triggered: bool,
16100 window: &mut Window,
16101 cx: &mut Context<Self>,
16102 ) {
16103 if self.git_blame_inline_enabled {
16104 self.git_blame_inline_enabled = false;
16105 self.show_git_blame_inline = false;
16106 self.show_git_blame_inline_delay_task.take();
16107 } else {
16108 self.git_blame_inline_enabled = true;
16109 self.start_git_blame_inline(user_triggered, window, cx);
16110 }
16111
16112 cx.notify();
16113 }
16114
16115 fn start_git_blame_inline(
16116 &mut self,
16117 user_triggered: bool,
16118 window: &mut Window,
16119 cx: &mut Context<Self>,
16120 ) {
16121 self.start_git_blame(user_triggered, window, cx);
16122
16123 if ProjectSettings::get_global(cx)
16124 .git
16125 .inline_blame_delay()
16126 .is_some()
16127 {
16128 self.start_inline_blame_timer(window, cx);
16129 } else {
16130 self.show_git_blame_inline = true
16131 }
16132 }
16133
16134 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16135 self.blame.as_ref()
16136 }
16137
16138 pub fn show_git_blame_gutter(&self) -> bool {
16139 self.show_git_blame_gutter
16140 }
16141
16142 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16143 self.show_git_blame_gutter && self.has_blame_entries(cx)
16144 }
16145
16146 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16147 self.show_git_blame_inline
16148 && (self.focus_handle.is_focused(window)
16149 || self
16150 .git_blame_inline_tooltip
16151 .as_ref()
16152 .and_then(|t| t.upgrade())
16153 .is_some())
16154 && !self.newest_selection_head_on_empty_line(cx)
16155 && self.has_blame_entries(cx)
16156 }
16157
16158 fn has_blame_entries(&self, cx: &App) -> bool {
16159 self.blame()
16160 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16161 }
16162
16163 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16164 let cursor_anchor = self.selections.newest_anchor().head();
16165
16166 let snapshot = self.buffer.read(cx).snapshot(cx);
16167 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16168
16169 snapshot.line_len(buffer_row) == 0
16170 }
16171
16172 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16173 let buffer_and_selection = maybe!({
16174 let selection = self.selections.newest::<Point>(cx);
16175 let selection_range = selection.range();
16176
16177 let multi_buffer = self.buffer().read(cx);
16178 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16179 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16180
16181 let (buffer, range, _) = if selection.reversed {
16182 buffer_ranges.first()
16183 } else {
16184 buffer_ranges.last()
16185 }?;
16186
16187 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16188 ..text::ToPoint::to_point(&range.end, &buffer).row;
16189 Some((
16190 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16191 selection,
16192 ))
16193 });
16194
16195 let Some((buffer, selection)) = buffer_and_selection else {
16196 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16197 };
16198
16199 let Some(project) = self.project.as_ref() else {
16200 return Task::ready(Err(anyhow!("editor does not have project")));
16201 };
16202
16203 project.update(cx, |project, cx| {
16204 project.get_permalink_to_line(&buffer, selection, cx)
16205 })
16206 }
16207
16208 pub fn copy_permalink_to_line(
16209 &mut self,
16210 _: &CopyPermalinkToLine,
16211 window: &mut Window,
16212 cx: &mut Context<Self>,
16213 ) {
16214 let permalink_task = self.get_permalink_to_line(cx);
16215 let workspace = self.workspace();
16216
16217 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16218 Ok(permalink) => {
16219 cx.update(|_, cx| {
16220 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16221 })
16222 .ok();
16223 }
16224 Err(err) => {
16225 let message = format!("Failed to copy permalink: {err}");
16226
16227 Err::<(), anyhow::Error>(err).log_err();
16228
16229 if let Some(workspace) = workspace {
16230 workspace
16231 .update_in(cx, |workspace, _, cx| {
16232 struct CopyPermalinkToLine;
16233
16234 workspace.show_toast(
16235 Toast::new(
16236 NotificationId::unique::<CopyPermalinkToLine>(),
16237 message,
16238 ),
16239 cx,
16240 )
16241 })
16242 .ok();
16243 }
16244 }
16245 })
16246 .detach();
16247 }
16248
16249 pub fn copy_file_location(
16250 &mut self,
16251 _: &CopyFileLocation,
16252 _: &mut Window,
16253 cx: &mut Context<Self>,
16254 ) {
16255 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16256 if let Some(file) = self.target_file(cx) {
16257 if let Some(path) = file.path().to_str() {
16258 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16259 }
16260 }
16261 }
16262
16263 pub fn open_permalink_to_line(
16264 &mut self,
16265 _: &OpenPermalinkToLine,
16266 window: &mut Window,
16267 cx: &mut Context<Self>,
16268 ) {
16269 let permalink_task = self.get_permalink_to_line(cx);
16270 let workspace = self.workspace();
16271
16272 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16273 Ok(permalink) => {
16274 cx.update(|_, cx| {
16275 cx.open_url(permalink.as_ref());
16276 })
16277 .ok();
16278 }
16279 Err(err) => {
16280 let message = format!("Failed to open permalink: {err}");
16281
16282 Err::<(), anyhow::Error>(err).log_err();
16283
16284 if let Some(workspace) = workspace {
16285 workspace
16286 .update(cx, |workspace, cx| {
16287 struct OpenPermalinkToLine;
16288
16289 workspace.show_toast(
16290 Toast::new(
16291 NotificationId::unique::<OpenPermalinkToLine>(),
16292 message,
16293 ),
16294 cx,
16295 )
16296 })
16297 .ok();
16298 }
16299 }
16300 })
16301 .detach();
16302 }
16303
16304 pub fn insert_uuid_v4(
16305 &mut self,
16306 _: &InsertUuidV4,
16307 window: &mut Window,
16308 cx: &mut Context<Self>,
16309 ) {
16310 self.insert_uuid(UuidVersion::V4, window, cx);
16311 }
16312
16313 pub fn insert_uuid_v7(
16314 &mut self,
16315 _: &InsertUuidV7,
16316 window: &mut Window,
16317 cx: &mut Context<Self>,
16318 ) {
16319 self.insert_uuid(UuidVersion::V7, window, cx);
16320 }
16321
16322 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16323 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16324 self.transact(window, cx, |this, window, cx| {
16325 let edits = this
16326 .selections
16327 .all::<Point>(cx)
16328 .into_iter()
16329 .map(|selection| {
16330 let uuid = match version {
16331 UuidVersion::V4 => uuid::Uuid::new_v4(),
16332 UuidVersion::V7 => uuid::Uuid::now_v7(),
16333 };
16334
16335 (selection.range(), uuid.to_string())
16336 });
16337 this.edit(edits, cx);
16338 this.refresh_inline_completion(true, false, window, cx);
16339 });
16340 }
16341
16342 pub fn open_selections_in_multibuffer(
16343 &mut self,
16344 _: &OpenSelectionsInMultibuffer,
16345 window: &mut Window,
16346 cx: &mut Context<Self>,
16347 ) {
16348 let multibuffer = self.buffer.read(cx);
16349
16350 let Some(buffer) = multibuffer.as_singleton() else {
16351 return;
16352 };
16353
16354 let Some(workspace) = self.workspace() else {
16355 return;
16356 };
16357
16358 let locations = self
16359 .selections
16360 .disjoint_anchors()
16361 .iter()
16362 .map(|range| Location {
16363 buffer: buffer.clone(),
16364 range: range.start.text_anchor..range.end.text_anchor,
16365 })
16366 .collect::<Vec<_>>();
16367
16368 let title = multibuffer.title(cx).to_string();
16369
16370 cx.spawn_in(window, async move |_, cx| {
16371 workspace.update_in(cx, |workspace, window, cx| {
16372 Self::open_locations_in_multibuffer(
16373 workspace,
16374 locations,
16375 format!("Selections for '{title}'"),
16376 false,
16377 MultibufferSelectionMode::All,
16378 window,
16379 cx,
16380 );
16381 })
16382 })
16383 .detach();
16384 }
16385
16386 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16387 /// last highlight added will be used.
16388 ///
16389 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16390 pub fn highlight_rows<T: 'static>(
16391 &mut self,
16392 range: Range<Anchor>,
16393 color: Hsla,
16394 should_autoscroll: bool,
16395 cx: &mut Context<Self>,
16396 ) {
16397 let snapshot = self.buffer().read(cx).snapshot(cx);
16398 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16399 let ix = row_highlights.binary_search_by(|highlight| {
16400 Ordering::Equal
16401 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16402 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16403 });
16404
16405 if let Err(mut ix) = ix {
16406 let index = post_inc(&mut self.highlight_order);
16407
16408 // If this range intersects with the preceding highlight, then merge it with
16409 // the preceding highlight. Otherwise insert a new highlight.
16410 let mut merged = false;
16411 if ix > 0 {
16412 let prev_highlight = &mut row_highlights[ix - 1];
16413 if prev_highlight
16414 .range
16415 .end
16416 .cmp(&range.start, &snapshot)
16417 .is_ge()
16418 {
16419 ix -= 1;
16420 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16421 prev_highlight.range.end = range.end;
16422 }
16423 merged = true;
16424 prev_highlight.index = index;
16425 prev_highlight.color = color;
16426 prev_highlight.should_autoscroll = should_autoscroll;
16427 }
16428 }
16429
16430 if !merged {
16431 row_highlights.insert(
16432 ix,
16433 RowHighlight {
16434 range: range.clone(),
16435 index,
16436 color,
16437 should_autoscroll,
16438 },
16439 );
16440 }
16441
16442 // If any of the following highlights intersect with this one, merge them.
16443 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16444 let highlight = &row_highlights[ix];
16445 if next_highlight
16446 .range
16447 .start
16448 .cmp(&highlight.range.end, &snapshot)
16449 .is_le()
16450 {
16451 if next_highlight
16452 .range
16453 .end
16454 .cmp(&highlight.range.end, &snapshot)
16455 .is_gt()
16456 {
16457 row_highlights[ix].range.end = next_highlight.range.end;
16458 }
16459 row_highlights.remove(ix + 1);
16460 } else {
16461 break;
16462 }
16463 }
16464 }
16465 }
16466
16467 /// Remove any highlighted row ranges of the given type that intersect the
16468 /// given ranges.
16469 pub fn remove_highlighted_rows<T: 'static>(
16470 &mut self,
16471 ranges_to_remove: Vec<Range<Anchor>>,
16472 cx: &mut Context<Self>,
16473 ) {
16474 let snapshot = self.buffer().read(cx).snapshot(cx);
16475 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16476 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16477 row_highlights.retain(|highlight| {
16478 while let Some(range_to_remove) = ranges_to_remove.peek() {
16479 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16480 Ordering::Less | Ordering::Equal => {
16481 ranges_to_remove.next();
16482 }
16483 Ordering::Greater => {
16484 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16485 Ordering::Less | Ordering::Equal => {
16486 return false;
16487 }
16488 Ordering::Greater => break,
16489 }
16490 }
16491 }
16492 }
16493
16494 true
16495 })
16496 }
16497
16498 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16499 pub fn clear_row_highlights<T: 'static>(&mut self) {
16500 self.highlighted_rows.remove(&TypeId::of::<T>());
16501 }
16502
16503 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16504 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16505 self.highlighted_rows
16506 .get(&TypeId::of::<T>())
16507 .map_or(&[] as &[_], |vec| vec.as_slice())
16508 .iter()
16509 .map(|highlight| (highlight.range.clone(), highlight.color))
16510 }
16511
16512 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16513 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16514 /// Allows to ignore certain kinds of highlights.
16515 pub fn highlighted_display_rows(
16516 &self,
16517 window: &mut Window,
16518 cx: &mut App,
16519 ) -> BTreeMap<DisplayRow, LineHighlight> {
16520 let snapshot = self.snapshot(window, cx);
16521 let mut used_highlight_orders = HashMap::default();
16522 self.highlighted_rows
16523 .iter()
16524 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16525 .fold(
16526 BTreeMap::<DisplayRow, LineHighlight>::new(),
16527 |mut unique_rows, highlight| {
16528 let start = highlight.range.start.to_display_point(&snapshot);
16529 let end = highlight.range.end.to_display_point(&snapshot);
16530 let start_row = start.row().0;
16531 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16532 && end.column() == 0
16533 {
16534 end.row().0.saturating_sub(1)
16535 } else {
16536 end.row().0
16537 };
16538 for row in start_row..=end_row {
16539 let used_index =
16540 used_highlight_orders.entry(row).or_insert(highlight.index);
16541 if highlight.index >= *used_index {
16542 *used_index = highlight.index;
16543 unique_rows.insert(DisplayRow(row), highlight.color.into());
16544 }
16545 }
16546 unique_rows
16547 },
16548 )
16549 }
16550
16551 pub fn highlighted_display_row_for_autoscroll(
16552 &self,
16553 snapshot: &DisplaySnapshot,
16554 ) -> Option<DisplayRow> {
16555 self.highlighted_rows
16556 .values()
16557 .flat_map(|highlighted_rows| highlighted_rows.iter())
16558 .filter_map(|highlight| {
16559 if highlight.should_autoscroll {
16560 Some(highlight.range.start.to_display_point(snapshot).row())
16561 } else {
16562 None
16563 }
16564 })
16565 .min()
16566 }
16567
16568 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16569 self.highlight_background::<SearchWithinRange>(
16570 ranges,
16571 |colors| colors.editor_document_highlight_read_background,
16572 cx,
16573 )
16574 }
16575
16576 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16577 self.breadcrumb_header = Some(new_header);
16578 }
16579
16580 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16581 self.clear_background_highlights::<SearchWithinRange>(cx);
16582 }
16583
16584 pub fn highlight_background<T: 'static>(
16585 &mut self,
16586 ranges: &[Range<Anchor>],
16587 color_fetcher: fn(&ThemeColors) -> Hsla,
16588 cx: &mut Context<Self>,
16589 ) {
16590 self.background_highlights
16591 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16592 self.scrollbar_marker_state.dirty = true;
16593 cx.notify();
16594 }
16595
16596 pub fn clear_background_highlights<T: 'static>(
16597 &mut self,
16598 cx: &mut Context<Self>,
16599 ) -> Option<BackgroundHighlight> {
16600 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16601 if !text_highlights.1.is_empty() {
16602 self.scrollbar_marker_state.dirty = true;
16603 cx.notify();
16604 }
16605 Some(text_highlights)
16606 }
16607
16608 pub fn highlight_gutter<T: 'static>(
16609 &mut self,
16610 ranges: &[Range<Anchor>],
16611 color_fetcher: fn(&App) -> Hsla,
16612 cx: &mut Context<Self>,
16613 ) {
16614 self.gutter_highlights
16615 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16616 cx.notify();
16617 }
16618
16619 pub fn clear_gutter_highlights<T: 'static>(
16620 &mut self,
16621 cx: &mut Context<Self>,
16622 ) -> Option<GutterHighlight> {
16623 cx.notify();
16624 self.gutter_highlights.remove(&TypeId::of::<T>())
16625 }
16626
16627 #[cfg(feature = "test-support")]
16628 pub fn all_text_background_highlights(
16629 &self,
16630 window: &mut Window,
16631 cx: &mut Context<Self>,
16632 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16633 let snapshot = self.snapshot(window, cx);
16634 let buffer = &snapshot.buffer_snapshot;
16635 let start = buffer.anchor_before(0);
16636 let end = buffer.anchor_after(buffer.len());
16637 let theme = cx.theme().colors();
16638 self.background_highlights_in_range(start..end, &snapshot, theme)
16639 }
16640
16641 #[cfg(feature = "test-support")]
16642 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16643 let snapshot = self.buffer().read(cx).snapshot(cx);
16644
16645 let highlights = self
16646 .background_highlights
16647 .get(&TypeId::of::<items::BufferSearchHighlights>());
16648
16649 if let Some((_color, ranges)) = highlights {
16650 ranges
16651 .iter()
16652 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16653 .collect_vec()
16654 } else {
16655 vec![]
16656 }
16657 }
16658
16659 fn document_highlights_for_position<'a>(
16660 &'a self,
16661 position: Anchor,
16662 buffer: &'a MultiBufferSnapshot,
16663 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16664 let read_highlights = self
16665 .background_highlights
16666 .get(&TypeId::of::<DocumentHighlightRead>())
16667 .map(|h| &h.1);
16668 let write_highlights = self
16669 .background_highlights
16670 .get(&TypeId::of::<DocumentHighlightWrite>())
16671 .map(|h| &h.1);
16672 let left_position = position.bias_left(buffer);
16673 let right_position = position.bias_right(buffer);
16674 read_highlights
16675 .into_iter()
16676 .chain(write_highlights)
16677 .flat_map(move |ranges| {
16678 let start_ix = match ranges.binary_search_by(|probe| {
16679 let cmp = probe.end.cmp(&left_position, buffer);
16680 if cmp.is_ge() {
16681 Ordering::Greater
16682 } else {
16683 Ordering::Less
16684 }
16685 }) {
16686 Ok(i) | Err(i) => i,
16687 };
16688
16689 ranges[start_ix..]
16690 .iter()
16691 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16692 })
16693 }
16694
16695 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16696 self.background_highlights
16697 .get(&TypeId::of::<T>())
16698 .map_or(false, |(_, highlights)| !highlights.is_empty())
16699 }
16700
16701 pub fn background_highlights_in_range(
16702 &self,
16703 search_range: Range<Anchor>,
16704 display_snapshot: &DisplaySnapshot,
16705 theme: &ThemeColors,
16706 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16707 let mut results = Vec::new();
16708 for (color_fetcher, ranges) in self.background_highlights.values() {
16709 let color = color_fetcher(theme);
16710 let start_ix = match ranges.binary_search_by(|probe| {
16711 let cmp = probe
16712 .end
16713 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16714 if cmp.is_gt() {
16715 Ordering::Greater
16716 } else {
16717 Ordering::Less
16718 }
16719 }) {
16720 Ok(i) | Err(i) => i,
16721 };
16722 for range in &ranges[start_ix..] {
16723 if range
16724 .start
16725 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16726 .is_ge()
16727 {
16728 break;
16729 }
16730
16731 let start = range.start.to_display_point(display_snapshot);
16732 let end = range.end.to_display_point(display_snapshot);
16733 results.push((start..end, color))
16734 }
16735 }
16736 results
16737 }
16738
16739 pub fn background_highlight_row_ranges<T: 'static>(
16740 &self,
16741 search_range: Range<Anchor>,
16742 display_snapshot: &DisplaySnapshot,
16743 count: usize,
16744 ) -> Vec<RangeInclusive<DisplayPoint>> {
16745 let mut results = Vec::new();
16746 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16747 return vec![];
16748 };
16749
16750 let start_ix = match ranges.binary_search_by(|probe| {
16751 let cmp = probe
16752 .end
16753 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16754 if cmp.is_gt() {
16755 Ordering::Greater
16756 } else {
16757 Ordering::Less
16758 }
16759 }) {
16760 Ok(i) | Err(i) => i,
16761 };
16762 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16763 if let (Some(start_display), Some(end_display)) = (start, end) {
16764 results.push(
16765 start_display.to_display_point(display_snapshot)
16766 ..=end_display.to_display_point(display_snapshot),
16767 );
16768 }
16769 };
16770 let mut start_row: Option<Point> = None;
16771 let mut end_row: Option<Point> = None;
16772 if ranges.len() > count {
16773 return Vec::new();
16774 }
16775 for range in &ranges[start_ix..] {
16776 if range
16777 .start
16778 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16779 .is_ge()
16780 {
16781 break;
16782 }
16783 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16784 if let Some(current_row) = &end_row {
16785 if end.row == current_row.row {
16786 continue;
16787 }
16788 }
16789 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16790 if start_row.is_none() {
16791 assert_eq!(end_row, None);
16792 start_row = Some(start);
16793 end_row = Some(end);
16794 continue;
16795 }
16796 if let Some(current_end) = end_row.as_mut() {
16797 if start.row > current_end.row + 1 {
16798 push_region(start_row, end_row);
16799 start_row = Some(start);
16800 end_row = Some(end);
16801 } else {
16802 // Merge two hunks.
16803 *current_end = end;
16804 }
16805 } else {
16806 unreachable!();
16807 }
16808 }
16809 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16810 push_region(start_row, end_row);
16811 results
16812 }
16813
16814 pub fn gutter_highlights_in_range(
16815 &self,
16816 search_range: Range<Anchor>,
16817 display_snapshot: &DisplaySnapshot,
16818 cx: &App,
16819 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16820 let mut results = Vec::new();
16821 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16822 let color = color_fetcher(cx);
16823 let start_ix = match ranges.binary_search_by(|probe| {
16824 let cmp = probe
16825 .end
16826 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16827 if cmp.is_gt() {
16828 Ordering::Greater
16829 } else {
16830 Ordering::Less
16831 }
16832 }) {
16833 Ok(i) | Err(i) => i,
16834 };
16835 for range in &ranges[start_ix..] {
16836 if range
16837 .start
16838 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16839 .is_ge()
16840 {
16841 break;
16842 }
16843
16844 let start = range.start.to_display_point(display_snapshot);
16845 let end = range.end.to_display_point(display_snapshot);
16846 results.push((start..end, color))
16847 }
16848 }
16849 results
16850 }
16851
16852 /// Get the text ranges corresponding to the redaction query
16853 pub fn redacted_ranges(
16854 &self,
16855 search_range: Range<Anchor>,
16856 display_snapshot: &DisplaySnapshot,
16857 cx: &App,
16858 ) -> Vec<Range<DisplayPoint>> {
16859 display_snapshot
16860 .buffer_snapshot
16861 .redacted_ranges(search_range, |file| {
16862 if let Some(file) = file {
16863 file.is_private()
16864 && EditorSettings::get(
16865 Some(SettingsLocation {
16866 worktree_id: file.worktree_id(cx),
16867 path: file.path().as_ref(),
16868 }),
16869 cx,
16870 )
16871 .redact_private_values
16872 } else {
16873 false
16874 }
16875 })
16876 .map(|range| {
16877 range.start.to_display_point(display_snapshot)
16878 ..range.end.to_display_point(display_snapshot)
16879 })
16880 .collect()
16881 }
16882
16883 pub fn highlight_text<T: 'static>(
16884 &mut self,
16885 ranges: Vec<Range<Anchor>>,
16886 style: HighlightStyle,
16887 cx: &mut Context<Self>,
16888 ) {
16889 self.display_map.update(cx, |map, _| {
16890 map.highlight_text(TypeId::of::<T>(), ranges, style)
16891 });
16892 cx.notify();
16893 }
16894
16895 pub(crate) fn highlight_inlays<T: 'static>(
16896 &mut self,
16897 highlights: Vec<InlayHighlight>,
16898 style: HighlightStyle,
16899 cx: &mut Context<Self>,
16900 ) {
16901 self.display_map.update(cx, |map, _| {
16902 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16903 });
16904 cx.notify();
16905 }
16906
16907 pub fn text_highlights<'a, T: 'static>(
16908 &'a self,
16909 cx: &'a App,
16910 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16911 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16912 }
16913
16914 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16915 let cleared = self
16916 .display_map
16917 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16918 if cleared {
16919 cx.notify();
16920 }
16921 }
16922
16923 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16924 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16925 && self.focus_handle.is_focused(window)
16926 }
16927
16928 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16929 self.show_cursor_when_unfocused = is_enabled;
16930 cx.notify();
16931 }
16932
16933 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16934 cx.notify();
16935 }
16936
16937 fn on_buffer_event(
16938 &mut self,
16939 multibuffer: &Entity<MultiBuffer>,
16940 event: &multi_buffer::Event,
16941 window: &mut Window,
16942 cx: &mut Context<Self>,
16943 ) {
16944 match event {
16945 multi_buffer::Event::Edited {
16946 singleton_buffer_edited,
16947 edited_buffer: buffer_edited,
16948 } => {
16949 self.scrollbar_marker_state.dirty = true;
16950 self.active_indent_guides_state.dirty = true;
16951 self.refresh_active_diagnostics(cx);
16952 self.refresh_code_actions(window, cx);
16953 if self.has_active_inline_completion() {
16954 self.update_visible_inline_completion(window, cx);
16955 }
16956 if let Some(buffer) = buffer_edited {
16957 let buffer_id = buffer.read(cx).remote_id();
16958 if !self.registered_buffers.contains_key(&buffer_id) {
16959 if let Some(project) = self.project.as_ref() {
16960 project.update(cx, |project, cx| {
16961 self.registered_buffers.insert(
16962 buffer_id,
16963 project.register_buffer_with_language_servers(&buffer, cx),
16964 );
16965 })
16966 }
16967 }
16968 }
16969 cx.emit(EditorEvent::BufferEdited);
16970 cx.emit(SearchEvent::MatchesInvalidated);
16971 if *singleton_buffer_edited {
16972 if let Some(project) = &self.project {
16973 #[allow(clippy::mutable_key_type)]
16974 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16975 multibuffer
16976 .all_buffers()
16977 .into_iter()
16978 .filter_map(|buffer| {
16979 buffer.update(cx, |buffer, cx| {
16980 let language = buffer.language()?;
16981 let should_discard = project.update(cx, |project, cx| {
16982 project.is_local()
16983 && !project.has_language_servers_for(buffer, cx)
16984 });
16985 should_discard.not().then_some(language.clone())
16986 })
16987 })
16988 .collect::<HashSet<_>>()
16989 });
16990 if !languages_affected.is_empty() {
16991 self.refresh_inlay_hints(
16992 InlayHintRefreshReason::BufferEdited(languages_affected),
16993 cx,
16994 );
16995 }
16996 }
16997 }
16998
16999 let Some(project) = &self.project else { return };
17000 let (telemetry, is_via_ssh) = {
17001 let project = project.read(cx);
17002 let telemetry = project.client().telemetry().clone();
17003 let is_via_ssh = project.is_via_ssh();
17004 (telemetry, is_via_ssh)
17005 };
17006 refresh_linked_ranges(self, window, cx);
17007 telemetry.log_edit_event("editor", is_via_ssh);
17008 }
17009 multi_buffer::Event::ExcerptsAdded {
17010 buffer,
17011 predecessor,
17012 excerpts,
17013 } => {
17014 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17015 let buffer_id = buffer.read(cx).remote_id();
17016 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17017 if let Some(project) = &self.project {
17018 get_uncommitted_diff_for_buffer(
17019 project,
17020 [buffer.clone()],
17021 self.buffer.clone(),
17022 cx,
17023 )
17024 .detach();
17025 }
17026 }
17027 cx.emit(EditorEvent::ExcerptsAdded {
17028 buffer: buffer.clone(),
17029 predecessor: *predecessor,
17030 excerpts: excerpts.clone(),
17031 });
17032 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17033 }
17034 multi_buffer::Event::ExcerptsRemoved { ids } => {
17035 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17036 let buffer = self.buffer.read(cx);
17037 self.registered_buffers
17038 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17039 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17040 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17041 }
17042 multi_buffer::Event::ExcerptsEdited {
17043 excerpt_ids,
17044 buffer_ids,
17045 } => {
17046 self.display_map.update(cx, |map, cx| {
17047 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17048 });
17049 cx.emit(EditorEvent::ExcerptsEdited {
17050 ids: excerpt_ids.clone(),
17051 })
17052 }
17053 multi_buffer::Event::ExcerptsExpanded { ids } => {
17054 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17055 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17056 }
17057 multi_buffer::Event::Reparsed(buffer_id) => {
17058 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17059 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17060
17061 cx.emit(EditorEvent::Reparsed(*buffer_id));
17062 }
17063 multi_buffer::Event::DiffHunksToggled => {
17064 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17065 }
17066 multi_buffer::Event::LanguageChanged(buffer_id) => {
17067 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17068 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17069 cx.emit(EditorEvent::Reparsed(*buffer_id));
17070 cx.notify();
17071 }
17072 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17073 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17074 multi_buffer::Event::FileHandleChanged
17075 | multi_buffer::Event::Reloaded
17076 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17077 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17078 multi_buffer::Event::DiagnosticsUpdated => {
17079 self.refresh_active_diagnostics(cx);
17080 self.refresh_inline_diagnostics(true, window, cx);
17081 self.scrollbar_marker_state.dirty = true;
17082 cx.notify();
17083 }
17084 _ => {}
17085 };
17086 }
17087
17088 fn on_display_map_changed(
17089 &mut self,
17090 _: Entity<DisplayMap>,
17091 _: &mut Window,
17092 cx: &mut Context<Self>,
17093 ) {
17094 cx.notify();
17095 }
17096
17097 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17098 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17099 self.update_edit_prediction_settings(cx);
17100 self.refresh_inline_completion(true, false, window, cx);
17101 self.refresh_inlay_hints(
17102 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17103 self.selections.newest_anchor().head(),
17104 &self.buffer.read(cx).snapshot(cx),
17105 cx,
17106 )),
17107 cx,
17108 );
17109
17110 let old_cursor_shape = self.cursor_shape;
17111
17112 {
17113 let editor_settings = EditorSettings::get_global(cx);
17114 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17115 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17116 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17117 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17118 }
17119
17120 if old_cursor_shape != self.cursor_shape {
17121 cx.emit(EditorEvent::CursorShapeChanged);
17122 }
17123
17124 let project_settings = ProjectSettings::get_global(cx);
17125 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17126
17127 if self.mode == EditorMode::Full {
17128 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17129 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17130 if self.show_inline_diagnostics != show_inline_diagnostics {
17131 self.show_inline_diagnostics = show_inline_diagnostics;
17132 self.refresh_inline_diagnostics(false, window, cx);
17133 }
17134
17135 if self.git_blame_inline_enabled != inline_blame_enabled {
17136 self.toggle_git_blame_inline_internal(false, window, cx);
17137 }
17138 }
17139
17140 cx.notify();
17141 }
17142
17143 pub fn set_searchable(&mut self, searchable: bool) {
17144 self.searchable = searchable;
17145 }
17146
17147 pub fn searchable(&self) -> bool {
17148 self.searchable
17149 }
17150
17151 fn open_proposed_changes_editor(
17152 &mut self,
17153 _: &OpenProposedChangesEditor,
17154 window: &mut Window,
17155 cx: &mut Context<Self>,
17156 ) {
17157 let Some(workspace) = self.workspace() else {
17158 cx.propagate();
17159 return;
17160 };
17161
17162 let selections = self.selections.all::<usize>(cx);
17163 let multi_buffer = self.buffer.read(cx);
17164 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17165 let mut new_selections_by_buffer = HashMap::default();
17166 for selection in selections {
17167 for (buffer, range, _) in
17168 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17169 {
17170 let mut range = range.to_point(buffer);
17171 range.start.column = 0;
17172 range.end.column = buffer.line_len(range.end.row);
17173 new_selections_by_buffer
17174 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17175 .or_insert(Vec::new())
17176 .push(range)
17177 }
17178 }
17179
17180 let proposed_changes_buffers = new_selections_by_buffer
17181 .into_iter()
17182 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17183 .collect::<Vec<_>>();
17184 let proposed_changes_editor = cx.new(|cx| {
17185 ProposedChangesEditor::new(
17186 "Proposed changes",
17187 proposed_changes_buffers,
17188 self.project.clone(),
17189 window,
17190 cx,
17191 )
17192 });
17193
17194 window.defer(cx, move |window, cx| {
17195 workspace.update(cx, |workspace, cx| {
17196 workspace.active_pane().update(cx, |pane, cx| {
17197 pane.add_item(
17198 Box::new(proposed_changes_editor),
17199 true,
17200 true,
17201 None,
17202 window,
17203 cx,
17204 );
17205 });
17206 });
17207 });
17208 }
17209
17210 pub fn open_excerpts_in_split(
17211 &mut self,
17212 _: &OpenExcerptsSplit,
17213 window: &mut Window,
17214 cx: &mut Context<Self>,
17215 ) {
17216 self.open_excerpts_common(None, true, window, cx)
17217 }
17218
17219 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17220 self.open_excerpts_common(None, false, window, cx)
17221 }
17222
17223 fn open_excerpts_common(
17224 &mut self,
17225 jump_data: Option<JumpData>,
17226 split: bool,
17227 window: &mut Window,
17228 cx: &mut Context<Self>,
17229 ) {
17230 let Some(workspace) = self.workspace() else {
17231 cx.propagate();
17232 return;
17233 };
17234
17235 if self.buffer.read(cx).is_singleton() {
17236 cx.propagate();
17237 return;
17238 }
17239
17240 let mut new_selections_by_buffer = HashMap::default();
17241 match &jump_data {
17242 Some(JumpData::MultiBufferPoint {
17243 excerpt_id,
17244 position,
17245 anchor,
17246 line_offset_from_top,
17247 }) => {
17248 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17249 if let Some(buffer) = multi_buffer_snapshot
17250 .buffer_id_for_excerpt(*excerpt_id)
17251 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17252 {
17253 let buffer_snapshot = buffer.read(cx).snapshot();
17254 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17255 language::ToPoint::to_point(anchor, &buffer_snapshot)
17256 } else {
17257 buffer_snapshot.clip_point(*position, Bias::Left)
17258 };
17259 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17260 new_selections_by_buffer.insert(
17261 buffer,
17262 (
17263 vec![jump_to_offset..jump_to_offset],
17264 Some(*line_offset_from_top),
17265 ),
17266 );
17267 }
17268 }
17269 Some(JumpData::MultiBufferRow {
17270 row,
17271 line_offset_from_top,
17272 }) => {
17273 let point = MultiBufferPoint::new(row.0, 0);
17274 if let Some((buffer, buffer_point, _)) =
17275 self.buffer.read(cx).point_to_buffer_point(point, cx)
17276 {
17277 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17278 new_selections_by_buffer
17279 .entry(buffer)
17280 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17281 .0
17282 .push(buffer_offset..buffer_offset)
17283 }
17284 }
17285 None => {
17286 let selections = self.selections.all::<usize>(cx);
17287 let multi_buffer = self.buffer.read(cx);
17288 for selection in selections {
17289 for (snapshot, range, _, anchor) in multi_buffer
17290 .snapshot(cx)
17291 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17292 {
17293 if let Some(anchor) = anchor {
17294 // selection is in a deleted hunk
17295 let Some(buffer_id) = anchor.buffer_id else {
17296 continue;
17297 };
17298 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17299 continue;
17300 };
17301 let offset = text::ToOffset::to_offset(
17302 &anchor.text_anchor,
17303 &buffer_handle.read(cx).snapshot(),
17304 );
17305 let range = offset..offset;
17306 new_selections_by_buffer
17307 .entry(buffer_handle)
17308 .or_insert((Vec::new(), None))
17309 .0
17310 .push(range)
17311 } else {
17312 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17313 else {
17314 continue;
17315 };
17316 new_selections_by_buffer
17317 .entry(buffer_handle)
17318 .or_insert((Vec::new(), None))
17319 .0
17320 .push(range)
17321 }
17322 }
17323 }
17324 }
17325 }
17326
17327 new_selections_by_buffer
17328 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17329
17330 if new_selections_by_buffer.is_empty() {
17331 return;
17332 }
17333
17334 // We defer the pane interaction because we ourselves are a workspace item
17335 // and activating a new item causes the pane to call a method on us reentrantly,
17336 // which panics if we're on the stack.
17337 window.defer(cx, move |window, cx| {
17338 workspace.update(cx, |workspace, cx| {
17339 let pane = if split {
17340 workspace.adjacent_pane(window, cx)
17341 } else {
17342 workspace.active_pane().clone()
17343 };
17344
17345 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17346 let editor = buffer
17347 .read(cx)
17348 .file()
17349 .is_none()
17350 .then(|| {
17351 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17352 // so `workspace.open_project_item` will never find them, always opening a new editor.
17353 // Instead, we try to activate the existing editor in the pane first.
17354 let (editor, pane_item_index) =
17355 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17356 let editor = item.downcast::<Editor>()?;
17357 let singleton_buffer =
17358 editor.read(cx).buffer().read(cx).as_singleton()?;
17359 if singleton_buffer == buffer {
17360 Some((editor, i))
17361 } else {
17362 None
17363 }
17364 })?;
17365 pane.update(cx, |pane, cx| {
17366 pane.activate_item(pane_item_index, true, true, window, cx)
17367 });
17368 Some(editor)
17369 })
17370 .flatten()
17371 .unwrap_or_else(|| {
17372 workspace.open_project_item::<Self>(
17373 pane.clone(),
17374 buffer,
17375 true,
17376 true,
17377 window,
17378 cx,
17379 )
17380 });
17381
17382 editor.update(cx, |editor, cx| {
17383 let autoscroll = match scroll_offset {
17384 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17385 None => Autoscroll::newest(),
17386 };
17387 let nav_history = editor.nav_history.take();
17388 editor.change_selections(Some(autoscroll), window, cx, |s| {
17389 s.select_ranges(ranges);
17390 });
17391 editor.nav_history = nav_history;
17392 });
17393 }
17394 })
17395 });
17396 }
17397
17398 // For now, don't allow opening excerpts in buffers that aren't backed by
17399 // regular project files.
17400 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17401 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17402 }
17403
17404 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17405 let snapshot = self.buffer.read(cx).read(cx);
17406 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17407 Some(
17408 ranges
17409 .iter()
17410 .map(move |range| {
17411 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17412 })
17413 .collect(),
17414 )
17415 }
17416
17417 fn selection_replacement_ranges(
17418 &self,
17419 range: Range<OffsetUtf16>,
17420 cx: &mut App,
17421 ) -> Vec<Range<OffsetUtf16>> {
17422 let selections = self.selections.all::<OffsetUtf16>(cx);
17423 let newest_selection = selections
17424 .iter()
17425 .max_by_key(|selection| selection.id)
17426 .unwrap();
17427 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17428 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17429 let snapshot = self.buffer.read(cx).read(cx);
17430 selections
17431 .into_iter()
17432 .map(|mut selection| {
17433 selection.start.0 =
17434 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17435 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17436 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17437 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17438 })
17439 .collect()
17440 }
17441
17442 fn report_editor_event(
17443 &self,
17444 event_type: &'static str,
17445 file_extension: Option<String>,
17446 cx: &App,
17447 ) {
17448 if cfg!(any(test, feature = "test-support")) {
17449 return;
17450 }
17451
17452 let Some(project) = &self.project else { return };
17453
17454 // If None, we are in a file without an extension
17455 let file = self
17456 .buffer
17457 .read(cx)
17458 .as_singleton()
17459 .and_then(|b| b.read(cx).file());
17460 let file_extension = file_extension.or(file
17461 .as_ref()
17462 .and_then(|file| Path::new(file.file_name(cx)).extension())
17463 .and_then(|e| e.to_str())
17464 .map(|a| a.to_string()));
17465
17466 let vim_mode = cx
17467 .global::<SettingsStore>()
17468 .raw_user_settings()
17469 .get("vim_mode")
17470 == Some(&serde_json::Value::Bool(true));
17471
17472 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17473 let copilot_enabled = edit_predictions_provider
17474 == language::language_settings::EditPredictionProvider::Copilot;
17475 let copilot_enabled_for_language = self
17476 .buffer
17477 .read(cx)
17478 .language_settings(cx)
17479 .show_edit_predictions;
17480
17481 let project = project.read(cx);
17482 telemetry::event!(
17483 event_type,
17484 file_extension,
17485 vim_mode,
17486 copilot_enabled,
17487 copilot_enabled_for_language,
17488 edit_predictions_provider,
17489 is_via_ssh = project.is_via_ssh(),
17490 );
17491 }
17492
17493 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17494 /// with each line being an array of {text, highlight} objects.
17495 fn copy_highlight_json(
17496 &mut self,
17497 _: &CopyHighlightJson,
17498 window: &mut Window,
17499 cx: &mut Context<Self>,
17500 ) {
17501 #[derive(Serialize)]
17502 struct Chunk<'a> {
17503 text: String,
17504 highlight: Option<&'a str>,
17505 }
17506
17507 let snapshot = self.buffer.read(cx).snapshot(cx);
17508 let range = self
17509 .selected_text_range(false, window, cx)
17510 .and_then(|selection| {
17511 if selection.range.is_empty() {
17512 None
17513 } else {
17514 Some(selection.range)
17515 }
17516 })
17517 .unwrap_or_else(|| 0..snapshot.len());
17518
17519 let chunks = snapshot.chunks(range, true);
17520 let mut lines = Vec::new();
17521 let mut line: VecDeque<Chunk> = VecDeque::new();
17522
17523 let Some(style) = self.style.as_ref() else {
17524 return;
17525 };
17526
17527 for chunk in chunks {
17528 let highlight = chunk
17529 .syntax_highlight_id
17530 .and_then(|id| id.name(&style.syntax));
17531 let mut chunk_lines = chunk.text.split('\n').peekable();
17532 while let Some(text) = chunk_lines.next() {
17533 let mut merged_with_last_token = false;
17534 if let Some(last_token) = line.back_mut() {
17535 if last_token.highlight == highlight {
17536 last_token.text.push_str(text);
17537 merged_with_last_token = true;
17538 }
17539 }
17540
17541 if !merged_with_last_token {
17542 line.push_back(Chunk {
17543 text: text.into(),
17544 highlight,
17545 });
17546 }
17547
17548 if chunk_lines.peek().is_some() {
17549 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17550 line.pop_front();
17551 }
17552 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17553 line.pop_back();
17554 }
17555
17556 lines.push(mem::take(&mut line));
17557 }
17558 }
17559 }
17560
17561 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17562 return;
17563 };
17564 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17565 }
17566
17567 pub fn open_context_menu(
17568 &mut self,
17569 _: &OpenContextMenu,
17570 window: &mut Window,
17571 cx: &mut Context<Self>,
17572 ) {
17573 self.request_autoscroll(Autoscroll::newest(), cx);
17574 let position = self.selections.newest_display(cx).start;
17575 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17576 }
17577
17578 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17579 &self.inlay_hint_cache
17580 }
17581
17582 pub fn replay_insert_event(
17583 &mut self,
17584 text: &str,
17585 relative_utf16_range: Option<Range<isize>>,
17586 window: &mut Window,
17587 cx: &mut Context<Self>,
17588 ) {
17589 if !self.input_enabled {
17590 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17591 return;
17592 }
17593 if let Some(relative_utf16_range) = relative_utf16_range {
17594 let selections = self.selections.all::<OffsetUtf16>(cx);
17595 self.change_selections(None, window, cx, |s| {
17596 let new_ranges = selections.into_iter().map(|range| {
17597 let start = OffsetUtf16(
17598 range
17599 .head()
17600 .0
17601 .saturating_add_signed(relative_utf16_range.start),
17602 );
17603 let end = OffsetUtf16(
17604 range
17605 .head()
17606 .0
17607 .saturating_add_signed(relative_utf16_range.end),
17608 );
17609 start..end
17610 });
17611 s.select_ranges(new_ranges);
17612 });
17613 }
17614
17615 self.handle_input(text, window, cx);
17616 }
17617
17618 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17619 let Some(provider) = self.semantics_provider.as_ref() else {
17620 return false;
17621 };
17622
17623 let mut supports = false;
17624 self.buffer().update(cx, |this, cx| {
17625 this.for_each_buffer(|buffer| {
17626 supports |= provider.supports_inlay_hints(buffer, cx);
17627 });
17628 });
17629
17630 supports
17631 }
17632
17633 pub fn is_focused(&self, window: &Window) -> bool {
17634 self.focus_handle.is_focused(window)
17635 }
17636
17637 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17638 cx.emit(EditorEvent::Focused);
17639
17640 if let Some(descendant) = self
17641 .last_focused_descendant
17642 .take()
17643 .and_then(|descendant| descendant.upgrade())
17644 {
17645 window.focus(&descendant);
17646 } else {
17647 if let Some(blame) = self.blame.as_ref() {
17648 blame.update(cx, GitBlame::focus)
17649 }
17650
17651 self.blink_manager.update(cx, BlinkManager::enable);
17652 self.show_cursor_names(window, cx);
17653 self.buffer.update(cx, |buffer, cx| {
17654 buffer.finalize_last_transaction(cx);
17655 if self.leader_peer_id.is_none() {
17656 buffer.set_active_selections(
17657 &self.selections.disjoint_anchors(),
17658 self.selections.line_mode,
17659 self.cursor_shape,
17660 cx,
17661 );
17662 }
17663 });
17664 }
17665 }
17666
17667 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17668 cx.emit(EditorEvent::FocusedIn)
17669 }
17670
17671 fn handle_focus_out(
17672 &mut self,
17673 event: FocusOutEvent,
17674 _window: &mut Window,
17675 cx: &mut Context<Self>,
17676 ) {
17677 if event.blurred != self.focus_handle {
17678 self.last_focused_descendant = Some(event.blurred);
17679 }
17680 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17681 }
17682
17683 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17684 self.blink_manager.update(cx, BlinkManager::disable);
17685 self.buffer
17686 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17687
17688 if let Some(blame) = self.blame.as_ref() {
17689 blame.update(cx, GitBlame::blur)
17690 }
17691 if !self.hover_state.focused(window, cx) {
17692 hide_hover(self, cx);
17693 }
17694 if !self
17695 .context_menu
17696 .borrow()
17697 .as_ref()
17698 .is_some_and(|context_menu| context_menu.focused(window, cx))
17699 {
17700 self.hide_context_menu(window, cx);
17701 }
17702 self.discard_inline_completion(false, cx);
17703 cx.emit(EditorEvent::Blurred);
17704 cx.notify();
17705 }
17706
17707 pub fn register_action<A: Action>(
17708 &mut self,
17709 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17710 ) -> Subscription {
17711 let id = self.next_editor_action_id.post_inc();
17712 let listener = Arc::new(listener);
17713 self.editor_actions.borrow_mut().insert(
17714 id,
17715 Box::new(move |window, _| {
17716 let listener = listener.clone();
17717 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17718 let action = action.downcast_ref().unwrap();
17719 if phase == DispatchPhase::Bubble {
17720 listener(action, window, cx)
17721 }
17722 })
17723 }),
17724 );
17725
17726 let editor_actions = self.editor_actions.clone();
17727 Subscription::new(move || {
17728 editor_actions.borrow_mut().remove(&id);
17729 })
17730 }
17731
17732 pub fn file_header_size(&self) -> u32 {
17733 FILE_HEADER_HEIGHT
17734 }
17735
17736 pub fn restore(
17737 &mut self,
17738 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17739 window: &mut Window,
17740 cx: &mut Context<Self>,
17741 ) {
17742 let workspace = self.workspace();
17743 let project = self.project.as_ref();
17744 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17745 let mut tasks = Vec::new();
17746 for (buffer_id, changes) in revert_changes {
17747 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17748 buffer.update(cx, |buffer, cx| {
17749 buffer.edit(
17750 changes
17751 .into_iter()
17752 .map(|(range, text)| (range, text.to_string())),
17753 None,
17754 cx,
17755 );
17756 });
17757
17758 if let Some(project) =
17759 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17760 {
17761 project.update(cx, |project, cx| {
17762 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17763 })
17764 }
17765 }
17766 }
17767 tasks
17768 });
17769 cx.spawn_in(window, async move |_, cx| {
17770 for (buffer, task) in save_tasks {
17771 let result = task.await;
17772 if result.is_err() {
17773 let Some(path) = buffer
17774 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17775 .ok()
17776 else {
17777 continue;
17778 };
17779 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17780 let Some(task) = cx
17781 .update_window_entity(&workspace, |workspace, window, cx| {
17782 workspace
17783 .open_path_preview(path, None, false, false, false, window, cx)
17784 })
17785 .ok()
17786 else {
17787 continue;
17788 };
17789 task.await.log_err();
17790 }
17791 }
17792 }
17793 })
17794 .detach();
17795 self.change_selections(None, window, cx, |selections| selections.refresh());
17796 }
17797
17798 pub fn to_pixel_point(
17799 &self,
17800 source: multi_buffer::Anchor,
17801 editor_snapshot: &EditorSnapshot,
17802 window: &mut Window,
17803 ) -> Option<gpui::Point<Pixels>> {
17804 let source_point = source.to_display_point(editor_snapshot);
17805 self.display_to_pixel_point(source_point, editor_snapshot, window)
17806 }
17807
17808 pub fn display_to_pixel_point(
17809 &self,
17810 source: DisplayPoint,
17811 editor_snapshot: &EditorSnapshot,
17812 window: &mut Window,
17813 ) -> Option<gpui::Point<Pixels>> {
17814 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17815 let text_layout_details = self.text_layout_details(window);
17816 let scroll_top = text_layout_details
17817 .scroll_anchor
17818 .scroll_position(editor_snapshot)
17819 .y;
17820
17821 if source.row().as_f32() < scroll_top.floor() {
17822 return None;
17823 }
17824 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17825 let source_y = line_height * (source.row().as_f32() - scroll_top);
17826 Some(gpui::Point::new(source_x, source_y))
17827 }
17828
17829 pub fn has_visible_completions_menu(&self) -> bool {
17830 !self.edit_prediction_preview_is_active()
17831 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17832 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17833 })
17834 }
17835
17836 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17837 self.addons
17838 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17839 }
17840
17841 pub fn unregister_addon<T: Addon>(&mut self) {
17842 self.addons.remove(&std::any::TypeId::of::<T>());
17843 }
17844
17845 pub fn addon<T: Addon>(&self) -> Option<&T> {
17846 let type_id = std::any::TypeId::of::<T>();
17847 self.addons
17848 .get(&type_id)
17849 .and_then(|item| item.to_any().downcast_ref::<T>())
17850 }
17851
17852 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17853 let text_layout_details = self.text_layout_details(window);
17854 let style = &text_layout_details.editor_style;
17855 let font_id = window.text_system().resolve_font(&style.text.font());
17856 let font_size = style.text.font_size.to_pixels(window.rem_size());
17857 let line_height = style.text.line_height_in_pixels(window.rem_size());
17858 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17859
17860 gpui::Size::new(em_width, line_height)
17861 }
17862
17863 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17864 self.load_diff_task.clone()
17865 }
17866
17867 fn read_metadata_from_db(
17868 &mut self,
17869 item_id: u64,
17870 workspace_id: WorkspaceId,
17871 window: &mut Window,
17872 cx: &mut Context<Editor>,
17873 ) {
17874 if self.is_singleton(cx)
17875 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17876 {
17877 let buffer_snapshot = OnceCell::new();
17878
17879 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17880 if !folds.is_empty() {
17881 let snapshot =
17882 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17883 self.fold_ranges(
17884 folds
17885 .into_iter()
17886 .map(|(start, end)| {
17887 snapshot.clip_offset(start, Bias::Left)
17888 ..snapshot.clip_offset(end, Bias::Right)
17889 })
17890 .collect(),
17891 false,
17892 window,
17893 cx,
17894 );
17895 }
17896 }
17897
17898 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17899 if !selections.is_empty() {
17900 let snapshot =
17901 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17902 self.change_selections(None, window, cx, |s| {
17903 s.select_ranges(selections.into_iter().map(|(start, end)| {
17904 snapshot.clip_offset(start, Bias::Left)
17905 ..snapshot.clip_offset(end, Bias::Right)
17906 }));
17907 });
17908 }
17909 };
17910 }
17911
17912 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17913 }
17914}
17915
17916fn insert_extra_newline_brackets(
17917 buffer: &MultiBufferSnapshot,
17918 range: Range<usize>,
17919 language: &language::LanguageScope,
17920) -> bool {
17921 let leading_whitespace_len = buffer
17922 .reversed_chars_at(range.start)
17923 .take_while(|c| c.is_whitespace() && *c != '\n')
17924 .map(|c| c.len_utf8())
17925 .sum::<usize>();
17926 let trailing_whitespace_len = buffer
17927 .chars_at(range.end)
17928 .take_while(|c| c.is_whitespace() && *c != '\n')
17929 .map(|c| c.len_utf8())
17930 .sum::<usize>();
17931 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17932
17933 language.brackets().any(|(pair, enabled)| {
17934 let pair_start = pair.start.trim_end();
17935 let pair_end = pair.end.trim_start();
17936
17937 enabled
17938 && pair.newline
17939 && buffer.contains_str_at(range.end, pair_end)
17940 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17941 })
17942}
17943
17944fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17945 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17946 [(buffer, range, _)] => (*buffer, range.clone()),
17947 _ => return false,
17948 };
17949 let pair = {
17950 let mut result: Option<BracketMatch> = None;
17951
17952 for pair in buffer
17953 .all_bracket_ranges(range.clone())
17954 .filter(move |pair| {
17955 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17956 })
17957 {
17958 let len = pair.close_range.end - pair.open_range.start;
17959
17960 if let Some(existing) = &result {
17961 let existing_len = existing.close_range.end - existing.open_range.start;
17962 if len > existing_len {
17963 continue;
17964 }
17965 }
17966
17967 result = Some(pair);
17968 }
17969
17970 result
17971 };
17972 let Some(pair) = pair else {
17973 return false;
17974 };
17975 pair.newline_only
17976 && buffer
17977 .chars_for_range(pair.open_range.end..range.start)
17978 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17979 .all(|c| c.is_whitespace() && c != '\n')
17980}
17981
17982fn get_uncommitted_diff_for_buffer(
17983 project: &Entity<Project>,
17984 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17985 buffer: Entity<MultiBuffer>,
17986 cx: &mut App,
17987) -> Task<()> {
17988 let mut tasks = Vec::new();
17989 project.update(cx, |project, cx| {
17990 for buffer in buffers {
17991 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
17992 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17993 }
17994 }
17995 });
17996 cx.spawn(async move |cx| {
17997 let diffs = future::join_all(tasks).await;
17998 buffer
17999 .update(cx, |buffer, cx| {
18000 for diff in diffs.into_iter().flatten() {
18001 buffer.add_diff(diff, cx);
18002 }
18003 })
18004 .ok();
18005 })
18006}
18007
18008fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18009 let tab_size = tab_size.get() as usize;
18010 let mut width = offset;
18011
18012 for ch in text.chars() {
18013 width += if ch == '\t' {
18014 tab_size - (width % tab_size)
18015 } else {
18016 1
18017 };
18018 }
18019
18020 width - offset
18021}
18022
18023#[cfg(test)]
18024mod tests {
18025 use super::*;
18026
18027 #[test]
18028 fn test_string_size_with_expanded_tabs() {
18029 let nz = |val| NonZeroU32::new(val).unwrap();
18030 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18031 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18032 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18033 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18034 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18035 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18036 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18037 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18038 }
18039}
18040
18041/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18042struct WordBreakingTokenizer<'a> {
18043 input: &'a str,
18044}
18045
18046impl<'a> WordBreakingTokenizer<'a> {
18047 fn new(input: &'a str) -> Self {
18048 Self { input }
18049 }
18050}
18051
18052fn is_char_ideographic(ch: char) -> bool {
18053 use unicode_script::Script::*;
18054 use unicode_script::UnicodeScript;
18055 matches!(ch.script(), Han | Tangut | Yi)
18056}
18057
18058fn is_grapheme_ideographic(text: &str) -> bool {
18059 text.chars().any(is_char_ideographic)
18060}
18061
18062fn is_grapheme_whitespace(text: &str) -> bool {
18063 text.chars().any(|x| x.is_whitespace())
18064}
18065
18066fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18067 text.chars().next().map_or(false, |ch| {
18068 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18069 })
18070}
18071
18072#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18073enum WordBreakToken<'a> {
18074 Word { token: &'a str, grapheme_len: usize },
18075 InlineWhitespace { token: &'a str, grapheme_len: usize },
18076 Newline,
18077}
18078
18079impl<'a> Iterator for WordBreakingTokenizer<'a> {
18080 /// Yields a span, the count of graphemes in the token, and whether it was
18081 /// whitespace. Note that it also breaks at word boundaries.
18082 type Item = WordBreakToken<'a>;
18083
18084 fn next(&mut self) -> Option<Self::Item> {
18085 use unicode_segmentation::UnicodeSegmentation;
18086 if self.input.is_empty() {
18087 return None;
18088 }
18089
18090 let mut iter = self.input.graphemes(true).peekable();
18091 let mut offset = 0;
18092 let mut grapheme_len = 0;
18093 if let Some(first_grapheme) = iter.next() {
18094 let is_newline = first_grapheme == "\n";
18095 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18096 offset += first_grapheme.len();
18097 grapheme_len += 1;
18098 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18099 if let Some(grapheme) = iter.peek().copied() {
18100 if should_stay_with_preceding_ideograph(grapheme) {
18101 offset += grapheme.len();
18102 grapheme_len += 1;
18103 }
18104 }
18105 } else {
18106 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18107 let mut next_word_bound = words.peek().copied();
18108 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18109 next_word_bound = words.next();
18110 }
18111 while let Some(grapheme) = iter.peek().copied() {
18112 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18113 break;
18114 };
18115 if is_grapheme_whitespace(grapheme) != is_whitespace
18116 || (grapheme == "\n") != is_newline
18117 {
18118 break;
18119 };
18120 offset += grapheme.len();
18121 grapheme_len += 1;
18122 iter.next();
18123 }
18124 }
18125 let token = &self.input[..offset];
18126 self.input = &self.input[offset..];
18127 if token == "\n" {
18128 Some(WordBreakToken::Newline)
18129 } else if is_whitespace {
18130 Some(WordBreakToken::InlineWhitespace {
18131 token,
18132 grapheme_len,
18133 })
18134 } else {
18135 Some(WordBreakToken::Word {
18136 token,
18137 grapheme_len,
18138 })
18139 }
18140 } else {
18141 None
18142 }
18143 }
18144}
18145
18146#[test]
18147fn test_word_breaking_tokenizer() {
18148 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18149 ("", &[]),
18150 (" ", &[whitespace(" ", 2)]),
18151 ("Ʒ", &[word("Ʒ", 1)]),
18152 ("Ǽ", &[word("Ǽ", 1)]),
18153 ("⋑", &[word("⋑", 1)]),
18154 ("⋑⋑", &[word("⋑⋑", 2)]),
18155 (
18156 "原理,进而",
18157 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18158 ),
18159 (
18160 "hello world",
18161 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18162 ),
18163 (
18164 "hello, world",
18165 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18166 ),
18167 (
18168 " hello world",
18169 &[
18170 whitespace(" ", 2),
18171 word("hello", 5),
18172 whitespace(" ", 1),
18173 word("world", 5),
18174 ],
18175 ),
18176 (
18177 "这是什么 \n 钢笔",
18178 &[
18179 word("这", 1),
18180 word("是", 1),
18181 word("什", 1),
18182 word("么", 1),
18183 whitespace(" ", 1),
18184 newline(),
18185 whitespace(" ", 1),
18186 word("钢", 1),
18187 word("笔", 1),
18188 ],
18189 ),
18190 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18191 ];
18192
18193 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18194 WordBreakToken::Word {
18195 token,
18196 grapheme_len,
18197 }
18198 }
18199
18200 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18201 WordBreakToken::InlineWhitespace {
18202 token,
18203 grapheme_len,
18204 }
18205 }
18206
18207 fn newline() -> WordBreakToken<'static> {
18208 WordBreakToken::Newline
18209 }
18210
18211 for (input, result) in tests {
18212 assert_eq!(
18213 WordBreakingTokenizer::new(input)
18214 .collect::<Vec<_>>()
18215 .as_slice(),
18216 *result,
18217 );
18218 }
18219}
18220
18221fn wrap_with_prefix(
18222 line_prefix: String,
18223 unwrapped_text: String,
18224 wrap_column: usize,
18225 tab_size: NonZeroU32,
18226 preserve_existing_whitespace: bool,
18227) -> String {
18228 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18229 let mut wrapped_text = String::new();
18230 let mut current_line = line_prefix.clone();
18231
18232 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18233 let mut current_line_len = line_prefix_len;
18234 let mut in_whitespace = false;
18235 for token in tokenizer {
18236 let have_preceding_whitespace = in_whitespace;
18237 match token {
18238 WordBreakToken::Word {
18239 token,
18240 grapheme_len,
18241 } => {
18242 in_whitespace = false;
18243 if current_line_len + grapheme_len > wrap_column
18244 && current_line_len != line_prefix_len
18245 {
18246 wrapped_text.push_str(current_line.trim_end());
18247 wrapped_text.push('\n');
18248 current_line.truncate(line_prefix.len());
18249 current_line_len = line_prefix_len;
18250 }
18251 current_line.push_str(token);
18252 current_line_len += grapheme_len;
18253 }
18254 WordBreakToken::InlineWhitespace {
18255 mut token,
18256 mut grapheme_len,
18257 } => {
18258 in_whitespace = true;
18259 if have_preceding_whitespace && !preserve_existing_whitespace {
18260 continue;
18261 }
18262 if !preserve_existing_whitespace {
18263 token = " ";
18264 grapheme_len = 1;
18265 }
18266 if current_line_len + grapheme_len > wrap_column {
18267 wrapped_text.push_str(current_line.trim_end());
18268 wrapped_text.push('\n');
18269 current_line.truncate(line_prefix.len());
18270 current_line_len = line_prefix_len;
18271 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18272 current_line.push_str(token);
18273 current_line_len += grapheme_len;
18274 }
18275 }
18276 WordBreakToken::Newline => {
18277 in_whitespace = true;
18278 if preserve_existing_whitespace {
18279 wrapped_text.push_str(current_line.trim_end());
18280 wrapped_text.push('\n');
18281 current_line.truncate(line_prefix.len());
18282 current_line_len = line_prefix_len;
18283 } else if have_preceding_whitespace {
18284 continue;
18285 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18286 {
18287 wrapped_text.push_str(current_line.trim_end());
18288 wrapped_text.push('\n');
18289 current_line.truncate(line_prefix.len());
18290 current_line_len = line_prefix_len;
18291 } else if current_line_len != line_prefix_len {
18292 current_line.push(' ');
18293 current_line_len += 1;
18294 }
18295 }
18296 }
18297 }
18298
18299 if !current_line.is_empty() {
18300 wrapped_text.push_str(¤t_line);
18301 }
18302 wrapped_text
18303}
18304
18305#[test]
18306fn test_wrap_with_prefix() {
18307 assert_eq!(
18308 wrap_with_prefix(
18309 "# ".to_string(),
18310 "abcdefg".to_string(),
18311 4,
18312 NonZeroU32::new(4).unwrap(),
18313 false,
18314 ),
18315 "# abcdefg"
18316 );
18317 assert_eq!(
18318 wrap_with_prefix(
18319 "".to_string(),
18320 "\thello world".to_string(),
18321 8,
18322 NonZeroU32::new(4).unwrap(),
18323 false,
18324 ),
18325 "hello\nworld"
18326 );
18327 assert_eq!(
18328 wrap_with_prefix(
18329 "// ".to_string(),
18330 "xx \nyy zz aa bb cc".to_string(),
18331 12,
18332 NonZeroU32::new(4).unwrap(),
18333 false,
18334 ),
18335 "// xx yy zz\n// aa bb cc"
18336 );
18337 assert_eq!(
18338 wrap_with_prefix(
18339 String::new(),
18340 "这是什么 \n 钢笔".to_string(),
18341 3,
18342 NonZeroU32::new(4).unwrap(),
18343 false,
18344 ),
18345 "这是什\n么 钢\n笔"
18346 );
18347}
18348
18349pub trait CollaborationHub {
18350 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18351 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18352 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18353}
18354
18355impl CollaborationHub for Entity<Project> {
18356 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18357 self.read(cx).collaborators()
18358 }
18359
18360 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18361 self.read(cx).user_store().read(cx).participant_indices()
18362 }
18363
18364 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18365 let this = self.read(cx);
18366 let user_ids = this.collaborators().values().map(|c| c.user_id);
18367 this.user_store().read_with(cx, |user_store, cx| {
18368 user_store.participant_names(user_ids, cx)
18369 })
18370 }
18371}
18372
18373pub trait SemanticsProvider {
18374 fn hover(
18375 &self,
18376 buffer: &Entity<Buffer>,
18377 position: text::Anchor,
18378 cx: &mut App,
18379 ) -> Option<Task<Vec<project::Hover>>>;
18380
18381 fn inlay_hints(
18382 &self,
18383 buffer_handle: Entity<Buffer>,
18384 range: Range<text::Anchor>,
18385 cx: &mut App,
18386 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18387
18388 fn resolve_inlay_hint(
18389 &self,
18390 hint: InlayHint,
18391 buffer_handle: Entity<Buffer>,
18392 server_id: LanguageServerId,
18393 cx: &mut App,
18394 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18395
18396 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18397
18398 fn document_highlights(
18399 &self,
18400 buffer: &Entity<Buffer>,
18401 position: text::Anchor,
18402 cx: &mut App,
18403 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18404
18405 fn definitions(
18406 &self,
18407 buffer: &Entity<Buffer>,
18408 position: text::Anchor,
18409 kind: GotoDefinitionKind,
18410 cx: &mut App,
18411 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18412
18413 fn range_for_rename(
18414 &self,
18415 buffer: &Entity<Buffer>,
18416 position: text::Anchor,
18417 cx: &mut App,
18418 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18419
18420 fn perform_rename(
18421 &self,
18422 buffer: &Entity<Buffer>,
18423 position: text::Anchor,
18424 new_name: String,
18425 cx: &mut App,
18426 ) -> Option<Task<Result<ProjectTransaction>>>;
18427}
18428
18429pub trait CompletionProvider {
18430 fn completions(
18431 &self,
18432 excerpt_id: ExcerptId,
18433 buffer: &Entity<Buffer>,
18434 buffer_position: text::Anchor,
18435 trigger: CompletionContext,
18436 window: &mut Window,
18437 cx: &mut Context<Editor>,
18438 ) -> Task<Result<Option<Vec<Completion>>>>;
18439
18440 fn resolve_completions(
18441 &self,
18442 buffer: Entity<Buffer>,
18443 completion_indices: Vec<usize>,
18444 completions: Rc<RefCell<Box<[Completion]>>>,
18445 cx: &mut Context<Editor>,
18446 ) -> Task<Result<bool>>;
18447
18448 fn apply_additional_edits_for_completion(
18449 &self,
18450 _buffer: Entity<Buffer>,
18451 _completions: Rc<RefCell<Box<[Completion]>>>,
18452 _completion_index: usize,
18453 _push_to_history: bool,
18454 _cx: &mut Context<Editor>,
18455 ) -> Task<Result<Option<language::Transaction>>> {
18456 Task::ready(Ok(None))
18457 }
18458
18459 fn is_completion_trigger(
18460 &self,
18461 buffer: &Entity<Buffer>,
18462 position: language::Anchor,
18463 text: &str,
18464 trigger_in_words: bool,
18465 cx: &mut Context<Editor>,
18466 ) -> bool;
18467
18468 fn sort_completions(&self) -> bool {
18469 true
18470 }
18471
18472 fn filter_completions(&self) -> bool {
18473 true
18474 }
18475}
18476
18477pub trait CodeActionProvider {
18478 fn id(&self) -> Arc<str>;
18479
18480 fn code_actions(
18481 &self,
18482 buffer: &Entity<Buffer>,
18483 range: Range<text::Anchor>,
18484 window: &mut Window,
18485 cx: &mut App,
18486 ) -> Task<Result<Vec<CodeAction>>>;
18487
18488 fn apply_code_action(
18489 &self,
18490 buffer_handle: Entity<Buffer>,
18491 action: CodeAction,
18492 excerpt_id: ExcerptId,
18493 push_to_history: bool,
18494 window: &mut Window,
18495 cx: &mut App,
18496 ) -> Task<Result<ProjectTransaction>>;
18497}
18498
18499impl CodeActionProvider for Entity<Project> {
18500 fn id(&self) -> Arc<str> {
18501 "project".into()
18502 }
18503
18504 fn code_actions(
18505 &self,
18506 buffer: &Entity<Buffer>,
18507 range: Range<text::Anchor>,
18508 _window: &mut Window,
18509 cx: &mut App,
18510 ) -> Task<Result<Vec<CodeAction>>> {
18511 self.update(cx, |project, cx| {
18512 let code_lens = project.code_lens(buffer, range.clone(), cx);
18513 let code_actions = project.code_actions(buffer, range, None, cx);
18514 cx.background_spawn(async move {
18515 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18516 Ok(code_lens
18517 .context("code lens fetch")?
18518 .into_iter()
18519 .chain(code_actions.context("code action fetch")?)
18520 .collect())
18521 })
18522 })
18523 }
18524
18525 fn apply_code_action(
18526 &self,
18527 buffer_handle: Entity<Buffer>,
18528 action: CodeAction,
18529 _excerpt_id: ExcerptId,
18530 push_to_history: bool,
18531 _window: &mut Window,
18532 cx: &mut App,
18533 ) -> Task<Result<ProjectTransaction>> {
18534 self.update(cx, |project, cx| {
18535 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18536 })
18537 }
18538}
18539
18540fn snippet_completions(
18541 project: &Project,
18542 buffer: &Entity<Buffer>,
18543 buffer_position: text::Anchor,
18544 cx: &mut App,
18545) -> Task<Result<Vec<Completion>>> {
18546 let language = buffer.read(cx).language_at(buffer_position);
18547 let language_name = language.as_ref().map(|language| language.lsp_id());
18548 let snippet_store = project.snippets().read(cx);
18549 let snippets = snippet_store.snippets_for(language_name, cx);
18550
18551 if snippets.is_empty() {
18552 return Task::ready(Ok(vec![]));
18553 }
18554 let snapshot = buffer.read(cx).text_snapshot();
18555 let chars: String = snapshot
18556 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18557 .collect();
18558
18559 let scope = language.map(|language| language.default_scope());
18560 let executor = cx.background_executor().clone();
18561
18562 cx.background_spawn(async move {
18563 let classifier = CharClassifier::new(scope).for_completion(true);
18564 let mut last_word = chars
18565 .chars()
18566 .take_while(|c| classifier.is_word(*c))
18567 .collect::<String>();
18568 last_word = last_word.chars().rev().collect();
18569
18570 if last_word.is_empty() {
18571 return Ok(vec![]);
18572 }
18573
18574 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18575 let to_lsp = |point: &text::Anchor| {
18576 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18577 point_to_lsp(end)
18578 };
18579 let lsp_end = to_lsp(&buffer_position);
18580
18581 let candidates = snippets
18582 .iter()
18583 .enumerate()
18584 .flat_map(|(ix, snippet)| {
18585 snippet
18586 .prefix
18587 .iter()
18588 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18589 })
18590 .collect::<Vec<StringMatchCandidate>>();
18591
18592 let mut matches = fuzzy::match_strings(
18593 &candidates,
18594 &last_word,
18595 last_word.chars().any(|c| c.is_uppercase()),
18596 100,
18597 &Default::default(),
18598 executor,
18599 )
18600 .await;
18601
18602 // Remove all candidates where the query's start does not match the start of any word in the candidate
18603 if let Some(query_start) = last_word.chars().next() {
18604 matches.retain(|string_match| {
18605 split_words(&string_match.string).any(|word| {
18606 // Check that the first codepoint of the word as lowercase matches the first
18607 // codepoint of the query as lowercase
18608 word.chars()
18609 .flat_map(|codepoint| codepoint.to_lowercase())
18610 .zip(query_start.to_lowercase())
18611 .all(|(word_cp, query_cp)| word_cp == query_cp)
18612 })
18613 });
18614 }
18615
18616 let matched_strings = matches
18617 .into_iter()
18618 .map(|m| m.string)
18619 .collect::<HashSet<_>>();
18620
18621 let result: Vec<Completion> = snippets
18622 .into_iter()
18623 .filter_map(|snippet| {
18624 let matching_prefix = snippet
18625 .prefix
18626 .iter()
18627 .find(|prefix| matched_strings.contains(*prefix))?;
18628 let start = as_offset - last_word.len();
18629 let start = snapshot.anchor_before(start);
18630 let range = start..buffer_position;
18631 let lsp_start = to_lsp(&start);
18632 let lsp_range = lsp::Range {
18633 start: lsp_start,
18634 end: lsp_end,
18635 };
18636 Some(Completion {
18637 old_range: range,
18638 new_text: snippet.body.clone(),
18639 source: CompletionSource::Lsp {
18640 server_id: LanguageServerId(usize::MAX),
18641 resolved: true,
18642 lsp_completion: Box::new(lsp::CompletionItem {
18643 label: snippet.prefix.first().unwrap().clone(),
18644 kind: Some(CompletionItemKind::SNIPPET),
18645 label_details: snippet.description.as_ref().map(|description| {
18646 lsp::CompletionItemLabelDetails {
18647 detail: Some(description.clone()),
18648 description: None,
18649 }
18650 }),
18651 insert_text_format: Some(InsertTextFormat::SNIPPET),
18652 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18653 lsp::InsertReplaceEdit {
18654 new_text: snippet.body.clone(),
18655 insert: lsp_range,
18656 replace: lsp_range,
18657 },
18658 )),
18659 filter_text: Some(snippet.body.clone()),
18660 sort_text: Some(char::MAX.to_string()),
18661 ..lsp::CompletionItem::default()
18662 }),
18663 lsp_defaults: None,
18664 },
18665 label: CodeLabel {
18666 text: matching_prefix.clone(),
18667 runs: Vec::new(),
18668 filter_range: 0..matching_prefix.len(),
18669 },
18670 icon_path: None,
18671 documentation: snippet
18672 .description
18673 .clone()
18674 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18675 insert_text_mode: None,
18676 confirm: None,
18677 })
18678 })
18679 .collect();
18680
18681 Ok(result)
18682 })
18683}
18684
18685impl CompletionProvider for Entity<Project> {
18686 fn completions(
18687 &self,
18688 _excerpt_id: ExcerptId,
18689 buffer: &Entity<Buffer>,
18690 buffer_position: text::Anchor,
18691 options: CompletionContext,
18692 _window: &mut Window,
18693 cx: &mut Context<Editor>,
18694 ) -> Task<Result<Option<Vec<Completion>>>> {
18695 self.update(cx, |project, cx| {
18696 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18697 let project_completions = project.completions(buffer, buffer_position, options, cx);
18698 cx.background_spawn(async move {
18699 let snippets_completions = snippets.await?;
18700 match project_completions.await? {
18701 Some(mut completions) => {
18702 completions.extend(snippets_completions);
18703 Ok(Some(completions))
18704 }
18705 None => {
18706 if snippets_completions.is_empty() {
18707 Ok(None)
18708 } else {
18709 Ok(Some(snippets_completions))
18710 }
18711 }
18712 }
18713 })
18714 })
18715 }
18716
18717 fn resolve_completions(
18718 &self,
18719 buffer: Entity<Buffer>,
18720 completion_indices: Vec<usize>,
18721 completions: Rc<RefCell<Box<[Completion]>>>,
18722 cx: &mut Context<Editor>,
18723 ) -> Task<Result<bool>> {
18724 self.update(cx, |project, cx| {
18725 project.lsp_store().update(cx, |lsp_store, cx| {
18726 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18727 })
18728 })
18729 }
18730
18731 fn apply_additional_edits_for_completion(
18732 &self,
18733 buffer: Entity<Buffer>,
18734 completions: Rc<RefCell<Box<[Completion]>>>,
18735 completion_index: usize,
18736 push_to_history: bool,
18737 cx: &mut Context<Editor>,
18738 ) -> Task<Result<Option<language::Transaction>>> {
18739 self.update(cx, |project, cx| {
18740 project.lsp_store().update(cx, |lsp_store, cx| {
18741 lsp_store.apply_additional_edits_for_completion(
18742 buffer,
18743 completions,
18744 completion_index,
18745 push_to_history,
18746 cx,
18747 )
18748 })
18749 })
18750 }
18751
18752 fn is_completion_trigger(
18753 &self,
18754 buffer: &Entity<Buffer>,
18755 position: language::Anchor,
18756 text: &str,
18757 trigger_in_words: bool,
18758 cx: &mut Context<Editor>,
18759 ) -> bool {
18760 let mut chars = text.chars();
18761 let char = if let Some(char) = chars.next() {
18762 char
18763 } else {
18764 return false;
18765 };
18766 if chars.next().is_some() {
18767 return false;
18768 }
18769
18770 let buffer = buffer.read(cx);
18771 let snapshot = buffer.snapshot();
18772 if !snapshot.settings_at(position, cx).show_completions_on_input {
18773 return false;
18774 }
18775 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18776 if trigger_in_words && classifier.is_word(char) {
18777 return true;
18778 }
18779
18780 buffer.completion_triggers().contains(text)
18781 }
18782}
18783
18784impl SemanticsProvider for Entity<Project> {
18785 fn hover(
18786 &self,
18787 buffer: &Entity<Buffer>,
18788 position: text::Anchor,
18789 cx: &mut App,
18790 ) -> Option<Task<Vec<project::Hover>>> {
18791 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18792 }
18793
18794 fn document_highlights(
18795 &self,
18796 buffer: &Entity<Buffer>,
18797 position: text::Anchor,
18798 cx: &mut App,
18799 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18800 Some(self.update(cx, |project, cx| {
18801 project.document_highlights(buffer, position, cx)
18802 }))
18803 }
18804
18805 fn definitions(
18806 &self,
18807 buffer: &Entity<Buffer>,
18808 position: text::Anchor,
18809 kind: GotoDefinitionKind,
18810 cx: &mut App,
18811 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18812 Some(self.update(cx, |project, cx| match kind {
18813 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18814 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18815 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18816 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18817 }))
18818 }
18819
18820 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18821 // TODO: make this work for remote projects
18822 self.update(cx, |this, cx| {
18823 buffer.update(cx, |buffer, cx| {
18824 this.any_language_server_supports_inlay_hints(buffer, cx)
18825 })
18826 })
18827 }
18828
18829 fn inlay_hints(
18830 &self,
18831 buffer_handle: Entity<Buffer>,
18832 range: Range<text::Anchor>,
18833 cx: &mut App,
18834 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18835 Some(self.update(cx, |project, cx| {
18836 project.inlay_hints(buffer_handle, range, cx)
18837 }))
18838 }
18839
18840 fn resolve_inlay_hint(
18841 &self,
18842 hint: InlayHint,
18843 buffer_handle: Entity<Buffer>,
18844 server_id: LanguageServerId,
18845 cx: &mut App,
18846 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18847 Some(self.update(cx, |project, cx| {
18848 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18849 }))
18850 }
18851
18852 fn range_for_rename(
18853 &self,
18854 buffer: &Entity<Buffer>,
18855 position: text::Anchor,
18856 cx: &mut App,
18857 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18858 Some(self.update(cx, |project, cx| {
18859 let buffer = buffer.clone();
18860 let task = project.prepare_rename(buffer.clone(), position, cx);
18861 cx.spawn(async move |_, cx| {
18862 Ok(match task.await? {
18863 PrepareRenameResponse::Success(range) => Some(range),
18864 PrepareRenameResponse::InvalidPosition => None,
18865 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18866 // Fallback on using TreeSitter info to determine identifier range
18867 buffer.update(cx, |buffer, _| {
18868 let snapshot = buffer.snapshot();
18869 let (range, kind) = snapshot.surrounding_word(position);
18870 if kind != Some(CharKind::Word) {
18871 return None;
18872 }
18873 Some(
18874 snapshot.anchor_before(range.start)
18875 ..snapshot.anchor_after(range.end),
18876 )
18877 })?
18878 }
18879 })
18880 })
18881 }))
18882 }
18883
18884 fn perform_rename(
18885 &self,
18886 buffer: &Entity<Buffer>,
18887 position: text::Anchor,
18888 new_name: String,
18889 cx: &mut App,
18890 ) -> Option<Task<Result<ProjectTransaction>>> {
18891 Some(self.update(cx, |project, cx| {
18892 project.perform_rename(buffer.clone(), position, new_name, cx)
18893 }))
18894 }
18895}
18896
18897fn inlay_hint_settings(
18898 location: Anchor,
18899 snapshot: &MultiBufferSnapshot,
18900 cx: &mut Context<Editor>,
18901) -> InlayHintSettings {
18902 let file = snapshot.file_at(location);
18903 let language = snapshot.language_at(location).map(|l| l.name());
18904 language_settings(language, file, cx).inlay_hints
18905}
18906
18907fn consume_contiguous_rows(
18908 contiguous_row_selections: &mut Vec<Selection<Point>>,
18909 selection: &Selection<Point>,
18910 display_map: &DisplaySnapshot,
18911 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18912) -> (MultiBufferRow, MultiBufferRow) {
18913 contiguous_row_selections.push(selection.clone());
18914 let start_row = MultiBufferRow(selection.start.row);
18915 let mut end_row = ending_row(selection, display_map);
18916
18917 while let Some(next_selection) = selections.peek() {
18918 if next_selection.start.row <= end_row.0 {
18919 end_row = ending_row(next_selection, display_map);
18920 contiguous_row_selections.push(selections.next().unwrap().clone());
18921 } else {
18922 break;
18923 }
18924 }
18925 (start_row, end_row)
18926}
18927
18928fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18929 if next_selection.end.column > 0 || next_selection.is_empty() {
18930 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18931 } else {
18932 MultiBufferRow(next_selection.end.row)
18933 }
18934}
18935
18936impl EditorSnapshot {
18937 pub fn remote_selections_in_range<'a>(
18938 &'a self,
18939 range: &'a Range<Anchor>,
18940 collaboration_hub: &dyn CollaborationHub,
18941 cx: &'a App,
18942 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18943 let participant_names = collaboration_hub.user_names(cx);
18944 let participant_indices = collaboration_hub.user_participant_indices(cx);
18945 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18946 let collaborators_by_replica_id = collaborators_by_peer_id
18947 .iter()
18948 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18949 .collect::<HashMap<_, _>>();
18950 self.buffer_snapshot
18951 .selections_in_range(range, false)
18952 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18953 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18954 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18955 let user_name = participant_names.get(&collaborator.user_id).cloned();
18956 Some(RemoteSelection {
18957 replica_id,
18958 selection,
18959 cursor_shape,
18960 line_mode,
18961 participant_index,
18962 peer_id: collaborator.peer_id,
18963 user_name,
18964 })
18965 })
18966 }
18967
18968 pub fn hunks_for_ranges(
18969 &self,
18970 ranges: impl IntoIterator<Item = Range<Point>>,
18971 ) -> Vec<MultiBufferDiffHunk> {
18972 let mut hunks = Vec::new();
18973 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18974 HashMap::default();
18975 for query_range in ranges {
18976 let query_rows =
18977 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18978 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18979 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18980 ) {
18981 // Include deleted hunks that are adjacent to the query range, because
18982 // otherwise they would be missed.
18983 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18984 if hunk.status().is_deleted() {
18985 intersects_range |= hunk.row_range.start == query_rows.end;
18986 intersects_range |= hunk.row_range.end == query_rows.start;
18987 }
18988 if intersects_range {
18989 if !processed_buffer_rows
18990 .entry(hunk.buffer_id)
18991 .or_default()
18992 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18993 {
18994 continue;
18995 }
18996 hunks.push(hunk);
18997 }
18998 }
18999 }
19000
19001 hunks
19002 }
19003
19004 fn display_diff_hunks_for_rows<'a>(
19005 &'a self,
19006 display_rows: Range<DisplayRow>,
19007 folded_buffers: &'a HashSet<BufferId>,
19008 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19009 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19010 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19011
19012 self.buffer_snapshot
19013 .diff_hunks_in_range(buffer_start..buffer_end)
19014 .filter_map(|hunk| {
19015 if folded_buffers.contains(&hunk.buffer_id) {
19016 return None;
19017 }
19018
19019 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19020 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19021
19022 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19023 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19024
19025 let display_hunk = if hunk_display_start.column() != 0 {
19026 DisplayDiffHunk::Folded {
19027 display_row: hunk_display_start.row(),
19028 }
19029 } else {
19030 let mut end_row = hunk_display_end.row();
19031 if hunk_display_end.column() > 0 {
19032 end_row.0 += 1;
19033 }
19034 let is_created_file = hunk.is_created_file();
19035 DisplayDiffHunk::Unfolded {
19036 status: hunk.status(),
19037 diff_base_byte_range: hunk.diff_base_byte_range,
19038 display_row_range: hunk_display_start.row()..end_row,
19039 multi_buffer_range: Anchor::range_in_buffer(
19040 hunk.excerpt_id,
19041 hunk.buffer_id,
19042 hunk.buffer_range,
19043 ),
19044 is_created_file,
19045 }
19046 };
19047
19048 Some(display_hunk)
19049 })
19050 }
19051
19052 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19053 self.display_snapshot.buffer_snapshot.language_at(position)
19054 }
19055
19056 pub fn is_focused(&self) -> bool {
19057 self.is_focused
19058 }
19059
19060 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19061 self.placeholder_text.as_ref()
19062 }
19063
19064 pub fn scroll_position(&self) -> gpui::Point<f32> {
19065 self.scroll_anchor.scroll_position(&self.display_snapshot)
19066 }
19067
19068 fn gutter_dimensions(
19069 &self,
19070 font_id: FontId,
19071 font_size: Pixels,
19072 max_line_number_width: Pixels,
19073 cx: &App,
19074 ) -> Option<GutterDimensions> {
19075 if !self.show_gutter {
19076 return None;
19077 }
19078
19079 let descent = cx.text_system().descent(font_id, font_size);
19080 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19081 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19082
19083 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19084 matches!(
19085 ProjectSettings::get_global(cx).git.git_gutter,
19086 Some(GitGutterSetting::TrackedFiles)
19087 )
19088 });
19089 let gutter_settings = EditorSettings::get_global(cx).gutter;
19090 let show_line_numbers = self
19091 .show_line_numbers
19092 .unwrap_or(gutter_settings.line_numbers);
19093 let line_gutter_width = if show_line_numbers {
19094 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19095 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19096 max_line_number_width.max(min_width_for_number_on_gutter)
19097 } else {
19098 0.0.into()
19099 };
19100
19101 let show_code_actions = self
19102 .show_code_actions
19103 .unwrap_or(gutter_settings.code_actions);
19104
19105 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19106 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19107
19108 let git_blame_entries_width =
19109 self.git_blame_gutter_max_author_length
19110 .map(|max_author_length| {
19111 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19112 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19113
19114 /// The number of characters to dedicate to gaps and margins.
19115 const SPACING_WIDTH: usize = 4;
19116
19117 let max_char_count = max_author_length.min(renderer.max_author_length())
19118 + ::git::SHORT_SHA_LENGTH
19119 + MAX_RELATIVE_TIMESTAMP.len()
19120 + SPACING_WIDTH;
19121
19122 em_advance * max_char_count
19123 });
19124
19125 let is_singleton = self.buffer_snapshot.is_singleton();
19126
19127 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19128 left_padding += if !is_singleton {
19129 em_width * 4.0
19130 } else if show_code_actions || show_runnables || show_breakpoints {
19131 em_width * 3.0
19132 } else if show_git_gutter && show_line_numbers {
19133 em_width * 2.0
19134 } else if show_git_gutter || show_line_numbers {
19135 em_width
19136 } else {
19137 px(0.)
19138 };
19139
19140 let shows_folds = is_singleton && gutter_settings.folds;
19141
19142 let right_padding = if shows_folds && show_line_numbers {
19143 em_width * 4.0
19144 } else if shows_folds || (!is_singleton && show_line_numbers) {
19145 em_width * 3.0
19146 } else if show_line_numbers {
19147 em_width
19148 } else {
19149 px(0.)
19150 };
19151
19152 Some(GutterDimensions {
19153 left_padding,
19154 right_padding,
19155 width: line_gutter_width + left_padding + right_padding,
19156 margin: -descent,
19157 git_blame_entries_width,
19158 })
19159 }
19160
19161 pub fn render_crease_toggle(
19162 &self,
19163 buffer_row: MultiBufferRow,
19164 row_contains_cursor: bool,
19165 editor: Entity<Editor>,
19166 window: &mut Window,
19167 cx: &mut App,
19168 ) -> Option<AnyElement> {
19169 let folded = self.is_line_folded(buffer_row);
19170 let mut is_foldable = false;
19171
19172 if let Some(crease) = self
19173 .crease_snapshot
19174 .query_row(buffer_row, &self.buffer_snapshot)
19175 {
19176 is_foldable = true;
19177 match crease {
19178 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19179 if let Some(render_toggle) = render_toggle {
19180 let toggle_callback =
19181 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19182 if folded {
19183 editor.update(cx, |editor, cx| {
19184 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
19185 });
19186 } else {
19187 editor.update(cx, |editor, cx| {
19188 editor.unfold_at(
19189 &crate::UnfoldAt { buffer_row },
19190 window,
19191 cx,
19192 )
19193 });
19194 }
19195 });
19196 return Some((render_toggle)(
19197 buffer_row,
19198 folded,
19199 toggle_callback,
19200 window,
19201 cx,
19202 ));
19203 }
19204 }
19205 }
19206 }
19207
19208 is_foldable |= self.starts_indent(buffer_row);
19209
19210 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19211 Some(
19212 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19213 .toggle_state(folded)
19214 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19215 if folded {
19216 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
19217 } else {
19218 this.fold_at(&FoldAt { buffer_row }, window, cx);
19219 }
19220 }))
19221 .into_any_element(),
19222 )
19223 } else {
19224 None
19225 }
19226 }
19227
19228 pub fn render_crease_trailer(
19229 &self,
19230 buffer_row: MultiBufferRow,
19231 window: &mut Window,
19232 cx: &mut App,
19233 ) -> Option<AnyElement> {
19234 let folded = self.is_line_folded(buffer_row);
19235 if let Crease::Inline { render_trailer, .. } = self
19236 .crease_snapshot
19237 .query_row(buffer_row, &self.buffer_snapshot)?
19238 {
19239 let render_trailer = render_trailer.as_ref()?;
19240 Some(render_trailer(buffer_row, folded, window, cx))
19241 } else {
19242 None
19243 }
19244 }
19245}
19246
19247impl Deref for EditorSnapshot {
19248 type Target = DisplaySnapshot;
19249
19250 fn deref(&self) -> &Self::Target {
19251 &self.display_snapshot
19252 }
19253}
19254
19255#[derive(Clone, Debug, PartialEq, Eq)]
19256pub enum EditorEvent {
19257 InputIgnored {
19258 text: Arc<str>,
19259 },
19260 InputHandled {
19261 utf16_range_to_replace: Option<Range<isize>>,
19262 text: Arc<str>,
19263 },
19264 ExcerptsAdded {
19265 buffer: Entity<Buffer>,
19266 predecessor: ExcerptId,
19267 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19268 },
19269 ExcerptsRemoved {
19270 ids: Vec<ExcerptId>,
19271 },
19272 BufferFoldToggled {
19273 ids: Vec<ExcerptId>,
19274 folded: bool,
19275 },
19276 ExcerptsEdited {
19277 ids: Vec<ExcerptId>,
19278 },
19279 ExcerptsExpanded {
19280 ids: Vec<ExcerptId>,
19281 },
19282 BufferEdited,
19283 Edited {
19284 transaction_id: clock::Lamport,
19285 },
19286 Reparsed(BufferId),
19287 Focused,
19288 FocusedIn,
19289 Blurred,
19290 DirtyChanged,
19291 Saved,
19292 TitleChanged,
19293 DiffBaseChanged,
19294 SelectionsChanged {
19295 local: bool,
19296 },
19297 ScrollPositionChanged {
19298 local: bool,
19299 autoscroll: bool,
19300 },
19301 Closed,
19302 TransactionUndone {
19303 transaction_id: clock::Lamport,
19304 },
19305 TransactionBegun {
19306 transaction_id: clock::Lamport,
19307 },
19308 Reloaded,
19309 CursorShapeChanged,
19310 PushedToNavHistory {
19311 anchor: Anchor,
19312 is_deactivate: bool,
19313 },
19314}
19315
19316impl EventEmitter<EditorEvent> for Editor {}
19317
19318impl Focusable for Editor {
19319 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19320 self.focus_handle.clone()
19321 }
19322}
19323
19324impl Render for Editor {
19325 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19326 let settings = ThemeSettings::get_global(cx);
19327
19328 let mut text_style = match self.mode {
19329 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19330 color: cx.theme().colors().editor_foreground,
19331 font_family: settings.ui_font.family.clone(),
19332 font_features: settings.ui_font.features.clone(),
19333 font_fallbacks: settings.ui_font.fallbacks.clone(),
19334 font_size: rems(0.875).into(),
19335 font_weight: settings.ui_font.weight,
19336 line_height: relative(settings.buffer_line_height.value()),
19337 ..Default::default()
19338 },
19339 EditorMode::Full => TextStyle {
19340 color: cx.theme().colors().editor_foreground,
19341 font_family: settings.buffer_font.family.clone(),
19342 font_features: settings.buffer_font.features.clone(),
19343 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19344 font_size: settings.buffer_font_size(cx).into(),
19345 font_weight: settings.buffer_font.weight,
19346 line_height: relative(settings.buffer_line_height.value()),
19347 ..Default::default()
19348 },
19349 };
19350 if let Some(text_style_refinement) = &self.text_style_refinement {
19351 text_style.refine(text_style_refinement)
19352 }
19353
19354 let background = match self.mode {
19355 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19356 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19357 EditorMode::Full => cx.theme().colors().editor_background,
19358 };
19359
19360 EditorElement::new(
19361 &cx.entity(),
19362 EditorStyle {
19363 background,
19364 local_player: cx.theme().players().local(),
19365 text: text_style,
19366 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19367 syntax: cx.theme().syntax().clone(),
19368 status: cx.theme().status().clone(),
19369 inlay_hints_style: make_inlay_hints_style(cx),
19370 inline_completion_styles: make_suggestion_styles(cx),
19371 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19372 },
19373 )
19374 }
19375}
19376
19377impl EntityInputHandler for Editor {
19378 fn text_for_range(
19379 &mut self,
19380 range_utf16: Range<usize>,
19381 adjusted_range: &mut Option<Range<usize>>,
19382 _: &mut Window,
19383 cx: &mut Context<Self>,
19384 ) -> Option<String> {
19385 let snapshot = self.buffer.read(cx).read(cx);
19386 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19387 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19388 if (start.0..end.0) != range_utf16 {
19389 adjusted_range.replace(start.0..end.0);
19390 }
19391 Some(snapshot.text_for_range(start..end).collect())
19392 }
19393
19394 fn selected_text_range(
19395 &mut self,
19396 ignore_disabled_input: bool,
19397 _: &mut Window,
19398 cx: &mut Context<Self>,
19399 ) -> Option<UTF16Selection> {
19400 // Prevent the IME menu from appearing when holding down an alphabetic key
19401 // while input is disabled.
19402 if !ignore_disabled_input && !self.input_enabled {
19403 return None;
19404 }
19405
19406 let selection = self.selections.newest::<OffsetUtf16>(cx);
19407 let range = selection.range();
19408
19409 Some(UTF16Selection {
19410 range: range.start.0..range.end.0,
19411 reversed: selection.reversed,
19412 })
19413 }
19414
19415 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19416 let snapshot = self.buffer.read(cx).read(cx);
19417 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19418 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19419 }
19420
19421 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19422 self.clear_highlights::<InputComposition>(cx);
19423 self.ime_transaction.take();
19424 }
19425
19426 fn replace_text_in_range(
19427 &mut self,
19428 range_utf16: Option<Range<usize>>,
19429 text: &str,
19430 window: &mut Window,
19431 cx: &mut Context<Self>,
19432 ) {
19433 if !self.input_enabled {
19434 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19435 return;
19436 }
19437
19438 self.transact(window, cx, |this, window, cx| {
19439 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19440 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19441 Some(this.selection_replacement_ranges(range_utf16, cx))
19442 } else {
19443 this.marked_text_ranges(cx)
19444 };
19445
19446 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19447 let newest_selection_id = this.selections.newest_anchor().id;
19448 this.selections
19449 .all::<OffsetUtf16>(cx)
19450 .iter()
19451 .zip(ranges_to_replace.iter())
19452 .find_map(|(selection, range)| {
19453 if selection.id == newest_selection_id {
19454 Some(
19455 (range.start.0 as isize - selection.head().0 as isize)
19456 ..(range.end.0 as isize - selection.head().0 as isize),
19457 )
19458 } else {
19459 None
19460 }
19461 })
19462 });
19463
19464 cx.emit(EditorEvent::InputHandled {
19465 utf16_range_to_replace: range_to_replace,
19466 text: text.into(),
19467 });
19468
19469 if let Some(new_selected_ranges) = new_selected_ranges {
19470 this.change_selections(None, window, cx, |selections| {
19471 selections.select_ranges(new_selected_ranges)
19472 });
19473 this.backspace(&Default::default(), window, cx);
19474 }
19475
19476 this.handle_input(text, window, cx);
19477 });
19478
19479 if let Some(transaction) = self.ime_transaction {
19480 self.buffer.update(cx, |buffer, cx| {
19481 buffer.group_until_transaction(transaction, cx);
19482 });
19483 }
19484
19485 self.unmark_text(window, cx);
19486 }
19487
19488 fn replace_and_mark_text_in_range(
19489 &mut self,
19490 range_utf16: Option<Range<usize>>,
19491 text: &str,
19492 new_selected_range_utf16: Option<Range<usize>>,
19493 window: &mut Window,
19494 cx: &mut Context<Self>,
19495 ) {
19496 if !self.input_enabled {
19497 return;
19498 }
19499
19500 let transaction = self.transact(window, cx, |this, window, cx| {
19501 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19502 let snapshot = this.buffer.read(cx).read(cx);
19503 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19504 for marked_range in &mut marked_ranges {
19505 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19506 marked_range.start.0 += relative_range_utf16.start;
19507 marked_range.start =
19508 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19509 marked_range.end =
19510 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19511 }
19512 }
19513 Some(marked_ranges)
19514 } else if let Some(range_utf16) = range_utf16 {
19515 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19516 Some(this.selection_replacement_ranges(range_utf16, cx))
19517 } else {
19518 None
19519 };
19520
19521 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19522 let newest_selection_id = this.selections.newest_anchor().id;
19523 this.selections
19524 .all::<OffsetUtf16>(cx)
19525 .iter()
19526 .zip(ranges_to_replace.iter())
19527 .find_map(|(selection, range)| {
19528 if selection.id == newest_selection_id {
19529 Some(
19530 (range.start.0 as isize - selection.head().0 as isize)
19531 ..(range.end.0 as isize - selection.head().0 as isize),
19532 )
19533 } else {
19534 None
19535 }
19536 })
19537 });
19538
19539 cx.emit(EditorEvent::InputHandled {
19540 utf16_range_to_replace: range_to_replace,
19541 text: text.into(),
19542 });
19543
19544 if let Some(ranges) = ranges_to_replace {
19545 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19546 }
19547
19548 let marked_ranges = {
19549 let snapshot = this.buffer.read(cx).read(cx);
19550 this.selections
19551 .disjoint_anchors()
19552 .iter()
19553 .map(|selection| {
19554 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19555 })
19556 .collect::<Vec<_>>()
19557 };
19558
19559 if text.is_empty() {
19560 this.unmark_text(window, cx);
19561 } else {
19562 this.highlight_text::<InputComposition>(
19563 marked_ranges.clone(),
19564 HighlightStyle {
19565 underline: Some(UnderlineStyle {
19566 thickness: px(1.),
19567 color: None,
19568 wavy: false,
19569 }),
19570 ..Default::default()
19571 },
19572 cx,
19573 );
19574 }
19575
19576 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19577 let use_autoclose = this.use_autoclose;
19578 let use_auto_surround = this.use_auto_surround;
19579 this.set_use_autoclose(false);
19580 this.set_use_auto_surround(false);
19581 this.handle_input(text, window, cx);
19582 this.set_use_autoclose(use_autoclose);
19583 this.set_use_auto_surround(use_auto_surround);
19584
19585 if let Some(new_selected_range) = new_selected_range_utf16 {
19586 let snapshot = this.buffer.read(cx).read(cx);
19587 let new_selected_ranges = marked_ranges
19588 .into_iter()
19589 .map(|marked_range| {
19590 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19591 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19592 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19593 snapshot.clip_offset_utf16(new_start, Bias::Left)
19594 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19595 })
19596 .collect::<Vec<_>>();
19597
19598 drop(snapshot);
19599 this.change_selections(None, window, cx, |selections| {
19600 selections.select_ranges(new_selected_ranges)
19601 });
19602 }
19603 });
19604
19605 self.ime_transaction = self.ime_transaction.or(transaction);
19606 if let Some(transaction) = self.ime_transaction {
19607 self.buffer.update(cx, |buffer, cx| {
19608 buffer.group_until_transaction(transaction, cx);
19609 });
19610 }
19611
19612 if self.text_highlights::<InputComposition>(cx).is_none() {
19613 self.ime_transaction.take();
19614 }
19615 }
19616
19617 fn bounds_for_range(
19618 &mut self,
19619 range_utf16: Range<usize>,
19620 element_bounds: gpui::Bounds<Pixels>,
19621 window: &mut Window,
19622 cx: &mut Context<Self>,
19623 ) -> Option<gpui::Bounds<Pixels>> {
19624 let text_layout_details = self.text_layout_details(window);
19625 let gpui::Size {
19626 width: em_width,
19627 height: line_height,
19628 } = self.character_size(window);
19629
19630 let snapshot = self.snapshot(window, cx);
19631 let scroll_position = snapshot.scroll_position();
19632 let scroll_left = scroll_position.x * em_width;
19633
19634 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19635 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19636 + self.gutter_dimensions.width
19637 + self.gutter_dimensions.margin;
19638 let y = line_height * (start.row().as_f32() - scroll_position.y);
19639
19640 Some(Bounds {
19641 origin: element_bounds.origin + point(x, y),
19642 size: size(em_width, line_height),
19643 })
19644 }
19645
19646 fn character_index_for_point(
19647 &mut self,
19648 point: gpui::Point<Pixels>,
19649 _window: &mut Window,
19650 _cx: &mut Context<Self>,
19651 ) -> Option<usize> {
19652 let position_map = self.last_position_map.as_ref()?;
19653 if !position_map.text_hitbox.contains(&point) {
19654 return None;
19655 }
19656 let display_point = position_map.point_for_position(point).previous_valid;
19657 let anchor = position_map
19658 .snapshot
19659 .display_point_to_anchor(display_point, Bias::Left);
19660 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19661 Some(utf16_offset.0)
19662 }
19663}
19664
19665trait SelectionExt {
19666 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19667 fn spanned_rows(
19668 &self,
19669 include_end_if_at_line_start: bool,
19670 map: &DisplaySnapshot,
19671 ) -> Range<MultiBufferRow>;
19672}
19673
19674impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19675 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19676 let start = self
19677 .start
19678 .to_point(&map.buffer_snapshot)
19679 .to_display_point(map);
19680 let end = self
19681 .end
19682 .to_point(&map.buffer_snapshot)
19683 .to_display_point(map);
19684 if self.reversed {
19685 end..start
19686 } else {
19687 start..end
19688 }
19689 }
19690
19691 fn spanned_rows(
19692 &self,
19693 include_end_if_at_line_start: bool,
19694 map: &DisplaySnapshot,
19695 ) -> Range<MultiBufferRow> {
19696 let start = self.start.to_point(&map.buffer_snapshot);
19697 let mut end = self.end.to_point(&map.buffer_snapshot);
19698 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19699 end.row -= 1;
19700 }
19701
19702 let buffer_start = map.prev_line_boundary(start).0;
19703 let buffer_end = map.next_line_boundary(end).0;
19704 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19705 }
19706}
19707
19708impl<T: InvalidationRegion> InvalidationStack<T> {
19709 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19710 where
19711 S: Clone + ToOffset,
19712 {
19713 while let Some(region) = self.last() {
19714 let all_selections_inside_invalidation_ranges =
19715 if selections.len() == region.ranges().len() {
19716 selections
19717 .iter()
19718 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19719 .all(|(selection, invalidation_range)| {
19720 let head = selection.head().to_offset(buffer);
19721 invalidation_range.start <= head && invalidation_range.end >= head
19722 })
19723 } else {
19724 false
19725 };
19726
19727 if all_selections_inside_invalidation_ranges {
19728 break;
19729 } else {
19730 self.pop();
19731 }
19732 }
19733 }
19734}
19735
19736impl<T> Default for InvalidationStack<T> {
19737 fn default() -> Self {
19738 Self(Default::default())
19739 }
19740}
19741
19742impl<T> Deref for InvalidationStack<T> {
19743 type Target = Vec<T>;
19744
19745 fn deref(&self) -> &Self::Target {
19746 &self.0
19747 }
19748}
19749
19750impl<T> DerefMut for InvalidationStack<T> {
19751 fn deref_mut(&mut self) -> &mut Self::Target {
19752 &mut self.0
19753 }
19754}
19755
19756impl InvalidationRegion for SnippetState {
19757 fn ranges(&self) -> &[Range<Anchor>] {
19758 &self.ranges[self.active_index]
19759 }
19760}
19761
19762pub fn diagnostic_block_renderer(
19763 diagnostic: Diagnostic,
19764 max_message_rows: Option<u8>,
19765 allow_closing: bool,
19766) -> RenderBlock {
19767 let (text_without_backticks, code_ranges) =
19768 highlight_diagnostic_message(&diagnostic, max_message_rows);
19769
19770 Arc::new(move |cx: &mut BlockContext| {
19771 let group_id: SharedString = cx.block_id.to_string().into();
19772
19773 let mut text_style = cx.window.text_style().clone();
19774 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19775 let theme_settings = ThemeSettings::get_global(cx);
19776 text_style.font_family = theme_settings.buffer_font.family.clone();
19777 text_style.font_style = theme_settings.buffer_font.style;
19778 text_style.font_features = theme_settings.buffer_font.features.clone();
19779 text_style.font_weight = theme_settings.buffer_font.weight;
19780
19781 let multi_line_diagnostic = diagnostic.message.contains('\n');
19782
19783 let buttons = |diagnostic: &Diagnostic| {
19784 if multi_line_diagnostic {
19785 v_flex()
19786 } else {
19787 h_flex()
19788 }
19789 .when(allow_closing, |div| {
19790 div.children(diagnostic.is_primary.then(|| {
19791 IconButton::new("close-block", IconName::XCircle)
19792 .icon_color(Color::Muted)
19793 .size(ButtonSize::Compact)
19794 .style(ButtonStyle::Transparent)
19795 .visible_on_hover(group_id.clone())
19796 .on_click(move |_click, window, cx| {
19797 window.dispatch_action(Box::new(Cancel), cx)
19798 })
19799 .tooltip(|window, cx| {
19800 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19801 })
19802 }))
19803 })
19804 .child(
19805 IconButton::new("copy-block", IconName::Copy)
19806 .icon_color(Color::Muted)
19807 .size(ButtonSize::Compact)
19808 .style(ButtonStyle::Transparent)
19809 .visible_on_hover(group_id.clone())
19810 .on_click({
19811 let message = diagnostic.message.clone();
19812 move |_click, _, cx| {
19813 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19814 }
19815 })
19816 .tooltip(Tooltip::text("Copy diagnostic message")),
19817 )
19818 };
19819
19820 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19821 AvailableSpace::min_size(),
19822 cx.window,
19823 cx.app,
19824 );
19825
19826 h_flex()
19827 .id(cx.block_id)
19828 .group(group_id.clone())
19829 .relative()
19830 .size_full()
19831 .block_mouse_down()
19832 .pl(cx.gutter_dimensions.width)
19833 .w(cx.max_width - cx.gutter_dimensions.full_width())
19834 .child(
19835 div()
19836 .flex()
19837 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19838 .flex_shrink(),
19839 )
19840 .child(buttons(&diagnostic))
19841 .child(div().flex().flex_shrink_0().child(
19842 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19843 &text_style,
19844 code_ranges.iter().map(|range| {
19845 (
19846 range.clone(),
19847 HighlightStyle {
19848 font_weight: Some(FontWeight::BOLD),
19849 ..Default::default()
19850 },
19851 )
19852 }),
19853 ),
19854 ))
19855 .into_any_element()
19856 })
19857}
19858
19859fn inline_completion_edit_text(
19860 current_snapshot: &BufferSnapshot,
19861 edits: &[(Range<Anchor>, String)],
19862 edit_preview: &EditPreview,
19863 include_deletions: bool,
19864 cx: &App,
19865) -> HighlightedText {
19866 let edits = edits
19867 .iter()
19868 .map(|(anchor, text)| {
19869 (
19870 anchor.start.text_anchor..anchor.end.text_anchor,
19871 text.clone(),
19872 )
19873 })
19874 .collect::<Vec<_>>();
19875
19876 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19877}
19878
19879pub fn highlight_diagnostic_message(
19880 diagnostic: &Diagnostic,
19881 mut max_message_rows: Option<u8>,
19882) -> (SharedString, Vec<Range<usize>>) {
19883 let mut text_without_backticks = String::new();
19884 let mut code_ranges = Vec::new();
19885
19886 if let Some(source) = &diagnostic.source {
19887 text_without_backticks.push_str(source);
19888 code_ranges.push(0..source.len());
19889 text_without_backticks.push_str(": ");
19890 }
19891
19892 let mut prev_offset = 0;
19893 let mut in_code_block = false;
19894 let has_row_limit = max_message_rows.is_some();
19895 let mut newline_indices = diagnostic
19896 .message
19897 .match_indices('\n')
19898 .filter(|_| has_row_limit)
19899 .map(|(ix, _)| ix)
19900 .fuse()
19901 .peekable();
19902
19903 for (quote_ix, _) in diagnostic
19904 .message
19905 .match_indices('`')
19906 .chain([(diagnostic.message.len(), "")])
19907 {
19908 let mut first_newline_ix = None;
19909 let mut last_newline_ix = None;
19910 while let Some(newline_ix) = newline_indices.peek() {
19911 if *newline_ix < quote_ix {
19912 if first_newline_ix.is_none() {
19913 first_newline_ix = Some(*newline_ix);
19914 }
19915 last_newline_ix = Some(*newline_ix);
19916
19917 if let Some(rows_left) = &mut max_message_rows {
19918 if *rows_left == 0 {
19919 break;
19920 } else {
19921 *rows_left -= 1;
19922 }
19923 }
19924 let _ = newline_indices.next();
19925 } else {
19926 break;
19927 }
19928 }
19929 let prev_len = text_without_backticks.len();
19930 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19931 text_without_backticks.push_str(new_text);
19932 if in_code_block {
19933 code_ranges.push(prev_len..text_without_backticks.len());
19934 }
19935 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19936 in_code_block = !in_code_block;
19937 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19938 text_without_backticks.push_str("...");
19939 break;
19940 }
19941 }
19942
19943 (text_without_backticks.into(), code_ranges)
19944}
19945
19946fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19947 match severity {
19948 DiagnosticSeverity::ERROR => colors.error,
19949 DiagnosticSeverity::WARNING => colors.warning,
19950 DiagnosticSeverity::INFORMATION => colors.info,
19951 DiagnosticSeverity::HINT => colors.info,
19952 _ => colors.ignored,
19953 }
19954}
19955
19956pub fn styled_runs_for_code_label<'a>(
19957 label: &'a CodeLabel,
19958 syntax_theme: &'a theme::SyntaxTheme,
19959) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19960 let fade_out = HighlightStyle {
19961 fade_out: Some(0.35),
19962 ..Default::default()
19963 };
19964
19965 let mut prev_end = label.filter_range.end;
19966 label
19967 .runs
19968 .iter()
19969 .enumerate()
19970 .flat_map(move |(ix, (range, highlight_id))| {
19971 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19972 style
19973 } else {
19974 return Default::default();
19975 };
19976 let mut muted_style = style;
19977 muted_style.highlight(fade_out);
19978
19979 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19980 if range.start >= label.filter_range.end {
19981 if range.start > prev_end {
19982 runs.push((prev_end..range.start, fade_out));
19983 }
19984 runs.push((range.clone(), muted_style));
19985 } else if range.end <= label.filter_range.end {
19986 runs.push((range.clone(), style));
19987 } else {
19988 runs.push((range.start..label.filter_range.end, style));
19989 runs.push((label.filter_range.end..range.end, muted_style));
19990 }
19991 prev_end = cmp::max(prev_end, range.end);
19992
19993 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19994 runs.push((prev_end..label.text.len(), fade_out));
19995 }
19996
19997 runs
19998 })
19999}
20000
20001pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20002 let mut prev_index = 0;
20003 let mut prev_codepoint: Option<char> = None;
20004 text.char_indices()
20005 .chain([(text.len(), '\0')])
20006 .filter_map(move |(index, codepoint)| {
20007 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20008 let is_boundary = index == text.len()
20009 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20010 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20011 if is_boundary {
20012 let chunk = &text[prev_index..index];
20013 prev_index = index;
20014 Some(chunk)
20015 } else {
20016 None
20017 }
20018 })
20019}
20020
20021pub trait RangeToAnchorExt: Sized {
20022 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20023
20024 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20025 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20026 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20027 }
20028}
20029
20030impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20031 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20032 let start_offset = self.start.to_offset(snapshot);
20033 let end_offset = self.end.to_offset(snapshot);
20034 if start_offset == end_offset {
20035 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20036 } else {
20037 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20038 }
20039 }
20040}
20041
20042pub trait RowExt {
20043 fn as_f32(&self) -> f32;
20044
20045 fn next_row(&self) -> Self;
20046
20047 fn previous_row(&self) -> Self;
20048
20049 fn minus(&self, other: Self) -> u32;
20050}
20051
20052impl RowExt for DisplayRow {
20053 fn as_f32(&self) -> f32 {
20054 self.0 as f32
20055 }
20056
20057 fn next_row(&self) -> Self {
20058 Self(self.0 + 1)
20059 }
20060
20061 fn previous_row(&self) -> Self {
20062 Self(self.0.saturating_sub(1))
20063 }
20064
20065 fn minus(&self, other: Self) -> u32 {
20066 self.0 - other.0
20067 }
20068}
20069
20070impl RowExt for MultiBufferRow {
20071 fn as_f32(&self) -> f32 {
20072 self.0 as f32
20073 }
20074
20075 fn next_row(&self) -> Self {
20076 Self(self.0 + 1)
20077 }
20078
20079 fn previous_row(&self) -> Self {
20080 Self(self.0.saturating_sub(1))
20081 }
20082
20083 fn minus(&self, other: Self) -> u32 {
20084 self.0 - other.0
20085 }
20086}
20087
20088trait RowRangeExt {
20089 type Row;
20090
20091 fn len(&self) -> usize;
20092
20093 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20094}
20095
20096impl RowRangeExt for Range<MultiBufferRow> {
20097 type Row = MultiBufferRow;
20098
20099 fn len(&self) -> usize {
20100 (self.end.0 - self.start.0) as usize
20101 }
20102
20103 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20104 (self.start.0..self.end.0).map(MultiBufferRow)
20105 }
20106}
20107
20108impl RowRangeExt for Range<DisplayRow> {
20109 type Row = DisplayRow;
20110
20111 fn len(&self) -> usize {
20112 (self.end.0 - self.start.0) as usize
20113 }
20114
20115 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20116 (self.start.0..self.end.0).map(DisplayRow)
20117 }
20118}
20119
20120/// If select range has more than one line, we
20121/// just point the cursor to range.start.
20122fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20123 if range.start.row == range.end.row {
20124 range
20125 } else {
20126 range.start..range.start
20127 }
20128}
20129pub struct KillRing(ClipboardItem);
20130impl Global for KillRing {}
20131
20132const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20133
20134enum BreakpointPromptEditAction {
20135 Log,
20136 Condition,
20137 HitCondition,
20138}
20139
20140struct BreakpointPromptEditor {
20141 pub(crate) prompt: Entity<Editor>,
20142 editor: WeakEntity<Editor>,
20143 breakpoint_anchor: Anchor,
20144 breakpoint: Breakpoint,
20145 edit_action: BreakpointPromptEditAction,
20146 block_ids: HashSet<CustomBlockId>,
20147 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20148 _subscriptions: Vec<Subscription>,
20149}
20150
20151impl BreakpointPromptEditor {
20152 const MAX_LINES: u8 = 4;
20153
20154 fn new(
20155 editor: WeakEntity<Editor>,
20156 breakpoint_anchor: Anchor,
20157 breakpoint: Breakpoint,
20158 edit_action: BreakpointPromptEditAction,
20159 window: &mut Window,
20160 cx: &mut Context<Self>,
20161 ) -> Self {
20162 let base_text = match edit_action {
20163 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20164 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20165 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20166 }
20167 .map(|msg| msg.to_string())
20168 .unwrap_or_default();
20169
20170 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20171 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20172
20173 let prompt = cx.new(|cx| {
20174 let mut prompt = Editor::new(
20175 EditorMode::AutoHeight {
20176 max_lines: Self::MAX_LINES as usize,
20177 },
20178 buffer,
20179 None,
20180 window,
20181 cx,
20182 );
20183 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20184 prompt.set_show_cursor_when_unfocused(false, cx);
20185 prompt.set_placeholder_text(
20186 match edit_action {
20187 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20188 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20189 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20190 },
20191 cx,
20192 );
20193
20194 prompt
20195 });
20196
20197 Self {
20198 prompt,
20199 editor,
20200 breakpoint_anchor,
20201 breakpoint,
20202 edit_action,
20203 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20204 block_ids: Default::default(),
20205 _subscriptions: vec![],
20206 }
20207 }
20208
20209 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20210 self.block_ids.extend(block_ids)
20211 }
20212
20213 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20214 if let Some(editor) = self.editor.upgrade() {
20215 let message = self
20216 .prompt
20217 .read(cx)
20218 .buffer
20219 .read(cx)
20220 .as_singleton()
20221 .expect("A multi buffer in breakpoint prompt isn't possible")
20222 .read(cx)
20223 .as_rope()
20224 .to_string();
20225
20226 editor.update(cx, |editor, cx| {
20227 editor.edit_breakpoint_at_anchor(
20228 self.breakpoint_anchor,
20229 self.breakpoint.clone(),
20230 match self.edit_action {
20231 BreakpointPromptEditAction::Log => {
20232 BreakpointEditAction::EditLogMessage(message.into())
20233 }
20234 BreakpointPromptEditAction::Condition => {
20235 BreakpointEditAction::EditCondition(message.into())
20236 }
20237 BreakpointPromptEditAction::HitCondition => {
20238 BreakpointEditAction::EditHitCondition(message.into())
20239 }
20240 },
20241 cx,
20242 );
20243
20244 editor.remove_blocks(self.block_ids.clone(), None, cx);
20245 cx.focus_self(window);
20246 });
20247 }
20248 }
20249
20250 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20251 self.editor
20252 .update(cx, |editor, cx| {
20253 editor.remove_blocks(self.block_ids.clone(), None, cx);
20254 window.focus(&editor.focus_handle);
20255 })
20256 .log_err();
20257 }
20258
20259 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20260 let settings = ThemeSettings::get_global(cx);
20261 let text_style = TextStyle {
20262 color: if self.prompt.read(cx).read_only(cx) {
20263 cx.theme().colors().text_disabled
20264 } else {
20265 cx.theme().colors().text
20266 },
20267 font_family: settings.buffer_font.family.clone(),
20268 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20269 font_size: settings.buffer_font_size(cx).into(),
20270 font_weight: settings.buffer_font.weight,
20271 line_height: relative(settings.buffer_line_height.value()),
20272 ..Default::default()
20273 };
20274 EditorElement::new(
20275 &self.prompt,
20276 EditorStyle {
20277 background: cx.theme().colors().editor_background,
20278 local_player: cx.theme().players().local(),
20279 text: text_style,
20280 ..Default::default()
20281 },
20282 )
20283 }
20284}
20285
20286impl Render for BreakpointPromptEditor {
20287 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20288 let gutter_dimensions = *self.gutter_dimensions.lock();
20289 h_flex()
20290 .key_context("Editor")
20291 .bg(cx.theme().colors().editor_background)
20292 .border_y_1()
20293 .border_color(cx.theme().status().info_border)
20294 .size_full()
20295 .py(window.line_height() / 2.5)
20296 .on_action(cx.listener(Self::confirm))
20297 .on_action(cx.listener(Self::cancel))
20298 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20299 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20300 }
20301}
20302
20303impl Focusable for BreakpointPromptEditor {
20304 fn focus_handle(&self, cx: &App) -> FocusHandle {
20305 self.prompt.focus_handle(cx)
20306 }
20307}
20308
20309fn all_edits_insertions_or_deletions(
20310 edits: &Vec<(Range<Anchor>, String)>,
20311 snapshot: &MultiBufferSnapshot,
20312) -> bool {
20313 let mut all_insertions = true;
20314 let mut all_deletions = true;
20315
20316 for (range, new_text) in edits.iter() {
20317 let range_is_empty = range.to_offset(&snapshot).is_empty();
20318 let text_is_empty = new_text.is_empty();
20319
20320 if range_is_empty != text_is_empty {
20321 if range_is_empty {
20322 all_deletions = false;
20323 } else {
20324 all_insertions = false;
20325 }
20326 } else {
20327 return false;
20328 }
20329
20330 if !all_insertions && !all_deletions {
20331 return false;
20332 }
20333 }
20334 all_insertions || all_deletions
20335}
20336
20337struct MissingEditPredictionKeybindingTooltip;
20338
20339impl Render for MissingEditPredictionKeybindingTooltip {
20340 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20341 ui::tooltip_container(window, cx, |container, _, cx| {
20342 container
20343 .flex_shrink_0()
20344 .max_w_80()
20345 .min_h(rems_from_px(124.))
20346 .justify_between()
20347 .child(
20348 v_flex()
20349 .flex_1()
20350 .text_ui_sm(cx)
20351 .child(Label::new("Conflict with Accept Keybinding"))
20352 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20353 )
20354 .child(
20355 h_flex()
20356 .pb_1()
20357 .gap_1()
20358 .items_end()
20359 .w_full()
20360 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20361 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20362 }))
20363 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20364 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20365 })),
20366 )
20367 })
20368 }
20369}
20370
20371#[derive(Debug, Clone, Copy, PartialEq)]
20372pub struct LineHighlight {
20373 pub background: Background,
20374 pub border: Option<gpui::Hsla>,
20375}
20376
20377impl From<Hsla> for LineHighlight {
20378 fn from(hsla: Hsla) -> Self {
20379 Self {
20380 background: hsla.into(),
20381 border: None,
20382 }
20383 }
20384}
20385
20386impl From<Background> for LineHighlight {
20387 fn from(background: Background) -> Self {
20388 Self {
20389 background,
20390 border: None,
20391 }
20392 }
20393}
20394
20395fn render_diff_hunk_controls(
20396 row: u32,
20397 status: &DiffHunkStatus,
20398 hunk_range: Range<Anchor>,
20399 is_created_file: bool,
20400 line_height: Pixels,
20401 editor: &Entity<Editor>,
20402 _window: &mut Window,
20403 cx: &mut App,
20404) -> AnyElement {
20405 h_flex()
20406 .h(line_height)
20407 .mr_1()
20408 .gap_1()
20409 .px_0p5()
20410 .pb_1()
20411 .border_x_1()
20412 .border_b_1()
20413 .border_color(cx.theme().colors().border_variant)
20414 .rounded_b_lg()
20415 .bg(cx.theme().colors().editor_background)
20416 .gap_1()
20417 .occlude()
20418 .shadow_md()
20419 .child(if status.has_secondary_hunk() {
20420 Button::new(("stage", row as u64), "Stage")
20421 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20422 .tooltip({
20423 let focus_handle = editor.focus_handle(cx);
20424 move |window, cx| {
20425 Tooltip::for_action_in(
20426 "Stage Hunk",
20427 &::git::ToggleStaged,
20428 &focus_handle,
20429 window,
20430 cx,
20431 )
20432 }
20433 })
20434 .on_click({
20435 let editor = editor.clone();
20436 move |_event, _window, cx| {
20437 editor.update(cx, |editor, cx| {
20438 editor.stage_or_unstage_diff_hunks(
20439 true,
20440 vec![hunk_range.start..hunk_range.start],
20441 cx,
20442 );
20443 });
20444 }
20445 })
20446 } else {
20447 Button::new(("unstage", row as u64), "Unstage")
20448 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20449 .tooltip({
20450 let focus_handle = editor.focus_handle(cx);
20451 move |window, cx| {
20452 Tooltip::for_action_in(
20453 "Unstage Hunk",
20454 &::git::ToggleStaged,
20455 &focus_handle,
20456 window,
20457 cx,
20458 )
20459 }
20460 })
20461 .on_click({
20462 let editor = editor.clone();
20463 move |_event, _window, cx| {
20464 editor.update(cx, |editor, cx| {
20465 editor.stage_or_unstage_diff_hunks(
20466 false,
20467 vec![hunk_range.start..hunk_range.start],
20468 cx,
20469 );
20470 });
20471 }
20472 })
20473 })
20474 .child(
20475 Button::new(("restore", row as u64), "Restore")
20476 .tooltip({
20477 let focus_handle = editor.focus_handle(cx);
20478 move |window, cx| {
20479 Tooltip::for_action_in(
20480 "Restore Hunk",
20481 &::git::Restore,
20482 &focus_handle,
20483 window,
20484 cx,
20485 )
20486 }
20487 })
20488 .on_click({
20489 let editor = editor.clone();
20490 move |_event, window, cx| {
20491 editor.update(cx, |editor, cx| {
20492 let snapshot = editor.snapshot(window, cx);
20493 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20494 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20495 });
20496 }
20497 })
20498 .disabled(is_created_file),
20499 )
20500 .when(
20501 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20502 |el| {
20503 el.child(
20504 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20505 .shape(IconButtonShape::Square)
20506 .icon_size(IconSize::Small)
20507 // .disabled(!has_multiple_hunks)
20508 .tooltip({
20509 let focus_handle = editor.focus_handle(cx);
20510 move |window, cx| {
20511 Tooltip::for_action_in(
20512 "Next Hunk",
20513 &GoToHunk,
20514 &focus_handle,
20515 window,
20516 cx,
20517 )
20518 }
20519 })
20520 .on_click({
20521 let editor = editor.clone();
20522 move |_event, window, cx| {
20523 editor.update(cx, |editor, cx| {
20524 let snapshot = editor.snapshot(window, cx);
20525 let position =
20526 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20527 editor.go_to_hunk_before_or_after_position(
20528 &snapshot,
20529 position,
20530 Direction::Next,
20531 window,
20532 cx,
20533 );
20534 editor.expand_selected_diff_hunks(cx);
20535 });
20536 }
20537 }),
20538 )
20539 .child(
20540 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20541 .shape(IconButtonShape::Square)
20542 .icon_size(IconSize::Small)
20543 // .disabled(!has_multiple_hunks)
20544 .tooltip({
20545 let focus_handle = editor.focus_handle(cx);
20546 move |window, cx| {
20547 Tooltip::for_action_in(
20548 "Previous Hunk",
20549 &GoToPreviousHunk,
20550 &focus_handle,
20551 window,
20552 cx,
20553 )
20554 }
20555 })
20556 .on_click({
20557 let editor = editor.clone();
20558 move |_event, window, cx| {
20559 editor.update(cx, |editor, cx| {
20560 let snapshot = editor.snapshot(window, cx);
20561 let point =
20562 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20563 editor.go_to_hunk_before_or_after_position(
20564 &snapshot,
20565 point,
20566 Direction::Prev,
20567 window,
20568 cx,
20569 );
20570 editor.expand_selected_diff_hunks(cx);
20571 });
20572 }
20573 }),
20574 )
20575 },
20576 )
20577 .into_any_element()
20578}